This source file includes following definitions.
- fts2Corrupt
- safe_isspace
- safe_tolower
- safe_isalnum
- putVarint
- getVarintSafe
- getVarint
- getVarint32Safe
- getVarint32
- dataBufferInit
- dataBufferReset
- dataBufferDestroy
- dataBufferSwap
- dataBufferExpand
- dataBufferAppend
- dataBufferAppend2
- dataBufferReplace
- initStringBuffer
- stringBufferLength
- stringBufferData
- stringBufferDestroy
- nappend
- append
- appendList
- endsInWhiteSpace
- appendWhiteSpace
- trimWhiteSpace
- dlrAtEnd
- dlrDocid
- dlrDocData
- dlrDocDataBytes
- dlrAllDataBytes
- dlrPosData
- dlrPosDataLen
- dlrStep
- dlrDestroy
- dlrInit
- docListValidate
- dlwInit
- dlwDestroy
- dlwAppend
- dlwCopy
- dlwAdd
- plrAtEnd
- plrColumn
- plrPosition
- plrStartOffset
- plrEndOffset
- plrStep
- plrDestroy
- plrInit
- plwAdd
- plwCopy
- plwInit
- plwTerminate
- plwDestroy
- dlcAddDoclist
- dlcNext
- dlcAddPos
- dlcNew
- dlcDelete
- docListTrim
- orderedDLReaderCmp
- orderedDLReaderReorder
- docListMerge
- posListCmp
- posListUnion
- docListUnion
- posListPhraseMerge
- docListPhraseMerge
- docListAndMerge
- docListOrMerge
- docListExceptMerge
- string_dup_n
- string_dup
- string_format
- sql_exec
- sql_prepare
- cursor_vtab
- contentInsertStatement
- contentUpdateStatement
- sql_get_statement
- sql_single_step
- sql_get_leaf_statement
- content_insert
- content_update
- freeStringArray
- content_select
- content_delete
- content_exists
- block_insert
- block_delete
- segdir_max_index
- segdir_set
- segdir_span
- segdir_delete
- segdir_delete_all
- segdir_count
- fulltext_vtab_destroy
- getToken
- tokenizeString
- dequoteString
- tokenListToIdList
- firstToken
- startsWith
- clearTableSpec
- parseSpec
- fulltextSchema
- constructVtab
- fulltextConnect
- fulltextCreate
- fulltextBestIndex
- fulltextDisconnect
- fulltextDestroy
- fulltextOpen
- queryClear
- snippetClear
- snippetAppendMatch
- snippetOffsetsOfColumn
- snippetAllOffsets
- snippetOffsetText
- wordBoundary
- snippetText
- fulltextClose
- fulltextNext
- docListOfTerm
- queryAdd
- checkColumnSpecifier
- tokenizeSegment
- parseQuery
- fulltextQuery
- fulltextFilter
- fulltextEof
- fulltextColumn
- fulltextRowid
- buildTerms
- insertTerms
- deleteTerms
- index_insert
- index_delete
- index_update
- interiorBlockNew
- interiorBlockValidate
- interiorWriterInit
- interiorWriterAppend
- interiorWriterDestroy
- interiorWriterRootInfo
- interiorReaderDestroy
- interiorReaderInit
- interiorReaderAtEnd
- interiorReaderCurrentBlockid
- interiorReaderTermBytes
- interiorReaderTerm
- interiorReaderStep
- interiorReaderTermCmp
- leafWriterInit
- leafNodeValidate
- leafWriterInternalFlush
- leafWriterFlush
- leafWriterRootInfo
- leafWriterFinalize
- leafWriterDestroy
- leafWriterEncodeTerm
- leafWriterInlineFlush
- leafWriterStepMerge
- leafWriterStep
- leafReaderDestroy
- leafReaderAtEnd
- leafReaderTermBytes
- leafReaderTerm
- leafReaderDataBytes
- leafReaderData
- leafReaderInit
- leafReaderStep
- leafReaderTermCmp
- leavesReaderTermBytes
- leavesReaderTerm
- leavesReaderDataBytes
- leavesReaderData
- leavesReaderAtEnd
- leavesReaderReset
- leavesReaderDestroy
- leavesReaderInit
- leavesReaderStep
- leavesReaderTermCmp
- leavesReaderCmp
- leavesReaderReorder
- leavesReadersInit
- leavesReadersMerge
- segdirNextIndex
- segmentMerge
- docListAccumulateUnion
- loadSegmentLeavesInt
- loadSegmentLeaf
- loadSegmentLeaves
- getChildrenContaining
- loadAndGetChildrenContaining
- loadSegmentInt
- loadSegment
- termSelect
- termDataCmp
- writeZeroSegment
- clearPendingTerms
- flushPendingTerms
- initPendingTerms
- fulltextUpdate
- fulltextSync
- fulltextBegin
- fulltextCommit
- fulltextRollback
- snippetFunc
- snippetOffsetsFunc
- optLeavesReaderAtEnd
- optLeavesReaderTermBytes
- optLeavesReaderData
- optLeavesReaderDataBytes
- optLeavesReaderTerm
- optLeavesReaderStep
- optLeavesReaderTermCmp
- optLeavesReaderCmp
- optLeavesReaderReorder
- optimizeInternal
- optimizeFunc
- generateError
- collectSegmentTerms
- generateTermsResult
- dumpTermsFunc
- createDoclistResult
- dumpDoclistFunc
- fulltextFindFunction
- fulltextRename
- hashDestroy
- sqlite3Fts2Init
- sqlite3_extension_init
#if (!defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2)) \
&& !defined(SQLITE_ENABLE_BROKEN_FTS2)
#error fts2 has a design flaw and has been deprecated.
#endif
#define GEARS_FTS2_CHANGES 1
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2)
#if defined(SQLITE_ENABLE_FTS2) && !defined(SQLITE_CORE)
# define SQLITE_CORE 1
#endif
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "fts2.h"
#include "fts2_hash.h"
#include "fts2_tokenizer.h"
#include "sqlite3.h"
#ifndef SQLITE_CORE
# include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1
#endif
#if 0
# define TRACE(A) printf A; fflush(stdout)
#else
# define TRACE(A)
#endif
#if 0
static int fts2Corrupt(void){
return SQLITE_CORRUPT;
}
# define SQLITE_CORRUPT_BKPT fts2Corrupt()
#else
# define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
#endif
static int safe_isspace(char c){
return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
}
static int safe_tolower(char c){
return (c>='A' && c<='Z') ? (c - 'A' + 'a') : c;
}
static int safe_isalnum(char c){
return (c>='0' && c<='9') || (c>='A' && c<='Z') || (c>='a' && c<='z');
}
typedef enum DocListType {
DL_DOCIDS,
DL_POSITIONS,
DL_POSITIONS_OFFSETS
} DocListType;
#ifndef DL_DEFAULT
# define DL_DEFAULT DL_POSITIONS
#endif
enum {
POS_END = 0,
POS_COLUMN,
POS_BASE
};
#define MERGE_COUNT 16
#define CLEAR(b) memset(b, '\0', sizeof(*(b)))
#ifndef NDEBUG
# define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b)))
#else
# define SCRAMBLE(b)
#endif
#define VARINT_MAX 10
static int putVarint(char *p, sqlite_int64 v){
unsigned char *q = (unsigned char *) p;
sqlite_uint64 vu = v;
do{
*q++ = (unsigned char) ((vu & 0x7f) | 0x80);
vu >>= 7;
}while( vu!=0 );
q[-1] &= 0x7f;
assert( q - (unsigned char *)p <= VARINT_MAX );
return (int) (q - (unsigned char *)p);
}
static int getVarintSafe(const char *p, sqlite_int64 *v, int max){
const unsigned char *q = (const unsigned char *) p;
sqlite_uint64 x = 0, y = 1;
if( max>VARINT_MAX ) max = VARINT_MAX;
while( max && (*q & 0x80) == 0x80 ){
max--;
x += y * (*q++ & 0x7f);
y <<= 7;
}
if ( !max ){
assert( 0 );
return 0;
}
x += y * (*q++);
*v = (sqlite_int64) x;
return (int) (q - (unsigned char *)p);
}
static int getVarint(const char *p, sqlite_int64 *v){
return getVarintSafe(p, v, VARINT_MAX);
}
static int getVarint32Safe(const char *p, int *pi, int max){
sqlite_int64 i;
int ret = getVarintSafe(p, &i, max);
if( !ret ) return ret;
*pi = (int) i;
assert( *pi==i );
return ret;
}
static int getVarint32(const char* p, int *pi){
return getVarint32Safe(p, pi, VARINT_MAX);
}
typedef struct DataBuffer {
char *pData;
int nCapacity;
int nData;
} DataBuffer;
static void dataBufferInit(DataBuffer *pBuffer, int nCapacity){
assert( nCapacity>=0 );
pBuffer->nData = 0;
pBuffer->nCapacity = nCapacity;
pBuffer->pData = nCapacity==0 ? NULL : sqlite3_malloc(nCapacity);
}
static void dataBufferReset(DataBuffer *pBuffer){
pBuffer->nData = 0;
}
static void dataBufferDestroy(DataBuffer *pBuffer){
if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData);
SCRAMBLE(pBuffer);
}
static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){
DataBuffer tmp = *pBuffer1;
*pBuffer1 = *pBuffer2;
*pBuffer2 = tmp;
}
static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){
assert( nAddCapacity>0 );
if( pBuffer->nData+nAddCapacity>pBuffer->nCapacity ){
pBuffer->nCapacity = pBuffer->nData+nAddCapacity;
pBuffer->pData = sqlite3_realloc(pBuffer->pData, pBuffer->nCapacity);
}
}
static void dataBufferAppend(DataBuffer *pBuffer,
const char *pSource, int nSource){
assert( nSource>0 && pSource!=NULL );
dataBufferExpand(pBuffer, nSource);
memcpy(pBuffer->pData+pBuffer->nData, pSource, nSource);
pBuffer->nData += nSource;
}
static void dataBufferAppend2(DataBuffer *pBuffer,
const char *pSource1, int nSource1,
const char *pSource2, int nSource2){
assert( nSource1>0 && pSource1!=NULL );
assert( nSource2>0 && pSource2!=NULL );
dataBufferExpand(pBuffer, nSource1+nSource2);
memcpy(pBuffer->pData+pBuffer->nData, pSource1, nSource1);
memcpy(pBuffer->pData+pBuffer->nData+nSource1, pSource2, nSource2);
pBuffer->nData += nSource1+nSource2;
}
static void dataBufferReplace(DataBuffer *pBuffer,
const char *pSource, int nSource){
dataBufferReset(pBuffer);
dataBufferAppend(pBuffer, pSource, nSource);
}
typedef struct StringBuffer {
DataBuffer b;
} StringBuffer;
static void initStringBuffer(StringBuffer *sb){
dataBufferInit(&sb->b, 100);
dataBufferReplace(&sb->b, "", 1);
}
static int stringBufferLength(StringBuffer *sb){
return sb->b.nData-1;
}
static char *stringBufferData(StringBuffer *sb){
return sb->b.pData;
}
static void stringBufferDestroy(StringBuffer *sb){
dataBufferDestroy(&sb->b);
}
static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
assert( sb->b.nData>0 );
if( nFrom>0 ){
sb->b.nData--;
dataBufferAppend2(&sb->b, zFrom, nFrom, "", 1);
}
}
static void append(StringBuffer *sb, const char *zFrom){
nappend(sb, zFrom, strlen(zFrom));
}
static void appendList(StringBuffer *sb, int nString, char **azString){
int i;
for(i=0; i<nString; ++i){
if( i>0 ) append(sb, ", ");
append(sb, azString[i]);
}
}
static int endsInWhiteSpace(StringBuffer *p){
return stringBufferLength(p)>0 &&
safe_isspace(stringBufferData(p)[stringBufferLength(p)-1]);
}
static void appendWhiteSpace(StringBuffer *p){
if( stringBufferLength(p)==0 ) return;
if( !endsInWhiteSpace(p) ) append(p, " ");
}
static void trimWhiteSpace(StringBuffer *p){
while( endsInWhiteSpace(p) ){
p->b.pData[--p->b.nData-1] = '\0';
}
}
typedef struct DLReader {
DocListType iType;
const char *pData;
int nData;
sqlite_int64 iDocid;
int nElement;
} DLReader;
static int dlrAtEnd(DLReader *pReader){
assert( pReader->nData>=0 );
return pReader->nData<=0;
}
static sqlite_int64 dlrDocid(DLReader *pReader){
assert( !dlrAtEnd(pReader) );
return pReader->iDocid;
}
static const char *dlrDocData(DLReader *pReader){
assert( !dlrAtEnd(pReader) );
return pReader->pData;
}
static int dlrDocDataBytes(DLReader *pReader){
assert( !dlrAtEnd(pReader) );
return pReader->nElement;
}
static int dlrAllDataBytes(DLReader *pReader){
assert( !dlrAtEnd(pReader) );
return pReader->nData;
}
static const char *dlrPosData(DLReader *pReader){
sqlite_int64 iDummy;
int n = getVarintSafe(pReader->pData, &iDummy, pReader->nElement);
if( !n ) return NULL;
assert( !dlrAtEnd(pReader) );
return pReader->pData+n;
}
static int dlrPosDataLen(DLReader *pReader){
sqlite_int64 iDummy;
int n = getVarint(pReader->pData, &iDummy);
assert( !dlrAtEnd(pReader) );
return pReader->nElement-n;
}
static int dlrStep(DLReader *pReader){
assert( !dlrAtEnd(pReader) );
assert( pReader->nElement<=pReader->nData );
pReader->pData += pReader->nElement;
pReader->nData -= pReader->nElement;
if( pReader->nData>0 ){
sqlite_int64 iDocidDelta;
int nTotal = 0;
int iDummy, n = getVarintSafe(pReader->pData, &iDocidDelta, pReader->nData);
if( !n ) return SQLITE_CORRUPT_BKPT;
nTotal += n;
pReader->iDocid += iDocidDelta;
if( pReader->iType>=DL_POSITIONS ){
while( 1 ){
n = getVarint32Safe(pReader->pData+nTotal, &iDummy,
pReader->nData-nTotal);
if( !n ) return SQLITE_CORRUPT_BKPT;
nTotal += n;
if( iDummy==POS_END ) break;
if( iDummy==POS_COLUMN ){
n = getVarint32Safe(pReader->pData+nTotal, &iDummy,
pReader->nData-nTotal);
if( !n ) return SQLITE_CORRUPT_BKPT;
nTotal += n;
}else if( pReader->iType==DL_POSITIONS_OFFSETS ){
n = getVarint32Safe(pReader->pData+nTotal, &iDummy,
pReader->nData-nTotal);
if( !n ) return SQLITE_CORRUPT_BKPT;
nTotal += n;
n = getVarint32Safe(pReader->pData+nTotal, &iDummy,
pReader->nData-nTotal);
if( !n ) return SQLITE_CORRUPT_BKPT;
nTotal += n;
}
}
}
pReader->nElement = nTotal;
assert( pReader->nElement<=pReader->nData );
}
return SQLITE_OK;
}
static void dlrDestroy(DLReader *pReader){
SCRAMBLE(pReader);
}
static int dlrInit(DLReader *pReader, DocListType iType,
const char *pData, int nData){
int rc;
assert( pData!=NULL && nData!=0 );
pReader->iType = iType;
pReader->pData = pData;
pReader->nData = nData;
pReader->nElement = 0;
pReader->iDocid = 0;
rc = dlrStep(pReader);
if( rc!=SQLITE_OK ) dlrDestroy(pReader);
return rc;
}
#ifndef NDEBUG
static void docListValidate(DocListType iType, const char *pData, int nData,
sqlite_int64 *pLastDocid){
sqlite_int64 iPrevDocid = 0;
assert( nData>0 );
assert( pData!=0 );
assert( pData+nData>pData );
while( nData!=0 ){
sqlite_int64 iDocidDelta;
int n = getVarint(pData, &iDocidDelta);
iPrevDocid += iDocidDelta;
if( iType>DL_DOCIDS ){
int iDummy;
while( 1 ){
n += getVarint32(pData+n, &iDummy);
if( iDummy==POS_END ) break;
if( iDummy==POS_COLUMN ){
n += getVarint32(pData+n, &iDummy);
}else if( iType>DL_POSITIONS ){
n += getVarint32(pData+n, &iDummy);
n += getVarint32(pData+n, &iDummy);
}
assert( n<=nData );
}
}
assert( n<=nData );
pData += n;
nData -= n;
}
if( pLastDocid ) *pLastDocid = iPrevDocid;
}
#define ASSERT_VALID_DOCLIST(i, p, n, o) docListValidate(i, p, n, o)
#else
#define ASSERT_VALID_DOCLIST(i, p, n, o) assert( 1 )
#endif
typedef struct DLWriter {
DocListType iType;
DataBuffer *b;
sqlite_int64 iPrevDocid;
#ifndef NDEBUG
int has_iPrevDocid;
#endif
} DLWriter;
static void dlwInit(DLWriter *pWriter, DocListType iType, DataBuffer *b){
pWriter->b = b;
pWriter->iType = iType;
pWriter->iPrevDocid = 0;
#ifndef NDEBUG
pWriter->has_iPrevDocid = 0;
#endif
}
static void dlwDestroy(DLWriter *pWriter){
SCRAMBLE(pWriter);
}
static int dlwAppend(DLWriter *pWriter,
const char *pData, int nData,
sqlite_int64 iFirstDocid, sqlite_int64 iLastDocid){
sqlite_int64 iDocid = 0;
char c[VARINT_MAX];
int nFirstOld, nFirstNew;
#ifndef NDEBUG
sqlite_int64 iLastDocidDelta;
#endif
nFirstOld = getVarintSafe(pData, &iDocid, nData);
if( !nFirstOld ) return SQLITE_CORRUPT_BKPT;
assert( nFirstOld<nData || (nFirstOld==nData && pWriter->iType==DL_DOCIDS) );
nFirstNew = putVarint(c, iFirstDocid-pWriter->iPrevDocid);
ASSERT_VALID_DOCLIST(pWriter->iType, pData, nData, &iLastDocidDelta);
assert( iLastDocid==iFirstDocid-iDocid+iLastDocidDelta );
if( nFirstOld<nData ){
dataBufferAppend2(pWriter->b, c, nFirstNew,
pData+nFirstOld, nData-nFirstOld);
}else{
dataBufferAppend(pWriter->b, c, nFirstNew);
}
pWriter->iPrevDocid = iLastDocid;
return SQLITE_OK;
}
static int dlwCopy(DLWriter *pWriter, DLReader *pReader){
return dlwAppend(pWriter, dlrDocData(pReader), dlrDocDataBytes(pReader),
dlrDocid(pReader), dlrDocid(pReader));
}
static void dlwAdd(DLWriter *pWriter, sqlite_int64 iDocid){
char c[VARINT_MAX];
int n = putVarint(c, iDocid-pWriter->iPrevDocid);
assert( !pWriter->has_iPrevDocid || iDocid>pWriter->iPrevDocid );
assert( pWriter->iType==DL_DOCIDS );
dataBufferAppend(pWriter->b, c, n);
pWriter->iPrevDocid = iDocid;
#ifndef NDEBUG
pWriter->has_iPrevDocid = 1;
#endif
}
typedef struct PLReader {
const char *pData;
int nData;
DocListType iType;
int iColumn;
int iPosition;
int iStartOffset;
int iEndOffset;
} PLReader;
static int plrAtEnd(PLReader *pReader){
return pReader->pData==NULL;
}
static int plrColumn(PLReader *pReader){
assert( !plrAtEnd(pReader) );
return pReader->iColumn;
}
static int plrPosition(PLReader *pReader){
assert( !plrAtEnd(pReader) );
return pReader->iPosition;
}
static int plrStartOffset(PLReader *pReader){
assert( !plrAtEnd(pReader) );
return pReader->iStartOffset;
}
static int plrEndOffset(PLReader *pReader){
assert( !plrAtEnd(pReader) );
return pReader->iEndOffset;
}
static int plrStep(PLReader *pReader){
int i, n, nTotal = 0;
assert( !plrAtEnd(pReader) );
if( pReader->nData<=0 ){
pReader->pData = NULL;
return SQLITE_OK;
}
n = getVarint32Safe(pReader->pData, &i, pReader->nData);
if( !n ) return SQLITE_CORRUPT_BKPT;
nTotal += n;
if( i==POS_COLUMN ){
n = getVarint32Safe(pReader->pData+nTotal, &pReader->iColumn,
pReader->nData-nTotal);
if( !n ) return SQLITE_CORRUPT_BKPT;
nTotal += n;
pReader->iPosition = 0;
pReader->iStartOffset = 0;
n = getVarint32Safe(pReader->pData+nTotal, &i, pReader->nData-nTotal);
if( !n ) return SQLITE_CORRUPT_BKPT;
nTotal += n;
}
assert( i!=POS_COLUMN );
if( i==POS_END ){
assert( nTotal<=pReader->nData );
pReader->nData = 0;
pReader->pData = NULL;
return SQLITE_OK;
}
pReader->iPosition += i-POS_BASE;
if( pReader->iType==DL_POSITIONS_OFFSETS ){
n = getVarint32Safe(pReader->pData+nTotal, &i, pReader->nData-nTotal);
if( !n ) return SQLITE_CORRUPT_BKPT;
nTotal += n;
pReader->iStartOffset += i;
n = getVarint32Safe(pReader->pData+nTotal, &i, pReader->nData-nTotal);
if( !n ) return SQLITE_CORRUPT_BKPT;
nTotal += n;
pReader->iEndOffset = pReader->iStartOffset+i;
}
assert( nTotal<=pReader->nData );
pReader->pData += nTotal;
pReader->nData -= nTotal;
return SQLITE_OK;
}
static void plrDestroy(PLReader *pReader){
SCRAMBLE(pReader);
}
static int plrInit(PLReader *pReader, DLReader *pDLReader){
int rc;
pReader->pData = dlrPosData(pDLReader);
pReader->nData = dlrPosDataLen(pDLReader);
pReader->iType = pDLReader->iType;
pReader->iColumn = 0;
pReader->iPosition = 0;
pReader->iStartOffset = 0;
pReader->iEndOffset = 0;
rc = plrStep(pReader);
if( rc!=SQLITE_OK ) plrDestroy(pReader);
return rc;
}
typedef struct PLWriter {
DLWriter *dlw;
int iColumn;
int iPos;
int iOffset;
} PLWriter;
static void plwAdd(PLWriter *pWriter, int iColumn, int iPos,
int iStartOffset, int iEndOffset){
char c[5*VARINT_MAX];
int n = 0;
assert( pWriter->iPos!=-1 );
if( pWriter->dlw->iType==DL_DOCIDS ) return;
if( iColumn!=pWriter->iColumn ){
n += putVarint(c+n, POS_COLUMN);
n += putVarint(c+n, iColumn);
pWriter->iColumn = iColumn;
pWriter->iPos = 0;
pWriter->iOffset = 0;
}
assert( iPos>=pWriter->iPos );
n += putVarint(c+n, POS_BASE+(iPos-pWriter->iPos));
pWriter->iPos = iPos;
if( pWriter->dlw->iType==DL_POSITIONS_OFFSETS ){
assert( iStartOffset>=pWriter->iOffset );
n += putVarint(c+n, iStartOffset-pWriter->iOffset);
pWriter->iOffset = iStartOffset;
assert( iEndOffset>=iStartOffset );
n += putVarint(c+n, iEndOffset-iStartOffset);
}
dataBufferAppend(pWriter->dlw->b, c, n);
}
static void plwCopy(PLWriter *pWriter, PLReader *pReader){
plwAdd(pWriter, plrColumn(pReader), plrPosition(pReader),
plrStartOffset(pReader), plrEndOffset(pReader));
}
static void plwInit(PLWriter *pWriter, DLWriter *dlw, sqlite_int64 iDocid){
char c[VARINT_MAX];
int n;
pWriter->dlw = dlw;
assert( !pWriter->dlw->has_iPrevDocid || iDocid>pWriter->dlw->iPrevDocid );
n = putVarint(c, iDocid-pWriter->dlw->iPrevDocid);
dataBufferAppend(pWriter->dlw->b, c, n);
pWriter->dlw->iPrevDocid = iDocid;
#ifndef NDEBUG
pWriter->dlw->has_iPrevDocid = 1;
#endif
pWriter->iColumn = 0;
pWriter->iPos = 0;
pWriter->iOffset = 0;
}
static void plwTerminate(PLWriter *pWriter){
if( pWriter->dlw->iType>DL_DOCIDS ){
char c[VARINT_MAX];
int n = putVarint(c, POS_END);
dataBufferAppend(pWriter->dlw->b, c, n);
}
#ifndef NDEBUG
pWriter->iPos = -1;
#endif
}
static void plwDestroy(PLWriter *pWriter){
SCRAMBLE(pWriter);
}
typedef struct DLCollector {
DataBuffer b;
DLWriter dlw;
PLWriter plw;
} DLCollector;
static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){
if( pCollector->dlw.iType>DL_DOCIDS ){
char c[VARINT_MAX];
int n = putVarint(c, POS_END);
dataBufferAppend2(b, pCollector->b.pData, pCollector->b.nData, c, n);
}else{
dataBufferAppend(b, pCollector->b.pData, pCollector->b.nData);
}
}
static void dlcNext(DLCollector *pCollector, sqlite_int64 iDocid){
plwTerminate(&pCollector->plw);
plwDestroy(&pCollector->plw);
plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
}
static void dlcAddPos(DLCollector *pCollector, int iColumn, int iPos,
int iStartOffset, int iEndOffset){
plwAdd(&pCollector->plw, iColumn, iPos, iStartOffset, iEndOffset);
}
static DLCollector *dlcNew(sqlite_int64 iDocid, DocListType iType){
DLCollector *pCollector = sqlite3_malloc(sizeof(DLCollector));
dataBufferInit(&pCollector->b, 0);
dlwInit(&pCollector->dlw, iType, &pCollector->b);
plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
return pCollector;
}
static void dlcDelete(DLCollector *pCollector){
plwDestroy(&pCollector->plw);
dlwDestroy(&pCollector->dlw);
dataBufferDestroy(&pCollector->b);
SCRAMBLE(pCollector);
sqlite3_free(pCollector);
}
static int docListTrim(DocListType iType, const char *pData, int nData,
int iColumn, DocListType iOutType, DataBuffer *out){
DLReader dlReader;
DLWriter dlWriter;
int rc;
assert( iOutType<=iType );
rc = dlrInit(&dlReader, iType, pData, nData);
if( rc!=SQLITE_OK ) return rc;
dlwInit(&dlWriter, iOutType, out);
while( !dlrAtEnd(&dlReader) ){
PLReader plReader;
PLWriter plWriter;
int match = 0;
rc = plrInit(&plReader, &dlReader);
if( rc!=SQLITE_OK ) break;
while( !plrAtEnd(&plReader) ){
if( iColumn==-1 || plrColumn(&plReader)==iColumn ){
if( !match ){
plwInit(&plWriter, &dlWriter, dlrDocid(&dlReader));
match = 1;
}
plwAdd(&plWriter, plrColumn(&plReader), plrPosition(&plReader),
plrStartOffset(&plReader), plrEndOffset(&plReader));
}
rc = plrStep(&plReader);
if( rc!=SQLITE_OK ){
plrDestroy(&plReader);
goto err;
}
}
if( match ){
plwTerminate(&plWriter);
plwDestroy(&plWriter);
}
plrDestroy(&plReader);
rc = dlrStep(&dlReader);
if( rc!=SQLITE_OK ) break;
}
err:
dlwDestroy(&dlWriter);
dlrDestroy(&dlReader);
return rc;
}
typedef struct OrderedDLReader {
DLReader *pReader;
int idx;
} OrderedDLReader;
static int orderedDLReaderCmp(OrderedDLReader *r1, OrderedDLReader *r2){
if( dlrAtEnd(r1->pReader) ){
if( dlrAtEnd(r2->pReader) ) return 0;
return 1;
}
if( dlrAtEnd(r2->pReader) ) return -1;
if( dlrDocid(r1->pReader)<dlrDocid(r2->pReader) ) return -1;
if( dlrDocid(r1->pReader)>dlrDocid(r2->pReader) ) return 1;
return r2->idx-r1->idx;
}
static void orderedDLReaderReorder(OrderedDLReader *p, int n){
while( n>1 && orderedDLReaderCmp(p, p+1)>0 ){
OrderedDLReader tmp = p[0];
p[0] = p[1];
p[1] = tmp;
n--;
p++;
}
}
static int docListMerge(DataBuffer *out,
DLReader *pReaders, int nReaders){
OrderedDLReader readers[MERGE_COUNT];
DLWriter writer;
int i, n;
const char *pStart = 0;
int nStart = 0;
sqlite_int64 iFirstDocid = 0, iLastDocid = 0;
int rc = SQLITE_OK;
assert( nReaders>0 );
if( nReaders==1 ){
dataBufferAppend(out, dlrDocData(pReaders), dlrAllDataBytes(pReaders));
return SQLITE_OK;
}
assert( nReaders<=MERGE_COUNT );
n = 0;
for(i=0; i<nReaders; i++){
assert( pReaders[i].iType==pReaders[0].iType );
readers[i].pReader = pReaders+i;
readers[i].idx = i;
n += dlrAllDataBytes(&pReaders[i]);
}
dataBufferExpand(out, n);
while( i-->0 ){
orderedDLReaderReorder(readers+i, nReaders-i);
}
dlwInit(&writer, pReaders[0].iType, out);
while( !dlrAtEnd(readers[0].pReader) ){
sqlite_int64 iDocid = dlrDocid(readers[0].pReader);
if( dlrDocData(readers[0].pReader)==pStart+nStart ){
nStart += dlrDocDataBytes(readers[0].pReader);
}else{
if( pStart!=0 ){
rc = dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
if( rc!=SQLITE_OK ) goto err;
}
pStart = dlrDocData(readers[0].pReader);
nStart = dlrDocDataBytes(readers[0].pReader);
iFirstDocid = iDocid;
}
iLastDocid = iDocid;
rc = dlrStep(readers[0].pReader);
if( rc!=SQLITE_OK ) goto err;
for(i=1; i<nReaders &&
!dlrAtEnd(readers[i].pReader) &&
dlrDocid(readers[i].pReader)==iDocid; i++){
rc = dlrStep(readers[i].pReader);
if( rc!=SQLITE_OK ) goto err;
}
while( i-->0 ){
orderedDLReaderReorder(readers+i, nReaders-i);
}
}
if( nStart>0 )
rc = dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
err:
dlwDestroy(&writer);
return rc;
}
static int posListCmp(PLReader *pLeft, PLReader *pRight){
assert( pLeft->iType==pRight->iType );
if( pLeft->iType==DL_DOCIDS ) return 0;
if( plrAtEnd(pLeft) ) return plrAtEnd(pRight) ? 0 : 1;
if( plrAtEnd(pRight) ) return -1;
if( plrColumn(pLeft)<plrColumn(pRight) ) return -1;
if( plrColumn(pLeft)>plrColumn(pRight) ) return 1;
if( plrPosition(pLeft)<plrPosition(pRight) ) return -1;
if( plrPosition(pLeft)>plrPosition(pRight) ) return 1;
if( pLeft->iType==DL_POSITIONS ) return 0;
if( plrStartOffset(pLeft)<plrStartOffset(pRight) ) return -1;
if( plrStartOffset(pLeft)>plrStartOffset(pRight) ) return 1;
if( plrEndOffset(pLeft)<plrEndOffset(pRight) ) return -1;
if( plrEndOffset(pLeft)>plrEndOffset(pRight) ) return 1;
return 0;
}
static int posListUnion(DLReader *pLeft, DLReader *pRight, DLWriter *pOut){
PLReader left, right;
PLWriter writer;
int rc;
assert( dlrDocid(pLeft)==dlrDocid(pRight) );
assert( pLeft->iType==pRight->iType );
assert( pLeft->iType==pOut->iType );
rc = plrInit(&left, pLeft);
if( rc != SQLITE_OK ) return rc;
rc = plrInit(&right, pRight);
if( rc != SQLITE_OK ){
plrDestroy(&left);
return rc;
}
plwInit(&writer, pOut, dlrDocid(pLeft));
while( !plrAtEnd(&left) || !plrAtEnd(&right) ){
int c = posListCmp(&left, &right);
if( c<0 ){
plwCopy(&writer, &left);
rc = plrStep(&left);
if( rc != SQLITE_OK ) break;
}else if( c>0 ){
plwCopy(&writer, &right);
rc = plrStep(&right);
if( rc != SQLITE_OK ) break;
}else{
plwCopy(&writer, &left);
rc = plrStep(&left);
if( rc != SQLITE_OK ) break;
rc = plrStep(&right);
if( rc != SQLITE_OK ) break;
}
}
plwTerminate(&writer);
plwDestroy(&writer);
plrDestroy(&left);
plrDestroy(&right);
return rc;
}
static int docListUnion(
const char *pLeft, int nLeft,
const char *pRight, int nRight,
DataBuffer *pOut
){
DLReader left, right;
DLWriter writer;
int rc;
if( nLeft==0 ){
if( nRight!=0) dataBufferAppend(pOut, pRight, nRight);
return SQLITE_OK;
}
if( nRight==0 ){
dataBufferAppend(pOut, pLeft, nLeft);
return SQLITE_OK;
}
rc = dlrInit(&left, DL_DEFAULT, pLeft, nLeft);
if( rc!=SQLITE_OK ) return rc;
rc = dlrInit(&right, DL_DEFAULT, pRight, nRight);
if( rc!=SQLITE_OK ){
dlrDestroy(&left);
return rc;
}
dlwInit(&writer, DL_DEFAULT, pOut);
while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
if( dlrAtEnd(&right) ){
rc = dlwCopy(&writer, &left);
if( rc!=SQLITE_OK ) break;
rc = dlrStep(&left);
if( rc!=SQLITE_OK ) break;
}else if( dlrAtEnd(&left) ){
rc = dlwCopy(&writer, &right);
if( rc!=SQLITE_OK ) break;
rc = dlrStep(&right);
if( rc!=SQLITE_OK ) break;
}else if( dlrDocid(&left)<dlrDocid(&right) ){
rc = dlwCopy(&writer, &left);
if( rc!=SQLITE_OK ) break;
rc = dlrStep(&left);
if( rc!=SQLITE_OK ) break;
}else if( dlrDocid(&left)>dlrDocid(&right) ){
rc = dlwCopy(&writer, &right);
if( rc!=SQLITE_OK ) break;
rc = dlrStep(&right);
if( rc!=SQLITE_OK ) break;
}else{
rc = posListUnion(&left, &right, &writer);
if( rc!=SQLITE_OK ) break;
rc = dlrStep(&left);
if( rc!=SQLITE_OK ) break;
rc = dlrStep(&right);
if( rc!=SQLITE_OK ) break;
}
}
dlrDestroy(&left);
dlrDestroy(&right);
dlwDestroy(&writer);
return rc;
}
static int posListPhraseMerge(DLReader *pLeft, DLReader *pRight,
DLWriter *pOut){
PLReader left, right;
PLWriter writer;
int match = 0;
int rc;
assert( dlrDocid(pLeft)==dlrDocid(pRight) );
assert( pOut->iType!=DL_POSITIONS_OFFSETS );
rc = plrInit(&left, pLeft);
if( rc!=SQLITE_OK ) return rc;
rc = plrInit(&right, pRight);
if( rc!=SQLITE_OK ){
plrDestroy(&left);
return rc;
}
while( !plrAtEnd(&left) && !plrAtEnd(&right) ){
if( plrColumn(&left)<plrColumn(&right) ){
rc = plrStep(&left);
if( rc!=SQLITE_OK ) break;
}else if( plrColumn(&left)>plrColumn(&right) ){
rc = plrStep(&right);
if( rc!=SQLITE_OK ) break;
}else if( plrPosition(&left)+1<plrPosition(&right) ){
rc = plrStep(&left);
if( rc!=SQLITE_OK ) break;
}else if( plrPosition(&left)+1>plrPosition(&right) ){
rc = plrStep(&right);
if( rc!=SQLITE_OK ) break;
}else{
if( !match ){
plwInit(&writer, pOut, dlrDocid(pLeft));
match = 1;
}
plwAdd(&writer, plrColumn(&right), plrPosition(&right), 0, 0);
rc = plrStep(&left);
if( rc!=SQLITE_OK ) break;
rc = plrStep(&right);
if( rc!=SQLITE_OK ) break;
}
}
if( match ){
plwTerminate(&writer);
plwDestroy(&writer);
}
plrDestroy(&left);
plrDestroy(&right);
return rc;
}
static int docListPhraseMerge(
const char *pLeft, int nLeft,
const char *pRight, int nRight,
DocListType iType,
DataBuffer *pOut
){
DLReader left, right;
DLWriter writer;
int rc;
if( nLeft==0 || nRight==0 ) return SQLITE_OK;
assert( iType!=DL_POSITIONS_OFFSETS );
rc = dlrInit(&left, DL_POSITIONS, pLeft, nLeft);
if( rc!=SQLITE_OK ) return rc;
rc = dlrInit(&right, DL_POSITIONS, pRight, nRight);
if( rc!=SQLITE_OK ){
dlrDestroy(&left);
return rc;
}
dlwInit(&writer, iType, pOut);
while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
if( dlrDocid(&left)<dlrDocid(&right) ){
rc = dlrStep(&left);
if( rc!=SQLITE_OK ) break;
}else if( dlrDocid(&right)<dlrDocid(&left) ){
rc = dlrStep(&right);
if( rc!=SQLITE_OK ) break;
}else{
rc = posListPhraseMerge(&left, &right, &writer);
if( rc!=SQLITE_OK ) break;
rc = dlrStep(&left);
if( rc!=SQLITE_OK ) break;
rc = dlrStep(&right);
if( rc!=SQLITE_OK ) break;
}
}
dlrDestroy(&left);
dlrDestroy(&right);
dlwDestroy(&writer);
return rc;
}
static int docListAndMerge(
const char *pLeft, int nLeft,
const char *pRight, int nRight,
DataBuffer *pOut
){
DLReader left, right;
DLWriter writer;
int rc;
if( nLeft==0 || nRight==0 ) return SQLITE_OK;
rc = dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
if( rc!=SQLITE_OK ) return rc;
rc = dlrInit(&right, DL_DOCIDS, pRight, nRight);
if( rc!=SQLITE_OK ){
dlrDestroy(&left);
return rc;
}
dlwInit(&writer, DL_DOCIDS, pOut);
while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
if( dlrDocid(&left)<dlrDocid(&right) ){
rc = dlrStep(&left);
if( rc!=SQLITE_OK ) break;
}else if( dlrDocid(&right)<dlrDocid(&left) ){
rc = dlrStep(&right);
if( rc!=SQLITE_OK ) break;
}else{
dlwAdd(&writer, dlrDocid(&left));
rc = dlrStep(&left);
if( rc!=SQLITE_OK ) break;
rc = dlrStep(&right);
if( rc!=SQLITE_OK ) break;
}
}
dlrDestroy(&left);
dlrDestroy(&right);
dlwDestroy(&writer);
return rc;
}
static int docListOrMerge(
const char *pLeft, int nLeft,
const char *pRight, int nRight,
DataBuffer *pOut
){
DLReader left, right;
DLWriter writer;
int rc;
if( nLeft==0 ){
if( nRight!=0 ) dataBufferAppend(pOut, pRight, nRight);
return SQLITE_OK;
}
if( nRight==0 ){
dataBufferAppend(pOut, pLeft, nLeft);
return SQLITE_OK;
}
rc = dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
if( rc!=SQLITE_OK ) return rc;
rc = dlrInit(&right, DL_DOCIDS, pRight, nRight);
if( rc!=SQLITE_OK ){
dlrDestroy(&left);
return rc;
}
dlwInit(&writer, DL_DOCIDS, pOut);
while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
if( dlrAtEnd(&right) ){
dlwAdd(&writer, dlrDocid(&left));
rc = dlrStep(&left);
if( rc!=SQLITE_OK ) break;
}else if( dlrAtEnd(&left) ){
dlwAdd(&writer, dlrDocid(&right));
rc = dlrStep(&right);
if( rc!=SQLITE_OK ) break;
}else if( dlrDocid(&left)<dlrDocid(&right) ){
dlwAdd(&writer, dlrDocid(&left));
rc = dlrStep(&left);
if( rc!=SQLITE_OK ) break;
}else if( dlrDocid(&right)<dlrDocid(&left) ){
dlwAdd(&writer, dlrDocid(&right));
rc = dlrStep(&right);
if( rc!=SQLITE_OK ) break;
}else{
dlwAdd(&writer, dlrDocid(&left));
rc = dlrStep(&left);
if( rc!=SQLITE_OK ) break;
rc = dlrStep(&right);
if( rc!=SQLITE_OK ) break;
}
}
dlrDestroy(&left);
dlrDestroy(&right);
dlwDestroy(&writer);
return rc;
}
static int docListExceptMerge(
const char *pLeft, int nLeft,
const char *pRight, int nRight,
DataBuffer *pOut
){
DLReader left, right;
DLWriter writer;
int rc;
if( nLeft==0 ) return SQLITE_OK;
if( nRight==0 ){
dataBufferAppend(pOut, pLeft, nLeft);
return SQLITE_OK;
}
rc = dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
if( rc!=SQLITE_OK ) return rc;
rc = dlrInit(&right, DL_DOCIDS, pRight, nRight);
if( rc!=SQLITE_OK ){
dlrDestroy(&left);
return rc;
}
dlwInit(&writer, DL_DOCIDS, pOut);
while( !dlrAtEnd(&left) ){
while( !dlrAtEnd(&right) && dlrDocid(&right)<dlrDocid(&left) ){
rc = dlrStep(&right);
if( rc!=SQLITE_OK ) goto err;
}
if( dlrAtEnd(&right) || dlrDocid(&left)<dlrDocid(&right) ){
dlwAdd(&writer, dlrDocid(&left));
}
rc = dlrStep(&left);
if( rc!=SQLITE_OK ) break;
}
err:
dlrDestroy(&left);
dlrDestroy(&right);
dlwDestroy(&writer);
return rc;
}
static char *string_dup_n(const char *s, int n){
char *str = sqlite3_malloc(n + 1);
memcpy(str, s, n);
str[n] = '\0';
return str;
}
static char *string_dup(const char *s){
return string_dup_n(s, strlen(s));
}
static char *string_format(const char *zFormat,
const char *zDb, const char *zName){
const char *p;
size_t len = 0;
size_t nDb = strlen(zDb);
size_t nName = strlen(zName);
size_t nFullTableName = nDb+1+nName;
char *result;
char *r;
for(p = zFormat ; *p ; ++p){
len += (*p=='%' ? nFullTableName : 1);
}
len += 1;
r = result = sqlite3_malloc(len);
for(p = zFormat; *p; ++p){
if( *p=='%' ){
memcpy(r, zDb, nDb);
r += nDb;
*r++ = '.';
memcpy(r, zName, nName);
r += nName;
} else {
*r++ = *p;
}
}
*r++ = '\0';
assert( r == result + len );
return result;
}
static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
const char *zFormat){
char *zCommand = string_format(zFormat, zDb, zName);
int rc;
TRACE(("FTS2 sql: %s\n", zCommand));
rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
sqlite3_free(zCommand);
return rc;
}
static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
sqlite3_stmt **ppStmt, const char *zFormat){
char *zCommand = string_format(zFormat, zDb, zName);
int rc;
TRACE(("FTS2 prepare: %s\n", zCommand));
rc = sqlite3_prepare_v2(db, zCommand, -1, ppStmt, NULL);
sqlite3_free(zCommand);
return rc;
}
typedef struct fulltext_vtab fulltext_vtab;
typedef struct QueryTerm {
short int nPhrase;
short int iPhrase;
short int iColumn;
signed char isOr;
signed char isNot;
signed char isPrefix;
char *pTerm;
int nTerm;
} QueryTerm;
typedef struct Query {
fulltext_vtab *pFts;
int nTerms;
QueryTerm *pTerms;
int nextIsOr;
int nextColumn;
int dfltColumn;
} Query;
typedef struct Snippet {
int nMatch;
int nAlloc;
struct snippetMatch {
char snStatus;
short int iCol;
short int iTerm;
short int nByte;
int iStart;
} *aMatch;
char *zOffset;
int nOffset;
char *zSnippet;
int nSnippet;
} Snippet;
typedef enum QueryType {
QUERY_GENERIC,
QUERY_ROWID,
QUERY_FULLTEXT
} QueryType;
typedef enum fulltext_statement {
CONTENT_INSERT_STMT,
CONTENT_SELECT_STMT,
CONTENT_UPDATE_STMT,
CONTENT_DELETE_STMT,
CONTENT_EXISTS_STMT,
BLOCK_INSERT_STMT,
BLOCK_SELECT_STMT,
BLOCK_DELETE_STMT,
BLOCK_DELETE_ALL_STMT,
SEGDIR_MAX_INDEX_STMT,
SEGDIR_SET_STMT,
SEGDIR_SELECT_LEVEL_STMT,
SEGDIR_SPAN_STMT,
SEGDIR_DELETE_STMT,
SEGDIR_SELECT_SEGMENT_STMT,
SEGDIR_SELECT_ALL_STMT,
SEGDIR_DELETE_ALL_STMT,
SEGDIR_COUNT_STMT,
MAX_STMT
} fulltext_statement;
static const char *const fulltext_zStatement[MAX_STMT] = {
NULL,
"select * from %_content where rowid = ?",
NULL,
"delete from %_content where rowid = ?",
"select rowid from %_content limit 1",
"insert into %_segments values (?)",
"select block from %_segments where rowid = ?",
"delete from %_segments where rowid between ? and ?",
"delete from %_segments",
"select max(idx) from %_segdir where level = ?",
"insert into %_segdir values (?, ?, ?, ?, ?, ?)",
"select start_block, leaves_end_block, root, idx from %_segdir "
" where level = ? order by idx",
"select min(start_block), max(end_block) from %_segdir "
" where level = ? and start_block <> 0",
"delete from %_segdir where level = ?",
"select start_block, leaves_end_block, root from %_segdir "
" where level = ? and idx = ?",
"select start_block, leaves_end_block, root from %_segdir "
" order by level desc, idx asc",
"delete from %_segdir",
"select count(*), ifnull(max(level),0) from %_segdir",
};
struct fulltext_vtab {
sqlite3_vtab base;
sqlite3 *db;
const char *zDb;
const char *zName;
int nColumn;
char **azColumn;
char **azContentColumn;
sqlite3_tokenizer *pTokenizer;
sqlite3_stmt *pFulltextStatements[MAX_STMT];
sqlite3_stmt *pLeafSelectStmts[MERGE_COUNT];
#define LEAF_SELECT \
"select block from %_segments where rowid between ? and ? order by rowid"
int nPendingData;
#define kPendingThreshold (1*1024*1024)
sqlite_int64 iPrevDocid;
fts2Hash pendingTerms;
};
typedef struct fulltext_cursor {
sqlite3_vtab_cursor base;
QueryType iCursorType;
sqlite3_stmt *pStmt;
int eof;
Query q;
Snippet snippet;
int iColumn;
DataBuffer result;
DLReader reader;
} fulltext_cursor;
static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){
return (fulltext_vtab *) c->base.pVtab;
}
static const sqlite3_module fts2Module;
static const char *contentInsertStatement(fulltext_vtab *v){
StringBuffer sb;
int i;
initStringBuffer(&sb);
append(&sb, "insert into %_content (rowid, ");
appendList(&sb, v->nColumn, v->azContentColumn);
append(&sb, ") values (?");
for(i=0; i<v->nColumn; ++i)
append(&sb, ", ?");
append(&sb, ")");
return stringBufferData(&sb);
}
static const char *contentUpdateStatement(fulltext_vtab *v){
StringBuffer sb;
int i;
initStringBuffer(&sb);
append(&sb, "update %_content set ");
for(i=0; i<v->nColumn; ++i) {
if( i>0 ){
append(&sb, ", ");
}
append(&sb, v->azContentColumn[i]);
append(&sb, " = ?");
}
append(&sb, " where rowid = ?");
return stringBufferData(&sb);
}
static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
sqlite3_stmt **ppStmt){
assert( iStmt<MAX_STMT );
if( v->pFulltextStatements[iStmt]==NULL ){
const char *zStmt;
int rc;
switch( iStmt ){
case CONTENT_INSERT_STMT:
zStmt = contentInsertStatement(v); break;
case CONTENT_UPDATE_STMT:
zStmt = contentUpdateStatement(v); break;
default:
zStmt = fulltext_zStatement[iStmt];
}
rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt],
zStmt);
if( zStmt != fulltext_zStatement[iStmt]) sqlite3_free((void *) zStmt);
if( rc!=SQLITE_OK ) return rc;
} else {
int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
if( rc!=SQLITE_OK ) return rc;
}
*ppStmt = v->pFulltextStatements[iStmt];
return SQLITE_OK;
}
static int sql_single_step(sqlite3_stmt *s){
int rc = sqlite3_step(s);
return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
}
static int sql_get_leaf_statement(fulltext_vtab *v, int idx,
sqlite3_stmt **ppStmt){
assert( idx>=-1 && idx<MERGE_COUNT );
if( idx==-1 ){
return sql_prepare(v->db, v->zDb, v->zName, ppStmt, LEAF_SELECT);
}else if( v->pLeafSelectStmts[idx]==NULL ){
int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx],
LEAF_SELECT);
if( rc!=SQLITE_OK ) return rc;
}else{
int rc = sqlite3_reset(v->pLeafSelectStmts[idx]);
if( rc!=SQLITE_OK ) return rc;
}
*ppStmt = v->pLeafSelectStmts[idx];
return SQLITE_OK;
}
static int content_insert(fulltext_vtab *v, sqlite3_value *rowid,
sqlite3_value **pValues){
sqlite3_stmt *s;
int i;
int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_value(s, 1, rowid);
if( rc!=SQLITE_OK ) return rc;
for(i=0; i<v->nColumn; ++i){
rc = sqlite3_bind_value(s, 2+i, pValues[i]);
if( rc!=SQLITE_OK ) return rc;
}
return sql_single_step(s);
}
static int content_update(fulltext_vtab *v, sqlite3_value **pValues,
sqlite_int64 iRowid){
sqlite3_stmt *s;
int i;
int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
for(i=0; i<v->nColumn; ++i){
rc = sqlite3_bind_value(s, 1+i, pValues[i]);
if( rc!=SQLITE_OK ) return rc;
}
rc = sqlite3_bind_int64(s, 1+v->nColumn, iRowid);
if( rc!=SQLITE_OK ) return rc;
return sql_single_step(s);
}
static void freeStringArray(int nString, const char **pString){
int i;
for (i=0 ; i < nString ; ++i) {
if( pString[i]!=NULL ) sqlite3_free((void *) pString[i]);
}
sqlite3_free((void *) pString);
}
static int content_select(fulltext_vtab *v, sqlite_int64 iRow,
const char ***pValues){
sqlite3_stmt *s;
const char **values;
int i;
int rc;
*pValues = NULL;
rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_int64(s, 1, iRow);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_step(s);
if( rc!=SQLITE_ROW ) return rc;
values = (const char **) sqlite3_malloc(v->nColumn * sizeof(const char *));
for(i=0; i<v->nColumn; ++i){
if( sqlite3_column_type(s, i)==SQLITE_NULL ){
values[i] = NULL;
}else{
values[i] = string_dup((char*)sqlite3_column_text(s, i));
}
}
rc = sqlite3_step(s);
if( rc==SQLITE_DONE ){
*pValues = values;
return SQLITE_OK;
}
freeStringArray(v->nColumn, values);
return rc;
}
static int content_delete(fulltext_vtab *v, sqlite_int64 iRow){
sqlite3_stmt *s;
int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_int64(s, 1, iRow);
if( rc!=SQLITE_OK ) return rc;
return sql_single_step(s);
}
static int content_exists(fulltext_vtab *v){
sqlite3_stmt *s;
int rc = sql_get_statement(v, CONTENT_EXISTS_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_step(s);
if( rc!=SQLITE_ROW ) return rc;
rc = sqlite3_step(s);
if( rc==SQLITE_DONE ) return SQLITE_ROW;
if( rc==SQLITE_ROW ) return SQLITE_ERROR;
return rc;
}
static int block_insert(fulltext_vtab *v, const char *pData, int nData,
sqlite_int64 *piBlockid){
sqlite3_stmt *s;
int rc = sql_get_statement(v, BLOCK_INSERT_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_blob(s, 1, pData, nData, SQLITE_STATIC);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_step(s);
if( rc==SQLITE_ROW ) return SQLITE_ERROR;
if( rc!=SQLITE_DONE ) return rc;
*piBlockid = sqlite3_last_insert_rowid(v->db);
return SQLITE_OK;
}
static int block_delete(fulltext_vtab *v,
sqlite_int64 iStartBlockid, sqlite_int64 iEndBlockid){
sqlite3_stmt *s;
int rc = sql_get_statement(v, BLOCK_DELETE_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_int64(s, 1, iStartBlockid);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_int64(s, 2, iEndBlockid);
if( rc!=SQLITE_OK ) return rc;
return sql_single_step(s);
}
static int segdir_max_index(fulltext_vtab *v, int iLevel, int *pidx){
sqlite3_stmt *s;
int rc = sql_get_statement(v, SEGDIR_MAX_INDEX_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_int(s, 1, iLevel);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_step(s);
if( rc==SQLITE_DONE ) return SQLITE_DONE;
if( rc!=SQLITE_ROW ) return rc;
if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
rc = sqlite3_step(s);
if( rc==SQLITE_ROW ) return SQLITE_ERROR;
return rc;
}
*pidx = sqlite3_column_int(s, 0);
rc = sqlite3_step(s);
if( rc==SQLITE_ROW ) return SQLITE_ERROR;
if( rc!=SQLITE_DONE ) return rc;
return SQLITE_ROW;
}
static int segdir_set(fulltext_vtab *v, int iLevel, int idx,
sqlite_int64 iStartBlockid,
sqlite_int64 iLeavesEndBlockid,
sqlite_int64 iEndBlockid,
const char *pRootData, int nRootData){
sqlite3_stmt *s;
int rc = sql_get_statement(v, SEGDIR_SET_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_int(s, 1, iLevel);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_int(s, 2, idx);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_int64(s, 3, iStartBlockid);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_int64(s, 4, iLeavesEndBlockid);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_int64(s, 5, iEndBlockid);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_blob(s, 6, pRootData, nRootData, SQLITE_STATIC);
if( rc!=SQLITE_OK ) return rc;
return sql_single_step(s);
}
static int segdir_span(fulltext_vtab *v, int iLevel,
sqlite_int64 *piStartBlockid,
sqlite_int64 *piEndBlockid){
sqlite3_stmt *s;
int rc = sql_get_statement(v, SEGDIR_SPAN_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_int(s, 1, iLevel);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_step(s);
if( rc==SQLITE_DONE ) return SQLITE_DONE;
if( rc!=SQLITE_ROW ) return rc;
if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
int rc2 = sqlite3_step(s);
if( rc2==SQLITE_ROW ) return SQLITE_ERROR;
return rc2;
}
*piStartBlockid = sqlite3_column_int64(s, 0);
*piEndBlockid = sqlite3_column_int64(s, 1);
rc = sqlite3_step(s);
if( rc==SQLITE_ROW ) return SQLITE_ERROR;
if( rc!=SQLITE_DONE ) return rc;
return SQLITE_ROW;
}
static int segdir_delete(fulltext_vtab *v, int iLevel){
sqlite3_stmt *s;
sqlite_int64 iStartBlockid, iEndBlockid;
int rc = segdir_span(v, iLevel, &iStartBlockid, &iEndBlockid);
if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;
if( rc==SQLITE_ROW ){
rc = block_delete(v, iStartBlockid, iEndBlockid);
if( rc!=SQLITE_OK ) return rc;
}
rc = sql_get_statement(v, SEGDIR_DELETE_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_int64(s, 1, iLevel);
if( rc!=SQLITE_OK ) return rc;
return sql_single_step(s);
}
static int segdir_delete_all(fulltext_vtab *v){
sqlite3_stmt *s;
int rc = sql_get_statement(v, SEGDIR_DELETE_ALL_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
rc = sql_single_step(s);
if( rc!=SQLITE_OK ) return rc;
rc = sql_get_statement(v, BLOCK_DELETE_ALL_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
return sql_single_step(s);
}
static int segdir_count(fulltext_vtab *v, int *pnSegments, int *piMaxLevel){
sqlite3_stmt *s;
int rc = sql_get_statement(v, SEGDIR_COUNT_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_step(s);
if( rc==SQLITE_DONE ){
*pnSegments = 0;
*piMaxLevel = 0;
return SQLITE_OK;
}
if( rc!=SQLITE_ROW ) return rc;
*pnSegments = sqlite3_column_int(s, 0);
*piMaxLevel = sqlite3_column_int(s, 1);
rc = sqlite3_step(s);
if( rc==SQLITE_DONE ) return SQLITE_OK;
if( rc==SQLITE_ROW ) return SQLITE_ERROR;
return rc;
}
static int clearPendingTerms(fulltext_vtab *v);
static void fulltext_vtab_destroy(fulltext_vtab *v){
int iStmt, i;
TRACE(("FTS2 Destroy %p\n", v));
for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
if( v->pFulltextStatements[iStmt]!=NULL ){
sqlite3_finalize(v->pFulltextStatements[iStmt]);
v->pFulltextStatements[iStmt] = NULL;
}
}
for( i=0; i<MERGE_COUNT; i++ ){
if( v->pLeafSelectStmts[i]!=NULL ){
sqlite3_finalize(v->pLeafSelectStmts[i]);
v->pLeafSelectStmts[i] = NULL;
}
}
if( v->pTokenizer!=NULL ){
v->pTokenizer->pModule->xDestroy(v->pTokenizer);
v->pTokenizer = NULL;
}
clearPendingTerms(v);
sqlite3_free(v->azColumn);
for(i = 0; i < v->nColumn; ++i) {
sqlite3_free(v->azContentColumn[i]);
}
sqlite3_free(v->azContentColumn);
sqlite3_free(v);
}
#define TOKEN_EOF 0
#define TOKEN_SPACE 1
#define TOKEN_ID 2
#define TOKEN_STRING 3
#define TOKEN_PUNCT 4
static const char isIdChar[] = {
0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
};
#define IdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && isIdChar[c-0x20]))
static int getToken(const char *z, int *tokenType){
int i, c;
switch( *z ){
case 0: {
*tokenType = TOKEN_EOF;
return 0;
}
case ' ': case '\t': case '\n': case '\f': case '\r': {
for(i=1; safe_isspace(z[i]); i++){}
*tokenType = TOKEN_SPACE;
return i;
}
case '`':
case '\'':
case '"': {
int delim = z[0];
for(i=1; (c=z[i])!=0; i++){
if( c==delim ){
if( z[i+1]==delim ){
i++;
}else{
break;
}
}
}
*tokenType = TOKEN_STRING;
return i + (c!=0);
}
case '[': {
for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
*tokenType = TOKEN_ID;
return i;
}
default: {
if( !IdChar(*z) ){
break;
}
for(i=1; IdChar(z[i]); i++){}
*tokenType = TOKEN_ID;
return i;
}
}
*tokenType = TOKEN_PUNCT;
return 1;
}
typedef struct Token {
const char *z;
short int n;
} Token;
static char **tokenizeString(const char *z, int *pnToken){
int nToken = 0;
Token *aToken = sqlite3_malloc( strlen(z) * sizeof(aToken[0]) );
int n = 1;
int e, i;
int totalSize = 0;
char **azToken;
char *zCopy;
while( n>0 ){
n = getToken(z, &e);
if( e!=TOKEN_SPACE ){
aToken[nToken].z = z;
aToken[nToken].n = n;
nToken++;
totalSize += n+1;
}
z += n;
}
azToken = (char**)sqlite3_malloc( nToken*sizeof(char*) + totalSize );
zCopy = (char*)&azToken[nToken];
nToken--;
for(i=0; i<nToken; i++){
azToken[i] = zCopy;
n = aToken[i].n;
memcpy(zCopy, aToken[i].z, n);
zCopy[n] = 0;
zCopy += n+1;
}
azToken[nToken] = 0;
sqlite3_free(aToken);
*pnToken = nToken;
return azToken;
}
static void dequoteString(char *z){
int quote;
int i, j;
if( z==0 ) return;
quote = z[0];
switch( quote ){
case '\'': break;
case '"': break;
case '`': break;
case '[': quote = ']'; break;
default: return;
}
for(i=1, j=0; z[i]; i++){
if( z[i]==quote ){
if( z[i+1]==quote ){
z[j++] = quote;
i++;
}else{
z[j++] = 0;
break;
}
}else{
z[j++] = z[i];
}
}
}
static void tokenListToIdList(char **azIn){
int i, j;
if( azIn ){
for(i=0, j=-1; azIn[i]; i++){
if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){
dequoteString(azIn[i]);
if( j>=0 ){
azIn[j] = azIn[i];
}
j++;
}
}
azIn[j] = 0;
}
}
static char *firstToken(char *zIn, char **pzTail){
int n, ttype;
while(1){
n = getToken(zIn, &ttype);
if( ttype==TOKEN_SPACE ){
zIn += n;
}else if( ttype==TOKEN_EOF ){
*pzTail = zIn;
return 0;
}else{
zIn[n] = 0;
*pzTail = &zIn[1];
dequoteString(zIn);
return zIn;
}
}
}
static int startsWith(const char *s, const char *t){
while( safe_isspace(*s) ){ s++; }
while( *t ){
if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0;
}
return *s!='_' && !safe_isalnum(*s);
}
typedef struct TableSpec {
const char *zDb;
const char *zName;
int nColumn;
char **azColumn;
char **azContentColumn;
char **azTokenizer;
} TableSpec;
static void clearTableSpec(TableSpec *p) {
sqlite3_free(p->azColumn);
sqlite3_free(p->azContentColumn);
sqlite3_free(p->azTokenizer);
}
static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv,
char**pzErr){
int i, n;
char *z, *zDummy;
char **azArg;
const char *zTokenizer = 0;
assert( argc>=3 );
CLEAR(pSpec);
for(i=n=0; i<argc; i++){
n += strlen(argv[i]) + 1;
}
azArg = sqlite3_malloc( sizeof(char*)*argc + n );
if( azArg==0 ){
return SQLITE_NOMEM;
}
z = (char*)&azArg[argc];
for(i=0; i<argc; i++){
azArg[i] = z;
strcpy(z, argv[i]);
z += strlen(z)+1;
}
pSpec->zDb = azArg[1];
pSpec->zName = azArg[2];
pSpec->nColumn = 0;
pSpec->azColumn = azArg;
zTokenizer = "tokenize simple";
for(i=3; i<argc; ++i){
if( startsWith(azArg[i],"tokenize") ){
zTokenizer = azArg[i];
}else{
z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy);
pSpec->nColumn++;
}
}
if( pSpec->nColumn==0 ){
azArg[0] = "content";
pSpec->nColumn = 1;
}
pSpec->azContentColumn = sqlite3_malloc( pSpec->nColumn * sizeof(char *) );
if( pSpec->azContentColumn==0 ){
clearTableSpec(pSpec);
return SQLITE_NOMEM;
}
for(i=0; i<pSpec->nColumn; i++){
char *p;
pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]);
for (p = pSpec->azContentColumn[i]; *p ; ++p) {
if( !safe_isalnum(*p) ) *p = '_';
}
}
pSpec->azTokenizer = tokenizeString(zTokenizer, &n);
tokenListToIdList(pSpec->azTokenizer);
return SQLITE_OK;
}
static char *fulltextSchema(
int nColumn,
const char *const* azColumn,
const char *zTableName
){
int i;
char *zSchema, *zNext;
const char *zSep = "(";
zSchema = sqlite3_mprintf("CREATE TABLE x");
for(i=0; i<nColumn; i++){
zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]);
sqlite3_free(zSchema);
zSchema = zNext;
zSep = ",";
}
zNext = sqlite3_mprintf("%s,%Q)", zSchema, zTableName);
sqlite3_free(zSchema);
return zNext;
}
static int constructVtab(
sqlite3 *db,
fts2Hash *pHash,
TableSpec *spec,
sqlite3_vtab **ppVTab,
char **pzErr
){
int rc;
int n;
fulltext_vtab *v = 0;
const sqlite3_tokenizer_module *m = NULL;
char *schema;
char const *zTok;
int nTok;
v = (fulltext_vtab *) sqlite3_malloc(sizeof(fulltext_vtab));
if( v==0 ) return SQLITE_NOMEM;
CLEAR(v);
v->db = db;
v->zDb = spec->zDb;
v->zName = spec->zName;
v->nColumn = spec->nColumn;
v->azContentColumn = spec->azContentColumn;
spec->azContentColumn = 0;
v->azColumn = spec->azColumn;
spec->azColumn = 0;
if( spec->azTokenizer==0 ){
return SQLITE_NOMEM;
}
zTok = spec->azTokenizer[0];
if( !zTok ){
zTok = "simple";
}
nTok = strlen(zTok)+1;
m = (sqlite3_tokenizer_module *)sqlite3Fts2HashFind(pHash, zTok, nTok);
if( !m ){
*pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
rc = SQLITE_ERROR;
goto err;
}
for(n=0; spec->azTokenizer[n]; n++){}
if( n ){
rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
&v->pTokenizer);
}else{
rc = m->xCreate(0, 0, &v->pTokenizer);
}
if( rc!=SQLITE_OK ) goto err;
v->pTokenizer->pModule = m;
schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn,
spec->zName);
rc = sqlite3_declare_vtab(db, schema);
sqlite3_free(schema);
if( rc!=SQLITE_OK ) goto err;
memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));
v->nPendingData = -1;
*ppVTab = &v->base;
TRACE(("FTS2 Connect %p\n", v));
return rc;
err:
fulltext_vtab_destroy(v);
return rc;
}
static int fulltextConnect(
sqlite3 *db,
void *pAux,
int argc, const char *const*argv,
sqlite3_vtab **ppVTab,
char **pzErr
){
TableSpec spec;
int rc = parseSpec(&spec, argc, argv, pzErr);
if( rc!=SQLITE_OK ) return rc;
rc = constructVtab(db, (fts2Hash *)pAux, &spec, ppVTab, pzErr);
clearTableSpec(&spec);
return rc;
}
static int fulltextCreate(sqlite3 *db, void *pAux,
int argc, const char * const *argv,
sqlite3_vtab **ppVTab, char **pzErr){
int rc;
TableSpec spec;
StringBuffer schema;
TRACE(("FTS2 Create\n"));
rc = parseSpec(&spec, argc, argv, pzErr);
if( rc!=SQLITE_OK ) return rc;
initStringBuffer(&schema);
append(&schema, "CREATE TABLE %_content(");
appendList(&schema, spec.nColumn, spec.azContentColumn);
append(&schema, ")");
rc = sql_exec(db, spec.zDb, spec.zName, stringBufferData(&schema));
stringBufferDestroy(&schema);
if( rc!=SQLITE_OK ) goto out;
rc = sql_exec(db, spec.zDb, spec.zName,
"create table %_segments(block blob);");
if( rc!=SQLITE_OK ) goto out;
rc = sql_exec(db, spec.zDb, spec.zName,
"create table %_segdir("
" level integer,"
" idx integer,"
" start_block integer,"
" leaves_end_block integer,"
" end_block integer,"
" root blob,"
" primary key(level, idx)"
");");
if( rc!=SQLITE_OK ) goto out;
rc = constructVtab(db, (fts2Hash *)pAux, &spec, ppVTab, pzErr);
out:
clearTableSpec(&spec);
return rc;
}
static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
int i;
TRACE(("FTS2 BestIndex\n"));
for(i=0; i<pInfo->nConstraint; ++i){
const struct sqlite3_index_constraint *pConstraint;
pConstraint = &pInfo->aConstraint[i];
if( pConstraint->usable ) {
if( pConstraint->iColumn==-1 &&
pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
pInfo->idxNum = QUERY_ROWID;
TRACE(("FTS2 QUERY_ROWID\n"));
} else if( pConstraint->iColumn>=0 &&
pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn;
TRACE(("FTS2 QUERY_FULLTEXT %d\n", pConstraint->iColumn));
} else continue;
pInfo->aConstraintUsage[i].argvIndex = 1;
pInfo->aConstraintUsage[i].omit = 1;
pInfo->estimatedCost = 1.0;
return SQLITE_OK;
}
}
pInfo->idxNum = QUERY_GENERIC;
return SQLITE_OK;
}
static int fulltextDisconnect(sqlite3_vtab *pVTab){
TRACE(("FTS2 Disconnect %p\n", pVTab));
fulltext_vtab_destroy((fulltext_vtab *)pVTab);
return SQLITE_OK;
}
static int fulltextDestroy(sqlite3_vtab *pVTab){
fulltext_vtab *v = (fulltext_vtab *)pVTab;
int rc;
TRACE(("FTS2 Destroy %p\n", pVTab));
rc = sql_exec(v->db, v->zDb, v->zName,
"drop table if exists %_content;"
"drop table if exists %_segments;"
"drop table if exists %_segdir;"
);
if( rc!=SQLITE_OK ) return rc;
fulltext_vtab_destroy((fulltext_vtab *)pVTab);
return SQLITE_OK;
}
static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
fulltext_cursor *c;
c = (fulltext_cursor *) sqlite3_malloc(sizeof(fulltext_cursor));
if( c ){
memset(c, 0, sizeof(fulltext_cursor));
*ppCursor = &c->base;
TRACE(("FTS2 Open %p: %p\n", pVTab, c));
return SQLITE_OK;
}else{
return SQLITE_NOMEM;
}
}
static void queryClear(Query *q){
int i;
for(i = 0; i < q->nTerms; ++i){
sqlite3_free(q->pTerms[i].pTerm);
}
sqlite3_free(q->pTerms);
CLEAR(q);
}
static void snippetClear(Snippet *p){
sqlite3_free(p->aMatch);
sqlite3_free(p->zOffset);
sqlite3_free(p->zSnippet);
CLEAR(p);
}
static void snippetAppendMatch(
Snippet *p,
int iCol, int iTerm,
int iStart, int nByte
){
int i;
struct snippetMatch *pMatch;
if( p->nMatch+1>=p->nAlloc ){
p->nAlloc = p->nAlloc*2 + 10;
p->aMatch = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
if( p->aMatch==0 ){
p->nMatch = 0;
p->nAlloc = 0;
return;
}
}
i = p->nMatch++;
pMatch = &p->aMatch[i];
pMatch->iCol = iCol;
pMatch->iTerm = iTerm;
pMatch->iStart = iStart;
pMatch->nByte = nByte;
}
#define FTS2_ROTOR_SZ (32)
#define FTS2_ROTOR_MASK (FTS2_ROTOR_SZ-1)
static void snippetOffsetsOfColumn(
Query *pQuery,
Snippet *pSnippet,
int iColumn,
const char *zDoc,
int nDoc
){
const sqlite3_tokenizer_module *pTModule;
sqlite3_tokenizer *pTokenizer;
sqlite3_tokenizer_cursor *pTCursor;
fulltext_vtab *pVtab;
int nColumn;
const QueryTerm *aTerm;
int nTerm;
int i, j;
int rc;
unsigned int match, prevMatch;
const char *zToken;
int nToken;
int iBegin, iEnd, iPos;
unsigned int iRotor = 0;
int iRotorBegin[FTS2_ROTOR_SZ];
int iRotorLen[FTS2_ROTOR_SZ];
pVtab = pQuery->pFts;
nColumn = pVtab->nColumn;
pTokenizer = pVtab->pTokenizer;
pTModule = pTokenizer->pModule;
rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
if( rc ) return;
pTCursor->pTokenizer = pTokenizer;
aTerm = pQuery->pTerms;
nTerm = pQuery->nTerms;
if( nTerm>=FTS2_ROTOR_SZ ){
nTerm = FTS2_ROTOR_SZ - 1;
}
prevMatch = 0;
while(1){
rc = pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
if( rc ) break;
iRotorBegin[iRotor&FTS2_ROTOR_MASK] = iBegin;
iRotorLen[iRotor&FTS2_ROTOR_MASK] = iEnd-iBegin;
match = 0;
for(i=0; i<nTerm; i++){
int iCol;
iCol = aTerm[i].iColumn;
if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
if( aTerm[i].nTerm>nToken ) continue;
if( !aTerm[i].isPrefix && aTerm[i].nTerm<nToken ) continue;
assert( aTerm[i].nTerm<=nToken );
if( memcmp(aTerm[i].pTerm, zToken, aTerm[i].nTerm) ) continue;
if( aTerm[i].iPhrase>1 && (prevMatch & (1<<i))==0 ) continue;
match |= 1<<i;
if( i==nTerm-1 || aTerm[i+1].iPhrase==1 ){
for(j=aTerm[i].iPhrase-1; j>=0; j--){
int k = (iRotor-j) & FTS2_ROTOR_MASK;
snippetAppendMatch(pSnippet, iColumn, i-j,
iRotorBegin[k], iRotorLen[k]);
}
}
}
prevMatch = match<<1;
iRotor++;
}
pTModule->xClose(pTCursor);
}
static void snippetAllOffsets(fulltext_cursor *p){
int nColumn;
int iColumn, i;
int iFirst, iLast;
fulltext_vtab *pFts;
if( p->snippet.nMatch ) return;
if( p->q.nTerms==0 ) return;
pFts = p->q.pFts;
nColumn = pFts->nColumn;
iColumn = (p->iCursorType - QUERY_FULLTEXT);
if( iColumn<0 || iColumn>=nColumn ){
iFirst = 0;
iLast = nColumn-1;
}else{
iFirst = iColumn;
iLast = iColumn;
}
for(i=iFirst; i<=iLast; i++){
const char *zDoc;
int nDoc;
zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1);
nDoc = sqlite3_column_bytes(p->pStmt, i+1);
snippetOffsetsOfColumn(&p->q, &p->snippet, i, zDoc, nDoc);
}
}
static void snippetOffsetText(Snippet *p){
int i;
int cnt = 0;
StringBuffer sb;
char zBuf[200];
if( p->zOffset ) return;
initStringBuffer(&sb);
for(i=0; i<p->nMatch; i++){
struct snippetMatch *pMatch = &p->aMatch[i];
zBuf[0] = ' ';
sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
append(&sb, zBuf);
cnt++;
}
p->zOffset = stringBufferData(&sb);
p->nOffset = stringBufferLength(&sb);
}
static int wordBoundary(
int iBreak,
const char *zDoc,
int nDoc,
struct snippetMatch *aMatch,
int nMatch,
int iCol
){
int i;
if( iBreak<=10 ){
return 0;
}
if( iBreak>=nDoc-10 ){
return nDoc;
}
for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){}
while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
if( i<nMatch ){
if( aMatch[i].iStart<iBreak+10 ){
return aMatch[i].iStart;
}
if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
return aMatch[i-1].iStart;
}
}
for(i=1; i<=10; i++){
if( safe_isspace(zDoc[iBreak-i]) ){
return iBreak - i + 1;
}
if( safe_isspace(zDoc[iBreak+i]) ){
return iBreak + i + 1;
}
}
return iBreak;
}
#define SNIPPET_IGNORE 0
#define SNIPPET_DESIRED 1
static void snippetText(
fulltext_cursor *pCursor,
const char *zStartMark,
const char *zEndMark,
const char *zEllipsis
){
int i, j;
struct snippetMatch *aMatch;
int nMatch;
int nDesired;
StringBuffer sb;
int tailCol;
int tailOffset;
int iCol;
int nDoc;
const char *zDoc;
int iStart, iEnd;
int tailEllipsis = 0;
int iMatch;
sqlite3_free(pCursor->snippet.zSnippet);
pCursor->snippet.zSnippet = 0;
aMatch = pCursor->snippet.aMatch;
nMatch = pCursor->snippet.nMatch;
initStringBuffer(&sb);
for(i=0; i<nMatch; i++){
aMatch[i].snStatus = SNIPPET_IGNORE;
}
nDesired = 0;
for(i=0; i<pCursor->q.nTerms; i++){
for(j=0; j<nMatch; j++){
if( aMatch[j].iTerm==i ){
aMatch[j].snStatus = SNIPPET_DESIRED;
nDesired++;
break;
}
}
}
iMatch = 0;
tailCol = -1;
tailOffset = 0;
for(i=0; i<nMatch && nDesired>0; i++){
if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
nDesired--;
iCol = aMatch[i].iCol;
zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
iStart = aMatch[i].iStart - 40;
iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
if( iStart<=10 ){
iStart = 0;
}
if( iCol==tailCol && iStart<=tailOffset+20 ){
iStart = tailOffset;
}
if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
trimWhiteSpace(&sb);
appendWhiteSpace(&sb);
append(&sb, zEllipsis);
appendWhiteSpace(&sb);
}
iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
if( iEnd>=nDoc-10 ){
iEnd = nDoc;
tailEllipsis = 0;
}else{
tailEllipsis = 1;
}
while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
while( iStart<iEnd ){
while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
&& aMatch[iMatch].iCol<=iCol ){
iMatch++;
}
if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
&& aMatch[iMatch].iCol==iCol ){
nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
iStart = aMatch[iMatch].iStart;
append(&sb, zStartMark);
nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
append(&sb, zEndMark);
iStart += aMatch[iMatch].nByte;
for(j=iMatch+1; j<nMatch; j++){
if( aMatch[j].iTerm==aMatch[iMatch].iTerm
&& aMatch[j].snStatus==SNIPPET_DESIRED ){
nDesired--;
aMatch[j].snStatus = SNIPPET_IGNORE;
}
}
}else{
nappend(&sb, &zDoc[iStart], iEnd - iStart);
iStart = iEnd;
}
}
tailCol = iCol;
tailOffset = iEnd;
}
trimWhiteSpace(&sb);
if( tailEllipsis ){
appendWhiteSpace(&sb);
append(&sb, zEllipsis);
}
pCursor->snippet.zSnippet = stringBufferData(&sb);
pCursor->snippet.nSnippet = stringBufferLength(&sb);
}
static int fulltextClose(sqlite3_vtab_cursor *pCursor){
fulltext_cursor *c = (fulltext_cursor *) pCursor;
TRACE(("FTS2 Close %p\n", c));
sqlite3_finalize(c->pStmt);
queryClear(&c->q);
snippetClear(&c->snippet);
if( c->result.nData!=0 ) dlrDestroy(&c->reader);
dataBufferDestroy(&c->result);
sqlite3_free(c);
return SQLITE_OK;
}
static int fulltextNext(sqlite3_vtab_cursor *pCursor){
fulltext_cursor *c = (fulltext_cursor *) pCursor;
int rc;
TRACE(("FTS2 Next %p\n", pCursor));
snippetClear(&c->snippet);
if( c->iCursorType < QUERY_FULLTEXT ){
rc = sqlite3_step(c->pStmt);
switch( rc ){
case SQLITE_ROW:
c->eof = 0;
return SQLITE_OK;
case SQLITE_DONE:
c->eof = 1;
return SQLITE_OK;
default:
c->eof = 1;
return rc;
}
} else {
rc = sqlite3_reset(c->pStmt);
if( rc!=SQLITE_OK ) return rc;
if( c->result.nData==0 || dlrAtEnd(&c->reader) ){
c->eof = 1;
return SQLITE_OK;
}
rc = sqlite3_bind_int64(c->pStmt, 1, dlrDocid(&c->reader));
if( rc!=SQLITE_OK ) return rc;
rc = dlrStep(&c->reader);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_step(c->pStmt);
if( rc==SQLITE_ROW ){
c->eof = 0;
return SQLITE_OK;
}
if( rc==SQLITE_DONE ) return SQLITE_CORRUPT_BKPT;
return rc;
}
}
static int termSelect(fulltext_vtab *v, int iColumn,
const char *pTerm, int nTerm, int isPrefix,
DocListType iType, DataBuffer *out);
static int docListOfTerm(
fulltext_vtab *v,
int iColumn,
QueryTerm *pQTerm,
DataBuffer *pResult
){
DataBuffer left, right, new;
int i, rc;
assert( pQTerm->nPhrase==0 || DL_DEFAULT!=DL_DOCIDS );
assert( v->nPendingData<0 );
dataBufferInit(&left, 0);
rc = termSelect(v, iColumn, pQTerm->pTerm, pQTerm->nTerm, pQTerm->isPrefix,
0<pQTerm->nPhrase ? DL_POSITIONS : DL_DOCIDS, &left);
if( rc ) return rc;
for(i=1; i<=pQTerm->nPhrase && left.nData>0; i++){
dataBufferInit(&right, 0);
rc = termSelect(v, iColumn, pQTerm[i].pTerm, pQTerm[i].nTerm,
pQTerm[i].isPrefix, DL_POSITIONS, &right);
if( rc ){
dataBufferDestroy(&left);
return rc;
}
dataBufferInit(&new, 0);
rc = docListPhraseMerge(left.pData, left.nData, right.pData, right.nData,
i<pQTerm->nPhrase ? DL_POSITIONS : DL_DOCIDS, &new);
dataBufferDestroy(&left);
dataBufferDestroy(&right);
if( rc!=SQLITE_OK ){
dataBufferDestroy(&new);
return rc;
}
left = new;
}
*pResult = left;
return rc;
}
static void queryAdd(Query *q, const char *pTerm, int nTerm){
QueryTerm *t;
++q->nTerms;
q->pTerms = sqlite3_realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0]));
if( q->pTerms==0 ){
q->nTerms = 0;
return;
}
t = &q->pTerms[q->nTerms - 1];
CLEAR(t);
t->pTerm = sqlite3_malloc(nTerm+1);
memcpy(t->pTerm, pTerm, nTerm);
t->pTerm[nTerm] = 0;
t->nTerm = nTerm;
t->isOr = q->nextIsOr;
t->isPrefix = 0;
q->nextIsOr = 0;
t->iColumn = q->nextColumn;
q->nextColumn = q->dfltColumn;
}
static int checkColumnSpecifier(
fulltext_vtab *pVtab,
const char *zToken,
int nToken
){
int i;
for(i=0; i<pVtab->nColumn; i++){
if( memcmp(pVtab->azColumn[i], zToken, nToken)==0
&& pVtab->azColumn[i][nToken]==0 ){
return i;
}
}
return -1;
}
static int tokenizeSegment(
sqlite3_tokenizer *pTokenizer,
const char *pSegment, int nSegment,
int inPhrase,
Query *pQuery
){
const sqlite3_tokenizer_module *pModule = pTokenizer->pModule;
sqlite3_tokenizer_cursor *pCursor;
int firstIndex = pQuery->nTerms;
int iCol;
int nTerm = 1;
int iEndLast = -1;
int rc = pModule->xOpen(pTokenizer, pSegment, nSegment, &pCursor);
if( rc!=SQLITE_OK ) return rc;
pCursor->pTokenizer = pTokenizer;
while( 1 ){
const char *pToken;
int nToken, iBegin, iEnd, iPos;
rc = pModule->xNext(pCursor,
&pToken, &nToken,
&iBegin, &iEnd, &iPos);
if( rc!=SQLITE_OK ) break;
if( !inPhrase &&
pSegment[iEnd]==':' &&
(iCol = checkColumnSpecifier(pQuery->pFts, pToken, nToken))>=0 ){
pQuery->nextColumn = iCol;
continue;
}
if( !inPhrase && pQuery->nTerms>0 && nToken==2
&& pSegment[iBegin]=='O' && pSegment[iBegin+1]=='R' ){
pQuery->nextIsOr = 1;
continue;
}
if( pQuery->nTerms>0 && nToken==1 && pSegment[iBegin]=='*' &&
iEndLast==iBegin){
pQuery->pTerms[pQuery->nTerms-1].isPrefix = 1;
continue;
}
iEndLast = iEnd;
queryAdd(pQuery, pToken, nToken);
if( !inPhrase && iBegin>0 && pSegment[iBegin-1]=='-' ){
pQuery->pTerms[pQuery->nTerms-1].isNot = 1;
}
if( iEnd<nSegment && pSegment[iEnd]=='*' ){
pQuery->pTerms[pQuery->nTerms-1].isPrefix = 1;
}
pQuery->pTerms[pQuery->nTerms-1].iPhrase = nTerm;
if( inPhrase ){
nTerm++;
}
}
if( inPhrase && pQuery->nTerms>firstIndex ){
pQuery->pTerms[firstIndex].nPhrase = pQuery->nTerms - firstIndex - 1;
}
return pModule->xClose(pCursor);
}
static int parseQuery(
fulltext_vtab *v,
const char *zInput,
int nInput,
int dfltColumn,
Query *pQuery
){
int iInput, inPhrase = 0;
if( zInput==0 ) nInput = 0;
if( nInput<0 ) nInput = strlen(zInput);
pQuery->nTerms = 0;
pQuery->pTerms = NULL;
pQuery->nextIsOr = 0;
pQuery->nextColumn = dfltColumn;
pQuery->dfltColumn = dfltColumn;
pQuery->pFts = v;
for(iInput=0; iInput<nInput; ++iInput){
int i;
for(i=iInput; i<nInput && zInput[i]!='"'; ++i){}
if( i>iInput ){
tokenizeSegment(v->pTokenizer, zInput+iInput, i-iInput, inPhrase,
pQuery);
}
iInput = i;
if( i<nInput ){
assert( zInput[i]=='"' );
inPhrase = !inPhrase;
}
}
if( inPhrase ){
queryClear(pQuery);
return SQLITE_ERROR;
}
return SQLITE_OK;
}
static int flushPendingTerms(fulltext_vtab *v);
static int fulltextQuery(
fulltext_vtab *v,
int iColumn,
const char *zInput,
int nInput,
DataBuffer *pResult,
Query *pQuery
){
int i, iNext, rc;
DataBuffer left, right, or, new;
int nNot = 0;
QueryTerm *aTerm;
rc = flushPendingTerms(v);
if( rc!=SQLITE_OK ) return rc;
rc = parseQuery(v, zInput, nInput, iColumn, pQuery);
if( rc!=SQLITE_OK ) return rc;
if( pQuery->nTerms==0 ){
dataBufferInit(pResult, 0);
return SQLITE_OK;
}
aTerm = pQuery->pTerms;
for(i = 0; i<pQuery->nTerms; i=iNext){
if( aTerm[i].isNot ){
nNot++;
iNext = i + aTerm[i].nPhrase+1;
continue;
}
iNext = i + aTerm[i].nPhrase + 1;
rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
if( rc ){
if( i!=nNot ) dataBufferDestroy(&left);
queryClear(pQuery);
return rc;
}
while( iNext<pQuery->nTerms && aTerm[iNext].isOr ){
rc = docListOfTerm(v, aTerm[iNext].iColumn, &aTerm[iNext], &or);
iNext += aTerm[iNext].nPhrase + 1;
if( rc ){
if( i!=nNot ) dataBufferDestroy(&left);
dataBufferDestroy(&right);
queryClear(pQuery);
return rc;
}
dataBufferInit(&new, 0);
rc = docListOrMerge(right.pData, right.nData, or.pData, or.nData, &new);
dataBufferDestroy(&right);
dataBufferDestroy(&or);
if( rc!=SQLITE_OK ){
if( i!=nNot ) dataBufferDestroy(&left);
queryClear(pQuery);
dataBufferDestroy(&new);
return rc;
}
right = new;
}
if( i==nNot ){
left = right;
}else{
dataBufferInit(&new, 0);
rc = docListAndMerge(left.pData, left.nData,
right.pData, right.nData, &new);
dataBufferDestroy(&right);
dataBufferDestroy(&left);
if( rc!=SQLITE_OK ){
queryClear(pQuery);
dataBufferDestroy(&new);
return rc;
}
left = new;
}
}
if( nNot==pQuery->nTerms ){
return SQLITE_ERROR;
}
for(i=0; i<pQuery->nTerms; i += aTerm[i].nPhrase + 1){
if( !aTerm[i].isNot ) continue;
rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
if( rc ){
queryClear(pQuery);
dataBufferDestroy(&left);
return rc;
}
dataBufferInit(&new, 0);
rc = docListExceptMerge(left.pData, left.nData,
right.pData, right.nData, &new);
dataBufferDestroy(&right);
dataBufferDestroy(&left);
if( rc!=SQLITE_OK ){
queryClear(pQuery);
dataBufferDestroy(&new);
return rc;
}
left = new;
}
*pResult = left;
return rc;
}
static int fulltextFilter(
sqlite3_vtab_cursor *pCursor,
int idxNum, const char *idxStr,
int argc, sqlite3_value **argv
){
fulltext_cursor *c = (fulltext_cursor *) pCursor;
fulltext_vtab *v = cursor_vtab(c);
int rc;
TRACE(("FTS2 Filter %p\n",pCursor));
if( c->pStmt && c->iCursorType!=idxNum ){
sqlite3_finalize(c->pStmt);
c->pStmt = NULL;
}
if( !c->pStmt ){
char *zSql = sqlite3_mprintf("select rowid, * from %%_content %s",
idxNum==QUERY_GENERIC ? "" : "where rowid=?");
rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt, zSql);
sqlite3_free(zSql);
if( rc!=SQLITE_OK ) return rc;
c->iCursorType = idxNum;
}else{
sqlite3_reset(c->pStmt);
assert( c->iCursorType==idxNum );
}
switch( idxNum ){
case QUERY_GENERIC:
break;
case QUERY_ROWID:
rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0]));
if( rc!=SQLITE_OK ) return rc;
break;
default:
{
const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
assert( idxNum<=QUERY_FULLTEXT+v->nColumn);
assert( argc==1 );
queryClear(&c->q);
if( c->result.nData!=0 ){
dlrDestroy(&c->reader);
dataBufferReset(&c->result);
}else{
dataBufferInit(&c->result, 0);
}
rc = fulltextQuery(v, idxNum-QUERY_FULLTEXT, zQuery, -1, &c->result, &c->q);
if( rc!=SQLITE_OK ) return rc;
if( c->result.nData!=0 ){
rc = dlrInit(&c->reader, DL_DOCIDS, c->result.pData, c->result.nData);
if( rc!=SQLITE_OK ) return rc;
}
break;
}
}
return fulltextNext(pCursor);
}
static int fulltextEof(sqlite3_vtab_cursor *pCursor){
fulltext_cursor *c = (fulltext_cursor *) pCursor;
return c->eof;
}
static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
sqlite3_context *pContext, int idxCol){
fulltext_cursor *c = (fulltext_cursor *) pCursor;
fulltext_vtab *v = cursor_vtab(c);
if( idxCol<v->nColumn ){
sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1);
sqlite3_result_value(pContext, pVal);
}else if( idxCol==v->nColumn ){
sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT);
}
return SQLITE_OK;
}
static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
fulltext_cursor *c = (fulltext_cursor *) pCursor;
*pRowid = sqlite3_column_int64(c->pStmt, 0);
return SQLITE_OK;
}
static int buildTerms(fulltext_vtab *v, sqlite_int64 iDocid,
const char *zText, int iColumn){
sqlite3_tokenizer *pTokenizer = v->pTokenizer;
sqlite3_tokenizer_cursor *pCursor;
const char *pToken;
int nTokenBytes;
int iStartOffset, iEndOffset, iPosition;
int rc;
rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
if( rc!=SQLITE_OK ) return rc;
pCursor->pTokenizer = pTokenizer;
while( SQLITE_OK==(rc=pTokenizer->pModule->xNext(pCursor,
&pToken, &nTokenBytes,
&iStartOffset, &iEndOffset,
&iPosition)) ){
DLCollector *p;
int nData;
if( iPosition<0 || pToken == NULL || nTokenBytes == 0 ){
rc = SQLITE_ERROR;
break;
}
p = fts2HashFind(&v->pendingTerms, pToken, nTokenBytes);
if( p==NULL ){
nData = 0;
p = dlcNew(iDocid, DL_DEFAULT);
fts2HashInsert(&v->pendingTerms, pToken, nTokenBytes, p);
v->nPendingData += sizeof(struct fts2HashElem)+sizeof(*p)+nTokenBytes;
}else{
nData = p->b.nData;
if( p->dlw.iPrevDocid!=iDocid ) dlcNext(p, iDocid);
}
if( iColumn>=0 ){
dlcAddPos(p, iColumn, iPosition, iStartOffset, iEndOffset);
}
v->nPendingData += p->b.nData-nData;
}
pTokenizer->pModule->xClose(pCursor);
if( SQLITE_DONE == rc ) return SQLITE_OK;
return rc;
}
static int insertTerms(fulltext_vtab *v, sqlite_int64 iRowid,
sqlite3_value **pValues){
int i;
for(i = 0; i < v->nColumn ; ++i){
char *zText = (char*)sqlite3_value_text(pValues[i]);
int rc = buildTerms(v, iRowid, zText, i);
if( rc!=SQLITE_OK ) return rc;
}
return SQLITE_OK;
}
static int deleteTerms(fulltext_vtab *v, sqlite_int64 iRowid){
const char **pValues;
int i, rc;
if( DL_DEFAULT==DL_DOCIDS ) return SQLITE_ERROR;
rc = content_select(v, iRowid, &pValues);
if( rc!=SQLITE_OK ) return rc;
for(i = 0 ; i < v->nColumn; ++i) {
rc = buildTerms(v, iRowid, pValues[i], -1);
if( rc!=SQLITE_OK ) break;
}
freeStringArray(v->nColumn, pValues);
return SQLITE_OK;
}
static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid);
static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestRowid,
sqlite3_value **pValues, sqlite_int64 *piRowid){
int rc;
rc = content_insert(v, pRequestRowid, pValues);
if( rc!=SQLITE_OK ) return rc;
*piRowid = sqlite3_last_insert_rowid(v->db);
rc = initPendingTerms(v, *piRowid);
if( rc!=SQLITE_OK ) return rc;
return insertTerms(v, *piRowid, pValues);
}
static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
int rc = initPendingTerms(v, iRow);
if( rc!=SQLITE_OK ) return rc;
rc = deleteTerms(v, iRow);
if( rc!=SQLITE_OK ) return rc;
return content_delete(v, iRow);
}
static int index_update(fulltext_vtab *v, sqlite_int64 iRow,
sqlite3_value **pValues){
int rc = initPendingTerms(v, iRow);
if( rc!=SQLITE_OK ) return rc;
rc = deleteTerms(v, iRow);
if( rc!=SQLITE_OK ) return rc;
rc = content_update(v, pValues, iRow);
if( rc!=SQLITE_OK ) return rc;
return insertTerms(v, iRow, pValues);
}
#define INTERIOR_MAX 2048
#define INTERIOR_MIN_TERMS 7
#if INTERIOR_MIN_TERMS<1
# error INTERIOR_MIN_TERMS must be greater than 0.
#endif
#define ROOT_MAX 1024
#if ROOT_MAX<VARINT_MAX*2
# error ROOT_MAX must have enough space for a header.
#endif
typedef struct InteriorBlock {
DataBuffer term;
DataBuffer data;
struct InteriorBlock *next;
} InteriorBlock;
static InteriorBlock *interiorBlockNew(int iHeight, sqlite_int64 iChildBlock,
const char *pTerm, int nTerm){
InteriorBlock *block = sqlite3_malloc(sizeof(InteriorBlock));
char c[VARINT_MAX+VARINT_MAX];
int n;
if( block ){
memset(block, 0, sizeof(*block));
dataBufferInit(&block->term, 0);
dataBufferReplace(&block->term, pTerm, nTerm);
n = putVarint(c, iHeight);
n += putVarint(c+n, iChildBlock);
dataBufferInit(&block->data, INTERIOR_MAX);
dataBufferReplace(&block->data, c, n);
}
return block;
}
#ifndef NDEBUG
static void interiorBlockValidate(InteriorBlock *pBlock){
const char *pData = pBlock->data.pData;
int nData = pBlock->data.nData;
int n, iDummy;
sqlite_int64 iBlockid;
assert( nData>0 );
assert( pData!=0 );
assert( pData+nData>pData );
n = getVarint32(pData, &iDummy);
assert( n>0 );
assert( iDummy>0 );
assert( n<nData );
pData += n;
nData -= n;
n = getVarint(pData, &iBlockid);
assert( n>0 );
assert( n<=nData );
pData += n;
nData -= n;
if( nData!=0 ){
n = getVarint32(pData, &iDummy);
assert( n>0 );
assert( iDummy>0 );
assert( n+iDummy>0);
assert( n+iDummy<=nData );
pData += n+iDummy;
nData -= n+iDummy;
while( nData!=0 ){
n = getVarint32(pData, &iDummy);
assert( n>0 );
assert( iDummy>=0 );
assert( n<nData );
pData += n;
nData -= n;
n = getVarint32(pData, &iDummy);
assert( n>0 );
assert( iDummy>0 );
assert( n+iDummy>0);
assert( n+iDummy<=nData );
pData += n+iDummy;
nData -= n+iDummy;
}
}
}
#define ASSERT_VALID_INTERIOR_BLOCK(x) interiorBlockValidate(x)
#else
#define ASSERT_VALID_INTERIOR_BLOCK(x) assert( 1 )
#endif
typedef struct InteriorWriter {
int iHeight;
InteriorBlock *first, *last;
struct InteriorWriter *parentWriter;
DataBuffer term;
sqlite_int64 iOpeningChildBlock;
#ifndef NDEBUG
sqlite_int64 iLastChildBlock;
#endif
} InteriorWriter;
static void interiorWriterInit(int iHeight, const char *pTerm, int nTerm,
sqlite_int64 iChildBlock,
InteriorWriter *pWriter){
InteriorBlock *block;
assert( iHeight>0 );
CLEAR(pWriter);
pWriter->iHeight = iHeight;
pWriter->iOpeningChildBlock = iChildBlock;
#ifndef NDEBUG
pWriter->iLastChildBlock = iChildBlock;
#endif
block = interiorBlockNew(iHeight, iChildBlock, pTerm, nTerm);
pWriter->last = pWriter->first = block;
ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
dataBufferInit(&pWriter->term, 0);
}
static void interiorWriterAppend(InteriorWriter *pWriter,
const char *pTerm, int nTerm,
sqlite_int64 iChildBlock){
char c[VARINT_MAX+VARINT_MAX];
int n, nPrefix = 0;
ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
if( pWriter->term.nData==0 ){
n = putVarint(c, nTerm);
}else{
while( nPrefix<pWriter->term.nData &&
pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
nPrefix++;
}
n = putVarint(c, nPrefix);
n += putVarint(c+n, nTerm-nPrefix);
}
#ifndef NDEBUG
pWriter->iLastChildBlock++;
#endif
assert( pWriter->iLastChildBlock==iChildBlock );
if( pWriter->last->data.nData+n+nTerm-nPrefix>INTERIOR_MAX &&
iChildBlock-pWriter->iOpeningChildBlock>INTERIOR_MIN_TERMS ){
pWriter->last->next = interiorBlockNew(pWriter->iHeight, iChildBlock,
pTerm, nTerm);
pWriter->last = pWriter->last->next;
pWriter->iOpeningChildBlock = iChildBlock;
dataBufferReset(&pWriter->term);
}else{
dataBufferAppend2(&pWriter->last->data, c, n,
pTerm+nPrefix, nTerm-nPrefix);
dataBufferReplace(&pWriter->term, pTerm, nTerm);
}
ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
}
static int interiorWriterDestroy(InteriorWriter *pWriter){
InteriorBlock *block = pWriter->first;
while( block!=NULL ){
InteriorBlock *b = block;
block = block->next;
dataBufferDestroy(&b->term);
dataBufferDestroy(&b->data);
sqlite3_free(b);
}
if( pWriter->parentWriter!=NULL ){
interiorWriterDestroy(pWriter->parentWriter);
sqlite3_free(pWriter->parentWriter);
}
dataBufferDestroy(&pWriter->term);
SCRAMBLE(pWriter);
return SQLITE_OK;
}
static int interiorWriterRootInfo(fulltext_vtab *v, InteriorWriter *pWriter,
char **ppRootInfo, int *pnRootInfo,
sqlite_int64 *piEndBlockid){
InteriorBlock *block = pWriter->first;
sqlite_int64 iBlockid = 0;
int rc;
if( block==pWriter->last && block->data.nData<ROOT_MAX ){
*ppRootInfo = block->data.pData;
*pnRootInfo = block->data.nData;
return SQLITE_OK;
}
ASSERT_VALID_INTERIOR_BLOCK(block);
rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
if( rc!=SQLITE_OK ) return rc;
*piEndBlockid = iBlockid;
pWriter->parentWriter = sqlite3_malloc(sizeof(*pWriter->parentWriter));
interiorWriterInit(pWriter->iHeight+1,
block->term.pData, block->term.nData,
iBlockid, pWriter->parentWriter);
for(block=block->next; block!=NULL; block=block->next){
ASSERT_VALID_INTERIOR_BLOCK(block);
rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
if( rc!=SQLITE_OK ) return rc;
*piEndBlockid = iBlockid;
interiorWriterAppend(pWriter->parentWriter,
block->term.pData, block->term.nData, iBlockid);
}
return interiorWriterRootInfo(v, pWriter->parentWriter,
ppRootInfo, pnRootInfo, piEndBlockid);
}
typedef struct InteriorReader {
const char *pData;
int nData;
DataBuffer term;
sqlite_int64 iBlockid;
} InteriorReader;
static void interiorReaderDestroy(InteriorReader *pReader){
dataBufferDestroy(&pReader->term);
SCRAMBLE(pReader);
}
static int interiorReaderInit(const char *pData, int nData,
InteriorReader *pReader){
int n, nTerm;
assert( nData>0 );
assert( pData[0]!='\0' );
CLEAR(pReader);
n = getVarintSafe(pData+1, &pReader->iBlockid, nData-1);
if( !n ) return SQLITE_CORRUPT_BKPT;
pReader->pData = pData+1+n;
pReader->nData = nData-(1+n);
if( pReader->nData==0 ){
dataBufferInit(&pReader->term, 0);
}else{
n = getVarint32Safe(pReader->pData, &nTerm, pReader->nData);
if( !n || nTerm<0 || nTerm>pReader->nData-n) return SQLITE_CORRUPT_BKPT;
dataBufferInit(&pReader->term, nTerm);
dataBufferReplace(&pReader->term, pReader->pData+n, nTerm);
pReader->pData += n+nTerm;
pReader->nData -= n+nTerm;
}
return SQLITE_OK;
}
static int interiorReaderAtEnd(InteriorReader *pReader){
return pReader->term.nData<=0;
}
static sqlite_int64 interiorReaderCurrentBlockid(InteriorReader *pReader){
return pReader->iBlockid;
}
static int interiorReaderTermBytes(InteriorReader *pReader){
assert( !interiorReaderAtEnd(pReader) );
return pReader->term.nData;
}
static const char *interiorReaderTerm(InteriorReader *pReader){
assert( !interiorReaderAtEnd(pReader) );
return pReader->term.pData;
}
static int interiorReaderStep(InteriorReader *pReader){
assert( !interiorReaderAtEnd(pReader) );
if( pReader->nData==0 ){
dataBufferReset(&pReader->term);
}else{
int n, nPrefix, nSuffix;
n = getVarint32Safe(pReader->pData, &nPrefix, pReader->nData);
if( !n ) return SQLITE_CORRUPT_BKPT;
pReader->nData -= n;
pReader->pData += n;
n = getVarint32Safe(pReader->pData, &nSuffix, pReader->nData);
if( !n ) return SQLITE_CORRUPT_BKPT;
pReader->nData -= n;
pReader->pData += n;
if( nSuffix<0 || nSuffix>pReader->nData ) return SQLITE_CORRUPT_BKPT;
if( nPrefix<0 || nPrefix>pReader->term.nData ) return SQLITE_CORRUPT_BKPT;
pReader->term.nData = nPrefix;
dataBufferAppend(&pReader->term, pReader->pData, nSuffix);
pReader->pData += nSuffix;
pReader->nData -= nSuffix;
}
pReader->iBlockid++;
return SQLITE_OK;
}
static int interiorReaderTermCmp(InteriorReader *pReader,
const char *pTerm, int nTerm, int isPrefix){
const char *pReaderTerm = interiorReaderTerm(pReader);
int nReaderTerm = interiorReaderTermBytes(pReader);
int c, n = nReaderTerm<nTerm ? nReaderTerm : nTerm;
if( n==0 ){
if( nReaderTerm>0 ) return -1;
if( nTerm>0 ) return 1;
return 0;
}
c = memcmp(pReaderTerm, pTerm, n);
if( c!=0 ) return c;
if( isPrefix && n==nTerm ) return 0;
return nReaderTerm - nTerm;
}
#define STANDALONE_MIN 1024
#define LEAF_MAX 2048
typedef struct LeafWriter {
int iLevel;
int idx;
sqlite_int64 iStartBlockid;
sqlite_int64 iEndBlockid;
DataBuffer term;
DataBuffer data;
int nTermDistinct;
InteriorWriter parentWriter;
int has_parent;
} LeafWriter;
static void leafWriterInit(int iLevel, int idx, LeafWriter *pWriter){
CLEAR(pWriter);
pWriter->iLevel = iLevel;
pWriter->idx = idx;
dataBufferInit(&pWriter->term, 32);
dataBufferInit(&pWriter->data, LEAF_MAX);
}
#ifndef NDEBUG
static void leafNodeValidate(const char *pData, int nData){
int n, iDummy;
if( nData==0 ) return;
assert( nData>0 );
assert( pData!=0 );
assert( pData+nData>pData );
n = getVarint32(pData, &iDummy);
assert( iDummy==0 );
assert( n>0 );
assert( n<nData );
pData += n;
nData -= n;
n = getVarint32(pData, &iDummy);
assert( n>0 );
assert( iDummy>0 );
assert( n+iDummy>0 );
assert( n+iDummy<nData );
pData += n+iDummy;
nData -= n+iDummy;
n = getVarint32(pData, &iDummy);
assert( n>0 );
assert( iDummy>0 );
assert( n+iDummy>0 );
assert( n+iDummy<=nData );
ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
pData += n+iDummy;
nData -= n+iDummy;
while( nData!=0 ){
n = getVarint32(pData, &iDummy);
assert( n>0 );
assert( iDummy>=0 );
assert( n<nData );
pData += n;
nData -= n;
n = getVarint32(pData, &iDummy);
assert( n>0 );
assert( iDummy>0 );
assert( n+iDummy>0 );
assert( n+iDummy<nData );
pData += n+iDummy;
nData -= n+iDummy;
n = getVarint32(pData, &iDummy);
assert( n>0 );
assert( iDummy>0 );
assert( n+iDummy>0 );
assert( n+iDummy<=nData );
ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
pData += n+iDummy;
nData -= n+iDummy;
}
}
#define ASSERT_VALID_LEAF_NODE(p, n) leafNodeValidate(p, n)
#else
#define ASSERT_VALID_LEAF_NODE(p, n) assert( 1 )
#endif
static int leafWriterInternalFlush(fulltext_vtab *v, LeafWriter *pWriter,
int iData, int nData){
sqlite_int64 iBlockid = 0;
const char *pStartingTerm;
int nStartingTerm, rc, n;
assert( nData>2 );
assert( iData>=0 );
assert( iData+nData<=pWriter->data.nData );
ASSERT_VALID_LEAF_NODE(pWriter->data.pData+iData, nData);
rc = block_insert(v, pWriter->data.pData+iData, nData, &iBlockid);
if( rc!=SQLITE_OK ) return rc;
assert( iBlockid!=0 );
n = getVarint32(pWriter->data.pData+iData+1, &nStartingTerm);
pStartingTerm = pWriter->data.pData+iData+1+n;
assert( pWriter->data.nData>iData+1+n+nStartingTerm );
assert( pWriter->nTermDistinct>0 );
assert( pWriter->nTermDistinct<=nStartingTerm );
nStartingTerm = pWriter->nTermDistinct;
if( pWriter->has_parent ){
interiorWriterAppend(&pWriter->parentWriter,
pStartingTerm, nStartingTerm, iBlockid);
}else{
interiorWriterInit(1, pStartingTerm, nStartingTerm, iBlockid,
&pWriter->parentWriter);
pWriter->has_parent = 1;
}
if( pWriter->iEndBlockid==0 ){
pWriter->iEndBlockid = pWriter->iStartBlockid = iBlockid;
}else{
pWriter->iEndBlockid++;
assert( iBlockid==pWriter->iEndBlockid );
}
return SQLITE_OK;
}
static int leafWriterFlush(fulltext_vtab *v, LeafWriter *pWriter){
int rc = leafWriterInternalFlush(v, pWriter, 0, pWriter->data.nData);
if( rc!=SQLITE_OK ) return rc;
dataBufferReset(&pWriter->data);
return SQLITE_OK;
}
static int leafWriterRootInfo(fulltext_vtab *v, LeafWriter *pWriter,
char **ppRootInfo, int *pnRootInfo,
sqlite_int64 *piEndBlockid){
if( !pWriter->has_parent && pWriter->data.nData<ROOT_MAX ){
*ppRootInfo = pWriter->data.pData;
*pnRootInfo = pWriter->data.nData;
*piEndBlockid = 0;
return SQLITE_OK;
}
if( pWriter->data.nData>0 ){
int rc = leafWriterFlush(v, pWriter);
if( rc!=SQLITE_OK ) return rc;
}
assert( pWriter->has_parent );
*piEndBlockid = pWriter->iEndBlockid;
return interiorWriterRootInfo(v, &pWriter->parentWriter,
ppRootInfo, pnRootInfo, piEndBlockid);
}
static int leafWriterFinalize(fulltext_vtab *v, LeafWriter *pWriter){
sqlite_int64 iEndBlockid;
char *pRootInfo;
int rc, nRootInfo;
rc = leafWriterRootInfo(v, pWriter, &pRootInfo, &nRootInfo, &iEndBlockid);
if( rc!=SQLITE_OK ) return rc;
if( iEndBlockid==0 && nRootInfo==0 ) return SQLITE_OK;
return segdir_set(v, pWriter->iLevel, pWriter->idx,
pWriter->iStartBlockid, pWriter->iEndBlockid,
iEndBlockid, pRootInfo, nRootInfo);
}
static void leafWriterDestroy(LeafWriter *pWriter){
if( pWriter->has_parent ) interiorWriterDestroy(&pWriter->parentWriter);
dataBufferDestroy(&pWriter->term);
dataBufferDestroy(&pWriter->data);
}
static int leafWriterEncodeTerm(LeafWriter *pWriter,
const char *pTerm, int nTerm){
char c[VARINT_MAX+VARINT_MAX];
int n, nPrefix = 0;
assert( nTerm>0 );
while( nPrefix<pWriter->term.nData &&
pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
nPrefix++;
assert( nPrefix<nTerm );
}
if( pWriter->data.nData==0 ){
n = putVarint(c, '\0');
n += putVarint(c+n, nTerm);
dataBufferAppend2(&pWriter->data, c, n, pTerm, nTerm);
}else{
n = putVarint(c, nPrefix);
n += putVarint(c+n, nTerm-nPrefix);
dataBufferAppend2(&pWriter->data, c, n, pTerm+nPrefix, nTerm-nPrefix);
}
dataBufferReplace(&pWriter->term, pTerm, nTerm);
return nPrefix+1;
}
static int leafWriterInlineFlush(fulltext_vtab *v, LeafWriter *pWriter,
const char *pTerm, int nTerm,
int iDoclistData){
char c[VARINT_MAX+VARINT_MAX];
int iData, n = putVarint(c, 0);
n += putVarint(c+n, nTerm);
assert( iDoclistData>=n+nTerm );
iData = iDoclistData-(n+nTerm);
memcpy(pWriter->data.pData+iData, c, n);
memcpy(pWriter->data.pData+iData+n, pTerm, nTerm);
return leafWriterInternalFlush(v, pWriter, iData, pWriter->data.nData-iData);
}
static int leafWriterStepMerge(fulltext_vtab *v, LeafWriter *pWriter,
const char *pTerm, int nTerm,
DLReader *pReaders, int nReaders){
char c[VARINT_MAX+VARINT_MAX];
int iTermData = pWriter->data.nData, iDoclistData;
int i, nData, n, nActualData, nActual, rc, nTermDistinct;
ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
nTermDistinct = leafWriterEncodeTerm(pWriter, pTerm, nTerm);
if( iTermData==0 ) pWriter->nTermDistinct = nTermDistinct;
iDoclistData = pWriter->data.nData;
for(i=0, nData=0; i<nReaders; i++){
nData += dlrAllDataBytes(&pReaders[i]);
}
n = putVarint(c, nData);
dataBufferAppend(&pWriter->data, c, n);
rc = docListMerge(&pWriter->data, pReaders, nReaders);
if( rc!= SQLITE_OK ) return rc;
ASSERT_VALID_DOCLIST(DL_DEFAULT,
pWriter->data.pData+iDoclistData+n,
pWriter->data.nData-iDoclistData-n, NULL);
nActualData = pWriter->data.nData-(iDoclistData+n);
nActual = putVarint(c, nActualData);
assert( nActualData<=nData );
assert( nActual<=n );
if( nTerm+nActualData>STANDALONE_MIN ){
if( iTermData>0 ){
rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
if( rc!=SQLITE_OK ) return rc;
pWriter->nTermDistinct = nTermDistinct;
}
iDoclistData += n - nActual;
memcpy(pWriter->data.pData+iDoclistData, c, nActual);
rc = leafWriterInlineFlush(v, pWriter, pTerm, nTerm, iDoclistData);
if( rc!=SQLITE_OK ) return rc;
dataBufferReset(&pWriter->data);
return rc;
}
if( nActual<n ){
memmove(pWriter->data.pData+iDoclistData+nActual,
pWriter->data.pData+iDoclistData+n,
pWriter->data.nData-(iDoclistData+n));
pWriter->data.nData -= n-nActual;
}
memcpy(pWriter->data.pData+iDoclistData, c, nActual);
if( iTermData+nTerm+nActualData>LEAF_MAX ){
rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
if( rc!=SQLITE_OK ) return rc;
pWriter->nTermDistinct = nTermDistinct;
n = putVarint(pWriter->data.pData, 0);
n += putVarint(pWriter->data.pData+n, nTerm);
memcpy(pWriter->data.pData+n, pTerm, nTerm);
n += nTerm;
assert( n<iDoclistData );
assert( 2*STANDALONE_MIN<=LEAF_MAX );
assert( n+pWriter->data.nData-iDoclistData<iDoclistData );
memcpy(pWriter->data.pData+n,
pWriter->data.pData+iDoclistData,
pWriter->data.nData-iDoclistData);
pWriter->data.nData -= iDoclistData-n;
}
ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
return SQLITE_OK;
}
static int leafWriterStep(fulltext_vtab *v, LeafWriter *pWriter,
const char *pTerm, int nTerm,
const char *pData, int nData){
int rc;
DLReader reader;
rc = dlrInit(&reader, DL_DEFAULT, pData, nData);
if( rc!=SQLITE_OK ) return rc;
rc = leafWriterStepMerge(v, pWriter, pTerm, nTerm, &reader, 1);
dlrDestroy(&reader);
return rc;
}
typedef struct LeafReader {
DataBuffer term;
const char *pData;
int nData;
} LeafReader;
static void leafReaderDestroy(LeafReader *pReader){
dataBufferDestroy(&pReader->term);
SCRAMBLE(pReader);
}
static int leafReaderAtEnd(LeafReader *pReader){
return pReader->nData<=0;
}
static int leafReaderTermBytes(LeafReader *pReader){
return pReader->term.nData;
}
static const char *leafReaderTerm(LeafReader *pReader){
assert( pReader->term.nData>0 );
return pReader->term.pData;
}
static int leafReaderDataBytes(LeafReader *pReader){
int nData;
assert( pReader->term.nData>0 );
getVarint32(pReader->pData, &nData);
return nData;
}
static const char *leafReaderData(LeafReader *pReader){
int n, nData;
assert( pReader->term.nData>0 );
n = getVarint32Safe(pReader->pData, &nData, pReader->nData);
if( !n || nData>pReader->nData-n ) return NULL;
return pReader->pData+n;
}
static int leafReaderInit(const char *pData, int nData, LeafReader *pReader){
int nTerm, n;
assert( nData>0 );
assert( pData[0]=='\0' );
CLEAR(pReader);
n = getVarint32Safe(pData+1, &nTerm, nData-1);
if( !n || nTerm<0 || nTerm>nData-1-n ) return SQLITE_CORRUPT_BKPT;
dataBufferInit(&pReader->term, nTerm);
dataBufferReplace(&pReader->term, pData+1+n, nTerm);
pReader->pData = pData+1+n+nTerm;
pReader->nData = nData-1-n-nTerm;
return SQLITE_OK;
}
static int leafReaderStep(LeafReader *pReader){
int n, nData, nPrefix, nSuffix;
assert( !leafReaderAtEnd(pReader) );
n = getVarint32Safe(pReader->pData, &nData, pReader->nData);
if( !n || nData<0 || nData>pReader->nData-n ) return SQLITE_CORRUPT_BKPT;
pReader->pData += n+nData;
pReader->nData -= n+nData;
if( !leafReaderAtEnd(pReader) ){
n = getVarint32Safe(pReader->pData, &nPrefix, pReader->nData);
if( !n ) return SQLITE_CORRUPT_BKPT;
pReader->nData -= n;
pReader->pData += n;
n = getVarint32Safe(pReader->pData, &nSuffix, pReader->nData);
if( !n ) return SQLITE_CORRUPT_BKPT;
pReader->nData -= n;
pReader->pData += n;
if( nSuffix<0 || nSuffix>pReader->nData ) return SQLITE_CORRUPT_BKPT;
if( nPrefix<0 || nPrefix>pReader->term.nData ) return SQLITE_CORRUPT_BKPT;
pReader->term.nData = nPrefix;
dataBufferAppend(&pReader->term, pReader->pData, nSuffix);
pReader->pData += nSuffix;
pReader->nData -= nSuffix;
}
return SQLITE_OK;
}
static int leafReaderTermCmp(LeafReader *pReader,
const char *pTerm, int nTerm, int isPrefix){
int c, n = pReader->term.nData<nTerm ? pReader->term.nData : nTerm;
if( n==0 ){
if( pReader->term.nData>0 ) return -1;
if(nTerm>0 ) return 1;
return 0;
}
c = memcmp(pReader->term.pData, pTerm, n);
if( c!=0 ) return c;
if( isPrefix && n==nTerm ) return 0;
return pReader->term.nData - nTerm;
}
typedef struct LeavesReader {
int idx;
sqlite3_stmt *pStmt;
int eof;
LeafReader leafReader;
DataBuffer rootData;
} LeavesReader;
static int leavesReaderTermBytes(LeavesReader *pReader){
assert( !pReader->eof );
return leafReaderTermBytes(&pReader->leafReader);
}
static const char *leavesReaderTerm(LeavesReader *pReader){
assert( !pReader->eof );
return leafReaderTerm(&pReader->leafReader);
}
static int leavesReaderDataBytes(LeavesReader *pReader){
assert( !pReader->eof );
return leafReaderDataBytes(&pReader->leafReader);
}
static const char *leavesReaderData(LeavesReader *pReader){
assert( !pReader->eof );
return leafReaderData(&pReader->leafReader);
}
static int leavesReaderAtEnd(LeavesReader *pReader){
return pReader->eof;
}
static int leavesReaderReset(LeavesReader *pReader){
return sqlite3_reset(pReader->pStmt);
}
static void leavesReaderDestroy(LeavesReader *pReader){
if( pReader->pStmt!=NULL && pReader->idx==-1 ){
sqlite3_finalize(pReader->pStmt);
}
leafReaderDestroy(&pReader->leafReader);
dataBufferDestroy(&pReader->rootData);
SCRAMBLE(pReader);
}
static int leavesReaderInit(fulltext_vtab *v,
int idx,
sqlite_int64 iStartBlockid,
sqlite_int64 iEndBlockid,
const char *pRootData, int nRootData,
LeavesReader *pReader){
CLEAR(pReader);
pReader->idx = idx;
dataBufferInit(&pReader->rootData, 0);
if( iStartBlockid==0 ){
int rc;
if( pRootData==NULL || nRootData<1 || pRootData[0]!='\0' ){
return SQLITE_CORRUPT_BKPT;
}
dataBufferReplace(&pReader->rootData, pRootData, nRootData);
rc = leafReaderInit(pReader->rootData.pData, pReader->rootData.nData,
&pReader->leafReader);
if( rc!=SQLITE_OK ){
dataBufferDestroy(&pReader->rootData);
return rc;
}
}else{
sqlite3_stmt *s;
int rc = sql_get_leaf_statement(v, idx, &s);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_int64(s, 1, iStartBlockid);
if( rc!=SQLITE_OK ) goto err;
rc = sqlite3_bind_int64(s, 2, iEndBlockid);
if( rc!=SQLITE_OK ) goto err;
rc = sqlite3_step(s);
if( rc==SQLITE_DONE ){
rc = SQLITE_CORRUPT_BKPT;
goto err;
}
if( rc!=SQLITE_ROW ) goto err;
rc = SQLITE_OK;
if( sqlite3_column_type(s, 0)!=SQLITE_BLOB ){
rc = SQLITE_CORRUPT_BKPT;
}else{
const char *pLeafData = sqlite3_column_blob(s, 0);
int nLeafData = sqlite3_column_bytes(s, 0);
if( pLeafData==NULL || nLeafData<1 || pLeafData[0]!='\0' ){
rc = SQLITE_CORRUPT_BKPT;
}else{
rc = leafReaderInit(pLeafData, nLeafData, &pReader->leafReader);
}
}
err:
if( rc!=SQLITE_OK ){
if( idx==-1 ){
sqlite3_finalize(s);
}else{
sqlite3_reset(s);
}
return rc;
}
pReader->pStmt = s;
}
return SQLITE_OK;
}
static int leavesReaderStep(fulltext_vtab *v, LeavesReader *pReader){
int rc;
assert( !leavesReaderAtEnd(pReader) );
rc = leafReaderStep(&pReader->leafReader);
if( rc!=SQLITE_OK ) return rc;
if( leafReaderAtEnd(&pReader->leafReader) ){
if( pReader->rootData.pData ){
pReader->eof = 1;
return SQLITE_OK;
}
rc = sqlite3_step(pReader->pStmt);
if( rc!=SQLITE_ROW ){
pReader->eof = 1;
return rc==SQLITE_DONE ? SQLITE_OK : rc;
}
if( sqlite3_column_type(pReader->pStmt, 0)!=SQLITE_BLOB ){
return SQLITE_CORRUPT_BKPT;
}else{
LeafReader tmp;
const char *pLeafData = sqlite3_column_blob(pReader->pStmt, 0);
int nLeafData = sqlite3_column_bytes(pReader->pStmt, 0);
if( pLeafData==NULL || nLeafData<1 || pLeafData[0]!='\0' ){
return SQLITE_CORRUPT_BKPT;
}
rc = leafReaderInit(pLeafData, nLeafData, &tmp);
if( rc!=SQLITE_OK ) return rc;
leafReaderDestroy(&pReader->leafReader);
pReader->leafReader = tmp;
}
}
return SQLITE_OK;
}
static int leavesReaderTermCmp(LeavesReader *lr1, LeavesReader *lr2){
if( leavesReaderAtEnd(lr1) ){
if( leavesReaderAtEnd(lr2) ) return 0;
return 1;
}
if( leavesReaderAtEnd(lr2) ) return -1;
return leafReaderTermCmp(&lr1->leafReader,
leavesReaderTerm(lr2), leavesReaderTermBytes(lr2),
0);
}
static int leavesReaderCmp(LeavesReader *lr1, LeavesReader *lr2){
int c = leavesReaderTermCmp(lr1, lr2);
if( c!=0 ) return c;
return lr1->idx-lr2->idx;
}
static void leavesReaderReorder(LeavesReader *pLr, int nLr){
while( nLr>1 && leavesReaderCmp(pLr, pLr+1)>0 ){
LeavesReader tmp = pLr[0];
pLr[0] = pLr[1];
pLr[1] = tmp;
nLr--;
pLr++;
}
}
static int leavesReadersInit(fulltext_vtab *v, int iLevel,
LeavesReader *pReaders, int *piReaders){
sqlite3_stmt *s;
int i, rc = sql_get_statement(v, SEGDIR_SELECT_LEVEL_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_int(s, 1, iLevel);
if( rc!=SQLITE_OK ) return rc;
i = 0;
while( (rc = sqlite3_step(s))==SQLITE_ROW ){
sqlite_int64 iStart = sqlite3_column_int64(s, 0);
sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
const char *pRootData = sqlite3_column_blob(s, 2);
int nRootData = sqlite3_column_bytes(s, 2);
sqlite_int64 iIndex = sqlite3_column_int64(s, 3);
if( sqlite3_column_type(s, 0)!=SQLITE_INTEGER ||
sqlite3_column_type(s, 1)!=SQLITE_INTEGER ||
sqlite3_column_type(s, 2)!=SQLITE_BLOB ||
i!=iIndex ||
i>=MERGE_COUNT ){
rc = SQLITE_CORRUPT_BKPT;
break;
}
rc = leavesReaderInit(v, i, iStart, iEnd, pRootData, nRootData,
&pReaders[i]);
if( rc!=SQLITE_OK ) break;
i++;
}
if( rc!=SQLITE_DONE ){
while( i-->0 ){
leavesReaderDestroy(&pReaders[i]);
}
sqlite3_reset(s);
return rc;
}
*piReaders = i;
while( i-- ){
leavesReaderReorder(pReaders+i, *piReaders-i);
}
return SQLITE_OK;
}
static int leavesReadersMerge(fulltext_vtab *v,
LeavesReader *pReaders, int nReaders,
LeafWriter *pWriter){
DLReader dlReaders[MERGE_COUNT];
const char *pTerm = leavesReaderTerm(pReaders);
int i, nTerm = leavesReaderTermBytes(pReaders);
int rc;
assert( nReaders<=MERGE_COUNT );
for(i=0; i<nReaders; i++){
const char *pData = leavesReaderData(pReaders+i);
if( pData==NULL ){
rc = SQLITE_CORRUPT_BKPT;
break;
}
rc = dlrInit(&dlReaders[i], DL_DEFAULT,
pData,
leavesReaderDataBytes(pReaders+i));
if( rc!=SQLITE_OK ) break;
}
if( rc!=SQLITE_OK ){
while( i-->0 ){
dlrDestroy(&dlReaders[i]);
}
return rc;
}
return leafWriterStepMerge(v, pWriter, pTerm, nTerm, dlReaders, nReaders);
}
static int segmentMerge(fulltext_vtab *v, int iLevel);
static int segdirNextIndex(fulltext_vtab *v, int iLevel, int *pidx){
int rc = segdir_max_index(v, iLevel, pidx);
if( rc==SQLITE_DONE ){
*pidx = 0;
}else if( rc==SQLITE_ROW ){
if( *pidx==(MERGE_COUNT-1) ){
rc = segmentMerge(v, iLevel);
if( rc!=SQLITE_OK ) return rc;
*pidx = 0;
}else{
(*pidx)++;
}
}else{
return rc;
}
return SQLITE_OK;
}
static int segmentMerge(fulltext_vtab *v, int iLevel){
LeafWriter writer;
LeavesReader lrs[MERGE_COUNT];
int i, rc, idx = 0;
rc = segdirNextIndex(v, iLevel+1, &idx);
if( rc!=SQLITE_OK ) return rc;
memset(&lrs, '\0', sizeof(lrs));
rc = leavesReadersInit(v, iLevel, lrs, &i);
if( rc!=SQLITE_OK ) return rc;
leafWriterInit(iLevel+1, idx, &writer);
if( i!=MERGE_COUNT ){
rc = SQLITE_CORRUPT_BKPT;
goto err;
}
while( !leavesReaderAtEnd(lrs) ){
for(i=1; i<MERGE_COUNT && !leavesReaderAtEnd(lrs+i); i++){
if( 0!=leavesReaderTermCmp(lrs, lrs+i) ) break;
}
rc = leavesReadersMerge(v, lrs, i, &writer);
if( rc!=SQLITE_OK ) goto err;
while( i-->0 ){
rc = leavesReaderStep(v, lrs+i);
if( rc!=SQLITE_OK ) goto err;
leavesReaderReorder(lrs+i, MERGE_COUNT-i);
}
}
for(i=0; i<MERGE_COUNT; i++){
leavesReaderDestroy(&lrs[i]);
}
rc = leafWriterFinalize(v, &writer);
leafWriterDestroy(&writer);
if( rc!=SQLITE_OK ) return rc;
return segdir_delete(v, iLevel);
err:
for(i=0; i<MERGE_COUNT; i++){
leavesReaderDestroy(&lrs[i]);
}
leafWriterDestroy(&writer);
return rc;
}
static int docListAccumulateUnion(DataBuffer *acc,
const char *pData, int nData) {
DataBuffer tmp = *acc;
int rc;
dataBufferInit(acc, tmp.nData+nData);
rc = docListUnion(tmp.pData, tmp.nData, pData, nData, acc);
dataBufferDestroy(&tmp);
return rc;
}
static int loadSegmentLeavesInt(fulltext_vtab *v, LeavesReader *pReader,
const char *pTerm, int nTerm, int isPrefix,
DataBuffer *out){
DataBuffer *pBuffers = NULL;
int nBuffers = 0, nMaxBuffers = 0, rc;
assert( nTerm>0 );
for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader);
rc=leavesReaderStep(v, pReader)){
int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix);
if( c>0 ) break;
if( c==0 ){
int iBuffer, nData;
const char *pData = leavesReaderData(pReader);
if( pData==NULL ){
rc = SQLITE_CORRUPT_BKPT;
break;
}
nData = leavesReaderDataBytes(pReader);
for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
if( 0==pBuffers[iBuffer].nData ) break;
}
if( iBuffer==nBuffers ){
if( nBuffers==nMaxBuffers ){
DataBuffer *p;
nMaxBuffers += 20;
p = sqlite3_malloc(nMaxBuffers*sizeof(*pBuffers));
if( p==NULL ){
rc = SQLITE_NOMEM;
break;
}
if( nBuffers>0 ){
assert(pBuffers!=NULL);
memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers));
sqlite3_free(pBuffers);
}
pBuffers = p;
}
dataBufferInit(&(pBuffers[nBuffers]), 0);
nBuffers++;
}
assert(iBuffer<nBuffers && pBuffers[iBuffer].nData==0);
if( iBuffer==0 ){
dataBufferReplace(&(pBuffers[0]), pData, nData);
}else{
DataBuffer *pAcc = &(pBuffers[iBuffer]);
DataBuffer *p = &(pBuffers[0]);
dataBufferSwap(p, pAcc);
rc = docListAccumulateUnion(pAcc, pData, nData);
if( rc!=SQLITE_OK ) goto err;
for(++p; p<pAcc; ++p){
rc = docListAccumulateUnion(pAcc, p->pData, p->nData);
if( rc!=SQLITE_OK ) goto err;
if( p->nCapacity<1024 ){
dataBufferReset(p);
}else{
dataBufferDestroy(p);
dataBufferInit(p, 0);
}
}
}
}
}
if( rc==SQLITE_OK && nBuffers>0 ){
int iBuffer;
for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
if( pBuffers[iBuffer].nData>0 ){
if( out->nData==0 ){
dataBufferSwap(out, &(pBuffers[iBuffer]));
}else{
rc = docListAccumulateUnion(out, pBuffers[iBuffer].pData,
pBuffers[iBuffer].nData);
if( rc!=SQLITE_OK ) break;
}
}
}
}
err:
while( nBuffers-- ){
dataBufferDestroy(&(pBuffers[nBuffers]));
}
if( pBuffers!=NULL ) sqlite3_free(pBuffers);
return rc;
}
static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData,
const char *pTerm, int nTerm, int isPrefix,
DataBuffer *out){
LeavesReader reader;
int rc;
assert( nData>1 );
assert( *pData=='\0' );
rc = leavesReaderInit(v, 0, 0, 0, pData, nData, &reader);
if( rc!=SQLITE_OK ) return rc;
rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
leavesReaderReset(&reader);
leavesReaderDestroy(&reader);
return rc;
}
static int loadSegmentLeaves(fulltext_vtab *v,
sqlite_int64 iStartLeaf, sqlite_int64 iEndLeaf,
const char *pTerm, int nTerm, int isPrefix,
DataBuffer *out){
int rc;
LeavesReader reader;
assert( iStartLeaf<=iEndLeaf );
rc = leavesReaderInit(v, 0, iStartLeaf, iEndLeaf, NULL, 0, &reader);
if( rc!=SQLITE_OK ) return rc;
rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
leavesReaderReset(&reader);
leavesReaderDestroy(&reader);
return rc;
}
static int getChildrenContaining(const char *pData, int nData,
const char *pTerm, int nTerm, int isPrefix,
sqlite_int64 *piStartChild,
sqlite_int64 *piEndChild){
InteriorReader reader;
int rc;
assert( nData>1 );
assert( *pData!='\0' );
rc = interiorReaderInit(pData, nData, &reader);
if( rc!=SQLITE_OK ) return rc;
while( !interiorReaderAtEnd(&reader) ){
if( interiorReaderTermCmp(&reader, pTerm, nTerm, 0)>0 ) break;
rc = interiorReaderStep(&reader);
if( rc!=SQLITE_OK ){
interiorReaderDestroy(&reader);
return rc;
}
}
*piStartChild = interiorReaderCurrentBlockid(&reader);
while( !interiorReaderAtEnd(&reader) ){
if( interiorReaderTermCmp(&reader, pTerm, nTerm, isPrefix)>0 ) break;
rc = interiorReaderStep(&reader);
if( rc!=SQLITE_OK ){
interiorReaderDestroy(&reader);
return rc;
}
}
*piEndChild = interiorReaderCurrentBlockid(&reader);
interiorReaderDestroy(&reader);
assert( *piEndChild>=*piStartChild );
assert( isPrefix || *piStartChild==*piEndChild );
return rc;
}
static int loadAndGetChildrenContaining(
fulltext_vtab *v,
sqlite_int64 iBlockid,
const char *pTerm, int nTerm, int isPrefix,
sqlite_int64 *piStartChild, sqlite_int64 *piEndChild
){
sqlite3_stmt *s = NULL;
int rc;
assert( iBlockid!=0 );
assert( pTerm!=NULL );
assert( nTerm!=0 );
assert( piStartChild!=NULL );
assert( piEndChild!=NULL );
rc = sql_get_statement(v, BLOCK_SELECT_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_bind_int64(s, 1, iBlockid);
if( rc!=SQLITE_OK ) return rc;
rc = sqlite3_step(s);
if( rc==SQLITE_DONE ) return SQLITE_CORRUPT_BKPT;
if( rc!=SQLITE_ROW ) return rc;
if( sqlite3_column_type(s, 0)!=SQLITE_BLOB ){
sqlite3_reset(s);
return SQLITE_CORRUPT_BKPT;
}else{
const char *pData = sqlite3_column_blob(s, 0);
int nData = sqlite3_column_bytes(s, 0);
if( pData==NULL || nData<1 || pData[0]=='\0' ){
sqlite3_reset(s);
return SQLITE_CORRUPT_BKPT;
}
rc = getChildrenContaining(pData, nData, pTerm, nTerm,
isPrefix, piStartChild, piEndChild);
if( rc!=SQLITE_OK ){
sqlite3_reset(s);
return rc;
}
}
rc = sqlite3_step(s);
if( rc==SQLITE_ROW ) return SQLITE_ERROR;
if( rc!=SQLITE_DONE ) return rc;
return SQLITE_OK;
}
static int loadSegmentInt(fulltext_vtab *v, const char *pData, int nData,
sqlite_int64 iLeavesEnd,
const char *pTerm, int nTerm, int isPrefix,
DataBuffer *out){
if( *pData=='\0' ){
return loadSegmentLeaf(v, pData, nData, pTerm, nTerm, isPrefix, out);
}else{
int rc;
sqlite_int64 iStartChild, iEndChild;
rc = getChildrenContaining(pData, nData, pTerm, nTerm, isPrefix,
&iStartChild, &iEndChild);
if( rc!=SQLITE_OK ) return rc;
while( iStartChild>iLeavesEnd ){
sqlite_int64 iNextStart, iNextEnd;
rc = loadAndGetChildrenContaining(v, iStartChild, pTerm, nTerm, isPrefix,
&iNextStart, &iNextEnd);
if( rc!=SQLITE_OK ) return rc;
if( iStartChild!=iEndChild ){
sqlite_int64 iDummy;
rc = loadAndGetChildrenContaining(v, iEndChild, pTerm, nTerm, isPrefix,
&iDummy, &iNextEnd);
if( rc!=SQLITE_OK ) return rc;
}
assert( iNextStart<=iNextEnd );
iStartChild = iNextStart;
iEndChild = iNextEnd;
}
assert( iStartChild<=iLeavesEnd );
assert( iEndChild<=iLeavesEnd );
return loadSegmentLeaves(v, iStartChild, iEndChild,
pTerm, nTerm, isPrefix, out);
}
}
static int loadSegment(fulltext_vtab *v, const char *pData, int nData,
sqlite_int64 iLeavesEnd,
const char *pTerm, int nTerm, int isPrefix,
DataBuffer *out){
DataBuffer result;
int rc;
if( pData==NULL || nData<1 ) return SQLITE_CORRUPT_BKPT;
assert( v->nPendingData<0 );
dataBufferInit(&result, 0);
rc = loadSegmentInt(v, pData, nData, iLeavesEnd,
pTerm, nTerm, isPrefix, &result);
if( rc==SQLITE_OK && result.nData>0 ){
if( out->nData==0 ){
DataBuffer tmp = *out;
*out = result;
result = tmp;
}else{
DataBuffer merged;
DLReader readers[2];
rc = dlrInit(&readers[0], DL_DEFAULT, out->pData, out->nData);
if( rc==SQLITE_OK ){
rc = dlrInit(&readers[1], DL_DEFAULT, result.pData, result.nData);
if( rc==SQLITE_OK ){
dataBufferInit(&merged, out->nData+result.nData);
rc = docListMerge(&merged, readers, 2);
dataBufferDestroy(out);
*out = merged;
dlrDestroy(&readers[1]);
}
dlrDestroy(&readers[0]);
}
}
}
dataBufferDestroy(&result);
return rc;
}
static int termSelect(fulltext_vtab *v, int iColumn,
const char *pTerm, int nTerm, int isPrefix,
DocListType iType, DataBuffer *out){
DataBuffer doclist;
sqlite3_stmt *s;
int rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
if( rc!=SQLITE_OK ) return rc;
assert( v->nPendingData<0 );
dataBufferInit(&doclist, 0);
while( (rc = sqlite3_step(s))==SQLITE_ROW ){
const char *pData = sqlite3_column_blob(s, 2);
const int nData = sqlite3_column_bytes(s, 2);
const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
if( sqlite3_column_type(s, 1)!=SQLITE_INTEGER ||
sqlite3_column_type(s, 2)!=SQLITE_BLOB ){
rc = SQLITE_CORRUPT_BKPT;
goto err;
}
rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix,
&doclist);
if( rc!=SQLITE_OK ) goto err;
}
if( rc==SQLITE_DONE ){
rc = SQLITE_OK;
if( doclist.nData!=0 ){
if( iColumn==v->nColumn) iColumn = -1;
rc = docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
iColumn, iType, out);
}
}
err:
sqlite3_reset(s);
dataBufferDestroy(&doclist);
return rc;
}
typedef struct TermData {
const char *pTerm;
int nTerm;
DLCollector *pCollector;
} TermData;
static int termDataCmp(const void *av, const void *bv){
const TermData *a = (const TermData *)av;
const TermData *b = (const TermData *)bv;
int n = a->nTerm<b->nTerm ? a->nTerm : b->nTerm;
int c = memcmp(a->pTerm, b->pTerm, n);
if( c!=0 ) return c;
return a->nTerm-b->nTerm;
}
static int writeZeroSegment(fulltext_vtab *v, fts2Hash *pTerms){
fts2HashElem *e;
int idx, rc, i, n;
TermData *pData;
LeafWriter writer;
DataBuffer dl;
rc = segdirNextIndex(v, 0, &idx);
if( rc!=SQLITE_OK ) return rc;
n = fts2HashCount(pTerms);
pData = sqlite3_malloc(n*sizeof(TermData));
for(i = 0, e = fts2HashFirst(pTerms); e; i++, e = fts2HashNext(e)){
assert( i<n );
pData[i].pTerm = fts2HashKey(e);
pData[i].nTerm = fts2HashKeysize(e);
pData[i].pCollector = fts2HashData(e);
}
assert( i==n );
if( n>1 ) qsort(pData, n, sizeof(*pData), termDataCmp);
leafWriterInit(0, idx, &writer);
dataBufferInit(&dl, 0);
for(i=0; i<n; i++){
dataBufferReset(&dl);
dlcAddDoclist(pData[i].pCollector, &dl);
rc = leafWriterStep(v, &writer,
pData[i].pTerm, pData[i].nTerm, dl.pData, dl.nData);
if( rc!=SQLITE_OK ) goto err;
}
rc = leafWriterFinalize(v, &writer);
err:
dataBufferDestroy(&dl);
sqlite3_free(pData);
leafWriterDestroy(&writer);
return rc;
}
static int clearPendingTerms(fulltext_vtab *v){
if( v->nPendingData>=0 ){
fts2HashElem *e;
for(e=fts2HashFirst(&v->pendingTerms); e; e=fts2HashNext(e)){
dlcDelete(fts2HashData(e));
}
fts2HashClear(&v->pendingTerms);
v->nPendingData = -1;
}
return SQLITE_OK;
}
static int flushPendingTerms(fulltext_vtab *v){
if( v->nPendingData>=0 ){
int rc = writeZeroSegment(v, &v->pendingTerms);
if( rc==SQLITE_OK ) clearPendingTerms(v);
return rc;
}
return SQLITE_OK;
}
static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid){
if( iDocid<=v->iPrevDocid || v->nPendingData>kPendingThreshold ){
int rc = flushPendingTerms(v);
if( rc!=SQLITE_OK ) return rc;
}
if( v->nPendingData<0 ){
fts2HashInit(&v->pendingTerms, FTS2_HASH_STRING, 1);
v->nPendingData = 0;
}
v->iPrevDocid = iDocid;
return SQLITE_OK;
}
static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
sqlite_int64 *pRowid){
fulltext_vtab *v = (fulltext_vtab *) pVtab;
int rc;
TRACE(("FTS2 Update %p\n", pVtab));
if( nArg<2 ){
rc = index_delete(v, sqlite3_value_int64(ppArg[0]));
if( rc==SQLITE_OK ){
rc = content_exists(v);
if( rc==SQLITE_ROW ){
rc = SQLITE_OK;
}else if( rc==SQLITE_DONE ){
rc = clearPendingTerms(v);
if( rc==SQLITE_OK ){
rc = segdir_delete_all(v);
}
}
}
} else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]);
if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER ||
sqlite3_value_int64(ppArg[1]) != rowid ){
rc = SQLITE_ERROR;
} else {
assert( nArg==2+v->nColumn+1);
rc = index_update(v, rowid, &ppArg[2]);
}
} else {
assert( nArg==2+v->nColumn+1);
rc = index_insert(v, ppArg[1], &ppArg[2], pRowid);
}
return rc;
}
static int fulltextSync(sqlite3_vtab *pVtab){
TRACE(("FTS2 xSync()\n"));
return flushPendingTerms((fulltext_vtab *)pVtab);
}
static int fulltextBegin(sqlite3_vtab *pVtab){
fulltext_vtab *v = (fulltext_vtab *) pVtab;
TRACE(("FTS2 xBegin()\n"));
assert( v->nPendingData<0 );
return clearPendingTerms(v);
}
static int fulltextCommit(sqlite3_vtab *pVtab){
fulltext_vtab *v = (fulltext_vtab *) pVtab;
TRACE(("FTS2 xCommit()\n"));
assert( v->nPendingData<0 );
return clearPendingTerms(v);
}
static int fulltextRollback(sqlite3_vtab *pVtab){
TRACE(("FTS2 xRollback()\n"));
return clearPendingTerms((fulltext_vtab *)pVtab);
}
static void snippetFunc(
sqlite3_context *pContext,
int argc,
sqlite3_value **argv
){
fulltext_cursor *pCursor;
if( argc<1 ) return;
if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1);
}else{
const char *zStart = "<b>";
const char *zEnd = "</b>";
const char *zEllipsis = "<b>...</b>";
memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
if( argc>=2 ){
zStart = (const char*)sqlite3_value_text(argv[1]);
if( argc>=3 ){
zEnd = (const char*)sqlite3_value_text(argv[2]);
if( argc>=4 ){
zEllipsis = (const char*)sqlite3_value_text(argv[3]);
}
}
}
snippetAllOffsets(pCursor);
snippetText(pCursor, zStart, zEnd, zEllipsis);
sqlite3_result_text(pContext, pCursor->snippet.zSnippet,
pCursor->snippet.nSnippet, SQLITE_STATIC);
}
}
static void snippetOffsetsFunc(
sqlite3_context *pContext,
int argc,
sqlite3_value **argv
){
fulltext_cursor *pCursor;
if( argc<1 ) return;
if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
sqlite3_result_error(pContext, "illegal first argument to offsets",-1);
}else{
memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
snippetAllOffsets(pCursor);
snippetOffsetText(&pCursor->snippet);
sqlite3_result_text(pContext,
pCursor->snippet.zOffset, pCursor->snippet.nOffset,
SQLITE_STATIC);
}
}
typedef struct OptLeavesReader {
int segment;
LeavesReader reader;
} OptLeavesReader;
static int optLeavesReaderAtEnd(OptLeavesReader *pReader){
return leavesReaderAtEnd(&pReader->reader);
}
static int optLeavesReaderTermBytes(OptLeavesReader *pReader){
return leavesReaderTermBytes(&pReader->reader);
}
static const char *optLeavesReaderData(OptLeavesReader *pReader){
return leavesReaderData(&pReader->reader);
}
static int optLeavesReaderDataBytes(OptLeavesReader *pReader){
return leavesReaderDataBytes(&pReader->reader);
}
static const char *optLeavesReaderTerm(OptLeavesReader *pReader){
return leavesReaderTerm(&pReader->reader);
}
static int optLeavesReaderStep(fulltext_vtab *v, OptLeavesReader *pReader){
return leavesReaderStep(v, &pReader->reader);
}
static int optLeavesReaderTermCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
return leavesReaderTermCmp(&lr1->reader, &lr2->reader);
}
static int optLeavesReaderCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
int c = optLeavesReaderTermCmp(lr1, lr2);
if( c!=0 ) return c;
return lr1->segment-lr2->segment;
}
static void optLeavesReaderReorder(OptLeavesReader *pLr, int nLr){
while( nLr>1 && optLeavesReaderCmp(pLr, pLr+1)>0 ){
OptLeavesReader tmp = pLr[0];
pLr[0] = pLr[1];
pLr[1] = tmp;
nLr--;
pLr++;
}
}
static int optimizeInternal(fulltext_vtab *v,
OptLeavesReader *readers, int nReaders,
LeafWriter *pWriter){
int i, rc = SQLITE_OK;
DataBuffer doclist, merged, tmp;
const char *pData;
i = nReaders;
while( i-- > 0 ){
optLeavesReaderReorder(&readers[i], nReaders-i);
}
dataBufferInit(&doclist, LEAF_MAX);
dataBufferInit(&merged, LEAF_MAX);
while( !optLeavesReaderAtEnd(&readers[0]) ){
for(i=1; i<nReaders && !optLeavesReaderAtEnd(&readers[i]); i++){
if( 0!=optLeavesReaderTermCmp(&readers[0], &readers[i]) ) break;
}
pData = optLeavesReaderData(&readers[0]);
if( pData==NULL ){
rc = SQLITE_CORRUPT_BKPT;
break;
}
if( i==1 ){
dataBufferReset(&merged);
rc = docListTrim(DL_DEFAULT,
pData,
optLeavesReaderDataBytes(&readers[0]),
-1, DL_DEFAULT, &merged);
if( rc!= SQLITE_OK ) break;
}else{
DLReader dlReaders[MERGE_COUNT];
int iReader, nReaders;
rc = dlrInit(&dlReaders[0], DL_DEFAULT,
pData,
optLeavesReaderDataBytes(&readers[0]));
if( rc!=SQLITE_OK ) break;
iReader = 1;
assert( iReader<i );
while( iReader<i ){
for( nReaders=1; iReader<i && nReaders<MERGE_COUNT;
iReader++, nReaders++ ){
pData = optLeavesReaderData(&readers[iReader]);
if( pData == NULL ){
rc = SQLITE_CORRUPT_BKPT;
break;
}
rc = dlrInit(&dlReaders[nReaders], DL_DEFAULT,
pData,
optLeavesReaderDataBytes(&readers[iReader]));
if( rc != SQLITE_OK ) break;
}
if( rc==SQLITE_OK ){
dataBufferReset(&merged);
rc = docListMerge(&merged, dlReaders, nReaders);
tmp = merged;
merged = doclist;
doclist = tmp;
}
while( nReaders-- > 0 ){
dlrDestroy(&dlReaders[nReaders]);
}
if( rc!=SQLITE_OK ) goto err;
rc = dlrInit(&dlReaders[0], DL_DEFAULT, doclist.pData, doclist.nData);
if( rc!=SQLITE_OK ) goto err;
}
dlrDestroy(&dlReaders[0]);
dataBufferReset(&merged);
rc = docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
-1, DL_DEFAULT, &merged);
if( rc!=SQLITE_OK ) goto err;
}
if( merged.nData>0 ){
rc = leafWriterStep(v, pWriter,
optLeavesReaderTerm(&readers[0]),
optLeavesReaderTermBytes(&readers[0]),
merged.pData, merged.nData);
if( rc!=SQLITE_OK ) goto err;
}
while( i-- > 0 ){
rc = optLeavesReaderStep(v, &readers[i]);
if( rc!=SQLITE_OK ) goto err;
optLeavesReaderReorder(&readers[i], nReaders-i);
}
}
err:
dataBufferDestroy(&doclist);
dataBufferDestroy(&merged);
return rc;
}
static void optimizeFunc(sqlite3_context *pContext,
int argc, sqlite3_value **argv){
fulltext_cursor *pCursor;
if( argc>1 ){
sqlite3_result_error(pContext, "excess arguments to optimize()",-1);
}else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
sqlite3_result_error(pContext, "illegal first argument to optimize",-1);
}else{
fulltext_vtab *v;
int i, rc, iMaxLevel;
OptLeavesReader *readers;
int nReaders;
LeafWriter writer;
sqlite3_stmt *s;
memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
v = cursor_vtab(pCursor);
rc = flushPendingTerms(v);
if( rc!=SQLITE_OK ) goto err;
rc = segdir_count(v, &nReaders, &iMaxLevel);
if( rc!=SQLITE_OK ) goto err;
if( nReaders==0 || nReaders==1 ){
sqlite3_result_text(pContext, "Index already optimal", -1,
SQLITE_STATIC);
return;
}
rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
if( rc!=SQLITE_OK ) goto err;
readers = sqlite3_malloc(nReaders*sizeof(readers[0]));
if( readers==NULL ) goto err;
leafWriterInit(iMaxLevel, 0, &writer);
i = 0;
while( (rc = sqlite3_step(s))==SQLITE_ROW ){
sqlite_int64 iStart = sqlite3_column_int64(s, 0);
sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
const char *pRootData = sqlite3_column_blob(s, 2);
int nRootData = sqlite3_column_bytes(s, 2);
if( sqlite3_column_type(s, 0)!=SQLITE_INTEGER ||
sqlite3_column_type(s, 1)!=SQLITE_INTEGER ||
sqlite3_column_type(s, 2)!=SQLITE_BLOB ){
rc = SQLITE_CORRUPT_BKPT;
break;
}
assert( i<nReaders );
rc = leavesReaderInit(v, -1, iStart, iEnd, pRootData, nRootData,
&readers[i].reader);
if( rc!=SQLITE_OK ) break;
readers[i].segment = i;
i++;
}
if( rc==SQLITE_DONE ){
assert( i==nReaders );
rc = optimizeInternal(v, readers, nReaders, &writer);
}else{
sqlite3_reset(s);
}
while( i-- > 0 ){
leavesReaderDestroy(&readers[i].reader);
}
sqlite3_free(readers);
if( rc==SQLITE_OK ){
for( i=0; i<=iMaxLevel; i++ ){
rc = segdir_delete(v, i);
if( rc!=SQLITE_OK ) break;
}
if( rc==SQLITE_OK ) rc = leafWriterFinalize(v, &writer);
}
leafWriterDestroy(&writer);
if( rc!=SQLITE_OK ) goto err;
sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
return;
err:
{
char buf[512];
sqlite3_snprintf(sizeof(buf), buf, "Error in optimize: %s",
sqlite3_errmsg(sqlite3_context_db_handle(pContext)));
sqlite3_result_error(pContext, buf, -1);
}
}
}
#ifdef SQLITE_TEST
static void generateError(sqlite3_context *pContext,
const char *prefix, const char *msg){
char buf[512];
if( msg==NULL ) msg = sqlite3_errmsg(sqlite3_context_db_handle(pContext));
sqlite3_snprintf(sizeof(buf), buf, "%s: %s", prefix, msg);
sqlite3_result_error(pContext, buf, -1);
}
static int collectSegmentTerms(fulltext_vtab *v, sqlite3_stmt *s,
fts2Hash *pTerms){
const sqlite_int64 iStartBlockid = sqlite3_column_int64(s, 0);
const sqlite_int64 iEndBlockid = sqlite3_column_int64(s, 1);
const char *pRootData = sqlite3_column_blob(s, 2);
const int nRootData = sqlite3_column_bytes(s, 2);
int rc;
LeavesReader reader;
if( sqlite3_column_type(s, 0)!=SQLITE_INTEGER ||
sqlite3_column_type(s, 1)!=SQLITE_INTEGER ||
sqlite3_column_type(s, 2)!=SQLITE_BLOB ){
return SQLITE_CORRUPT_BKPT;
}
rc = leavesReaderInit(v, 0, iStartBlockid, iEndBlockid,
pRootData, nRootData, &reader);
if( rc!=SQLITE_OK ) return rc;
while( rc==SQLITE_OK && !leavesReaderAtEnd(&reader) ){
const char *pTerm = leavesReaderTerm(&reader);
const int nTerm = leavesReaderTermBytes(&reader);
void *oldValue = sqlite3Fts2HashFind(pTerms, pTerm, nTerm);
void *newValue = (void *)((char *)oldValue+1);
if( newValue==sqlite3Fts2HashInsert(pTerms, pTerm, nTerm, newValue) ){
rc = SQLITE_NOMEM;
}else{
rc = leavesReaderStep(v, &reader);
}
}
leavesReaderDestroy(&reader);
return rc;
}
static int generateTermsResult(sqlite3_context *pContext, fts2Hash *pTerms){
int iTerm, nTerms, nResultBytes, iByte;
char *result;
TermData *pData;
fts2HashElem *e;
nTerms = fts2HashCount(pTerms);
assert( nTerms>0 );
pData = sqlite3_malloc(nTerms*sizeof(TermData));
if( pData==NULL ) return SQLITE_NOMEM;
nResultBytes = 0;
for(iTerm = 0, e = fts2HashFirst(pTerms); e; iTerm++, e = fts2HashNext(e)){
nResultBytes += fts2HashKeysize(e)+1;
assert( iTerm<nTerms );
pData[iTerm].pTerm = fts2HashKey(e);
pData[iTerm].nTerm = fts2HashKeysize(e);
pData[iTerm].pCollector = fts2HashData(e);
}
assert( iTerm==nTerms );
assert( nResultBytes>0 );
result = sqlite3_malloc(nResultBytes);
if( result==NULL ){
sqlite3_free(pData);
return SQLITE_NOMEM;
}
if( nTerms>1 ) qsort(pData, nTerms, sizeof(*pData), termDataCmp);
iByte = 0;
for(iTerm=0; iTerm<nTerms; ++iTerm){
memcpy(result+iByte, pData[iTerm].pTerm, pData[iTerm].nTerm);
iByte += pData[iTerm].nTerm;
result[iByte++] = ' ';
}
assert( iByte==nResultBytes );
assert( result[nResultBytes-1]==' ' );
result[nResultBytes-1] = '\0';
sqlite3_result_text(pContext, result, nResultBytes-1, sqlite3_free);
sqlite3_free(pData);
return SQLITE_OK;
}
static void dumpTermsFunc(
sqlite3_context *pContext,
int argc, sqlite3_value **argv
){
fulltext_cursor *pCursor;
if( argc!=3 && argc!=1 ){
generateError(pContext, "dump_terms", "incorrect arguments");
}else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
generateError(pContext, "dump_terms", "illegal first argument");
}else{
fulltext_vtab *v;
fts2Hash terms;
sqlite3_stmt *s = NULL;
int rc;
memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
v = cursor_vtab(pCursor);
if( argc==1 ){
rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
}else{
rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
if( rc==SQLITE_OK ){
rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[1]));
if( rc==SQLITE_OK ){
rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[2]));
}
}
}
if( rc!=SQLITE_OK ){
generateError(pContext, "dump_terms", NULL);
return;
}
sqlite3Fts2HashInit(&terms, FTS2_HASH_STRING, 1);
while( (rc = sqlite3_step(s))==SQLITE_ROW ){
rc = collectSegmentTerms(v, s, &terms);
if( rc!=SQLITE_OK ) break;
}
if( rc!=SQLITE_DONE ){
sqlite3_reset(s);
generateError(pContext, "dump_terms", NULL);
}else{
const int nTerms = fts2HashCount(&terms);
if( nTerms>0 ){
rc = generateTermsResult(pContext, &terms);
if( rc==SQLITE_NOMEM ){
generateError(pContext, "dump_terms", "out of memory");
}else{
assert( rc==SQLITE_OK );
}
}else if( argc==3 ){
generateError(pContext, "dump_terms", "segment not found");
}else{
sqlite3_result_null(pContext);
}
}
sqlite3Fts2HashClear(&terms);
}
}
static void createDoclistResult(sqlite3_context *pContext,
const char *pData, int nData){
DataBuffer dump;
DLReader dlReader;
int rc;
assert( pData!=NULL && nData>0 );
rc = dlrInit(&dlReader, DL_DEFAULT, pData, nData);
if( rc!=SQLITE_OK ) return rc;
dataBufferInit(&dump, 0);
for( ; rc==SQLITE_OK && !dlrAtEnd(&dlReader); rc = dlrStep(&dlReader) ){
char buf[256];
PLReader plReader;
rc = plrInit(&plReader, &dlReader);
if( rc!=SQLITE_OK ) break;
if( DL_DEFAULT==DL_DOCIDS || plrAtEnd(&plReader) ){
sqlite3_snprintf(sizeof(buf), buf, "[%lld] ", dlrDocid(&dlReader));
dataBufferAppend(&dump, buf, strlen(buf));
}else{
int iColumn = plrColumn(&plReader);
sqlite3_snprintf(sizeof(buf), buf, "[%lld %d[",
dlrDocid(&dlReader), iColumn);
dataBufferAppend(&dump, buf, strlen(buf));
for( ; !plrAtEnd(&plReader); rc = plrStep(&plReader) ){
if( rc!=SQLITE_OK ) break;
if( plrColumn(&plReader)!=iColumn ){
iColumn = plrColumn(&plReader);
sqlite3_snprintf(sizeof(buf), buf, "] %d[", iColumn);
assert( dump.nData>0 );
dump.nData--;
assert( dump.pData[dump.nData]==' ');
dataBufferAppend(&dump, buf, strlen(buf));
}
if( DL_DEFAULT==DL_POSITIONS_OFFSETS ){
sqlite3_snprintf(sizeof(buf), buf, "%d,%d,%d ",
plrPosition(&plReader),
plrStartOffset(&plReader), plrEndOffset(&plReader));
}else if( DL_DEFAULT==DL_POSITIONS ){
sqlite3_snprintf(sizeof(buf), buf, "%d ", plrPosition(&plReader));
}else{
assert( NULL=="Unhandled DL_DEFAULT value");
}
dataBufferAppend(&dump, buf, strlen(buf));
}
plrDestroy(&plReader);
if( rc!= SQLITE_OK ) break;
assert( dump.nData>0 );
dump.nData--;
assert( dump.pData[dump.nData]==' ');
dataBufferAppend(&dump, "]] ", 3);
}
}
dlrDestroy(&dlReader);
if( rc!=SQLITE_OK ){
dataBufferDestroy(&dump);
return rc;
}
assert( dump.nData>0 );
dump.nData--;
assert( dump.pData[dump.nData]==' ');
dump.pData[dump.nData] = '\0';
assert( dump.nData>0 );
sqlite3_result_text(pContext, dump.pData, dump.nData, sqlite3_free);
dump.pData = NULL;
dump.nData = dump.nCapacity = 0;
return SQLITE_OK;
}
static void dumpDoclistFunc(
sqlite3_context *pContext,
int argc, sqlite3_value **argv
){
fulltext_cursor *pCursor;
if( argc!=2 && argc!=4 ){
generateError(pContext, "dump_doclist", "incorrect arguments");
}else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
generateError(pContext, "dump_doclist", "illegal first argument");
}else if( sqlite3_value_text(argv[1])==NULL ||
sqlite3_value_text(argv[1])[0]=='\0' ){
generateError(pContext, "dump_doclist", "empty second argument");
}else{
const char *pTerm = (const char *)sqlite3_value_text(argv[1]);
const int nTerm = strlen(pTerm);
fulltext_vtab *v;
int rc;
DataBuffer doclist;
memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
v = cursor_vtab(pCursor);
dataBufferInit(&doclist, 0);
if( argc==2 ){
rc = termSelect(v, v->nColumn, pTerm, nTerm, 0, DL_DEFAULT, &doclist);
}else{
sqlite3_stmt *s = NULL;
rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
if( rc==SQLITE_OK ){
rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[2]));
if( rc==SQLITE_OK ){
rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[3]));
}
}
if( rc==SQLITE_OK ){
rc = sqlite3_step(s);
if( rc==SQLITE_DONE ){
dataBufferDestroy(&doclist);
generateError(pContext, "dump_doclist", "segment not found");
return;
}
if( rc==SQLITE_ROW ){
const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
const char *pData = sqlite3_column_blob(s, 2);
const int nData = sqlite3_column_bytes(s, 2);
rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, 0,
&doclist);
if( rc==SQLITE_OK ){
rc = sqlite3_step(s);
if( rc!=SQLITE_DONE ){
sqlite3_reset(s);
dataBufferDestroy(&doclist);
generateError(pContext, "dump_doclist", "invalid segdir");
return;
}
rc = SQLITE_OK;
}
}
}
sqlite3_reset(s);
}
if( rc==SQLITE_OK ){
if( doclist.nData>0 ){
createDoclistResult(pContext, doclist.pData, doclist.nData);
}else{
sqlite3_result_text(pContext, "", 0, SQLITE_STATIC);
}
}else if( rc==SQLITE_NOMEM ){
generateError(pContext, "dump_doclist", "out of memory");
}else{
generateError(pContext, "dump_doclist", NULL);
}
dataBufferDestroy(&doclist);
}
}
#endif
static int fulltextFindFunction(
sqlite3_vtab *pVtab,
int nArg,
const char *zName,
void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
void **ppArg
){
if( strcmp(zName,"snippet")==0 ){
*pxFunc = snippetFunc;
return 1;
}else if( strcmp(zName,"offsets")==0 ){
*pxFunc = snippetOffsetsFunc;
return 1;
}else if( strcmp(zName,"optimize")==0 ){
*pxFunc = optimizeFunc;
return 1;
#ifdef SQLITE_TEST
}else if( strcmp(zName,"dump_terms")==0 ){
*pxFunc = dumpTermsFunc;
return 1;
}else if( strcmp(zName,"dump_doclist")==0 ){
*pxFunc = dumpDoclistFunc;
return 1;
#endif
}
return 0;
}
static int fulltextRename(
sqlite3_vtab *pVtab,
const char *zName
){
fulltext_vtab *p = (fulltext_vtab *)pVtab;
int rc = SQLITE_NOMEM;
char *zSql = sqlite3_mprintf(
"ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';"
"ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
"ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';"
, p->zDb, p->zName, zName
, p->zDb, p->zName, zName
, p->zDb, p->zName, zName
);
if( zSql ){
rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
sqlite3_free(zSql);
}
return rc;
}
static const sqlite3_module fts2Module = {
0,
fulltextCreate,
fulltextConnect,
fulltextBestIndex,
fulltextDisconnect,
fulltextDestroy,
fulltextOpen,
fulltextClose,
fulltextFilter,
fulltextNext,
fulltextEof,
fulltextColumn,
fulltextRowid,
fulltextUpdate,
fulltextBegin,
fulltextSync,
fulltextCommit,
fulltextRollback,
fulltextFindFunction,
fulltextRename,
};
static void hashDestroy(void *p){
fts2Hash *pHash = (fts2Hash *)p;
sqlite3Fts2HashClear(pHash);
sqlite3_free(pHash);
}
void sqlite3Fts2SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
void sqlite3Fts2PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
void sqlite3Fts2IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
int sqlite3Fts2InitHashTable(sqlite3 *, fts2Hash *, const char *);
int sqlite3Fts2Init(sqlite3 *db){
int rc = SQLITE_OK;
fts2Hash *pHash = 0;
const sqlite3_tokenizer_module *pSimple = 0;
const sqlite3_tokenizer_module *pPorter = 0;
const sqlite3_tokenizer_module *pIcu = 0;
sqlite3Fts2SimpleTokenizerModule(&pSimple);
sqlite3Fts2PorterTokenizerModule(&pPorter);
#ifdef SQLITE_ENABLE_ICU
sqlite3Fts2IcuTokenizerModule(&pIcu);
#endif
pHash = sqlite3_malloc(sizeof(fts2Hash));
if( !pHash ){
rc = SQLITE_NOMEM;
}else{
sqlite3Fts2HashInit(pHash, FTS2_HASH_STRING, 1);
}
if( rc==SQLITE_OK ){
if( sqlite3Fts2HashInsert(pHash, "simple", 7, (void *)pSimple)
|| sqlite3Fts2HashInsert(pHash, "porter", 7, (void *)pPorter)
|| (pIcu && sqlite3Fts2HashInsert(pHash, "icu", 4, (void *)pIcu))
){
rc = SQLITE_NOMEM;
}
}
if( SQLITE_OK==rc
#if GEARS_FTS2_CHANGES && !SQLITE_TEST
#else
&& SQLITE_OK==(rc = sqlite3Fts2InitHashTable(db, pHash, "fts2_tokenizer"))
#endif
&& SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
&& SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1))
&& SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", -1))
#ifdef SQLITE_TEST
&& SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_terms", -1))
&& SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_doclist", -1))
#endif
){
return sqlite3_create_module_v2(
db, "fts2", &fts2Module, (void *)pHash, hashDestroy
);
}
assert( rc!=SQLITE_OK );
if( pHash ){
sqlite3Fts2HashClear(pHash);
sqlite3_free(pHash);
}
return rc;
}
#if !SQLITE_CORE
int sqlite3_extension_init(
sqlite3 *db,
char **pzErrMsg,
const sqlite3_api_routines *pApi
){
SQLITE_EXTENSION_INIT2(pApi)
return sqlite3Fts2Init(db);
}
#endif
#endif