mirror of
https://github.com/bdnugget/php-src.git
synced 2026-11-26 10:25:41 +00:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6c0a753e7 | ||
|
|
32314dd11a | ||
|
|
bf9929b6bf | ||
|
|
81cf825db0 | ||
|
|
0b3f98f75b | ||
|
|
905c4fe3c1 | ||
|
|
e3c8fb8ee9 | ||
|
|
c9ebab4edc | ||
|
|
5a14982be6 | ||
|
|
61d7ccfb87 | ||
|
|
a9818789c3 | ||
|
|
30f8f95197 |
No files matched your search
@@ -1,2 +0,0 @@
|
||||
sqlite
|
||||
Wez Furlong
|
||||
@@ -1,28 +0,0 @@
|
||||
|
||||
LEMON="@LEMON@"
|
||||
|
||||
# sqlite has some generated source files; this specifies how to
|
||||
# build them
|
||||
|
||||
# We avoid building these last three by bundling the generated versions
|
||||
# in our release packages
|
||||
|
||||
$(srcdir)/libsqlite/src/opcodes.c: $(srcdir)/libsqlite/src/vdbe.c
|
||||
echo '/* Automatically generated file. Do not edit */' >$@
|
||||
echo 'char *sqliteOpcodeNames[] = { "???", ' >>$@
|
||||
grep '^case OP_' $< | \
|
||||
sed -e 's/^.*OP_/ "/' -e 's/:.*$$/", /' >>$@
|
||||
echo '};' >>$@
|
||||
|
||||
$(srcdir)/libsqlite/src/opcodes.h: $(srcdir)/libsqlite/src/vdbe.c
|
||||
echo '/* Automatically generated file. Do not edit */' >$@
|
||||
grep '^case OP_' $< | \
|
||||
sed -e 's/://' | \
|
||||
awk '{printf "#define %-30s %3d\n", $$2, ++cnt}' >>$@
|
||||
|
||||
$(srcdir)/libsqlite/src/sqlite.c: $(srcdir)/libsqlite/src/sqlite.h
|
||||
|
||||
$(srcdir)/libsqlite/src/parse.c: $(srcdir)/libsqlite/src/parse.y
|
||||
$(LEMON) $(srcdir)/libsqlite/src/parse.y
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
This is an extension for the SQLite Embeddable SQL Database Engine.
|
||||
http://www.sqlite.org/
|
||||
|
||||
SQLite is a C library that implements an embeddable SQL database engine.
|
||||
Programs that link with the SQLite library can have SQL database access
|
||||
without running a separate RDBMS process.
|
||||
|
||||
SQLite is not a client library used to connect to a big database server.
|
||||
SQLite is the server. The SQLite library reads and writes directly to and from
|
||||
the database files on disk
|
||||
|
||||
|
||||
|
||||
vim:tw=78:et
|
||||
@@ -1,6 +0,0 @@
|
||||
- Implement an aggregating php function handler for use in SQL statements and
|
||||
triggers etc.
|
||||
|
||||
- Make a release
|
||||
|
||||
vim:tw=78
|
||||
@@ -1,85 +0,0 @@
|
||||
dnl $Id$
|
||||
dnl config.m4 for extension sqlite
|
||||
|
||||
PHP_ARG_WITH(sqlite, for sqlite support,
|
||||
[ --with-sqlite Include sqlite support])
|
||||
|
||||
if test "$PHP_SQLITE" != "no"; then
|
||||
|
||||
if test "$PHP_SQLITE" != "yes"; then
|
||||
SEARCH_PATH="/usr/local /usr"
|
||||
SEARCH_FOR="/include/sqlite.h"
|
||||
if test -r $PHP_SQLITE/; then # path given as parameter
|
||||
SQLITE_DIR=$PHP_SQLITE
|
||||
else # search default path list
|
||||
AC_MSG_CHECKING([for sqlite files in default path])
|
||||
for i in $SEARCH_PATH ; do
|
||||
if test -r $i/$SEARCH_FOR; then
|
||||
SQLITE_DIR=$i
|
||||
AC_MSG_RESULT(found in $i)
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
if test -z "$SQLITE_DIR"; then
|
||||
AC_MSG_RESULT([not found])
|
||||
AC_MSG_ERROR([Please reinstall the sqlite distribution from http://www.sqlite.org])
|
||||
fi
|
||||
|
||||
PHP_ADD_INCLUDE($SQLITE_DIR/include)
|
||||
|
||||
LIBNAME=sqlite
|
||||
LIBSYMBOL=sqlite_open
|
||||
|
||||
PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL,
|
||||
[
|
||||
PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $SQLITE_DIR/lib, SQLITE_SHARED_LIBADD)
|
||||
AC_DEFINE(HAVE_SQLITELIB,1,[ ])
|
||||
],[
|
||||
AC_MSG_ERROR([wrong sqlite lib version or lib not found])
|
||||
],[
|
||||
-L$SQLITE_DIR/lib -lm -ldl
|
||||
])
|
||||
|
||||
PHP_SUBST(SQLITE_SHARED_LIBADD)
|
||||
PHP_NEW_EXTENSION(sqlite, sqlite.c, $ext_shared)
|
||||
else
|
||||
# use bundled library
|
||||
sources="libsqlite/src/opcodes.c
|
||||
libsqlite/src/parse.c libsqlite/src/encode.c \
|
||||
libsqlite/src/auth.c libsqlite/src/btree.c libsqlite/src/build.c \
|
||||
libsqlite/src/delete.c libsqlite/src/expr.c libsqlite/src/func.c \
|
||||
libsqlite/src/hash.c libsqlite/src/insert.c libsqlite/src/main.c \
|
||||
libsqlite/src/os.c libsqlite/src/pager.c \
|
||||
libsqlite/src/printf.c libsqlite/src/random.c \
|
||||
libsqlite/src/select.c libsqlite/src/table.c libsqlite/src/tokenize.c \
|
||||
libsqlite/src/update.c libsqlite/src/util.c libsqlite/src/vdbe.c \
|
||||
libsqlite/src/where.c libsqlite/src/trigger.c"
|
||||
|
||||
PHP_NEW_EXTENSION(sqlite, sqlite.c $sources, $ext_shared,,-I@ext_srcdir@/libsqlite/src)
|
||||
PHP_ADD_BUILD_DIR($ext_builddir/libsqlite)
|
||||
PHP_ADD_BUILD_DIR($ext_builddir/libsqlite/src)
|
||||
AC_CHECK_SIZEOF(char *,4)
|
||||
AC_DEFINE(SQLITE_PTR_SZ, SIZEOF_CHAR_P, [Size of a pointer])
|
||||
AC_DEFINE(OS_UNIX, 1, [if this is unix])
|
||||
AC_DEFINE(OS_WIN, 0, [if this is windows])
|
||||
AC_CHECK_FUNCS(usleep)
|
||||
dnl use latin 1 for now; the utf-8 handling in funcs.c uses assert(),
|
||||
dnl which is a bit silly and something we want to avoid
|
||||
SQLITE_ENCODING="iso8859"
|
||||
dnl SQLITE_ENCODING="UTF-8"
|
||||
dnl AC_DEFINE(SQLITE_UTF8,1,[if SQLite should use utf-8 encoding])
|
||||
AC_SUBST(SQLITE_ENCODING)
|
||||
|
||||
AC_PATH_PROG(LEMON,lemon,no)
|
||||
AC_SUBST(LEMON)
|
||||
|
||||
SQLITE_VERSION=`cat $ext_srcdir/libsqlite/VERSION`
|
||||
AC_SUBST(SQLITE_VERSION)
|
||||
|
||||
sed -e s/--VERS--/`cat $ext_srcdir/libsqlite/VERSION`/ -e s/--ENCODING--/$SQLITE_ENCODING/ $ext_srcdir/libsqlite/src/sqlite.h.in >$ext_srcdir/libsqlite/src/sqlite.h
|
||||
|
||||
PHP_ADD_MAKEFILE_FRAGMENT
|
||||
fi
|
||||
|
||||
fi
|
||||
@@ -1,37 +0,0 @@
|
||||
This directory contains source code to
|
||||
|
||||
SQLite: An Embeddable SQL Database Engine
|
||||
|
||||
To compile the project, first create a directory in which to place
|
||||
the build products. It is recommended, but not required, that the
|
||||
build directory be separate from the source directory. Cd into the
|
||||
build directory and then from the build directory run the configure
|
||||
script found at the root of the source tree. Then run "make".
|
||||
|
||||
For example:
|
||||
|
||||
tar xzf sqlite.tar.gz ;# Unpack the source tree into "sqlite"
|
||||
mkdir bld ;# Build will occur in a sibling directory
|
||||
cd bld ;# Change to the build directory
|
||||
../sqlite/configure ;# Run the configure script
|
||||
make ;# Run the makefile.
|
||||
|
||||
The configure script uses autoconf 2.50 and libtool. If the configure
|
||||
script does not work out for you, there is a generic makefile named
|
||||
"Makefile.linux-gcc" in the top directory of the source tree that you
|
||||
can copy and edit to suite your needs. Comments on the generic makefile
|
||||
show what changes are needed.
|
||||
|
||||
The linux binaries on the website are created using the generic makefile,
|
||||
not the configure script. The configure script is unmaintained. (You
|
||||
can volunteer to take over maintenance of the configure script, if you want!)
|
||||
The windows binaries on the website are created using MinGW32 configured
|
||||
as a cross-compiler running under Linux. For details, see the ./publish.sh
|
||||
script at the top-level of the source tree.
|
||||
|
||||
Contacts:
|
||||
|
||||
http://www.sqlite.org/
|
||||
http://www.hwaci.com/sw/sqlite/
|
||||
http://groups.yahoo.com/group/sqlite/
|
||||
drh@hwaci.com
|
||||
@@ -1 +0,0 @@
|
||||
2.8.0
|
||||
@@ -1,152 +0,0 @@
|
||||
/*
|
||||
** 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$
|
||||
*/
|
||||
#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
|
||||
** 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_READ_COLUMN
|
||||
** SQLITE_WRITE_COLUMN
|
||||
** SQLITE_DELETE_ROW
|
||||
** SQLITE_INSERT_ROW
|
||||
**
|
||||
** 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*),
|
||||
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 with an offset of base. 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 */
|
||||
int base /* Offset of pTabList relative to pExpr */
|
||||
){
|
||||
sqlite *db = pParse->db;
|
||||
int rc;
|
||||
Table *pTab;
|
||||
const char *zCol;
|
||||
if( db->xAuth==0 ) return;
|
||||
assert( pExpr->op==TK_COLUMN );
|
||||
assert( pExpr->iTable>=base && pExpr->iTable<base+pTabList->nSrc );
|
||||
pTab = pTabList->a[pExpr->iTable-base].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";
|
||||
}
|
||||
rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol);
|
||||
if( rc==SQLITE_IGNORE ){
|
||||
pExpr->op = TK_NULL;
|
||||
}else if( rc==SQLITE_DENY ){
|
||||
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
|
||||
){
|
||||
sqlite *db = pParse->db;
|
||||
int rc;
|
||||
if( db->xAuth==0 ){
|
||||
return SQLITE_OK;
|
||||
}
|
||||
rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2);
|
||||
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;
|
||||
}
|
||||
|
||||
#endif /* SQLITE_OMIT_AUTHORIZATION */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,71 +0,0 @@
|
||||
/*
|
||||
** 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$
|
||||
*/
|
||||
#ifndef _BTREE_H_
|
||||
#define _BTREE_H_
|
||||
|
||||
typedef struct Btree Btree;
|
||||
typedef struct BtCursor BtCursor;
|
||||
|
||||
int sqliteBtreeOpen(const char *zFilename, int mode, int nPg, Btree **ppBtree);
|
||||
int sqliteBtreeClose(Btree*);
|
||||
int sqliteBtreeSetCacheSize(Btree*, int);
|
||||
int sqliteBtreeSetSafetyLevel(Btree*, int);
|
||||
|
||||
int sqliteBtreeBeginTrans(Btree*);
|
||||
int sqliteBtreeCommit(Btree*);
|
||||
int sqliteBtreeRollback(Btree*);
|
||||
int sqliteBtreeBeginCkpt(Btree*);
|
||||
int sqliteBtreeCommitCkpt(Btree*);
|
||||
int sqliteBtreeRollbackCkpt(Btree*);
|
||||
|
||||
int sqliteBtreeCreateTable(Btree*, int*);
|
||||
int sqliteBtreeCreateIndex(Btree*, int*);
|
||||
int sqliteBtreeDropTable(Btree*, int);
|
||||
int sqliteBtreeClearTable(Btree*, int);
|
||||
|
||||
int sqliteBtreeCursor(Btree*, int iTable, int wrFlag, BtCursor **ppCur);
|
||||
int sqliteBtreeMoveto(BtCursor*, const void *pKey, int nKey, int *pRes);
|
||||
int sqliteBtreeDelete(BtCursor*);
|
||||
int sqliteBtreeInsert(BtCursor*, const void *pKey, int nKey,
|
||||
const void *pData, int nData);
|
||||
int sqliteBtreeFirst(BtCursor*, int *pRes);
|
||||
int sqliteBtreeLast(BtCursor*, int *pRes);
|
||||
int sqliteBtreeNext(BtCursor*, int *pRes);
|
||||
int sqliteBtreePrevious(BtCursor*, int *pRes);
|
||||
int sqliteBtreeKeySize(BtCursor*, int *pSize);
|
||||
int sqliteBtreeKey(BtCursor*, int offset, int amt, char *zBuf);
|
||||
int sqliteBtreeKeyCompare(BtCursor*, const void *pKey, int nKey,
|
||||
int nIgnore, int *pRes);
|
||||
int sqliteBtreeDataSize(BtCursor*, int *pSize);
|
||||
int sqliteBtreeData(BtCursor*, int offset, int amt, char *zBuf);
|
||||
int sqliteBtreeCloseCursor(BtCursor*);
|
||||
|
||||
#define SQLITE_N_BTREE_META 10
|
||||
int sqliteBtreeGetMeta(Btree*, int*);
|
||||
int sqliteBtreeUpdateMeta(Btree*, int*);
|
||||
|
||||
char *sqliteBtreeIntegrityCheck(Btree*, int*, int);
|
||||
|
||||
#ifdef SQLITE_TEST
|
||||
int sqliteBtreePageDump(Btree*, int, int);
|
||||
int sqliteBtreeCursorDump(BtCursor*, int*);
|
||||
struct Pager *sqliteBtreePager(Btree*);
|
||||
int btree_native_byte_order;
|
||||
#endif
|
||||
|
||||
#endif /* _BTREE_H_ */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,389 +0,0 @@
|
||||
/*
|
||||
** 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$
|
||||
*/
|
||||
#include "sqliteInt.h"
|
||||
|
||||
|
||||
/*
|
||||
** Given a table name, find the corresponding table and make sure the
|
||||
** table is writeable. Generate an error and return NULL if not. If
|
||||
** everything checks out, return a pointer to the Table structure.
|
||||
*/
|
||||
Table *sqliteTableNameToTable(Parse *pParse, const char *zTab){
|
||||
Table *pTab;
|
||||
pTab = sqliteFindTable(pParse->db, zTab);
|
||||
if( pTab==0 ){
|
||||
sqliteSetString(&pParse->zErrMsg, "no such table: ", zTab, 0);
|
||||
pParse->nErr++;
|
||||
return 0;
|
||||
}
|
||||
if( pTab->readOnly || pTab->pSelect ){
|
||||
sqliteSetString(&pParse->zErrMsg,
|
||||
pTab->pSelect ? "view " : "table ",
|
||||
zTab,
|
||||
" may not be modified", 0);
|
||||
pParse->nErr++;
|
||||
return 0;
|
||||
}
|
||||
return pTab;
|
||||
}
|
||||
|
||||
/*
|
||||
** Given a table name, check to make sure the table exists, is writable
|
||||
** and is not a view. If everything is OK, construct an SrcList holding
|
||||
** the table and return a pointer to the SrcList. The calling function
|
||||
** is responsible for freeing the SrcList when it has finished with it.
|
||||
** If there is an error, leave a message on pParse->zErrMsg and return
|
||||
** NULL.
|
||||
*/
|
||||
SrcList *sqliteTableTokenToSrcList(Parse *pParse, Token *pTableName){
|
||||
Table *pTab;
|
||||
SrcList *pTabList;
|
||||
|
||||
pTabList = sqliteSrcListAppend(0, pTableName);
|
||||
if( pTabList==0 ) return 0;
|
||||
assert( pTabList->nSrc==1 );
|
||||
pTab = sqliteTableNameToTable(pParse, pTabList->a[0].zName);
|
||||
if( pTab==0 ){
|
||||
sqliteSrcListDelete(pTabList);
|
||||
return 0;
|
||||
}
|
||||
pTabList->a[0].pTab = pTab;
|
||||
return pTabList;
|
||||
}
|
||||
|
||||
/*
|
||||
** Process a DELETE FROM statement.
|
||||
*/
|
||||
void sqliteDeleteFrom(
|
||||
Parse *pParse, /* The parser context */
|
||||
Token *pTableName, /* 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 */
|
||||
char *zTab; /* Name of the table from which we are deleting */
|
||||
SrcList *pTabList; /* A fake FROM clause holding just 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 base; /* Index of the first available table cursor */
|
||||
sqlite *db; /* Main database structure */
|
||||
int openOp; /* Opcode used to open a cursor to the table */
|
||||
|
||||
int row_triggers_exist = 0;
|
||||
int oldIdx = -1;
|
||||
|
||||
if( pParse->nErr || sqlite_malloc_failed ){
|
||||
pTabList = 0;
|
||||
goto delete_from_cleanup;
|
||||
}
|
||||
db = pParse->db;
|
||||
|
||||
/* Check for the special case of a VIEW with one or more ON DELETE triggers
|
||||
** defined
|
||||
*/
|
||||
zTab = sqliteTableNameFromToken(pTableName);
|
||||
if( zTab != 0 ){
|
||||
pTab = sqliteFindTable(pParse->db, zTab);
|
||||
if( pTab ){
|
||||
row_triggers_exist =
|
||||
sqliteTriggersExist(pParse, pTab->pTrigger,
|
||||
TK_DELETE, TK_BEFORE, TK_ROW, 0) ||
|
||||
sqliteTriggersExist(pParse, pTab->pTrigger,
|
||||
TK_DELETE, TK_AFTER, TK_ROW, 0);
|
||||
}
|
||||
sqliteFree(zTab);
|
||||
if( row_triggers_exist && pTab->pSelect ){
|
||||
/* Just fire VIEW triggers */
|
||||
sqliteViewTriggers(pParse, pTab, pWhere, OE_Replace, 0);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/* 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.
|
||||
*/
|
||||
pTabList = sqliteTableTokenToSrcList(pParse, pTableName);
|
||||
if( pTabList==0 ) goto delete_from_cleanup;
|
||||
assert( pTabList->nSrc==1 );
|
||||
pTab = pTabList->a[0].pTab;
|
||||
assert( pTab->pSelect==0 ); /* This table is not a view */
|
||||
if( sqliteAuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0) ){
|
||||
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.
|
||||
*/
|
||||
base = pParse->nTab++;
|
||||
if( pWhere ){
|
||||
if( sqliteExprResolveIds(pParse, base, pTabList, 0, pWhere) ){
|
||||
goto delete_from_cleanup;
|
||||
}
|
||||
if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
|
||||
goto delete_from_cleanup;
|
||||
}
|
||||
}
|
||||
|
||||
/* Begin generating code.
|
||||
*/
|
||||
v = sqliteGetVdbe(pParse);
|
||||
if( v==0 ){
|
||||
goto delete_from_cleanup;
|
||||
}
|
||||
sqliteBeginWriteOperation(pParse, row_triggers_exist,
|
||||
!row_triggers_exist && pTab->isTemp);
|
||||
|
||||
/* 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;
|
||||
openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
|
||||
sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
|
||||
sqliteVdbeAddOp(v, OP_Rewind, base, sqliteVdbeCurrentAddr(v)+2);
|
||||
addr = sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
|
||||
sqliteVdbeAddOp(v, OP_Next, base, addr);
|
||||
sqliteVdbeResolveLabel(v, endOfLoop);
|
||||
sqliteVdbeAddOp(v, OP_Close, base, 0);
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_Clear, pTab->tnum, pTab->isTemp);
|
||||
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
|
||||
sqliteVdbeAddOp(v, OP_Clear, pIdx->tnum, pTab->isTemp);
|
||||
}
|
||||
}
|
||||
|
||||
/* 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, base, 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);
|
||||
|
||||
/* 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);
|
||||
|
||||
openOp = pTab->isTemp ? OP_OpenAux : OP_Open;
|
||||
sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
|
||||
sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
|
||||
sqliteVdbeAddOp(v, OP_OpenTemp, oldIdx, 0);
|
||||
|
||||
sqliteVdbeAddOp(v, OP_Integer, 13, 0);
|
||||
for(i = 0; i<pTab->nCol; i++){
|
||||
if( i==pTab->iPKey ){
|
||||
sqliteVdbeAddOp(v, OP_Recno, base, 0);
|
||||
} else {
|
||||
sqliteVdbeAddOp(v, OP_Column, base, i);
|
||||
}
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
|
||||
sqliteVdbeAddOp(v, OP_PutIntKey, oldIdx, 0);
|
||||
sqliteVdbeAddOp(v, OP_Close, base, 0);
|
||||
sqliteVdbeAddOp(v, OP_Rewind, oldIdx, 0);
|
||||
|
||||
sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_BEFORE, pTab, -1,
|
||||
oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
|
||||
addr);
|
||||
}
|
||||
|
||||
/* 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 = base + 1;
|
||||
openOp = pTab->isTemp ? OP_OpenWrAux : OP_OpenWrite;
|
||||
sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
|
||||
for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
|
||||
sqliteVdbeAddOp(v, openOp, 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, base, pParse->trigStack==0);
|
||||
|
||||
/* If there are row triggers, close all cursors then invoke
|
||||
** the AFTER triggers
|
||||
*/
|
||||
if( row_triggers_exist ){
|
||||
for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
|
||||
sqliteVdbeAddOp(v, OP_Close, base + i, pIdx->tnum);
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_Close, base, 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, base + i, pIdx->tnum);
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_Close, base, 0);
|
||||
pParse->nTab = base;
|
||||
}
|
||||
}
|
||||
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:
|
||||
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 base, /* Cursor number for the table */
|
||||
int count /* Increment the row change counter */
|
||||
){
|
||||
int addr;
|
||||
addr = sqliteVdbeAddOp(v, OP_NotExists, base, 0);
|
||||
sqliteGenerateRowIndexDelete(db, v, pTab, base, 0);
|
||||
sqliteVdbeAddOp(v, OP_Delete, base, 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 "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 "base" 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 base, /* 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, base, 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, base, idx);
|
||||
}
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
|
||||
if( db->file_format>=4 ) sqliteAddIdxKeyType(v, pIdx);
|
||||
sqliteVdbeAddOp(v, OP_IdxDelete, base+i, 0);
|
||||
}
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
/*
|
||||
** 2002 April 25
|
||||
**
|
||||
** 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 helper routines used to translate binary data into
|
||||
** a null-terminated string (suitable for use in SQLite) and back again.
|
||||
** These are convenience routines for use by people who want to store binary
|
||||
** data in an SQLite database. The code in this file is not used by any other
|
||||
** part of the SQLite library.
|
||||
**
|
||||
** $Id$
|
||||
*/
|
||||
#include <string.h>
|
||||
|
||||
/*
|
||||
** Encode a binary buffer "in" of size n bytes so that it contains
|
||||
** no instances of characters '\'' or '\000'. The output is
|
||||
** null-terminated and can be used as a string value in an INSERT
|
||||
** or UPDATE statement. Use sqlite_decode_binary() to convert the
|
||||
** string back into its original binary.
|
||||
**
|
||||
** The result is written into a preallocated output buffer "out".
|
||||
** "out" must be able to hold at least (256*n + 1262)/253 bytes.
|
||||
** In other words, the output will be expanded by as much as 3
|
||||
** bytes for every 253 bytes of input plus 2 bytes of fixed overhead.
|
||||
** (This is approximately 2 + 1.019*n or about a 2% size increase.)
|
||||
**
|
||||
** The return value is the number of characters in the encoded
|
||||
** string, excluding the "\000" terminator.
|
||||
*/
|
||||
int sqlite_encode_binary(const unsigned char *in, int n, unsigned char *out){
|
||||
int i, j, e, m;
|
||||
int cnt[256];
|
||||
if( n<=0 ){
|
||||
out[0] = 'x';
|
||||
out[1] = 0;
|
||||
return 1;
|
||||
}
|
||||
memset(cnt, 0, sizeof(cnt));
|
||||
for(i=n-1; i>=0; i--){ cnt[in[i]]++; }
|
||||
m = n;
|
||||
for(i=1; i<256; i++){
|
||||
int sum;
|
||||
if( i=='\'' ) continue;
|
||||
sum = cnt[i] + cnt[(i+1)&0xff] + cnt[(i+'\'')&0xff];
|
||||
if( sum<m ){
|
||||
m = sum;
|
||||
e = i;
|
||||
if( m==0 ) break;
|
||||
}
|
||||
}
|
||||
out[0] = e;
|
||||
j = 1;
|
||||
for(i=0; i<n; i++){
|
||||
int c = (in[i] - e)&0xff;
|
||||
if( c==0 ){
|
||||
out[j++] = 1;
|
||||
out[j++] = 1;
|
||||
}else if( c==1 ){
|
||||
out[j++] = 1;
|
||||
out[j++] = 2;
|
||||
}else if( c=='\'' ){
|
||||
out[j++] = 1;
|
||||
out[j++] = 3;
|
||||
}else{
|
||||
out[j++] = c;
|
||||
}
|
||||
}
|
||||
out[j] = 0;
|
||||
return j;
|
||||
}
|
||||
|
||||
/*
|
||||
** Decode the string "in" into binary data and write it into "out".
|
||||
** This routine reverses the encoded created by sqlite_encode_binary().
|
||||
** The output will always be a few bytes less than the input. The number
|
||||
** of bytes of output is returned. If the input is not a well-formed
|
||||
** encoding, -1 is returned.
|
||||
**
|
||||
** The "in" and "out" parameters may point to the same buffer in order
|
||||
** to decode a string in place.
|
||||
*/
|
||||
int sqlite_decode_binary(const unsigned char *in, unsigned char *out){
|
||||
int i, c, e;
|
||||
e = *(in++);
|
||||
i = 0;
|
||||
while( (c = *(in++))!=0 ){
|
||||
if( c==1 ){
|
||||
c = *(in++);
|
||||
if( c==1 ){
|
||||
c = 0;
|
||||
}else if( c==2 ){
|
||||
c = 1;
|
||||
}else if( c==3 ){
|
||||
c = '\'';
|
||||
}else{
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
out[i++] = (c + e)&0xff;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
#ifdef ENCODER_TEST
|
||||
/*
|
||||
** The subroutines above are not tested by the usual test suite. To test
|
||||
** these routines, compile just this one file with a -DENCODER_TEST=1 option
|
||||
** and run the result.
|
||||
*/
|
||||
int main(int argc, char **argv){
|
||||
int i, j, n, m, nOut;
|
||||
unsigned char in[30000];
|
||||
unsigned char out[33000];
|
||||
|
||||
for(i=0; i<sizeof(in); i++){
|
||||
printf("Test %d: ", i+1);
|
||||
n = rand() % (i+1);
|
||||
if( i%100==0 ){
|
||||
int k;
|
||||
for(j=k=0; j<n; j++){
|
||||
/* if( k==0 || k=='\'' ) k++; */
|
||||
in[j] = k;
|
||||
k = (k+1)&0xff;
|
||||
}
|
||||
}else{
|
||||
for(j=0; j<n; j++) in[j] = rand() & 0xff;
|
||||
}
|
||||
nOut = sqlite_encode_binary(in, n, out);
|
||||
if( nOut!=strlen(out) ){
|
||||
printf(" ERROR return value is %d instead of %d\n", nOut, strlen(out));
|
||||
exit(1);
|
||||
}
|
||||
m = (256*n + 1262)/253;
|
||||
printf("size %d->%d (max %d)", n, strlen(out)+1, m);
|
||||
if( strlen(out)+1>m ){
|
||||
printf(" ERROR output too big\n");
|
||||
exit(1);
|
||||
}
|
||||
for(j=0; out[j]; j++){
|
||||
if( out[j]=='\'' ){
|
||||
printf(" ERROR contains (')\n");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
j = sqlite_decode_binary(out, out);
|
||||
if( j!=n ){
|
||||
printf(" ERROR decode size %d\n", j);
|
||||
exit(1);
|
||||
}
|
||||
if( memcmp(in, out, n)!=0 ){
|
||||
printf(" ERROR decode mismatch\n");
|
||||
exit(1);
|
||||
}
|
||||
printf(" OK\n");
|
||||
}
|
||||
}
|
||||
#endif /* ENCODER_TEST */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,531 +0,0 @@
|
||||
/*
|
||||
** 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$
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
#include <assert.h>
|
||||
#include "sqliteInt.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);
|
||||
}
|
||||
|
||||
#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();
|
||||
if( r<0 ) r = -r;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
** This function registered all of the above C functions as SQL
|
||||
** functions. This should be the only routine in this file with
|
||||
** external linkage.
|
||||
*/
|
||||
void sqliteRegisterBuiltinFunctions(sqlite *db){
|
||||
static struct {
|
||||
char *zName;
|
||||
int nArg;
|
||||
int dataType;
|
||||
void (*xFunc)(sqlite_func*,int,const char**);
|
||||
} aFuncs[] = {
|
||||
{ "min", -1, SQLITE_ARGS, minFunc },
|
||||
{ "min", 0, 0, 0 },
|
||||
{ "max", -1, SQLITE_ARGS, maxFunc },
|
||||
{ "max", 0, 0, 0 },
|
||||
{ "length", 1, SQLITE_NUMERIC, lengthFunc },
|
||||
{ "substr", 3, SQLITE_TEXT, substrFunc },
|
||||
{ "abs", 1, SQLITE_NUMERIC, absFunc },
|
||||
{ "round", 1, SQLITE_NUMERIC, roundFunc },
|
||||
{ "round", 2, SQLITE_NUMERIC, roundFunc },
|
||||
{ "upper", 1, SQLITE_TEXT, upperFunc },
|
||||
{ "lower", 1, SQLITE_TEXT, lowerFunc },
|
||||
{ "coalesce", -1, SQLITE_ARGS, ifnullFunc },
|
||||
{ "coalesce", 0, 0, 0 },
|
||||
{ "coalesce", 1, 0, 0 },
|
||||
{ "ifnull", 2, SQLITE_ARGS, ifnullFunc },
|
||||
{ "random", -1, SQLITE_NUMERIC, randomFunc },
|
||||
{ "like", 2, SQLITE_NUMERIC, likeFunc },
|
||||
{ "glob", 2, SQLITE_NUMERIC, globFunc },
|
||||
{ "nullif", 2, SQLITE_ARGS, nullifFunc },
|
||||
{ "sqlite_version",0,SQLITE_TEXT, versionFunc},
|
||||
#ifdef SQLITE_TEST
|
||||
{ "randstr", 2, SQLITE_TEXT, randStr },
|
||||
#endif
|
||||
};
|
||||
static struct {
|
||||
char *zName;
|
||||
int nArg;
|
||||
int dataType;
|
||||
void (*xStep)(sqlite_func*,int,const char**);
|
||||
void (*xFinalize)(sqlite_func*);
|
||||
} aAggs[] = {
|
||||
{ "min", 1, 0, minStep, minMaxFinalize },
|
||||
{ "max", 1, 0, maxStep, minMaxFinalize },
|
||||
{ "sum", 1, SQLITE_NUMERIC, sumStep, sumFinalize },
|
||||
{ "avg", 1, SQLITE_NUMERIC, sumStep, avgFinalize },
|
||||
{ "count", 0, SQLITE_NUMERIC, countStep, countFinalize },
|
||||
{ "count", 1, SQLITE_NUMERIC, countStep, countFinalize },
|
||||
#if 0
|
||||
{ "stddev", 1, SQLITE_NUMERIC, stdDevStep, stdDevFinalize },
|
||||
#endif
|
||||
};
|
||||
int i;
|
||||
|
||||
for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
|
||||
sqlite_create_function(db, aFuncs[i].zName,
|
||||
aFuncs[i].nArg, aFuncs[i].xFunc, 0);
|
||||
if( aFuncs[i].xFunc ){
|
||||
sqlite_function_type(db, aFuncs[i].zName, aFuncs[i].dataType);
|
||||
}
|
||||
}
|
||||
sqlite_create_function(db, "last_insert_rowid", 0,
|
||||
last_insert_rowid, db);
|
||||
sqlite_function_type(db, "last_insert_rowid", SQLITE_NUMERIC);
|
||||
for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
|
||||
sqlite_create_aggregate(db, aAggs[i].zName,
|
||||
aAggs[i].nArg, aAggs[i].xStep, aAggs[i].xFinalize, 0);
|
||||
sqlite_function_type(db, aAggs[i].zName, aAggs[i].dataType);
|
||||
}
|
||||
}
|
||||
@@ -1,355 +0,0 @@
|
||||
/*
|
||||
** 2001 September 22
|
||||
**
|
||||
** 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 is the implementation of generic hash-tables
|
||||
** used in SQLite.
|
||||
**
|
||||
** $Id$
|
||||
*/
|
||||
#include "sqliteInt.h"
|
||||
#include <assert.h>
|
||||
|
||||
/* Turn bulk memory into a hash table object by initializing the
|
||||
** fields of the Hash structure.
|
||||
**
|
||||
** "new" is a pointer to the hash table that is to be initialized.
|
||||
** keyClass is one of the constants SQLITE_HASH_INT, SQLITE_HASH_POINTER,
|
||||
** SQLITE_HASH_BINARY, or SQLITE_HASH_STRING. The value of keyClass
|
||||
** determines what kind of key the hash table will use. "copyKey" is
|
||||
** true if the hash table should make its own private copy of keys and
|
||||
** false if it should just use the supplied pointer. CopyKey only makes
|
||||
** sense for SQLITE_HASH_STRING and SQLITE_HASH_BINARY and is ignored
|
||||
** for other key classes.
|
||||
*/
|
||||
void sqliteHashInit(Hash *new, int keyClass, int copyKey){
|
||||
assert( new!=0 );
|
||||
assert( keyClass>=SQLITE_HASH_INT && keyClass<=SQLITE_HASH_BINARY );
|
||||
new->keyClass = keyClass;
|
||||
new->copyKey = copyKey &&
|
||||
(keyClass==SQLITE_HASH_STRING || keyClass==SQLITE_HASH_BINARY);
|
||||
new->first = 0;
|
||||
new->count = 0;
|
||||
new->htsize = 0;
|
||||
new->ht = 0;
|
||||
}
|
||||
|
||||
/* Remove all entries from a hash table. Reclaim all memory.
|
||||
** Call this routine to delete a hash table or to reset a hash table
|
||||
** to the empty state.
|
||||
*/
|
||||
void sqliteHashClear(Hash *pH){
|
||||
HashElem *elem; /* For looping over all elements of the table */
|
||||
|
||||
assert( pH!=0 );
|
||||
elem = pH->first;
|
||||
pH->first = 0;
|
||||
if( pH->ht ) sqliteFree(pH->ht);
|
||||
pH->ht = 0;
|
||||
pH->htsize = 0;
|
||||
while( elem ){
|
||||
HashElem *next_elem = elem->next;
|
||||
if( pH->copyKey && elem->pKey ){
|
||||
sqliteFree(elem->pKey);
|
||||
}
|
||||
sqliteFree(elem);
|
||||
elem = next_elem;
|
||||
}
|
||||
pH->count = 0;
|
||||
}
|
||||
|
||||
/*
|
||||
** Hash and comparison functions when the mode is SQLITE_HASH_INT
|
||||
*/
|
||||
static int intHash(const void *pKey, int nKey){
|
||||
return nKey ^ (nKey<<8) ^ (nKey>>8);
|
||||
}
|
||||
static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2){
|
||||
return n2 - n1;
|
||||
}
|
||||
|
||||
/*
|
||||
** Hash and comparison functions when the mode is SQLITE_HASH_POINTER
|
||||
*/
|
||||
static int ptrHash(const void *pKey, int nKey){
|
||||
uptr x = Addr(pKey);
|
||||
return x ^ (x<<8) ^ (x>>8);
|
||||
}
|
||||
static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
|
||||
if( pKey1==pKey2 ) return 0;
|
||||
if( pKey1<pKey2 ) return -1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
** Hash and comparison functions when the mode is SQLITE_HASH_STRING
|
||||
*/
|
||||
static int strHash(const void *pKey, int nKey){
|
||||
return sqliteHashNoCase((const char*)pKey, nKey);
|
||||
}
|
||||
static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
|
||||
if( n1!=n2 ) return n2-n1;
|
||||
return sqliteStrNICmp((const char*)pKey1,(const char*)pKey2,n1);
|
||||
}
|
||||
|
||||
/*
|
||||
** Hash and comparison functions when the mode is SQLITE_HASH_BINARY
|
||||
*/
|
||||
static int binHash(const void *pKey, int nKey){
|
||||
int h = 0;
|
||||
const char *z = (const char *)pKey;
|
||||
while( nKey-- > 0 ){
|
||||
h = (h<<3) ^ h ^ *(z++);
|
||||
}
|
||||
if( h<0 ) h = -h;
|
||||
return h;
|
||||
}
|
||||
static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
|
||||
if( n1!=n2 ) return n2-n1;
|
||||
return memcmp(pKey1,pKey2,n1);
|
||||
}
|
||||
|
||||
/*
|
||||
** Return a pointer to the appropriate hash function given the key class.
|
||||
**
|
||||
** The C syntax in this function definition may be unfamilar to some
|
||||
** programmers, so we provide the following additional explanation:
|
||||
**
|
||||
** The name of the function is "hashFunction". The function takes a
|
||||
** single parameter "keyClass". The return value of hashFunction()
|
||||
** is a pointer to another function. Specifically, the return value
|
||||
** of hashFunction() is a pointer to a function that takes two parameters
|
||||
** with types "const void*" and "int" and returns an "int".
|
||||
*/
|
||||
static int (*hashFunction(int keyClass))(const void*,int){
|
||||
switch( keyClass ){
|
||||
case SQLITE_HASH_INT: return &intHash;
|
||||
case SQLITE_HASH_POINTER: return &ptrHash;
|
||||
case SQLITE_HASH_STRING: return &strHash;
|
||||
case SQLITE_HASH_BINARY: return &binHash;;
|
||||
default: break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
** Return a pointer to the appropriate hash function given the key class.
|
||||
**
|
||||
** For help in interpreted the obscure C code in the function definition,
|
||||
** see the header comment on the previous function.
|
||||
*/
|
||||
static int (*compareFunction(int keyClass))(const void*,int,const void*,int){
|
||||
switch( keyClass ){
|
||||
case SQLITE_HASH_INT: return &intCompare;
|
||||
case SQLITE_HASH_POINTER: return &ptrCompare;
|
||||
case SQLITE_HASH_STRING: return &strCompare;
|
||||
case SQLITE_HASH_BINARY: return &binCompare;
|
||||
default: break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
/* Resize the hash table so that it cantains "new_size" buckets.
|
||||
** "new_size" must be a power of 2. The hash table might fail
|
||||
** to resize if sqliteMalloc() fails.
|
||||
*/
|
||||
static void rehash(Hash *pH, int new_size){
|
||||
struct _ht *new_ht; /* The new hash table */
|
||||
HashElem *elem, *next_elem; /* For looping over existing elements */
|
||||
HashElem *x; /* Element being copied to new hash table */
|
||||
int (*xHash)(const void*,int); /* The hash function */
|
||||
|
||||
assert( (new_size & (new_size-1))==0 );
|
||||
new_ht = (struct _ht *)sqliteMalloc( new_size*sizeof(struct _ht) );
|
||||
if( new_ht==0 ) return;
|
||||
if( pH->ht ) sqliteFree(pH->ht);
|
||||
pH->ht = new_ht;
|
||||
pH->htsize = new_size;
|
||||
xHash = hashFunction(pH->keyClass);
|
||||
for(elem=pH->first, pH->first=0; elem; elem = next_elem){
|
||||
int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
|
||||
next_elem = elem->next;
|
||||
x = new_ht[h].chain;
|
||||
if( x ){
|
||||
elem->next = x;
|
||||
elem->prev = x->prev;
|
||||
if( x->prev ) x->prev->next = elem;
|
||||
else pH->first = elem;
|
||||
x->prev = elem;
|
||||
}else{
|
||||
elem->next = pH->first;
|
||||
if( pH->first ) pH->first->prev = elem;
|
||||
elem->prev = 0;
|
||||
pH->first = elem;
|
||||
}
|
||||
new_ht[h].chain = elem;
|
||||
new_ht[h].count++;
|
||||
}
|
||||
}
|
||||
|
||||
/* This function (for internal use only) locates an element in an
|
||||
** hash table that matches the given key. The hash for this key has
|
||||
** already been computed and is passed as the 4th parameter.
|
||||
*/
|
||||
static HashElem *findElementGivenHash(
|
||||
const Hash *pH, /* The pH to be searched */
|
||||
const void *pKey, /* The key we are searching for */
|
||||
int nKey,
|
||||
int h /* The hash for this key. */
|
||||
){
|
||||
HashElem *elem; /* Used to loop thru the element list */
|
||||
int count; /* Number of elements left to test */
|
||||
int (*xCompare)(const void*,int,const void*,int); /* comparison function */
|
||||
|
||||
if( pH->ht ){
|
||||
elem = pH->ht[h].chain;
|
||||
count = pH->ht[h].count;
|
||||
xCompare = compareFunction(pH->keyClass);
|
||||
while( count-- && elem ){
|
||||
if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
|
||||
return elem;
|
||||
}
|
||||
elem = elem->next;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Remove a single entry from the hash table given a pointer to that
|
||||
** element and a hash on the element's key.
|
||||
*/
|
||||
static void removeElementGivenHash(
|
||||
Hash *pH, /* The pH containing "elem" */
|
||||
HashElem* elem, /* The element to be removed from the pH */
|
||||
int h /* Hash value for the element */
|
||||
){
|
||||
if( elem->prev ){
|
||||
elem->prev->next = elem->next;
|
||||
}else{
|
||||
pH->first = elem->next;
|
||||
}
|
||||
if( elem->next ){
|
||||
elem->next->prev = elem->prev;
|
||||
}
|
||||
if( pH->ht[h].chain==elem ){
|
||||
pH->ht[h].chain = elem->next;
|
||||
}
|
||||
pH->ht[h].count--;
|
||||
if( pH->ht[h].count<=0 ){
|
||||
pH->ht[h].chain = 0;
|
||||
}
|
||||
if( pH->copyKey && elem->pKey ){
|
||||
sqliteFree(elem->pKey);
|
||||
}
|
||||
sqliteFree( elem );
|
||||
pH->count--;
|
||||
}
|
||||
|
||||
/* Attempt to locate an element of the hash table pH with a key
|
||||
** that matches pKey,nKey. Return the data for this element if it is
|
||||
** found, or NULL if there is no match.
|
||||
*/
|
||||
void *sqliteHashFind(const Hash *pH, const void *pKey, int nKey){
|
||||
int h; /* A hash on key */
|
||||
HashElem *elem; /* The element that matches key */
|
||||
int (*xHash)(const void*,int); /* The hash function */
|
||||
|
||||
if( pH==0 || pH->ht==0 ) return 0;
|
||||
xHash = hashFunction(pH->keyClass);
|
||||
assert( xHash!=0 );
|
||||
h = (*xHash)(pKey,nKey);
|
||||
assert( (pH->htsize & (pH->htsize-1))==0 );
|
||||
elem = findElementGivenHash(pH,pKey,nKey, h & (pH->htsize-1));
|
||||
return elem ? elem->data : 0;
|
||||
}
|
||||
|
||||
/* Insert an element into the hash table pH. The key is pKey,nKey
|
||||
** and the data is "data".
|
||||
**
|
||||
** If no element exists with a matching key, then a new
|
||||
** element is created. A copy of the key is made if the copyKey
|
||||
** flag is set. NULL is returned.
|
||||
**
|
||||
** If another element already exists with the same key, then the
|
||||
** new data replaces the old data and the old data is returned.
|
||||
** The key is not copied in this instance. If a malloc fails, then
|
||||
** the new data is returned and the hash table is unchanged.
|
||||
**
|
||||
** If the "data" parameter to this function is NULL, then the
|
||||
** element corresponding to "key" is removed from the hash table.
|
||||
*/
|
||||
void *sqliteHashInsert(Hash *pH, const void *pKey, int nKey, void *data){
|
||||
int hraw; /* Raw hash value of the key */
|
||||
int h; /* the hash of the key modulo hash table size */
|
||||
HashElem *elem; /* Used to loop thru the element list */
|
||||
HashElem *new_elem; /* New element added to the pH */
|
||||
int (*xHash)(const void*,int); /* The hash function */
|
||||
|
||||
assert( pH!=0 );
|
||||
xHash = hashFunction(pH->keyClass);
|
||||
assert( xHash!=0 );
|
||||
hraw = (*xHash)(pKey, nKey);
|
||||
assert( (pH->htsize & (pH->htsize-1))==0 );
|
||||
h = hraw & (pH->htsize-1);
|
||||
elem = findElementGivenHash(pH,pKey,nKey,h);
|
||||
if( elem ){
|
||||
void *old_data = elem->data;
|
||||
if( data==0 ){
|
||||
removeElementGivenHash(pH,elem,h);
|
||||
}else{
|
||||
elem->data = data;
|
||||
}
|
||||
return old_data;
|
||||
}
|
||||
if( data==0 ) return 0;
|
||||
new_elem = (HashElem*)sqliteMalloc( sizeof(HashElem) );
|
||||
if( new_elem==0 ) return data;
|
||||
if( pH->copyKey && pKey!=0 ){
|
||||
new_elem->pKey = sqliteMallocRaw( nKey );
|
||||
if( new_elem->pKey==0 ){
|
||||
sqliteFree(new_elem);
|
||||
return data;
|
||||
}
|
||||
memcpy((void*)new_elem->pKey, pKey, nKey);
|
||||
}else{
|
||||
new_elem->pKey = (void*)pKey;
|
||||
}
|
||||
new_elem->nKey = nKey;
|
||||
pH->count++;
|
||||
if( pH->htsize==0 ) rehash(pH,8);
|
||||
if( pH->htsize==0 ){
|
||||
pH->count = 0;
|
||||
sqliteFree(new_elem);
|
||||
return data;
|
||||
}
|
||||
if( pH->count > pH->htsize ){
|
||||
rehash(pH,pH->htsize*2);
|
||||
}
|
||||
assert( (pH->htsize & (pH->htsize-1))==0 );
|
||||
h = hraw & (pH->htsize-1);
|
||||
elem = pH->ht[h].chain;
|
||||
if( elem ){
|
||||
new_elem->next = elem;
|
||||
new_elem->prev = elem->prev;
|
||||
if( elem->prev ){ elem->prev->next = new_elem; }
|
||||
else { pH->first = new_elem; }
|
||||
elem->prev = new_elem;
|
||||
}else{
|
||||
new_elem->next = pH->first;
|
||||
new_elem->prev = 0;
|
||||
if( pH->first ){ pH->first->prev = new_elem; }
|
||||
pH->first = new_elem;
|
||||
}
|
||||
pH->ht[h].count++;
|
||||
pH->ht[h].chain = new_elem;
|
||||
new_elem->data = data;
|
||||
return 0;
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
/*
|
||||
** 2001 September 22
|
||||
**
|
||||
** 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 is the header file for the generic hash-table implemenation
|
||||
** used in SQLite.
|
||||
**
|
||||
** $Id$
|
||||
*/
|
||||
#ifndef _SQLITE_HASH_H_
|
||||
#define _SQLITE_HASH_H_
|
||||
|
||||
/* Forward declarations of structures. */
|
||||
typedef struct Hash Hash;
|
||||
typedef struct HashElem HashElem;
|
||||
|
||||
/* A complete hash table is an instance of the following structure.
|
||||
** The internals of this structure are intended to be opaque -- client
|
||||
** code should not attempt to access or modify the fields of this structure
|
||||
** directly. Change this structure only by using the routines below.
|
||||
** However, many of the "procedures" and "functions" for modifying and
|
||||
** accessing this structure are really macros, so we can't really make
|
||||
** this structure opaque.
|
||||
*/
|
||||
struct Hash {
|
||||
char keyClass; /* SQLITE_HASH_INT, _POINTER, _STRING, _BINARY */
|
||||
char copyKey; /* True if copy of key made on insert */
|
||||
int count; /* Number of entries in this table */
|
||||
HashElem *first; /* The first element of the array */
|
||||
int htsize; /* Number of buckets in the hash table */
|
||||
struct _ht { /* the hash table */
|
||||
int count; /* Number of entries with this hash */
|
||||
HashElem *chain; /* Pointer to first entry with this hash */
|
||||
} *ht;
|
||||
};
|
||||
|
||||
/* Each element in the hash table is an instance of the following
|
||||
** structure. All elements are stored on a single doubly-linked list.
|
||||
**
|
||||
** Again, this structure is intended to be opaque, but it can't really
|
||||
** be opaque because it is used by macros.
|
||||
*/
|
||||
struct HashElem {
|
||||
HashElem *next, *prev; /* Next and previous elements in the table */
|
||||
void *data; /* Data associated with this element */
|
||||
void *pKey; int nKey; /* Key associated with this element */
|
||||
};
|
||||
|
||||
/*
|
||||
** There are 4 different modes of operation for a hash table:
|
||||
**
|
||||
** SQLITE_HASH_INT nKey is used as the key and pKey is ignored.
|
||||
**
|
||||
** SQLITE_HASH_POINTER pKey is used as the key and nKey is ignored.
|
||||
**
|
||||
** SQLITE_HASH_STRING pKey points to a string that is nKey bytes long
|
||||
** (including the null-terminator, if any). Case
|
||||
** is ignored in comparisons.
|
||||
**
|
||||
** SQLITE_HASH_BINARY pKey points to binary data nKey bytes long.
|
||||
** memcmp() is used to compare keys.
|
||||
**
|
||||
** A copy of the key is made for SQLITE_HASH_STRING and SQLITE_HASH_BINARY
|
||||
** if the copyKey parameter to HashInit is 1.
|
||||
*/
|
||||
#define SQLITE_HASH_INT 1
|
||||
#define SQLITE_HASH_POINTER 2
|
||||
#define SQLITE_HASH_STRING 3
|
||||
#define SQLITE_HASH_BINARY 4
|
||||
|
||||
/*
|
||||
** Access routines. To delete, insert a NULL pointer.
|
||||
*/
|
||||
void sqliteHashInit(Hash*, int keytype, int copyKey);
|
||||
void *sqliteHashInsert(Hash*, const void *pKey, int nKey, void *pData);
|
||||
void *sqliteHashFind(const Hash*, const void *pKey, int nKey);
|
||||
void sqliteHashClear(Hash*);
|
||||
|
||||
/*
|
||||
** Macros for looping over all elements of a hash table. The idiom is
|
||||
** like this:
|
||||
**
|
||||
** Hash h;
|
||||
** HashElem *p;
|
||||
** ...
|
||||
** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
|
||||
** SomeStructure *pData = sqliteHashData(p);
|
||||
** // do something with pData
|
||||
** }
|
||||
*/
|
||||
#define sqliteHashFirst(H) ((H)->first)
|
||||
#define sqliteHashNext(E) ((E)->next)
|
||||
#define sqliteHashData(E) ((E)->data)
|
||||
#define sqliteHashKey(E) ((E)->pKey)
|
||||
#define sqliteHashKeysize(E) ((E)->nKey)
|
||||
|
||||
/*
|
||||
** Number of entries in a hash table
|
||||
*/
|
||||
#define sqliteHashCount(H) ((H)->count)
|
||||
|
||||
#endif /* _SQLITE_HASH_H_ */
|
||||
@@ -1,832 +0,0 @@
|
||||
/*
|
||||
** 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 INSERT statements in SQLite.
|
||||
**
|
||||
** $Id$
|
||||
*/
|
||||
#include "sqliteInt.h"
|
||||
|
||||
/*
|
||||
** This routine is call to handle SQL of the following forms:
|
||||
**
|
||||
** insert into TABLE (IDLIST) values(EXPRLIST)
|
||||
** insert into TABLE (IDLIST) select
|
||||
**
|
||||
** The IDLIST following the table name is always optional. If omitted,
|
||||
** then a list of all columns for the table is substituted. The IDLIST
|
||||
** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
|
||||
**
|
||||
** The pList parameter holds EXPRLIST in the first form of the INSERT
|
||||
** statement above, and pSelect is NULL. For the second form, pList is
|
||||
** NULL and pSelect is a pointer to the select statement used to generate
|
||||
** data for the insert.
|
||||
**
|
||||
** The code generated follows one of three templates. For a simple
|
||||
** select with data coming from a VALUES clause, the code executes
|
||||
** once straight down through. The template looks like this:
|
||||
**
|
||||
** open write cursor to <table> and its indices
|
||||
** puts VALUES clause expressions onto the stack
|
||||
** write the resulting record into <table>
|
||||
** cleanup
|
||||
**
|
||||
** If the statement is of the form
|
||||
**
|
||||
** INSERT INTO <table> SELECT ...
|
||||
**
|
||||
** And the SELECT clause does not read from <table> at any time, then
|
||||
** the generated code follows this template:
|
||||
**
|
||||
** goto B
|
||||
** A: setup for the SELECT
|
||||
** loop over the tables in the SELECT
|
||||
** gosub C
|
||||
** end loop
|
||||
** cleanup after the SELECT
|
||||
** goto D
|
||||
** B: open write cursor to <table> and its indices
|
||||
** goto A
|
||||
** C: insert the select result into <table>
|
||||
** return
|
||||
** D: cleanup
|
||||
**
|
||||
** The third template is used if the insert statement takes its
|
||||
** values from a SELECT but the data is being inserted into a table
|
||||
** that is also read as part of the SELECT. In the third form,
|
||||
** we have to use a intermediate table to store the results of
|
||||
** the select. The template is like this:
|
||||
**
|
||||
** goto B
|
||||
** A: setup for the SELECT
|
||||
** loop over the tables in the SELECT
|
||||
** gosub C
|
||||
** end loop
|
||||
** cleanup after the SELECT
|
||||
** goto D
|
||||
** C: insert the select result into the intermediate table
|
||||
** return
|
||||
** B: open a cursor to an intermediate table
|
||||
** goto A
|
||||
** D: open write cursor to <table> and its indices
|
||||
** loop over the intermediate table
|
||||
** transfer values form intermediate table into <table>
|
||||
** end the loop
|
||||
** cleanup
|
||||
*/
|
||||
void sqliteInsert(
|
||||
Parse *pParse, /* Parser context */
|
||||
Token *pTableName, /* Name of table into which we are inserting */
|
||||
ExprList *pList, /* List of values to be inserted */
|
||||
Select *pSelect, /* A SELECT statement to use as the data source */
|
||||
IdList *pColumn, /* Column names corresponding to IDLIST. */
|
||||
int onError /* How to handle constraint errors */
|
||||
){
|
||||
Table *pTab; /* The table to insert into */
|
||||
char *zTab = 0; /* Name of the table into which we are inserting */
|
||||
int i, j, idx; /* Loop counters */
|
||||
Vdbe *v; /* Generate code into this virtual machine */
|
||||
Index *pIdx; /* For looping over indices of the table */
|
||||
int nColumn; /* Number of columns in the data */
|
||||
int base; /* First available cursor */
|
||||
int iCont, iBreak; /* Beginning and end of the loop over srcTab */
|
||||
sqlite *db; /* The main database structure */
|
||||
int openOp; /* Opcode used to open cursors */
|
||||
int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
|
||||
int endOfLoop; /* Label for the end of the insertion loop */
|
||||
int useTempTable; /* Store SELECT results in intermediate table */
|
||||
int srcTab; /* Data comes from this temporary cursor if >=0 */
|
||||
int iSelectLoop; /* Address of code that implements the SELECT */
|
||||
int iCleanup; /* Address of the cleanup code */
|
||||
int iInsertBlock; /* Address of the subroutine used to insert data */
|
||||
int iCntMem; /* Memory cell used for the row counter */
|
||||
|
||||
int row_triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
|
||||
int newIdx = -1;
|
||||
|
||||
if( pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
|
||||
db = pParse->db;
|
||||
|
||||
/* Locate the table into which we will be inserting new information.
|
||||
*/
|
||||
zTab = sqliteTableNameFromToken(pTableName);
|
||||
if( zTab==0 ) goto insert_cleanup;
|
||||
pTab = sqliteFindTable(pParse->db, zTab);
|
||||
if( pTab==0 ){
|
||||
sqliteSetString(&pParse->zErrMsg, "no such table: ", zTab, 0);
|
||||
pParse->nErr++;
|
||||
goto insert_cleanup;
|
||||
}
|
||||
if( sqliteAuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0) ){
|
||||
goto insert_cleanup;
|
||||
}
|
||||
|
||||
/* Ensure that:
|
||||
* (a) the table is not read-only,
|
||||
* (b) that if it is a view then ON INSERT triggers exist
|
||||
*/
|
||||
row_triggers_exist =
|
||||
sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT,
|
||||
TK_BEFORE, TK_ROW, 0) ||
|
||||
sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT, TK_AFTER, TK_ROW, 0);
|
||||
if( pTab->readOnly || (pTab->pSelect && !row_triggers_exist) ){
|
||||
sqliteSetString(&pParse->zErrMsg,
|
||||
pTab->pSelect ? "view " : "table ",
|
||||
zTab,
|
||||
" may not be modified", 0);
|
||||
pParse->nErr++;
|
||||
goto insert_cleanup;
|
||||
}
|
||||
sqliteFree(zTab);
|
||||
zTab = 0;
|
||||
|
||||
if( pTab==0 ) goto insert_cleanup;
|
||||
|
||||
/* If pTab is really a view, make sure it has been initialized.
|
||||
*/
|
||||
if( pTab->pSelect ){
|
||||
if( sqliteViewGetColumnNames(pParse, pTab) ){
|
||||
goto insert_cleanup;
|
||||
}
|
||||
}
|
||||
|
||||
/* Allocate a VDBE
|
||||
*/
|
||||
v = sqliteGetVdbe(pParse);
|
||||
if( v==0 ) goto insert_cleanup;
|
||||
sqliteBeginWriteOperation(pParse, pSelect || row_triggers_exist,
|
||||
!row_triggers_exist && pTab->isTemp);
|
||||
|
||||
/* if there are row triggers, allocate a temp table for new.* references. */
|
||||
if( row_triggers_exist ){
|
||||
newIdx = pParse->nTab++;
|
||||
}
|
||||
|
||||
/* Figure out how many columns of data are supplied. If the data
|
||||
** is coming from a SELECT statement, then this step also generates
|
||||
** all the code to implement the SELECT statement and invoke a subroutine
|
||||
** to process each row of the result. (Template 2.) If the SELECT
|
||||
** statement uses the the table that is being inserted into, then the
|
||||
** subroutine is also coded here. That subroutine stores the SELECT
|
||||
** results in a temporary table. (Template 3.)
|
||||
*/
|
||||
if( pSelect ){
|
||||
/* Data is coming from a SELECT. Generate code to implement that SELECT
|
||||
*/
|
||||
int rc, iInitCode;
|
||||
int opCode;
|
||||
iInitCode = sqliteVdbeAddOp(v, OP_Goto, 0, 0);
|
||||
iSelectLoop = sqliteVdbeCurrentAddr(v);
|
||||
iInsertBlock = sqliteVdbeMakeLabel(v);
|
||||
rc = sqliteSelect(pParse, pSelect, SRT_Subroutine, iInsertBlock, 0,0,0);
|
||||
if( rc || pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
|
||||
iCleanup = sqliteVdbeMakeLabel(v);
|
||||
sqliteVdbeAddOp(v, OP_Goto, 0, iCleanup);
|
||||
assert( pSelect->pEList );
|
||||
nColumn = pSelect->pEList->nExpr;
|
||||
|
||||
/* Set useTempTable to TRUE if the result of the SELECT statement
|
||||
** should be written into a temporary table. Set to FALSE if each
|
||||
** row of the SELECT can be written directly into the result table.
|
||||
*/
|
||||
opCode = pTab->isTemp ? OP_OpenTemp : OP_Open;
|
||||
useTempTable = row_triggers_exist || sqliteVdbeFindOp(v,opCode,pTab->tnum);
|
||||
|
||||
if( useTempTable ){
|
||||
/* Generate the subroutine that SELECT calls to process each row of
|
||||
** the result. Store the result in a temporary table
|
||||
*/
|
||||
srcTab = pParse->nTab++;
|
||||
sqliteVdbeResolveLabel(v, iInsertBlock);
|
||||
sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
|
||||
sqliteVdbeAddOp(v, OP_NewRecno, srcTab, 0);
|
||||
sqliteVdbeAddOp(v, OP_Pull, 1, 0);
|
||||
sqliteVdbeAddOp(v, OP_PutIntKey, srcTab, 0);
|
||||
sqliteVdbeAddOp(v, OP_Return, 0, 0);
|
||||
|
||||
/* The following code runs first because the GOTO at the very top
|
||||
** of the program jumps to it. Create the temporary table, then jump
|
||||
** back up and execute the SELECT code above.
|
||||
*/
|
||||
sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
|
||||
sqliteVdbeAddOp(v, OP_OpenTemp, srcTab, 0);
|
||||
sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
|
||||
sqliteVdbeResolveLabel(v, iCleanup);
|
||||
}else{
|
||||
sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
|
||||
}
|
||||
}else{
|
||||
/* This is the case if the data for the INSERT is coming from a VALUES
|
||||
** clause
|
||||
*/
|
||||
SrcList dummy;
|
||||
assert( pList!=0 );
|
||||
srcTab = -1;
|
||||
useTempTable = 0;
|
||||
assert( pList );
|
||||
nColumn = pList->nExpr;
|
||||
dummy.nSrc = 0;
|
||||
for(i=0; i<nColumn; i++){
|
||||
if( sqliteExprResolveIds(pParse, 0, &dummy, 0, pList->a[i].pExpr) ){
|
||||
goto insert_cleanup;
|
||||
}
|
||||
if( sqliteExprCheck(pParse, pList->a[i].pExpr, 0, 0) ){
|
||||
goto insert_cleanup;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Make sure the number of columns in the source data matches the number
|
||||
** of columns to be inserted into the table.
|
||||
*/
|
||||
if( pColumn==0 && nColumn!=pTab->nCol ){
|
||||
char zNum1[30];
|
||||
char zNum2[30];
|
||||
sprintf(zNum1,"%d", nColumn);
|
||||
sprintf(zNum2,"%d", pTab->nCol);
|
||||
sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName,
|
||||
" has ", zNum2, " columns but ",
|
||||
zNum1, " values were supplied", 0);
|
||||
pParse->nErr++;
|
||||
goto insert_cleanup;
|
||||
}
|
||||
if( pColumn!=0 && nColumn!=pColumn->nId ){
|
||||
char zNum1[30];
|
||||
char zNum2[30];
|
||||
sprintf(zNum1,"%d", nColumn);
|
||||
sprintf(zNum2,"%d", pColumn->nId);
|
||||
sqliteSetString(&pParse->zErrMsg, zNum1, " values for ",
|
||||
zNum2, " columns", 0);
|
||||
pParse->nErr++;
|
||||
goto insert_cleanup;
|
||||
}
|
||||
|
||||
/* If the INSERT statement included an IDLIST term, then make sure
|
||||
** all elements of the IDLIST really are columns of the table and
|
||||
** remember the column indices.
|
||||
**
|
||||
** If the table has an INTEGER PRIMARY KEY column and that column
|
||||
** is named in the IDLIST, then record in the keyColumn variable
|
||||
** the index into IDLIST of the primary key column. keyColumn is
|
||||
** the index of the primary key as it appears in IDLIST, not as
|
||||
** is appears in the original table. (The index of the primary
|
||||
** key in the original table is pTab->iPKey.)
|
||||
*/
|
||||
if( pColumn ){
|
||||
for(i=0; i<pColumn->nId; i++){
|
||||
pColumn->a[i].idx = -1;
|
||||
}
|
||||
for(i=0; i<pColumn->nId; i++){
|
||||
for(j=0; j<pTab->nCol; j++){
|
||||
if( sqliteStrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
|
||||
pColumn->a[i].idx = j;
|
||||
if( j==pTab->iPKey ){
|
||||
keyColumn = i;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if( j>=pTab->nCol ){
|
||||
sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName,
|
||||
" has no column named ", pColumn->a[i].zName, 0);
|
||||
pParse->nErr++;
|
||||
goto insert_cleanup;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* If there is no IDLIST term but the table has an integer primary
|
||||
** key, the set the keyColumn variable to the primary key column index
|
||||
** in the original table definition.
|
||||
*/
|
||||
if( pColumn==0 ){
|
||||
keyColumn = pTab->iPKey;
|
||||
}
|
||||
|
||||
/* Open the temp table for FOR EACH ROW triggers
|
||||
*/
|
||||
if( row_triggers_exist ){
|
||||
sqliteVdbeAddOp(v, OP_OpenTemp, newIdx, 0);
|
||||
}
|
||||
|
||||
/* Initialize the count of rows to be inserted
|
||||
*/
|
||||
if( db->flags & SQLITE_CountRows ){
|
||||
iCntMem = pParse->nMem++;
|
||||
sqliteVdbeAddOp(v, OP_Integer, 0, 0);
|
||||
sqliteVdbeAddOp(v, OP_MemStore, iCntMem, 1);
|
||||
}
|
||||
|
||||
/* Open tables and indices if there are no row triggers */
|
||||
if( !row_triggers_exist ){
|
||||
base = pParse->nTab;
|
||||
openOp = pTab->isTemp ? OP_OpenWrAux : OP_OpenWrite;
|
||||
sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
|
||||
sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
|
||||
for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
|
||||
sqliteVdbeAddOp(v, openOp, idx+base, pIdx->tnum);
|
||||
sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
|
||||
}
|
||||
pParse->nTab += idx;
|
||||
}
|
||||
|
||||
/* If the data source is a temporary table, then we have to create
|
||||
** a loop because there might be multiple rows of data. If the data
|
||||
** source is a subroutine call from the SELECT statement, then we need
|
||||
** to launch the SELECT statement processing.
|
||||
*/
|
||||
if( useTempTable ){
|
||||
iBreak = sqliteVdbeMakeLabel(v);
|
||||
sqliteVdbeAddOp(v, OP_Rewind, srcTab, iBreak);
|
||||
iCont = sqliteVdbeCurrentAddr(v);
|
||||
}else if( pSelect ){
|
||||
sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
|
||||
sqliteVdbeResolveLabel(v, iInsertBlock);
|
||||
}
|
||||
|
||||
endOfLoop = sqliteVdbeMakeLabel(v);
|
||||
if( row_triggers_exist ){
|
||||
|
||||
/* build the new.* reference row */
|
||||
sqliteVdbeAddOp(v, OP_Integer, 13, 0);
|
||||
for(i=0; i<pTab->nCol; i++){
|
||||
if( pColumn==0 ){
|
||||
j = i;
|
||||
}else{
|
||||
for(j=0; j<pColumn->nId; j++){
|
||||
if( pColumn->a[j].idx==i ) break;
|
||||
}
|
||||
}
|
||||
if( pColumn && j>=pColumn->nId ){
|
||||
sqliteVdbeAddOp(v, OP_String, 0, 0);
|
||||
sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
|
||||
}else if( useTempTable ){
|
||||
sqliteVdbeAddOp(v, OP_Column, srcTab, j);
|
||||
}else if( pSelect ){
|
||||
sqliteVdbeAddOp(v, OP_Dup, nColumn-j-1, 1);
|
||||
}else{
|
||||
sqliteExprCode(pParse, pList->a[j].pExpr);
|
||||
}
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
|
||||
sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
|
||||
sqliteVdbeAddOp(v, OP_Rewind, newIdx, 0);
|
||||
|
||||
/* Fire BEFORE triggers */
|
||||
if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_BEFORE, pTab, newIdx, -1,
|
||||
onError, endOfLoop) ){
|
||||
goto insert_cleanup;
|
||||
}
|
||||
|
||||
/* Open the tables and indices for the INSERT */
|
||||
if( !pTab->pSelect ){
|
||||
base = pParse->nTab;
|
||||
openOp = pTab->isTemp ? OP_OpenWrAux : OP_OpenWrite;
|
||||
sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
|
||||
sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
|
||||
for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
|
||||
sqliteVdbeAddOp(v, openOp, idx+base, pIdx->tnum);
|
||||
sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
|
||||
}
|
||||
pParse->nTab += idx;
|
||||
}
|
||||
}
|
||||
|
||||
/* Push the record number for the new entry onto the stack. The
|
||||
** record number is a randomly generate integer created by NewRecno
|
||||
** except when the table has an INTEGER PRIMARY KEY column, in which
|
||||
** case the record number is the same as that column.
|
||||
*/
|
||||
if( !pTab->pSelect ){
|
||||
if( keyColumn>=0 ){
|
||||
if( useTempTable ){
|
||||
sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
|
||||
}else if( pSelect ){
|
||||
sqliteVdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
|
||||
}else{
|
||||
sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
|
||||
}
|
||||
/* If the PRIMARY KEY expression is NULL, then use OP_NewRecno
|
||||
** to generate a unique primary key value.
|
||||
*/
|
||||
sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
|
||||
sqliteVdbeAddOp(v, OP_Pop, 1, 0);
|
||||
sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
|
||||
sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
|
||||
}else{
|
||||
sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
|
||||
}
|
||||
|
||||
/* Push onto the stack, data for all columns of the new entry, beginning
|
||||
** with the first column.
|
||||
*/
|
||||
for(i=0; i<pTab->nCol; i++){
|
||||
if( i==pTab->iPKey ){
|
||||
/* The value of the INTEGER PRIMARY KEY column is always a NULL.
|
||||
** Whenever this column is read, the record number will be substituted
|
||||
** in its place. So will fill this column with a NULL to avoid
|
||||
** taking up data space with information that will never be used. */
|
||||
sqliteVdbeAddOp(v, OP_String, 0, 0);
|
||||
continue;
|
||||
}
|
||||
if( pColumn==0 ){
|
||||
j = i;
|
||||
}else{
|
||||
for(j=0; j<pColumn->nId; j++){
|
||||
if( pColumn->a[j].idx==i ) break;
|
||||
}
|
||||
}
|
||||
if( pColumn && j>=pColumn->nId ){
|
||||
sqliteVdbeAddOp(v, OP_String, 0, 0);
|
||||
sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
|
||||
}else if( useTempTable ){
|
||||
sqliteVdbeAddOp(v, OP_Column, srcTab, j);
|
||||
}else if( pSelect ){
|
||||
sqliteVdbeAddOp(v, OP_Dup, i+nColumn-j, 1);
|
||||
}else{
|
||||
sqliteExprCode(pParse, pList->a[j].pExpr);
|
||||
}
|
||||
}
|
||||
|
||||
/* Generate code to check constraints and generate index keys and
|
||||
** do the insertion.
|
||||
*/
|
||||
sqliteGenerateConstraintChecks(pParse, pTab, base, 0,0,0,onError,endOfLoop);
|
||||
sqliteCompleteInsertion(pParse, pTab, base, 0,0,0);
|
||||
|
||||
/* Update the count of rows that are inserted
|
||||
*/
|
||||
if( (db->flags & SQLITE_CountRows)!=0 ){
|
||||
sqliteVdbeAddOp(v, OP_MemIncr, iCntMem, 0);
|
||||
}
|
||||
}
|
||||
|
||||
if( row_triggers_exist ){
|
||||
/* Close all tables opened */
|
||||
if( !pTab->pSelect ){
|
||||
sqliteVdbeAddOp(v, OP_Close, base, 0);
|
||||
for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
|
||||
sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Code AFTER triggers */
|
||||
if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_AFTER, pTab, newIdx, -1,
|
||||
onError, endOfLoop) ){
|
||||
goto insert_cleanup;
|
||||
}
|
||||
}
|
||||
|
||||
/* The bottom of the loop, if the data source is a SELECT statement
|
||||
*/
|
||||
sqliteVdbeResolveLabel(v, endOfLoop);
|
||||
if( useTempTable ){
|
||||
sqliteVdbeAddOp(v, OP_Next, srcTab, iCont);
|
||||
sqliteVdbeResolveLabel(v, iBreak);
|
||||
sqliteVdbeAddOp(v, OP_Close, srcTab, 0);
|
||||
}else if( pSelect ){
|
||||
sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
|
||||
sqliteVdbeAddOp(v, OP_Return, 0, 0);
|
||||
sqliteVdbeResolveLabel(v, iCleanup);
|
||||
}
|
||||
|
||||
if( !row_triggers_exist ){
|
||||
/* Close all tables opened */
|
||||
sqliteVdbeAddOp(v, OP_Close, base, 0);
|
||||
for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
|
||||
sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
|
||||
}
|
||||
}
|
||||
|
||||
sqliteEndWriteOperation(pParse);
|
||||
|
||||
/*
|
||||
** Return the number of rows inserted.
|
||||
*/
|
||||
if( db->flags & SQLITE_CountRows ){
|
||||
sqliteVdbeAddOp(v, OP_ColumnName, 0, 0);
|
||||
sqliteVdbeChangeP3(v, -1, "rows inserted", P3_STATIC);
|
||||
sqliteVdbeAddOp(v, OP_MemLoad, iCntMem, 0);
|
||||
sqliteVdbeAddOp(v, OP_Callback, 1, 0);
|
||||
}
|
||||
|
||||
insert_cleanup:
|
||||
if( pList ) sqliteExprListDelete(pList);
|
||||
if( pSelect ) sqliteSelectDelete(pSelect);
|
||||
if ( zTab ) sqliteFree(zTab);
|
||||
sqliteIdListDelete(pColumn);
|
||||
}
|
||||
|
||||
/*
|
||||
** Generate code to do a constraint check prior to an INSERT or an UPDATE.
|
||||
**
|
||||
** When this routine is called, the stack contains (from bottom to top)
|
||||
** the following values:
|
||||
**
|
||||
** 1. The recno of the row to be updated before it is updated. This
|
||||
** value is omitted unless we are doing an UPDATE that involves a
|
||||
** change to the record number.
|
||||
**
|
||||
** 2. The recno of the row after the update.
|
||||
**
|
||||
** 3. The data in the first column of the entry after the update.
|
||||
**
|
||||
** i. Data from middle columns...
|
||||
**
|
||||
** N. The data in the last column of the entry after the update.
|
||||
**
|
||||
** The old recno shown as entry (1) above is omitted unless both isUpdate
|
||||
** and recnoChng are 1. isUpdate is true for UPDATEs and false for
|
||||
** INSERTs and recnoChng is true if the record number is being changed.
|
||||
**
|
||||
** The code generated by this routine pushes additional entries onto
|
||||
** the stack which are the keys for new index entries for the new record.
|
||||
** The order of index keys is the same as the order of the indices on
|
||||
** the pTable->pIndex list. A key is only created for index i if
|
||||
** aIdxUsed!=0 and aIdxUsed[i]!=0.
|
||||
**
|
||||
** This routine also generates code to check constraints. NOT NULL,
|
||||
** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
|
||||
** then the appropriate action is performed. There are five possible
|
||||
** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
|
||||
**
|
||||
** Constraint type Action What Happens
|
||||
** --------------- ---------- ----------------------------------------
|
||||
** any ROLLBACK The current transaction is rolled back and
|
||||
** sqlite_exec() returns immediately with a
|
||||
** return code of SQLITE_CONSTRAINT.
|
||||
**
|
||||
** any ABORT Back out changes from the current command
|
||||
** only (do not do a complete rollback) then
|
||||
** cause sqlite_exec() to return immediately
|
||||
** with SQLITE_CONSTRAINT.
|
||||
**
|
||||
** any FAIL Sqlite_exec() returns immediately with a
|
||||
** return code of SQLITE_CONSTRAINT. The
|
||||
** transaction is not rolled back and any
|
||||
** prior changes are retained.
|
||||
**
|
||||
** any IGNORE The record number and data is popped from
|
||||
** the stack and there is an immediate jump
|
||||
** to label ignoreDest.
|
||||
**
|
||||
** NOT NULL REPLACE The NULL value is replace by the default
|
||||
** value for that column. If the default value
|
||||
** is NULL, the action is the same as ABORT.
|
||||
**
|
||||
** UNIQUE REPLACE The other row that conflicts with the row
|
||||
** being inserted is removed.
|
||||
**
|
||||
** CHECK REPLACE Illegal. The results in an exception.
|
||||
**
|
||||
** Which action to take is determined by the overrideError parameter.
|
||||
** Or if overrideError==OE_Default, then the pParse->onError parameter
|
||||
** is used. Or if pParse->onError==OE_Default then the onError value
|
||||
** for the constraint is used.
|
||||
**
|
||||
** The calling routine must open a read/write cursor for pTab with
|
||||
** cursor number "base". All indices of pTab must also have open
|
||||
** read/write cursors with cursor number base+i for the i-th cursor.
|
||||
** Except, if there is no possibility of a REPLACE action then
|
||||
** cursors do not need to be open for indices where aIdxUsed[i]==0.
|
||||
**
|
||||
** If the isUpdate flag is true, it means that the "base" cursor is
|
||||
** initially pointing to an entry that is being updated. The isUpdate
|
||||
** flag causes extra code to be generated so that the "base" cursor
|
||||
** is still pointing at the same entry after the routine returns.
|
||||
** Without the isUpdate flag, the "base" cursor might be moved.
|
||||
*/
|
||||
void sqliteGenerateConstraintChecks(
|
||||
Parse *pParse, /* The parser context */
|
||||
Table *pTab, /* the table into which we are inserting */
|
||||
int base, /* Index of a read/write cursor pointing at pTab */
|
||||
char *aIdxUsed, /* Which indices are used. NULL means all are used */
|
||||
int recnoChng, /* True if the record number will change */
|
||||
int isUpdate, /* True for UPDATE, False for INSERT */
|
||||
int overrideError, /* Override onError to this if not OE_Default */
|
||||
int ignoreDest /* Jump to this label on an OE_Ignore resolution */
|
||||
){
|
||||
int i;
|
||||
Vdbe *v;
|
||||
int nCol;
|
||||
int onError;
|
||||
int addr;
|
||||
int extra;
|
||||
int iCur;
|
||||
Index *pIdx;
|
||||
int seenReplace = 0;
|
||||
int jumpInst1, jumpInst2;
|
||||
int contAddr;
|
||||
int hasTwoRecnos = (isUpdate && recnoChng);
|
||||
|
||||
v = sqliteGetVdbe(pParse);
|
||||
assert( v!=0 );
|
||||
assert( pTab->pSelect==0 ); /* This table is not a VIEW */
|
||||
nCol = pTab->nCol;
|
||||
|
||||
/* Test all NOT NULL constraints.
|
||||
*/
|
||||
for(i=0; i<nCol; i++){
|
||||
if( i==pTab->iPKey ){
|
||||
/* Fix me: Make sure the INTEGER PRIMARY KEY is not NULL. */
|
||||
continue;
|
||||
}
|
||||
onError = pTab->aCol[i].notNull;
|
||||
if( onError==OE_None ) continue;
|
||||
if( overrideError!=OE_Default ){
|
||||
onError = overrideError;
|
||||
}else if( onError==OE_Default ){
|
||||
onError = pParse->db->onError;
|
||||
if( onError==OE_Default ) onError = OE_Abort;
|
||||
}
|
||||
if( onError==OE_Replace && pTab->aCol[i].zDflt==0 ){
|
||||
onError = OE_Abort;
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_Dup, nCol-1-i, 1);
|
||||
addr = sqliteVdbeAddOp(v, OP_NotNull, 1, 0);
|
||||
switch( onError ){
|
||||
case OE_Rollback:
|
||||
case OE_Abort:
|
||||
case OE_Fail: {
|
||||
char *zMsg = 0;
|
||||
sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
|
||||
sqliteSetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
|
||||
" may not be NULL", 0);
|
||||
sqliteVdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
|
||||
break;
|
||||
}
|
||||
case OE_Ignore: {
|
||||
sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
|
||||
sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
|
||||
break;
|
||||
}
|
||||
case OE_Replace: {
|
||||
sqliteVdbeAddOp(v, OP_String, 0, 0);
|
||||
sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
|
||||
sqliteVdbeAddOp(v, OP_Push, nCol-i, 0);
|
||||
break;
|
||||
}
|
||||
default: assert(0);
|
||||
}
|
||||
sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
|
||||
}
|
||||
|
||||
/* Test all CHECK constraints
|
||||
*/
|
||||
/**** TBD ****/
|
||||
|
||||
/* If we have an INTEGER PRIMARY KEY, make sure the primary key
|
||||
** of the new record does not previously exist. Except, if this
|
||||
** is an UPDATE and the primary key is not changing, that is OK.
|
||||
** Also, if the conflict resolution policy is REPLACE, then we
|
||||
** can skip this test.
|
||||
*/
|
||||
if( (recnoChng || !isUpdate) && pTab->iPKey>=0 ){
|
||||
onError = pTab->keyConf;
|
||||
if( overrideError!=OE_Default ){
|
||||
onError = overrideError;
|
||||
}else if( onError==OE_Default ){
|
||||
onError = pParse->db->onError;
|
||||
if( onError==OE_Default ) onError = OE_Abort;
|
||||
}
|
||||
if( onError!=OE_Replace ){
|
||||
if( isUpdate ){
|
||||
sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
|
||||
sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
|
||||
jumpInst1 = sqliteVdbeAddOp(v, OP_Eq, 0, 0);
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_Dup, nCol, 1);
|
||||
jumpInst2 = sqliteVdbeAddOp(v, OP_NotExists, base, 0);
|
||||
switch( onError ){
|
||||
case OE_Rollback:
|
||||
case OE_Abort:
|
||||
case OE_Fail: {
|
||||
sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
|
||||
sqliteVdbeChangeP3(v, -1, "PRIMARY KEY must be unique", P3_STATIC);
|
||||
break;
|
||||
}
|
||||
case OE_Ignore: {
|
||||
sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
|
||||
sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
|
||||
break;
|
||||
}
|
||||
default: assert(0);
|
||||
}
|
||||
contAddr = sqliteVdbeCurrentAddr(v);
|
||||
sqliteVdbeChangeP2(v, jumpInst2, contAddr);
|
||||
if( isUpdate ){
|
||||
sqliteVdbeChangeP2(v, jumpInst1, contAddr);
|
||||
sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
|
||||
sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Test all UNIQUE constraints by creating entries for each UNIQUE
|
||||
** index and making sure that duplicate entries do not already exist.
|
||||
** Add the new records to the indices as we go.
|
||||
*/
|
||||
extra = 0;
|
||||
for(extra=(-1), iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
|
||||
if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;
|
||||
extra++;
|
||||
sqliteVdbeAddOp(v, OP_Dup, nCol+extra, 1);
|
||||
for(i=0; i<pIdx->nColumn; i++){
|
||||
int idx = pIdx->aiColumn[i];
|
||||
if( idx==pTab->iPKey ){
|
||||
sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
|
||||
}else{
|
||||
sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
|
||||
}
|
||||
}
|
||||
jumpInst1 = sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
|
||||
if( pParse->db->file_format>=4 ) sqliteAddIdxKeyType(v, pIdx);
|
||||
onError = pIdx->onError;
|
||||
if( onError==OE_None ) continue;
|
||||
if( overrideError!=OE_Default ){
|
||||
onError = overrideError;
|
||||
}else if( onError==OE_Default ){
|
||||
onError = pParse->db->onError;
|
||||
if( onError==OE_Default ) onError = OE_Abort;
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRecnos, 1);
|
||||
jumpInst2 = sqliteVdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
|
||||
switch( onError ){
|
||||
case OE_Rollback:
|
||||
case OE_Abort:
|
||||
case OE_Fail: {
|
||||
sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
|
||||
sqliteVdbeChangeP3(v, -1, "uniqueness constraint failed", P3_STATIC);
|
||||
break;
|
||||
}
|
||||
case OE_Ignore: {
|
||||
assert( seenReplace==0 );
|
||||
sqliteVdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRecnos, 0);
|
||||
sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
|
||||
break;
|
||||
}
|
||||
case OE_Replace: {
|
||||
sqliteGenerateRowDelete(pParse->db, v, pTab, base, 0);
|
||||
if( isUpdate ){
|
||||
sqliteVdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRecnos, 1);
|
||||
sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
|
||||
}
|
||||
seenReplace = 1;
|
||||
break;
|
||||
}
|
||||
default: assert(0);
|
||||
}
|
||||
contAddr = sqliteVdbeCurrentAddr(v);
|
||||
#if NULL_DISTINCT_FOR_UNIQUE
|
||||
sqliteVdbeChangeP2(v, jumpInst1, contAddr);
|
||||
#endif
|
||||
sqliteVdbeChangeP2(v, jumpInst2, contAddr);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
** This routine generates code to finish the INSERT or UPDATE operation
|
||||
** that was started by a prior call to sqliteGenerateConstraintChecks.
|
||||
** The stack must contain keys for all active indices followed by data
|
||||
** and the recno for the new entry. This routine creates the new
|
||||
** entries in all indices and in the main table.
|
||||
**
|
||||
** The arguments to this routine should be the same as the first six
|
||||
** arguments to sqliteGenerateConstraintChecks.
|
||||
*/
|
||||
void sqliteCompleteInsertion(
|
||||
Parse *pParse, /* The parser context */
|
||||
Table *pTab, /* the table into which we are inserting */
|
||||
int base, /* Index of a read/write cursor pointing at pTab */
|
||||
char *aIdxUsed, /* Which indices are used. NULL means all are used */
|
||||
int recnoChng, /* True if the record number will change */
|
||||
int isUpdate /* True for UPDATE, False for INSERT */
|
||||
){
|
||||
int i;
|
||||
Vdbe *v;
|
||||
int nIdx;
|
||||
Index *pIdx;
|
||||
|
||||
v = sqliteGetVdbe(pParse);
|
||||
assert( v!=0 );
|
||||
assert( pTab->pSelect==0 ); /* This table is not a VIEW */
|
||||
for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
|
||||
for(i=nIdx-1; i>=0; i--){
|
||||
if( aIdxUsed && aIdxUsed[i]==0 ) continue;
|
||||
sqliteVdbeAddOp(v, OP_IdxPut, base+i+1, 0);
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
|
||||
sqliteVdbeAddOp(v, OP_PutIntKey, base, pParse->trigStack?0:1);
|
||||
if( isUpdate && recnoChng ){
|
||||
sqliteVdbeAddOp(v, OP_Pop, 1, 0);
|
||||
}
|
||||
}
|
||||
@@ -1,989 +0,0 @@
|
||||
/*
|
||||
** 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.
|
||||
**
|
||||
*************************************************************************
|
||||
** Main file for the SQLite library. The routines in this file
|
||||
** implement the programmer interface to the library. Routines in
|
||||
** other files are for internal use by SQLite and should not be
|
||||
** accessed by users of the library.
|
||||
**
|
||||
** $Id$
|
||||
*/
|
||||
#include "sqliteInt.h"
|
||||
#include "os.h"
|
||||
#include <ctype.h>
|
||||
|
||||
/*
|
||||
** A pointer to this structure is used to communicate information
|
||||
** from sqliteInit into the sqliteInitCallback.
|
||||
*/
|
||||
typedef struct {
|
||||
sqlite *db; /* The database being initialized */
|
||||
char **pzErrMsg; /* Error message stored here */
|
||||
} InitData;
|
||||
|
||||
|
||||
/*
|
||||
** This is the callback routine for the code that initializes the
|
||||
** database. See sqliteInit() below for additional information.
|
||||
**
|
||||
** Each callback contains the following information:
|
||||
**
|
||||
** argv[0] = "file-format" or "schema-cookie" or "table" or "index"
|
||||
** argv[1] = table or index name or meta statement type.
|
||||
** argv[2] = root page number for table or index. NULL for meta.
|
||||
** argv[3] = SQL text for a CREATE TABLE or CREATE INDEX statement.
|
||||
** argv[4] = "1" for temporary files, "0" for main database
|
||||
**
|
||||
*/
|
||||
static
|
||||
int sqliteInitCallback(void *pInit, int argc, char **argv, char **azColName){
|
||||
InitData *pData = (InitData*)pInit;
|
||||
Parse sParse;
|
||||
int nErr = 0;
|
||||
|
||||
/* TODO: Do some validity checks on all fields. In particular,
|
||||
** make sure fields do not contain NULLs. Otherwise we might core
|
||||
** when attempting to initialize from a corrupt database file. */
|
||||
|
||||
assert( argc==5 );
|
||||
switch( argv[0][0] ){
|
||||
case 'v':
|
||||
case 'i':
|
||||
case 't': { /* CREATE TABLE, CREATE INDEX, or CREATE VIEW statements */
|
||||
if( argv[3] && argv[3][0] ){
|
||||
/* Call the parser to process a CREATE TABLE, INDEX or VIEW.
|
||||
** But because sParse.initFlag is set to 1, no VDBE code is generated
|
||||
** or executed. All the parser does is build the internal data
|
||||
** structures that describe the table, index, or view.
|
||||
*/
|
||||
memset(&sParse, 0, sizeof(sParse));
|
||||
sParse.db = pData->db;
|
||||
sParse.initFlag = 1;
|
||||
sParse.isTemp = argv[4][0] - '0';
|
||||
sParse.newTnum = atoi(argv[2]);
|
||||
sParse.useCallback = 1;
|
||||
sqliteRunParser(&sParse, argv[3], pData->pzErrMsg);
|
||||
}else{
|
||||
/* If the SQL column is blank it means this is an index that
|
||||
** was created to be the PRIMARY KEY or to fulfill a UNIQUE
|
||||
** constraint for a CREATE TABLE. The index should have already
|
||||
** been created when we processed the CREATE TABLE. All we have
|
||||
** to do here is record the root page number for that index.
|
||||
*/
|
||||
Index *pIndex = sqliteFindIndex(pData->db, argv[1]);
|
||||
if( pIndex==0 || pIndex->tnum!=0 ){
|
||||
/* This can occur if there exists an index on a TEMP table which
|
||||
** has the same name as another index on a permanent index. Since
|
||||
** the permanent table is hidden by the TEMP table, we can also
|
||||
** safely ignore the index on the permanent table.
|
||||
*/
|
||||
/* Do Nothing */;
|
||||
}else{
|
||||
pIndex->tnum = atoi(argv[2]);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
/* This can not happen! */
|
||||
nErr = 1;
|
||||
assert( nErr==0 );
|
||||
}
|
||||
}
|
||||
return nErr;
|
||||
}
|
||||
|
||||
/*
|
||||
** This is a callback procedure used to reconstruct a table. The
|
||||
** name of the table to be reconstructed is passed in as argv[0].
|
||||
**
|
||||
** This routine is used to automatically upgrade a database from
|
||||
** format version 1 or 2 to version 3. The correct operation of
|
||||
** this routine relys on the fact that no indices are used when
|
||||
** copying a table out to a temporary file.
|
||||
*/
|
||||
static
|
||||
int upgrade_3_callback(void *pInit, int argc, char **argv, char **NotUsed){
|
||||
InitData *pData = (InitData*)pInit;
|
||||
int rc;
|
||||
Table *pTab;
|
||||
Trigger *pTrig;
|
||||
char *zErr = 0;
|
||||
|
||||
pTab = sqliteFindTable(pData->db, argv[0]);
|
||||
assert( pTab!=0 );
|
||||
assert( sqliteStrICmp(pTab->zName, argv[0])==0 );
|
||||
if( pTab ){
|
||||
pTrig = pTab->pTrigger;
|
||||
pTab->pTrigger = 0; /* Disable all triggers before rebuilding the table */
|
||||
}
|
||||
rc = sqlite_exec_printf(pData->db,
|
||||
"CREATE TEMP TABLE sqlite_x AS SELECT * FROM '%q'; "
|
||||
"DELETE FROM '%q'; "
|
||||
"INSERT INTO '%q' SELECT * FROM sqlite_x; "
|
||||
"DROP TABLE sqlite_x;",
|
||||
0, 0, &zErr, argv[0], argv[0], argv[0]);
|
||||
if( zErr ){
|
||||
sqliteSetString(pData->pzErrMsg, zErr, 0);
|
||||
sqlite_freemem(zErr);
|
||||
}
|
||||
|
||||
/* If an error occurred in the SQL above, then the transaction will
|
||||
** rollback which will delete the internal symbol tables. This will
|
||||
** cause the structure that pTab points to be deleted. In case that
|
||||
** happened, we need to refetch pTab.
|
||||
*/
|
||||
pTab = sqliteFindTable(pData->db, argv[0]);
|
||||
if( pTab ){
|
||||
assert( sqliteStrICmp(pTab->zName, argv[0])==0 );
|
||||
pTab->pTrigger = pTrig; /* Re-enable triggers */
|
||||
}
|
||||
return rc!=SQLITE_OK;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*
|
||||
** Attempt to read the database schema and initialize internal
|
||||
** data structures. Return one of the SQLITE_ error codes to
|
||||
** indicate success or failure.
|
||||
**
|
||||
** After the database is initialized, the SQLITE_Initialized
|
||||
** bit is set in the flags field of the sqlite structure. An
|
||||
** attempt is made to initialize the database as soon as it
|
||||
** is opened. If that fails (perhaps because another process
|
||||
** has the sqlite_master table locked) than another attempt
|
||||
** is made the first time the database is accessed.
|
||||
*/
|
||||
int sqliteInit(sqlite *db, char **pzErrMsg){
|
||||
int rc;
|
||||
BtCursor *curMain;
|
||||
int size;
|
||||
Table *pTab;
|
||||
char *azArg[6];
|
||||
int meta[SQLITE_N_BTREE_META];
|
||||
Parse sParse;
|
||||
InitData initData;
|
||||
|
||||
/*
|
||||
** The master database table has a structure like this
|
||||
*/
|
||||
static char master_schema[] =
|
||||
"CREATE TABLE sqlite_master(\n"
|
||||
" type text,\n"
|
||||
" name text,\n"
|
||||
" tbl_name text,\n"
|
||||
" rootpage integer,\n"
|
||||
" sql text\n"
|
||||
")"
|
||||
;
|
||||
static char temp_master_schema[] =
|
||||
"CREATE TEMP TABLE sqlite_temp_master(\n"
|
||||
" type text,\n"
|
||||
" name text,\n"
|
||||
" tbl_name text,\n"
|
||||
" rootpage integer,\n"
|
||||
" sql text\n"
|
||||
")"
|
||||
;
|
||||
|
||||
/* The following SQL will read the schema from the master tables.
|
||||
** The first version works with SQLite file formats 2 or greater.
|
||||
** The second version is for format 1 files.
|
||||
**
|
||||
** Beginning with file format 2, the rowid for new table entries
|
||||
** (including entries in sqlite_master) is an increasing integer.
|
||||
** So for file format 2 and later, we can play back sqlite_master
|
||||
** and all the CREATE statements will appear in the right order.
|
||||
** But with file format 1, table entries were random and so we
|
||||
** have to make sure the CREATE TABLEs occur before their corresponding
|
||||
** CREATE INDEXs. (We don't have to deal with CREATE VIEW or
|
||||
** CREATE TRIGGER in file format 1 because those constructs did
|
||||
** not exist then.)
|
||||
*/
|
||||
static char init_script[] =
|
||||
"SELECT type, name, rootpage, sql, 1 FROM sqlite_temp_master "
|
||||
"UNION ALL "
|
||||
"SELECT type, name, rootpage, sql, 0 FROM sqlite_master";
|
||||
static char older_init_script[] =
|
||||
"SELECT type, name, rootpage, sql, 1 FROM sqlite_temp_master "
|
||||
"UNION ALL "
|
||||
"SELECT type, name, rootpage, sql, 0 FROM sqlite_master "
|
||||
"WHERE type='table' "
|
||||
"UNION ALL "
|
||||
"SELECT type, name, rootpage, sql, 0 FROM sqlite_master "
|
||||
"WHERE type='index'";
|
||||
|
||||
|
||||
/* Construct the schema tables: sqlite_master and sqlite_temp_master
|
||||
*/
|
||||
azArg[0] = "table";
|
||||
azArg[1] = MASTER_NAME;
|
||||
azArg[2] = "2";
|
||||
azArg[3] = master_schema;
|
||||
azArg[4] = "0";
|
||||
azArg[5] = 0;
|
||||
initData.db = db;
|
||||
initData.pzErrMsg = pzErrMsg;
|
||||
sqliteInitCallback(&initData, 5, azArg, 0);
|
||||
pTab = sqliteFindTable(db, MASTER_NAME);
|
||||
if( pTab ){
|
||||
pTab->readOnly = 1;
|
||||
}
|
||||
azArg[1] = TEMP_MASTER_NAME;
|
||||
azArg[3] = temp_master_schema;
|
||||
azArg[4] = "1";
|
||||
sqliteInitCallback(&initData, 5, azArg, 0);
|
||||
pTab = sqliteFindTable(db, TEMP_MASTER_NAME);
|
||||
if( pTab ){
|
||||
pTab->readOnly = 1;
|
||||
}
|
||||
|
||||
/* Create a cursor to hold the database open
|
||||
*/
|
||||
if( db->pBe==0 ) return SQLITE_OK;
|
||||
rc = sqliteBtreeCursor(db->pBe, 2, 0, &curMain);
|
||||
if( rc ){
|
||||
sqliteSetString(pzErrMsg, sqlite_error_string(rc), 0);
|
||||
sqliteResetInternalSchema(db);
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* Get the database meta information
|
||||
*/
|
||||
rc = sqliteBtreeGetMeta(db->pBe, meta);
|
||||
if( rc ){
|
||||
sqliteSetString(pzErrMsg, sqlite_error_string(rc), 0);
|
||||
sqliteResetInternalSchema(db);
|
||||
sqliteBtreeCloseCursor(curMain);
|
||||
return rc;
|
||||
}
|
||||
db->schema_cookie = meta[1];
|
||||
db->next_cookie = db->schema_cookie;
|
||||
db->file_format = meta[2];
|
||||
size = meta[3];
|
||||
if( size==0 ){ size = MAX_PAGES; }
|
||||
db->cache_size = size;
|
||||
sqliteBtreeSetCacheSize(db->pBe, size);
|
||||
db->safety_level = meta[4];
|
||||
if( db->safety_level==0 ) db->safety_level = 2;
|
||||
sqliteBtreeSetSafetyLevel(db->pBe, db->safety_level);
|
||||
|
||||
/*
|
||||
** file_format==1 Version 2.1.0.
|
||||
** file_format==2 Version 2.2.0. Add support for INTEGER PRIMARY KEY.
|
||||
** file_format==3 Version 2.6.0. Fix empty-string index bug.
|
||||
** file_format==4 Version 2.7.0. Add support for separate numeric and
|
||||
** text datatypes.
|
||||
*/
|
||||
if( db->file_format==0 ){
|
||||
/* This happens if the database was initially empty */
|
||||
db->file_format = 4;
|
||||
}else if( db->file_format>4 ){
|
||||
sqliteBtreeCloseCursor(curMain);
|
||||
sqliteSetString(pzErrMsg, "unsupported file format", 0);
|
||||
return SQLITE_ERROR;
|
||||
}
|
||||
|
||||
/* Read the schema information out of the schema tables
|
||||
*/
|
||||
memset(&sParse, 0, sizeof(sParse));
|
||||
sParse.db = db;
|
||||
sParse.pBe = db->pBe;
|
||||
sParse.xCallback = sqliteInitCallback;
|
||||
sParse.pArg = (void*)&initData;
|
||||
sParse.initFlag = 1;
|
||||
sParse.useCallback = 1;
|
||||
sqliteRunParser(&sParse,
|
||||
db->file_format>=2 ? init_script : older_init_script,
|
||||
pzErrMsg);
|
||||
if( sqlite_malloc_failed ){
|
||||
sqliteSetString(pzErrMsg, "out of memory", 0);
|
||||
sParse.rc = SQLITE_NOMEM;
|
||||
sqliteBtreeRollback(db->pBe);
|
||||
sqliteResetInternalSchema(db);
|
||||
}
|
||||
if( sParse.rc==SQLITE_OK ){
|
||||
db->flags |= SQLITE_Initialized;
|
||||
sqliteCommitInternalChanges(db);
|
||||
}else{
|
||||
db->flags &= ~SQLITE_Initialized;
|
||||
sqliteResetInternalSchema(db);
|
||||
}
|
||||
sqliteBtreeCloseCursor(curMain);
|
||||
return sParse.rc;
|
||||
}
|
||||
|
||||
/*
|
||||
** The version of the library
|
||||
*/
|
||||
const char rcsid[] = "@(#) \044Id: SQLite version " SQLITE_VERSION " $";
|
||||
const char sqlite_version[] = SQLITE_VERSION;
|
||||
|
||||
/*
|
||||
** Does the library expect data to be encoded as UTF-8 or iso8859? The
|
||||
** following global constant always lets us know.
|
||||
*/
|
||||
#ifdef SQLITE_UTF8
|
||||
const char sqlite_encoding[] = "UTF-8";
|
||||
#else
|
||||
const char sqlite_encoding[] = "iso8859";
|
||||
#endif
|
||||
|
||||
/*
|
||||
** Open a new SQLite database. Construct an "sqlite" structure to define
|
||||
** the state of this database and return a pointer to that structure.
|
||||
**
|
||||
** An attempt is made to initialize the in-memory data structures that
|
||||
** hold the database schema. But if this fails (because the schema file
|
||||
** is locked) then that step is deferred until the first call to
|
||||
** sqlite_exec().
|
||||
*/
|
||||
sqlite *sqlite_open(const char *zFilename, int mode, char **pzErrMsg){
|
||||
sqlite *db;
|
||||
int rc;
|
||||
|
||||
/* Allocate the sqlite data structure */
|
||||
db = sqliteMalloc( sizeof(sqlite) );
|
||||
if( pzErrMsg ) *pzErrMsg = 0;
|
||||
if( db==0 ) goto no_mem_on_open;
|
||||
sqliteHashInit(&db->tblHash, SQLITE_HASH_STRING, 0);
|
||||
sqliteHashInit(&db->idxHash, SQLITE_HASH_STRING, 0);
|
||||
sqliteHashInit(&db->trigHash, SQLITE_HASH_STRING, 0);
|
||||
sqliteHashInit(&db->aFunc, SQLITE_HASH_STRING, 1);
|
||||
sqliteHashInit(&db->aFKey, SQLITE_HASH_STRING, 1);
|
||||
db->onError = OE_Default;
|
||||
db->priorNewRowid = 0;
|
||||
db->magic = SQLITE_MAGIC_BUSY;
|
||||
|
||||
/* Open the backend database driver */
|
||||
rc = sqliteBtreeOpen(zFilename, 0, MAX_PAGES, &db->pBe);
|
||||
if( rc!=SQLITE_OK ){
|
||||
switch( rc ){
|
||||
default: {
|
||||
sqliteSetString(pzErrMsg, "unable to open database: ", zFilename, 0);
|
||||
}
|
||||
}
|
||||
sqliteFree(db);
|
||||
sqliteStrRealloc(pzErrMsg);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Attempt to read the schema */
|
||||
sqliteRegisterBuiltinFunctions(db);
|
||||
rc = sqliteInit(db, pzErrMsg);
|
||||
db->magic = SQLITE_MAGIC_OPEN;
|
||||
if( sqlite_malloc_failed ){
|
||||
sqlite_close(db);
|
||||
goto no_mem_on_open;
|
||||
}else if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
|
||||
sqlite_close(db);
|
||||
sqliteStrRealloc(pzErrMsg);
|
||||
return 0;
|
||||
}else if( pzErrMsg ){
|
||||
sqliteFree(*pzErrMsg);
|
||||
*pzErrMsg = 0;
|
||||
}
|
||||
|
||||
/* If the database is in formats 1 or 2, then upgrade it to
|
||||
** version 3. This will reconstruct all indices. If the
|
||||
** upgrade fails for any reason (ex: out of disk space, database
|
||||
** is read only, interrupt received, etc.) then refuse to open.
|
||||
*/
|
||||
if( rc==SQLITE_OK && db->file_format<3 ){
|
||||
char *zErr = 0;
|
||||
InitData initData;
|
||||
int meta[SQLITE_N_BTREE_META];
|
||||
|
||||
initData.db = db;
|
||||
initData.pzErrMsg = &zErr;
|
||||
db->file_format = 3;
|
||||
rc = sqlite_exec(db,
|
||||
"BEGIN; SELECT name FROM sqlite_master WHERE type='table';",
|
||||
upgrade_3_callback,
|
||||
&initData,
|
||||
&zErr);
|
||||
if( rc==SQLITE_OK ){
|
||||
sqliteBtreeGetMeta(db->pBe, meta);
|
||||
meta[2] = 4;
|
||||
sqliteBtreeUpdateMeta(db->pBe, meta);
|
||||
sqlite_exec(db, "COMMIT", 0, 0, 0);
|
||||
}
|
||||
if( rc!=SQLITE_OK ){
|
||||
sqliteSetString(pzErrMsg,
|
||||
"unable to upgrade database to the version 2.6 format",
|
||||
zErr ? ": " : 0, zErr, 0);
|
||||
sqlite_freemem(zErr);
|
||||
sqliteStrRealloc(pzErrMsg);
|
||||
sqlite_close(db);
|
||||
return 0;
|
||||
}
|
||||
sqlite_freemem(zErr);
|
||||
}
|
||||
|
||||
/* Return a pointer to the newly opened database structure */
|
||||
return db;
|
||||
|
||||
no_mem_on_open:
|
||||
sqliteSetString(pzErrMsg, "out of memory", 0);
|
||||
sqliteStrRealloc(pzErrMsg);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
** Return the ROWID of the most recent insert
|
||||
*/
|
||||
int sqlite_last_insert_rowid(sqlite *db){
|
||||
return db->lastRowid;
|
||||
}
|
||||
|
||||
/*
|
||||
** Return the number of changes in the most recent call to sqlite_exec().
|
||||
*/
|
||||
int sqlite_changes(sqlite *db){
|
||||
return db->nChange;
|
||||
}
|
||||
|
||||
/*
|
||||
** Close an existing SQLite database
|
||||
*/
|
||||
void sqlite_close(sqlite *db){
|
||||
HashElem *i;
|
||||
db->want_to_close = 1;
|
||||
if( sqliteSafetyCheck(db) || sqliteSafetyOn(db) ){
|
||||
/* printf("DID NOT CLOSE\n"); fflush(stdout); */
|
||||
return;
|
||||
}
|
||||
db->magic = SQLITE_MAGIC_CLOSED;
|
||||
sqliteBtreeClose(db->pBe);
|
||||
sqliteResetInternalSchema(db);
|
||||
if( db->pBeTemp ){
|
||||
sqliteBtreeClose(db->pBeTemp);
|
||||
}
|
||||
for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
|
||||
FuncDef *pFunc, *pNext;
|
||||
for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
|
||||
pNext = pFunc->pNext;
|
||||
sqliteFree(pFunc);
|
||||
}
|
||||
}
|
||||
sqliteHashClear(&db->aFunc);
|
||||
sqliteHashClear(&db->aFKey);
|
||||
sqliteFree(db);
|
||||
}
|
||||
|
||||
/*
|
||||
** Return TRUE if the given SQL string ends in a semicolon.
|
||||
**
|
||||
** Special handling is require for CREATE TRIGGER statements.
|
||||
** Whenever the CREATE TRIGGER keywords are seen, the statement
|
||||
** must end with ";END;".
|
||||
*/
|
||||
int sqlite_complete(const char *zSql){
|
||||
int isComplete = 1;
|
||||
int requireEnd = 0;
|
||||
int seenText = 0;
|
||||
int seenCreate = 0;
|
||||
while( *zSql ){
|
||||
switch( *zSql ){
|
||||
case ';': {
|
||||
isComplete = 1;
|
||||
seenText = 1;
|
||||
seenCreate = 0;
|
||||
break;
|
||||
}
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\n':
|
||||
case '\f': {
|
||||
break;
|
||||
}
|
||||
case '[': {
|
||||
isComplete = 0;
|
||||
seenText = 1;
|
||||
seenCreate = 0;
|
||||
zSql++;
|
||||
while( *zSql && *zSql!=']' ){ zSql++; }
|
||||
if( *zSql==0 ) return 0;
|
||||
break;
|
||||
}
|
||||
case '"':
|
||||
case '\'': {
|
||||
int c = *zSql;
|
||||
isComplete = 0;
|
||||
seenText = 1;
|
||||
seenCreate = 0;
|
||||
zSql++;
|
||||
while( *zSql && *zSql!=c ){ zSql++; }
|
||||
if( *zSql==0 ) return 0;
|
||||
break;
|
||||
}
|
||||
case '-': {
|
||||
if( zSql[1]!='-' ){
|
||||
isComplete = 0;
|
||||
seenCreate = 0;
|
||||
break;
|
||||
}
|
||||
while( *zSql && *zSql!='\n' ){ zSql++; }
|
||||
if( *zSql==0 ) return seenText && isComplete && requireEnd==0;
|
||||
break;
|
||||
}
|
||||
case 'c':
|
||||
case 'C': {
|
||||
seenText = 1;
|
||||
if( !isComplete ) break;
|
||||
isComplete = 0;
|
||||
if( sqliteStrNICmp(zSql, "create", 6)!=0 ) break;
|
||||
if( !isspace(zSql[6]) ) break;
|
||||
zSql += 5;
|
||||
seenCreate = 1;
|
||||
while( isspace(zSql[1]) ) zSql++;
|
||||
if( sqliteStrNICmp(&zSql[1],"trigger", 7)!=0 ) break;
|
||||
zSql += 7;
|
||||
requireEnd++;
|
||||
break;
|
||||
}
|
||||
case 't':
|
||||
case 'T': {
|
||||
seenText = 1;
|
||||
if( !seenCreate ) break;
|
||||
seenCreate = 0;
|
||||
isComplete = 0;
|
||||
if( sqliteStrNICmp(zSql, "trigger", 7)!=0 ) break;
|
||||
if( !isspace(zSql[7]) ) break;
|
||||
zSql += 6;
|
||||
requireEnd++;
|
||||
break;
|
||||
}
|
||||
case 'e':
|
||||
case 'E': {
|
||||
seenCreate = 0;
|
||||
seenText = 1;
|
||||
if( !isComplete ) break;
|
||||
isComplete = 0;
|
||||
if( requireEnd==0 ) break;
|
||||
if( sqliteStrNICmp(zSql, "end", 3)!=0 ) break;
|
||||
zSql += 2;
|
||||
while( isspace(zSql[1]) ) zSql++;
|
||||
if( zSql[1]==';' ){
|
||||
zSql++;
|
||||
isComplete = 1;
|
||||
requireEnd--;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
seenCreate = 0;
|
||||
seenText = 1;
|
||||
isComplete = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
zSql++;
|
||||
}
|
||||
return seenText && isComplete && requireEnd==0;
|
||||
}
|
||||
|
||||
/*
|
||||
** This routine does the work of either sqlite_exec() or sqlite_compile().
|
||||
** It works like sqlite_exec() if pVm==NULL and it works like sqlite_compile()
|
||||
** otherwise.
|
||||
*/
|
||||
static int sqliteMain(
|
||||
sqlite *db, /* The database on which the SQL executes */
|
||||
const char *zSql, /* The SQL to be executed */
|
||||
sqlite_callback xCallback, /* Invoke this callback routine */
|
||||
void *pArg, /* First argument to xCallback() */
|
||||
const char **pzTail, /* OUT: Next statement after the first */
|
||||
sqlite_vm **ppVm, /* OUT: The virtual machine */
|
||||
char **pzErrMsg /* OUT: Write error messages here */
|
||||
){
|
||||
Parse sParse;
|
||||
|
||||
if( pzErrMsg ) *pzErrMsg = 0;
|
||||
if( sqliteSafetyOn(db) ) goto exec_misuse;
|
||||
if( (db->flags & SQLITE_Initialized)==0 ){
|
||||
int rc, cnt = 1;
|
||||
while( (rc = sqliteInit(db, pzErrMsg))==SQLITE_BUSY
|
||||
&& db->xBusyCallback && db->xBusyCallback(db->pBusyArg, "", cnt++)!=0 ){}
|
||||
if( rc!=SQLITE_OK ){
|
||||
sqliteStrRealloc(pzErrMsg);
|
||||
sqliteSafetyOff(db);
|
||||
return rc;
|
||||
}
|
||||
if( pzErrMsg ){
|
||||
sqliteFree(*pzErrMsg);
|
||||
*pzErrMsg = 0;
|
||||
}
|
||||
}
|
||||
if( db->file_format<3 ){
|
||||
sqliteSafetyOff(db);
|
||||
sqliteSetString(pzErrMsg, "obsolete database file format", 0);
|
||||
return SQLITE_ERROR;
|
||||
}
|
||||
if( db->pVdbe==0 ){ db->nChange = 0; }
|
||||
memset(&sParse, 0, sizeof(sParse));
|
||||
sParse.db = db;
|
||||
sParse.pBe = db->pBe;
|
||||
sParse.xCallback = xCallback;
|
||||
sParse.pArg = pArg;
|
||||
sParse.useCallback = ppVm==0;
|
||||
#ifndef SQLITE_OMIT_TRACE
|
||||
if( db->xTrace ) db->xTrace(db->pTraceArg, zSql);
|
||||
#endif
|
||||
sqliteRunParser(&sParse, zSql, pzErrMsg);
|
||||
if( sqlite_malloc_failed ){
|
||||
sqliteSetString(pzErrMsg, "out of memory", 0);
|
||||
sParse.rc = SQLITE_NOMEM;
|
||||
sqliteBtreeRollback(db->pBe);
|
||||
if( db->pBeTemp ) sqliteBtreeRollback(db->pBeTemp);
|
||||
db->flags &= ~SQLITE_InTrans;
|
||||
sqliteResetInternalSchema(db);
|
||||
}
|
||||
if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
|
||||
if( sParse.rc!=SQLITE_OK && pzErrMsg && *pzErrMsg==0 ){
|
||||
sqliteSetString(pzErrMsg, sqlite_error_string(sParse.rc), 0);
|
||||
}
|
||||
sqliteStrRealloc(pzErrMsg);
|
||||
if( sParse.rc==SQLITE_SCHEMA ){
|
||||
sqliteResetInternalSchema(db);
|
||||
}
|
||||
if( sParse.useCallback==0 ){
|
||||
assert( ppVm );
|
||||
*ppVm = (sqlite_vm*)sParse.pVdbe;
|
||||
*pzTail = sParse.zTail;
|
||||
}
|
||||
if( sqliteSafetyOff(db) ) goto exec_misuse;
|
||||
return sParse.rc;
|
||||
|
||||
exec_misuse:
|
||||
if( pzErrMsg ){
|
||||
*pzErrMsg = 0;
|
||||
sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), 0);
|
||||
sqliteStrRealloc(pzErrMsg);
|
||||
}
|
||||
return SQLITE_MISUSE;
|
||||
}
|
||||
|
||||
/*
|
||||
** Execute SQL code. Return one of the SQLITE_ success/failure
|
||||
** codes. Also write an error message into memory obtained from
|
||||
** malloc() and make *pzErrMsg point to that message.
|
||||
**
|
||||
** If the SQL is a query, then for each row in the query result
|
||||
** the xCallback() function is called. pArg becomes the first
|
||||
** argument to xCallback(). If xCallback=NULL then no callback
|
||||
** is invoked, even for queries.
|
||||
*/
|
||||
int sqlite_exec(
|
||||
sqlite *db, /* The database on which the SQL executes */
|
||||
const char *zSql, /* The SQL to be executed */
|
||||
sqlite_callback xCallback, /* Invoke this callback routine */
|
||||
void *pArg, /* First argument to xCallback() */
|
||||
char **pzErrMsg /* Write error messages here */
|
||||
){
|
||||
return sqliteMain(db, zSql, xCallback, pArg, 0, 0, pzErrMsg);
|
||||
}
|
||||
|
||||
/*
|
||||
** Compile a single statement of SQL into a virtual machine. Return one
|
||||
** of the SQLITE_ success/failure codes. Also write an error message into
|
||||
** memory obtained from malloc() and make *pzErrMsg point to that message.
|
||||
*/
|
||||
int sqlite_compile(
|
||||
sqlite *db, /* The database on which the SQL executes */
|
||||
const char *zSql, /* The SQL to be executed */
|
||||
const char **pzTail, /* OUT: Next statement after the first */
|
||||
sqlite_vm **ppVm, /* OUT: The virtual machine */
|
||||
char **pzErrMsg /* OUT: Write error messages here */
|
||||
){
|
||||
return sqliteMain(db, zSql, 0, 0, pzTail, ppVm, pzErrMsg);
|
||||
}
|
||||
|
||||
/*
|
||||
** The following routine destroys a virtual machine that is created by
|
||||
** the sqlite_compile() routine.
|
||||
**
|
||||
** The integer returned is an SQLITE_ success/failure code that describes
|
||||
** the result of executing the virtual machine. An error message is
|
||||
** written into memory obtained from malloc and *pzErrMsg is made to
|
||||
** point to that error if pzErrMsg is not NULL. The calling routine
|
||||
** should use sqlite_freemem() to delete the message when it has finished
|
||||
** with it.
|
||||
*/
|
||||
int sqlite_finalize(
|
||||
sqlite_vm *pVm, /* The virtual machine to be destroyed */
|
||||
char **pzErrMsg /* OUT: Write error messages here */
|
||||
){
|
||||
int rc = sqliteVdbeFinalize((Vdbe*)pVm, pzErrMsg);
|
||||
sqliteStrRealloc(pzErrMsg);
|
||||
return rc;
|
||||
}
|
||||
|
||||
/*
|
||||
** Return a static string that describes the kind of error specified in the
|
||||
** argument.
|
||||
*/
|
||||
const char *sqlite_error_string(int rc){
|
||||
const char *z;
|
||||
switch( rc ){
|
||||
case SQLITE_OK: z = "not an error"; break;
|
||||
case SQLITE_ERROR: z = "SQL logic error or missing database"; break;
|
||||
case SQLITE_INTERNAL: z = "internal SQLite implementation flaw"; break;
|
||||
case SQLITE_PERM: z = "access permission denied"; break;
|
||||
case SQLITE_ABORT: z = "callback requested query abort"; break;
|
||||
case SQLITE_BUSY: z = "database is locked"; break;
|
||||
case SQLITE_LOCKED: z = "database table is locked"; break;
|
||||
case SQLITE_NOMEM: z = "out of memory"; break;
|
||||
case SQLITE_READONLY: z = "attempt to write a readonly database"; break;
|
||||
case SQLITE_INTERRUPT: z = "interrupted"; break;
|
||||
case SQLITE_IOERR: z = "disk I/O error"; break;
|
||||
case SQLITE_CORRUPT: z = "database disk image is malformed"; break;
|
||||
case SQLITE_NOTFOUND: z = "table or record not found"; break;
|
||||
case SQLITE_FULL: z = "database is full"; break;
|
||||
case SQLITE_CANTOPEN: z = "unable to open database file"; break;
|
||||
case SQLITE_PROTOCOL: z = "database locking protocol failure"; break;
|
||||
case SQLITE_EMPTY: z = "table contains no data"; break;
|
||||
case SQLITE_SCHEMA: z = "database schema has changed"; break;
|
||||
case SQLITE_TOOBIG: z = "too much data for one table row"; break;
|
||||
case SQLITE_CONSTRAINT: z = "constraint failed"; break;
|
||||
case SQLITE_MISMATCH: z = "datatype mismatch"; break;
|
||||
case SQLITE_MISUSE: z = "library routine called out of sequence";break;
|
||||
case SQLITE_NOLFS: z = "kernel lacks large file support"; break;
|
||||
case SQLITE_AUTH: z = "authorization denied"; break;
|
||||
default: z = "unknown error"; break;
|
||||
}
|
||||
return z;
|
||||
}
|
||||
|
||||
/*
|
||||
** This routine implements a busy callback that sleeps and tries
|
||||
** again until a timeout value is reached. The timeout value is
|
||||
** an integer number of milliseconds passed in as the first
|
||||
** argument.
|
||||
*/
|
||||
static int sqliteDefaultBusyCallback(
|
||||
void *Timeout, /* Maximum amount of time to wait */
|
||||
const char *NotUsed, /* The name of the table that is busy */
|
||||
int count /* Number of times table has been busy */
|
||||
){
|
||||
#if SQLITE_MIN_SLEEP_MS==1
|
||||
int delay = 10;
|
||||
int prior_delay = 0;
|
||||
int timeout = (int)Timeout;
|
||||
int i;
|
||||
|
||||
for(i=1; i<count; i++){
|
||||
prior_delay += delay;
|
||||
delay = delay*2;
|
||||
if( delay>=1000 ){
|
||||
delay = 1000;
|
||||
prior_delay += 1000*(count - i - 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if( prior_delay + delay > timeout ){
|
||||
delay = timeout - prior_delay;
|
||||
if( delay<=0 ) return 0;
|
||||
}
|
||||
sqliteOsSleep(delay);
|
||||
return 1;
|
||||
#else
|
||||
int timeout = (int)Timeout;
|
||||
if( (count+1)*1000 > timeout ){
|
||||
return 0;
|
||||
}
|
||||
sqliteOsSleep(1000);
|
||||
return 1;
|
||||
#endif
|
||||
}
|
||||
|
||||
/*
|
||||
** This routine sets the busy callback for an Sqlite database to the
|
||||
** given callback function with the given argument.
|
||||
*/
|
||||
void sqlite_busy_handler(
|
||||
sqlite *db,
|
||||
int (*xBusy)(void*,const char*,int),
|
||||
void *pArg
|
||||
){
|
||||
db->xBusyCallback = xBusy;
|
||||
db->pBusyArg = pArg;
|
||||
}
|
||||
|
||||
/*
|
||||
** This routine installs a default busy handler that waits for the
|
||||
** specified number of milliseconds before returning 0.
|
||||
*/
|
||||
void sqlite_busy_timeout(sqlite *db, int ms){
|
||||
if( ms>0 ){
|
||||
sqlite_busy_handler(db, sqliteDefaultBusyCallback, (void*)ms);
|
||||
}else{
|
||||
sqlite_busy_handler(db, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
** Cause any pending operation to stop at its earliest opportunity.
|
||||
*/
|
||||
void sqlite_interrupt(sqlite *db){
|
||||
db->flags |= SQLITE_Interrupt;
|
||||
}
|
||||
|
||||
/*
|
||||
** Windows systems should call this routine to free memory that
|
||||
** is returned in the in the errmsg parameter of sqlite_open() when
|
||||
** SQLite is a DLL. For some reason, it does not work to call free()
|
||||
** directly.
|
||||
**
|
||||
** Note that we need to call free() not sqliteFree() here, since every
|
||||
** string that is exported from SQLite should have already passed through
|
||||
** sqliteStrRealloc().
|
||||
*/
|
||||
void sqlite_freemem(void *p){ free(p); }
|
||||
|
||||
/*
|
||||
** Windows systems need functions to call to return the sqlite_version
|
||||
** and sqlite_encoding strings since they are unable to access constants
|
||||
** within DLLs.
|
||||
*/
|
||||
const char *sqlite_libversion(void){ return sqlite_version; }
|
||||
const char *sqlite_libencoding(void){ return sqlite_encoding; }
|
||||
|
||||
/*
|
||||
** Create new user-defined functions. The sqlite_create_function()
|
||||
** routine creates a regular function and sqlite_create_aggregate()
|
||||
** creates an aggregate function.
|
||||
**
|
||||
** Passing a NULL xFunc argument or NULL xStep and xFinalize arguments
|
||||
** disables the function. Calling sqlite_create_function() with the
|
||||
** same name and number of arguments as a prior call to
|
||||
** sqlite_create_aggregate() disables the prior call to
|
||||
** sqlite_create_aggregate(), and vice versa.
|
||||
**
|
||||
** If nArg is -1 it means that this function will accept any number
|
||||
** of arguments, including 0.
|
||||
*/
|
||||
int sqlite_create_function(
|
||||
sqlite *db, /* Add the function to this database connection */
|
||||
const char *zName, /* Name of the function to add */
|
||||
int nArg, /* Number of arguments */
|
||||
void (*xFunc)(sqlite_func*,int,const char**), /* The implementation */
|
||||
void *pUserData /* User data */
|
||||
){
|
||||
FuncDef *p;
|
||||
int nName;
|
||||
if( db==0 || zName==0 || sqliteSafetyCheck(db) ) return 1;
|
||||
nName = strlen(zName);
|
||||
if( nName>255 ) return 1;
|
||||
p = sqliteFindFunction(db, zName, nName, nArg, 1);
|
||||
if( p==0 ) return 1;
|
||||
p->xFunc = xFunc;
|
||||
p->xStep = 0;
|
||||
p->xFinalize = 0;
|
||||
p->pUserData = pUserData;
|
||||
return 0;
|
||||
}
|
||||
int sqlite_create_aggregate(
|
||||
sqlite *db, /* Add the function to this database connection */
|
||||
const char *zName, /* Name of the function to add */
|
||||
int nArg, /* Number of arguments */
|
||||
void (*xStep)(sqlite_func*,int,const char**), /* The step function */
|
||||
void (*xFinalize)(sqlite_func*), /* The finalizer */
|
||||
void *pUserData /* User data */
|
||||
){
|
||||
FuncDef *p;
|
||||
int nName;
|
||||
if( db==0 || zName==0 || sqliteSafetyCheck(db) ) return 1;
|
||||
nName = strlen(zName);
|
||||
if( nName>255 ) return 1;
|
||||
p = sqliteFindFunction(db, zName, nName, nArg, 1);
|
||||
if( p==0 ) return 1;
|
||||
p->xFunc = 0;
|
||||
p->xStep = xStep;
|
||||
p->xFinalize = xFinalize;
|
||||
p->pUserData = pUserData;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
** Change the datatype for all functions with a given name. See the
|
||||
** header comment for the prototype of this function in sqlite.h for
|
||||
** additional information.
|
||||
*/
|
||||
int sqlite_function_type(sqlite *db, const char *zName, int dataType){
|
||||
FuncDef *p = (FuncDef*)sqliteHashFind(&db->aFunc, zName, strlen(zName));
|
||||
while( p ){
|
||||
p->dataType = dataType;
|
||||
p = p->pNext;
|
||||
}
|
||||
return SQLITE_OK;
|
||||
}
|
||||
|
||||
/*
|
||||
** Register a trace function. The pArg from the previously registered trace
|
||||
** is returned.
|
||||
**
|
||||
** A NULL trace function means that no tracing is executes. A non-NULL
|
||||
** trace is a pointer to a function that is invoked at the start of each
|
||||
** sqlite_exec().
|
||||
*/
|
||||
void *sqlite_trace(sqlite *db, void (*xTrace)(void*,const char*), void *pArg){
|
||||
#ifndef SQLITE_OMIT_TRACE
|
||||
void *pOld = db->pTraceArg;
|
||||
db->xTrace = xTrace;
|
||||
db->pTraceArg = pArg;
|
||||
return pOld;
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Attempt to open the file named in the argument as the auxiliary database
|
||||
** file. The auxiliary database file is used to store TEMP tables. But
|
||||
** by using this API, it is possible to trick SQLite into opening two
|
||||
** separate databases and acting on them as if they were one.
|
||||
**
|
||||
** This routine closes the existing auxiliary database file, which will
|
||||
** cause any previously created TEMP tables to be dropped.
|
||||
**
|
||||
** The zName parameter can be a NULL pointer or an empty string to cause
|
||||
** a temporary file to be opened and automatically deleted when closed.
|
||||
*/
|
||||
int sqlite_open_aux_file(sqlite *db, const char *zName, char **pzErrMsg){
|
||||
int rc;
|
||||
if( zName && zName[0]==0 ) zName = 0;
|
||||
if( sqliteSafetyOn(db) ) goto openaux_misuse;
|
||||
sqliteResetInternalSchema(db);
|
||||
if( db->pBeTemp!=0 ){
|
||||
sqliteBtreeClose(db->pBeTemp);
|
||||
}
|
||||
rc = sqliteBtreeOpen(zName, 0, MAX_PAGES, &db->pBeTemp);
|
||||
if( rc ){
|
||||
if( zName==0 ) zName = "a temporary file";
|
||||
sqliteSetString(pzErrMsg, "unable to open ", zName,
|
||||
": ", sqlite_error_string(rc), 0);
|
||||
sqliteStrRealloc(pzErrMsg);
|
||||
sqliteSafetyOff(db);
|
||||
return rc;
|
||||
}
|
||||
rc = sqliteInit(db, pzErrMsg);
|
||||
if( sqliteSafetyOff(db) ) goto openaux_misuse;
|
||||
sqliteStrRealloc(pzErrMsg);
|
||||
return rc;
|
||||
|
||||
openaux_misuse:
|
||||
sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), 0);
|
||||
sqliteStrRealloc(pzErrMsg);
|
||||
return SQLITE_MISUSE;
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
/* Automatically generated file. Do not edit */
|
||||
#define OP_Goto 1
|
||||
#define OP_Gosub 2
|
||||
#define OP_Return 3
|
||||
#define OP_Halt 4
|
||||
#define OP_Integer 5
|
||||
#define OP_String 6
|
||||
#define OP_Pop 7
|
||||
#define OP_Dup 8
|
||||
#define OP_Pull 9
|
||||
#define OP_Push 10
|
||||
#define OP_ColumnName 11
|
||||
#define OP_Callback 12
|
||||
#define OP_NullCallback 13
|
||||
#define OP_Concat 14
|
||||
#define OP_Add 15
|
||||
#define OP_Subtract 16
|
||||
#define OP_Multiply 17
|
||||
#define OP_Divide 18
|
||||
#define OP_Remainder 19
|
||||
#define OP_Function 20
|
||||
#define OP_BitAnd 21
|
||||
#define OP_BitOr 22
|
||||
#define OP_ShiftLeft 23
|
||||
#define OP_ShiftRight 24
|
||||
#define OP_AddImm 25
|
||||
#define OP_MustBeInt 26
|
||||
#define OP_Eq 27
|
||||
#define OP_Ne 28
|
||||
#define OP_Lt 29
|
||||
#define OP_Le 30
|
||||
#define OP_Gt 31
|
||||
#define OP_Ge 32
|
||||
#define OP_StrEq 33
|
||||
#define OP_StrNe 34
|
||||
#define OP_StrLt 35
|
||||
#define OP_StrLe 36
|
||||
#define OP_StrGt 37
|
||||
#define OP_StrGe 38
|
||||
#define OP_And 39
|
||||
#define OP_Or 40
|
||||
#define OP_Negative 41
|
||||
#define OP_AbsValue 42
|
||||
#define OP_Not 43
|
||||
#define OP_BitNot 44
|
||||
#define OP_Noop 45
|
||||
#define OP_If 46
|
||||
#define OP_IfNot 47
|
||||
#define OP_IsNull 48
|
||||
#define OP_NotNull 49
|
||||
#define OP_MakeRecord 50
|
||||
#define OP_MakeIdxKey 51
|
||||
#define OP_MakeKey 52
|
||||
#define OP_IncrKey 53
|
||||
#define OP_Checkpoint 54
|
||||
#define OP_Transaction 55
|
||||
#define OP_Commit 56
|
||||
#define OP_Rollback 57
|
||||
#define OP_ReadCookie 58
|
||||
#define OP_SetCookie 59
|
||||
#define OP_VerifyCookie 60
|
||||
#define OP_OpenAux 61
|
||||
#define OP_OpenWrAux 62
|
||||
#define OP_OpenWrite 63
|
||||
#define OP_Open 64
|
||||
#define OP_OpenTemp 65
|
||||
#define OP_RenameCursor 66
|
||||
#define OP_Close 67
|
||||
#define OP_MoveLt 68
|
||||
#define OP_MoveTo 69
|
||||
#define OP_Distinct 70
|
||||
#define OP_NotFound 71
|
||||
#define OP_Found 72
|
||||
#define OP_IsUnique 73
|
||||
#define OP_NotExists 74
|
||||
#define OP_NewRecno 75
|
||||
#define OP_PutIntKey 76
|
||||
#define OP_PutStrKey 77
|
||||
#define OP_Delete 78
|
||||
#define OP_KeyAsData 79
|
||||
#define OP_Column 80
|
||||
#define OP_Recno 81
|
||||
#define OP_FullKey 82
|
||||
#define OP_NullRow 83
|
||||
#define OP_Last 84
|
||||
#define OP_Rewind 85
|
||||
#define OP_Prev 86
|
||||
#define OP_Next 87
|
||||
#define OP_IdxPut 88
|
||||
#define OP_IdxDelete 89
|
||||
#define OP_IdxRecno 90
|
||||
#define OP_IdxLT 91
|
||||
#define OP_IdxGT 92
|
||||
#define OP_IdxGE 93
|
||||
#define OP_Destroy 94
|
||||
#define OP_Clear 95
|
||||
#define OP_CreateIndex 96
|
||||
#define OP_CreateTable 97
|
||||
#define OP_IntegrityCk 98
|
||||
#define OP_ListWrite 99
|
||||
#define OP_ListRewind 100
|
||||
#define OP_ListRead 101
|
||||
#define OP_ListReset 102
|
||||
#define OP_ListPush 103
|
||||
#define OP_ListPop 104
|
||||
#define OP_SortPut 105
|
||||
#define OP_SortMakeRec 106
|
||||
#define OP_SortMakeKey 107
|
||||
#define OP_Sort 108
|
||||
#define OP_SortNext 109
|
||||
#define OP_SortCallback 110
|
||||
#define OP_SortReset 111
|
||||
#define OP_FileOpen 112
|
||||
#define OP_FileRead 113
|
||||
#define OP_FileColumn 114
|
||||
#define OP_MemStore 115
|
||||
#define OP_MemLoad 116
|
||||
#define OP_MemIncr 117
|
||||
#define OP_AggReset 118
|
||||
#define OP_AggInit 119
|
||||
#define OP_AggFunc 120
|
||||
#define OP_AggFocus 121
|
||||
#define OP_AggSet 122
|
||||
#define OP_AggGet 123
|
||||
#define OP_AggNext 124
|
||||
#define OP_SetInsert 125
|
||||
#define OP_SetFound 126
|
||||
#define OP_SetNotFound 127
|
||||
#define OP_SetFirst 128
|
||||
#define OP_SetNext 129
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,172 +0,0 @@
|
||||
/*
|
||||
** 2001 September 16
|
||||
**
|
||||
** 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 (together with is companion C source-code file
|
||||
** "os.c") attempt to abstract the underlying operating system so that
|
||||
** the SQLite library will work on both POSIX and windows systems.
|
||||
*/
|
||||
#ifndef _SQLITE_OS_H_
|
||||
#define _SQLITE_OS_H_
|
||||
|
||||
/*
|
||||
** These #defines should enable >2GB file support on Posix if the
|
||||
** underlying operating system supports it. If the OS lacks
|
||||
** large file support, or if the OS is windows, these should be no-ops.
|
||||
**
|
||||
** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
|
||||
** on the compiler command line. This is necessary if you are compiling
|
||||
** on a recent machine (ex: RedHat 7.2) but you want your code to work
|
||||
** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
|
||||
** without this option, LFS is enable. But LFS does not exist in the kernel
|
||||
** in RedHat 6.0, so the code won't work. Hence, for maximum binary
|
||||
** portability you should omit LFS.
|
||||
**
|
||||
** Similar is true for MacOS. LFS is only supported on MacOS 9 and later.
|
||||
*/
|
||||
#ifndef SQLITE_DISABLE_LFS
|
||||
# define _LARGE_FILE 1
|
||||
# define _FILE_OFFSET_BITS 64
|
||||
# define _LARGEFILE_SOURCE 1
|
||||
#endif
|
||||
|
||||
/*
|
||||
** Temporary files are named starting with this prefix followed by 16 random
|
||||
** alphanumeric characters, and no file extension. They are stored in the
|
||||
** OS's standard temporary file directory, and are deleted prior to exit.
|
||||
** If sqlite is being embedded in another program, you may wish to change the
|
||||
** prefix to reflect your program's name, so that if your program exits
|
||||
** prematurely, old temporary files can be easily identified. This can be done
|
||||
** using -DTEMP_FILE_PREFIX=myprefix_ on the compiler command line.
|
||||
*/
|
||||
#ifndef TEMP_FILE_PREFIX
|
||||
# define TEMP_FILE_PREFIX "sqlite_"
|
||||
#endif
|
||||
|
||||
/*
|
||||
** Figure out if we are dealing with Unix, Windows or MacOS.
|
||||
**
|
||||
** N.B. MacOS means Mac Classic (or Carbon). Treat Darwin (OS X) as Unix.
|
||||
** The MacOS build is designed to use CodeWarrior (tested with v8)
|
||||
*/
|
||||
#ifndef OS_UNIX
|
||||
# ifndef OS_WIN
|
||||
# ifndef OS_MAC
|
||||
# if defined(__MACOS__)
|
||||
# define OS_MAC 1
|
||||
# define OS_WIN 0
|
||||
# define OS_UNIX 0
|
||||
# elif defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
|
||||
# define OS_MAC 0
|
||||
# define OS_WIN 1
|
||||
# define OS_UNIX 0
|
||||
# else
|
||||
# define OS_MAC 0
|
||||
# define OS_WIN 0
|
||||
# define OS_UNIX 1
|
||||
# endif
|
||||
# else
|
||||
# define OS_WIN 0
|
||||
# define OS_UNIX 0
|
||||
# endif
|
||||
# else
|
||||
# define OS_MAC 0
|
||||
# define OS_UNIX 0
|
||||
# endif
|
||||
#else
|
||||
# define OS_MAC 0
|
||||
# define OS_WIN 0
|
||||
#endif
|
||||
|
||||
/*
|
||||
** A handle for an open file is stored in an OsFile object.
|
||||
*/
|
||||
#if OS_UNIX
|
||||
# include <sys/types.h>
|
||||
# include <sys/stat.h>
|
||||
# include <fcntl.h>
|
||||
# include <unistd.h>
|
||||
typedef struct OsFile OsFile;
|
||||
struct OsFile {
|
||||
struct lockInfo *pLock; /* Information about locks on this inode */
|
||||
int fd; /* The file descriptor */
|
||||
int locked; /* True if this user holds the lock */
|
||||
};
|
||||
# define SQLITE_TEMPNAME_SIZE 200
|
||||
# if defined(HAVE_USLEEP) && HAVE_USLEEP
|
||||
# define SQLITE_MIN_SLEEP_MS 1
|
||||
# else
|
||||
# define SQLITE_MIN_SLEEP_MS 1000
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#if OS_WIN
|
||||
#include <windows.h>
|
||||
#include <winbase.h>
|
||||
typedef struct OsFile OsFile;
|
||||
struct OsFile {
|
||||
HANDLE h; /* Handle for accessing the file */
|
||||
int locked; /* 0: unlocked, <0: write lock, >0: read lock */
|
||||
};
|
||||
# if defined(_MSC_VER) || defined(__BORLANDC__)
|
||||
typedef __int64 off_t;
|
||||
# else
|
||||
typedef long long off_t;
|
||||
# endif
|
||||
# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
|
||||
# define SQLITE_MIN_SLEEP_MS 1
|
||||
#endif
|
||||
|
||||
#if OS_MAC
|
||||
# include <unistd.h>
|
||||
# include <Files.h>
|
||||
typedef struct OsFile OsFile;
|
||||
struct OsFile {
|
||||
SInt16 refNum; /* Data fork/file reference number */
|
||||
SInt16 refNumRF; /* Resource fork reference number (for locking) */
|
||||
int locked; /* 0: unlocked, <0: write lock, >0: read lock */
|
||||
int delOnClose; /* True if file is to be deleted on close */
|
||||
char *pathToDel; /* Name of file to delete on close */
|
||||
};
|
||||
# ifdef _LARGE_FILE
|
||||
typedef SInt64 off_t;
|
||||
# else
|
||||
typedef SInt32 off_t;
|
||||
# endif
|
||||
# define SQLITE_TEMPNAME_SIZE _MAX_PATH
|
||||
# define SQLITE_MIN_SLEEP_MS 17
|
||||
#endif
|
||||
|
||||
int sqliteOsDelete(const char*);
|
||||
int sqliteOsFileExists(const char*);
|
||||
int sqliteOsOpenReadWrite(const char*, OsFile*, int*);
|
||||
int sqliteOsOpenExclusive(const char*, OsFile*, int);
|
||||
int sqliteOsOpenReadOnly(const char*, OsFile*);
|
||||
int sqliteOsTempFileName(char*);
|
||||
int sqliteOsClose(OsFile*);
|
||||
int sqliteOsRead(OsFile*, void*, int amt);
|
||||
int sqliteOsWrite(OsFile*, const void*, int amt);
|
||||
int sqliteOsSeek(OsFile*, off_t offset);
|
||||
int sqliteOsSync(OsFile*);
|
||||
int sqliteOsTruncate(OsFile*, off_t size);
|
||||
int sqliteOsFileSize(OsFile*, off_t *pSize);
|
||||
int sqliteOsReadLock(OsFile*);
|
||||
int sqliteOsWriteLock(OsFile*);
|
||||
int sqliteOsUnlock(OsFile*);
|
||||
int sqliteOsRandomSeed(char*);
|
||||
int sqliteOsSleep(int ms);
|
||||
void sqliteOsEnterMutex(void);
|
||||
void sqliteOsLeaveMutex(void);
|
||||
char *sqliteOsFullPathname(const char*);
|
||||
|
||||
|
||||
|
||||
#endif /* _SQLITE_OS_H_ */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,79 +0,0 @@
|
||||
/*
|
||||
** 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 page cache
|
||||
** subsystem. The page cache subsystem reads and writes a file a page
|
||||
** at a time and provides a journal for rollback.
|
||||
**
|
||||
** @(#) $Id$
|
||||
*/
|
||||
|
||||
/*
|
||||
** The size of one page
|
||||
**
|
||||
** You can change this value to another (reasonable) power of two
|
||||
** such as 512, 2048, 4096, or 8192 and things will still work. But
|
||||
** experiments show that a page size of 1024 gives the best speed.
|
||||
** (The speed differences are minimal.)
|
||||
*/
|
||||
#define SQLITE_PAGE_SIZE 1024
|
||||
|
||||
/*
|
||||
** Maximum number of pages in one database. (This is a limitation of
|
||||
** imposed by 4GB files size limits.)
|
||||
*/
|
||||
#define SQLITE_MAX_PAGE 1073741823
|
||||
|
||||
/*
|
||||
** The type used to represent a page number. The first page in a file
|
||||
** is called page 1. 0 is used to represent "not a page".
|
||||
*/
|
||||
typedef unsigned int Pgno;
|
||||
|
||||
/*
|
||||
** Each open file is managed by a separate instance of the "Pager" structure.
|
||||
*/
|
||||
typedef struct Pager Pager;
|
||||
|
||||
/*
|
||||
** See source code comments for a detailed description of the following
|
||||
** routines:
|
||||
*/
|
||||
int sqlitepager_open(Pager **ppPager, const char *zFilename,
|
||||
int nPage, int nExtra, int useJournal);
|
||||
void sqlitepager_set_destructor(Pager*, void(*)(void*));
|
||||
void sqlitepager_set_cachesize(Pager*, int);
|
||||
int sqlitepager_close(Pager *pPager);
|
||||
int sqlitepager_get(Pager *pPager, Pgno pgno, void **ppPage);
|
||||
void *sqlitepager_lookup(Pager *pPager, Pgno pgno);
|
||||
int sqlitepager_ref(void*);
|
||||
int sqlitepager_unref(void*);
|
||||
Pgno sqlitepager_pagenumber(void*);
|
||||
int sqlitepager_write(void*);
|
||||
int sqlitepager_iswriteable(void*);
|
||||
int sqlitepager_pagecount(Pager*);
|
||||
int sqlitepager_begin(void*);
|
||||
int sqlitepager_commit(Pager*);
|
||||
int sqlitepager_rollback(Pager*);
|
||||
int sqlitepager_isreadonly(Pager*);
|
||||
int sqlitepager_ckpt_begin(Pager*);
|
||||
int sqlitepager_ckpt_commit(Pager*);
|
||||
int sqlitepager_ckpt_rollback(Pager*);
|
||||
void sqlitepager_dont_rollback(void*);
|
||||
void sqlitepager_dont_write(Pager*, Pgno);
|
||||
int *sqlitepager_stats(Pager*);
|
||||
void sqlitepager_set_safety_level(Pager*,int);
|
||||
|
||||
#ifdef SQLITE_TEST
|
||||
void sqlitepager_refdump(Pager*);
|
||||
int pager_refinfo_enable;
|
||||
int journal_format;
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,127 +0,0 @@
|
||||
#define TK_ABORT 1
|
||||
#define TK_AFTER 2
|
||||
#define TK_AGG_FUNCTION 3
|
||||
#define TK_ALL 4
|
||||
#define TK_AND 5
|
||||
#define TK_AS 6
|
||||
#define TK_ASC 7
|
||||
#define TK_BEFORE 8
|
||||
#define TK_BEGIN 9
|
||||
#define TK_BETWEEN 10
|
||||
#define TK_BITAND 11
|
||||
#define TK_BITNOT 12
|
||||
#define TK_BITOR 13
|
||||
#define TK_BY 14
|
||||
#define TK_CASCADE 15
|
||||
#define TK_CASE 16
|
||||
#define TK_CHECK 17
|
||||
#define TK_CLUSTER 18
|
||||
#define TK_COLLATE 19
|
||||
#define TK_COLUMN 20
|
||||
#define TK_COMMA 21
|
||||
#define TK_COMMENT 22
|
||||
#define TK_COMMIT 23
|
||||
#define TK_CONCAT 24
|
||||
#define TK_CONFLICT 25
|
||||
#define TK_CONSTRAINT 26
|
||||
#define TK_COPY 27
|
||||
#define TK_CREATE 28
|
||||
#define TK_DEFAULT 29
|
||||
#define TK_DEFERRABLE 30
|
||||
#define TK_DEFERRED 31
|
||||
#define TK_DELETE 32
|
||||
#define TK_DELIMITERS 33
|
||||
#define TK_DESC 34
|
||||
#define TK_DISTINCT 35
|
||||
#define TK_DOT 36
|
||||
#define TK_DROP 37
|
||||
#define TK_EACH 38
|
||||
#define TK_ELSE 39
|
||||
#define TK_END 40
|
||||
#define TK_END_OF_FILE 41
|
||||
#define TK_EQ 42
|
||||
#define TK_EXCEPT 43
|
||||
#define TK_EXPLAIN 44
|
||||
#define TK_FAIL 45
|
||||
#define TK_FLOAT 46
|
||||
#define TK_FOR 47
|
||||
#define TK_FOREIGN 48
|
||||
#define TK_FROM 49
|
||||
#define TK_FUNCTION 50
|
||||
#define TK_GE 51
|
||||
#define TK_GLOB 52
|
||||
#define TK_GROUP 53
|
||||
#define TK_GT 54
|
||||
#define TK_HAVING 55
|
||||
#define TK_ID 56
|
||||
#define TK_IGNORE 57
|
||||
#define TK_ILLEGAL 58
|
||||
#define TK_IMMEDIATE 59
|
||||
#define TK_IN 60
|
||||
#define TK_INDEX 61
|
||||
#define TK_INITIALLY 62
|
||||
#define TK_INSERT 63
|
||||
#define TK_INSTEAD 64
|
||||
#define TK_INTEGER 65
|
||||
#define TK_INTERSECT 66
|
||||
#define TK_INTO 67
|
||||
#define TK_IS 68
|
||||
#define TK_ISNULL 69
|
||||
#define TK_JOIN 70
|
||||
#define TK_JOIN_KW 71
|
||||
#define TK_KEY 72
|
||||
#define TK_LE 73
|
||||
#define TK_LIKE 74
|
||||
#define TK_LIMIT 75
|
||||
#define TK_LP 76
|
||||
#define TK_LSHIFT 77
|
||||
#define TK_LT 78
|
||||
#define TK_MATCH 79
|
||||
#define TK_MINUS 80
|
||||
#define TK_NE 81
|
||||
#define TK_NOT 82
|
||||
#define TK_NOTNULL 83
|
||||
#define TK_NULL 84
|
||||
#define TK_OF 85
|
||||
#define TK_OFFSET 86
|
||||
#define TK_ON 87
|
||||
#define TK_OR 88
|
||||
#define TK_ORACLE_OUTER_JOIN 89
|
||||
#define TK_ORDER 90
|
||||
#define TK_PLUS 91
|
||||
#define TK_PRAGMA 92
|
||||
#define TK_PRIMARY 93
|
||||
#define TK_RAISE 94
|
||||
#define TK_REFERENCES 95
|
||||
#define TK_REM 96
|
||||
#define TK_REPLACE 97
|
||||
#define TK_RESTRICT 98
|
||||
#define TK_ROLLBACK 99
|
||||
#define TK_ROW 100
|
||||
#define TK_RP 101
|
||||
#define TK_RSHIFT 102
|
||||
#define TK_SELECT 103
|
||||
#define TK_SEMI 104
|
||||
#define TK_SET 105
|
||||
#define TK_SLASH 106
|
||||
#define TK_SPACE 107
|
||||
#define TK_STAR 108
|
||||
#define TK_STATEMENT 109
|
||||
#define TK_STRING 110
|
||||
#define TK_TABLE 111
|
||||
#define TK_TEMP 112
|
||||
#define TK_THEN 113
|
||||
#define TK_TRANSACTION 114
|
||||
#define TK_TRIGGER 115
|
||||
#define TK_UMINUS 116
|
||||
#define TK_UNCLOSED_STRING 117
|
||||
#define TK_UNION 118
|
||||
#define TK_UNIQUE 119
|
||||
#define TK_UPDATE 120
|
||||
#define TK_UPLUS 121
|
||||
#define TK_USING 122
|
||||
#define TK_VACUUM 123
|
||||
#define TK_VALUES 124
|
||||
#define TK_VIEW 125
|
||||
#define TK_WHEN 126
|
||||
#define TK_WHERE 127
|
||||
@@ -1,827 +0,0 @@
|
||||
/*
|
||||
** 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 SQLite's grammar for SQL. Process this file
|
||||
** using the lemon parser generator to generate C code that runs
|
||||
** the parser. Lemon will also generate a header file containing
|
||||
** numeric codes for all of the tokens.
|
||||
**
|
||||
** @(#) $Id$
|
||||
*/
|
||||
%token_prefix TK_
|
||||
%token_type {Token}
|
||||
%default_type {Token}
|
||||
%extra_argument {Parse *pParse}
|
||||
%syntax_error {
|
||||
if( pParse->zErrMsg==0 ){
|
||||
if( TOKEN.z[0] ){
|
||||
sqliteSetNString(&pParse->zErrMsg,
|
||||
"near \"", -1, TOKEN.z, TOKEN.n, "\": syntax error", -1, 0);
|
||||
}else{
|
||||
sqliteSetString(&pParse->zErrMsg, "incomplete SQL statement", 0);
|
||||
}
|
||||
}
|
||||
pParse->nErr++;
|
||||
}
|
||||
%name sqliteParser
|
||||
%include {
|
||||
#include "sqliteInt.h"
|
||||
#include "parse.h"
|
||||
|
||||
/*
|
||||
** An instance of this structure holds information about the
|
||||
** LIMIT clause of a SELECT statement.
|
||||
*/
|
||||
struct LimitVal {
|
||||
int limit; /* The LIMIT value. -1 if there is no limit */
|
||||
int offset; /* The OFFSET. 0 if there is none */
|
||||
};
|
||||
|
||||
/*
|
||||
** An instance of the following structure describes the event of a
|
||||
** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
|
||||
** TK_DELETE, or TK_INSTEAD. If the event is of the form
|
||||
**
|
||||
** UPDATE ON (a,b,c)
|
||||
**
|
||||
** Then the "b" IdList records the list "a,b,c".
|
||||
*/
|
||||
struct TrigEvent { int a; IdList * b; };
|
||||
|
||||
} // end %include
|
||||
|
||||
// These are extra tokens used by the lexer but never seen by the
|
||||
// parser. We put them in a rule so that the parser generator will
|
||||
// add them to the parse.h output file.
|
||||
//
|
||||
%nonassoc END_OF_FILE ILLEGAL SPACE UNCLOSED_STRING COMMENT FUNCTION
|
||||
COLUMN AGG_FUNCTION.
|
||||
|
||||
// Input is zero or more commands.
|
||||
input ::= cmdlist.
|
||||
|
||||
// A list of commands is zero or more commands
|
||||
//
|
||||
cmdlist ::= ecmd.
|
||||
cmdlist ::= cmdlist ecmd.
|
||||
ecmd ::= explain cmdx SEMI.
|
||||
ecmd ::= SEMI.
|
||||
cmdx ::= cmd. { sqliteExec(pParse); }
|
||||
explain ::= EXPLAIN. { sqliteBeginParse(pParse, 1); }
|
||||
explain ::= . { sqliteBeginParse(pParse, 0); }
|
||||
|
||||
///////////////////// Begin and end transactions. ////////////////////////////
|
||||
//
|
||||
|
||||
cmd ::= BEGIN trans_opt onconf(R). {sqliteBeginTransaction(pParse,R);}
|
||||
trans_opt ::= .
|
||||
trans_opt ::= TRANSACTION.
|
||||
trans_opt ::= TRANSACTION nm.
|
||||
cmd ::= COMMIT trans_opt. {sqliteCommitTransaction(pParse);}
|
||||
cmd ::= END trans_opt. {sqliteCommitTransaction(pParse);}
|
||||
cmd ::= ROLLBACK trans_opt. {sqliteRollbackTransaction(pParse);}
|
||||
|
||||
///////////////////// The CREATE TABLE statement ////////////////////////////
|
||||
//
|
||||
cmd ::= create_table create_table_args.
|
||||
create_table ::= CREATE(X) temp(T) TABLE nm(Y). {
|
||||
sqliteStartTable(pParse,&X,&Y,T,0);
|
||||
}
|
||||
%type temp {int}
|
||||
temp(A) ::= TEMP. {A = pParse->isTemp || !pParse->initFlag;}
|
||||
temp(A) ::= . {A = pParse->isTemp;}
|
||||
create_table_args ::= LP columnlist conslist_opt RP(X). {
|
||||
sqliteEndTable(pParse,&X,0);
|
||||
}
|
||||
create_table_args ::= AS select(S). {
|
||||
sqliteEndTable(pParse,0,S);
|
||||
sqliteSelectDelete(S);
|
||||
}
|
||||
columnlist ::= columnlist COMMA column.
|
||||
columnlist ::= column.
|
||||
|
||||
// About the only information used for a column is the name of the
|
||||
// column. The type is always just "text". But the code will accept
|
||||
// an elaborate typename. Perhaps someday we'll do something with it.
|
||||
//
|
||||
column ::= columnid type carglist.
|
||||
columnid ::= nm(X). {sqliteAddColumn(pParse,&X);}
|
||||
|
||||
// An IDENTIFIER can be a generic identifier, or one of several
|
||||
// keywords. Any non-standard keyword can also be an identifier.
|
||||
//
|
||||
%type id {Token}
|
||||
id(A) ::= ID(X). {A = X;}
|
||||
|
||||
// The following directive causes tokens ABORT, AFTER, ASC, etc. to
|
||||
// fallback to ID if they will not parse as their original value.
|
||||
// This obviates the need for the "id" nonterminal.
|
||||
//
|
||||
%fallback ID
|
||||
ABORT AFTER ASC BEFORE BEGIN CASCADE CLUSTER CONFLICT
|
||||
COPY DEFERRED DELIMITERS DESC EACH END EXPLAIN FAIL FOR
|
||||
IGNORE IMMEDIATE INITIALLY INSTEAD MATCH KEY
|
||||
OF OFFSET PRAGMA RAISE REPLACE RESTRICT ROW STATEMENT
|
||||
TEMP TRIGGER VACUUM VIEW.
|
||||
|
||||
// And "ids" is an identifer-or-string.
|
||||
//
|
||||
%type ids {Token}
|
||||
ids(A) ::= ID(X). {A = X;}
|
||||
ids(A) ::= STRING(X). {A = X;}
|
||||
|
||||
// The name of a column or table can be any of the following:
|
||||
//
|
||||
%type nm {Token}
|
||||
nm(A) ::= ID(X). {A = X;}
|
||||
nm(A) ::= STRING(X). {A = X;}
|
||||
nm(A) ::= JOIN_KW(X). {A = X;}
|
||||
|
||||
type ::= .
|
||||
type ::= typename(X). {sqliteAddColumnType(pParse,&X,&X);}
|
||||
type ::= typename(X) LP signed RP(Y). {sqliteAddColumnType(pParse,&X,&Y);}
|
||||
type ::= typename(X) LP signed COMMA signed RP(Y).
|
||||
{sqliteAddColumnType(pParse,&X,&Y);}
|
||||
%type typename {Token}
|
||||
typename(A) ::= ids(X). {A = X;}
|
||||
typename(A) ::= typename(X) ids. {A = X;}
|
||||
signed ::= INTEGER.
|
||||
signed ::= PLUS INTEGER.
|
||||
signed ::= MINUS INTEGER.
|
||||
carglist ::= carglist carg.
|
||||
carglist ::= .
|
||||
carg ::= CONSTRAINT nm ccons.
|
||||
carg ::= ccons.
|
||||
carg ::= DEFAULT STRING(X). {sqliteAddDefaultValue(pParse,&X,0);}
|
||||
carg ::= DEFAULT ID(X). {sqliteAddDefaultValue(pParse,&X,0);}
|
||||
carg ::= DEFAULT INTEGER(X). {sqliteAddDefaultValue(pParse,&X,0);}
|
||||
carg ::= DEFAULT PLUS INTEGER(X). {sqliteAddDefaultValue(pParse,&X,0);}
|
||||
carg ::= DEFAULT MINUS INTEGER(X). {sqliteAddDefaultValue(pParse,&X,1);}
|
||||
carg ::= DEFAULT FLOAT(X). {sqliteAddDefaultValue(pParse,&X,0);}
|
||||
carg ::= DEFAULT PLUS FLOAT(X). {sqliteAddDefaultValue(pParse,&X,0);}
|
||||
carg ::= DEFAULT MINUS FLOAT(X). {sqliteAddDefaultValue(pParse,&X,1);}
|
||||
carg ::= DEFAULT NULL.
|
||||
|
||||
// In addition to the type name, we also care about the primary key and
|
||||
// UNIQUE constraints.
|
||||
//
|
||||
ccons ::= NULL onconf.
|
||||
ccons ::= NOT NULL onconf(R). {sqliteAddNotNull(pParse, R);}
|
||||
ccons ::= PRIMARY KEY sortorder onconf(R). {sqliteAddPrimaryKey(pParse,0,R);}
|
||||
ccons ::= UNIQUE onconf(R). {sqliteCreateIndex(pParse,0,0,0,R,0,0);}
|
||||
ccons ::= CHECK LP expr RP onconf.
|
||||
ccons ::= REFERENCES nm(T) idxlist_opt(TA) refargs(R).
|
||||
{sqliteCreateForeignKey(pParse,0,&T,TA,R);}
|
||||
ccons ::= defer_subclause(D). {sqliteDeferForeignKey(pParse,D);}
|
||||
ccons ::= COLLATE id(C). {
|
||||
sqliteAddCollateType(pParse, sqliteCollateType(C.z, C.n));
|
||||
}
|
||||
|
||||
// The next group of rules parses the arguments to a REFERENCES clause
|
||||
// that determine if the referential integrity checking is deferred or
|
||||
// or immediate and which determine what action to take if a ref-integ
|
||||
// check fails.
|
||||
//
|
||||
%type refargs {int}
|
||||
refargs(A) ::= . { A = OE_Restrict * 0x010101; }
|
||||
refargs(A) ::= refargs(X) refarg(Y). { A = (X & Y.mask) | Y.value; }
|
||||
%type refarg {struct {int value; int mask;}}
|
||||
refarg(A) ::= MATCH nm. { A.value = 0; A.mask = 0x000000; }
|
||||
refarg(A) ::= ON DELETE refact(X). { A.value = X; A.mask = 0x0000ff; }
|
||||
refarg(A) ::= ON UPDATE refact(X). { A.value = X<<8; A.mask = 0x00ff00; }
|
||||
refarg(A) ::= ON INSERT refact(X). { A.value = X<<16; A.mask = 0xff0000; }
|
||||
%type refact {int}
|
||||
refact(A) ::= SET NULL. { A = OE_SetNull; }
|
||||
refact(A) ::= SET DEFAULT. { A = OE_SetDflt; }
|
||||
refact(A) ::= CASCADE. { A = OE_Cascade; }
|
||||
refact(A) ::= RESTRICT. { A = OE_Restrict; }
|
||||
%type defer_subclause {int}
|
||||
defer_subclause(A) ::= NOT DEFERRABLE init_deferred_pred_opt(X). {A = X;}
|
||||
defer_subclause(A) ::= DEFERRABLE init_deferred_pred_opt(X). {A = X;}
|
||||
%type init_deferred_pred_opt {int}
|
||||
init_deferred_pred_opt(A) ::= . {A = 0;}
|
||||
init_deferred_pred_opt(A) ::= INITIALLY DEFERRED. {A = 1;}
|
||||
init_deferred_pred_opt(A) ::= INITIALLY IMMEDIATE. {A = 0;}
|
||||
|
||||
// For the time being, the only constraint we care about is the primary
|
||||
// key and UNIQUE. Both create indices.
|
||||
//
|
||||
conslist_opt ::= .
|
||||
conslist_opt ::= COMMA conslist.
|
||||
conslist ::= conslist COMMA tcons.
|
||||
conslist ::= conslist tcons.
|
||||
conslist ::= tcons.
|
||||
tcons ::= CONSTRAINT nm.
|
||||
tcons ::= PRIMARY KEY LP idxlist(X) RP onconf(R).
|
||||
{sqliteAddPrimaryKey(pParse,X,R);}
|
||||
tcons ::= UNIQUE LP idxlist(X) RP onconf(R).
|
||||
{sqliteCreateIndex(pParse,0,0,X,R,0,0);}
|
||||
tcons ::= CHECK expr onconf.
|
||||
tcons ::= FOREIGN KEY LP idxlist(FA) RP
|
||||
REFERENCES nm(T) idxlist_opt(TA) refargs(R) defer_subclause_opt(D). {
|
||||
sqliteCreateForeignKey(pParse, FA, &T, TA, R);
|
||||
sqliteDeferForeignKey(pParse, D);
|
||||
}
|
||||
%type defer_subclause_opt {int}
|
||||
defer_subclause_opt(A) ::= . {A = 0;}
|
||||
defer_subclause_opt(A) ::= defer_subclause(X). {A = X;}
|
||||
|
||||
// The following is a non-standard extension that allows us to declare the
|
||||
// default behavior when there is a constraint conflict.
|
||||
//
|
||||
%type onconf {int}
|
||||
%type orconf {int}
|
||||
%type resolvetype {int}
|
||||
onconf(A) ::= . { A = OE_Default; }
|
||||
onconf(A) ::= ON CONFLICT resolvetype(X). { A = X; }
|
||||
orconf(A) ::= . { A = OE_Default; }
|
||||
orconf(A) ::= OR resolvetype(X). { A = X; }
|
||||
resolvetype(A) ::= ROLLBACK. { A = OE_Rollback; }
|
||||
resolvetype(A) ::= ABORT. { A = OE_Abort; }
|
||||
resolvetype(A) ::= FAIL. { A = OE_Fail; }
|
||||
resolvetype(A) ::= IGNORE. { A = OE_Ignore; }
|
||||
resolvetype(A) ::= REPLACE. { A = OE_Replace; }
|
||||
|
||||
////////////////////////// The DROP TABLE /////////////////////////////////////
|
||||
//
|
||||
cmd ::= DROP TABLE nm(X). {sqliteDropTable(pParse,&X,0);}
|
||||
|
||||
///////////////////// The CREATE VIEW statement /////////////////////////////
|
||||
//
|
||||
cmd ::= CREATE(X) temp(T) VIEW nm(Y) AS select(S). {
|
||||
sqliteCreateView(pParse, &X, &Y, S, T);
|
||||
}
|
||||
cmd ::= DROP VIEW nm(X). {
|
||||
sqliteDropTable(pParse, &X, 1);
|
||||
}
|
||||
|
||||
//////////////////////// The SELECT statement /////////////////////////////////
|
||||
//
|
||||
cmd ::= select(X). {
|
||||
sqliteSelect(pParse, X, SRT_Callback, 0, 0, 0, 0);
|
||||
sqliteSelectDelete(X);
|
||||
}
|
||||
|
||||
%type select {Select*}
|
||||
%destructor select {sqliteSelectDelete($$);}
|
||||
%type oneselect {Select*}
|
||||
%destructor oneselect {sqliteSelectDelete($$);}
|
||||
|
||||
select(A) ::= oneselect(X). {A = X;}
|
||||
select(A) ::= select(X) multiselect_op(Y) oneselect(Z). {
|
||||
if( Z ){
|
||||
Z->op = Y;
|
||||
Z->pPrior = X;
|
||||
}
|
||||
A = Z;
|
||||
}
|
||||
%type multiselect_op {int}
|
||||
multiselect_op(A) ::= UNION. {A = TK_UNION;}
|
||||
multiselect_op(A) ::= UNION ALL. {A = TK_ALL;}
|
||||
multiselect_op(A) ::= INTERSECT. {A = TK_INTERSECT;}
|
||||
multiselect_op(A) ::= EXCEPT. {A = TK_EXCEPT;}
|
||||
oneselect(A) ::= SELECT distinct(D) selcollist(W) from(X) where_opt(Y)
|
||||
groupby_opt(P) having_opt(Q) orderby_opt(Z) limit_opt(L). {
|
||||
A = sqliteSelectNew(W,X,Y,P,Q,Z,D,L.limit,L.offset);
|
||||
}
|
||||
|
||||
// The "distinct" nonterminal is true (1) if the DISTINCT keyword is
|
||||
// present and false (0) if it is not.
|
||||
//
|
||||
%type distinct {int}
|
||||
distinct(A) ::= DISTINCT. {A = 1;}
|
||||
distinct(A) ::= ALL. {A = 0;}
|
||||
distinct(A) ::= . {A = 0;}
|
||||
|
||||
// selcollist is a list of expressions that are to become the return
|
||||
// values of the SELECT statement. The "*" in statements like
|
||||
// "SELECT * FROM ..." is encoded as a special expression with an
|
||||
// opcode of TK_ALL.
|
||||
//
|
||||
%type selcollist {ExprList*}
|
||||
%destructor selcollist {sqliteExprListDelete($$);}
|
||||
%type sclp {ExprList*}
|
||||
%destructor sclp {sqliteExprListDelete($$);}
|
||||
sclp(A) ::= selcollist(X) COMMA. {A = X;}
|
||||
sclp(A) ::= . {A = 0;}
|
||||
selcollist(A) ::= sclp(P) expr(X) as(Y). {
|
||||
A = sqliteExprListAppend(P,X,Y.n?&Y:0);
|
||||
}
|
||||
selcollist(A) ::= sclp(P) STAR. {
|
||||
A = sqliteExprListAppend(P, sqliteExpr(TK_ALL, 0, 0, 0), 0);
|
||||
}
|
||||
selcollist(A) ::= sclp(P) nm(X) DOT STAR. {
|
||||
Expr *pRight = sqliteExpr(TK_ALL, 0, 0, 0);
|
||||
Expr *pLeft = sqliteExpr(TK_ID, 0, 0, &X);
|
||||
A = sqliteExprListAppend(P, sqliteExpr(TK_DOT, pLeft, pRight, 0), 0);
|
||||
}
|
||||
|
||||
// An option "AS <id>" phrase that can follow one of the expressions that
|
||||
// define the result set, or one of the tables in the FROM clause.
|
||||
//
|
||||
%type as {Token}
|
||||
as(X) ::= AS nm(Y). { X = Y; }
|
||||
as(X) ::= ids(Y). { X = Y; }
|
||||
as(X) ::= . { X.n = 0; }
|
||||
|
||||
|
||||
%type seltablist {SrcList*}
|
||||
%destructor seltablist {sqliteSrcListDelete($$);}
|
||||
%type stl_prefix {SrcList*}
|
||||
%destructor stl_prefix {sqliteSrcListDelete($$);}
|
||||
%type from {SrcList*}
|
||||
%destructor from {sqliteSrcListDelete($$);}
|
||||
|
||||
// A complete FROM clause.
|
||||
//
|
||||
from(A) ::= . {A = sqliteMalloc(sizeof(*A));}
|
||||
from(A) ::= FROM seltablist(X). {A = X;}
|
||||
|
||||
// "seltablist" is a "Select Table List" - the content of the FROM clause
|
||||
// in a SELECT statement. "stl_prefix" is a prefix of this list.
|
||||
//
|
||||
stl_prefix(A) ::= seltablist(X) joinop(Y). {
|
||||
A = X;
|
||||
if( A && A->nSrc>0 ) A->a[A->nSrc-1].jointype = Y;
|
||||
}
|
||||
stl_prefix(A) ::= . {A = 0;}
|
||||
seltablist(A) ::= stl_prefix(X) nm(Y) as(Z) on_opt(N) using_opt(U). {
|
||||
A = sqliteSrcListAppend(X,&Y);
|
||||
if( Z.n ) sqliteSrcListAddAlias(A,&Z);
|
||||
if( N ){
|
||||
if( A && A->nSrc>1 ){ A->a[A->nSrc-2].pOn = N; }
|
||||
else { sqliteExprDelete(N); }
|
||||
}
|
||||
if( U ){
|
||||
if( A && A->nSrc>1 ){ A->a[A->nSrc-2].pUsing = U; }
|
||||
else { sqliteIdListDelete(U); }
|
||||
}
|
||||
}
|
||||
seltablist(A) ::= stl_prefix(X) LP select(S) RP as(Z) on_opt(N) using_opt(U). {
|
||||
A = sqliteSrcListAppend(X,0);
|
||||
A->a[A->nSrc-1].pSelect = S;
|
||||
if( Z.n ) sqliteSrcListAddAlias(A,&Z);
|
||||
if( N ){
|
||||
if( A && A->nSrc>1 ){ A->a[A->nSrc-2].pOn = N; }
|
||||
else { sqliteExprDelete(N); }
|
||||
}
|
||||
if( U ){
|
||||
if( A && A->nSrc>1 ){ A->a[A->nSrc-2].pUsing = U; }
|
||||
else { sqliteIdListDelete(U); }
|
||||
}
|
||||
}
|
||||
|
||||
%type joinop {int}
|
||||
%type joinop2 {int}
|
||||
joinop(X) ::= COMMA. { X = JT_INNER; }
|
||||
joinop(X) ::= JOIN. { X = JT_INNER; }
|
||||
joinop(X) ::= JOIN_KW(A) JOIN. { X = sqliteJoinType(pParse,&A,0,0); }
|
||||
joinop(X) ::= JOIN_KW(A) nm(B) JOIN. { X = sqliteJoinType(pParse,&A,&B,0); }
|
||||
joinop(X) ::= JOIN_KW(A) nm(B) nm(C) JOIN.
|
||||
{ X = sqliteJoinType(pParse,&A,&B,&C); }
|
||||
|
||||
%type on_opt {Expr*}
|
||||
%destructor on_opt {sqliteExprDelete($$);}
|
||||
on_opt(N) ::= ON expr(E). {N = E;}
|
||||
on_opt(N) ::= . {N = 0;}
|
||||
|
||||
%type using_opt {IdList*}
|
||||
%destructor using_opt {sqliteIdListDelete($$);}
|
||||
using_opt(U) ::= USING LP idxlist(L) RP. {U = L;}
|
||||
using_opt(U) ::= . {U = 0;}
|
||||
|
||||
|
||||
%type orderby_opt {ExprList*}
|
||||
%destructor orderby_opt {sqliteExprListDelete($$);}
|
||||
%type sortlist {ExprList*}
|
||||
%destructor sortlist {sqliteExprListDelete($$);}
|
||||
%type sortitem {Expr*}
|
||||
%destructor sortitem {sqliteExprDelete($$);}
|
||||
|
||||
orderby_opt(A) ::= . {A = 0;}
|
||||
orderby_opt(A) ::= ORDER BY sortlist(X). {A = X;}
|
||||
sortlist(A) ::= sortlist(X) COMMA sortitem(Y) collate(C) sortorder(Z). {
|
||||
A = sqliteExprListAppend(X,Y,0);
|
||||
if( A ) A->a[A->nExpr-1].sortOrder = C+Z;
|
||||
}
|
||||
sortlist(A) ::= sortitem(Y) collate(C) sortorder(Z). {
|
||||
A = sqliteExprListAppend(0,Y,0);
|
||||
if( A ) A->a[0].sortOrder = C+Z;
|
||||
}
|
||||
sortitem(A) ::= expr(X). {A = X;}
|
||||
|
||||
%type sortorder {int}
|
||||
%type collate {int}
|
||||
|
||||
sortorder(A) ::= ASC. {A = SQLITE_SO_ASC;}
|
||||
sortorder(A) ::= DESC. {A = SQLITE_SO_DESC;}
|
||||
sortorder(A) ::= . {A = SQLITE_SO_ASC;}
|
||||
collate(C) ::= . {C = SQLITE_SO_UNK;}
|
||||
collate(C) ::= COLLATE id(X). {C = sqliteCollateType(X.z, X.n);}
|
||||
|
||||
%type groupby_opt {ExprList*}
|
||||
%destructor groupby_opt {sqliteExprListDelete($$);}
|
||||
groupby_opt(A) ::= . {A = 0;}
|
||||
groupby_opt(A) ::= GROUP BY exprlist(X). {A = X;}
|
||||
|
||||
%type having_opt {Expr*}
|
||||
%destructor having_opt {sqliteExprDelete($$);}
|
||||
having_opt(A) ::= . {A = 0;}
|
||||
having_opt(A) ::= HAVING expr(X). {A = X;}
|
||||
|
||||
%type limit_opt {struct LimitVal}
|
||||
limit_opt(A) ::= . {A.limit = -1; A.offset = 0;}
|
||||
limit_opt(A) ::= LIMIT INTEGER(X). {A.limit = atoi(X.z); A.offset = 0;}
|
||||
limit_opt(A) ::= LIMIT INTEGER(X) limit_sep INTEGER(Y).
|
||||
{A.limit = atoi(X.z); A.offset = atoi(Y.z);}
|
||||
limit_sep ::= OFFSET.
|
||||
limit_sep ::= COMMA.
|
||||
|
||||
/////////////////////////// The DELETE statement /////////////////////////////
|
||||
//
|
||||
cmd ::= DELETE FROM nm(X) where_opt(Y).
|
||||
{sqliteDeleteFrom(pParse, &X, Y);}
|
||||
|
||||
%type where_opt {Expr*}
|
||||
%destructor where_opt {sqliteExprDelete($$);}
|
||||
|
||||
where_opt(A) ::= . {A = 0;}
|
||||
where_opt(A) ::= WHERE expr(X). {A = X;}
|
||||
|
||||
%type setlist {ExprList*}
|
||||
%destructor setlist {sqliteExprListDelete($$);}
|
||||
|
||||
////////////////////////// The UPDATE command ////////////////////////////////
|
||||
//
|
||||
cmd ::= UPDATE orconf(R) nm(X) SET setlist(Y) where_opt(Z).
|
||||
{sqliteUpdate(pParse,&X,Y,Z,R);}
|
||||
|
||||
setlist(A) ::= setlist(Z) COMMA nm(X) EQ expr(Y).
|
||||
{A = sqliteExprListAppend(Z,Y,&X);}
|
||||
setlist(A) ::= nm(X) EQ expr(Y). {A = sqliteExprListAppend(0,Y,&X);}
|
||||
|
||||
////////////////////////// The INSERT command /////////////////////////////////
|
||||
//
|
||||
cmd ::= insert_cmd(R) INTO nm(X) inscollist_opt(F) VALUES LP itemlist(Y) RP.
|
||||
{sqliteInsert(pParse, &X, Y, 0, F, R);}
|
||||
cmd ::= insert_cmd(R) INTO nm(X) inscollist_opt(F) select(S).
|
||||
{sqliteInsert(pParse, &X, 0, S, F, R);}
|
||||
|
||||
%type insert_cmd {int}
|
||||
insert_cmd(A) ::= INSERT orconf(R). {A = R;}
|
||||
insert_cmd(A) ::= REPLACE. {A = OE_Replace;}
|
||||
|
||||
|
||||
%type itemlist {ExprList*}
|
||||
%destructor itemlist {sqliteExprListDelete($$);}
|
||||
|
||||
itemlist(A) ::= itemlist(X) COMMA expr(Y). {A = sqliteExprListAppend(X,Y,0);}
|
||||
itemlist(A) ::= expr(X). {A = sqliteExprListAppend(0,X,0);}
|
||||
|
||||
%type inscollist_opt {IdList*}
|
||||
%destructor inscollist_opt {sqliteIdListDelete($$);}
|
||||
%type inscollist {IdList*}
|
||||
%destructor inscollist {sqliteIdListDelete($$);}
|
||||
|
||||
inscollist_opt(A) ::= . {A = 0;}
|
||||
inscollist_opt(A) ::= LP inscollist(X) RP. {A = X;}
|
||||
inscollist(A) ::= inscollist(X) COMMA nm(Y). {A = sqliteIdListAppend(X,&Y);}
|
||||
inscollist(A) ::= nm(Y). {A = sqliteIdListAppend(0,&Y);}
|
||||
|
||||
/////////////////////////// Expression Processing /////////////////////////////
|
||||
//
|
||||
%left OR.
|
||||
%left AND.
|
||||
%right NOT.
|
||||
%left EQ NE ISNULL NOTNULL IS LIKE GLOB BETWEEN IN.
|
||||
%left GT GE LT LE.
|
||||
%left BITAND BITOR LSHIFT RSHIFT.
|
||||
%left PLUS MINUS.
|
||||
%left STAR SLASH REM.
|
||||
%left CONCAT.
|
||||
%right UMINUS UPLUS BITNOT.
|
||||
%right ORACLE_OUTER_JOIN.
|
||||
|
||||
%type expr {Expr*}
|
||||
%destructor expr {sqliteExprDelete($$);}
|
||||
|
||||
expr(A) ::= LP(B) expr(X) RP(E). {A = X; sqliteExprSpan(A,&B,&E); }
|
||||
expr(A) ::= NULL(X). {A = sqliteExpr(TK_NULL, 0, 0, &X);}
|
||||
expr(A) ::= ID(X). {A = sqliteExpr(TK_ID, 0, 0, &X);}
|
||||
expr(A) ::= JOIN_KW(X). {A = sqliteExpr(TK_ID, 0, 0, &X);}
|
||||
expr(A) ::= nm(X) DOT nm(Y). {
|
||||
Expr *temp1 = sqliteExpr(TK_ID, 0, 0, &X);
|
||||
Expr *temp2 = sqliteExpr(TK_ID, 0, 0, &Y);
|
||||
A = sqliteExpr(TK_DOT, temp1, temp2, 0);
|
||||
}
|
||||
expr(A) ::= expr(B) ORACLE_OUTER_JOIN.
|
||||
{A = B; ExprSetProperty(A,EP_Oracle8Join);}
|
||||
expr(A) ::= INTEGER(X). {A = sqliteExpr(TK_INTEGER, 0, 0, &X);}
|
||||
expr(A) ::= FLOAT(X). {A = sqliteExpr(TK_FLOAT, 0, 0, &X);}
|
||||
expr(A) ::= STRING(X). {A = sqliteExpr(TK_STRING, 0, 0, &X);}
|
||||
expr(A) ::= ID(X) LP exprlist(Y) RP(E). {
|
||||
A = sqliteExprFunction(Y, &X);
|
||||
sqliteExprSpan(A,&X,&E);
|
||||
}
|
||||
expr(A) ::= ID(X) LP STAR RP(E). {
|
||||
A = sqliteExprFunction(0, &X);
|
||||
sqliteExprSpan(A,&X,&E);
|
||||
}
|
||||
expr(A) ::= expr(X) AND expr(Y). {A = sqliteExpr(TK_AND, X, Y, 0);}
|
||||
expr(A) ::= expr(X) OR expr(Y). {A = sqliteExpr(TK_OR, X, Y, 0);}
|
||||
expr(A) ::= expr(X) LT expr(Y). {A = sqliteExpr(TK_LT, X, Y, 0);}
|
||||
expr(A) ::= expr(X) GT expr(Y). {A = sqliteExpr(TK_GT, X, Y, 0);}
|
||||
expr(A) ::= expr(X) LE expr(Y). {A = sqliteExpr(TK_LE, X, Y, 0);}
|
||||
expr(A) ::= expr(X) GE expr(Y). {A = sqliteExpr(TK_GE, X, Y, 0);}
|
||||
expr(A) ::= expr(X) NE expr(Y). {A = sqliteExpr(TK_NE, X, Y, 0);}
|
||||
expr(A) ::= expr(X) EQ expr(Y). {A = sqliteExpr(TK_EQ, X, Y, 0);}
|
||||
expr(A) ::= expr(X) BITAND expr(Y). {A = sqliteExpr(TK_BITAND, X, Y, 0);}
|
||||
expr(A) ::= expr(X) BITOR expr(Y). {A = sqliteExpr(TK_BITOR, X, Y, 0);}
|
||||
expr(A) ::= expr(X) LSHIFT expr(Y). {A = sqliteExpr(TK_LSHIFT, X, Y, 0);}
|
||||
expr(A) ::= expr(X) RSHIFT expr(Y). {A = sqliteExpr(TK_RSHIFT, X, Y, 0);}
|
||||
expr(A) ::= expr(X) likeop(OP) expr(Y). [LIKE] {
|
||||
ExprList *pList = sqliteExprListAppend(0, Y, 0);
|
||||
pList = sqliteExprListAppend(pList, X, 0);
|
||||
A = sqliteExprFunction(pList, 0);
|
||||
if( A ) A->op = OP;
|
||||
sqliteExprSpan(A, &X->span, &Y->span);
|
||||
}
|
||||
expr(A) ::= expr(X) NOT likeop(OP) expr(Y). [LIKE] {
|
||||
ExprList *pList = sqliteExprListAppend(0, Y, 0);
|
||||
pList = sqliteExprListAppend(pList, X, 0);
|
||||
A = sqliteExprFunction(pList, 0);
|
||||
if( A ) A->op = OP;
|
||||
A = sqliteExpr(TK_NOT, A, 0, 0);
|
||||
sqliteExprSpan(A,&X->span,&Y->span);
|
||||
}
|
||||
%type likeop {int}
|
||||
likeop(A) ::= LIKE. {A = TK_LIKE;}
|
||||
likeop(A) ::= GLOB. {A = TK_GLOB;}
|
||||
expr(A) ::= expr(X) PLUS expr(Y). {A = sqliteExpr(TK_PLUS, X, Y, 0);}
|
||||
expr(A) ::= expr(X) MINUS expr(Y). {A = sqliteExpr(TK_MINUS, X, Y, 0);}
|
||||
expr(A) ::= expr(X) STAR expr(Y). {A = sqliteExpr(TK_STAR, X, Y, 0);}
|
||||
expr(A) ::= expr(X) SLASH expr(Y). {A = sqliteExpr(TK_SLASH, X, Y, 0);}
|
||||
expr(A) ::= expr(X) REM expr(Y). {A = sqliteExpr(TK_REM, X, Y, 0);}
|
||||
expr(A) ::= expr(X) CONCAT expr(Y). {A = sqliteExpr(TK_CONCAT, X, Y, 0);}
|
||||
expr(A) ::= expr(X) ISNULL(E). {
|
||||
A = sqliteExpr(TK_ISNULL, X, 0, 0);
|
||||
sqliteExprSpan(A,&X->span,&E);
|
||||
}
|
||||
expr(A) ::= expr(X) IS NULL(E). {
|
||||
A = sqliteExpr(TK_ISNULL, X, 0, 0);
|
||||
sqliteExprSpan(A,&X->span,&E);
|
||||
}
|
||||
expr(A) ::= expr(X) NOTNULL(E). {
|
||||
A = sqliteExpr(TK_NOTNULL, X, 0, 0);
|
||||
sqliteExprSpan(A,&X->span,&E);
|
||||
}
|
||||
expr(A) ::= expr(X) NOT NULL(E). {
|
||||
A = sqliteExpr(TK_NOTNULL, X, 0, 0);
|
||||
sqliteExprSpan(A,&X->span,&E);
|
||||
}
|
||||
expr(A) ::= expr(X) IS NOT NULL(E). {
|
||||
A = sqliteExpr(TK_NOTNULL, X, 0, 0);
|
||||
sqliteExprSpan(A,&X->span,&E);
|
||||
}
|
||||
expr(A) ::= NOT(B) expr(X). {
|
||||
A = sqliteExpr(TK_NOT, X, 0, 0);
|
||||
sqliteExprSpan(A,&B,&X->span);
|
||||
}
|
||||
expr(A) ::= BITNOT(B) expr(X). {
|
||||
A = sqliteExpr(TK_BITNOT, X, 0, 0);
|
||||
sqliteExprSpan(A,&B,&X->span);
|
||||
}
|
||||
expr(A) ::= MINUS(B) expr(X). [UMINUS] {
|
||||
A = sqliteExpr(TK_UMINUS, X, 0, 0);
|
||||
sqliteExprSpan(A,&B,&X->span);
|
||||
}
|
||||
expr(A) ::= PLUS(B) expr(X). [UPLUS] {
|
||||
A = sqliteExpr(TK_UPLUS, X, 0, 0);
|
||||
sqliteExprSpan(A,&B,&X->span);
|
||||
}
|
||||
expr(A) ::= LP(B) select(X) RP(E). {
|
||||
A = sqliteExpr(TK_SELECT, 0, 0, 0);
|
||||
if( A ) A->pSelect = X;
|
||||
sqliteExprSpan(A,&B,&E);
|
||||
}
|
||||
expr(A) ::= expr(W) BETWEEN expr(X) AND expr(Y). {
|
||||
ExprList *pList = sqliteExprListAppend(0, X, 0);
|
||||
pList = sqliteExprListAppend(pList, Y, 0);
|
||||
A = sqliteExpr(TK_BETWEEN, W, 0, 0);
|
||||
if( A ) A->pList = pList;
|
||||
sqliteExprSpan(A,&W->span,&Y->span);
|
||||
}
|
||||
expr(A) ::= expr(W) NOT BETWEEN expr(X) AND expr(Y). {
|
||||
ExprList *pList = sqliteExprListAppend(0, X, 0);
|
||||
pList = sqliteExprListAppend(pList, Y, 0);
|
||||
A = sqliteExpr(TK_BETWEEN, W, 0, 0);
|
||||
if( A ) A->pList = pList;
|
||||
A = sqliteExpr(TK_NOT, A, 0, 0);
|
||||
sqliteExprSpan(A,&W->span,&Y->span);
|
||||
}
|
||||
expr(A) ::= expr(X) IN LP exprlist(Y) RP(E). {
|
||||
A = sqliteExpr(TK_IN, X, 0, 0);
|
||||
if( A ) A->pList = Y;
|
||||
sqliteExprSpan(A,&X->span,&E);
|
||||
}
|
||||
expr(A) ::= expr(X) IN LP select(Y) RP(E). {
|
||||
A = sqliteExpr(TK_IN, X, 0, 0);
|
||||
if( A ) A->pSelect = Y;
|
||||
sqliteExprSpan(A,&X->span,&E);
|
||||
}
|
||||
expr(A) ::= expr(X) NOT IN LP exprlist(Y) RP(E). {
|
||||
A = sqliteExpr(TK_IN, X, 0, 0);
|
||||
if( A ) A->pList = Y;
|
||||
A = sqliteExpr(TK_NOT, A, 0, 0);
|
||||
sqliteExprSpan(A,&X->span,&E);
|
||||
}
|
||||
expr(A) ::= expr(X) NOT IN LP select(Y) RP(E). {
|
||||
A = sqliteExpr(TK_IN, X, 0, 0);
|
||||
if( A ) A->pSelect = Y;
|
||||
A = sqliteExpr(TK_NOT, A, 0, 0);
|
||||
sqliteExprSpan(A,&X->span,&E);
|
||||
}
|
||||
|
||||
/* CASE expressions */
|
||||
expr(A) ::= CASE(C) case_operand(X) case_exprlist(Y) case_else(Z) END(E). {
|
||||
A = sqliteExpr(TK_CASE, X, Z, 0);
|
||||
if( A ) A->pList = Y;
|
||||
sqliteExprSpan(A, &C, &E);
|
||||
}
|
||||
%type case_exprlist {ExprList*}
|
||||
%destructor case_exprlist {sqliteExprListDelete($$);}
|
||||
case_exprlist(A) ::= case_exprlist(X) WHEN expr(Y) THEN expr(Z). {
|
||||
A = sqliteExprListAppend(X, Y, 0);
|
||||
A = sqliteExprListAppend(A, Z, 0);
|
||||
}
|
||||
case_exprlist(A) ::= WHEN expr(Y) THEN expr(Z). {
|
||||
A = sqliteExprListAppend(0, Y, 0);
|
||||
A = sqliteExprListAppend(A, Z, 0);
|
||||
}
|
||||
%type case_else {Expr*}
|
||||
case_else(A) ::= ELSE expr(X). {A = X;}
|
||||
case_else(A) ::= . {A = 0;}
|
||||
%type case_operand {Expr*}
|
||||
case_operand(A) ::= expr(X). {A = X;}
|
||||
case_operand(A) ::= . {A = 0;}
|
||||
|
||||
%type exprlist {ExprList*}
|
||||
%destructor exprlist {sqliteExprListDelete($$);}
|
||||
%type expritem {Expr*}
|
||||
%destructor expritem {sqliteExprDelete($$);}
|
||||
|
||||
exprlist(A) ::= exprlist(X) COMMA expritem(Y).
|
||||
{A = sqliteExprListAppend(X,Y,0);}
|
||||
exprlist(A) ::= expritem(X). {A = sqliteExprListAppend(0,X,0);}
|
||||
expritem(A) ::= expr(X). {A = X;}
|
||||
expritem(A) ::= . {A = 0;}
|
||||
|
||||
///////////////////////////// The CREATE INDEX command ///////////////////////
|
||||
//
|
||||
cmd ::= CREATE(S) uniqueflag(U) INDEX nm(X)
|
||||
ON nm(Y) LP idxlist(Z) RP(E) onconf(R). {
|
||||
if( U!=OE_None ) U = R;
|
||||
if( U==OE_Default) U = OE_Abort;
|
||||
sqliteCreateIndex(pParse, &X, &Y, Z, U, &S, &E);
|
||||
}
|
||||
|
||||
%type uniqueflag {int}
|
||||
uniqueflag(A) ::= UNIQUE. { A = OE_Abort; }
|
||||
uniqueflag(A) ::= . { A = OE_None; }
|
||||
|
||||
%type idxlist {IdList*}
|
||||
%destructor idxlist {sqliteIdListDelete($$);}
|
||||
%type idxlist_opt {IdList*}
|
||||
%destructor idxlist_opt {sqliteIdListDelete($$);}
|
||||
%type idxitem {Token}
|
||||
|
||||
idxlist_opt(A) ::= . {A = 0;}
|
||||
idxlist_opt(A) ::= LP idxlist(X) RP. {A = X;}
|
||||
idxlist(A) ::= idxlist(X) COMMA idxitem(Y). {A = sqliteIdListAppend(X,&Y);}
|
||||
idxlist(A) ::= idxitem(Y). {A = sqliteIdListAppend(0,&Y);}
|
||||
idxitem(A) ::= nm(X). {A = X;}
|
||||
|
||||
///////////////////////////// The DROP INDEX command /////////////////////////
|
||||
//
|
||||
|
||||
cmd ::= DROP INDEX nm(X). {sqliteDropIndex(pParse, &X);}
|
||||
|
||||
|
||||
///////////////////////////// The COPY command ///////////////////////////////
|
||||
//
|
||||
cmd ::= COPY orconf(R) nm(X) FROM nm(Y) USING DELIMITERS STRING(Z).
|
||||
{sqliteCopy(pParse,&X,&Y,&Z,R);}
|
||||
cmd ::= COPY orconf(R) nm(X) FROM nm(Y).
|
||||
{sqliteCopy(pParse,&X,&Y,0,R);}
|
||||
|
||||
///////////////////////////// The VACUUM command /////////////////////////////
|
||||
//
|
||||
cmd ::= VACUUM. {sqliteVacuum(pParse,0);}
|
||||
cmd ::= VACUUM nm(X). {sqliteVacuum(pParse,&X);}
|
||||
|
||||
///////////////////////////// The PRAGMA command /////////////////////////////
|
||||
//
|
||||
cmd ::= PRAGMA ids(X) EQ nm(Y). {sqlitePragma(pParse,&X,&Y,0);}
|
||||
cmd ::= PRAGMA ids(X) EQ ON(Y). {sqlitePragma(pParse,&X,&Y,0);}
|
||||
cmd ::= PRAGMA ids(X) EQ plus_num(Y). {sqlitePragma(pParse,&X,&Y,0);}
|
||||
cmd ::= PRAGMA ids(X) EQ minus_num(Y). {sqlitePragma(pParse,&X,&Y,1);}
|
||||
cmd ::= PRAGMA ids(X) LP nm(Y) RP. {sqlitePragma(pParse,&X,&Y,0);}
|
||||
cmd ::= PRAGMA ids(X). {sqlitePragma(pParse,&X,&X,0);}
|
||||
plus_num(A) ::= plus_opt number(X). {A = X;}
|
||||
minus_num(A) ::= MINUS number(X). {A = X;}
|
||||
number(A) ::= INTEGER(X). {A = X;}
|
||||
number(A) ::= FLOAT(X). {A = X;}
|
||||
plus_opt ::= PLUS.
|
||||
plus_opt ::= .
|
||||
|
||||
//////////////////////////// The CREATE TRIGGER command /////////////////////
|
||||
cmd ::= CREATE(A) TRIGGER nm(B) trigger_time(C) trigger_event(D) ON nm(E)
|
||||
foreach_clause(F) when_clause(G)
|
||||
BEGIN trigger_cmd_list(S) END(Z). {
|
||||
Token all;
|
||||
all.z = A.z;
|
||||
all.n = (Z.z - A.z) + Z.n;
|
||||
sqliteCreateTrigger(pParse, &B, C, D.a, D.b, &E, F, G, S, &all);
|
||||
}
|
||||
|
||||
%type trigger_time {int}
|
||||
trigger_time(A) ::= BEFORE. { A = TK_BEFORE; }
|
||||
trigger_time(A) ::= AFTER. { A = TK_AFTER; }
|
||||
trigger_time(A) ::= INSTEAD OF. { A = TK_INSTEAD;}
|
||||
trigger_time(A) ::= . { A = TK_BEFORE; }
|
||||
|
||||
%type trigger_event {struct TrigEvent}
|
||||
%destructor trigger_event {sqliteIdListDelete($$.b);}
|
||||
trigger_event(A) ::= DELETE. { A.a = TK_DELETE; A.b = 0; }
|
||||
trigger_event(A) ::= INSERT. { A.a = TK_INSERT; A.b = 0; }
|
||||
trigger_event(A) ::= UPDATE. { A.a = TK_UPDATE; A.b = 0;}
|
||||
trigger_event(A) ::= UPDATE OF inscollist(X). {A.a = TK_UPDATE; A.b = X; }
|
||||
|
||||
%type foreach_clause {int}
|
||||
foreach_clause(A) ::= . { A = TK_ROW; }
|
||||
foreach_clause(A) ::= FOR EACH ROW. { A = TK_ROW; }
|
||||
foreach_clause(A) ::= FOR EACH STATEMENT. { A = TK_STATEMENT; }
|
||||
|
||||
%type when_clause {Expr *}
|
||||
when_clause(A) ::= . { A = 0; }
|
||||
when_clause(A) ::= WHEN expr(X). { A = X; }
|
||||
|
||||
%type trigger_cmd_list {TriggerStep *}
|
||||
trigger_cmd_list(A) ::= trigger_cmd(X) SEMI trigger_cmd_list(Y). {
|
||||
X->pNext = Y ; A = X; }
|
||||
trigger_cmd_list(A) ::= . { A = 0; }
|
||||
|
||||
%type trigger_cmd {TriggerStep *}
|
||||
// UPDATE
|
||||
trigger_cmd(A) ::= UPDATE orconf(R) nm(X) SET setlist(Y) where_opt(Z).
|
||||
{ A = sqliteTriggerUpdateStep(&X, Y, Z, R); }
|
||||
|
||||
// INSERT
|
||||
trigger_cmd(A) ::= INSERT orconf(R) INTO nm(X) inscollist_opt(F)
|
||||
VALUES LP itemlist(Y) RP.
|
||||
{A = sqliteTriggerInsertStep(&X, F, Y, 0, R);}
|
||||
|
||||
trigger_cmd(A) ::= INSERT orconf(R) INTO nm(X) inscollist_opt(F) select(S).
|
||||
{A = sqliteTriggerInsertStep(&X, F, 0, S, R);}
|
||||
|
||||
// DELETE
|
||||
trigger_cmd(A) ::= DELETE FROM nm(X) where_opt(Y).
|
||||
{A = sqliteTriggerDeleteStep(&X, Y);}
|
||||
|
||||
// SELECT
|
||||
trigger_cmd(A) ::= select(X). {A = sqliteTriggerSelectStep(X); }
|
||||
|
||||
// The special RAISE expression that may occur in trigger programs
|
||||
expr(A) ::= RAISE(X) LP IGNORE RP(Y). {
|
||||
A = sqliteExpr(TK_RAISE, 0, 0, 0);
|
||||
A->iColumn = OE_Ignore;
|
||||
sqliteExprSpan(A, &X, &Y);
|
||||
}
|
||||
expr(A) ::= RAISE(X) LP ROLLBACK COMMA nm(Z) RP(Y). {
|
||||
A = sqliteExpr(TK_RAISE, 0, 0, &Z);
|
||||
A->iColumn = OE_Rollback;
|
||||
sqliteExprSpan(A, &X, &Y);
|
||||
}
|
||||
expr(A) ::= RAISE(X) LP ABORT COMMA nm(Z) RP(Y). {
|
||||
A = sqliteExpr(TK_RAISE, 0, 0, &Z);
|
||||
A->iColumn = OE_Abort;
|
||||
sqliteExprSpan(A, &X, &Y);
|
||||
}
|
||||
expr(A) ::= RAISE(X) LP FAIL COMMA nm(Z) RP(Y). {
|
||||
A = sqliteExpr(TK_RAISE, 0, 0, &Z);
|
||||
A->iColumn = OE_Fail;
|
||||
sqliteExprSpan(A, &X, &Y);
|
||||
}
|
||||
|
||||
//////////////////////// DROP TRIGGER statement //////////////////////////////
|
||||
cmd ::= DROP TRIGGER nm(X). {
|
||||
sqliteDropTrigger(pParse,&X,0);
|
||||
}
|
||||
@@ -1,824 +0,0 @@
|
||||
/*
|
||||
** The "printf" code that follows dates from the 1980's. It is in
|
||||
** the public domain. The original comments are included here for
|
||||
** completeness. They are slightly out-of-date.
|
||||
**
|
||||
** The following modules is an enhanced replacement for the "printf" subroutines
|
||||
** found in the standard C library. The following enhancements are
|
||||
** supported:
|
||||
**
|
||||
** + Additional functions. The standard set of "printf" functions
|
||||
** includes printf, fprintf, sprintf, vprintf, vfprintf, and
|
||||
** vsprintf. This module adds the following:
|
||||
**
|
||||
** * snprintf -- Works like sprintf, but has an extra argument
|
||||
** which is the size of the buffer written to.
|
||||
**
|
||||
** * mprintf -- Similar to sprintf. Writes output to memory
|
||||
** obtained from malloc.
|
||||
**
|
||||
** * xprintf -- Calls a function to dispose of output.
|
||||
**
|
||||
** * nprintf -- No output, but returns the number of characters
|
||||
** that would have been output by printf.
|
||||
**
|
||||
** * A v- version (ex: vsnprintf) of every function is also
|
||||
** supplied.
|
||||
**
|
||||
** + A few extensions to the formatting notation are supported:
|
||||
**
|
||||
** * The "=" flag (similar to "-") causes the output to be
|
||||
** be centered in the appropriately sized field.
|
||||
**
|
||||
** * The %b field outputs an integer in binary notation.
|
||||
**
|
||||
** * The %c field now accepts a precision. The character output
|
||||
** is repeated by the number of times the precision specifies.
|
||||
**
|
||||
** * The %' field works like %c, but takes as its character the
|
||||
** next character of the format string, instead of the next
|
||||
** argument. For example, printf("%.78'-") prints 78 minus
|
||||
** signs, the same as printf("%.78c",'-').
|
||||
**
|
||||
** + When compiled using GCC on a SPARC, this version of printf is
|
||||
** faster than the library printf for SUN OS 4.1.
|
||||
**
|
||||
** + All functions are fully reentrant.
|
||||
**
|
||||
*/
|
||||
#include "sqliteInt.h"
|
||||
|
||||
/*
|
||||
** Undefine COMPATIBILITY to make some slight changes in the way things
|
||||
** work. I think the changes are an improvement, but they are not
|
||||
** backwards compatible.
|
||||
*/
|
||||
/* #define COMPATIBILITY / * Compatible with SUN OS 4.1 */
|
||||
|
||||
/*
|
||||
** Conversion types fall into various categories as defined by the
|
||||
** following enumeration.
|
||||
*/
|
||||
enum et_type { /* The type of the format field */
|
||||
etRADIX, /* Integer types. %d, %x, %o, and so forth */
|
||||
etFLOAT, /* Floating point. %f */
|
||||
etEXP, /* Exponentional notation. %e and %E */
|
||||
etGENERIC, /* Floating or exponential, depending on exponent. %g */
|
||||
etSIZE, /* Return number of characters processed so far. %n */
|
||||
etSTRING, /* Strings. %s */
|
||||
etPERCENT, /* Percent symbol. %% */
|
||||
etCHARX, /* Characters. %c */
|
||||
etERROR, /* Used to indicate no such conversion type */
|
||||
/* The rest are extensions, not normally found in printf() */
|
||||
etCHARLIT, /* Literal characters. %' */
|
||||
etSQLESCAPE, /* Strings with '\'' doubled. %q */
|
||||
etSQLESCAPE2, /* Strings with '\'' doubled and enclosed in '',
|
||||
NULL pointers replaced by SQL NULL. %Q */
|
||||
etORDINAL /* 1st, 2nd, 3rd and so forth */
|
||||
};
|
||||
|
||||
/*
|
||||
** Each builtin conversion character (ex: the 'd' in "%d") is described
|
||||
** by an instance of the following structure
|
||||
*/
|
||||
typedef struct et_info { /* Information about each format field */
|
||||
int fmttype; /* The format field code letter */
|
||||
int base; /* The base for radix conversion */
|
||||
char *charset; /* The character set for conversion */
|
||||
int flag_signed; /* Is the quantity signed? */
|
||||
char *prefix; /* Prefix on non-zero values in alt format */
|
||||
enum et_type type; /* Conversion paradigm */
|
||||
} et_info;
|
||||
|
||||
/*
|
||||
** The following table is searched linearly, so it is good to put the
|
||||
** most frequently used conversion types first.
|
||||
*/
|
||||
static et_info fmtinfo[] = {
|
||||
{ 'd', 10, "0123456789", 1, 0, etRADIX, },
|
||||
{ 's', 0, 0, 0, 0, etSTRING, },
|
||||
{ 'q', 0, 0, 0, 0, etSQLESCAPE, },
|
||||
{ 'Q', 0, 0, 0, 0, etSQLESCAPE2, },
|
||||
{ 'c', 0, 0, 0, 0, etCHARX, },
|
||||
{ 'o', 8, "01234567", 0, "0", etRADIX, },
|
||||
{ 'u', 10, "0123456789", 0, 0, etRADIX, },
|
||||
{ 'x', 16, "0123456789abcdef", 0, "x0", etRADIX, },
|
||||
{ 'X', 16, "0123456789ABCDEF", 0, "X0", etRADIX, },
|
||||
{ 'r', 10, "0123456789", 0, 0, etORDINAL, },
|
||||
{ 'f', 0, 0, 1, 0, etFLOAT, },
|
||||
{ 'e', 0, "e", 1, 0, etEXP, },
|
||||
{ 'E', 0, "E", 1, 0, etEXP, },
|
||||
{ 'g', 0, "e", 1, 0, etGENERIC, },
|
||||
{ 'G', 0, "E", 1, 0, etGENERIC, },
|
||||
{ 'i', 10, "0123456789", 1, 0, etRADIX, },
|
||||
{ 'n', 0, 0, 0, 0, etSIZE, },
|
||||
{ '%', 0, 0, 0, 0, etPERCENT, },
|
||||
{ 'b', 2, "01", 0, "b0", etRADIX, }, /* Binary */
|
||||
{ 'p', 10, "0123456789", 0, 0, etRADIX, }, /* Pointers */
|
||||
{ '\'', 0, 0, 0, 0, etCHARLIT, }, /* Literal char */
|
||||
};
|
||||
#define etNINFO (sizeof(fmtinfo)/sizeof(fmtinfo[0]))
|
||||
|
||||
/*
|
||||
** If NOFLOATINGPOINT is defined, then none of the floating point
|
||||
** conversions will work.
|
||||
*/
|
||||
#ifndef etNOFLOATINGPOINT
|
||||
/*
|
||||
** "*val" is a double such that 0.1 <= *val < 10.0
|
||||
** Return the ascii code for the leading digit of *val, then
|
||||
** multiply "*val" by 10.0 to renormalize.
|
||||
**
|
||||
** Example:
|
||||
** input: *val = 3.14159
|
||||
** output: *val = 1.4159 function return = '3'
|
||||
**
|
||||
** The counter *cnt is incremented each time. After counter exceeds
|
||||
** 16 (the number of significant digits in a 64-bit float) '0' is
|
||||
** always returned.
|
||||
*/
|
||||
static int et_getdigit(double *val, int *cnt){
|
||||
int digit;
|
||||
double d;
|
||||
if( (*cnt)++ >= 16 ) return '0';
|
||||
digit = (int)*val;
|
||||
d = digit;
|
||||
digit += '0';
|
||||
*val = (*val - d)*10.0;
|
||||
return digit;
|
||||
}
|
||||
#endif
|
||||
|
||||
#define etBUFSIZE 1000 /* Size of the output buffer */
|
||||
|
||||
/*
|
||||
** The root program. All variations call this core.
|
||||
**
|
||||
** INPUTS:
|
||||
** func This is a pointer to a function taking three arguments
|
||||
** 1. A pointer to anything. Same as the "arg" parameter.
|
||||
** 2. A pointer to the list of characters to be output
|
||||
** (Note, this list is NOT null terminated.)
|
||||
** 3. An integer number of characters to be output.
|
||||
** (Note: This number might be zero.)
|
||||
**
|
||||
** arg This is the pointer to anything which will be passed as the
|
||||
** first argument to "func". Use it for whatever you like.
|
||||
**
|
||||
** fmt This is the format string, as in the usual print.
|
||||
**
|
||||
** ap This is a pointer to a list of arguments. Same as in
|
||||
** vfprint.
|
||||
**
|
||||
** OUTPUTS:
|
||||
** The return value is the total number of characters sent to
|
||||
** the function "func". Returns -1 on a error.
|
||||
**
|
||||
** Note that the order in which automatic variables are declared below
|
||||
** seems to make a big difference in determining how fast this beast
|
||||
** will run.
|
||||
*/
|
||||
static int vxprintf(
|
||||
void (*func)(void*,char*,int),
|
||||
void *arg,
|
||||
const char *format,
|
||||
va_list ap
|
||||
){
|
||||
register const char *fmt; /* The format string. */
|
||||
register int c; /* Next character in the format string */
|
||||
register char *bufpt; /* Pointer to the conversion buffer */
|
||||
register int precision; /* Precision of the current field */
|
||||
register int length; /* Length of the field */
|
||||
register int idx; /* A general purpose loop counter */
|
||||
int count; /* Total number of characters output */
|
||||
int width; /* Width of the current field */
|
||||
int flag_leftjustify; /* True if "-" flag is present */
|
||||
int flag_plussign; /* True if "+" flag is present */
|
||||
int flag_blanksign; /* True if " " flag is present */
|
||||
int flag_alternateform; /* True if "#" flag is present */
|
||||
int flag_zeropad; /* True if field width constant starts with zero */
|
||||
int flag_long; /* True if "l" flag is present */
|
||||
int flag_center; /* True if "=" flag is present */
|
||||
unsigned long longvalue; /* Value for integer types */
|
||||
double realvalue; /* Value for real types */
|
||||
et_info *infop; /* Pointer to the appropriate info structure */
|
||||
char buf[etBUFSIZE]; /* Conversion buffer */
|
||||
char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
|
||||
int errorflag = 0; /* True if an error is encountered */
|
||||
enum et_type xtype; /* Conversion paradigm */
|
||||
char *zExtra; /* Extra memory used for etTCLESCAPE conversions */
|
||||
static char spaces[] = " "
|
||||
" ";
|
||||
#define etSPACESIZE (sizeof(spaces)-1)
|
||||
#ifndef etNOFLOATINGPOINT
|
||||
int exp; /* exponent of real numbers */
|
||||
double rounder; /* Used for rounding floating point values */
|
||||
int flag_dp; /* True if decimal point should be shown */
|
||||
int flag_rtz; /* True if trailing zeros should be removed */
|
||||
int flag_exp; /* True to force display of the exponent */
|
||||
int nsd; /* Number of significant digits returned */
|
||||
#endif
|
||||
|
||||
fmt = format; /* Put in a register for speed */
|
||||
count = length = 0;
|
||||
bufpt = 0;
|
||||
for(; (c=(*fmt))!=0; ++fmt){
|
||||
if( c!='%' ){
|
||||
register int amt;
|
||||
bufpt = (char *)fmt;
|
||||
amt = 1;
|
||||
while( (c=(*++fmt))!='%' && c!=0 ) amt++;
|
||||
(*func)(arg,bufpt,amt);
|
||||
count += amt;
|
||||
if( c==0 ) break;
|
||||
}
|
||||
if( (c=(*++fmt))==0 ){
|
||||
errorflag = 1;
|
||||
(*func)(arg,"%",1);
|
||||
count++;
|
||||
break;
|
||||
}
|
||||
/* Find out what flags are present */
|
||||
flag_leftjustify = flag_plussign = flag_blanksign =
|
||||
flag_alternateform = flag_zeropad = flag_center = 0;
|
||||
do{
|
||||
switch( c ){
|
||||
case '-': flag_leftjustify = 1; c = 0; break;
|
||||
case '+': flag_plussign = 1; c = 0; break;
|
||||
case ' ': flag_blanksign = 1; c = 0; break;
|
||||
case '#': flag_alternateform = 1; c = 0; break;
|
||||
case '0': flag_zeropad = 1; c = 0; break;
|
||||
case '=': flag_center = 1; c = 0; break;
|
||||
default: break;
|
||||
}
|
||||
}while( c==0 && (c=(*++fmt))!=0 );
|
||||
if( flag_center ) flag_leftjustify = 0;
|
||||
/* Get the field width */
|
||||
width = 0;
|
||||
if( c=='*' ){
|
||||
width = va_arg(ap,int);
|
||||
if( width<0 ){
|
||||
flag_leftjustify = 1;
|
||||
width = -width;
|
||||
}
|
||||
c = *++fmt;
|
||||
}else{
|
||||
while( c>='0' && c<='9' ){
|
||||
width = width*10 + c - '0';
|
||||
c = *++fmt;
|
||||
}
|
||||
}
|
||||
if( width > etBUFSIZE-10 ){
|
||||
width = etBUFSIZE-10;
|
||||
}
|
||||
/* Get the precision */
|
||||
if( c=='.' ){
|
||||
precision = 0;
|
||||
c = *++fmt;
|
||||
if( c=='*' ){
|
||||
precision = va_arg(ap,int);
|
||||
#ifndef etCOMPATIBILITY
|
||||
/* This is sensible, but SUN OS 4.1 doesn't do it. */
|
||||
if( precision<0 ) precision = -precision;
|
||||
#endif
|
||||
c = *++fmt;
|
||||
}else{
|
||||
while( c>='0' && c<='9' ){
|
||||
precision = precision*10 + c - '0';
|
||||
c = *++fmt;
|
||||
}
|
||||
}
|
||||
/* Limit the precision to prevent overflowing buf[] during conversion */
|
||||
if( precision>etBUFSIZE-40 ) precision = etBUFSIZE-40;
|
||||
}else{
|
||||
precision = -1;
|
||||
}
|
||||
/* Get the conversion type modifier */
|
||||
if( c=='l' ){
|
||||
flag_long = 1;
|
||||
c = *++fmt;
|
||||
}else{
|
||||
flag_long = 0;
|
||||
}
|
||||
/* Fetch the info entry for the field */
|
||||
infop = 0;
|
||||
for(idx=0; idx<etNINFO; idx++){
|
||||
if( c==fmtinfo[idx].fmttype ){
|
||||
infop = &fmtinfo[idx];
|
||||
break;
|
||||
}
|
||||
}
|
||||
/* No info entry found. It must be an error. */
|
||||
if( infop==0 ){
|
||||
xtype = etERROR;
|
||||
}else{
|
||||
xtype = infop->type;
|
||||
}
|
||||
zExtra = 0;
|
||||
|
||||
/*
|
||||
** At this point, variables are initialized as follows:
|
||||
**
|
||||
** flag_alternateform TRUE if a '#' is present.
|
||||
** flag_plussign TRUE if a '+' is present.
|
||||
** flag_leftjustify TRUE if a '-' is present or if the
|
||||
** field width was negative.
|
||||
** flag_zeropad TRUE if the width began with 0.
|
||||
** flag_long TRUE if the letter 'l' (ell) prefixed
|
||||
** the conversion character.
|
||||
** flag_blanksign TRUE if a ' ' is present.
|
||||
** width The specified field width. This is
|
||||
** always non-negative. Zero is the default.
|
||||
** precision The specified precision. The default
|
||||
** is -1.
|
||||
** xtype The class of the conversion.
|
||||
** infop Pointer to the appropriate info struct.
|
||||
*/
|
||||
switch( xtype ){
|
||||
case etORDINAL:
|
||||
case etRADIX:
|
||||
if( flag_long ) longvalue = va_arg(ap,long);
|
||||
else longvalue = va_arg(ap,int);
|
||||
#ifdef etCOMPATIBILITY
|
||||
/* For the format %#x, the value zero is printed "0" not "0x0".
|
||||
** I think this is stupid. */
|
||||
if( longvalue==0 ) flag_alternateform = 0;
|
||||
#else
|
||||
/* More sensible: turn off the prefix for octal (to prevent "00"),
|
||||
** but leave the prefix for hex. */
|
||||
if( longvalue==0 && infop->base==8 ) flag_alternateform = 0;
|
||||
#endif
|
||||
if( infop->flag_signed ){
|
||||
if( *(long*)&longvalue<0 ){
|
||||
longvalue = -*(long*)&longvalue;
|
||||
prefix = '-';
|
||||
}else if( flag_plussign ) prefix = '+';
|
||||
else if( flag_blanksign ) prefix = ' ';
|
||||
else prefix = 0;
|
||||
}else prefix = 0;
|
||||
if( flag_zeropad && precision<width-(prefix!=0) ){
|
||||
precision = width-(prefix!=0);
|
||||
}
|
||||
bufpt = &buf[etBUFSIZE];
|
||||
if( xtype==etORDINAL ){
|
||||
long a,b;
|
||||
a = longvalue%10;
|
||||
b = longvalue%100;
|
||||
bufpt -= 2;
|
||||
if( a==0 || a>3 || (b>10 && b<14) ){
|
||||
bufpt[0] = 't';
|
||||
bufpt[1] = 'h';
|
||||
}else if( a==1 ){
|
||||
bufpt[0] = 's';
|
||||
bufpt[1] = 't';
|
||||
}else if( a==2 ){
|
||||
bufpt[0] = 'n';
|
||||
bufpt[1] = 'd';
|
||||
}else if( a==3 ){
|
||||
bufpt[0] = 'r';
|
||||
bufpt[1] = 'd';
|
||||
}
|
||||
}
|
||||
{
|
||||
register char *cset; /* Use registers for speed */
|
||||
register int base;
|
||||
cset = infop->charset;
|
||||
base = infop->base;
|
||||
do{ /* Convert to ascii */
|
||||
*(--bufpt) = cset[longvalue%base];
|
||||
longvalue = longvalue/base;
|
||||
}while( longvalue>0 );
|
||||
}
|
||||
length = (long)&buf[etBUFSIZE]-(long)bufpt;
|
||||
for(idx=precision-length; idx>0; idx--){
|
||||
*(--bufpt) = '0'; /* Zero pad */
|
||||
}
|
||||
if( prefix ) *(--bufpt) = prefix; /* Add sign */
|
||||
if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
|
||||
char *pre, x;
|
||||
pre = infop->prefix;
|
||||
if( *bufpt!=pre[0] ){
|
||||
for(pre=infop->prefix; (x=(*pre))!=0; pre++) *(--bufpt) = x;
|
||||
}
|
||||
}
|
||||
length = (long)&buf[etBUFSIZE]-(long)bufpt;
|
||||
break;
|
||||
case etFLOAT:
|
||||
case etEXP:
|
||||
case etGENERIC:
|
||||
realvalue = va_arg(ap,double);
|
||||
#ifndef etNOFLOATINGPOINT
|
||||
if( precision<0 ) precision = 6; /* Set default precision */
|
||||
if( precision>etBUFSIZE-10 ) precision = etBUFSIZE-10;
|
||||
if( realvalue<0.0 ){
|
||||
realvalue = -realvalue;
|
||||
prefix = '-';
|
||||
}else{
|
||||
if( flag_plussign ) prefix = '+';
|
||||
else if( flag_blanksign ) prefix = ' ';
|
||||
else prefix = 0;
|
||||
}
|
||||
if( infop->type==etGENERIC && precision>0 ) precision--;
|
||||
rounder = 0.0;
|
||||
#ifdef COMPATIBILITY
|
||||
/* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
|
||||
for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
|
||||
#else
|
||||
/* It makes more sense to use 0.5 */
|
||||
for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1);
|
||||
#endif
|
||||
if( infop->type==etFLOAT ) realvalue += rounder;
|
||||
/* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
|
||||
exp = 0;
|
||||
if( realvalue>0.0 ){
|
||||
int k = 0;
|
||||
while( realvalue>=1e8 && k++<100 ){ realvalue *= 1e-8; exp+=8; }
|
||||
while( realvalue>=10.0 && k++<100 ){ realvalue *= 0.1; exp++; }
|
||||
while( realvalue<1e-8 && k++<100 ){ realvalue *= 1e8; exp-=8; }
|
||||
while( realvalue<1.0 && k++<100 ){ realvalue *= 10.0; exp--; }
|
||||
if( k>=100 ){
|
||||
bufpt = "NaN";
|
||||
length = 3;
|
||||
break;
|
||||
}
|
||||
}
|
||||
bufpt = buf;
|
||||
/*
|
||||
** If the field type is etGENERIC, then convert to either etEXP
|
||||
** or etFLOAT, as appropriate.
|
||||
*/
|
||||
flag_exp = xtype==etEXP;
|
||||
if( xtype!=etFLOAT ){
|
||||
realvalue += rounder;
|
||||
if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
|
||||
}
|
||||
if( xtype==etGENERIC ){
|
||||
flag_rtz = !flag_alternateform;
|
||||
if( exp<-4 || exp>precision ){
|
||||
xtype = etEXP;
|
||||
}else{
|
||||
precision = precision - exp;
|
||||
xtype = etFLOAT;
|
||||
}
|
||||
}else{
|
||||
flag_rtz = 0;
|
||||
}
|
||||
/*
|
||||
** The "exp+precision" test causes output to be of type etEXP if
|
||||
** the precision is too large to fit in buf[].
|
||||
*/
|
||||
nsd = 0;
|
||||
if( xtype==etFLOAT && exp+precision<etBUFSIZE-30 ){
|
||||
flag_dp = (precision>0 || flag_alternateform);
|
||||
if( prefix ) *(bufpt++) = prefix; /* Sign */
|
||||
if( exp<0 ) *(bufpt++) = '0'; /* Digits before "." */
|
||||
else for(; exp>=0; exp--) *(bufpt++) = et_getdigit(&realvalue,&nsd);
|
||||
if( flag_dp ) *(bufpt++) = '.'; /* The decimal point */
|
||||
for(exp++; exp<0 && precision>0; precision--, exp++){
|
||||
*(bufpt++) = '0';
|
||||
}
|
||||
while( (precision--)>0 ) *(bufpt++) = et_getdigit(&realvalue,&nsd);
|
||||
*(bufpt--) = 0; /* Null terminate */
|
||||
if( flag_rtz && flag_dp ){ /* Remove trailing zeros and "." */
|
||||
while( bufpt>=buf && *bufpt=='0' ) *(bufpt--) = 0;
|
||||
if( bufpt>=buf && *bufpt=='.' ) *(bufpt--) = 0;
|
||||
}
|
||||
bufpt++; /* point to next free slot */
|
||||
}else{ /* etEXP or etGENERIC */
|
||||
flag_dp = (precision>0 || flag_alternateform);
|
||||
if( prefix ) *(bufpt++) = prefix; /* Sign */
|
||||
*(bufpt++) = et_getdigit(&realvalue,&nsd); /* First digit */
|
||||
if( flag_dp ) *(bufpt++) = '.'; /* Decimal point */
|
||||
while( (precision--)>0 ) *(bufpt++) = et_getdigit(&realvalue,&nsd);
|
||||
bufpt--; /* point to last digit */
|
||||
if( flag_rtz && flag_dp ){ /* Remove tail zeros */
|
||||
while( bufpt>=buf && *bufpt=='0' ) *(bufpt--) = 0;
|
||||
if( bufpt>=buf && *bufpt=='.' ) *(bufpt--) = 0;
|
||||
}
|
||||
bufpt++; /* point to next free slot */
|
||||
if( exp || flag_exp ){
|
||||
*(bufpt++) = infop->charset[0];
|
||||
if( exp<0 ){ *(bufpt++) = '-'; exp = -exp; } /* sign of exp */
|
||||
else { *(bufpt++) = '+'; }
|
||||
if( exp>=100 ){
|
||||
*(bufpt++) = (exp/100)+'0'; /* 100's digit */
|
||||
exp %= 100;
|
||||
}
|
||||
*(bufpt++) = exp/10+'0'; /* 10's digit */
|
||||
*(bufpt++) = exp%10+'0'; /* 1's digit */
|
||||
}
|
||||
}
|
||||
/* The converted number is in buf[] and zero terminated. Output it.
|
||||
** Note that the number is in the usual order, not reversed as with
|
||||
** integer conversions. */
|
||||
length = (long)bufpt-(long)buf;
|
||||
bufpt = buf;
|
||||
|
||||
/* Special case: Add leading zeros if the flag_zeropad flag is
|
||||
** set and we are not left justified */
|
||||
if( flag_zeropad && !flag_leftjustify && length < width){
|
||||
int i;
|
||||
int nPad = width - length;
|
||||
for(i=width; i>=nPad; i--){
|
||||
bufpt[i] = bufpt[i-nPad];
|
||||
}
|
||||
i = prefix!=0;
|
||||
while( nPad-- ) bufpt[i++] = '0';
|
||||
length = width;
|
||||
}
|
||||
#endif
|
||||
break;
|
||||
case etSIZE:
|
||||
*(va_arg(ap,int*)) = count;
|
||||
length = width = 0;
|
||||
break;
|
||||
case etPERCENT:
|
||||
buf[0] = '%';
|
||||
bufpt = buf;
|
||||
length = 1;
|
||||
break;
|
||||
case etCHARLIT:
|
||||
case etCHARX:
|
||||
c = buf[0] = (xtype==etCHARX ? va_arg(ap,int) : *++fmt);
|
||||
if( precision>=0 ){
|
||||
for(idx=1; idx<precision; idx++) buf[idx] = c;
|
||||
length = precision;
|
||||
}else{
|
||||
length =1;
|
||||
}
|
||||
bufpt = buf;
|
||||
break;
|
||||
case etSTRING:
|
||||
bufpt = va_arg(ap,char*);
|
||||
if( bufpt==0 ) bufpt = "(null)";
|
||||
length = strlen(bufpt);
|
||||
if( precision>=0 && precision<length ) length = precision;
|
||||
break;
|
||||
case etSQLESCAPE:
|
||||
case etSQLESCAPE2:
|
||||
{
|
||||
int i, j, n, c, isnull;
|
||||
char *arg = va_arg(ap,char*);
|
||||
isnull = arg==0;
|
||||
if( isnull ) arg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
|
||||
for(i=n=0; (c=arg[i])!=0; i++){
|
||||
if( c=='\'' ) n++;
|
||||
}
|
||||
n += i + 1 + ((!isnull && xtype==etSQLESCAPE2) ? 2 : 0);
|
||||
if( n>etBUFSIZE ){
|
||||
bufpt = zExtra = sqliteMalloc( n );
|
||||
if( bufpt==0 ) return -1;
|
||||
}else{
|
||||
bufpt = buf;
|
||||
}
|
||||
j = 0;
|
||||
if( !isnull && xtype==etSQLESCAPE2 ) bufpt[j++] = '\'';
|
||||
for(i=0; (c=arg[i])!=0; i++){
|
||||
bufpt[j++] = c;
|
||||
if( c=='\'' ) bufpt[j++] = c;
|
||||
}
|
||||
if( !isnull && xtype==etSQLESCAPE2 ) bufpt[j++] = '\'';
|
||||
bufpt[j] = 0;
|
||||
length = j;
|
||||
if( precision>=0 && precision<length ) length = precision;
|
||||
}
|
||||
break;
|
||||
case etERROR:
|
||||
buf[0] = '%';
|
||||
buf[1] = c;
|
||||
errorflag = 0;
|
||||
idx = 1+(c!=0);
|
||||
(*func)(arg,"%",idx);
|
||||
count += idx;
|
||||
if( c==0 ) fmt--;
|
||||
break;
|
||||
}/* End switch over the format type */
|
||||
/*
|
||||
** The text of the conversion is pointed to by "bufpt" and is
|
||||
** "length" characters long. The field width is "width". Do
|
||||
** the output.
|
||||
*/
|
||||
if( !flag_leftjustify ){
|
||||
register int nspace;
|
||||
nspace = width-length;
|
||||
if( nspace>0 ){
|
||||
if( flag_center ){
|
||||
nspace = nspace/2;
|
||||
width -= nspace;
|
||||
flag_leftjustify = 1;
|
||||
}
|
||||
count += nspace;
|
||||
while( nspace>=etSPACESIZE ){
|
||||
(*func)(arg,spaces,etSPACESIZE);
|
||||
nspace -= etSPACESIZE;
|
||||
}
|
||||
if( nspace>0 ) (*func)(arg,spaces,nspace);
|
||||
}
|
||||
}
|
||||
if( length>0 ){
|
||||
(*func)(arg,bufpt,length);
|
||||
count += length;
|
||||
}
|
||||
if( flag_leftjustify ){
|
||||
register int nspace;
|
||||
nspace = width-length;
|
||||
if( nspace>0 ){
|
||||
count += nspace;
|
||||
while( nspace>=etSPACESIZE ){
|
||||
(*func)(arg,spaces,etSPACESIZE);
|
||||
nspace -= etSPACESIZE;
|
||||
}
|
||||
if( nspace>0 ) (*func)(arg,spaces,nspace);
|
||||
}
|
||||
}
|
||||
if( zExtra ){
|
||||
sqliteFree(zExtra);
|
||||
}
|
||||
}/* End for loop over the format string */
|
||||
return errorflag ? -1 : count;
|
||||
} /* End of function */
|
||||
|
||||
|
||||
/* This structure is used to store state information about the
|
||||
** write to memory that is currently in progress.
|
||||
*/
|
||||
struct sgMprintf {
|
||||
char *zBase; /* A base allocation */
|
||||
char *zText; /* The string collected so far */
|
||||
int nChar; /* Length of the string so far */
|
||||
int nAlloc; /* Amount of space allocated in zText */
|
||||
};
|
||||
|
||||
/*
|
||||
** This function implements the callback from vxprintf.
|
||||
**
|
||||
** This routine add nNewChar characters of text in zNewText to
|
||||
** the sgMprintf structure pointed to by "arg".
|
||||
*/
|
||||
static void mout(void *arg, char *zNewText, int nNewChar){
|
||||
struct sgMprintf *pM = (struct sgMprintf*)arg;
|
||||
if( pM->nChar + nNewChar + 1 > pM->nAlloc ){
|
||||
pM->nAlloc = pM->nChar + nNewChar*2 + 1;
|
||||
if( pM->zText==pM->zBase ){
|
||||
pM->zText = sqliteMalloc(pM->nAlloc);
|
||||
if( pM->zText && pM->nChar ) memcpy(pM->zText,pM->zBase,pM->nChar);
|
||||
}else{
|
||||
char *z = sqliteRealloc(pM->zText, pM->nAlloc);
|
||||
if( z==0 ){
|
||||
sqliteFree(pM->zText);
|
||||
pM->nChar = 0;
|
||||
pM->nAlloc = 0;
|
||||
}
|
||||
pM->zText = z;
|
||||
}
|
||||
}
|
||||
if( pM->zText ){
|
||||
memcpy(&pM->zText[pM->nChar], zNewText, nNewChar);
|
||||
pM->nChar += nNewChar;
|
||||
pM->zText[pM->nChar] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
** sqlite_mprintf() works like printf(), but allocations memory to hold the
|
||||
** resulting string and returns a pointer to the allocated memory. Use
|
||||
** sqliteFree() to release the memory allocated.
|
||||
*/
|
||||
char *sqliteMPrintf(const char *zFormat, ...){
|
||||
va_list ap;
|
||||
struct sgMprintf sMprintf;
|
||||
char *zNew;
|
||||
char zBuf[200];
|
||||
|
||||
sMprintf.nChar = 0;
|
||||
sMprintf.nAlloc = sizeof(zBuf);
|
||||
sMprintf.zText = zBuf;
|
||||
sMprintf.zBase = zBuf;
|
||||
va_start(ap,zFormat);
|
||||
vxprintf(mout,&sMprintf,zFormat,ap);
|
||||
va_end(ap);
|
||||
sMprintf.zText[sMprintf.nChar] = 0;
|
||||
return sqliteRealloc(sMprintf.zText, sMprintf.nChar+1);
|
||||
}
|
||||
|
||||
/*
|
||||
** sqlite_mprintf() works like printf(), but allocations memory to hold the
|
||||
** resulting string and returns a pointer to the allocated memory. Use
|
||||
** sqliteFree() to release the memory allocated.
|
||||
*/
|
||||
char *sqlite_mprintf(const char *zFormat, ...){
|
||||
va_list ap;
|
||||
struct sgMprintf sMprintf;
|
||||
char *zNew;
|
||||
char zBuf[200];
|
||||
|
||||
sMprintf.nChar = 0;
|
||||
sMprintf.nAlloc = sizeof(zBuf);
|
||||
sMprintf.zText = zBuf;
|
||||
sMprintf.zBase = zBuf;
|
||||
va_start(ap,zFormat);
|
||||
vxprintf(mout,&sMprintf,zFormat,ap);
|
||||
va_end(ap);
|
||||
sMprintf.zText[sMprintf.nChar] = 0;
|
||||
zNew = malloc( sMprintf.nChar+1 );
|
||||
if( zNew ) strcpy(zNew,sMprintf.zText);
|
||||
if( sMprintf.zText!=sMprintf.zBase ){
|
||||
sqliteFree(sMprintf.zText);
|
||||
}
|
||||
return zNew;
|
||||
}
|
||||
|
||||
/* This is the varargs version of sqlite_mprintf.
|
||||
*/
|
||||
char *sqlite_vmprintf(const char *zFormat, va_list ap){
|
||||
struct sgMprintf sMprintf;
|
||||
char *zNew;
|
||||
char zBuf[200];
|
||||
sMprintf.nChar = 0;
|
||||
sMprintf.zText = zBuf;
|
||||
sMprintf.nAlloc = sizeof(zBuf);
|
||||
sMprintf.zBase = zBuf;
|
||||
vxprintf(mout,&sMprintf,zFormat,ap);
|
||||
sMprintf.zText[sMprintf.nChar] = 0;
|
||||
zNew = malloc( sMprintf.nChar+1 );
|
||||
if( zNew ) strcpy(zNew,sMprintf.zText);
|
||||
if( sMprintf.zText!=sMprintf.zBase ){
|
||||
sqliteFree(sMprintf.zText);
|
||||
}
|
||||
return zNew;
|
||||
}
|
||||
|
||||
/*
|
||||
** The following four routines implement the varargs versions of the
|
||||
** sqlite_exec() and sqlite_get_table() interfaces. See the sqlite.h
|
||||
** header files for a more detailed description of how these interfaces
|
||||
** work.
|
||||
**
|
||||
** These routines are all just simple wrappers.
|
||||
*/
|
||||
int sqlite_exec_printf(
|
||||
sqlite *db, /* An open database */
|
||||
const char *sqlFormat, /* printf-style format string for the SQL */
|
||||
sqlite_callback xCallback, /* Callback function */
|
||||
void *pArg, /* 1st argument to callback function */
|
||||
char **errmsg, /* Error msg written here */
|
||||
... /* Arguments to the format string. */
|
||||
){
|
||||
va_list ap;
|
||||
int rc;
|
||||
|
||||
va_start(ap, errmsg);
|
||||
rc = sqlite_exec_vprintf(db, sqlFormat, xCallback, pArg, errmsg, ap);
|
||||
va_end(ap);
|
||||
return rc;
|
||||
}
|
||||
int sqlite_exec_vprintf(
|
||||
sqlite *db, /* An open database */
|
||||
const char *sqlFormat, /* printf-style format string for the SQL */
|
||||
sqlite_callback xCallback, /* Callback function */
|
||||
void *pArg, /* 1st argument to callback function */
|
||||
char **errmsg, /* Error msg written here */
|
||||
va_list ap /* Arguments to the format string. */
|
||||
){
|
||||
char *zSql;
|
||||
int rc;
|
||||
|
||||
zSql = sqlite_vmprintf(sqlFormat, ap);
|
||||
rc = sqlite_exec(db, zSql, xCallback, pArg, errmsg);
|
||||
free(zSql);
|
||||
return rc;
|
||||
}
|
||||
int sqlite_get_table_printf(
|
||||
sqlite *db, /* An open database */
|
||||
const char *sqlFormat, /* printf-style format string for the SQL */
|
||||
char ***resultp, /* Result written to a char *[] that this points to */
|
||||
int *nrow, /* Number of result rows written here */
|
||||
int *ncol, /* Number of result columns written here */
|
||||
char **errmsg, /* Error msg written here */
|
||||
... /* Arguments to the format string */
|
||||
){
|
||||
va_list ap;
|
||||
int rc;
|
||||
|
||||
va_start(ap, errmsg);
|
||||
rc = sqlite_get_table_vprintf(db, sqlFormat, resultp, nrow, ncol, errmsg, ap);
|
||||
va_end(ap);
|
||||
return rc;
|
||||
}
|
||||
int sqlite_get_table_vprintf(
|
||||
sqlite *db, /* An open database */
|
||||
const char *sqlFormat, /* printf-style format string for the SQL */
|
||||
char ***resultp, /* Result written to a char *[] that this points to */
|
||||
int *nrow, /* Number of result rows written here */
|
||||
int *ncolumn, /* Number of result columns written here */
|
||||
char **errmsg, /* Error msg written here */
|
||||
va_list ap /* Arguments to the format string */
|
||||
){
|
||||
char *zSql;
|
||||
int rc;
|
||||
|
||||
zSql = sqlite_vmprintf(sqlFormat, ap);
|
||||
rc = sqlite_get_table(db, zSql, resultp, nrow, ncolumn, errmsg);
|
||||
free(zSql);
|
||||
return rc;
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
/*
|
||||
** 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 code to implement a pseudo-random number
|
||||
** generator (PRNG) for SQLite.
|
||||
**
|
||||
** Random numbers are used by some of the database backends in order
|
||||
** to generate random integer keys for tables or random filenames.
|
||||
**
|
||||
** $Id$
|
||||
*/
|
||||
#include "sqliteInt.h"
|
||||
#include "os.h"
|
||||
|
||||
|
||||
/*
|
||||
** Get a single 8-bit random value from the RC4 PRNG. The Mutex
|
||||
** must be held while executing this routine.
|
||||
**
|
||||
** Why not just use a library random generator like lrand48() for this?
|
||||
** Because the OP_NewRecno opcode in the VDBE depends on having a very
|
||||
** good source of random numbers. The lrand48() library function may
|
||||
** well be good enough. But maybe not. Or maybe lrand48() has some
|
||||
** subtle problems on some systems that could cause problems. It is hard
|
||||
** to know. To minimize the risk of problems due to bad lrand48()
|
||||
** implementations, SQLite uses this random number generator based
|
||||
** on RC4, which we know works very well.
|
||||
*/
|
||||
static int randomByte(){
|
||||
int t;
|
||||
|
||||
/* All threads share a single random number generator.
|
||||
** This structure is the current state of the generator.
|
||||
*/
|
||||
static struct {
|
||||
int isInit; /* True if initialized */
|
||||
int i, j; /* State variables */
|
||||
int s[256]; /* State variables */
|
||||
} prng;
|
||||
|
||||
/* Initialize the state of the random number generator once,
|
||||
** the first time this routine is called. The seed value does
|
||||
** not need to contain a lot of randomness since we are not
|
||||
** trying to do secure encryption or anything like that...
|
||||
**
|
||||
** Nothing in this file or anywhere else in SQLite does any kind of
|
||||
** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
|
||||
** number generator) not as an encryption device.
|
||||
*/
|
||||
if( !prng.isInit ){
|
||||
int i;
|
||||
char k[256];
|
||||
prng.j = 0;
|
||||
prng.i = 0;
|
||||
sqliteOsRandomSeed(k);
|
||||
for(i=0; i<256; i++){
|
||||
prng.s[i] = i;
|
||||
}
|
||||
for(i=0; i<256; i++){
|
||||
int t;
|
||||
prng.j = (prng.j + prng.s[i] + k[i]) & 0xff;
|
||||
t = prng.s[prng.j];
|
||||
prng.s[prng.j] = prng.s[i];
|
||||
prng.s[i] = t;
|
||||
}
|
||||
prng.isInit = 1;
|
||||
}
|
||||
|
||||
/* Generate and return single random byte
|
||||
*/
|
||||
prng.i = (prng.i + 1) & 0xff;
|
||||
prng.j = (prng.j + prng.s[prng.i]) & 0xff;
|
||||
t = prng.s[prng.i];
|
||||
prng.s[prng.i] = prng.s[prng.j];
|
||||
prng.s[prng.j] = t;
|
||||
t = prng.s[prng.i] + prng.s[prng.j];
|
||||
return prng.s[t & 0xff];
|
||||
}
|
||||
|
||||
/*
|
||||
** Return an random 8-bit integer.
|
||||
*/
|
||||
int sqliteRandomByte(){
|
||||
int r;
|
||||
sqliteOsEnterMutex();
|
||||
r = randomByte();
|
||||
sqliteOsLeaveMutex();
|
||||
return r;
|
||||
}
|
||||
|
||||
/*
|
||||
** Return a random 32-bit integer. The integer is generated by making
|
||||
** 4 calls to sqliteRandomByte().
|
||||
*/
|
||||
int sqliteRandomInteger(){
|
||||
int r;
|
||||
int i;
|
||||
sqliteOsEnterMutex();
|
||||
r = randomByte();
|
||||
for(i=1; i<4; i++){
|
||||
r = (r<<8) + randomByte();
|
||||
}
|
||||
sqliteOsLeaveMutex();
|
||||
return r;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,692 +0,0 @@
|
||||
/*
|
||||
** 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 library
|
||||
** presents to client programs.
|
||||
**
|
||||
** @(#) $Id$
|
||||
*/
|
||||
#ifndef _SQLITE_H_
|
||||
#define _SQLITE_H_
|
||||
#include <stdarg.h> /* Needed for the definition of va_list */
|
||||
|
||||
/*
|
||||
** Make sure we can call this stuff from C++.
|
||||
*/
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
** The version of the SQLite library.
|
||||
*/
|
||||
#define SQLITE_VERSION "--VERS--"
|
||||
|
||||
/*
|
||||
** The version string is also compiled into the library so that a program
|
||||
** can check to make sure that the lib*.a file and the *.h file are from
|
||||
** the same version.
|
||||
*/
|
||||
extern const char sqlite_version[];
|
||||
|
||||
/*
|
||||
** The SQLITE_UTF8 macro is defined if the library expects to see
|
||||
** UTF-8 encoded data. The SQLITE_ISO8859 macro is defined if the
|
||||
** iso8859 encoded should be used.
|
||||
*/
|
||||
#define SQLITE_--ENCODING-- 1
|
||||
|
||||
/*
|
||||
** The following constant holds one of two strings, "UTF-8" or "iso8859",
|
||||
** depending on which character encoding the SQLite library expects to
|
||||
** see. The character encoding makes a difference for the LIKE and GLOB
|
||||
** operators and for the LENGTH() and SUBSTR() functions.
|
||||
*/
|
||||
extern const char sqlite_encoding[];
|
||||
|
||||
/*
|
||||
** Each open sqlite database is represented by an instance of the
|
||||
** following opaque structure.
|
||||
*/
|
||||
typedef struct sqlite sqlite;
|
||||
|
||||
/*
|
||||
** A function to open a new sqlite database.
|
||||
**
|
||||
** If the database does not exist and mode indicates write
|
||||
** permission, then a new database is created. If the database
|
||||
** does not exist and mode does not indicate write permission,
|
||||
** then the open fails, an error message generated (if errmsg!=0)
|
||||
** and the function returns 0.
|
||||
**
|
||||
** If mode does not indicates user write permission, then the
|
||||
** database is opened read-only.
|
||||
**
|
||||
** The Truth: As currently implemented, all databases are opened
|
||||
** for writing all the time. Maybe someday we will provide the
|
||||
** ability to open a database readonly. The mode parameters is
|
||||
** provided in anticipation of that enhancement.
|
||||
*/
|
||||
sqlite *sqlite_open(const char *filename, int mode, char **errmsg);
|
||||
|
||||
/*
|
||||
** A function to close the database.
|
||||
**
|
||||
** Call this function with a pointer to a structure that was previously
|
||||
** returned from sqlite_open() and the corresponding database will by closed.
|
||||
*/
|
||||
void sqlite_close(sqlite *);
|
||||
|
||||
/*
|
||||
** The type for a callback function.
|
||||
*/
|
||||
typedef int (*sqlite_callback)(void*,int,char**, char**);
|
||||
|
||||
/*
|
||||
** A function to executes one or more statements of SQL.
|
||||
**
|
||||
** If one or more of the SQL statements are queries, then
|
||||
** the callback function specified by the 3rd parameter is
|
||||
** invoked once for each row of the query result. This callback
|
||||
** should normally return 0. If the callback returns a non-zero
|
||||
** value then the query is aborted, all subsequent SQL statements
|
||||
** are skipped and the sqlite_exec() function returns the SQLITE_ABORT.
|
||||
**
|
||||
** The 4th parameter is an arbitrary pointer that is passed
|
||||
** to the callback function as its first parameter.
|
||||
**
|
||||
** The 2nd parameter to the callback function is the number of
|
||||
** columns in the query result. The 3rd parameter to the callback
|
||||
** is an array of strings holding the values for each column.
|
||||
** The 4th parameter to the callback is an array of strings holding
|
||||
** the names of each column.
|
||||
**
|
||||
** The callback function may be NULL, even for queries. A NULL
|
||||
** callback is not an error. It just means that no callback
|
||||
** will be invoked.
|
||||
**
|
||||
** If an error occurs while parsing or evaluating the SQL (but
|
||||
** not while executing the callback) then an appropriate error
|
||||
** message is written into memory obtained from malloc() and
|
||||
** *errmsg is made to point to that message. The calling function
|
||||
** is responsible for freeing the memory that holds the error
|
||||
** message. Use sqlite_freemem() for this. If errmsg==NULL,
|
||||
** then no error message is ever written.
|
||||
**
|
||||
** The return value is is SQLITE_OK if there are no errors and
|
||||
** some other return code if there is an error. The particular
|
||||
** return value depends on the type of error.
|
||||
**
|
||||
** If the query could not be executed because a database file is
|
||||
** locked or busy, then this function returns SQLITE_BUSY. (This
|
||||
** behavior can be modified somewhat using the sqlite_busy_handler()
|
||||
** and sqlite_busy_timeout() functions below.)
|
||||
*/
|
||||
int sqlite_exec(
|
||||
sqlite*, /* An open database */
|
||||
const char *sql, /* SQL to be executed */
|
||||
sqlite_callback, /* Callback function */
|
||||
void *, /* 1st argument to callback function */
|
||||
char **errmsg /* Error msg written here */
|
||||
);
|
||||
|
||||
/*
|
||||
** Return values for sqlite_exec() and sqlite_step()
|
||||
*/
|
||||
#define SQLITE_OK 0 /* Successful result */
|
||||
#define SQLITE_ERROR 1 /* SQL error or missing database */
|
||||
#define SQLITE_INTERNAL 2 /* An internal logic error in SQLite */
|
||||
#define SQLITE_PERM 3 /* Access permission denied */
|
||||
#define SQLITE_ABORT 4 /* Callback routine requested an abort */
|
||||
#define SQLITE_BUSY 5 /* The database file is locked */
|
||||
#define SQLITE_LOCKED 6 /* A table in the database is locked */
|
||||
#define SQLITE_NOMEM 7 /* A malloc() failed */
|
||||
#define SQLITE_READONLY 8 /* Attempt to write a readonly database */
|
||||
#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite_interrupt() */
|
||||
#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
|
||||
#define SQLITE_CORRUPT 11 /* The database disk image is malformed */
|
||||
#define SQLITE_NOTFOUND 12 /* (Internal Only) Table or record not found */
|
||||
#define SQLITE_FULL 13 /* Insertion failed because database is full */
|
||||
#define SQLITE_CANTOPEN 14 /* Unable to open the database file */
|
||||
#define SQLITE_PROTOCOL 15 /* Database lock protocol error */
|
||||
#define SQLITE_EMPTY 16 /* (Internal Only) Database table is empty */
|
||||
#define SQLITE_SCHEMA 17 /* The database schema changed */
|
||||
#define SQLITE_TOOBIG 18 /* Too much data for one row of a table */
|
||||
#define SQLITE_CONSTRAINT 19 /* Abort due to contraint violation */
|
||||
#define SQLITE_MISMATCH 20 /* Data type mismatch */
|
||||
#define SQLITE_MISUSE 21 /* Library used incorrectly */
|
||||
#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
|
||||
#define SQLITE_AUTH 23 /* Authorization denied */
|
||||
#define SQLITE_ROW 100 /* sqlite_step() has another row ready */
|
||||
#define SQLITE_DONE 101 /* sqlite_step() has finished executing */
|
||||
|
||||
/*
|
||||
** Each entry in an SQLite table has a unique integer key. (The key is
|
||||
** the value of the INTEGER PRIMARY KEY column if there is such a column,
|
||||
** otherwise the key is generated at random. The unique key is always
|
||||
** available as the ROWID, OID, or _ROWID_ column.) The following routine
|
||||
** returns the integer key of the most recent insert in the database.
|
||||
**
|
||||
** This function is similar to the mysql_insert_id() function from MySQL.
|
||||
*/
|
||||
int sqlite_last_insert_rowid(sqlite*);
|
||||
|
||||
/*
|
||||
** This function returns the number of database rows that were changed
|
||||
** (or inserted or deleted) by the most recent called sqlite_exec().
|
||||
**
|
||||
** All changes are counted, even if they were later undone by a
|
||||
** ROLLBACK or ABORT. Except, changes associated with creating and
|
||||
** dropping tables are not counted.
|
||||
**
|
||||
** If a callback invokes sqlite_exec() recursively, then the changes
|
||||
** in the inner, recursive call are counted together with the changes
|
||||
** in the outer call.
|
||||
**
|
||||
** SQLite implements the command "DELETE FROM table" without a WHERE clause
|
||||
** by dropping and recreating the table. (This is much faster than going
|
||||
** through and deleting individual elements form the table.) Because of
|
||||
** this optimization, the change count for "DELETE FROM table" will be
|
||||
** zero regardless of the number of elements that were originally in the
|
||||
** table. To get an accurate count of the number of rows deleted, use
|
||||
** "DELETE FROM table WHERE 1" instead.
|
||||
*/
|
||||
int sqlite_changes(sqlite*);
|
||||
|
||||
/* If the parameter to this routine is one of the return value constants
|
||||
** defined above, then this routine returns a constant text string which
|
||||
** descripts (in English) the meaning of the return value.
|
||||
*/
|
||||
const char *sqlite_error_string(int);
|
||||
#define sqliteErrStr sqlite_error_string /* Legacy. Do not use in new code. */
|
||||
|
||||
/* This function causes any pending database operation to abort and
|
||||
** return at its earliest opportunity. This routine is typically
|
||||
** called in response to a user action such as pressing "Cancel"
|
||||
** or Ctrl-C where the user wants a long query operation to halt
|
||||
** immediately.
|
||||
*/
|
||||
void sqlite_interrupt(sqlite*);
|
||||
|
||||
|
||||
/* This function returns true if the given input string comprises
|
||||
** one or more complete SQL statements.
|
||||
**
|
||||
** The algorithm is simple. If the last token other than spaces
|
||||
** and comments is a semicolon, then return true. otherwise return
|
||||
** false.
|
||||
*/
|
||||
int sqlite_complete(const char *sql);
|
||||
|
||||
/*
|
||||
** This routine identifies a callback function that is invoked
|
||||
** whenever an attempt is made to open a database table that is
|
||||
** currently locked by another process or thread. If the busy callback
|
||||
** is NULL, then sqlite_exec() returns SQLITE_BUSY immediately if
|
||||
** it finds a locked table. If the busy callback is not NULL, then
|
||||
** sqlite_exec() invokes the callback with three arguments. The
|
||||
** second argument is the name of the locked table and the third
|
||||
** argument is the number of times the table has been busy. If the
|
||||
** busy callback returns 0, then sqlite_exec() immediately returns
|
||||
** SQLITE_BUSY. If the callback returns non-zero, then sqlite_exec()
|
||||
** tries to open the table again and the cycle repeats.
|
||||
**
|
||||
** The default busy callback is NULL.
|
||||
**
|
||||
** Sqlite is re-entrant, so the busy handler may start a new query.
|
||||
** (It is not clear why anyone would every want to do this, but it
|
||||
** is allowed, in theory.) But the busy handler may not close the
|
||||
** database. Closing the database from a busy handler will delete
|
||||
** data structures out from under the executing query and will
|
||||
** probably result in a coredump.
|
||||
*/
|
||||
void sqlite_busy_handler(sqlite*, int(*)(void*,const char*,int), void*);
|
||||
|
||||
/*
|
||||
** This routine sets a busy handler that sleeps for a while when a
|
||||
** table is locked. The handler will sleep multiple times until
|
||||
** at least "ms" milleseconds of sleeping have been done. After
|
||||
** "ms" milleseconds of sleeping, the handler returns 0 which
|
||||
** causes sqlite_exec() to return SQLITE_BUSY.
|
||||
**
|
||||
** Calling this routine with an argument less than or equal to zero
|
||||
** turns off all busy handlers.
|
||||
*/
|
||||
void sqlite_busy_timeout(sqlite*, int ms);
|
||||
|
||||
/*
|
||||
** This next routine is really just a wrapper around sqlite_exec().
|
||||
** Instead of invoking a user-supplied callback for each row of the
|
||||
** result, this routine remembers each row of the result in memory
|
||||
** obtained from malloc(), then returns all of the result after the
|
||||
** query has finished.
|
||||
**
|
||||
** As an example, suppose the query result where this table:
|
||||
**
|
||||
** Name | Age
|
||||
** -----------------------
|
||||
** Alice | 43
|
||||
** Bob | 28
|
||||
** Cindy | 21
|
||||
**
|
||||
** If the 3rd argument were &azResult then after the function returns
|
||||
** azResult will contain the following data:
|
||||
**
|
||||
** azResult[0] = "Name";
|
||||
** azResult[1] = "Age";
|
||||
** azResult[2] = "Alice";
|
||||
** azResult[3] = "43";
|
||||
** azResult[4] = "Bob";
|
||||
** azResult[5] = "28";
|
||||
** azResult[6] = "Cindy";
|
||||
** azResult[7] = "21";
|
||||
**
|
||||
** Notice that there is an extra row of data containing the column
|
||||
** headers. But the *nrow return value is still 3. *ncolumn is
|
||||
** set to 2. In general, the number of values inserted into azResult
|
||||
** will be ((*nrow) + 1)*(*ncolumn).
|
||||
**
|
||||
** After the calling function has finished using the result, it should
|
||||
** pass the result data pointer to sqlite_free_table() in order to
|
||||
** release the memory that was malloc-ed. Because of the way the
|
||||
** malloc() happens, the calling function must not try to call
|
||||
** malloc() directly. Only sqlite_free_table() is able to release
|
||||
** the memory properly and safely.
|
||||
**
|
||||
** The return value of this routine is the same as from sqlite_exec().
|
||||
*/
|
||||
int sqlite_get_table(
|
||||
sqlite*, /* An open database */
|
||||
const char *sql, /* SQL to be executed */
|
||||
char ***resultp, /* Result written to a char *[] that this points to */
|
||||
int *nrow, /* Number of result rows written here */
|
||||
int *ncolumn, /* Number of result columns written here */
|
||||
char **errmsg /* Error msg written here */
|
||||
);
|
||||
|
||||
/*
|
||||
** Call this routine to free the memory that sqlite_get_table() allocated.
|
||||
*/
|
||||
void sqlite_free_table(char **result);
|
||||
|
||||
/*
|
||||
** The following routines are wrappers around sqlite_exec() and
|
||||
** sqlite_get_table(). The only difference between the routines that
|
||||
** follow and the originals is that the second argument to the
|
||||
** routines that follow is really a printf()-style format
|
||||
** string describing the SQL to be executed. Arguments to the format
|
||||
** string appear at the end of the argument list.
|
||||
**
|
||||
** All of the usual printf formatting options apply. In addition, there
|
||||
** is a "%q" option. %q works like %s in that it substitutes a null-terminated
|
||||
** string from the argument list. But %q also doubles every '\'' character.
|
||||
** %q is designed for use inside a string literal. By doubling each '\''
|
||||
** character it escapes that character and allows it to be inserted into
|
||||
** the string.
|
||||
**
|
||||
** For example, so some string variable contains text as follows:
|
||||
**
|
||||
** char *zText = "It's a happy day!";
|
||||
**
|
||||
** We can use this text in an SQL statement as follows:
|
||||
**
|
||||
** sqlite_exec_printf(db, "INSERT INTO table VALUES('%q')",
|
||||
** callback1, 0, 0, zText);
|
||||
**
|
||||
** Because the %q format string is used, the '\'' character in zText
|
||||
** is escaped and the SQL generated is as follows:
|
||||
**
|
||||
** INSERT INTO table1 VALUES('It''s a happy day!')
|
||||
**
|
||||
** This is correct. Had we used %s instead of %q, the generated SQL
|
||||
** would have looked like this:
|
||||
**
|
||||
** INSERT INTO table1 VALUES('It's a happy day!');
|
||||
**
|
||||
** This second example is an SQL syntax error. As a general rule you
|
||||
** should always use %q instead of %s when inserting text into a string
|
||||
** literal.
|
||||
*/
|
||||
int sqlite_exec_printf(
|
||||
sqlite*, /* An open database */
|
||||
const char *sqlFormat, /* printf-style format string for the SQL */
|
||||
sqlite_callback, /* Callback function */
|
||||
void *, /* 1st argument to callback function */
|
||||
char **errmsg, /* Error msg written here */
|
||||
... /* Arguments to the format string. */
|
||||
);
|
||||
int sqlite_exec_vprintf(
|
||||
sqlite*, /* An open database */
|
||||
const char *sqlFormat, /* printf-style format string for the SQL */
|
||||
sqlite_callback, /* Callback function */
|
||||
void *, /* 1st argument to callback function */
|
||||
char **errmsg, /* Error msg written here */
|
||||
va_list ap /* Arguments to the format string. */
|
||||
);
|
||||
int sqlite_get_table_printf(
|
||||
sqlite*, /* An open database */
|
||||
const char *sqlFormat, /* printf-style format string for the SQL */
|
||||
char ***resultp, /* Result written to a char *[] that this points to */
|
||||
int *nrow, /* Number of result rows written here */
|
||||
int *ncolumn, /* Number of result columns written here */
|
||||
char **errmsg, /* Error msg written here */
|
||||
... /* Arguments to the format string */
|
||||
);
|
||||
int sqlite_get_table_vprintf(
|
||||
sqlite*, /* An open database */
|
||||
const char *sqlFormat, /* printf-style format string for the SQL */
|
||||
char ***resultp, /* Result written to a char *[] that this points to */
|
||||
int *nrow, /* Number of result rows written here */
|
||||
int *ncolumn, /* Number of result columns written here */
|
||||
char **errmsg, /* Error msg written here */
|
||||
va_list ap /* Arguments to the format string */
|
||||
);
|
||||
char *sqlite_mprintf(const char*,...);
|
||||
|
||||
/*
|
||||
** Windows systems should call this routine to free memory that
|
||||
** is returned in the in the errmsg parameter of sqlite_open() when
|
||||
** SQLite is a DLL. For some reason, it does not work to call free()
|
||||
** directly.
|
||||
*/
|
||||
void sqlite_freemem(void *p);
|
||||
|
||||
/*
|
||||
** Windows systems need functions to call to return the sqlite_version
|
||||
** and sqlite_encoding strings.
|
||||
*/
|
||||
const char *sqlite_libversion(void);
|
||||
const char *sqlite_libencoding(void);
|
||||
|
||||
/*
|
||||
** A pointer to the following structure is used to communicate with
|
||||
** the implementations of user-defined functions.
|
||||
*/
|
||||
typedef struct sqlite_func sqlite_func;
|
||||
|
||||
/*
|
||||
** Use the following routines to create new user-defined functions. See
|
||||
** the documentation for details.
|
||||
*/
|
||||
int sqlite_create_function(
|
||||
sqlite*, /* Database where the new function is registered */
|
||||
const char *zName, /* Name of the new function */
|
||||
int nArg, /* Number of arguments. -1 means any number */
|
||||
void (*xFunc)(sqlite_func*,int,const char**), /* C code to implement */
|
||||
void *pUserData /* Available via the sqlite_user_data() call */
|
||||
);
|
||||
int sqlite_create_aggregate(
|
||||
sqlite*, /* Database where the new function is registered */
|
||||
const char *zName, /* Name of the function */
|
||||
int nArg, /* Number of arguments */
|
||||
void (*xStep)(sqlite_func*,int,const char**), /* Called for each row */
|
||||
void (*xFinalize)(sqlite_func*), /* Called once to get final result */
|
||||
void *pUserData /* Available via the sqlite_user_data() call */
|
||||
);
|
||||
|
||||
/*
|
||||
** Use the following routine to define the datatype returned by a
|
||||
** user-defined function. The second argument can be one of the
|
||||
** constants SQLITE_NUMERIC, SQLITE_TEXT, or SQLITE_ARGS or it
|
||||
** can be an integer greater than or equal to zero. The datatype
|
||||
** will be numeric or text (the only two types supported) if the
|
||||
** argument is SQLITE_NUMERIC or SQLITE_TEXT. If the argument is
|
||||
** SQLITE_ARGS, then the datatype is numeric if any argument to the
|
||||
** function is numeric and is text otherwise. If the second argument
|
||||
** is an integer, then the datatype of the result is the same as the
|
||||
** parameter to the function that corresponds to that integer.
|
||||
*/
|
||||
int sqlite_function_type(
|
||||
sqlite *db, /* The database there the function is registered */
|
||||
const char *zName, /* Name of the function */
|
||||
int datatype /* The datatype for this function */
|
||||
);
|
||||
#define SQLITE_NUMERIC (-1)
|
||||
#define SQLITE_TEXT (-2)
|
||||
#define SQLITE_ARGS (-3)
|
||||
|
||||
/*
|
||||
** The user function implementations call one of the following four routines
|
||||
** in order to return their results. The first parameter to each of these
|
||||
** routines is a copy of the first argument to xFunc() or xFinialize().
|
||||
** The second parameter to these routines is the result to be returned.
|
||||
** A NULL can be passed as the second parameter to sqlite_set_result_string()
|
||||
** in order to return a NULL result.
|
||||
**
|
||||
** The 3rd argument to _string and _error is the number of characters to
|
||||
** take from the string. If this argument is negative, then all characters
|
||||
** up to and including the first '\000' are used.
|
||||
**
|
||||
** The sqlite_set_result_string() function allocates a buffer to hold the
|
||||
** result and returns a pointer to this buffer. The calling routine
|
||||
** (that is, the implmentation of a user function) can alter the content
|
||||
** of this buffer if desired.
|
||||
*/
|
||||
char *sqlite_set_result_string(sqlite_func*,const char*,int);
|
||||
void sqlite_set_result_int(sqlite_func*,int);
|
||||
void sqlite_set_result_double(sqlite_func*,double);
|
||||
void sqlite_set_result_error(sqlite_func*,const char*,int);
|
||||
|
||||
/*
|
||||
** The pUserData parameter to the sqlite_create_function() and
|
||||
** sqlite_create_aggregate() routines used to register user functions
|
||||
** is available to the implementation of the function using this
|
||||
** call.
|
||||
*/
|
||||
void *sqlite_user_data(sqlite_func*);
|
||||
|
||||
/*
|
||||
** Aggregate functions use the following routine to allocate
|
||||
** a structure for storing their state. The first time this routine
|
||||
** is called for a particular aggregate, a new structure of size nBytes
|
||||
** is allocated, zeroed, and returned. On subsequent calls (for the
|
||||
** same aggregate instance) the same buffer is returned. The implementation
|
||||
** of the aggregate can use the returned buffer to accumulate data.
|
||||
**
|
||||
** The buffer allocated is freed automatically be SQLite.
|
||||
*/
|
||||
void *sqlite_aggregate_context(sqlite_func*, int nBytes);
|
||||
|
||||
/*
|
||||
** The next routine returns the number of calls to xStep for a particular
|
||||
** aggregate function instance. The current call to xStep counts so this
|
||||
** routine always returns at least 1.
|
||||
*/
|
||||
int sqlite_aggregate_count(sqlite_func*);
|
||||
|
||||
/*
|
||||
** This routine registers a callback with the SQLite library. The
|
||||
** callback is invoked (at compile-time, not at run-time) for each
|
||||
** attempt to access a column of a table in the database. The callback
|
||||
** returns SQLITE_OK if access is allowed, SQLITE_DENY if the entire
|
||||
** SQL statement should be aborted with an error and SQLITE_IGNORE
|
||||
** if the column should be treated as a NULL value.
|
||||
*/
|
||||
int sqlite_set_authorizer(
|
||||
sqlite*,
|
||||
int (*xAuth)(void*,int,const char*,const char*),
|
||||
void *pUserData
|
||||
);
|
||||
|
||||
/*
|
||||
** The second parameter to the access authorization function above will
|
||||
** be one of the values below. These values signify what kind of operation
|
||||
** is to be authorized. The 3rd and 4th parameters to the authorization
|
||||
** function will be parameters or NULL depending on which of the following
|
||||
** codes is used as the second parameter.
|
||||
**
|
||||
** Arg-3 Arg-4
|
||||
*/
|
||||
#define SQLITE_COPY 0 /* Table Name File Name */
|
||||
#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
|
||||
#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
|
||||
#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
|
||||
#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
|
||||
#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
|
||||
#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
|
||||
#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
|
||||
#define SQLITE_CREATE_VIEW 8 /* View Name NULL */
|
||||
#define SQLITE_DELETE 9 /* Table Name NULL */
|
||||
#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
|
||||
#define SQLITE_DROP_TABLE 11 /* Table Name NULL */
|
||||
#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
|
||||
#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
|
||||
#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
|
||||
#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
|
||||
#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
|
||||
#define SQLITE_DROP_VIEW 17 /* View Name NULL */
|
||||
#define SQLITE_INSERT 18 /* Table Name NULL */
|
||||
#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
|
||||
#define SQLITE_READ 20 /* Table Name Column Name */
|
||||
#define SQLITE_SELECT 21 /* NULL NULL */
|
||||
#define SQLITE_TRANSACTION 22 /* NULL NULL */
|
||||
#define SQLITE_UPDATE 23 /* Table Name Column Name */
|
||||
|
||||
/*
|
||||
** The return value of the authorization function should be one of the
|
||||
** following constants:
|
||||
*/
|
||||
/* #define SQLITE_OK 0 // Allow access (This is actually defined above) */
|
||||
#define SQLITE_DENY 1 /* Abort the SQL statement with an error */
|
||||
#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
|
||||
|
||||
/*
|
||||
** Register a function that is called at every invocation of sqlite_exec()
|
||||
** or sqlite_compile(). This function can be used (for example) to generate
|
||||
** a log file of all SQL executed against a database.
|
||||
*/
|
||||
void *sqlite_trace(sqlite*, void(*xTrace)(void*,const char*), void*);
|
||||
|
||||
/*** The Callback-Free API
|
||||
**
|
||||
** The following routines implement a new way to access SQLite that does not
|
||||
** involve the use of callbacks.
|
||||
**
|
||||
** An sqlite_vm is an opaque object that represents a single SQL statement
|
||||
** that is ready to be executed.
|
||||
*/
|
||||
typedef struct sqlite_vm sqlite_vm;
|
||||
|
||||
/*
|
||||
** To execute an SQLite query without the use of callbacks, you first have
|
||||
** to compile the SQL using this routine. The 1st parameter "db" is a pointer
|
||||
** to an sqlite object obtained from sqlite_open(). The 2nd parameter
|
||||
** "zSql" is the text of the SQL to be compiled. The remaining parameters
|
||||
** are all outputs.
|
||||
**
|
||||
** *pzTail is made to point to the first character past the end of the first
|
||||
** SQL statement in zSql. This routine only compiles the first statement
|
||||
** in zSql, so *pzTail is left pointing to what remains uncompiled.
|
||||
**
|
||||
** *ppVm is left pointing to a "virtual machine" that can be used to execute
|
||||
** the compiled statement. Or if there is an error, *ppVm may be set to NULL.
|
||||
** If the input text contained no SQL (if the input is and empty string or
|
||||
** a comment) then *ppVm is set to NULL.
|
||||
**
|
||||
** If any errors are detected during compilation, an error message is written
|
||||
** into space obtained from malloc() and *pzErrMsg is made to point to that
|
||||
** error message. The calling routine is responsible for freeing the text
|
||||
** of this message when it has finished with it. Use sqlite_freemem() to
|
||||
** free the message. pzErrMsg may be NULL in which case no error message
|
||||
** will be generated.
|
||||
**
|
||||
** On success, SQLITE_OK is returned. Otherwise and error code is returned.
|
||||
*/
|
||||
int sqlite_compile(
|
||||
sqlite *db, /* The open database */
|
||||
const char *zSql, /* SQL statement to be compiled */
|
||||
const char **pzTail, /* OUT: uncompiled tail of zSql */
|
||||
sqlite_vm **ppVm, /* OUT: the virtual machine to execute zSql */
|
||||
char **pzErrmsg /* OUT: Error message. */
|
||||
);
|
||||
|
||||
/*
|
||||
** After an SQL statement has been compiled, it is handed to this routine
|
||||
** to be executed. This routine executes the statement as far as it can
|
||||
** go then returns. The return value will be one of SQLITE_DONE,
|
||||
** SQLITE_ERROR, SQLITE_BUSY, SQLITE_ROW, or SQLITE_MISUSE.
|
||||
**
|
||||
** SQLITE_DONE means that the execute of the SQL statement is complete
|
||||
** an no errors have occurred. sqlite_step() should not be called again
|
||||
** for the same virtual machine. *pN is set to the number of columns in
|
||||
** the result set and *pazColName is set to an array of strings that
|
||||
** describe the column names and datatypes. The name of the i-th column
|
||||
** is (*pazColName)[i] and the datatype of the i-th column is
|
||||
** (*pazColName)[i+*pN]. *pazValue is set to NULL.
|
||||
**
|
||||
** SQLITE_ERROR means that the virtual machine encountered a run-time
|
||||
** error. sqlite_step() should not be called again for the same
|
||||
** virtual machine. *pN is set to 0 and *pazColName and *pazValue are set
|
||||
** to NULL. Use sqlite_finalize() to obtain the specific error code
|
||||
** and the error message text for the error.
|
||||
**
|
||||
** SQLITE_BUSY means that an attempt to open the database failed because
|
||||
** another thread or process is holding a lock. The calling routine
|
||||
** can try again to open the database by calling sqlite_step() again.
|
||||
** The return code will only be SQLITE_BUSY if no busy handler is registered
|
||||
** using the sqlite_busy_handler() or sqlite_busy_timeout() routines. If
|
||||
** a busy handler callback has been registered but returns 0, then this
|
||||
** routine will return SQLITE_ERROR and sqltie_finalize() will return
|
||||
** SQLITE_BUSY when it is called.
|
||||
**
|
||||
** SQLITE_ROW means that a single row of the result is now available.
|
||||
** The data is contained in *pazValue. The value of the i-th column is
|
||||
** (*azValue)[i]. *pN and *pazColName are set as described in SQLITE_DONE.
|
||||
** Invoke sqlite_step() again to advance to the next row.
|
||||
**
|
||||
** SQLITE_MISUSE is returned if sqlite_step() is called incorrectly.
|
||||
** For example, if you call sqlite_step() after the virtual machine
|
||||
** has halted (after a prior call to sqlite_step() has returned SQLITE_DONE)
|
||||
** or if you call sqlite_step() with an incorrectly initialized virtual
|
||||
** machine or a virtual machine that has been deleted or that is associated
|
||||
** with an sqlite structure that has been closed.
|
||||
*/
|
||||
int sqlite_step(
|
||||
sqlite_vm *pVm, /* The virtual machine to execute */
|
||||
int *pN, /* OUT: Number of columns in result */
|
||||
const char ***pazValue, /* OUT: Column data */
|
||||
const char ***pazColName /* OUT: Column names and datatypes */
|
||||
);
|
||||
|
||||
/*
|
||||
** This routine is called to delete a virtual machine after it has finished
|
||||
** executing. The return value is the result code. SQLITE_OK is returned
|
||||
** if the statement executed successfully and some other value is returned if
|
||||
** there was any kind of error. If an error occurred and pzErrMsg is not
|
||||
** NULL, then an error message is written into memory obtained from malloc()
|
||||
** and *pzErrMsg is made to point to that error message. The calling routine
|
||||
** should use sqlite_freemem() to delete this message when it has finished
|
||||
** with it.
|
||||
**
|
||||
** This routine can be called at any point during the execution of the
|
||||
** virtual machine. If the virtual machine has not completed execution
|
||||
** when this routine is called, that is like encountering an error or
|
||||
** an interrupt. (See sqlite_interrupt().) Incomplete updates may be
|
||||
** rolled back and transactions cancelled, depending on the circumstances,
|
||||
** and the result code returned will be SQLITE_ABORT.
|
||||
*/
|
||||
int sqlite_finalize(sqlite_vm*, char **pzErrMsg);
|
||||
|
||||
/*
|
||||
** Attempt to open the file named in the argument as the auxiliary database
|
||||
** file. The auxiliary database file is used to store TEMP tables. But
|
||||
** by using this API, it is possible to trick SQLite into opening two
|
||||
** separate databases and acting on them as if they were one.
|
||||
**
|
||||
****** THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE. ******
|
||||
*/
|
||||
int sqlite_open_aux_file(sqlite *db, const char *zName, char **pzErrMsg);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* End of the 'extern "C"' block */
|
||||
#endif
|
||||
|
||||
#endif /* _SQLITE_H_ */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,200 +0,0 @@
|
||||
/*
|
||||
** 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 the sqlite_get_table() and sqlite_free_table()
|
||||
** interface routines. These are just wrappers around the main
|
||||
** interface routine of sqlite_exec().
|
||||
**
|
||||
** These routines are in a separate files so that they will not be linked
|
||||
** if they are not used.
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "sqliteInt.h"
|
||||
|
||||
/*
|
||||
** This structure is used to pass data from sqlite_get_table() through
|
||||
** to the callback function is uses to build the result.
|
||||
*/
|
||||
typedef struct TabResult {
|
||||
char **azResult;
|
||||
char *zErrMsg;
|
||||
int nResult;
|
||||
int nAlloc;
|
||||
int nRow;
|
||||
int nColumn;
|
||||
int nData;
|
||||
int rc;
|
||||
} TabResult;
|
||||
|
||||
/*
|
||||
** This routine is called once for each row in the result table. Its job
|
||||
** is to fill in the TabResult structure appropriately, allocating new
|
||||
** memory as necessary.
|
||||
*/
|
||||
static int sqlite_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
|
||||
TabResult *p = (TabResult*)pArg;
|
||||
int need;
|
||||
int i;
|
||||
char *z;
|
||||
|
||||
/* Make sure there is enough space in p->azResult to hold everything
|
||||
** we need to remember from this invocation of the callback.
|
||||
*/
|
||||
if( p->nRow==0 && argv!=0 ){
|
||||
need = nCol*2;
|
||||
}else{
|
||||
need = nCol;
|
||||
}
|
||||
if( p->nData + need >= p->nAlloc ){
|
||||
char **azNew;
|
||||
p->nAlloc = p->nAlloc*2 + need + 1;
|
||||
azNew = realloc( p->azResult, sizeof(char*)*p->nAlloc );
|
||||
if( azNew==0 ){
|
||||
p->rc = SQLITE_NOMEM;
|
||||
return 1;
|
||||
}
|
||||
p->azResult = azNew;
|
||||
}
|
||||
|
||||
/* If this is the first row, then generate an extra row containing
|
||||
** the names of all columns.
|
||||
*/
|
||||
if( p->nRow==0 ){
|
||||
p->nColumn = nCol;
|
||||
for(i=0; i<nCol; i++){
|
||||
if( colv[i]==0 ){
|
||||
z = 0;
|
||||
}else{
|
||||
z = malloc( strlen(colv[i])+1 );
|
||||
if( z==0 ){
|
||||
p->rc = SQLITE_NOMEM;
|
||||
return 1;
|
||||
}
|
||||
strcpy(z, colv[i]);
|
||||
}
|
||||
p->azResult[p->nData++] = z;
|
||||
}
|
||||
}else if( p->nColumn!=nCol ){
|
||||
sqliteSetString(&p->zErrMsg,
|
||||
"sqlite_get_table() called with two or more incompatible queries", 0);
|
||||
p->rc = SQLITE_ERROR;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Copy over the row data
|
||||
*/
|
||||
if( argv!=0 ){
|
||||
for(i=0; i<nCol; i++){
|
||||
if( argv[i]==0 ){
|
||||
z = 0;
|
||||
}else{
|
||||
z = malloc( strlen(argv[i])+1 );
|
||||
if( z==0 ){
|
||||
p->rc = SQLITE_NOMEM;
|
||||
return 1;
|
||||
}
|
||||
strcpy(z, argv[i]);
|
||||
}
|
||||
p->azResult[p->nData++] = z;
|
||||
}
|
||||
p->nRow++;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
** Query the database. But instead of invoking a callback for each row,
|
||||
** malloc() for space to hold the result and return the entire results
|
||||
** at the conclusion of the call.
|
||||
**
|
||||
** The result that is written to ***pazResult is held in memory obtained
|
||||
** from malloc(). But the caller cannot free this memory directly.
|
||||
** Instead, the entire table should be passed to sqlite_free_table() when
|
||||
** the calling procedure is finished using it.
|
||||
*/
|
||||
int sqlite_get_table(
|
||||
sqlite *db, /* The database on which the SQL executes */
|
||||
const char *zSql, /* The SQL to be executed */
|
||||
char ***pazResult, /* Write the result table here */
|
||||
int *pnRow, /* Write the number of rows in the result here */
|
||||
int *pnColumn, /* Write the number of columns of result here */
|
||||
char **pzErrMsg /* Write error messages here */
|
||||
){
|
||||
int rc;
|
||||
TabResult res;
|
||||
if( pazResult==0 ){ return SQLITE_ERROR; }
|
||||
*pazResult = 0;
|
||||
if( pnColumn ) *pnColumn = 0;
|
||||
if( pnRow ) *pnRow = 0;
|
||||
res.zErrMsg = 0;
|
||||
res.nResult = 0;
|
||||
res.nRow = 0;
|
||||
res.nColumn = 0;
|
||||
res.nData = 1;
|
||||
res.nAlloc = 20;
|
||||
res.rc = SQLITE_OK;
|
||||
res.azResult = malloc( sizeof(char*)*res.nAlloc );
|
||||
if( res.azResult==0 ){
|
||||
return SQLITE_NOMEM;
|
||||
}
|
||||
res.azResult[0] = 0;
|
||||
rc = sqlite_exec(db, zSql, sqlite_get_table_cb, &res, pzErrMsg);
|
||||
if( res.azResult ){
|
||||
res.azResult[0] = (char*)res.nData;
|
||||
}
|
||||
if( rc==SQLITE_ABORT ){
|
||||
sqlite_free_table(&res.azResult[1]);
|
||||
if( res.zErrMsg ){
|
||||
if( pzErrMsg ){
|
||||
free(*pzErrMsg);
|
||||
*pzErrMsg = res.zErrMsg;
|
||||
sqliteStrRealloc(pzErrMsg);
|
||||
}else{
|
||||
sqliteFree(res.zErrMsg);
|
||||
}
|
||||
}
|
||||
return res.rc;
|
||||
}
|
||||
sqliteFree(res.zErrMsg);
|
||||
if( rc!=SQLITE_OK ){
|
||||
sqlite_free_table(&res.azResult[1]);
|
||||
return rc;
|
||||
}
|
||||
if( res.nAlloc>res.nData ){
|
||||
char **azNew;
|
||||
azNew = realloc( res.azResult, sizeof(char*)*(res.nData+1) );
|
||||
if( res.azResult==0 ){
|
||||
sqlite_free_table(&res.azResult[1]);
|
||||
return SQLITE_NOMEM;
|
||||
}
|
||||
res.azResult = azNew;
|
||||
}
|
||||
*pazResult = &res.azResult[1];
|
||||
if( pnColumn ) *pnColumn = res.nColumn;
|
||||
if( pnRow ) *pnRow = res.nRow;
|
||||
return rc;
|
||||
}
|
||||
|
||||
/*
|
||||
** This routine frees the space the sqlite_get_table() malloced.
|
||||
*/
|
||||
void sqlite_free_table(
|
||||
char **azResult /* Result returned from from sqlite_get_table() */
|
||||
){
|
||||
if( azResult ){
|
||||
int i, n;
|
||||
azResult--;
|
||||
n = (int)azResult[0];
|
||||
for(i=1; i<n; i++){ if( azResult[i] ) free(azResult[i]); }
|
||||
free(azResult);
|
||||
}
|
||||
}
|
||||
@@ -1,496 +0,0 @@
|
||||
/*
|
||||
** 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.
|
||||
**
|
||||
*************************************************************************
|
||||
** An tokenizer for SQL
|
||||
**
|
||||
** This file contains C code that splits an SQL input string up into
|
||||
** individual tokens and sends those tokens one-by-one over to the
|
||||
** parser for analysis.
|
||||
**
|
||||
** $Id$
|
||||
*/
|
||||
#include "sqliteInt.h"
|
||||
#include "os.h"
|
||||
#include <ctype.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
/*
|
||||
** All the keywords of the SQL language are stored as in a hash
|
||||
** table composed of instances of the following structure.
|
||||
*/
|
||||
typedef struct Keyword Keyword;
|
||||
struct Keyword {
|
||||
char *zName; /* The keyword name */
|
||||
int len; /* Number of characters in the keyword */
|
||||
int tokenType; /* The token value for this keyword */
|
||||
Keyword *pNext; /* Next keyword with the same hash */
|
||||
};
|
||||
|
||||
/*
|
||||
** These are the keywords
|
||||
*/
|
||||
static Keyword aKeywordTable[] = {
|
||||
{ "ABORT", 0, TK_ABORT, 0 },
|
||||
{ "AFTER", 0, TK_AFTER, 0 },
|
||||
{ "ALL", 0, TK_ALL, 0 },
|
||||
{ "AND", 0, TK_AND, 0 },
|
||||
{ "AS", 0, TK_AS, 0 },
|
||||
{ "ASC", 0, TK_ASC, 0 },
|
||||
{ "BEFORE", 0, TK_BEFORE, 0 },
|
||||
{ "BEGIN", 0, TK_BEGIN, 0 },
|
||||
{ "BETWEEN", 0, TK_BETWEEN, 0 },
|
||||
{ "BY", 0, TK_BY, 0 },
|
||||
{ "CASCADE", 0, TK_CASCADE, 0 },
|
||||
{ "CASE", 0, TK_CASE, 0 },
|
||||
{ "CHECK", 0, TK_CHECK, 0 },
|
||||
{ "CLUSTER", 0, TK_CLUSTER, 0 },
|
||||
{ "COLLATE", 0, TK_COLLATE, 0 },
|
||||
{ "COMMIT", 0, TK_COMMIT, 0 },
|
||||
{ "CONFLICT", 0, TK_CONFLICT, 0 },
|
||||
{ "CONSTRAINT", 0, TK_CONSTRAINT, 0 },
|
||||
{ "COPY", 0, TK_COPY, 0 },
|
||||
{ "CREATE", 0, TK_CREATE, 0 },
|
||||
{ "CROSS", 0, TK_JOIN_KW, 0 },
|
||||
{ "DEFAULT", 0, TK_DEFAULT, 0 },
|
||||
{ "DEFERRED", 0, TK_DEFERRED, 0 },
|
||||
{ "DEFERRABLE", 0, TK_DEFERRABLE, 0 },
|
||||
{ "DELETE", 0, TK_DELETE, 0 },
|
||||
{ "DELIMITERS", 0, TK_DELIMITERS, 0 },
|
||||
{ "DESC", 0, TK_DESC, 0 },
|
||||
{ "DISTINCT", 0, TK_DISTINCT, 0 },
|
||||
{ "DROP", 0, TK_DROP, 0 },
|
||||
{ "END", 0, TK_END, 0 },
|
||||
{ "EACH", 0, TK_EACH, 0 },
|
||||
{ "ELSE", 0, TK_ELSE, 0 },
|
||||
{ "EXCEPT", 0, TK_EXCEPT, 0 },
|
||||
{ "EXPLAIN", 0, TK_EXPLAIN, 0 },
|
||||
{ "FAIL", 0, TK_FAIL, 0 },
|
||||
{ "FOR", 0, TK_FOR, 0 },
|
||||
{ "FOREIGN", 0, TK_FOREIGN, 0 },
|
||||
{ "FROM", 0, TK_FROM, 0 },
|
||||
{ "FULL", 0, TK_JOIN_KW, 0 },
|
||||
{ "GLOB", 0, TK_GLOB, 0 },
|
||||
{ "GROUP", 0, TK_GROUP, 0 },
|
||||
{ "HAVING", 0, TK_HAVING, 0 },
|
||||
{ "IGNORE", 0, TK_IGNORE, 0 },
|
||||
{ "IMMEDIATE", 0, TK_IMMEDIATE, 0 },
|
||||
{ "IN", 0, TK_IN, 0 },
|
||||
{ "INDEX", 0, TK_INDEX, 0 },
|
||||
{ "INITIALLY", 0, TK_INITIALLY, 0 },
|
||||
{ "INNER", 0, TK_JOIN_KW, 0 },
|
||||
{ "INSERT", 0, TK_INSERT, 0 },
|
||||
{ "INSTEAD", 0, TK_INSTEAD, 0 },
|
||||
{ "INTERSECT", 0, TK_INTERSECT, 0 },
|
||||
{ "INTO", 0, TK_INTO, 0 },
|
||||
{ "IS", 0, TK_IS, 0 },
|
||||
{ "ISNULL", 0, TK_ISNULL, 0 },
|
||||
{ "JOIN", 0, TK_JOIN, 0 },
|
||||
{ "KEY", 0, TK_KEY, 0 },
|
||||
{ "LEFT", 0, TK_JOIN_KW, 0 },
|
||||
{ "LIKE", 0, TK_LIKE, 0 },
|
||||
{ "LIMIT", 0, TK_LIMIT, 0 },
|
||||
{ "MATCH", 0, TK_MATCH, 0 },
|
||||
{ "NATURAL", 0, TK_JOIN_KW, 0 },
|
||||
{ "NOT", 0, TK_NOT, 0 },
|
||||
{ "NOTNULL", 0, TK_NOTNULL, 0 },
|
||||
{ "NULL", 0, TK_NULL, 0 },
|
||||
{ "OF", 0, TK_OF, 0 },
|
||||
{ "OFFSET", 0, TK_OFFSET, 0 },
|
||||
{ "ON", 0, TK_ON, 0 },
|
||||
{ "OR", 0, TK_OR, 0 },
|
||||
{ "ORDER", 0, TK_ORDER, 0 },
|
||||
{ "OUTER", 0, TK_JOIN_KW, 0 },
|
||||
{ "PRAGMA", 0, TK_PRAGMA, 0 },
|
||||
{ "PRIMARY", 0, TK_PRIMARY, 0 },
|
||||
{ "RAISE", 0, TK_RAISE, 0 },
|
||||
{ "REFERENCES", 0, TK_REFERENCES, 0 },
|
||||
{ "REPLACE", 0, TK_REPLACE, 0 },
|
||||
{ "RESTRICT", 0, TK_RESTRICT, 0 },
|
||||
{ "RIGHT", 0, TK_JOIN_KW, 0 },
|
||||
{ "ROLLBACK", 0, TK_ROLLBACK, 0 },
|
||||
{ "ROW", 0, TK_ROW, 0 },
|
||||
{ "SELECT", 0, TK_SELECT, 0 },
|
||||
{ "SET", 0, TK_SET, 0 },
|
||||
{ "STATEMENT", 0, TK_STATEMENT, 0 },
|
||||
{ "TABLE", 0, TK_TABLE, 0 },
|
||||
{ "TEMP", 0, TK_TEMP, 0 },
|
||||
{ "TEMPORARY", 0, TK_TEMP, 0 },
|
||||
{ "THEN", 0, TK_THEN, 0 },
|
||||
{ "TRANSACTION", 0, TK_TRANSACTION, 0 },
|
||||
{ "TRIGGER", 0, TK_TRIGGER, 0 },
|
||||
{ "UNION", 0, TK_UNION, 0 },
|
||||
{ "UNIQUE", 0, TK_UNIQUE, 0 },
|
||||
{ "UPDATE", 0, TK_UPDATE, 0 },
|
||||
{ "USING", 0, TK_USING, 0 },
|
||||
{ "VACUUM", 0, TK_VACUUM, 0 },
|
||||
{ "VALUES", 0, TK_VALUES, 0 },
|
||||
{ "VIEW", 0, TK_VIEW, 0 },
|
||||
{ "WHEN", 0, TK_WHEN, 0 },
|
||||
{ "WHERE", 0, TK_WHERE, 0 },
|
||||
};
|
||||
|
||||
/*
|
||||
** This is the hash table
|
||||
*/
|
||||
#define KEY_HASH_SIZE 71
|
||||
static Keyword *apHashTable[KEY_HASH_SIZE];
|
||||
|
||||
|
||||
/*
|
||||
** This function looks up an identifier to determine if it is a
|
||||
** keyword. If it is a keyword, the token code of that keyword is
|
||||
** returned. If the input is not a keyword, TK_ID is returned.
|
||||
*/
|
||||
int sqliteKeywordCode(const char *z, int n){
|
||||
int h;
|
||||
Keyword *p;
|
||||
if( aKeywordTable[0].len==0 ){
|
||||
/* Initialize the keyword hash table */
|
||||
sqliteOsEnterMutex();
|
||||
if( aKeywordTable[0].len==0 ){
|
||||
int i;
|
||||
int n;
|
||||
n = sizeof(aKeywordTable)/sizeof(aKeywordTable[0]);
|
||||
for(i=0; i<n; i++){
|
||||
aKeywordTable[i].len = strlen(aKeywordTable[i].zName);
|
||||
h = sqliteHashNoCase(aKeywordTable[i].zName, aKeywordTable[i].len);
|
||||
h %= KEY_HASH_SIZE;
|
||||
aKeywordTable[i].pNext = apHashTable[h];
|
||||
apHashTable[h] = &aKeywordTable[i];
|
||||
}
|
||||
}
|
||||
sqliteOsLeaveMutex();
|
||||
}
|
||||
h = sqliteHashNoCase(z, n) % KEY_HASH_SIZE;
|
||||
for(p=apHashTable[h]; p; p=p->pNext){
|
||||
if( p->len==n && sqliteStrNICmp(p->zName, z, n)==0 ){
|
||||
return p->tokenType;
|
||||
}
|
||||
}
|
||||
return TK_ID;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** If X is a character that can be used in an identifier then
|
||||
** isIdChar[X] will be 1. Otherwise isIdChar[X] will be 0.
|
||||
**
|
||||
** In this implementation, an identifier can be a string of
|
||||
** alphabetic characters, digits, and "_" plus any character
|
||||
** with the high-order bit set. The latter rule means that
|
||||
** any sequence of UTF-8 characters or characters taken from
|
||||
** an extended ISO8859 character set can form an identifier.
|
||||
*/
|
||||
static const char isIdChar[] = {
|
||||
/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
|
||||
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
|
||||
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 8x */
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 9x */
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* Ax */
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* Bx */
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* Cx */
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* Dx */
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* Ex */
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* Fx */
|
||||
};
|
||||
|
||||
|
||||
/*
|
||||
** Return the length of the token that begins at z[0]. Return
|
||||
** -1 if the token is (or might be) incomplete. Store the token
|
||||
** type in *tokenType before returning.
|
||||
*/
|
||||
static int sqliteGetToken(const unsigned char *z, int *tokenType){
|
||||
int i;
|
||||
switch( *z ){
|
||||
case ' ': case '\t': case '\n': case '\f': case '\r': {
|
||||
for(i=1; isspace(z[i]); i++){}
|
||||
*tokenType = TK_SPACE;
|
||||
return i;
|
||||
}
|
||||
case '-': {
|
||||
if( z[1]==0 ) return -1;
|
||||
if( z[1]=='-' ){
|
||||
for(i=2; z[i] && z[i]!='\n'; i++){}
|
||||
*tokenType = TK_COMMENT;
|
||||
return i;
|
||||
}
|
||||
*tokenType = TK_MINUS;
|
||||
return 1;
|
||||
}
|
||||
case '(': {
|
||||
if( z[1]=='+' && z[2]==')' ){
|
||||
*tokenType = TK_ORACLE_OUTER_JOIN;
|
||||
return 3;
|
||||
}else{
|
||||
*tokenType = TK_LP;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
case ')': {
|
||||
*tokenType = TK_RP;
|
||||
return 1;
|
||||
}
|
||||
case ';': {
|
||||
*tokenType = TK_SEMI;
|
||||
return 1;
|
||||
}
|
||||
case '+': {
|
||||
*tokenType = TK_PLUS;
|
||||
return 1;
|
||||
}
|
||||
case '*': {
|
||||
*tokenType = TK_STAR;
|
||||
return 1;
|
||||
}
|
||||
case '/': {
|
||||
if( z[1]!='*' || z[2]==0 ){
|
||||
*tokenType = TK_SLASH;
|
||||
return 1;
|
||||
}
|
||||
for(i=3; z[i] && (z[i]!='/' || z[i-1]!='*'); i++){}
|
||||
if( z[i] ) i++;
|
||||
*tokenType = TK_COMMENT;
|
||||
return i;
|
||||
}
|
||||
case '%': {
|
||||
*tokenType = TK_REM;
|
||||
return 1;
|
||||
}
|
||||
case '=': {
|
||||
*tokenType = TK_EQ;
|
||||
return 1 + (z[1]=='=');
|
||||
}
|
||||
case '<': {
|
||||
if( z[1]=='=' ){
|
||||
*tokenType = TK_LE;
|
||||
return 2;
|
||||
}else if( z[1]=='>' ){
|
||||
*tokenType = TK_NE;
|
||||
return 2;
|
||||
}else if( z[1]=='<' ){
|
||||
*tokenType = TK_LSHIFT;
|
||||
return 2;
|
||||
}else{
|
||||
*tokenType = TK_LT;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
case '>': {
|
||||
if( z[1]=='=' ){
|
||||
*tokenType = TK_GE;
|
||||
return 2;
|
||||
}else if( z[1]=='>' ){
|
||||
*tokenType = TK_RSHIFT;
|
||||
return 2;
|
||||
}else{
|
||||
*tokenType = TK_GT;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
case '!': {
|
||||
if( z[1]!='=' ){
|
||||
*tokenType = TK_ILLEGAL;
|
||||
return 2;
|
||||
}else{
|
||||
*tokenType = TK_NE;
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
case '|': {
|
||||
if( z[1]!='|' ){
|
||||
*tokenType = TK_BITOR;
|
||||
return 1;
|
||||
}else{
|
||||
*tokenType = TK_CONCAT;
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
case ',': {
|
||||
*tokenType = TK_COMMA;
|
||||
return 1;
|
||||
}
|
||||
case '&': {
|
||||
*tokenType = TK_BITAND;
|
||||
return 1;
|
||||
}
|
||||
case '~': {
|
||||
*tokenType = TK_BITNOT;
|
||||
return 1;
|
||||
}
|
||||
case '\'': case '"': {
|
||||
int delim = z[0];
|
||||
for(i=1; z[i]; i++){
|
||||
if( z[i]==delim ){
|
||||
if( z[i+1]==delim ){
|
||||
i++;
|
||||
}else{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if( z[i] ) i++;
|
||||
*tokenType = TK_STRING;
|
||||
return i;
|
||||
}
|
||||
case '.': {
|
||||
if( !isdigit(z[1]) ){
|
||||
*tokenType = TK_DOT;
|
||||
return 1;
|
||||
}
|
||||
/* Fall thru into the next case */
|
||||
}
|
||||
case '0': case '1': case '2': case '3': case '4':
|
||||
case '5': case '6': case '7': case '8': case '9': {
|
||||
*tokenType = TK_INTEGER;
|
||||
for(i=1; isdigit(z[i]); i++){}
|
||||
if( z[i]=='.' ){
|
||||
i++;
|
||||
while( isdigit(z[i]) ){ i++; }
|
||||
*tokenType = TK_FLOAT;
|
||||
}
|
||||
if( (z[i]=='e' || z[i]=='E') &&
|
||||
( isdigit(z[i+1])
|
||||
|| ((z[i+1]=='+' || z[i+1]=='-') && isdigit(z[i+2]))
|
||||
)
|
||||
){
|
||||
i += 2;
|
||||
while( isdigit(z[i]) ){ i++; }
|
||||
*tokenType = TK_FLOAT;
|
||||
}else if( z[0]=='.' ){
|
||||
*tokenType = TK_FLOAT;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
case '[': {
|
||||
for(i=1; z[i] && z[i-1]!=']'; i++){}
|
||||
*tokenType = TK_ID;
|
||||
return i;
|
||||
}
|
||||
default: {
|
||||
if( !isIdChar[*z] ){
|
||||
break;
|
||||
}
|
||||
for(i=1; isIdChar[z[i]]; i++){}
|
||||
*tokenType = sqliteKeywordCode((char*)z, i);
|
||||
return i;
|
||||
}
|
||||
}
|
||||
*tokenType = TK_ILLEGAL;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
** Run the parser on the given SQL string. The parser structure is
|
||||
** passed in. An SQLITE_ status code is returned. If an error occurs
|
||||
** and pzErrMsg!=NULL then an error message might be written into
|
||||
** memory obtained from malloc() and *pzErrMsg made to point to that
|
||||
** error message. Or maybe not.
|
||||
*/
|
||||
int sqliteRunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
|
||||
int nErr = 0;
|
||||
int i;
|
||||
void *pEngine;
|
||||
int tokenType;
|
||||
int lastTokenParsed = -1;
|
||||
sqlite *db = pParse->db;
|
||||
extern void *sqliteParserAlloc(void*(*)(int));
|
||||
extern void sqliteParserFree(void*, void(*)(void*));
|
||||
extern int sqliteParser(void*, int, Token, Parse*);
|
||||
|
||||
db->flags &= ~SQLITE_Interrupt;
|
||||
pParse->rc = SQLITE_OK;
|
||||
i = 0;
|
||||
pEngine = sqliteParserAlloc((void*(*)(int))malloc);
|
||||
if( pEngine==0 ){
|
||||
sqliteSetString(pzErrMsg, "out of memory", 0);
|
||||
return 1;
|
||||
}
|
||||
pParse->sLastToken.dyn = 0;
|
||||
pParse->zTail = zSql;
|
||||
while( sqlite_malloc_failed==0 && zSql[i]!=0 ){
|
||||
|
||||
assert( i>=0 );
|
||||
pParse->sLastToken.z = &zSql[i];
|
||||
assert( pParse->sLastToken.dyn==0 );
|
||||
pParse->sLastToken.n = sqliteGetToken((unsigned char*)&zSql[i], &tokenType);
|
||||
i += pParse->sLastToken.n;
|
||||
switch( tokenType ){
|
||||
case TK_SPACE:
|
||||
case TK_COMMENT: {
|
||||
if( (db->flags & SQLITE_Interrupt)!=0 ){
|
||||
pParse->rc = SQLITE_INTERRUPT;
|
||||
sqliteSetString(pzErrMsg, "interrupt", 0);
|
||||
goto abort_parse;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case TK_ILLEGAL: {
|
||||
sqliteSetNString(pzErrMsg, "unrecognized token: \"", -1,
|
||||
pParse->sLastToken.z, pParse->sLastToken.n, "\"", 1, 0);
|
||||
nErr++;
|
||||
goto abort_parse;
|
||||
}
|
||||
case TK_SEMI: {
|
||||
pParse->zTail = &zSql[i];
|
||||
/* Fall thru into the default case */
|
||||
}
|
||||
default: {
|
||||
sqliteParser(pEngine, tokenType, pParse->sLastToken, pParse);
|
||||
lastTokenParsed = tokenType;
|
||||
if( pParse->rc!=SQLITE_OK ){
|
||||
goto abort_parse;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
abort_parse:
|
||||
if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
|
||||
if( lastTokenParsed!=TK_SEMI ){
|
||||
sqliteParser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
|
||||
pParse->zTail = &zSql[i];
|
||||
}
|
||||
sqliteParser(pEngine, 0, pParse->sLastToken, pParse);
|
||||
}
|
||||
sqliteParserFree(pEngine, free);
|
||||
if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
|
||||
sqliteSetString(&pParse->zErrMsg, sqlite_error_string(pParse->rc), 0);
|
||||
}
|
||||
if( pParse->zErrMsg ){
|
||||
if( pzErrMsg && *pzErrMsg==0 ){
|
||||
*pzErrMsg = pParse->zErrMsg;
|
||||
}else{
|
||||
sqliteFree(pParse->zErrMsg);
|
||||
}
|
||||
pParse->zErrMsg = 0;
|
||||
if( !nErr ) nErr++;
|
||||
}
|
||||
if( pParse->pVdbe && (pParse->useCallback || pParse->nErr>0) ){
|
||||
sqliteVdbeDelete(pParse->pVdbe);
|
||||
pParse->pVdbe = 0;
|
||||
}
|
||||
if( pParse->pNewTable ){
|
||||
sqliteDeleteTable(pParse->db, pParse->pNewTable);
|
||||
pParse->pNewTable = 0;
|
||||
}
|
||||
if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
|
||||
pParse->rc = SQLITE_ERROR;
|
||||
}
|
||||
return nErr;
|
||||
}
|
||||
@@ -1,793 +0,0 @@
|
||||
/*
|
||||
**
|
||||
** 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.
|
||||
**
|
||||
*************************************************************************
|
||||
*
|
||||
*/
|
||||
#include "sqliteInt.h"
|
||||
|
||||
/*
|
||||
** Delete a linked list of TriggerStep structures.
|
||||
*/
|
||||
static void sqliteDeleteTriggerStep(TriggerStep *pTriggerStep){
|
||||
while( pTriggerStep ){
|
||||
TriggerStep * pTmp = pTriggerStep;
|
||||
pTriggerStep = pTriggerStep->pNext;
|
||||
|
||||
if( pTmp->target.dyn ) sqliteFree((char*)pTmp->target.z);
|
||||
sqliteExprDelete(pTmp->pWhere);
|
||||
sqliteExprListDelete(pTmp->pExprList);
|
||||
sqliteSelectDelete(pTmp->pSelect);
|
||||
sqliteIdListDelete(pTmp->pIdList);
|
||||
|
||||
sqliteFree(pTmp);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
** This is called by the parser when it sees a CREATE TRIGGER statement. See
|
||||
** comments surrounding struct Trigger in sqliteInt.h for a description of
|
||||
** how triggers are stored.
|
||||
*/
|
||||
void sqliteCreateTrigger(
|
||||
Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
|
||||
Token *pName, /* The name of the trigger */
|
||||
int tr_tm, /* One of TK_BEFORE, TK_AFTER , TK_INSTEAD */
|
||||
int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
|
||||
IdList *pColumns, /* column list if this is an UPDATE OF trigger */
|
||||
Token *pTableName, /* The name of the table/view the trigger applies to */
|
||||
int foreach, /* One of TK_ROW or TK_STATEMENT */
|
||||
Expr *pWhen, /* WHEN clause */
|
||||
TriggerStep *pStepList, /* The triggered program */
|
||||
Token *pAll /* Token that describes the complete CREATE TRIGGER */
|
||||
){
|
||||
Trigger *nt;
|
||||
Table *tab;
|
||||
char *zName = 0; /* Name of the trigger */
|
||||
|
||||
/* Check that:
|
||||
** 1. the trigger name does not already exist.
|
||||
** 2. the table (or view) does exist.
|
||||
** 3. that we are not trying to create a trigger on the sqlite_master table
|
||||
** 4. That we are not trying to create an INSTEAD OF trigger on a table.
|
||||
** 5. That we are not trying to create a BEFORE or AFTER trigger on a view.
|
||||
*/
|
||||
zName = sqliteStrNDup(pName->z, pName->n);
|
||||
if( sqliteHashFind(&(pParse->db->trigHash), zName, pName->n + 1) ){
|
||||
sqliteSetNString(&pParse->zErrMsg, "trigger ", -1,
|
||||
pName->z, pName->n, " already exists", -1, 0);
|
||||
pParse->nErr++;
|
||||
goto trigger_cleanup;
|
||||
}
|
||||
{
|
||||
char *tmp_str = sqliteStrNDup(pTableName->z, pTableName->n);
|
||||
if( tmp_str==0 ) goto trigger_cleanup;
|
||||
tab = sqliteFindTable(pParse->db, tmp_str);
|
||||
sqliteFree(tmp_str);
|
||||
if( !tab ){
|
||||
sqliteSetNString(&pParse->zErrMsg, "no such table: ", -1,
|
||||
pTableName->z, pTableName->n, 0);
|
||||
pParse->nErr++;
|
||||
goto trigger_cleanup;
|
||||
}
|
||||
if( sqliteStrICmp(tab->zName, MASTER_NAME)==0 ){
|
||||
sqliteSetString(&pParse->zErrMsg, "cannot create trigger on system "
|
||||
"table: " MASTER_NAME, 0);
|
||||
pParse->nErr++;
|
||||
goto trigger_cleanup;
|
||||
}
|
||||
if( sqliteStrICmp(tab->zName, TEMP_MASTER_NAME)==0 ){
|
||||
sqliteSetString(&pParse->zErrMsg, "cannot create trigger on system "
|
||||
"table: " TEMP_MASTER_NAME, 0);
|
||||
pParse->nErr++;
|
||||
goto trigger_cleanup;
|
||||
}
|
||||
if( tab->pSelect && tr_tm != TK_INSTEAD ){
|
||||
sqliteSetNString(&pParse->zErrMsg, "cannot create ", -1,
|
||||
(tr_tm == TK_BEFORE)?"BEFORE":"AFTER", -1, " trigger on view: ", -1
|
||||
, pTableName->z, pTableName->n, 0);
|
||||
goto trigger_cleanup;
|
||||
}
|
||||
if( !tab->pSelect && tr_tm == TK_INSTEAD ){
|
||||
sqliteSetNString(&pParse->zErrMsg, "cannot create INSTEAD OF", -1,
|
||||
" trigger on table: ", -1, pTableName->z, pTableName->n, 0);
|
||||
goto trigger_cleanup;
|
||||
}
|
||||
#ifndef SQLITE_OMIT_AUTHORIZATION
|
||||
{
|
||||
int code = SQLITE_CREATE_TRIGGER;
|
||||
if( tab->isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
|
||||
if( sqliteAuthCheck(pParse, code, zName, tab->zName) ){
|
||||
goto trigger_cleanup;
|
||||
}
|
||||
if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(tab->isTemp), 0)){
|
||||
goto trigger_cleanup;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
if (tr_tm == TK_INSTEAD){
|
||||
tr_tm = TK_BEFORE;
|
||||
}
|
||||
|
||||
/* Build the Trigger object */
|
||||
nt = (Trigger*)sqliteMalloc(sizeof(Trigger));
|
||||
if( nt==0 ) goto trigger_cleanup;
|
||||
nt->name = zName;
|
||||
zName = 0;
|
||||
nt->table = sqliteStrNDup(pTableName->z, pTableName->n);
|
||||
if( sqlite_malloc_failed ) goto trigger_cleanup;
|
||||
nt->op = op;
|
||||
nt->tr_tm = tr_tm;
|
||||
nt->pWhen = sqliteExprDup(pWhen);
|
||||
sqliteExprDelete(pWhen);
|
||||
nt->pColumns = sqliteIdListDup(pColumns);
|
||||
sqliteIdListDelete(pColumns);
|
||||
nt->foreach = foreach;
|
||||
nt->step_list = pStepList;
|
||||
|
||||
/* if we are not initializing, and this trigger is not on a TEMP table,
|
||||
** build the sqlite_master entry
|
||||
*/
|
||||
if( !pParse->initFlag ){
|
||||
static VdbeOp insertTrig[] = {
|
||||
{ OP_NewRecno, 0, 0, 0 },
|
||||
{ OP_String, 0, 0, "trigger" },
|
||||
{ OP_String, 0, 0, 0 }, /* 2: trigger name */
|
||||
{ OP_String, 0, 0, 0 }, /* 3: table name */
|
||||
{ OP_Integer, 0, 0, 0 },
|
||||
{ OP_String, 0, 0, 0 }, /* 5: SQL */
|
||||
{ OP_MakeRecord, 5, 0, 0 },
|
||||
{ OP_PutIntKey, 0, 0, 0 },
|
||||
};
|
||||
int addr;
|
||||
Vdbe *v;
|
||||
|
||||
/* Make an entry in the sqlite_master table */
|
||||
v = sqliteGetVdbe(pParse);
|
||||
if( v==0 ) goto trigger_cleanup;
|
||||
sqliteBeginWriteOperation(pParse, 0, 0);
|
||||
sqliteOpenMasterTable(v, tab->isTemp);
|
||||
addr = sqliteVdbeAddOpList(v, ArraySize(insertTrig), insertTrig);
|
||||
sqliteVdbeChangeP3(v, addr, tab->isTemp ? TEMP_MASTER_NAME : MASTER_NAME,
|
||||
P3_STATIC);
|
||||
sqliteVdbeChangeP3(v, addr+2, nt->name, 0);
|
||||
sqliteVdbeChangeP3(v, addr+3, nt->table, 0);
|
||||
sqliteVdbeChangeP3(v, addr+5, pAll->z, pAll->n);
|
||||
if( !tab->isTemp ){
|
||||
sqliteChangeCookie(pParse->db, v);
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_Close, 0, 0);
|
||||
sqliteEndWriteOperation(pParse);
|
||||
}
|
||||
|
||||
if( !pParse->explain ){
|
||||
/* Stick it in the hash-table */
|
||||
sqliteHashInsert(&(pParse->db->trigHash), nt->name, pName->n + 1, nt);
|
||||
|
||||
/* Attach it to the table object */
|
||||
nt->pNext = tab->pTrigger;
|
||||
tab->pTrigger = nt;
|
||||
return;
|
||||
}else{
|
||||
sqliteFree(nt->name);
|
||||
sqliteFree(nt->table);
|
||||
sqliteFree(nt);
|
||||
}
|
||||
|
||||
trigger_cleanup:
|
||||
|
||||
sqliteFree(zName);
|
||||
sqliteIdListDelete(pColumns);
|
||||
sqliteExprDelete(pWhen);
|
||||
sqliteDeleteTriggerStep(pStepList);
|
||||
}
|
||||
|
||||
/*
|
||||
** Make a copy of all components of the given trigger step. This has
|
||||
** the effect of copying all Expr.token.z values into memory obtained
|
||||
** from sqliteMalloc(). As initially created, the Expr.token.z values
|
||||
** all point to the input string that was fed to the parser. But that
|
||||
** string is ephemeral - it will go away as soon as the sqlite_exec()
|
||||
** call that started the parser exits. This routine makes a persistent
|
||||
** copy of all the Expr.token.z strings so that the TriggerStep structure
|
||||
** will be valid even after the sqlite_exec() call returns.
|
||||
*/
|
||||
static void sqlitePersistTriggerStep(TriggerStep *p){
|
||||
if( p->target.z ){
|
||||
p->target.z = sqliteStrNDup(p->target.z, p->target.n);
|
||||
p->target.dyn = 1;
|
||||
}
|
||||
if( p->pSelect ){
|
||||
Select *pNew = sqliteSelectDup(p->pSelect);
|
||||
sqliteSelectDelete(p->pSelect);
|
||||
p->pSelect = pNew;
|
||||
}
|
||||
if( p->pWhere ){
|
||||
Expr *pNew = sqliteExprDup(p->pWhere);
|
||||
sqliteExprDelete(p->pWhere);
|
||||
p->pWhere = pNew;
|
||||
}
|
||||
if( p->pExprList ){
|
||||
ExprList *pNew = sqliteExprListDup(p->pExprList);
|
||||
sqliteExprListDelete(p->pExprList);
|
||||
p->pExprList = pNew;
|
||||
}
|
||||
if( p->pIdList ){
|
||||
IdList *pNew = sqliteIdListDup(p->pIdList);
|
||||
sqliteIdListDelete(p->pIdList);
|
||||
p->pIdList = pNew;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
** Turn a SELECT statement (that the pSelect parameter points to) into
|
||||
** a trigger step. Return a pointer to a TriggerStep structure.
|
||||
**
|
||||
** The parser calls this routine when it finds a SELECT statement in
|
||||
** body of a TRIGGER.
|
||||
*/
|
||||
TriggerStep *sqliteTriggerSelectStep(Select *pSelect){
|
||||
TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
|
||||
if( pTriggerStep==0 ) return 0;
|
||||
|
||||
pTriggerStep->op = TK_SELECT;
|
||||
pTriggerStep->pSelect = pSelect;
|
||||
pTriggerStep->orconf = OE_Default;
|
||||
sqlitePersistTriggerStep(pTriggerStep);
|
||||
|
||||
return pTriggerStep;
|
||||
}
|
||||
|
||||
/*
|
||||
** Build a trigger step out of an INSERT statement. Return a pointer
|
||||
** to the new trigger step.
|
||||
**
|
||||
** The parser calls this routine when it sees an INSERT inside the
|
||||
** body of a trigger.
|
||||
*/
|
||||
TriggerStep *sqliteTriggerInsertStep(
|
||||
Token *pTableName, /* Name of the table into which we insert */
|
||||
IdList *pColumn, /* List of columns in pTableName to insert into */
|
||||
ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
|
||||
Select *pSelect, /* A SELECT statement that supplies values */
|
||||
int orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
|
||||
){
|
||||
TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
|
||||
if( pTriggerStep==0 ) return 0;
|
||||
|
||||
assert(pEList == 0 || pSelect == 0);
|
||||
assert(pEList != 0 || pSelect != 0);
|
||||
|
||||
pTriggerStep->op = TK_INSERT;
|
||||
pTriggerStep->pSelect = pSelect;
|
||||
pTriggerStep->target = *pTableName;
|
||||
pTriggerStep->pIdList = pColumn;
|
||||
pTriggerStep->pExprList = pEList;
|
||||
pTriggerStep->orconf = orconf;
|
||||
sqlitePersistTriggerStep(pTriggerStep);
|
||||
|
||||
return pTriggerStep;
|
||||
}
|
||||
|
||||
/*
|
||||
** Construct a trigger step that implements an UPDATE statement and return
|
||||
** a pointer to that trigger step. The parser calls this routine when it
|
||||
** sees an UPDATE statement inside the body of a CREATE TRIGGER.
|
||||
*/
|
||||
TriggerStep *sqliteTriggerUpdateStep(
|
||||
Token *pTableName, /* Name of the table to be updated */
|
||||
ExprList *pEList, /* The SET clause: list of column and new values */
|
||||
Expr *pWhere, /* The WHERE clause */
|
||||
int orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
|
||||
){
|
||||
TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
|
||||
if( pTriggerStep==0 ) return 0;
|
||||
|
||||
pTriggerStep->op = TK_UPDATE;
|
||||
pTriggerStep->target = *pTableName;
|
||||
pTriggerStep->pExprList = pEList;
|
||||
pTriggerStep->pWhere = pWhere;
|
||||
pTriggerStep->orconf = orconf;
|
||||
sqlitePersistTriggerStep(pTriggerStep);
|
||||
|
||||
return pTriggerStep;
|
||||
}
|
||||
|
||||
/*
|
||||
** Construct a trigger step that implements a DELETE statement and return
|
||||
** a pointer to that trigger step. The parser calls this routine when it
|
||||
** sees a DELETE statement inside the body of a CREATE TRIGGER.
|
||||
*/
|
||||
TriggerStep *sqliteTriggerDeleteStep(Token *pTableName, Expr *pWhere){
|
||||
TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
|
||||
if( pTriggerStep==0 ) return 0;
|
||||
|
||||
pTriggerStep->op = TK_DELETE;
|
||||
pTriggerStep->target = *pTableName;
|
||||
pTriggerStep->pWhere = pWhere;
|
||||
pTriggerStep->orconf = OE_Default;
|
||||
sqlitePersistTriggerStep(pTriggerStep);
|
||||
|
||||
return pTriggerStep;
|
||||
}
|
||||
|
||||
/*
|
||||
** Recursively delete a Trigger structure
|
||||
*/
|
||||
void sqliteDeleteTrigger(Trigger *pTrigger){
|
||||
sqliteDeleteTriggerStep(pTrigger->step_list);
|
||||
sqliteFree(pTrigger->name);
|
||||
sqliteFree(pTrigger->table);
|
||||
sqliteExprDelete(pTrigger->pWhen);
|
||||
sqliteIdListDelete(pTrigger->pColumns);
|
||||
sqliteFree(pTrigger);
|
||||
}
|
||||
|
||||
/*
|
||||
* This function is called to drop a trigger from the database schema.
|
||||
*
|
||||
* This may be called directly from the parser, or from within
|
||||
* sqliteDropTable(). In the latter case the "nested" argument is true.
|
||||
*
|
||||
* Note that this function does not delete the trigger entirely. Instead it
|
||||
* removes it from the internal schema and places it in the trigDrop hash
|
||||
* table. This is so that the trigger can be restored into the database schema
|
||||
* if the transaction is rolled back.
|
||||
*/
|
||||
void sqliteDropTrigger(Parse *pParse, Token *pName, int nested){
|
||||
char *zName;
|
||||
Trigger *pTrigger;
|
||||
Table *pTable;
|
||||
Vdbe *v;
|
||||
|
||||
zName = sqliteStrNDup(pName->z, pName->n);
|
||||
|
||||
/* ensure that the trigger being dropped exists */
|
||||
pTrigger = sqliteHashFind(&(pParse->db->trigHash), zName, pName->n + 1);
|
||||
if( !pTrigger ){
|
||||
sqliteSetNString(&pParse->zErrMsg, "no such trigger: ", -1,
|
||||
zName, -1, 0);
|
||||
sqliteFree(zName);
|
||||
return;
|
||||
}
|
||||
pTable = sqliteFindTable(pParse->db, pTrigger->table);
|
||||
assert(pTable);
|
||||
#ifndef SQLITE_OMIT_AUTHORIZATION
|
||||
{
|
||||
int code = SQLITE_DROP_TRIGGER;
|
||||
if( pTable->isTemp ) code = SQLITE_DROP_TEMP_TRIGGER;
|
||||
if( sqliteAuthCheck(pParse, code, pTrigger->name, pTable->zName) ||
|
||||
sqliteAuthCheck(pParse, SQLITE_DELETE, SCHEMA_TABLE(pTable->isTemp),0) ){
|
||||
sqliteFree(zName);
|
||||
return;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/*
|
||||
* If this is not an "explain", then delete the trigger structure.
|
||||
*/
|
||||
if( !pParse->explain ){
|
||||
if( pTable->pTrigger == pTrigger ){
|
||||
pTable->pTrigger = pTrigger->pNext;
|
||||
}else{
|
||||
Trigger *cc = pTable->pTrigger;
|
||||
while( cc ){
|
||||
if( cc->pNext == pTrigger ){
|
||||
cc->pNext = cc->pNext->pNext;
|
||||
break;
|
||||
}
|
||||
cc = cc->pNext;
|
||||
}
|
||||
assert(cc);
|
||||
}
|
||||
sqliteHashInsert(&(pParse->db->trigHash), zName, pName->n + 1, NULL);
|
||||
sqliteDeleteTrigger(pTrigger);
|
||||
}
|
||||
|
||||
/* Generate code to destroy the database record of the trigger.
|
||||
*/
|
||||
if( pTable!=0 && !nested && (v = sqliteGetVdbe(pParse))!=0 ){
|
||||
int base;
|
||||
static VdbeOp dropTrigger[] = {
|
||||
{ OP_Rewind, 0, ADDR(8), 0},
|
||||
{ OP_String, 0, 0, 0}, /* 1 */
|
||||
{ OP_MemStore, 1, 1, 0},
|
||||
{ OP_MemLoad, 1, 0, 0}, /* 3 */
|
||||
{ OP_Column, 0, 1, 0},
|
||||
{ OP_Ne, 0, ADDR(7), 0},
|
||||
{ OP_Delete, 0, 0, 0},
|
||||
{ OP_Next, 0, ADDR(3), 0}, /* 7 */
|
||||
};
|
||||
|
||||
sqliteBeginWriteOperation(pParse, 0, 0);
|
||||
sqliteOpenMasterTable(v, pTable->isTemp);
|
||||
base = sqliteVdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
|
||||
sqliteVdbeChangeP3(v, base+1, zName, 0);
|
||||
if( !pTable->isTemp ){
|
||||
sqliteChangeCookie(pParse->db, v);
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_Close, 0, 0);
|
||||
sqliteEndWriteOperation(pParse);
|
||||
}
|
||||
|
||||
sqliteFree(zName);
|
||||
}
|
||||
|
||||
/*
|
||||
** pEList is the SET clause of an UPDATE statement. Each entry
|
||||
** in pEList is of the format <id>=<expr>. If any of the entries
|
||||
** in pEList have an <id> which matches an identifier in pIdList,
|
||||
** then return TRUE. If pIdList==NULL, then it is considered a
|
||||
** wildcard that matches anything. Likewise if pEList==NULL then
|
||||
** it matches anything so always return true. Return false only
|
||||
** if there is no match.
|
||||
*/
|
||||
static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
|
||||
int e;
|
||||
if( !pIdList || !pEList ) return 1;
|
||||
for(e=0; e<pEList->nExpr; e++){
|
||||
if( sqliteIdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* A global variable that is TRUE if we should always set up temp tables for
|
||||
* for triggers, even if there are no triggers to code. This is used to test
|
||||
* how much overhead the triggers algorithm is causing.
|
||||
*
|
||||
* This flag can be set or cleared using the "trigger_overhead_test" pragma.
|
||||
* The pragma is not documented since it is not really part of the interface
|
||||
* to SQLite, just the test procedure.
|
||||
*/
|
||||
int always_code_trigger_setup = 0;
|
||||
|
||||
/*
|
||||
* Returns true if a trigger matching op, tr_tm and foreach that is NOT already
|
||||
* on the Parse objects trigger-stack (to prevent recursive trigger firing) is
|
||||
* found in the list specified as pTrigger.
|
||||
*/
|
||||
int sqliteTriggersExist(
|
||||
Parse *pParse, /* Used to check for recursive triggers */
|
||||
Trigger *pTrigger, /* A list of triggers associated with a table */
|
||||
int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
|
||||
int tr_tm, /* one of TK_BEFORE, TK_AFTER */
|
||||
int foreach, /* one of TK_ROW or TK_STATEMENT */
|
||||
ExprList *pChanges /* Columns that change in an UPDATE statement */
|
||||
){
|
||||
Trigger * pTriggerCursor;
|
||||
|
||||
if( always_code_trigger_setup ){
|
||||
return 1;
|
||||
}
|
||||
|
||||
pTriggerCursor = pTrigger;
|
||||
while( pTriggerCursor ){
|
||||
if( pTriggerCursor->op == op &&
|
||||
pTriggerCursor->tr_tm == tr_tm &&
|
||||
pTriggerCursor->foreach == foreach &&
|
||||
checkColumnOverLap(pTriggerCursor->pColumns, pChanges) ){
|
||||
TriggerStack * ss;
|
||||
ss = pParse->trigStack;
|
||||
while( ss && ss->pTrigger != pTrigger ){
|
||||
ss = ss->pNext;
|
||||
}
|
||||
if( !ss )return 1;
|
||||
}
|
||||
pTriggerCursor = pTriggerCursor->pNext;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
** Generate VDBE code for zero or more statements inside the body of a
|
||||
** trigger.
|
||||
*/
|
||||
static int codeTriggerProgram(
|
||||
Parse *pParse, /* The parser context */
|
||||
TriggerStep *pStepList, /* List of statements inside the trigger body */
|
||||
int orconfin /* Conflict algorithm. (OE_Abort, etc) */
|
||||
){
|
||||
TriggerStep * pTriggerStep = pStepList;
|
||||
int orconf;
|
||||
|
||||
while( pTriggerStep ){
|
||||
int saveNTab = pParse->nTab;
|
||||
orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
|
||||
pParse->trigStack->orconf = orconf;
|
||||
switch( pTriggerStep->op ){
|
||||
case TK_SELECT: {
|
||||
Select * ss = sqliteSelectDup(pTriggerStep->pSelect);
|
||||
assert(ss);
|
||||
assert(ss->pSrc);
|
||||
sqliteSelect(pParse, ss, SRT_Discard, 0, 0, 0, 0);
|
||||
sqliteSelectDelete(ss);
|
||||
break;
|
||||
}
|
||||
case TK_UPDATE: {
|
||||
sqliteVdbeAddOp(pParse->pVdbe, OP_ListPush, 0, 0);
|
||||
sqliteUpdate(pParse, &pTriggerStep->target,
|
||||
sqliteExprListDup(pTriggerStep->pExprList),
|
||||
sqliteExprDup(pTriggerStep->pWhere), orconf);
|
||||
sqliteVdbeAddOp(pParse->pVdbe, OP_ListPop, 0, 0);
|
||||
break;
|
||||
}
|
||||
case TK_INSERT: {
|
||||
sqliteInsert(pParse, &pTriggerStep->target,
|
||||
sqliteExprListDup(pTriggerStep->pExprList),
|
||||
sqliteSelectDup(pTriggerStep->pSelect),
|
||||
sqliteIdListDup(pTriggerStep->pIdList), orconf);
|
||||
break;
|
||||
}
|
||||
case TK_DELETE: {
|
||||
sqliteVdbeAddOp(pParse->pVdbe, OP_ListPush, 0, 0);
|
||||
sqliteDeleteFrom(pParse, &pTriggerStep->target,
|
||||
sqliteExprDup(pTriggerStep->pWhere));
|
||||
sqliteVdbeAddOp(pParse->pVdbe, OP_ListPop, 0, 0);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
assert(0);
|
||||
}
|
||||
pParse->nTab = saveNTab;
|
||||
pTriggerStep = pTriggerStep->pNext;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
** This is called to code FOR EACH ROW triggers.
|
||||
**
|
||||
** When the code that this function generates is executed, the following
|
||||
** must be true:
|
||||
**
|
||||
** 1. No cursors may be open in the main database. (But newIdx and oldIdx
|
||||
** can be indices of cursors in temporary tables. See below.)
|
||||
**
|
||||
** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
|
||||
** a temporary vdbe cursor (index newIdx) must be open and pointing at
|
||||
** a row containing values to be substituted for new.* expressions in the
|
||||
** trigger program(s).
|
||||
**
|
||||
** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
|
||||
** a temporary vdbe cursor (index oldIdx) must be open and pointing at
|
||||
** a row containing values to be substituted for old.* expressions in the
|
||||
** trigger program(s).
|
||||
**
|
||||
*/
|
||||
int sqliteCodeRowTrigger(
|
||||
Parse *pParse, /* Parse context */
|
||||
int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
|
||||
ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
|
||||
int tr_tm, /* One of TK_BEFORE, TK_AFTER */
|
||||
Table *pTab, /* The table to code triggers from */
|
||||
int newIdx, /* The indice of the "new" row to access */
|
||||
int oldIdx, /* The indice of the "old" row to access */
|
||||
int orconf, /* ON CONFLICT policy */
|
||||
int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
|
||||
){
|
||||
Trigger * pTrigger;
|
||||
TriggerStack * pTriggerStack;
|
||||
|
||||
assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
|
||||
assert(tr_tm == TK_BEFORE || tr_tm == TK_AFTER);
|
||||
|
||||
assert(newIdx != -1 || oldIdx != -1);
|
||||
|
||||
pTrigger = pTab->pTrigger;
|
||||
while( pTrigger ){
|
||||
int fire_this = 0;
|
||||
|
||||
/* determine whether we should code this trigger */
|
||||
if( pTrigger->op == op && pTrigger->tr_tm == tr_tm &&
|
||||
pTrigger->foreach == TK_ROW ){
|
||||
fire_this = 1;
|
||||
pTriggerStack = pParse->trigStack;
|
||||
while( pTriggerStack ){
|
||||
if( pTriggerStack->pTrigger == pTrigger ){
|
||||
fire_this = 0;
|
||||
}
|
||||
pTriggerStack = pTriggerStack->pNext;
|
||||
}
|
||||
if( op == TK_UPDATE && pTrigger->pColumns &&
|
||||
!checkColumnOverLap(pTrigger->pColumns, pChanges) ){
|
||||
fire_this = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if( fire_this && (pTriggerStack = sqliteMalloc(sizeof(TriggerStack)))!=0 ){
|
||||
int endTrigger;
|
||||
SrcList dummyTablist;
|
||||
Expr * whenExpr;
|
||||
|
||||
dummyTablist.nSrc = 0;
|
||||
dummyTablist.a = 0;
|
||||
|
||||
/* Push an entry on to the trigger stack */
|
||||
pTriggerStack->pTrigger = pTrigger;
|
||||
pTriggerStack->newIdx = newIdx;
|
||||
pTriggerStack->oldIdx = oldIdx;
|
||||
pTriggerStack->pTab = pTab;
|
||||
pTriggerStack->pNext = pParse->trigStack;
|
||||
pTriggerStack->ignoreJump = ignoreJump;
|
||||
pParse->trigStack = pTriggerStack;
|
||||
|
||||
/* code the WHEN clause */
|
||||
endTrigger = sqliteVdbeMakeLabel(pParse->pVdbe);
|
||||
whenExpr = sqliteExprDup(pTrigger->pWhen);
|
||||
if( sqliteExprResolveIds(pParse, 0, &dummyTablist, 0, whenExpr) ){
|
||||
pParse->trigStack = pParse->trigStack->pNext;
|
||||
sqliteFree(pTriggerStack);
|
||||
sqliteExprDelete(whenExpr);
|
||||
return 1;
|
||||
}
|
||||
sqliteExprIfFalse(pParse, whenExpr, endTrigger, 1);
|
||||
sqliteExprDelete(whenExpr);
|
||||
|
||||
codeTriggerProgram(pParse, pTrigger->step_list, orconf);
|
||||
|
||||
/* Pop the entry off the trigger stack */
|
||||
pParse->trigStack = pParse->trigStack->pNext;
|
||||
sqliteFree(pTriggerStack);
|
||||
|
||||
sqliteVdbeResolveLabel(pParse->pVdbe, endTrigger);
|
||||
}
|
||||
pTrigger = pTrigger->pNext;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* This function is called to code ON UPDATE and ON DELETE triggers on
|
||||
* views.
|
||||
*
|
||||
* This function deletes the data pointed at by the pWhere and pChanges
|
||||
* arguments before it completes.
|
||||
*/
|
||||
void sqliteViewTriggers(
|
||||
Parse *pParse,
|
||||
Table *pTab, /* The view to code triggers on */
|
||||
Expr *pWhere, /* The WHERE clause of the statement causing triggers*/
|
||||
int orconf, /* The ON CONFLICT policy specified as part of the
|
||||
statement causing these triggers */
|
||||
ExprList *pChanges /* If this is an statement causing triggers to fire
|
||||
is an UPDATE, then this list holds the columns
|
||||
to update and the expressions to update them to.
|
||||
See comments for sqliteUpdate(). */
|
||||
){
|
||||
int oldIdx = -1;
|
||||
int newIdx = -1;
|
||||
int *aXRef = 0;
|
||||
Vdbe *v;
|
||||
int endOfLoop;
|
||||
int startOfLoop;
|
||||
Select theSelect;
|
||||
Token tblNameToken;
|
||||
|
||||
assert(pTab->pSelect);
|
||||
|
||||
tblNameToken.z = pTab->zName;
|
||||
tblNameToken.n = strlen(pTab->zName);
|
||||
|
||||
theSelect.isDistinct = 0;
|
||||
theSelect.pEList = sqliteExprListAppend(0, sqliteExpr(TK_ALL, 0, 0, 0), 0);
|
||||
theSelect.pSrc = sqliteSrcListAppend(0, &tblNameToken);
|
||||
theSelect.pWhere = pWhere; pWhere = 0;
|
||||
theSelect.pGroupBy = 0;
|
||||
theSelect.pHaving = 0;
|
||||
theSelect.pOrderBy = 0;
|
||||
theSelect.op = TK_SELECT; /* ?? */
|
||||
theSelect.pPrior = 0;
|
||||
theSelect.nLimit = -1;
|
||||
theSelect.nOffset = -1;
|
||||
theSelect.zSelect = 0;
|
||||
theSelect.base = 0;
|
||||
|
||||
v = sqliteGetVdbe(pParse);
|
||||
assert(v);
|
||||
sqliteBeginWriteOperation(pParse, 1, 0);
|
||||
|
||||
/* Allocate temp tables */
|
||||
oldIdx = pParse->nTab++;
|
||||
sqliteVdbeAddOp(v, OP_OpenTemp, oldIdx, 0);
|
||||
if( pChanges ){
|
||||
newIdx = pParse->nTab++;
|
||||
sqliteVdbeAddOp(v, OP_OpenTemp, newIdx, 0);
|
||||
}
|
||||
|
||||
/* Snapshot the view */
|
||||
if( sqliteSelect(pParse, &theSelect, SRT_Table, oldIdx, 0, 0, 0) ){
|
||||
goto trigger_cleanup;
|
||||
}
|
||||
|
||||
/* loop thru the view snapshot, executing triggers for each row */
|
||||
endOfLoop = sqliteVdbeMakeLabel(v);
|
||||
sqliteVdbeAddOp(v, OP_Rewind, oldIdx, endOfLoop);
|
||||
|
||||
/* Loop thru the view snapshot, executing triggers for each row */
|
||||
startOfLoop = sqliteVdbeCurrentAddr(v);
|
||||
|
||||
/* Build the updated row if required */
|
||||
if( pChanges ){
|
||||
int ii;
|
||||
|
||||
aXRef = sqliteMalloc( sizeof(int) * pTab->nCol );
|
||||
if( aXRef==0 ) goto trigger_cleanup;
|
||||
for(ii = 0; ii < pTab->nCol; ii++){
|
||||
aXRef[ii] = -1;
|
||||
}
|
||||
|
||||
for(ii=0; ii<pChanges->nExpr; ii++){
|
||||
int jj;
|
||||
if( sqliteExprResolveIds(pParse, oldIdx, theSelect.pSrc , 0,
|
||||
pChanges->a[ii].pExpr) ){
|
||||
goto trigger_cleanup;
|
||||
}
|
||||
|
||||
if( sqliteExprCheck(pParse, pChanges->a[ii].pExpr, 0, 0) )
|
||||
goto trigger_cleanup;
|
||||
|
||||
for(jj=0; jj<pTab->nCol; jj++){
|
||||
if( sqliteStrICmp(pTab->aCol[jj].zName, pChanges->a[ii].zName)==0 ){
|
||||
aXRef[jj] = ii;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if( jj>=pTab->nCol ){
|
||||
sqliteSetString(&pParse->zErrMsg, "no such column: ",
|
||||
pChanges->a[ii].zName, 0);
|
||||
pParse->nErr++;
|
||||
goto trigger_cleanup;
|
||||
}
|
||||
}
|
||||
|
||||
sqliteVdbeAddOp(v, OP_Integer, 13, 0);
|
||||
|
||||
for(ii = 0; ii<pTab->nCol; ii++){
|
||||
if( aXRef[ii] < 0 ){
|
||||
sqliteVdbeAddOp(v, OP_Column, oldIdx, ii);
|
||||
}else{
|
||||
sqliteExprCode(pParse, pChanges->a[aXRef[ii]].pExpr);
|
||||
}
|
||||
}
|
||||
|
||||
sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
|
||||
sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
|
||||
sqliteVdbeAddOp(v, OP_Rewind, newIdx, 0);
|
||||
|
||||
sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_BEFORE,
|
||||
pTab, newIdx, oldIdx, orconf, endOfLoop);
|
||||
sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_AFTER,
|
||||
pTab, newIdx, oldIdx, orconf, endOfLoop);
|
||||
}else{
|
||||
sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_BEFORE, pTab, -1, oldIdx,
|
||||
orconf, endOfLoop);
|
||||
sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_AFTER, pTab, -1, oldIdx,
|
||||
orconf, endOfLoop);
|
||||
}
|
||||
|
||||
sqliteVdbeAddOp(v, OP_Next, oldIdx, startOfLoop);
|
||||
|
||||
sqliteVdbeResolveLabel(v, endOfLoop);
|
||||
sqliteEndWriteOperation(pParse);
|
||||
|
||||
trigger_cleanup:
|
||||
sqliteFree(aXRef);
|
||||
sqliteExprListDelete(pChanges);
|
||||
sqliteExprDelete(pWhere);
|
||||
sqliteExprListDelete(theSelect.pEList);
|
||||
sqliteSrcListDelete(theSelect.pSrc);
|
||||
sqliteExprDelete(theSelect.pWhere);
|
||||
return;
|
||||
}
|
||||
@@ -1,415 +0,0 @@
|
||||
/*
|
||||
** 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 UPDATE statements.
|
||||
**
|
||||
** $Id$
|
||||
*/
|
||||
#include "sqliteInt.h"
|
||||
|
||||
/*
|
||||
** Process an UPDATE statement.
|
||||
*/
|
||||
void sqliteUpdate(
|
||||
Parse *pParse, /* The parser context */
|
||||
Token *pTableName, /* The table in which we should change things */
|
||||
ExprList *pChanges, /* Things to be changed */
|
||||
Expr *pWhere, /* The WHERE clause. May be null */
|
||||
int onError /* How to handle constraint errors */
|
||||
){
|
||||
int i, j; /* Loop counters */
|
||||
Table *pTab; /* The table to be updated */
|
||||
SrcList *pTabList = 0; /* Fake FROM clause containing only pTab */
|
||||
int addr; /* VDBE instruction address of the start of the loop */
|
||||
WhereInfo *pWInfo; /* Information about the WHERE clause */
|
||||
Vdbe *v; /* The virtual database engine */
|
||||
Index *pIdx; /* For looping over indices */
|
||||
int nIdx; /* Number of indices that need updating */
|
||||
int nIdxTotal; /* Total number of indices */
|
||||
int base; /* Index of first available table cursor */
|
||||
sqlite *db; /* The database structure */
|
||||
Index **apIdx = 0; /* An array of indices that need updating too */
|
||||
char *aIdxUsed = 0; /* aIdxUsed[i] if the i-th index is used */
|
||||
int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
|
||||
** an expression for the i-th column of the table.
|
||||
** aXRef[i]==-1 if the i-th column is not changed. */
|
||||
int openOp; /* Opcode used to open tables */
|
||||
int chngRecno; /* True if the record number is being changed */
|
||||
Expr *pRecnoExpr; /* Expression defining the new record number */
|
||||
int openAll; /* True if all indices need to be opened */
|
||||
|
||||
int row_triggers_exist = 0;
|
||||
|
||||
int newIdx = -1; /* index of trigger "new" temp table */
|
||||
int oldIdx = -1; /* index of trigger "old" temp table */
|
||||
|
||||
if( pParse->nErr || sqlite_malloc_failed ) goto update_cleanup;
|
||||
db = pParse->db;
|
||||
|
||||
/* Check for the special case of a VIEW with one or more ON UPDATE triggers
|
||||
* defined
|
||||
*/
|
||||
{
|
||||
char *zTab = sqliteTableNameFromToken(pTableName);
|
||||
|
||||
if( zTab != 0 ){
|
||||
pTab = sqliteFindTable(pParse->db, zTab);
|
||||
if( pTab ){
|
||||
row_triggers_exist =
|
||||
sqliteTriggersExist(pParse, pTab->pTrigger,
|
||||
TK_UPDATE, TK_BEFORE, TK_ROW, pChanges) ||
|
||||
sqliteTriggersExist(pParse, pTab->pTrigger,
|
||||
TK_UPDATE, TK_AFTER, TK_ROW, pChanges);
|
||||
}
|
||||
sqliteFree(zTab);
|
||||
if( row_triggers_exist && pTab->pSelect ){
|
||||
/* Just fire VIEW triggers */
|
||||
sqliteViewTriggers(pParse, pTab, pWhere, onError, pChanges);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Locate the table which we want to update. 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.
|
||||
*/
|
||||
pTabList = sqliteTableTokenToSrcList(pParse, pTableName);
|
||||
if( pTabList==0 ) goto update_cleanup;
|
||||
pTab = pTabList->a[0].pTab;
|
||||
assert( pTab->pSelect==0 ); /* This table is not a VIEW */
|
||||
aXRef = sqliteMalloc( sizeof(int) * pTab->nCol );
|
||||
if( aXRef==0 ) goto update_cleanup;
|
||||
for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
|
||||
|
||||
/* If there are FOR EACH ROW triggers, allocate temp tables */
|
||||
if( row_triggers_exist ){
|
||||
newIdx = pParse->nTab++;
|
||||
oldIdx = pParse->nTab++;
|
||||
}
|
||||
|
||||
/* Allocate a cursors for the main database table and for all indices.
|
||||
** The index cursors might not be used, but if they are used they
|
||||
** need to occur right after the database cursor. So go ahead and
|
||||
** allocate enough space, just in case.
|
||||
*/
|
||||
base = pParse->nTab++;
|
||||
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
|
||||
pParse->nTab++;
|
||||
}
|
||||
|
||||
/* Resolve the column names in all the expressions in both the
|
||||
** WHERE clause and in the new values. Also find the column index
|
||||
** for each column to be updated in the pChanges array. For each
|
||||
** column to be updated, make sure we have authorization to change
|
||||
** that column.
|
||||
*/
|
||||
if( pWhere ){
|
||||
if( sqliteExprResolveIds(pParse, base, pTabList, 0, pWhere) ){
|
||||
goto update_cleanup;
|
||||
}
|
||||
if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
|
||||
goto update_cleanup;
|
||||
}
|
||||
}
|
||||
chngRecno = 0;
|
||||
for(i=0; i<pChanges->nExpr; i++){
|
||||
if( sqliteExprResolveIds(pParse, base, pTabList, 0, pChanges->a[i].pExpr) ){
|
||||
goto update_cleanup;
|
||||
}
|
||||
if( sqliteExprCheck(pParse, pChanges->a[i].pExpr, 0, 0) ){
|
||||
goto update_cleanup;
|
||||
}
|
||||
for(j=0; j<pTab->nCol; j++){
|
||||
if( sqliteStrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
|
||||
if( j==pTab->iPKey ){
|
||||
chngRecno = 1;
|
||||
pRecnoExpr = pChanges->a[i].pExpr;
|
||||
}
|
||||
aXRef[j] = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if( j>=pTab->nCol ){
|
||||
sqliteSetString(&pParse->zErrMsg, "no such column: ",
|
||||
pChanges->a[i].zName, 0);
|
||||
pParse->nErr++;
|
||||
goto update_cleanup;
|
||||
}
|
||||
#ifndef SQLITE_OMIT_AUTHORIZATION
|
||||
{
|
||||
int rc;
|
||||
rc = sqliteAuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
|
||||
pTab->aCol[j].zName);
|
||||
if( rc==SQLITE_DENY ){
|
||||
goto update_cleanup;
|
||||
}else if( rc==SQLITE_IGNORE ){
|
||||
aXRef[j] = -1;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/* Allocate memory for the array apIdx[] and fill it with pointers to every
|
||||
** index that needs to be updated. Indices only need updating if their
|
||||
** key includes one of the columns named in pChanges or if the record
|
||||
** number of the original table entry is changing.
|
||||
*/
|
||||
for(nIdx=nIdxTotal=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdxTotal++){
|
||||
if( chngRecno ){
|
||||
i = 0;
|
||||
}else {
|
||||
for(i=0; i<pIdx->nColumn; i++){
|
||||
if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
|
||||
}
|
||||
}
|
||||
if( i<pIdx->nColumn ) nIdx++;
|
||||
}
|
||||
if( nIdxTotal>0 ){
|
||||
apIdx = sqliteMalloc( sizeof(Index*) * nIdx + nIdxTotal );
|
||||
if( apIdx==0 ) goto update_cleanup;
|
||||
aIdxUsed = (char*)&apIdx[nIdx];
|
||||
}
|
||||
for(nIdx=j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
|
||||
if( chngRecno ){
|
||||
i = 0;
|
||||
}else{
|
||||
for(i=0; i<pIdx->nColumn; i++){
|
||||
if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
|
||||
}
|
||||
}
|
||||
if( i<pIdx->nColumn ){
|
||||
apIdx[nIdx++] = pIdx;
|
||||
aIdxUsed[j] = 1;
|
||||
}else{
|
||||
aIdxUsed[j] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Begin generating code.
|
||||
*/
|
||||
v = sqliteGetVdbe(pParse);
|
||||
if( v==0 ) goto update_cleanup;
|
||||
sqliteBeginWriteOperation(pParse, 1, !row_triggers_exist && pTab->isTemp);
|
||||
|
||||
/* Begin the database scan
|
||||
*/
|
||||
pWInfo = sqliteWhereBegin(pParse, base, pTabList, pWhere, 1, 0);
|
||||
if( pWInfo==0 ) goto update_cleanup;
|
||||
|
||||
/* Remember the index of every item to be updated.
|
||||
*/
|
||||
sqliteVdbeAddOp(v, OP_ListWrite, 0, 0);
|
||||
|
||||
/* End the database scan loop.
|
||||
*/
|
||||
sqliteWhereEnd(pWInfo);
|
||||
|
||||
/* Initialize the count of updated rows
|
||||
*/
|
||||
if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
|
||||
sqliteVdbeAddOp(v, OP_Integer, 0, 0);
|
||||
}
|
||||
|
||||
if( row_triggers_exist ){
|
||||
int ii;
|
||||
|
||||
sqliteVdbeAddOp(v, OP_OpenTemp, oldIdx, 0);
|
||||
sqliteVdbeAddOp(v, OP_OpenTemp, newIdx, 0);
|
||||
|
||||
sqliteVdbeAddOp(v, OP_ListRewind, 0, 0);
|
||||
addr = sqliteVdbeAddOp(v, OP_ListRead, 0, 0);
|
||||
sqliteVdbeAddOp(v, OP_Dup, 0, 0);
|
||||
|
||||
sqliteVdbeAddOp(v, OP_Dup, 0, 0);
|
||||
sqliteVdbeAddOp(v, (pTab->isTemp?OP_OpenAux:OP_Open), base, pTab->tnum);
|
||||
sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
|
||||
|
||||
sqliteVdbeAddOp(v, OP_Integer, 13, 0);
|
||||
for(ii = 0; ii < pTab->nCol; ii++){
|
||||
if( ii == pTab->iPKey ){
|
||||
sqliteVdbeAddOp(v, OP_Recno, base, 0);
|
||||
}else{
|
||||
sqliteVdbeAddOp(v, OP_Column, base, ii);
|
||||
}
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
|
||||
sqliteVdbeAddOp(v, OP_PutIntKey, oldIdx, 0);
|
||||
|
||||
sqliteVdbeAddOp(v, OP_Integer, 13, 0);
|
||||
for(ii = 0; ii < pTab->nCol; ii++){
|
||||
if( aXRef[ii] < 0 ){
|
||||
if( ii == pTab->iPKey ){
|
||||
sqliteVdbeAddOp(v, OP_Recno, base, 0);
|
||||
}else{
|
||||
sqliteVdbeAddOp(v, OP_Column, base, ii);
|
||||
}
|
||||
}else{
|
||||
sqliteExprCode(pParse, pChanges->a[aXRef[ii]].pExpr);
|
||||
}
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
|
||||
sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
|
||||
sqliteVdbeAddOp(v, OP_Close, base, 0);
|
||||
|
||||
sqliteVdbeAddOp(v, OP_Rewind, oldIdx, 0);
|
||||
sqliteVdbeAddOp(v, OP_Rewind, newIdx, 0);
|
||||
|
||||
if( sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_BEFORE, pTab,
|
||||
newIdx, oldIdx, onError, addr) ){
|
||||
goto update_cleanup;
|
||||
}
|
||||
}
|
||||
|
||||
/* Rewind the list of records that need to be updated and
|
||||
** open every index that needs updating. Note that if any
|
||||
** index could potentially invoke a REPLACE conflict resolution
|
||||
** action, then we need to open all indices because we might need
|
||||
** to be deleting some records.
|
||||
*/
|
||||
openOp = pTab->isTemp ? OP_OpenWrAux : OP_OpenWrite;
|
||||
sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
|
||||
if( onError==OE_Replace ){
|
||||
openAll = 1;
|
||||
}else{
|
||||
openAll = 0;
|
||||
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
|
||||
if( pIdx->onError==OE_Replace ){
|
||||
openAll = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
|
||||
if( openAll || aIdxUsed[i] ){
|
||||
sqliteVdbeAddOp(v, openOp, base+i+1, pIdx->tnum);
|
||||
assert( pParse->nTab>base+i+1 );
|
||||
}
|
||||
}
|
||||
|
||||
/* Loop over every record that needs updating. We have to load
|
||||
** the old data for each record to be updated because some columns
|
||||
** might not change and we will need to copy the old value.
|
||||
** Also, the old data is needed to delete the old index entires.
|
||||
** So make the cursor point at the old record.
|
||||
*/
|
||||
if( !row_triggers_exist ){
|
||||
sqliteVdbeAddOp(v, OP_ListRewind, 0, 0);
|
||||
addr = sqliteVdbeAddOp(v, OP_ListRead, 0, 0);
|
||||
sqliteVdbeAddOp(v, OP_Dup, 0, 0);
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_NotExists, base, addr);
|
||||
|
||||
/* If the record number will change, push the record number as it
|
||||
** will be after the update. (The old record number is currently
|
||||
** on top of the stack.)
|
||||
*/
|
||||
if( chngRecno ){
|
||||
sqliteExprCode(pParse, pRecnoExpr);
|
||||
sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
|
||||
}
|
||||
|
||||
/* Compute new data for this record.
|
||||
*/
|
||||
for(i=0; i<pTab->nCol; i++){
|
||||
if( i==pTab->iPKey ){
|
||||
sqliteVdbeAddOp(v, OP_String, 0, 0);
|
||||
continue;
|
||||
}
|
||||
j = aXRef[i];
|
||||
if( j<0 ){
|
||||
sqliteVdbeAddOp(v, OP_Column, base, i);
|
||||
}else{
|
||||
sqliteExprCode(pParse, pChanges->a[j].pExpr);
|
||||
}
|
||||
}
|
||||
|
||||
/* Do constraint checks
|
||||
*/
|
||||
sqliteGenerateConstraintChecks(pParse, pTab, base, aIdxUsed, chngRecno, 1,
|
||||
onError, addr);
|
||||
|
||||
/* Delete the old indices for the current record.
|
||||
*/
|
||||
sqliteGenerateRowIndexDelete(db, v, pTab, base, aIdxUsed);
|
||||
|
||||
/* If changing the record number, delete the old record.
|
||||
*/
|
||||
if( chngRecno ){
|
||||
sqliteVdbeAddOp(v, OP_Delete, base, 0);
|
||||
}
|
||||
|
||||
/* Create the new index entries and the new record.
|
||||
*/
|
||||
sqliteCompleteInsertion(pParse, pTab, base, aIdxUsed, chngRecno, 1);
|
||||
|
||||
/* Increment the row counter
|
||||
*/
|
||||
if( db->flags & SQLITE_CountRows && !pParse->trigStack){
|
||||
sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
|
||||
}
|
||||
|
||||
if( row_triggers_exist ){
|
||||
for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
|
||||
if( openAll || aIdxUsed[i] )
|
||||
sqliteVdbeAddOp(v, OP_Close, base+i+1, 0);
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_Close, base, 0);
|
||||
pParse->nTab = base;
|
||||
|
||||
if( sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_AFTER, pTab,
|
||||
newIdx, oldIdx, onError, addr) ){
|
||||
goto update_cleanup;
|
||||
}
|
||||
}
|
||||
|
||||
/* Repeat the above with the next record to be updated, until
|
||||
** all record selected by the WHERE clause have been updated.
|
||||
*/
|
||||
sqliteVdbeAddOp(v, OP_Goto, 0, addr);
|
||||
sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
|
||||
sqliteVdbeAddOp(v, OP_ListReset, 0, 0);
|
||||
|
||||
/* Close all tables if there were no FOR EACH ROW triggers */
|
||||
if( !row_triggers_exist ){
|
||||
for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
|
||||
if( openAll || aIdxUsed[i] ){
|
||||
sqliteVdbeAddOp(v, OP_Close, base+i+1, 0);
|
||||
}
|
||||
}
|
||||
sqliteVdbeAddOp(v, OP_Close, base, 0);
|
||||
pParse->nTab = base;
|
||||
}else{
|
||||
sqliteVdbeAddOp(v, OP_Close, newIdx, 0);
|
||||
sqliteVdbeAddOp(v, OP_Close, oldIdx, 0);
|
||||
}
|
||||
|
||||
sqliteEndWriteOperation(pParse);
|
||||
|
||||
/*
|
||||
** Return the number of rows that were changed.
|
||||
*/
|
||||
if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
|
||||
sqliteVdbeAddOp(v, OP_ColumnName, 0, 0);
|
||||
sqliteVdbeChangeP3(v, -1, "rows updated", P3_STATIC);
|
||||
sqliteVdbeAddOp(v, OP_Callback, 1, 0);
|
||||
}
|
||||
|
||||
update_cleanup:
|
||||
sqliteFree(apIdx);
|
||||
sqliteFree(aXRef);
|
||||
sqliteSrcListDelete(pTabList);
|
||||
sqliteExprListDelete(pChanges);
|
||||
sqliteExprDelete(pWhere);
|
||||
return;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,95 +0,0 @@
|
||||
/*
|
||||
** 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.
|
||||
**
|
||||
*************************************************************************
|
||||
** Header file for the Virtual DataBase Engine (VDBE)
|
||||
**
|
||||
** This header defines the interface to the virtual database engine
|
||||
** or VDBE. The VDBE implements an abstract machine that runs a
|
||||
** simple program to access and modify the underlying database.
|
||||
**
|
||||
** $Id$
|
||||
*/
|
||||
#ifndef _SQLITE_VDBE_H_
|
||||
#define _SQLITE_VDBE_H_
|
||||
#include <stdio.h>
|
||||
|
||||
/*
|
||||
** A single VDBE is an opaque structure named "Vdbe". Only routines
|
||||
** in the source file sqliteVdbe.c are allowed to see the insides
|
||||
** of this structure.
|
||||
*/
|
||||
typedef struct Vdbe Vdbe;
|
||||
|
||||
/*
|
||||
** A single instruction of the virtual machine has an opcode
|
||||
** and as many as three operands. The instruction is recorded
|
||||
** as an instance of the following structure:
|
||||
*/
|
||||
struct VdbeOp {
|
||||
int opcode; /* What operation to perform */
|
||||
int p1; /* First operand */
|
||||
int p2; /* Second parameter (often the jump destination) */
|
||||
char *p3; /* Third parameter */
|
||||
int p3type; /* P3_STATIC, P3_DYNAMIC or P3_POINTER */
|
||||
#ifdef VDBE_PROFILE
|
||||
int cnt; /* Number of times this instruction was executed */
|
||||
long long cycles; /* Total time spend executing this instruction */
|
||||
#endif
|
||||
};
|
||||
typedef struct VdbeOp VdbeOp;
|
||||
|
||||
/*
|
||||
** Allowed values of VdbeOp.p3type
|
||||
*/
|
||||
#define P3_NOTUSED 0 /* The P3 parameter is not used */
|
||||
#define P3_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
|
||||
#define P3_STATIC (-2) /* Pointer to a static string */
|
||||
#define P3_POINTER (-3) /* P3 is a pointer to some structure or object */
|
||||
|
||||
/*
|
||||
** The following macro converts a relative address in the p2 field
|
||||
** of a VdbeOp structure into a negative number so that
|
||||
** sqliteVdbeAddOpList() knows that the address is relative. Calling
|
||||
** the macro again restores the address.
|
||||
*/
|
||||
#define ADDR(X) (-1-(X))
|
||||
|
||||
/*
|
||||
** The makefile scans the vdbe.c source file and creates the "opcodes.h"
|
||||
** header file that defines a number for each opcode used by the VDBE.
|
||||
*/
|
||||
#include "opcodes.h"
|
||||
|
||||
/*
|
||||
** Prototypes for the VDBE interface. See comments on the implementation
|
||||
** for a description of what each of these routines does.
|
||||
*/
|
||||
Vdbe *sqliteVdbeCreate(sqlite*);
|
||||
void sqliteVdbeCreateCallback(Vdbe*, int*);
|
||||
int sqliteVdbeAddOp(Vdbe*,int,int,int);
|
||||
int sqliteVdbeAddOpList(Vdbe*, int nOp, VdbeOp const *aOp);
|
||||
void sqliteVdbeChangeP1(Vdbe*, int addr, int P1);
|
||||
void sqliteVdbeChangeP2(Vdbe*, int addr, int P2);
|
||||
void sqliteVdbeChangeP3(Vdbe*, int addr, const char *zP1, int N);
|
||||
void sqliteVdbeDequoteP3(Vdbe*, int addr);
|
||||
int sqliteVdbeFindOp(Vdbe*, int, int);
|
||||
int sqliteVdbeMakeLabel(Vdbe*);
|
||||
void sqliteVdbeDelete(Vdbe*);
|
||||
void sqliteVdbeMakeReady(Vdbe*,sqlite_callback,void*,int);
|
||||
int sqliteVdbeExec(Vdbe*);
|
||||
int sqliteVdbeList(Vdbe*);
|
||||
int sqliteVdbeFinalize(Vdbe*,char**);
|
||||
void sqliteVdbeResolveLabel(Vdbe*, int);
|
||||
int sqliteVdbeCurrentAddr(Vdbe*);
|
||||
void sqliteVdbeTrace(Vdbe*,FILE*);
|
||||
void sqliteVdbeCompressSpace(Vdbe*,int);
|
||||
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,93 +0,0 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<!DOCTYPE package SYSTEM "../../../php4/pear/package.dtd">
|
||||
<package>
|
||||
<name>SQLite</name>
|
||||
<summary>SQLite database bindings</summary>
|
||||
<maintainers>
|
||||
<maintainer>
|
||||
<user>wez</user>
|
||||
<name>Wez Furlong</name>
|
||||
<email>wez@php.net</email>
|
||||
<role>lead</role>
|
||||
</maintainer>
|
||||
</maintainers>
|
||||
<description>
|
||||
SQLite is a C library that implements an embeddable SQL database engine.
|
||||
Programs that link with the SQLite library can have SQL database access
|
||||
without running a separate RDBMS process.
|
||||
This extension allows you to access SQLite databases from within PHP.
|
||||
</description>
|
||||
<license>PHP</license>
|
||||
<release>
|
||||
<state>beta</state>
|
||||
<version>0.6</version>
|
||||
<date>2003-04-18</date>
|
||||
<notes>
|
||||
SQLite is now bundled with the extension; no need to download and build
|
||||
it separately.
|
||||
|
||||
Fixed memory corruption bug when calling back into a PHP function from
|
||||
an SQL statement.
|
||||
|
||||
Added sqlite_busy_timeout() to set the maximum duration for attempting
|
||||
to lock the database when updating it. Default timeout is set to 1/2
|
||||
second.
|
||||
|
||||
NULL columns are now correctly returned as NULL values.
|
||||
</notes>
|
||||
<filelist>
|
||||
<file role="src" name="config.m4"/>
|
||||
<file role="src" name="sqlite.c"/>
|
||||
<file role="src" name="php_sqlite.h"/>
|
||||
<file role="src" name="Makefile.frag"/>
|
||||
<file role="doc" name="CREDITS"/>
|
||||
<file role="doc" name="README"/>
|
||||
<file role="doc" name="TODO"/>
|
||||
<file role="doc" name="sqlite.php"/>
|
||||
<file role="test" name="tests/001.phpt"/>
|
||||
|
||||
<dir name="libsqlite">
|
||||
<file role="doc" name="README"/>
|
||||
<file role="src" name="VERSION"/>
|
||||
|
||||
<dir name="src">
|
||||
<file role="src" name="parse.c"/>
|
||||
<file role="src" name="parse.y"/>
|
||||
<file role="src" name="auth.c"/>
|
||||
<file role="src" name="btree.c"/>
|
||||
<file role="src" name="encode.c"/>
|
||||
<file role="src" name="build.c"/>
|
||||
<file role="src" name="delete.c"/>
|
||||
<file role="src" name="expr.c"/>
|
||||
<file role="src" name="func.c"/>
|
||||
<file role="src" name="hash.c"/>
|
||||
<file role="src" name="insert.c"/>
|
||||
<file role="src" name="main.c"/>
|
||||
<file role="src" name="os.c"/>
|
||||
<file role="src" name="pager.c"/>
|
||||
<file role="src" name="printf.c"/>
|
||||
<file role="src" name="random.c"/>
|
||||
<file role="src" name="select.c"/>
|
||||
<file role="src" name="table.c"/>
|
||||
<file role="src" name="tokenize.c"/>
|
||||
<file role="src" name="update.c"/>
|
||||
<file role="src" name="util.c"/>
|
||||
<file role="src" name="vdbe.c"/>
|
||||
<file role="src" name="where.c"/>
|
||||
<file role="src" name="trigger.c"/>
|
||||
|
||||
<file role="src" name="opcodes.h"/>
|
||||
<file role="src" name="btree.h"/>
|
||||
<file role="src" name="hash.h"/>
|
||||
<file role="src" name="os.h"/>
|
||||
<file role="src" name="pager.h"/>
|
||||
<file role="src" name="parse.h"/>
|
||||
<file role="src" name="sqliteInt.h"/>
|
||||
<file role="src" name="sqlite.h.in"/>
|
||||
<file role="src" name="vdbe.h"/>
|
||||
</dir>
|
||||
|
||||
</dir>
|
||||
</filelist>
|
||||
</release>
|
||||
</package>
|
||||
@@ -1,78 +0,0 @@
|
||||
/*
|
||||
+----------------------------------------------------------------------+
|
||||
| PHP Version 4 |
|
||||
+----------------------------------------------------------------------+
|
||||
| Copyright (c) 1997-2003 The PHP Group |
|
||||
+----------------------------------------------------------------------+
|
||||
| This source file is subject to version 2.02 of the PHP license, |
|
||||
| that is bundled with this package in the file LICENSE, and is |
|
||||
| available at through the world-wide-web at |
|
||||
| http://www.php.net/license/2_02.txt. |
|
||||
| If you did not receive a copy of the PHP license and are unable to |
|
||||
| obtain it through the world-wide-web, please send a note to |
|
||||
| license@php.net so we can mail you a copy immediately. |
|
||||
+----------------------------------------------------------------------+
|
||||
| Author: Wez Furlong <wez@thebrainroom.com> |
|
||||
+----------------------------------------------------------------------+
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
#ifndef PHP_SQLITE_H
|
||||
#define PHP_SQLITE_H
|
||||
|
||||
extern zend_module_entry sqlite_module_entry;
|
||||
#define phpext_sqlite_ptr &sqlite_module_entry
|
||||
|
||||
#ifdef PHP_WIN32
|
||||
#define PHP_SQLITE_API __declspec(dllexport)
|
||||
#else
|
||||
#define PHP_SQLITE_API
|
||||
#endif
|
||||
|
||||
#ifdef ZTS
|
||||
#include "TSRM.h"
|
||||
#endif
|
||||
|
||||
PHP_MINIT_FUNCTION(sqlite);
|
||||
PHP_MSHUTDOWN_FUNCTION(sqlite);
|
||||
PHP_RINIT_FUNCTION(sqlite);
|
||||
PHP_RSHUTDOWN_FUNCTION(sqlite);
|
||||
PHP_MINFO_FUNCTION(sqlite);
|
||||
|
||||
PHP_FUNCTION(sqlite_open);
|
||||
PHP_FUNCTION(sqlite_close);
|
||||
PHP_FUNCTION(sqlite_query);
|
||||
PHP_FUNCTION(sqlite_fetch_array);
|
||||
|
||||
PHP_FUNCTION(sqlite_num_rows);
|
||||
PHP_FUNCTION(sqlite_num_fields);
|
||||
PHP_FUNCTION(sqlite_field_name);
|
||||
PHP_FUNCTION(sqlite_seek);
|
||||
|
||||
PHP_FUNCTION(sqlite_libversion);
|
||||
PHP_FUNCTION(sqlite_libencoding);
|
||||
|
||||
PHP_FUNCTION(sqlite_changes);
|
||||
PHP_FUNCTION(sqlite_last_insert_rowid);
|
||||
|
||||
PHP_FUNCTION(sqlite_escape_string);
|
||||
|
||||
PHP_FUNCTION(sqlite_busy_timeout);
|
||||
|
||||
#ifdef ZTS
|
||||
#define SQLITE_G(v) TSRMG(sqlite_globals_id, zend_sqlite_globals *, v)
|
||||
#else
|
||||
#define SQLITE_G(v) (sqlite_globals.v)
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
* Local variables:
|
||||
* tab-width: 4
|
||||
* c-basic-offset: 4
|
||||
* indent-tabs-mode: t
|
||||
* End:
|
||||
*/
|
||||
@@ -1,537 +0,0 @@
|
||||
/*
|
||||
+----------------------------------------------------------------------+
|
||||
| PHP Version 4 |
|
||||
+----------------------------------------------------------------------+
|
||||
| Copyright (c) 1997-2003 The PHP Group |
|
||||
+----------------------------------------------------------------------+
|
||||
| This source file is subject to version 2.02 of the PHP license, |
|
||||
| that is bundled with this package in the file LICENSE, and is |
|
||||
| available at through the world-wide-web at |
|
||||
| http://www.php.net/license/2_02.txt. |
|
||||
| If you did not receive a copy of the PHP license and are unable to |
|
||||
| obtain it through the world-wide-web, please send a note to |
|
||||
| license@php.net so we can mail you a copy immediately. |
|
||||
+----------------------------------------------------------------------+
|
||||
| Author: Wez Furlong <wez@thebrainroom.com> |
|
||||
+----------------------------------------------------------------------+
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include "config.h"
|
||||
#endif
|
||||
|
||||
#include "php.h"
|
||||
#include "php_ini.h"
|
||||
#include "ext/standard/info.h"
|
||||
#include "php_sqlite.h"
|
||||
|
||||
#include <sqlite.h>
|
||||
|
||||
static unsigned char arg3_force_ref[] = {3, BYREF_NONE, BYREF_NONE, BYREF_FORCE };
|
||||
|
||||
static int le_sqlite_db, le_sqlite_result;
|
||||
|
||||
struct php_sqlite_result {
|
||||
char **table;
|
||||
int nrows;
|
||||
int ncolumns;
|
||||
int curr_row;
|
||||
};
|
||||
|
||||
enum { PHPSQLITE_ASSOC = 1, PHPSQLITE_NUM = 2, PHPSQLITE_BOTH = PHPSQLITE_ASSOC|PHPSQLITE_NUM };
|
||||
|
||||
function_entry sqlite_functions[] = {
|
||||
PHP_FE(sqlite_open, arg3_force_ref)
|
||||
PHP_FE(sqlite_close, NULL)
|
||||
PHP_FE(sqlite_query, NULL)
|
||||
PHP_FE(sqlite_fetch_array, NULL)
|
||||
PHP_FE(sqlite_libversion, NULL)
|
||||
PHP_FE(sqlite_libencoding, NULL)
|
||||
PHP_FE(sqlite_changes, NULL)
|
||||
PHP_FE(sqlite_last_insert_rowid, NULL)
|
||||
PHP_FE(sqlite_num_rows, NULL)
|
||||
PHP_FE(sqlite_num_fields, NULL)
|
||||
PHP_FE(sqlite_field_name, NULL)
|
||||
PHP_FE(sqlite_seek, NULL)
|
||||
PHP_FE(sqlite_escape_string, NULL)
|
||||
PHP_FE(sqlite_busy_timeout, NULL)
|
||||
{NULL, NULL, NULL}
|
||||
};
|
||||
|
||||
|
||||
zend_module_entry sqlite_module_entry = {
|
||||
#if ZEND_MODULE_API_NO >= 20010901
|
||||
STANDARD_MODULE_HEADER,
|
||||
#endif
|
||||
"sqlite",
|
||||
sqlite_functions,
|
||||
PHP_MINIT(sqlite),
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
PHP_MINFO(sqlite),
|
||||
#if ZEND_MODULE_API_NO >= 20010901
|
||||
"0.1",
|
||||
#endif
|
||||
STANDARD_MODULE_PROPERTIES
|
||||
};
|
||||
|
||||
|
||||
#ifdef COMPILE_DL_SQLITE
|
||||
ZEND_GET_MODULE(sqlite)
|
||||
#endif
|
||||
|
||||
|
||||
static ZEND_RSRC_DTOR_FUNC(php_sqlite_db_dtor)
|
||||
{
|
||||
sqlite *db = (sqlite*)rsrc->ptr;
|
||||
|
||||
sqlite_close(db);
|
||||
}
|
||||
|
||||
static ZEND_RSRC_DTOR_FUNC(php_sqlite_result_dtor)
|
||||
{
|
||||
struct php_sqlite_result *res = (struct php_sqlite_result *)rsrc->ptr;
|
||||
|
||||
sqlite_free_table(res->table);
|
||||
efree(res);
|
||||
}
|
||||
|
||||
/* PHP Function interface */
|
||||
|
||||
static void php_sqlite_function_callback(sqlite_func *func, int argc, const char **argv)
|
||||
{
|
||||
zval *retval = NULL;
|
||||
zval ***zargs;
|
||||
zval funcname;
|
||||
int i, res;
|
||||
char *callable = NULL, *errbuf=NULL;
|
||||
|
||||
/* sanity check the args */
|
||||
if (argc == 0) {
|
||||
sqlite_set_result_error(func, "not enough parameters", -1);
|
||||
return;
|
||||
}
|
||||
|
||||
ZVAL_STRING(&funcname, (char*)argv[0], 0);
|
||||
|
||||
if (!zend_is_callable(&funcname, 0, &callable)) {
|
||||
spprintf(&errbuf, 0, "function `%s' is not callable", callable);
|
||||
sqlite_set_result_error(func, errbuf, -1);
|
||||
efree(errbuf);
|
||||
efree(callable);
|
||||
return;
|
||||
}
|
||||
efree(callable);
|
||||
|
||||
if (argc > 1) {
|
||||
zargs = (zval ***)emalloc((argc - 1) * sizeof(zval **));
|
||||
|
||||
for (i = 0; i < argc-1; i++) {
|
||||
zargs[i] = emalloc(sizeof(zval *));
|
||||
MAKE_STD_ZVAL(*zargs[i]);
|
||||
ZVAL_STRING(*zargs[i], (char*)argv[i+1], 1);
|
||||
}
|
||||
}
|
||||
|
||||
res = call_user_function_ex(EG(function_table),
|
||||
NULL,
|
||||
&funcname,
|
||||
&retval,
|
||||
argc-1,
|
||||
zargs,
|
||||
0, NULL TSRMLS_CC);
|
||||
|
||||
if (res == SUCCESS) {
|
||||
if (retval == NULL) {
|
||||
sqlite_set_result_string(func, NULL, 0);
|
||||
} else {
|
||||
switch (Z_TYPE_P(retval)) {
|
||||
case IS_STRING:
|
||||
sqlite_set_result_string(func, Z_STRVAL_P(retval), Z_STRLEN_P(retval));
|
||||
break;
|
||||
case IS_LONG:
|
||||
case IS_BOOL:
|
||||
sqlite_set_result_int(func, Z_LVAL_P(retval));
|
||||
break;
|
||||
case IS_DOUBLE:
|
||||
sqlite_set_result_double(func, Z_DVAL_P(retval));
|
||||
break;
|
||||
case IS_NULL:
|
||||
default:
|
||||
sqlite_set_result_string(func, NULL, 0);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
sqlite_set_result_error(func, "call_user_function_ex failed", -1);
|
||||
}
|
||||
|
||||
if (retval) {
|
||||
zval_ptr_dtor(&retval);
|
||||
}
|
||||
|
||||
if (zargs) {
|
||||
for (i = 0; i < argc-1; i++) {
|
||||
zval_ptr_dtor(zargs[i]);
|
||||
efree(zargs[i]);
|
||||
}
|
||||
efree(zargs);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
PHP_MINIT_FUNCTION(sqlite)
|
||||
{
|
||||
le_sqlite_db = zend_register_list_destructors_ex(php_sqlite_db_dtor, NULL, "sqlite database", module_number);
|
||||
le_sqlite_result = zend_register_list_destructors_ex(php_sqlite_result_dtor, NULL, "sqlite result", module_number);
|
||||
|
||||
REGISTER_LONG_CONSTANT("SQLITE_BOTH", PHPSQLITE_BOTH, CONST_CS|CONST_PERSISTENT);
|
||||
REGISTER_LONG_CONSTANT("SQLITE_NUM", PHPSQLITE_NUM, CONST_CS|CONST_PERSISTENT);
|
||||
REGISTER_LONG_CONSTANT("SQLITE_ASSOC", PHPSQLITE_ASSOC, CONST_CS|CONST_PERSISTENT);
|
||||
|
||||
return SUCCESS;
|
||||
}
|
||||
|
||||
PHP_MINFO_FUNCTION(sqlite)
|
||||
{
|
||||
php_info_print_table_start();
|
||||
php_info_print_table_header(2, "SQLite support", "enabled");
|
||||
php_info_print_table_row(2, "PECL Module version", "$Id$");
|
||||
php_info_print_table_row(2, "SQLite Library", sqlite_libversion());
|
||||
php_info_print_table_row(2, "SQLite Encoding", sqlite_libencoding());
|
||||
php_info_print_table_end();
|
||||
}
|
||||
|
||||
/* {{{ proto resource sqlite_open(string filename [, int mode, string &errmessage])
|
||||
Opens an SQLite database. Will create the database if it does not exist */
|
||||
PHP_FUNCTION(sqlite_open)
|
||||
{
|
||||
int mode = 0666;
|
||||
char *filename;
|
||||
long filename_len;
|
||||
zval *errmsg = NULL;
|
||||
sqlite *db = NULL;
|
||||
char *errtext = NULL;
|
||||
|
||||
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz/",
|
||||
&filename, &filename_len, &mode, &errmsg)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (PG(safe_mode) && (!php_checkuid(filename, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
|
||||
RETURN_FALSE;
|
||||
}
|
||||
|
||||
if (php_check_open_basedir(filename TSRMLS_CC)) {
|
||||
RETURN_FALSE;
|
||||
}
|
||||
|
||||
db = sqlite_open(filename, mode, &errtext);
|
||||
|
||||
if (db == NULL) {
|
||||
php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
|
||||
|
||||
if (errmsg) {
|
||||
ZVAL_STRING(errmsg, errtext, 1);
|
||||
}
|
||||
|
||||
sqlite_freemem(errtext);
|
||||
|
||||
RETURN_FALSE;
|
||||
}
|
||||
|
||||
/* register the PHP functions */
|
||||
sqlite_create_function(db, "php", -1, php_sqlite_function_callback, 0);
|
||||
|
||||
/* set default busy handler; keep retrying up until 1/2 second has passed,
|
||||
* then fail with a busy status code */
|
||||
sqlite_busy_timeout(db, 500);
|
||||
|
||||
ZEND_REGISTER_RESOURCE(return_value, db, le_sqlite_db);
|
||||
|
||||
}
|
||||
/* }}} */
|
||||
|
||||
/* {{{ proto void sqlite_busy_timeout(resource db, int ms)
|
||||
Set busy timeout duration. If ms <= 0, all busy handlers are disabled */
|
||||
PHP_FUNCTION(sqlite_busy_timeout)
|
||||
{
|
||||
zval *zdb;
|
||||
sqlite *db;
|
||||
long ms;
|
||||
|
||||
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &zdb, &ms)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ZEND_FETCH_RESOURCE(db, sqlite *, &zdb, -1, "sqlite database", le_sqlite_db);
|
||||
|
||||
sqlite_busy_timeout(db, ms);
|
||||
}
|
||||
/* }}} */
|
||||
|
||||
/* {{{ proto void sqlite_close(resource db)
|
||||
Closes an open sqlite database */
|
||||
PHP_FUNCTION(sqlite_close)
|
||||
{
|
||||
zval *zdb;
|
||||
sqlite *db;
|
||||
|
||||
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zdb)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ZEND_FETCH_RESOURCE(db, sqlite *, &zdb, -1, "sqlite database", le_sqlite_db);
|
||||
zend_list_delete(Z_RESVAL_P(zdb));
|
||||
}
|
||||
/* }}} */
|
||||
|
||||
/* {{{ proto resource sqlite_query(string query, resource db)
|
||||
Executes a query against a given database and returns a result handle */
|
||||
PHP_FUNCTION(sqlite_query)
|
||||
{
|
||||
zval *zdb;
|
||||
sqlite *db;
|
||||
char *sql;
|
||||
long sql_len;
|
||||
struct php_sqlite_result res, *rres;
|
||||
int ret;
|
||||
char *errtext = NULL;
|
||||
|
||||
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sr", &sql, &sql_len, &zdb)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ZEND_FETCH_RESOURCE(db, sqlite *, &zdb, -1, "sqlite database", le_sqlite_db);
|
||||
|
||||
memset(&res, 0, sizeof(res));
|
||||
|
||||
ret = sqlite_get_table(db, sql, &res.table, &res.nrows, &res.ncolumns, &errtext);
|
||||
|
||||
if (ret != SQLITE_OK) {
|
||||
php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
|
||||
sqlite_freemem(errtext);
|
||||
RETURN_FALSE;
|
||||
}
|
||||
|
||||
rres = (struct php_sqlite_result*)emalloc(sizeof(*rres));
|
||||
memcpy(rres, &res, sizeof(*rres));
|
||||
|
||||
rres->curr_row = 1; /* 0 holds the column header names */
|
||||
|
||||
ZEND_REGISTER_RESOURCE(return_value, rres, le_sqlite_result);
|
||||
}
|
||||
/* }}} */
|
||||
|
||||
/* {{{ proto array sqlite_fetch_array(resource result [, int result_type])
|
||||
Fetches the next row from a result set as an array */
|
||||
PHP_FUNCTION(sqlite_fetch_array)
|
||||
{
|
||||
zval *zres;
|
||||
struct php_sqlite_result *res;
|
||||
int mode = PHPSQLITE_BOTH;
|
||||
int i, j;
|
||||
|
||||
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &zres, &mode)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
|
||||
|
||||
/* check range of the row */
|
||||
if (res->curr_row > res->nrows) {
|
||||
/* no more */
|
||||
RETURN_FALSE;
|
||||
}
|
||||
|
||||
array_init(return_value);
|
||||
|
||||
/* calculate the starting slot for the row */
|
||||
i = res->curr_row * res->ncolumns;
|
||||
|
||||
/* now populate the result */
|
||||
for (j = 0; j < res->ncolumns; j++) {
|
||||
if (mode & PHPSQLITE_NUM) {
|
||||
if (res->table[i + j] == NULL) {
|
||||
add_index_null(return_value, j);
|
||||
} else {
|
||||
add_index_string(return_value, j, res->table[i + j], 1);
|
||||
}
|
||||
}
|
||||
if (mode & PHPSQLITE_ASSOC) {
|
||||
if (res->table[i + j] == NULL) {
|
||||
add_assoc_null(return_value, res->table[j]);
|
||||
} else {
|
||||
add_assoc_string(return_value, res->table[j], res->table[i + j], 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* advance the row pointer */
|
||||
res->curr_row++;
|
||||
}
|
||||
/* }}} */
|
||||
|
||||
/* {{{ proto string sqlite_libversion()
|
||||
Returns the version of the linked SQLite library */
|
||||
PHP_FUNCTION(sqlite_libversion)
|
||||
{
|
||||
if (ZEND_NUM_ARGS() != 0) {
|
||||
WRONG_PARAM_COUNT;
|
||||
}
|
||||
RETURN_STRING((char*)sqlite_libversion(), 1);
|
||||
}
|
||||
/* }}} */
|
||||
|
||||
/* {{{ proto string sqlite_libencoding()
|
||||
Returns the encoding (iso8859 or UTF-8) of the linked SQLite library */
|
||||
PHP_FUNCTION(sqlite_libencoding)
|
||||
{
|
||||
if (ZEND_NUM_ARGS() != 0) {
|
||||
WRONG_PARAM_COUNT;
|
||||
}
|
||||
RETURN_STRING((char*)sqlite_libencoding(), 1);
|
||||
}
|
||||
/* }}} */
|
||||
|
||||
/* {{{ proto int sqlite_changes(resource db)
|
||||
Returns the number of rows that were changed by the most recent SQL statement */
|
||||
PHP_FUNCTION(sqlite_changes)
|
||||
{
|
||||
zval *zdb;
|
||||
sqlite *db;
|
||||
|
||||
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zdb)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ZEND_FETCH_RESOURCE(db, sqlite *, &zdb, -1, "sqlite database", le_sqlite_db);
|
||||
|
||||
RETURN_LONG(sqlite_changes(db));
|
||||
}
|
||||
/* }}} */
|
||||
|
||||
/* {{{ proto int sqlite_last_insert_rowid(resource db)
|
||||
Returns the rowid of the most recently inserted row */
|
||||
PHP_FUNCTION(sqlite_last_insert_rowid)
|
||||
{
|
||||
zval *zdb;
|
||||
sqlite *db;
|
||||
|
||||
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zdb)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ZEND_FETCH_RESOURCE(db, sqlite *, &zdb, -1, "sqlite database", le_sqlite_db);
|
||||
|
||||
RETURN_LONG(sqlite_last_insert_rowid(db));
|
||||
}
|
||||
/* }}} */
|
||||
|
||||
/* {{{ proto int sqlite_num_rows(resource result)
|
||||
Returns the number of rows in a result set */
|
||||
PHP_FUNCTION(sqlite_num_rows)
|
||||
{
|
||||
zval *zres;
|
||||
struct php_sqlite_result *res;
|
||||
|
||||
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
|
||||
|
||||
RETURN_LONG(res->nrows);
|
||||
|
||||
}
|
||||
/* }}} */
|
||||
|
||||
/* {{{ proto int sqlite_num_fields(resource result)
|
||||
Returns the number of fields in a result set */
|
||||
PHP_FUNCTION(sqlite_num_fields)
|
||||
{
|
||||
zval *zres;
|
||||
struct php_sqlite_result *res;
|
||||
|
||||
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
|
||||
|
||||
RETURN_LONG(res->ncolumns);
|
||||
|
||||
}
|
||||
/* }}} */
|
||||
|
||||
/* {{{ proto string sqlite_field_name(resource result, int field)
|
||||
Returns the name of a particular field */
|
||||
PHP_FUNCTION(sqlite_field_name)
|
||||
{
|
||||
zval *zres;
|
||||
struct php_sqlite_result *res;
|
||||
int field;
|
||||
|
||||
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &zres, &field)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
|
||||
|
||||
if (field < 0 || field >= res->ncolumns) {
|
||||
php_error_docref(NULL TSRMLS_CC, E_WARNING, "field %d out of range", field);
|
||||
RETURN_FALSE;
|
||||
}
|
||||
|
||||
RETURN_STRING(res->table[field], 1);
|
||||
}
|
||||
/* }}} */
|
||||
|
||||
/* {{{ proto bool sqlite_seek(resource result, int row)
|
||||
Seek to a particular row number */
|
||||
PHP_FUNCTION(sqlite_seek)
|
||||
{
|
||||
zval *zres;
|
||||
struct php_sqlite_result *res;
|
||||
int row;
|
||||
|
||||
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &zres, &row)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
|
||||
|
||||
if (row < 1 || row >= res->nrows) {
|
||||
php_error_docref(NULL TSRMLS_CC, E_WARNING, "row %d out of range", row);
|
||||
RETURN_FALSE;
|
||||
}
|
||||
|
||||
res->curr_row = row;
|
||||
RETURN_TRUE;
|
||||
}
|
||||
/* }}} */
|
||||
|
||||
/* {{{ proto string sqlite_escape_string(string item)
|
||||
Escapes a string for use as a query parameter */
|
||||
PHP_FUNCTION(sqlite_escape_string)
|
||||
{
|
||||
char *string;
|
||||
long stringlen;
|
||||
char *ret;
|
||||
|
||||
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &string, &stringlen)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ret = sqlite_mprintf("%q", string);
|
||||
|
||||
if (ret) {
|
||||
RETVAL_STRING(ret, 1);
|
||||
sqlite_freemem(ret);
|
||||
}
|
||||
}
|
||||
/* }}} */
|
||||
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
<?php
|
||||
if (!extension_loaded("sqlite")) {
|
||||
dl("sqlite.so");
|
||||
}
|
||||
|
||||
debug_zval_dump(sqlite_libversion());
|
||||
debug_zval_dump(sqlite_libencoding());
|
||||
|
||||
$s = sqlite_open("weztest.sqlite", 0666, $err);
|
||||
|
||||
debug_zval_dump($err);
|
||||
debug_zval_dump($s);
|
||||
|
||||
$r = sqlite_query("create table foo (a INTEGER PRIMARY KEY, b INTEGER )", $s);
|
||||
$r = sqlite_query("select *, php('md5', sql) as o from sqlite_master", $s);
|
||||
debug_zval_dump($r);
|
||||
debug_zval_dump(sqlite_num_rows($r));
|
||||
debug_zval_dump(sqlite_num_fields($r));
|
||||
|
||||
for ($j = 0; $j < sqlite_num_fields($r); $j++) {
|
||||
echo "Field $j is " . sqlite_field_name($r, $j) . "\n";
|
||||
}
|
||||
|
||||
while ($row = sqlite_fetch_array($r, SQLITE_ASSOC)) {
|
||||
print_r($row);
|
||||
}
|
||||
|
||||
sqlite_close($s);
|
||||
|
||||
?>
|
||||
@@ -1,24 +0,0 @@
|
||||
--TEST--
|
||||
Check for sqlite presence
|
||||
--SKIPIF--
|
||||
<?php if (!extension_loaded("sqlite")) print "skip"; ?>
|
||||
--POST--
|
||||
--GET--
|
||||
--INI--
|
||||
--FILE--
|
||||
<?php
|
||||
echo "sqlite extension is available";
|
||||
/*
|
||||
you can add regression tests for your extension here
|
||||
|
||||
the output of your test code has to be equal to the
|
||||
text in the --EXPECT-- section below for the tests
|
||||
to pass, differences between the output and the
|
||||
expected text are interpreted as failure
|
||||
|
||||
see php4/README.TESTING for further information on
|
||||
writing regression tests
|
||||
*/
|
||||
?>
|
||||
--EXPECT--
|
||||
sqlite extension is available
|
||||
@@ -0,0 +1,167 @@
|
||||
/*
|
||||
Build Configuration for Win32.
|
||||
This has only been tested with MS VisualC++ 6 (and later).
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
/* Default PHP / PEAR directories */
|
||||
#define CONFIGURATION_FILE_PATH "php.ini"
|
||||
#define PHP_BINDIR "c:\\php4"
|
||||
#define PHP_PREFIX "c:\\php4"
|
||||
#define PHP_CONFIG_FILE_PATH (getenv("SystemRoot"))?getenv("SystemRoot"):""
|
||||
#define PHP_DATADIR "c:\\php4"
|
||||
#define PHP_EXTENSION_DIR "c:\\php4"
|
||||
#define PHP_INCLUDE_PATH ".;c:\\php4\\pear"
|
||||
#define PHP_LIBDIR "c:\\php4"
|
||||
#define PHP_LOCALSTATEDIR "c:\\php4"
|
||||
#define PHP_SYSCONFDIR "c:\\php4"
|
||||
#define PEAR_INSTALLDIR "c:\\php4\\pear"
|
||||
|
||||
/* Enable / Disable BCMATH extension (default: enabled) */
|
||||
#define WITH_BCMATH 1
|
||||
|
||||
/* Enable / Disable crypt() function (default: enabled) */
|
||||
#define HAVE_CRYPT 1
|
||||
#define PHP_STD_DES_CRYPT 1
|
||||
#define PHP_EXT_DES_CRYPT 0
|
||||
#define PHP_MD5_CRYPT 1
|
||||
#define PHP_BLOWFISH_CRYPT 0
|
||||
|
||||
/* Enable / Disable CALENDAR extension (default: enabled) */
|
||||
#define HAVE_CALENDAR 1
|
||||
|
||||
/* Enable / Disable RPC extension (default: enabled) */
|
||||
#define HAVE_RPC 1
|
||||
|
||||
/* Enable / Disable CTYPE extension (default: enabled) */
|
||||
#define HAVE_CTYPE 1
|
||||
|
||||
/* Enable / Disable FTP extension (default: enabled) */
|
||||
#define HAVE_FTP 1
|
||||
|
||||
/* Enable / Disable MBSTRING extension (default: enabled) */
|
||||
#define HAVE_MBSTRING 1
|
||||
#define HAVE_MBREGEX 1
|
||||
#define HAVE_MBSTR_CN 1
|
||||
#define HAVE_MBSTR_JA 1
|
||||
#define HAVE_MBSTR_KR 1
|
||||
#define HAVE_MBSTR_RU 1
|
||||
#define HAVE_MBSTR_TW 1
|
||||
#define MBSTR_ENC_TRANS 1
|
||||
|
||||
/* Enable / Disable MySQL extension (default: enabled) */
|
||||
#define HAVE_MYSQL 1
|
||||
|
||||
/* Enable / Disable ODBC extension (default: enabled) */
|
||||
#define HAVE_UODBC 1
|
||||
|
||||
/* Enable / Disable OVERLOAD extension (default: enabled) */
|
||||
#define HAVE_OVERLOAD 1
|
||||
|
||||
/* Enable / Disable PCRE extension (default: enabled) */
|
||||
#define HAVE_BUNDLED_PCRE 1
|
||||
#define HAVE_PCRE 1
|
||||
|
||||
/* Enable / Disable SESSION extension (default: enabled) */
|
||||
#define HAVE_SESSION 1
|
||||
|
||||
/* Enable / Disable TOKENIZER extension (default: enabled) */
|
||||
#define HAVE_TOKENIZER 1
|
||||
|
||||
/* Enable / Disable WDDX extension (default: enabled) */
|
||||
#define HAVE_WDDX 1
|
||||
|
||||
/* Enable / Disable XML extension (default: enabled) */
|
||||
#define HAVE_LIBEXPAT 1
|
||||
|
||||
/* PHP Runtime Configuration */
|
||||
#define FORCE_CGI_REDIRECT 1
|
||||
#define PHP_URL_FOPEN 1
|
||||
#define PHP_SAFE_MODE 0
|
||||
#define MAGIC_QUOTES 0
|
||||
#define USE_CONFIG_FILE 1
|
||||
#define DEFAULT_SHORT_OPEN_TAG "1"
|
||||
|
||||
/* Platform-Specific Configuration. Should not be changed. */
|
||||
#define PHP_SIGCHILD 0
|
||||
#define HAVE_LIBBIND 1
|
||||
#define HAVE_GETSERVBYNAME 1
|
||||
#define HAVE_GETSERVBYPORT 1
|
||||
#define HAVE_GETPROTOBYNAME 1
|
||||
#define HAVE_GETPROTOBYNUMBER 1
|
||||
#define STDIN_FILENO 0
|
||||
#define STDOUT_FILENO 1
|
||||
#define STDERR_FILENO 2
|
||||
#define HAVE_ERRMSG_H 0
|
||||
#undef HAVE_ADABAS
|
||||
#undef HAVE_SOLID
|
||||
#undef HAVE_LINK
|
||||
#undef HAVE_SYMLINK
|
||||
#undef HAVE_USLEEP
|
||||
#define HAVE_GETCWD 1
|
||||
#define HAVE_POSIX_READDIR_R 1
|
||||
#define NEED_ISBLANK 1
|
||||
#define DISCARD_PATH 0
|
||||
#undef HAVE_SETITIMER
|
||||
#undef HAVE_IODBC
|
||||
#define HAVE_LIBDL 1
|
||||
#define HAVE_SENDMAIL 1
|
||||
#define HAVE_GETTIMEOFDAY 1
|
||||
#define HAVE_PUTENV 1
|
||||
#define HAVE_LIMITS_H 1
|
||||
#define HAVE_TZSET 1
|
||||
#define HAVE_TZNAME 1
|
||||
#undef HAVE_FLOCK
|
||||
#define HAVE_ALLOCA 1
|
||||
#undef HAVE_SYS_TIME_H
|
||||
#define HAVE_SIGNAL_H 1
|
||||
#undef HAVE_ST_BLKSIZE
|
||||
#undef HAVE_ST_BLOCKS
|
||||
#define HAVE_ST_RDEV 1
|
||||
#define HAVE_UTIME_NULL 1
|
||||
#define HAVE_VPRINTF 1
|
||||
#define STDC_HEADERS 1
|
||||
#define REGEX 1
|
||||
#define HSREGEX 1
|
||||
#define HAVE_GCVT 1
|
||||
#define HAVE_GETLOGIN 1
|
||||
#define HAVE_GETTIMEOFDAY 1
|
||||
#define HAVE_MEMCPY 1
|
||||
#define HAVE_MEMMOVE 1
|
||||
#define HAVE_PUTENV 1
|
||||
#define HAVE_REGCOMP 1
|
||||
#define HAVE_SETLOCALE 1
|
||||
#define HAVE_LOCALECONV 1
|
||||
#define HAVE_LOCALE_H 1
|
||||
#ifndef HAVE_LIBBIND
|
||||
#define HAVE_SETVBUF 1
|
||||
#endif
|
||||
#define HAVE_SHUTDOWN 1
|
||||
#define HAVE_SNPRINTF 1
|
||||
#define HAVE_VSNPRINTF 1
|
||||
#define HAVE_STRCASECMP 1
|
||||
#define HAVE_STRDUP 1
|
||||
#define HAVE_STRERROR 1
|
||||
#define HAVE_STRSTR 1
|
||||
#define HAVE_TEMPNAM 1
|
||||
#define HAVE_UTIME 1
|
||||
#undef HAVE_DIRENT_H
|
||||
#define HAVE_ASSERT_H 1
|
||||
#define HAVE_FCNTL_H 1
|
||||
#define HAVE_GRP_H 0
|
||||
#define HAVE_PWD_H 1
|
||||
#define HAVE_STRING_H 1
|
||||
#undef HAVE_SYS_FILE_H
|
||||
#undef HAVE_SYS_SOCKET_H
|
||||
#undef HAVE_SYS_WAIT_H
|
||||
#define HAVE_SYSLOG_H 1
|
||||
#undef HAVE_UNISTD_H
|
||||
#define HAVE_LIBDL 1
|
||||
#define HAVE_LIBM 1
|
||||
#define HAVE_CUSERID 0
|
||||
#undef HAVE_RINT
|
||||
#define HAVE_STRFTIME 1
|
||||
#define SIZEOF_INT 4
|
||||
#define HAVE_GLOB
|
||||
#define PHP_SHLIB_SUFFIX "dll"
|
||||
@@ -0,0 +1,165 @@
|
||||
/*
|
||||
+----------------------------------------------------------------------+
|
||||
| PHP Version 4 |
|
||||
+----------------------------------------------------------------------+
|
||||
| Copyright (c) 1997-2002 The PHP Group |
|
||||
+----------------------------------------------------------------------+
|
||||
| This source file is subject to version 2.02 of the PHP license, |
|
||||
| that is bundled with this package in the file LICENSE, and is |
|
||||
| available at through the world-wide-web at |
|
||||
| http://www.php.net/license/2_02.txt. |
|
||||
| If you did not receive a copy of the PHP license and are unable to |
|
||||
| obtain it through the world-wide-web, please send a note to |
|
||||
| license@php.net so we can mail you a copy immediately. |
|
||||
+----------------------------------------------------------------------+
|
||||
| Authors: Andi Gutmans <andi@zend.com> |
|
||||
| Zeev Suraski <zeev@zend.com> |
|
||||
+----------------------------------------------------------------------+
|
||||
*/
|
||||
|
||||
|
||||
/* $Id$ */
|
||||
|
||||
/* {{{ includes
|
||||
*/
|
||||
#include "php.h"
|
||||
#include "php_main.h"
|
||||
#include "zend_modules.h"
|
||||
#include "internal_functions_registry.h"
|
||||
#include "zend_compile.h"
|
||||
#include <stdarg.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include "ext/standard/dl.h"
|
||||
#include "ext/standard/file.h"
|
||||
#include "ext/standard/fsock.h"
|
||||
#include "ext/standard/head.h"
|
||||
#include "ext/standard/pack.h"
|
||||
#include "ext/standard/php_browscap.h"
|
||||
#include "ext/standard/php_crypt.h"
|
||||
#include "ext/standard/php_dir.h"
|
||||
#include "ext/standard/php_filestat.h"
|
||||
#include "ext/standard/php_mail.h"
|
||||
#include "ext/standard/php_ext_syslog.h"
|
||||
#include "ext/standard/php_standard.h"
|
||||
#include "ext/standard/php_lcg.h"
|
||||
#include "ext/standard/php_array.h"
|
||||
#include "ext/standard/php_assert.h"
|
||||
#if WITH_BCMATH
|
||||
#include "ext/bcmath/php_bcmath.h"
|
||||
#endif
|
||||
#if HAVE_CALENDAR
|
||||
#include "ext/calendar/php_calendar.h"
|
||||
#endif
|
||||
#if HAVE_CTYPE
|
||||
#include "ext/ctype/php_ctype.h"
|
||||
#endif
|
||||
#if HAVE_COM
|
||||
#include "ext/com/php_COM.h"
|
||||
#endif
|
||||
#if HAVE_RPC
|
||||
#include "ext/rpc/php_rpc.h"
|
||||
#endif
|
||||
#if HAVE_FTP
|
||||
#include "ext/ftp/php_ftp.h"
|
||||
#endif
|
||||
#include "ext/standard/reg.h"
|
||||
#if HAVE_PCRE || HAVE_BUNDLED_PCRE
|
||||
#include "ext/pcre/php_pcre.h"
|
||||
#endif
|
||||
#if HAVE_UODBC
|
||||
#include "ext/odbc/php_odbc.h"
|
||||
#endif
|
||||
#if HAVE_SESSION
|
||||
#include "ext/session/php_session.h"
|
||||
#endif
|
||||
#if HAVE_LIBEXPAT
|
||||
#include "ext/xml/php_xml.h"
|
||||
#endif
|
||||
#if HAVE_LIBEXPAT && HAVE_WDDX
|
||||
#include "ext/wddx/php_wddx.h"
|
||||
#endif
|
||||
#if HAVE_MYSQL
|
||||
#include "ext/mysql/php_mysql.h"
|
||||
#endif
|
||||
#if HAVE_MBSTRING
|
||||
#include "ext/mbstring/mbstring.h"
|
||||
#endif
|
||||
#if HAVE_OVERLOAD
|
||||
#include "ext/overload/php_overload.h"
|
||||
#endif
|
||||
#if HAVE_TOKENIZER
|
||||
#include "ext/tokenizer/php_tokenizer.h"
|
||||
#endif
|
||||
/* }}} */
|
||||
|
||||
/* {{{ php_builtin_extensions[]
|
||||
*/
|
||||
zend_module_entry *php_builtin_extensions[] = {
|
||||
phpext_standard_ptr
|
||||
#if WITH_BCMATH
|
||||
,phpext_bcmath_ptr
|
||||
#endif
|
||||
#if HAVE_CALENDAR
|
||||
,phpext_calendar_ptr
|
||||
#endif
|
||||
#if HAVE_CTYPE
|
||||
,phpext_ctype_ptr
|
||||
#endif
|
||||
#if HAVE_COM
|
||||
,phpext_com_ptr
|
||||
#endif
|
||||
#if HAVE_RPC
|
||||
,phpext_rpc_ptr
|
||||
#endif
|
||||
#if HAVE_FTP
|
||||
,phpext_ftp_ptr
|
||||
#endif
|
||||
#if HAVE_MBSTRING
|
||||
,phpext_mbstring_ptr
|
||||
#endif
|
||||
#if HAVE_MYSQL
|
||||
,phpext_mysql_ptr
|
||||
#endif
|
||||
#if HAVE_UODBC
|
||||
,phpext_odbc_ptr
|
||||
#endif
|
||||
#if HAVE_OVERLOAD
|
||||
,phpext_overload_ptr
|
||||
#endif
|
||||
#if HAVE_PCRE || HAVE_BUNDLED_PCRE
|
||||
,phpext_pcre_ptr
|
||||
#endif
|
||||
#if HAVE_SESSION
|
||||
,phpext_session_ptr
|
||||
#endif
|
||||
#if HAVE_TOKENIZER
|
||||
,phpext_tokenizer_ptr
|
||||
#endif
|
||||
#if HAVE_LIBEXPAT
|
||||
,phpext_xml_ptr
|
||||
#endif
|
||||
#if HAVE_LIBEXPAT && HAVE_WDDX
|
||||
,phpext_wddx_ptr
|
||||
#endif
|
||||
};
|
||||
/* }}} */
|
||||
|
||||
#define EXTCOUNT (sizeof(php_builtin_extensions)/sizeof(zend_module_entry *))
|
||||
|
||||
|
||||
int php_startup_internal_extensions(void)
|
||||
{
|
||||
return php_startup_extensions(php_builtin_extensions, EXTCOUNT);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Local variables:
|
||||
* tab-width: 4
|
||||
* c-basic-offset: 4
|
||||
* End:
|
||||
* vim600: sw=4 ts=4 fdm=marker
|
||||
* vim<600: sw=4 ts=4
|
||||
*/
|
||||
+2223
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user