Update of /cvsroot/wpdev/wolfpack/sqlite
In directory sc8-pr-cvs1:/tmp/cvs-serv2466/src/sqlite
Added Files:
attach.c auth.c btree.c btree.h btree_rb.c build.c config.h
copy.c delete.c expr.c func.c hash.c hash.h insert.c main.c
opcodes.c opcodes.h os.c os.h pager.c pager.h parse.c parse.h
pragma.c printf.c random.c select.c sqlite.h sqliteInt.h
table.c tokenize.c trigger.c update.c util.c vacuum.c vdbe.c
vdbe.h where.c
Log Message:
Implemented SQLite support.
driver=sqlite
database name is the filename
--- NEW FILE: attach.c ---
/*
** 2003 April 6
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the ATTACH and DETACH commands.
**
** $Id: attach.c,v 1.1 2003/08/26 15:02:43 dark-storm Exp $
*/
#include "sqliteInt.h"
/*
** This routine is called by the parser to process an ATTACH statement:
**
** ATTACH DATABASE filename AS dbname
**
** The pFilename and pDbname arguments are the tokens that define the
** filename and dbname in the ATTACH statement.
*/
void sqliteAttach(Parse *pParse, Token *pFilename, Token *pDbname){
Db *aNew;
int rc, i;
char *zFile, *zName;
sqlite *db;
if( pParse->explain ) return;
db = pParse->db;
if( db->file_format<4 ){
sqliteErrorMsg(pParse, "cannot attach auxiliary databases to an "
"older format master database", 0);
pParse->rc = SQLITE_ERROR;
return;
}
if( db->nDb>=MAX_ATTACHED+2 ){
sqliteErrorMsg(pParse, "too many attached databases - max %d",
MAX_ATTACHED);
pParse->rc = SQLITE_ERROR;
return;
}
zFile = 0;
sqliteSetNString(&zFile, pFilename->z, pFilename->n, 0);
if( zFile==0 ) return;
sqliteDequote(zFile);
#ifndef SQLITE_OMIT_AUTHORIZATION
if( sqliteAuthCheck(pParse, SQLITE_ATTACH, zFile, 0, 0)!=SQLITE_OK ){
sqliteFree(zFile);
return;
}
#endif /* SQLITE_OMIT_AUTHORIZATION */
zName = 0;
sqliteSetNString(&zName, pDbname->z, pDbname->n, 0);
if( zName==0 ) return;
sqliteDequote(zName);
for(i=0; i<db->nDb; i++){
if( db->aDb[i].zName && sqliteStrICmp(db->aDb[i].zName, zName)==0 ){
sqliteErrorMsg(pParse, "database %z is already in use", zName);
pParse->rc = SQLITE_ERROR;
sqliteFree(zFile);
return;
}
}
if( db->aDb==db->aDbStatic ){
aNew = sqliteMalloc( sizeof(db->aDb[0])*3 );
if( aNew==0 ) return;
memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
}else{
aNew = sqliteRealloc(db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
if( aNew==0 ) return;
}
db->aDb = aNew;
aNew = &db->aDb[db->nDb++];
memset(aNew, 0, sizeof(*aNew));
sqliteHashInit(&aNew->tblHash, SQLITE_HASH_STRING, 0);
sqliteHashInit(&aNew->idxHash, SQLITE_HASH_STRING, 0);
sqliteHashInit(&aNew->trigHash, SQLITE_HASH_STRING, 0);
sqliteHashInit(&aNew->aFKey, SQLITE_HASH_STRING, 1);
aNew->zName = zName;
rc = sqliteBtreeFactory(db, zFile, 0, MAX_PAGES, &aNew->pBt);
if( rc ){
sqliteErrorMsg(pParse, "unable to open database: %s", zFile);
}
sqliteFree(zFile);
db->flags &= ~SQLITE_Initialized;
if( pParse->nErr ) return;
rc = sqliteInit(pParse->db, &pParse->zErrMsg);
if( rc ){
sqliteResetInternalSchema(db, 0);
pParse->nErr++;
pParse->rc = SQLITE_ERROR;
}
}
/*
** This routine is called by the parser to process a DETACH statement:
**
** DETACH DATABASE dbname
**
** The pDbname argument is the name of the database in the DETACH statement.
*/
void sqliteDetach(Parse *pParse, Token *pDbname){
int i;
sqlite *db;
if( pParse->explain ) return;
db = pParse->db;
for(i=0; i<db->nDb; i++){
if( db->aDb[i].pBt==0 || db->aDb[i].zName==0 ) continue;
if( strlen(db->aDb[i].zName)!=pDbname->n ) continue;
if( sqliteStrNICmp(db->aDb[i].zName, pDbname->z, pDbname->n)==0 ) break;
}
if( i>=db->nDb ){
sqliteErrorMsg(pParse, "no such database: %T", pDbname);
return;
}
if( i<2 ){
sqliteErrorMsg(pParse, "cannot detach database %T", pDbname);
return;
}
#ifndef SQLITE_OMIT_AUTHORIZATION
if( sqliteAuthCheck(pParse,SQLITE_DETACH,db->aDb[i].zName,0,0)!=SQLITE_OK ){
return;
}
#endif /* SQLITE_OMIT_AUTHORIZATION */
sqliteBtreeClose(db->aDb[i].pBt);
db->aDb[i].pBt = 0;
sqliteFree(db->aDb[i].zName);
sqliteResetInternalSchema(db, i);
db->nDb--;
if( i<db->nDb ){
db->aDb[i] = db->aDb[db->nDb];
memset(&db->aDb[db->nDb], 0, sizeof(db->aDb[0]));
sqliteResetInternalSchema(db, i);
}
}
/*
** Initialize a DbFixer structure. This routine must be called prior
** to passing the structure to one of the sqliteFixAAAA() routines below.
**
** The return value indicates whether or not fixation is required. TRUE
** means we do need to fix the database references, FALSE means we do not.
*/
int sqliteFixInit(
DbFixer *pFix, /* The fixer to be initialized */
Parse *pParse, /* Error messages will be written here */
int iDb, /* This is the database that must must be used */
const char *zType, /* "view", "trigger", or "index" */
const Token *pName /* Name of the view, trigger, or index */
){
sqlite *db;
if( iDb<0 || iDb==1 ) return 0;
db = pParse->db;
assert( db->nDb>iDb );
pFix->pParse = pParse;
pFix->zDb = db->aDb[iDb].zName;
pFix->zType = zType;
pFix->pName = pName;
return 1;
}
/*
** The following set of routines walk through the parse tree and assign
** a specific database to all table references where the database name
** was left unspecified in the original SQL statement. The pFix structure
** must have been initialized by a prior call to sqliteFixInit().
**
** These routines are used to make sure that an index, trigger, or
** view in one database does not refer to objects in a different database.
** (Exception: indices, triggers, and views in the TEMP database are
** allowed to refer to anything.) If a reference is explicitly made
** to an object in a different database, an error message is added to
** pParse->zErrMsg and these routines return non-zero. If everything
** checks out, these routines return 0.
*/
int sqliteFixSrcList(
DbFixer *pFix, /* Context of the fixation */
SrcList *pList /* The Source list to check and modify */
){
int i;
const char *zDb;
if( pList==0 ) return 0;
zDb = pFix->zDb;
for(i=0; i<pList->nSrc; i++){
if( pList->a[i].zDatabase==0 ){
pList->a[i].zDatabase = sqliteStrDup(zDb);
}else if( sqliteStrICmp(pList->a[i].zDatabase,zDb)!=0 ){
sqliteErrorMsg(pFix->pParse,
"%s %z cannot reference objects in database %s",
pFix->zType, sqliteStrNDup(pFix->pName->z, pFix->pName->n),
pList->a[i].zDatabase);
return 1;
}
if( sqliteFixSelect(pFix, pList->a[i].pSelect) ) return 1;
if( sqliteFixExpr(pFix, pList->a[i].pOn) ) return 1;
}
return 0;
}
int sqliteFixSelect(
DbFixer *pFix, /* Context of the fixation */
Select *pSelect /* The SELECT statement to be fixed to one database */
){
while( pSelect ){
if( sqliteFixExprList(pFix, pSelect->pEList) ){
return 1;
}
if( sqliteFixSrcList(pFix, pSelect->pSrc) ){
return 1;
}
if( sqliteFixExpr(pFix, pSelect->pWhere) ){
return 1;
}
if( sqliteFixExpr(pFix, pSelect->pHaving) ){
return 1;
}
pSelect = pSelect->pPrior;
}
return 0;
}
int sqliteFixExpr(
DbFixer *pFix, /* Context of the fixation */
Expr *pExpr /* The expression to be fixed to one database */
){
while( pExpr ){
if( sqliteFixSelect(pFix, pExpr->pSelect) ){
return 1;
}
if( sqliteFixExprList(pFix, pExpr->pList) ){
return 1;
}
if( sqliteFixExpr(pFix, pExpr->pRight) ){
return 1;
}
pExpr = pExpr->pLeft;
}
return 0;
}
int sqliteFixExprList(
DbFixer *pFix, /* Context of the fixation */
ExprList *pList /* The expression to be fixed to one database */
){
int i;
if( pList==0 ) return 0;
for(i=0; i<pList->nExpr; i++){
if( sqliteFixExpr(pFix, pList->a[i].pExpr) ){
return 1;
}
}
return 0;
}
int sqliteFixTriggerStep(
DbFixer *pFix, /* Context of the fixation */
TriggerStep *pStep /* The trigger step be fixed to one database */
){
while( pStep ){
if( sqliteFixSelect(pFix, pStep->pSelect) ){
return 1;
}
if( sqliteFixExpr(pFix, pStep->pWhere) ){
return 1;
}
if( sqliteFixExprList(pFix, pStep->pExprList) ){
return 1;
}
pStep = pStep->pNext;
}
return 0;
}
--- NEW FILE: auth.c ---
/*
** 2003 January 11
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the sqlite_set_authorizer()
** API. This facility is an optional feature of the library. Embedded
** systems that do not need this facility may omit it by recompiling
** the library with -DSQLITE_OMIT_AUTHORIZATION=1
**
** $Id: auth.c,v 1.1 2003/08/26 15:02:43 dark-storm Exp $
*/
#include "sqliteInt.h"
/*
** All of the code in this file may be omitted by defining a single
** macro.
*/
#ifndef SQLITE_OMIT_AUTHORIZATION
/*
** Set or clear the access authorization function.
**
** The access authorization function is be called during the compilation
** phase to verify that the user has read and/or write access permission on
** various fields of the database. The first argument to the auth function
** is a copy of the 3rd argument to this routine. The second argument
** to the auth function is one of these constants:
**
** SQLITE_COPY
** SQLITE_CREATE_INDEX
** SQLITE_CREATE_TABLE
** SQLITE_CREATE_TEMP_INDEX
** SQLITE_CREATE_TEMP_TABLE
** SQLITE_CREATE_TEMP_TRIGGER
** SQLITE_CREATE_TEMP_VIEW
** SQLITE_CREATE_TRIGGER
** SQLITE_CREATE_VIEW
** SQLITE_DELETE
** SQLITE_DROP_INDEX
** SQLITE_DROP_TABLE
** SQLITE_DROP_TEMP_INDEX
** SQLITE_DROP_TEMP_TABLE
** SQLITE_DROP_TEMP_TRIGGER
** SQLITE_DROP_TEMP_VIEW
** SQLITE_DROP_TRIGGER
** SQLITE_DROP_VIEW
** SQLITE_INSERT
** SQLITE_PRAGMA
** SQLITE_READ
** SQLITE_SELECT
** SQLITE_TRANSACTION
** SQLITE_UPDATE
**
** The third and fourth arguments to the auth function are the name of
** the table and the column that are being accessed. The auth function
** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
** means that the SQL statement will never-run - the sqlite_exec() call
** will return with an error. SQLITE_IGNORE means that the SQL statement
** should run but attempts to read the specified column will return NULL
** and attempts to write the column will be ignored.
**
** Setting the auth function to NULL disables this hook. The default
** setting of the auth function is NULL.
*/
int sqlite_set_authorizer(
sqlite *db,
int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
void *pArg
){
db->xAuth = xAuth;
db->pAuthArg = pArg;
return SQLITE_OK;
}
/*
** Write an error message into pParse->zErrMsg that explains that the
** user-supplied authorization function returned an illegal value.
*/
static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
char zBuf[20];
sprintf(zBuf, "(%d)", rc);
sqliteSetString(&pParse->zErrMsg, "illegal return value ", zBuf,
" from the authorization function - should be SQLITE_OK, "
"SQLITE_IGNORE, or SQLITE_DENY", 0);
pParse->nErr++;
pParse->rc = SQLITE_MISUSE;
}
/*
** The pExpr should be a TK_COLUMN expression. The table referred to
** is in pTabList or else it is the NEW or OLD table of a trigger.
** Check to see if it is OK to read this particular column.
**
** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
** then generate an error.
*/
void sqliteAuthRead(
Parse *pParse, /* The parser context */
Expr *pExpr, /* The expression to check authorization on */
SrcList *pTabList /* All table that pExpr might refer to */
){
sqlite *db = pParse->db;
int rc;
Table *pTab; /* The table being read */
const char *zCol; /* Name of the column of the table */
int iSrc; /* Index in pTabList->a[] of table being read */
const char *zDBase; /* Name of database being accessed */
if( db->xAuth==0 ) return;
assert( pExpr->op==TK_COLUMN );
for(iSrc=0; iSrc<pTabList->nSrc; iSrc++){
if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
}
if( iSrc>=0 && iSrc<pTabList->nSrc ){
pTab = pTabList->a[iSrc].pTab;
}else{
/* This must be an attempt to read the NEW or OLD pseudo-tables
** of a trigger.
*/
TriggerStack *pStack; /* The stack of current triggers */
pStack = pParse->trigStack;
assert( pStack!=0 );
assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
pTab = pStack->pTab;
}
if( pTab==0 ) return;
if( pExpr->iColumn>=0 ){
assert( pExpr->iColumn<pTab->nCol );
zCol = pTab->aCol[pExpr->iColumn].zName;
}else if( pTab->iPKey>=0 ){
assert( pTab->iPKey<pTab->nCol );
zCol = pTab->aCol[pTab->iPKey].zName;
}else{
zCol = "ROWID";
}
assert( pExpr->iDb<db->nDb );
zDBase = db->aDb[pExpr->iDb].zName;
rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase,
pParse->zAuthContext);
if( rc==SQLITE_IGNORE ){
pExpr->op = TK_NULL;
}else if( rc==SQLITE_DENY ){
if( db->nDb>2 || pExpr->iDb!=0 ){
sqliteSetString(&pParse->zErrMsg,"access to ", zDBase, ".",
pTab->zName, ".", zCol, " is prohibited", 0);
}else{
sqliteSetString(&pParse->zErrMsg,"access to ", pTab->zName, ".",
zCol, " is prohibited", 0);
}
pParse->nErr++;
pParse->rc = SQLITE_AUTH;
}else if( rc!=SQLITE_OK ){
sqliteAuthBadReturnCode(pParse, rc);
}
}
/*
** Do an authorization check using the code and arguments given. Return
** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
** is returned, then the error count and error message in pParse are
** modified appropriately.
*/
int sqliteAuthCheck(
Parse *pParse,
int code,
const char *zArg1,
const char *zArg2,
const char *zArg3
){
sqlite *db = pParse->db;
int rc;
if( db->xAuth==0 ){
return SQLITE_OK;
}
rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
if( rc==SQLITE_DENY ){
sqliteSetString(&pParse->zErrMsg, "not authorized", 0);
pParse->rc = SQLITE_AUTH;
pParse->nErr++;
}else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
rc = SQLITE_DENY;
sqliteAuthBadReturnCode(pParse, rc);
}
return rc;
}
/*
** Push an authorization context. After this routine is called, the
** zArg3 argument to authorization callbacks will be zContext until
** popped. Or if pParse==0, this routine is a no-op.
*/
void sqliteAuthContextPush(
Parse *pParse,
AuthContext *pContext,
const char *zContext
){
pContext->pParse = pParse;
if( pParse ){
pContext->zAuthContext = pParse->zAuthContext;
pParse->zAuthContext = zContext;
}
}
/*
** Pop an authorization context that was previously pushed
** by sqliteAuthContextPush
*/
void sqliteAuthContextPop(AuthContext *pContext){
if( pContext->pParse ){
pContext->pParse->zAuthContext = pContext->zAuthContext;
pContext->pParse = 0;
}
}
#endif /* SQLITE_OMIT_AUTHORIZATION */
--- NEW FILE: btree.c ---
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** $Id: btree.c,v 1.1 2003/08/26 15:02:43 dark-storm Exp $
**
** This file implements a external (disk-based) database using BTrees.
** For a detailed discussion of BTrees, refer to
**
** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
** "Sorting And Searching", pages 473-480. Addison-Wesley
** Publishing Company, Reading, Massachusetts.
[...3546 lines suppressed...]
#endif
};
static BtCursorOps sqliteBtreeCursorOps = {
fileBtreeMoveto,
fileBtreeDelete,
fileBtreeInsert,
fileBtreeFirst,
fileBtreeLast,
fileBtreeNext,
fileBtreePrevious,
fileBtreeKeySize,
fileBtreeKey,
fileBtreeKeyCompare,
fileBtreeDataSize,
fileBtreeData,
fileBtreeCloseCursor,
#ifdef SQLITE_TEST
fileBtreeCursorDump,
#endif
};
--- NEW FILE: btree.h ---
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the sqlite B-Tree file
** subsystem. See comments in the source code for a detailed description
** of what each interface routine does.
**
** @(#) $Id: btree.h,v 1.1 2003/08/26 15:02:43 dark-storm Exp $
*/
#ifndef _BTREE_H_
#define _BTREE_H_
/*
** Forward declarations of structure
*/
typedef struct Btree Btree;
typedef struct BtCursor BtCursor;
typedef struct BtOps BtOps;
typedef struct BtCursorOps BtCursorOps;
/*
** An instance of the following structure contains pointers to all
** methods against an open BTree. Alternative BTree implementations
** (examples: file based versus in-memory) can be created by substituting
** different methods. Users of the BTree cannot tell the difference.
**
** In C++ we could do this by defining a virtual base class and then
** creating subclasses for each different implementation. But this is
** C not C++ so we have to be a little more explicit.
*/
struct BtOps {
int (*Close)(Btree*);
int (*SetCacheSize)(Btree*, int);
int (*SetSafetyLevel)(Btree*, int);
int (*BeginTrans)(Btree*);
int (*Commit)(Btree*);
int (*Rollback)(Btree*);
int (*BeginCkpt)(Btree*);
int (*CommitCkpt)(Btree*);
int (*RollbackCkpt)(Btree*);
int (*CreateTable)(Btree*, int*);
int (*CreateIndex)(Btree*, int*);
int (*DropTable)(Btree*, int);
int (*ClearTable)(Btree*, int);
int (*Cursor)(Btree*, int iTable, int wrFlag, BtCursor **ppCur);
int (*GetMeta)(Btree*, int*);
int (*UpdateMeta)(Btree*, int*);
char *(*IntegrityCheck)(Btree*, int*, int);
const char *(*GetFilename)(Btree*);
int (*Copyfile)(Btree*,Btree*);
#ifdef SQLITE_TEST
int (*PageDump)(Btree*, int, int);
struct Pager *(*Pager)(Btree*);
#endif
};
/*
** An instance of this structure defines all of the methods that can
** be executed against a cursor.
*/
struct BtCursorOps {
int (*Moveto)(BtCursor*, const void *pKey, int nKey, int *pRes);
int (*Delete)(BtCursor*);
int (*Insert)(BtCursor*, const void *pKey, int nKey,
const void *pData, int nData);
int (*First)(BtCursor*, int *pRes);
int (*Last)(BtCursor*, int *pRes);
int (*Next)(BtCursor*, int *pRes);
int (*Previous)(BtCursor*, int *pRes);
int (*KeySize)(BtCursor*, int *pSize);
int (*Key)(BtCursor*, int offset, int amt, char *zBuf);
int (*KeyCompare)(BtCursor*, const void *pKey, int nKey,
int nIgnore, int *pRes);
int (*DataSize)(BtCursor*, int *pSize);
int (*Data)(BtCursor*, int offset, int amt, char *zBuf);
int (*CloseCursor)(BtCursor*);
#ifdef SQLITE_TEST
int (*CursorDump)(BtCursor*, int*);
#endif
};
/*
** The number of 4-byte "meta" values contained on the first page of each
** database file.
*/
#define SQLITE_N_BTREE_META 10
int sqliteBtreeOpen(const char *zFilename, int mode, int nPg, Btree **ppBtree);
int sqliteRbtreeOpen(const char *zFilename, int mode, int nPg, Btree **ppBtree);
#define btOps(pBt) (*((BtOps **)(pBt)))
#define btCOps(pCur) (*((BtCursorOps **)(pCur)))
#define sqliteBtreeClose(pBt) (btOps(pBt)->Close(pBt))
#define sqliteBtreeSetCacheSize(pBt, sz) (btOps(pBt)->SetCacheSize(pBt, sz))
#define sqliteBtreeSetSafetyLevel(pBt, sl) (btOps(pBt)->SetSafetyLevel(pBt, sl))
#define sqliteBtreeBeginTrans(pBt) (btOps(pBt)->BeginTrans(pBt))
#define sqliteBtreeCommit(pBt) (btOps(pBt)->Commit(pBt))
#define sqliteBtreeRollback(pBt) (btOps(pBt)->Rollback(pBt))
#define sqliteBtreeBeginCkpt(pBt) (btOps(pBt)->BeginCkpt(pBt))
#define sqliteBtreeCommitCkpt(pBt) (btOps(pBt)->CommitCkpt(pBt))
#define sqliteBtreeRollbackCkpt(pBt) (btOps(pBt)->RollbackCkpt(pBt))
#define sqliteBtreeCreateTable(pBt,piTable)\
(btOps(pBt)->CreateTable(pBt,piTable))
#define sqliteBtreeCreateIndex(pBt, piIndex)\
(btOps(pBt)->CreateIndex(pBt, piIndex))
#define sqliteBtreeDropTable(pBt, iTable) (btOps(pBt)->DropTable(pBt, iTable))
#define sqliteBtreeClearTable(pBt, iTable)\
(btOps(pBt)->ClearTable(pBt, iTable))
#define sqliteBtreeCursor(pBt, iTable, wrFlag, ppCur)\
(btOps(pBt)->Cursor(pBt, iTable, wrFlag, ppCur))
#define sqliteBtreeMoveto(pCur, pKey, nKey, pRes)\
(btCOps(pCur)->Moveto(pCur, pKey, nKey, pRes))
#define sqliteBtreeDelete(pCur) (btCOps(pCur)->Delete(pCur))
#define sqliteBtreeInsert(pCur, pKey, nKey, pData, nData) \
(btCOps(pCur)->Insert(pCur, pKey, nKey, pData, nData))
#define sqliteBtreeFirst(pCur, pRes) (btCOps(pCur)->First(pCur, pRes))
#define sqliteBtreeLast(pCur, pRes) (btCOps(pCur)->Last(pCur, pRes))
#define sqliteBtreeNext(pCur, pRes) (btCOps(pCur)->Next(pCur, pRes))
#define sqliteBtreePrevious(pCur, pRes) (btCOps(pCur)->Previous(pCur, pRes))
#define sqliteBtreeKeySize(pCur, pSize) (btCOps(pCur)->KeySize(pCur, pSize) )
#define sqliteBtreeKey(pCur, offset, amt, zBuf)\
(btCOps(pCur)->Key(pCur, offset, amt, zBuf))
#define sqliteBtreeKeyCompare(pCur, pKey, nKey, nIgnore, pRes)\
(btCOps(pCur)->KeyCompare(pCur, pKey, nKey, nIgnore, pRes))
#define sqliteBtreeDataSize(pCur, pSize) (btCOps(pCur)->DataSize(pCur, pSize))
#define sqliteBtreeData(pCur, offset, amt, zBuf)\
(btCOps(pCur)->Data(pCur, offset, amt, zBuf))
#define sqliteBtreeCloseCursor(pCur) (btCOps(pCur)->CloseCursor(pCur))
#define sqliteBtreeGetMeta(pBt, aMeta) (btOps(pBt)->GetMeta(pBt, aMeta))
#define sqliteBtreeUpdateMeta(pBt, aMeta) (btOps(pBt)->UpdateMeta(pBt, aMeta))
#define sqliteBtreeIntegrityCheck(pBt, aRoot, nRoot)\
(btOps(pBt)->IntegrityCheck(pBt, aRoot, nRoot))
#define sqliteBtreeGetFilename(pBt) (btOps(pBt)->GetFilename(pBt))
#define sqliteBtreeCopyFile(pBt1, pBt2) (btOps(pBt1)->Copyfile(pBt1, pBt2))
#ifdef SQLITE_TEST
#define sqliteBtreePageDump(pBt, pgno, recursive)\
(btOps(pBt)->PageDump(pBt, pgno, recursive))
#define sqliteBtreeCursorDump(pCur, aResult)\
(btCOps(pCur)->CursorDump(pCur, aResult))
#define sqliteBtreePager(pBt) (btOps(pBt)->Pager(pBt))
int btree_native_byte_order;
#endif /* SQLITE_TEST */
#endif /* _BTREE_H_ */
--- NEW FILE: btree_rb.c ---
/*
** 2003 Feb 4
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** $Id: btree_rb.c,v 1.1 2003/08/26 15:02:43 dark-storm Exp $
**
** This file implements an in-core database using Red-Black balanced
** binary trees.
**
** It was contributed to SQLite by anonymous on 2003-Feb-04 23:24:49 UTC.
*/
#include "btree.h"
[...1378 lines suppressed...]
(int(*)(BtCursor*,const void*,int,int*)) memRbtreeMoveto,
(int(*)(BtCursor*)) memRbtreeDelete,
(int(*)(BtCursor*,const void*,int,const void*,int)) memRbtreeInsert,
(int(*)(BtCursor*,int*)) memRbtreeFirst,
(int(*)(BtCursor*,int*)) memRbtreeLast,
(int(*)(BtCursor*,int*)) memRbtreeNext,
(int(*)(BtCursor*,int*)) memRbtreePrevious,
(int(*)(BtCursor*,int*)) memRbtreeKeySize,
(int(*)(BtCursor*,int,int,char*)) memRbtreeKey,
(int(*)(BtCursor*,const void*,int,int,int*)) memRbtreeKeyCompare,
(int(*)(BtCursor*,int*)) memRbtreeDataSize,
(int(*)(BtCursor*,int,int,char*)) memRbtreeData,
(int(*)(BtCursor*)) memRbtreeCloseCursor,
#ifdef SQLITE_TEST
(int(*)(BtCursor*,int*)) memRbtreeCursorDump,
#endif
};
#endif /* SQLITE_OMIT_INMEMORYDB */
--- NEW FILE: build.c ---
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the SQLite parser
** when syntax rules are reduced. The routines in this file handle the
** following kinds of SQL syntax:
**
** CREATE TABLE
** DROP TABLE
** CREATE INDEX
** DROP INDEX
[...2179 lines suppressed...]
** an OP_Commit that will cause the changes to be committed to disk.
**
** Note that checkpoints are automatically committed at the end of
** a statement. Note also that there can be multiple calls to
** sqliteBeginWriteOperation() but there should only be a single
** call to sqliteEndWriteOperation() at the conclusion of the statement.
*/
void sqliteEndWriteOperation(Parse *pParse){
Vdbe *v;
sqlite *db = pParse->db;
if( pParse->trigStack ) return; /* if this is in a trigger */
v = sqliteGetVdbe(pParse);
if( v==0 ) return;
if( db->flags & SQLITE_InTrans ){
/* A BEGIN has executed. Do not commit until we see an explicit
** COMMIT statement. */
}else{
sqliteVdbeAddOp(v, OP_Commit, 0, 0);
}
}
--- NEW FILE: config.h ---
#define SQLITE_PTR_SZ 4
#define NO_TCL 1
--- NEW FILE: copy.c ---
/*
** 2003 April 6
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the COPY command.
**
** $Id: copy.c,v 1.1 2003/08/26 15:02:44 dark-storm Exp $
*/
#include "sqliteInt.h"
/*
** The COPY command is for compatibility with PostgreSQL and specificially
** for the ability to read the output of pg_dump. The format is as
** follows:
**
** COPY table FROM file [USING DELIMITERS string]
**
** "table" is an existing table name. We will read lines of code from
** file to fill this table with data. File might be "stdin". The optional
** delimiter string identifies the field separators. The default is a tab.
*/
void sqliteCopy(
Parse *pParse, /* The parser context */
SrcList *pTableName, /* The name of the table into which we will insert */
Token *pFilename, /* The file from which to obtain information */
Token *pDelimiter, /* Use this as the field delimiter */
int onError /* What to do if a constraint fails */
){
Table *pTab;
int i;
Vdbe *v;
int addr, end;
Index *pIdx;
char *zFile = 0;
const char *zDb;
sqlite *db = pParse->db;
if( sqlite_malloc_failed ) goto copy_cleanup;
assert( pTableName->nSrc==1 );
pTab = sqliteSrcListLookup(pParse, pTableName);
if( pTab==0 || sqliteIsReadOnly(pParse, pTab, 0) ) goto copy_cleanup;
zFile = sqliteStrNDup(pFilename->z, pFilename->n);
sqliteDequote(zFile);
assert( pTab->iDb<db->nDb );
zDb = db->aDb[pTab->iDb].zName;
if( sqliteAuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb)
|| sqliteAuthCheck(pParse, SQLITE_COPY, pTab->zName, zFile, zDb) ){
goto copy_cleanup;
}
v = sqliteGetVdbe(pParse);
if( v ){
sqliteBeginWriteOperation(pParse, 1, pTab->iDb);
addr = sqliteVdbeAddOp(v, OP_FileOpen, 0, 0);
sqliteVdbeChangeP3(v, addr, pFilename->z, pFilename->n);
sqliteVdbeDequoteP3(v, addr);
sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
sqliteVdbeAddOp(v, OP_OpenWrite, 0, pTab->tnum);
sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
assert( pIdx->iDb==1 || pIdx->iDb==pTab->iDb );
sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
sqliteVdbeAddOp(v, OP_OpenWrite, i, pIdx->tnum);
sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
}
if( db->flags & SQLITE_CountRows ){
sqliteVdbeAddOp(v, OP_Integer, 0, 0); /* Initialize the row count */
}
end = sqliteVdbeMakeLabel(v);
addr = sqliteVdbeAddOp(v, OP_FileRead, pTab->nCol, end);
if( pDelimiter ){
sqliteVdbeChangeP3(v, addr, pDelimiter->z, pDelimiter->n);
sqliteVdbeDequoteP3(v, addr);
}else{
sqliteVdbeChangeP3(v, addr, "\t", 1);
}
if( pTab->iPKey>=0 ){
sqliteVdbeAddOp(v, OP_FileColumn, pTab->iPKey, 0);
sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
}else{
sqliteVdbeAddOp(v, OP_NewRecno, 0, 0);
}
for(i=0; i<pTab->nCol; i++){
if( i==pTab->iPKey ){
/* The integer primary key column is filled with NULL since its
** value is always pulled from the record number */
sqliteVdbeAddOp(v, OP_String, 0, 0);
}else{
sqliteVdbeAddOp(v, OP_FileColumn, i, 0);
}
}
sqliteGenerateConstraintChecks(pParse, pTab, 0, 0, pTab->iPKey>=0,
0, onError, addr);
sqliteCompleteInsertion(pParse, pTab, 0, 0, 0, 0, -1);
if( (db->flags & SQLITE_CountRows)!=0 ){
sqliteVdbeAddOp(v, OP_AddImm, 1, 0); /* Increment row count */
}
sqliteVdbeAddOp(v, OP_Goto, 0, addr);
sqliteVdbeResolveLabel(v, end);
sqliteVdbeAddOp(v, OP_Noop, 0, 0);
sqliteEndWriteOperation(pParse);
if( db->flags & SQLITE_CountRows ){
sqliteVdbeAddOp(v, OP_ColumnName, 0, 0);
sqliteVdbeChangeP3(v, -1, "rows inserted", P3_STATIC);
sqliteVdbeAddOp(v, OP_Callback, 1, 0);
}
}
copy_cleanup:
sqliteSrcListDelete(pTableName);
sqliteFree(zFile);
return;
}
--- NEW FILE: delete.c ---
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** to handle DELETE FROM statements.
**
** $Id: delete.c,v 1.1 2003/08/26 15:02:44 dark-storm Exp $
*/
#include "sqliteInt.h"
/*
** Look up every table that is named in pSrc. If any table is not found,
** add an error message to pParse->zErrMsg and return NULL. If all tables
** are found, return a pointer to the last table.
*/
Table *sqliteSrcListLookup(Parse *pParse, SrcList *pSrc){
Table *pTab = 0;
int i;
for(i=0; i<pSrc->nSrc; i++){
const char *zTab = pSrc->a[i].zName;
const char *zDb = pSrc->a[i].zDatabase;
pTab = sqliteLocateTable(pParse, zTab, zDb);
pSrc->a[i].pTab = pTab;
}
return pTab;
}
/*
** Check to make sure the given table is writable. If it is not
** writable, generate an error message and return 1. If it is
** writable return 0;
*/
int sqliteIsReadOnly(Parse *pParse, Table *pTab, int viewOk){
if( pTab->readOnly ){
sqliteErrorMsg(pParse, "table %s may not be modified", pTab->zName);
return 1;
}
if( !viewOk && pTab->pSelect ){
sqliteErrorMsg(pParse, "cannot modify %s because it is a view",pTab->zName);
return 1;
}
return 0;
}
/*
** Process a DELETE FROM statement.
*/
void sqliteDeleteFrom(
Parse *pParse, /* The parser context */
SrcList *pTabList, /* The table from which we should delete things */
Expr *pWhere /* The WHERE clause. May be null */
){
Vdbe *v; /* The virtual database engine */
Table *pTab; /* The table from which records will be deleted */
const char *zDb; /* Name of database holding pTab */
int end, addr; /* A couple addresses of generated code */
int i; /* Loop counter */
WhereInfo *pWInfo; /* Information about the WHERE clause */
Index *pIdx; /* For looping over indices of the table */
int iCur; /* VDBE Cursor number for pTab */
sqlite *db; /* Main database structure */
int isView; /* True if attempting to delete from a view */
AuthContext sContext; /* Authorization context */
int row_triggers_exist = 0; /* True if any triggers exist */
int before_triggers; /* True if there are BEFORE triggers */
int after_triggers; /* True if there are AFTER triggers */
int oldIdx = -1; /* Cursor for the OLD table of AFTER triggers */
sContext.pParse = 0;
if( pParse->nErr || sqlite_malloc_failed ){
pTabList = 0;
goto delete_from_cleanup;
}
db = pParse->db;
assert( pTabList->nSrc==1 );
/* Locate the table which we want to delete. This table has to be
** put in an SrcList structure because some of the subroutines we
** will be calling are designed to work with multiple tables and expect
** an SrcList* parameter instead of just a Table* parameter.
*/
pTab = sqliteSrcListLookup(pParse, pTabList);
if( pTab==0 ) goto delete_from_cleanup;
before_triggers = sqliteTriggersExist(pParse, pTab->pTrigger,
TK_DELETE, TK_BEFORE, TK_ROW, 0);
after_triggers = sqliteTriggersExist(pParse, pTab->pTrigger,
TK_DELETE, TK_AFTER, TK_ROW, 0);
row_triggers_exist = before_triggers || after_triggers;
isView = pTab->pSelect!=0;
if( sqliteIsReadOnly(pParse, pTab, before_triggers) ){
goto delete_from_cleanup;
}
assert( pTab->iDb<db->nDb );
zDb = db->aDb[pTab->iDb].zName;
if( sqliteAuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
goto delete_from_cleanup;
}
/* If pTab is really a view, make sure it has been initialized.
*/
if( isView && sqliteViewGetColumnNames(pParse, pTab) ){
goto delete_from_cleanup;
}
/* Allocate a cursor used to store the old.* data for a trigger.
*/
if( row_triggers_exist ){
oldIdx = pParse->nTab++;
}
/* Resolve the column names in all the expressions.
*/
assert( pTabList->nSrc==1 );
iCur = pTabList->a[0].iCursor = pParse->nTab++;
if( pWhere ){
if( sqliteExprResolveIds(pParse, pTabList, 0, pWhere) ){
goto delete_from_cleanup;
}
if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
goto delete_from_cleanup;
}
}
/* Start the view context
*/
if( isView ){
sqliteAuthContextPush(pParse, &sContext, pTab->zName);
}
/* Begin generating code.
*/
v = sqliteGetVdbe(pParse);
if( v==0 ){
goto delete_from_cleanup;
}
sqliteBeginWriteOperation(pParse, row_triggers_exist, pTab->iDb);
/* If we are trying to delete from a view, construct that view into
** a temporary table.
*/
if( isView ){
Select *pView = sqliteSelectDup(pTab->pSelect);
sqliteSelect(pParse, pView, SRT_TempTable, iCur, 0, 0, 0);
sqliteSelectDelete(pView);
}
/* Initialize the counter of the number of rows deleted, if
** we are counting rows.
*/
if( db->flags & SQLITE_CountRows ){
sqliteVdbeAddOp(v, OP_Integer, 0, 0);
}
/* Special case: A DELETE without a WHERE clause deletes everything.
** It is easier just to erase the whole table. Note, however, that
** this means that the row change count will be incorrect.
*/
if( pWhere==0 && !row_triggers_exist ){
if( db->flags & SQLITE_CountRows ){
/* If counting rows deleted, just count the total number of
** entries in the table. */
int endOfLoop = sqliteVdbeMakeLabel(v);
int addr;
if( !isView ){
sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
sqliteVdbeAddOp(v, OP_OpenRead, iCur, pTab->tnum);
}
sqliteVdbeAddOp(v, OP_Rewind, iCur, sqliteVdbeCurrentAddr(v)+2);
addr = sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
sqliteVdbeAddOp(v, OP_Next, iCur, addr);
sqliteVdbeResolveLabel(v, endOfLoop);
sqliteVdbeAddOp(v, OP_Close, iCur, 0);
}
if( !isView ){
sqliteVdbeAddOp(v, OP_Clear, pTab->tnum, pTab->iDb);
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
sqliteVdbeAddOp(v, OP_Clear, pIdx->tnum, pIdx->iDb);
}
}
}
/* The usual case: There is a WHERE clause so we have to scan through
** the table an pick which records to delete.
*/
else{
/* Begin the database scan
*/
pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 1, 0);
if( pWInfo==0 ) goto delete_from_cleanup;
/* Remember the key of every item to be deleted.
*/
sqliteVdbeAddOp(v, OP_ListWrite, 0, 0);
if( db->flags & SQLITE_CountRows ){
sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
}
/* End the database scan loop.
*/
sqliteWhereEnd(pWInfo);
/* Open the pseudo-table used to store OLD if there are triggers.
*/
if( row_triggers_exist ){
sqliteVdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
}
/* Delete every item whose key was written to the list during the
** database scan. We have to delete items after the scan is complete
** because deleting an item can change the scan order.
*/
sqliteVdbeAddOp(v, OP_ListRewind, 0, 0);
end = sqliteVdbeMakeLabel(v);
/* This is the beginning of the delete loop when there are
** row triggers.
*/
if( row_triggers_exist ){
addr = sqliteVdbeAddOp(v, OP_ListRead, 0, end);
sqliteVdbeAddOp(v, OP_Dup, 0, 0);
if( !isView ){
sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
sqliteVdbeAddOp(v, OP_OpenRead, iCur, pTab->tnum);
}
sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
sqliteVdbeAddOp(v, OP_RowData, iCur, 0);
sqliteVdbeAddOp(v, OP_PutIntKey, oldIdx, 0);
if( !isView ){
sqliteVdbeAddOp(v, OP_Close, iCur, 0);
}
sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_BEFORE, pTab, -1,
oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
addr);
}
if( !isView ){
/* Open cursors for the table we are deleting from and all its
** indices. If there are row triggers, this happens inside the
** OP_ListRead loop because the cursor have to all be closed
** before the trigger fires. If there are no row triggers, the
** cursors are opened only once on the outside the loop.
*/
pParse->nTab = iCur + 1;
sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
sqliteVdbeAddOp(v, OP_OpenWrite, iCur, pTab->tnum);
for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
sqliteVdbeAddOp(v, OP_OpenWrite, pParse->nTab++, pIdx->tnum);
}
/* This is the beginning of the delete loop when there are no
** row triggers */
if( !row_triggers_exist ){
addr = sqliteVdbeAddOp(v, OP_ListRead, 0, end);
}
/* Delete the row */
sqliteGenerateRowDelete(db, v, pTab, iCur, pParse->trigStack==0);
}
/* If there are row triggers, close all cursors then invoke
** the AFTER triggers
*/
if( row_triggers_exist ){
if( !isView ){
for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
sqliteVdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
}
sqliteVdbeAddOp(v, OP_Close, iCur, 0);
}
sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_AFTER, pTab, -1,
oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
addr);
}
/* End of the delete loop */
sqliteVdbeAddOp(v, OP_Goto, 0, addr);
sqliteVdbeResolveLabel(v, end);
sqliteVdbeAddOp(v, OP_ListReset, 0, 0);
/* Close the cursors after the loop if there are no row triggers */
if( !row_triggers_exist ){
for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
sqliteVdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
}
sqliteVdbeAddOp(v, OP_Close, iCur, 0);
pParse->nTab = iCur;
}
}
sqliteEndWriteOperation(pParse);
/*
** Return the number of rows that were deleted.
*/
if( db->flags & SQLITE_CountRows ){
sqliteVdbeAddOp(v, OP_ColumnName, 0, 0);
sqliteVdbeChangeP3(v, -1, "rows deleted", P3_STATIC);
sqliteVdbeAddOp(v, OP_Callback, 1, 0);
}
delete_from_cleanup:
sqliteAuthContextPop(&sContext);
sqliteSrcListDelete(pTabList);
sqliteExprDelete(pWhere);
return;
}
/*
** This routine generates VDBE code that causes a single row of a
** single table to be deleted.
**
** The VDBE must be in a particular state when this routine is called.
** These are the requirements:
**
** 1. A read/write cursor pointing to pTab, the table containing the row
** to be deleted, must be opened as cursor number "base".
**
** 2. Read/write cursors for all indices of pTab must be open as
** cursor number base+i for the i-th index.
**
** 3. The record number of the row to be deleted must be on the top
** of the stack.
**
** This routine pops the top of the stack to remove the record number
** and then generates code to remove both the table record and all index
** entries that point to that record.
*/
void sqliteGenerateRowDelete(
sqlite *db, /* The database containing the index */
Vdbe *v, /* Generate code into this VDBE */
Table *pTab, /* Table containing the row to be deleted */
int iCur, /* Cursor number for the table */
int count /* Increment the row change counter */
){
int addr;
addr = sqliteVdbeAddOp(v, OP_NotExists, iCur, 0);
sqliteGenerateRowIndexDelete(db, v, pTab, iCur, 0);
sqliteVdbeAddOp(v, OP_Delete, iCur, count);
sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
}
/*
** This routine generates VDBE code that causes the deletion of all
** index entries associated with a single row of a single table.
**
** The VDBE must be in a particular state when this routine is called.
** These are the requirements:
**
** 1. A read/write cursor pointing to pTab, the table containing the row
** to be deleted, must be opened as cursor number "iCur".
**
** 2. Read/write cursors for all indices of pTab must be open as
** cursor number iCur+i for the i-th index.
**
** 3. The "iCur" cursor must be pointing to the row that is to be
** deleted.
*/
void sqliteGenerateRowIndexDelete(
sqlite *db, /* The database containing the index */
Vdbe *v, /* Generate code into this VDBE */
Table *pTab, /* Table containing the row to be deleted */
int iCur, /* Cursor number for the table */
char *aIdxUsed /* Only delete if aIdxUsed!=0 && aIdxUsed[i]!=0 */
){
int i;
Index *pIdx;
for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
int j;
if( aIdxUsed!=0 && aIdxUsed[i-1]==0 ) continue;
sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
for(j=0; j<pIdx->nColumn; j++){
int idx = pIdx->aiColumn[j];
if( idx==pTab->iPKey ){
sqliteVdbeAddOp(v, OP_Dup, j, 0);
}else{
sqliteVdbeAddOp(v, OP_Column, iCur, idx);
}
}
sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
if( db->file_format>=4 ) sqliteAddIdxKeyType(v, pIdx);
sqliteVdbeAddOp(v, OP_IdxDelete, iCur+i, 0);
}
}
--- NEW FILE: expr.c ---
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains routines used for analyzing expressions and
** for generating VDBE code that evaluates expressions in SQLite.
**
** $Id: expr.c,v 1.1 2003/08/26 15:02:44 dark-storm Exp $
*/
#include "sqliteInt.h"
#include <ctype.h>
[...1585 lines suppressed...]
pMaybe = 0;
while( p && p->nArg!=nArg ){
if( p->nArg<0 && !createFlag && (p->xFunc || p->xStep) ) pMaybe = p;
p = p->pNext;
}
if( p && !createFlag && p->xFunc==0 && p->xStep==0 ){
return 0;
}
if( p==0 && pMaybe ){
assert( createFlag==0 );
return pMaybe;
}
if( p==0 && createFlag && (p = sqliteMalloc(sizeof(*p)))!=0 ){
p->nArg = nArg;
p->pNext = pFirst;
p->dataType = pFirst ? pFirst->dataType : SQLITE_NUMERIC;
sqliteHashInsert(&db->aFunc, zName, nName, (void*)p);
}
return p;
}
--- NEW FILE: func.c ---
/*
** 2002 February 23
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the C functions that implement various SQL
** functions of SQLite.
**
** There is only one exported symbol in this file - the function
** sqliteRegisterBuildinFunctions() found at the bottom of the file.
** All other code has file scope.
**
** $Id: func.c,v 1.1 2003/08/26 15:02:44 dark-storm Exp $
*/
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include "sqliteInt.h"
#include "os.h"
/*
** Implementation of the non-aggregate min() and max() functions
*/
static void minFunc(sqlite_func *context, int argc, const char **argv){
const char *zBest;
int i;
if( argc==0 ) return;
zBest = argv[0];
if( zBest==0 ) return;
for(i=1; i<argc; i++){
if( argv[i]==0 ) return;
if( sqliteCompare(argv[i], zBest)<0 ){
zBest = argv[i];
}
}
sqlite_set_result_string(context, zBest, -1);
}
static void maxFunc(sqlite_func *context, int argc, const char **argv){
const char *zBest;
int i;
if( argc==0 ) return;
zBest = argv[0];
if( zBest==0 ) return;
for(i=1; i<argc; i++){
if( argv[i]==0 ) return;
if( sqliteCompare(argv[i], zBest)>0 ){
zBest = argv[i];
}
}
sqlite_set_result_string(context, zBest, -1);
}
/*
** Implementation of the length() function
*/
static void lengthFunc(sqlite_func *context, int argc, const char **argv){
const char *z;
int len;
assert( argc==1 );
z = argv[0];
if( z==0 ) return;
#ifdef SQLITE_UTF8
for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
#else
len = strlen(z);
#endif
sqlite_set_result_int(context, len);
}
/*
** Implementation of the abs() function
*/
static void absFunc(sqlite_func *context, int argc, const char **argv){
const char *z;
assert( argc==1 );
z = argv[0];
if( z==0 ) return;
if( z[0]=='-' && isdigit(z[1]) ) z++;
sqlite_set_result_string(context, z, -1);
}
/*
** Implementation of the substr() function
*/
static void substrFunc(sqlite_func *context, int argc, const char **argv){
const char *z;
#ifdef SQLITE_UTF8
const char *z2;
int i;
#endif
int p1, p2, len;
assert( argc==3 );
z = argv[0];
if( z==0 ) return;
p1 = atoi(argv[1]?argv[1]:0);
p2 = atoi(argv[2]?argv[2]:0);
#ifdef SQLITE_UTF8
for(len=0, z2=z; *z2; z2++){ if( (0xc0&*z2)!=0x80 ) len++; }
#else
len = strlen(z);
#endif
if( p1<0 ){
p1 += len;
if( p1<0 ){
p2 += p1;
p1 = 0;
}
}else if( p1>0 ){
p1--;
}
if( p1+p2>len ){
p2 = len-p1;
}
#ifdef SQLITE_UTF8
for(i=0; i<p1; i++){
assert( z[i] );
if( (z[i]&0xc0)==0x80 ) p1++;
}
while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
for(; i<p1+p2; i++){
assert( z[i] );
if( (z[i]&0xc0)==0x80 ) p2++;
}
while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
#endif
if( p2<0 ) p2 = 0;
sqlite_set_result_string(context, &z[p1], p2);
}
/*
** Implementation of the round() function
*/
static void roundFunc(sqlite_func *context, int argc, const char **argv){
int n;
double r;
char zBuf[100];
assert( argc==1 || argc==2 );
if( argv[0]==0 || (argc==2 && argv[1]==0) ) return;
n = argc==2 ? atoi(argv[1]) : 0;
if( n>30 ) n = 30;
if( n<0 ) n = 0;
r = atof(argv[0]);
sprintf(zBuf,"%.*f",n,r);
sqlite_set_result_string(context, zBuf, -1);
}
/*
** Implementation of the upper() and lower() SQL functions.
*/
static void upperFunc(sqlite_func *context, int argc, const char **argv){
char *z;
int i;
if( argc<1 || argv[0]==0 ) return;
z = sqlite_set_result_string(context, argv[0], -1);
if( z==0 ) return;
for(i=0; z[i]; i++){
if( islower(z[i]) ) z[i] = toupper(z[i]);
}
}
static void lowerFunc(sqlite_func *context, int argc, const char **argv){
char *z;
int i;
if( argc<1 || argv[0]==0 ) return;
z = sqlite_set_result_string(context, argv[0], -1);
if( z==0 ) return;
for(i=0; z[i]; i++){
if( isupper(z[i]) ) z[i] = tolower(z[i]);
}
}
/*
** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
** All three do the same thing. They return the first argument
** non-NULL argument.
*/
static void ifnullFunc(sqlite_func *context, int argc, const char **argv){
int i;
for(i=0; i<argc; i++){
if( argv[i] ){
sqlite_set_result_string(context, argv[i], -1);
break;
}
}
}
/*
** Implementation of random(). Return a random integer.
*/
static void randomFunc(sqlite_func *context, int argc, const char **argv){
sqlite_set_result_int(context, sqliteRandomInteger());
}
/*
** Implementation of the last_insert_rowid() SQL function. The return
** value is the same as the sqlite_last_insert_rowid() API function.
*/
static void last_insert_rowid(sqlite_func *context, int arg, const char **argv){
sqlite *db = sqlite_user_data(context);
sqlite_set_result_int(context, sqlite_last_insert_rowid(db));
}
/*
** Implementation of the like() SQL function. This function implements
** the build-in LIKE operator. The first argument to the function is the
** string and the second argument is the pattern. So, the SQL statements:
**
** A LIKE B
**
** is implemented as like(A,B).
*/
static void likeFunc(sqlite_func *context, int arg, const char **argv){
if( argv[0]==0 || argv[1]==0 ) return;
sqlite_set_result_int(context, sqliteLikeCompare(argv[0], argv[1]));
}
/*
** Implementation of the glob() SQL function. This function implements
** the build-in GLOB operator. The first argument to the function is the
** string and the second argument is the pattern. So, the SQL statements:
**
** A GLOB B
**
** is implemented as glob(A,B).
*/
static void globFunc(sqlite_func *context, int arg, const char **argv){
if( argv[0]==0 || argv[1]==0 ) return;
sqlite_set_result_int(context, sqliteGlobCompare(argv[0], argv[1]));
}
/*
** Implementation of the NULLIF(x,y) function. The result is the first
** argument if the arguments are different. The result is NULL if the
** arguments are equal to each other.
*/
static void nullifFunc(sqlite_func *context, int argc, const char **argv){
if( argv[0]!=0 && sqliteCompare(argv[0],argv[1])!=0 ){
sqlite_set_result_string(context, argv[0], -1);
}
}
/*
** Implementation of the VERSION(*) function. The result is the version
** of the SQLite library that is running.
*/
static void versionFunc(sqlite_func *context, int argc, const char **argv){
sqlite_set_result_string(context, sqlite_version, -1);
}
/*
** EXPERIMENTAL - This is not an official function. The interface may
** change. This function may disappear. Do not write code that depends
** on this function.
**
** Implementation of the QUOTE() function. This function takes a single
** argument. If the argument is numeric, the return value is the same as
** the argument. If the argument is NULL, the return value is the string
** "NULL". Otherwise, the argument is enclosed in single quotes with
** single-quote escapes.
*/
static void quoteFunc(sqlite_func *context, int argc, const char **argv){
if( argc<1 ) return;
if( argv[0]==0 ){
sqlite_set_result_string(context, "NULL", 4);
}else if( sqliteIsNumber(argv[0]) ){
sqlite_set_result_string(context, argv[0], -1);
}else{
int i,j,n;
char *z;
for(i=n=0; argv[0][i]; i++){ if( argv[0][i]=='\'' ) n++; }
z = sqliteMalloc( i+n+3 );
if( z==0 ) return;
z[0] = '\'';
for(i=0, j=1; argv[0][i]; i++){
z[j++] = argv[0][i];
if( argv[0][i]=='\'' ){
z[j++] = '\'';
}
}
z[j++] = '\'';
z[j] = 0;
sqlite_set_result_string(context, z, j);
sqliteFree(z);
}
}
#ifdef SQLITE_SOUNDEX
/*
** Compute the soundex encoding of a word.
*/
static void soundexFunc(sqlite_func *context, int argc, const char **argv){
char zResult[8];
const char *zIn;
int i, j;
static const unsigned char iCode[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
};
assert( argc==1 );
zIn = argv[0];
for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
if( zIn[i] ){
zResult[0] = toupper(zIn[i]);
for(j=1; j<4 && zIn[i]; i++){
int code = iCode[zIn[i]&0x7f];
if( code>0 ){
zResult[j++] = code + '0';
}
}
while( j<4 ){
zResult[j++] = '0';
}
zResult[j] = 0;
sqlite_set_result_string(context, zResult, 4);
}else{
sqlite_set_result_string(context, "?000", 4);
}
}
#endif
#ifdef SQLITE_TEST
/*
** This function generates a string of random characters. Used for
** generating test data.
*/
static void randStr(sqlite_func *context, int argc, const char **argv){
static const char zSrc[] =
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789"
".-!,:*^+=_|?/<> ";
int iMin, iMax, n, r, i;
char zBuf[1000];
if( argc>=1 ){
iMin = atoi(argv[0]);
if( iMin<0 ) iMin = 0;
if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
}else{
iMin = 1;
}
if( argc>=2 ){
iMax = atoi(argv[1]);
if( iMax<iMin ) iMax = iMin;
if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf);
}else{
iMax = 50;
}
n = iMin;
if( iMax>iMin ){
r = sqliteRandomInteger() & 0x7fffffff;
n += r%(iMax + 1 - iMin);
}
r = 0;
for(i=0; i<n; i++){
r = (r + sqliteRandomByte())% (sizeof(zSrc)-1);
zBuf[i] = zSrc[r];
}
zBuf[n] = 0;
sqlite_set_result_string(context, zBuf, n);
}
#endif
/*
** An instance of the following structure holds the context of a
** sum() or avg() aggregate computation.
*/
typedef struct SumCtx SumCtx;
struct SumCtx {
double sum; /* Sum of terms */
int cnt; /* Number of elements summed */
};
/*
** Routines used to compute the sum or average.
*/
static void sumStep(sqlite_func *context, int argc, const char **argv){
SumCtx *p;
if( argc<1 ) return;
p = sqlite_aggregate_context(context, sizeof(*p));
if( p && argv[0] ){
p->sum += atof(argv[0]);
p->cnt++;
}
}
static void sumFinalize(sqlite_func *context){
SumCtx *p;
p = sqlite_aggregate_context(context, sizeof(*p));
sqlite_set_result_double(context, p ? p->sum : 0.0);
}
static void avgFinalize(sqlite_func *context){
SumCtx *p;
p = sqlite_aggregate_context(context, sizeof(*p));
if( p && p->cnt>0 ){
sqlite_set_result_double(context, p->sum/(double)p->cnt);
}
}
/*
** An instance of the following structure holds the context of a
** variance or standard deviation computation.
*/
typedef struct StdDevCtx StdDevCtx;
struct StdDevCtx {
double sum; /* Sum of terms */
double sum2; /* Sum of the squares of terms */
int cnt; /* Number of terms counted */
};
#if 0 /* Omit because math library is required */
/*
** Routines used to compute the standard deviation as an aggregate.
*/
static void stdDevStep(sqlite_func *context, int argc, const char **argv){
StdDevCtx *p;
double x;
if( argc<1 ) return;
p = sqlite_aggregate_context(context, sizeof(*p));
if( p && argv[0] ){
x = atof(argv[0]);
p->sum += x;
p->sum2 += x*x;
p->cnt++;
}
}
static void stdDevFinalize(sqlite_func *context){
double rN = sqlite_aggregate_count(context);
StdDevCtx *p = sqlite_aggregate_context(context, sizeof(*p));
if( p && p->cnt>1 ){
double rCnt = cnt;
sqlite_set_result_double(context,
sqrt((p->sum2 - p->sum*p->sum/rCnt)/(rCnt-1.0)));
}
}
#endif
/*
** The following structure keeps track of state information for the
** count() aggregate function.
*/
typedef struct CountCtx CountCtx;
struct CountCtx {
int n;
};
/*
** Routines to implement the count() aggregate function.
*/
static void countStep(sqlite_func *context, int argc, const char **argv){
CountCtx *p;
p = sqlite_aggregate_context(context, sizeof(*p));
if( (argc==0 || argv[0]) && p ){
p->n++;
}
}
static void countFinalize(sqlite_func *context){
CountCtx *p;
p = sqlite_aggregate_context(context, sizeof(*p));
sqlite_set_result_int(context, p ? p->n : 0);
}
/*
** This function tracks state information for the min() and max()
** aggregate functions.
*/
typedef struct MinMaxCtx MinMaxCtx;
struct MinMaxCtx {
char *z; /* The best so far */
char zBuf[28]; /* Space that can be used for storage */
};
/*
** Routines to implement min() and max() aggregate functions.
*/
static void minStep(sqlite_func *context, int argc, const char **argv){
MinMaxCtx *p;
p = sqlite_aggregate_context(context, sizeof(*p));
if( p==0 || argc<1 || argv[0]==0 ) return;
if( p->z==0 || sqliteCompare(argv[0],p->z)<0 ){
int len;
if( p->z && p->z!=p->zBuf ){
sqliteFree(p->z);
}
len = strlen(argv[0]);
if( len < sizeof(p->zBuf) ){
p->z = p->zBuf;
}else{
p->z = sqliteMalloc( len+1 );
if( p->z==0 ) return;
}
strcpy(p->z, argv[0]);
}
}
static void maxStep(sqlite_func *context, int argc, const char **argv){
MinMaxCtx *p;
p = sqlite_aggregate_context(context, sizeof(*p));
if( p==0 || argc<1 || argv[0]==0 ) return;
if( p->z==0 || sqliteCompare(argv[0],p->z)>0 ){
int len;
if( p->z && p->z!=p->zBuf ){
sqliteFree(p->z);
}
len = strlen(argv[0]);
if( len < sizeof(p->zBuf) ){
p->z = p->zBuf;
}else{
p->z = sqliteMalloc( len+1 );
if( p->z==0 ) return;
}
strcpy(p->z, argv[0]);
}
}
static void minMaxFinalize(sqlite_func *context){
MinMaxCtx *p;
p = sqlite_aggregate_context(context, sizeof(*p));
if( p && p->z ){
sqlite_set_result_string(context, p->z, strlen(p->z));
}
if( p && p->z && p->z!=p->zBuf ){
sqliteFree(p->z);
}
}
/****************************************************************************
** Time and date functions.
**
** SQLite processes all times and dates as Julian Day numbers. The
** dates and times are stored as the number of days since noon
** in Greenwich on November 24, 4714 B.C. according to the Gregorian
** calendar system.
**
** This implement requires years to be expressed as a 4-digit number
** which means that only dates between 0000-01-01 and 9999-12-31 can
** be represented, even though julian day numbers allow a much wider
** range of dates.
**
** The Gregorian calendar system is used for all dates and times,
** even those that predate the Gregorian calendar. Historians usually
** use the Julian calendar for dates prior to 1582-10-15 and for some
** dates afterwards, depending on locale. Beware of this ...
[truncated message content] |