1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/extensions/sqlite/Makefile Sun Jul 29 01:15:31 2007 +0000
1.3 @@ -0,0 +1,87 @@
1.4 +#(C)2004-2006 SourceMM Development Team
1.5 +# Makefile written by David "BAILOPAN" Anderson
1.6 +
1.7 +SMSDK = ../..
1.8 +SRCDS = ~/srcds
1.9 +SOURCEMM = ../../../../sourcemm
1.10 +
1.11 +#####################################
1.12 +### EDIT BELOW FOR OTHER PROJECTS ###
1.13 +#####################################
1.14 +
1.15 +PROJECT = sample
1.16 +
1.17 +#Uncomment for SourceMM-enabled extensions
1.18 +#LINK_HL2 = $(HL2LIB)/tier1_i486.a vstdlib_i486.so tier0_i486.so
1.19 +
1.20 +OBJECTS = sdk/smsdk_ext.cpp extension.cpp
1.21 +
1.22 +##############################################
1.23 +### CONFIGURE ANY OTHER FLAGS/OPTIONS HERE ###
1.24 +##############################################
1.25 +
1.26 +C_OPT_FLAGS = -O3 -funroll-loops -s -pipe -fno-strict-aliasing
1.27 +C_DEBUG_FLAGS = -g -ggdb3
1.28 +CPP_GCC4_FLAGS = -fvisibility=hidden -fvisibility-inlines-hidden
1.29 +CPP = gcc-4.1
1.30 +
1.31 +HL2PUB = $(HL2SDK)/public
1.32 +HL2LIB = $(HL2SDK)/linux_sdk
1.33 +HL2SDK = $(SOURCEMM)/hl2sdk
1.34 +SMM_TRUNK = $(SOURCEMM)/trunk
1.35 +
1.36 +LINK = $(LINK_HL2) -static-libgcc
1.37 +
1.38 +INCLUDE = -I. -I.. -Isdk -I$(HL2PUB) -I$(HL2PUB)/dlls -I$(HL2PUB)/engine -I$(HL2PUB)/tier0 -I$(HL2PUB)/tier1 \
1.39 + -I$(HL2PUB)/vstdlib -I$(HL2SDK)/tier1 -I$(SMM_TRUNK) -I$(SMM_TRUNK)/sourcehook -I$(SMM_TRUNK)/sourcemm \
1.40 + -I$(SMSDK)/public -I$(SMSDK)/public/sourcepawn -I$(SMSDK)/public/extensions \
1.41 +
1.42 +CFLAGS = -D_LINUX -DNDEBUG -Dstricmp=strcasecmp -D_stricmp=strcasecmp -D_strnicmp=strncasecmp -Dstrnicmp=strncasecmp -D_snprintf=snprintf -D_vsnprintf=vsnprintf -D_alloca=alloca -Dstrcmpi=strcasecmp -Wall -Werror -fPIC -msse -DSOURCEMOD_BUILD -DHAVE_STDINT_H
1.43 +CPPFLAGS = -Wno-non-virtual-dtor -fno-exceptions -fno-rtti
1.44 +
1.45 +################################################
1.46 +### DO NOT EDIT BELOW HERE FOR MOST PROJECTS ###
1.47 +################################################
1.48 +
1.49 +ifeq "$(DEBUG)" "true"
1.50 + BIN_DIR = Debug
1.51 + CFLAGS += $(C_DEBUG_FLAGS)
1.52 +else
1.53 + BIN_DIR = Release
1.54 + CFLAGS += $(C_OPT_FLAGS)
1.55 +endif
1.56 +
1.57 +
1.58 +GCC_VERSION := $(shell $(CPP) -dumpversion >&1 | cut -b1)
1.59 +ifeq "$(GCC_VERSION)" "4"
1.60 + CPPFLAGS += $(CPP_GCC4_FLAGS)
1.61 +endif
1.62 +
1.63 +BINARY = $(PROJECT).ext.so
1.64 +
1.65 +OBJ_LINUX := $(OBJECTS:%.cpp=$(BIN_DIR)/%.o)
1.66 +
1.67 +$(BIN_DIR)/%.o: %.cpp
1.68 + $(CPP) $(INCLUDE) $(CFLAGS) $(CPPFLAGS) -o $@ -c $<
1.69 +
1.70 +all:
1.71 + mkdir -p $(BIN_DIR)/sdk
1.72 + ln -sf $(SRCDS)/bin/vstdlib_i486.so vstdlib_i486.so
1.73 + ln -sf $(SRCDS)/bin/tier0_i486.so tier0_i486.so
1.74 + $(MAKE) extension
1.75 +
1.76 +extension: $(OBJ_LINUX)
1.77 + $(CPP) $(INCLUDE) $(CFLAGS) $(CPPFLAGS) $(OBJ_LINUX) $(LINK) -shared -ldl -lm -o$(BIN_DIR)/$(BINARY)
1.78 +
1.79 +debug:
1.80 + $(MAKE) all DEBUG=true
1.81 +
1.82 +default: all
1.83 +
1.84 +clean:
1.85 + rm -rf Release/*.o
1.86 + rm -rf Release/sdk/*.o
1.87 + rm -rf Release/$(BINARY)
1.88 + rm -rf Debug/*.o
1.89 + rm -rf Debug/sdk/*.o
1.90 + rm -rf Debug/$(BINARY)
2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
2.2 +++ b/extensions/sqlite/driver/SqDatabase.cpp Sun Jul 29 01:15:31 2007 +0000
2.3 @@ -0,0 +1,186 @@
2.4 +/**
2.5 + * vim: set ts=4 :
2.6 + * ===============================================================
2.7 + * SourceMod SQLite Driver Extension
2.8 + * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
2.9 + * ===============================================================
2.10 + *
2.11 + * This program is free software; you can redistribute it and/or
2.12 + * modify it under the terms of the GNU General Public License
2.13 + * as published by the Free Software Foundation; either version 2
2.14 + * of the License, or (at your option) any later version.
2.15 + * This program is distributed in the hope that it will be useful,
2.16 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
2.17 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2.18 + * GNU General Public License for more details.
2.19 + *
2.20 + * You should have received a copy of the GNU General Public License
2.21 + * along with this program; if not, write to the Free Software
2.22 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
2.23 + *
2.24 + * Version: $Id$
2.25 + */
2.26 +
2.27 +#include "extension.h"
2.28 +#include "SqDatabase.h"
2.29 +#include "SqQuery.h"
2.30 +
2.31 +SqDatabase::SqDatabase(sqlite3 *sq3, bool persistent) :
2.32 + m_sq3(sq3), m_refcount(1), m_pFullLock(NULL), m_Persistent(persistent)
2.33 +{
2.34 + m_pRefLock = threader->MakeMutex();
2.35 +}
2.36 +
2.37 +SqDatabase::~SqDatabase()
2.38 +{
2.39 + m_pRefLock->DestroyThis();
2.40 + if (m_pFullLock)
2.41 + {
2.42 + m_pFullLock->DestroyThis();
2.43 + }
2.44 + sqlite3_close(m_sq3);
2.45 +}
2.46 +
2.47 +void SqDatabase::IncReferenceCount()
2.48 +{
2.49 + m_pRefLock->Lock();
2.50 + m_refcount++;
2.51 + m_pRefLock->Unlock();
2.52 +}
2.53 +
2.54 +bool SqDatabase::Close()
2.55 +{
2.56 + m_pRefLock->Lock();
2.57 + if (m_refcount > 1)
2.58 + {
2.59 + m_refcount--;
2.60 + m_pRefLock->Unlock();
2.61 + return false;
2.62 + }
2.63 + m_pRefLock->Unlock();
2.64 +
2.65 + if (m_Persistent)
2.66 + {
2.67 + g_SqDriver.RemovePersistent(this);
2.68 + }
2.69 +
2.70 + delete this;
2.71 +
2.72 + return true;
2.73 +}
2.74 +
2.75 +const char *SqDatabase::GetError(int *errorCode/* =NULL */)
2.76 +{
2.77 + return sqlite3_errmsg(m_sq3);
2.78 +}
2.79 +
2.80 +bool SqDatabase::LockForFullAtomicOperation()
2.81 +{
2.82 + if (!m_pFullLock)
2.83 + {
2.84 + m_pFullLock = threader->MakeMutex();
2.85 + if (!m_pFullLock)
2.86 + {
2.87 + return false;
2.88 + }
2.89 + }
2.90 +
2.91 + m_pFullLock->Lock();
2.92 +
2.93 + return true;
2.94 +}
2.95 +
2.96 +void SqDatabase::UnlockFromFullAtomicOperation()
2.97 +{
2.98 + if (m_pFullLock)
2.99 + {
2.100 + m_pFullLock->Unlock();
2.101 + }
2.102 +}
2.103 +
2.104 +IDBDriver *SqDatabase::GetDriver()
2.105 +{
2.106 + return &g_SqDriver;
2.107 +}
2.108 +
2.109 +bool SqDatabase::QuoteString(const char *str, char buffer[], size_t maxlen, size_t *newSize)
2.110 +{
2.111 + char *res = sqlite3_snprintf(static_cast<int>(maxlen), buffer, "%q", str);
2.112 +
2.113 + if (res != NULL && newSize != NULL)
2.114 + {
2.115 + *newSize = strlen(buffer);
2.116 + }
2.117 +
2.118 + return (res != NULL);
2.119 +}
2.120 +
2.121 +unsigned int SqDatabase::GetInsertID()
2.122 +{
2.123 + return (unsigned int)sqlite3_last_insert_rowid(m_sq3);
2.124 +}
2.125 +
2.126 +unsigned int SqDatabase::GetAffectedRows()
2.127 +{
2.128 + return (unsigned int)sqlite3_changes(m_sq3);
2.129 +}
2.130 +
2.131 +bool SqDatabase::DoSimpleQuery(const char *query)
2.132 +{
2.133 + IQuery *pQuery = DoQuery(query);
2.134 + if (!pQuery)
2.135 + {
2.136 + return false;
2.137 + }
2.138 + pQuery->Destroy();
2.139 + return true;
2.140 +}
2.141 +
2.142 +/* this sounds like daiquiri.. i'm tired. */
2.143 +IQuery *SqDatabase::DoQuery(const char *query)
2.144 +{
2.145 + IPreparedQuery *pQuery = PrepareQuery(query, NULL, 0, NULL);
2.146 + if (!pQuery)
2.147 + {
2.148 + return NULL;
2.149 + }
2.150 + if (!pQuery->Execute())
2.151 + {
2.152 + pQuery->Destroy();
2.153 + return NULL;
2.154 + }
2.155 + return pQuery;
2.156 +}
2.157 +
2.158 +IPreparedQuery *SqDatabase::PrepareQuery(const char *query, char *error, size_t maxlength, int *errCode/* =NULL */)
2.159 +{
2.160 + sqlite3_stmt *stmt = NULL;
2.161 + if ((m_LastErrorCode = sqlite3_prepare_v2(m_sq3, query, -1, &stmt, NULL)) != SQLITE_OK
2.162 + || !stmt)
2.163 + {
2.164 + const char *msg;
2.165 + if (m_LastErrorCode != SQLITE_OK)
2.166 + {
2.167 + msg = sqlite3_errmsg(m_sq3);
2.168 + } else {
2.169 + msg = "Invalid query string";
2.170 + m_LastErrorCode = SQLITE_MISUSE;
2.171 + }
2.172 + if (error)
2.173 + {
2.174 + strncopy(error, msg, maxlength);
2.175 + }
2.176 + m_LastError.assign(msg);
2.177 + if (stmt)
2.178 + {
2.179 + sqlite3_finalize(stmt);
2.180 + }
2.181 + return NULL;
2.182 + }
2.183 + return new SqQuery(this, stmt);
2.184 +}
2.185 +
2.186 +sqlite3 *SqDatabase::GetDb()
2.187 +{
2.188 + return m_sq3;
2.189 +}
3.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3.2 +++ b/extensions/sqlite/driver/SqDatabase.h Sun Jul 29 01:15:31 2007 +0000
3.3 @@ -0,0 +1,60 @@
3.4 +/**
3.5 + * vim: set ts=4 :
3.6 + * ===============================================================
3.7 + * SourceMod SQLite Driver Extension
3.8 + * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
3.9 + * ===============================================================
3.10 + *
3.11 + * This program is free software; you can redistribute it and/or
3.12 + * modify it under the terms of the GNU General Public License
3.13 + * as published by the Free Software Foundation; either version 2
3.14 + * of the License, or (at your option) any later version.
3.15 + * This program is distributed in the hope that it will be useful,
3.16 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
3.17 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
3.18 + * GNU General Public License for more details.
3.19 + *
3.20 + * You should have received a copy of the GNU General Public License
3.21 + * along with this program; if not, write to the Free Software
3.22 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
3.23 + *
3.24 + * Version: $Id$
3.25 + */
3.26 +
3.27 +#ifndef _INCLUDE_SQLITE_SOURCEMOD_DATABASE_H_
3.28 +#define _INCLUDE_SQLITE_SOURCEMOD_DATABASE_H_
3.29 +
3.30 +#include <IThreader.h>
3.31 +#include "SqDriver.h"
3.32 +
3.33 +class SqDatabase : public IDatabase
3.34 +{
3.35 +public:
3.36 + SqDatabase(sqlite3 *sq3, bool persistent);
3.37 + ~SqDatabase();
3.38 +public:
3.39 + bool Close();
3.40 + const char *GetError(int *errorCode=NULL);
3.41 + bool DoSimpleQuery(const char *query);
3.42 + IQuery *DoQuery(const char *query);
3.43 + IPreparedQuery *PrepareQuery(const char *query, char *error, size_t maxlength, int *errCode=NULL);
3.44 + bool QuoteString(const char *str, char buffer[], size_t maxlen, size_t *newSize);
3.45 + unsigned int GetAffectedRows();
3.46 + unsigned int GetInsertID();
3.47 + bool LockForFullAtomicOperation();
3.48 + void UnlockFromFullAtomicOperation();
3.49 + void IncReferenceCount();
3.50 + IDBDriver *GetDriver();
3.51 +public:
3.52 + sqlite3 *GetDb();
3.53 +private:
3.54 + sqlite3 *m_sq3;
3.55 + unsigned int m_refcount;
3.56 + IMutex *m_pFullLock;
3.57 + IMutex *m_pRefLock;
3.58 + bool m_Persistent;
3.59 + String m_LastError;
3.60 + int m_LastErrorCode;
3.61 +};
3.62 +
3.63 +#endif //_INCLUDE_SQLITE_SOURCEMOD_DATABASE_H_
4.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
4.2 +++ b/extensions/sqlite/driver/SqDriver.cpp Sun Jul 29 01:15:31 2007 +0000
4.3 @@ -0,0 +1,244 @@
4.4 +/**
4.5 + * vim: set ts=4 :
4.6 + * ===============================================================
4.7 + * SourceMod SQLite Driver Extension
4.8 + * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
4.9 + * ===============================================================
4.10 + *
4.11 + * This program is free software; you can redistribute it and/or
4.12 + * modify it under the terms of the GNU General Public License
4.13 + * as published by the Free Software Foundation; either version 2
4.14 + * of the License, or (at your option) any later version.
4.15 + * This program is distributed in the hope that it will be useful,
4.16 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
4.17 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4.18 + * GNU General Public License for more details.
4.19 + *
4.20 + * You should have received a copy of the GNU General Public License
4.21 + * along with this program; if not, write to the Free Software
4.22 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
4.23 + *
4.24 + * Version: $Id$
4.25 + */
4.26 +
4.27 +#include <sm_platform.h>
4.28 +#include "extension.h"
4.29 +#include "SqDriver.h"
4.30 +#include "SqDatabase.h"
4.31 +
4.32 +SqDriver g_SqDriver;
4.33 +
4.34 +unsigned int strncopy(char *dest, const char *src, size_t count)
4.35 +{
4.36 + if (!count)
4.37 + {
4.38 + return 0;
4.39 + }
4.40 +
4.41 + char *start = dest;
4.42 + while ((*src) && (--count))
4.43 + {
4.44 + *dest++ = *src++;
4.45 + }
4.46 + *dest = '\0';
4.47 +
4.48 + return (dest - start);
4.49 +}
4.50 +
4.51 +SqDriver::SqDriver()
4.52 +{
4.53 + m_Handle = BAD_HANDLE;
4.54 + m_pOpenLock = NULL;
4.55 +}
4.56 +
4.57 +void SqDriver::Initialize()
4.58 +{
4.59 + m_pOpenLock = threader->MakeMutex();
4.60 +}
4.61 +
4.62 +void SqDriver::Shutdown()
4.63 +{
4.64 + if (m_pOpenLock)
4.65 + {
4.66 + m_pOpenLock->DestroyThis();
4.67 + }
4.68 +}
4.69 +
4.70 +bool SqDriver::IsThreadSafe()
4.71 +{
4.72 + return true;
4.73 +}
4.74 +
4.75 +bool SqDriver::InitializeThreadSafety()
4.76 +{
4.77 + /* sqlite should be thread safe if the locks are done right.
4.78 + * we don't enable the "shared cache" because it can corrupt
4.79 + * open databases!
4.80 + */
4.81 + return true;
4.82 +}
4.83 +
4.84 +void SqDriver::ShutdownThreadSafety()
4.85 +{
4.86 + return;
4.87 +}
4.88 +
4.89 +IdentityToken_t *SqDriver::GetIdentity()
4.90 +{
4.91 + return myself->GetIdentity();
4.92 +}
4.93 +
4.94 +const char *SqDriver::GetProductName()
4.95 +{
4.96 + return "SQLite";
4.97 +}
4.98 +
4.99 +const char *SqDriver::GetIdentifier()
4.100 +{
4.101 + return "sqlite";
4.102 +}
4.103 +
4.104 +Handle_t SqDriver::GetHandle()
4.105 +{
4.106 + if (m_Handle == BAD_HANDLE)
4.107 + {
4.108 + m_Handle = dbi->CreateHandle(DBHandle_Driver, this, myself->GetIdentity());
4.109 + }
4.110 +
4.111 + return m_Handle;
4.112 +}
4.113 +
4.114 +inline bool IsPathSepChar(char c)
4.115 +{
4.116 +#if defined PLATFORM_WINDOWS
4.117 + return (c == '\\' || c == '/');
4.118 +#elif defined PLATFORM_LINUX
4.119 + return (c == '/');
4.120 +#endif
4.121 +}
4.122 +
4.123 +IDatabase *SqDriver::Connect(const DatabaseInfo *info, bool persistent, char *error, size_t maxlength)
4.124 +{
4.125 + /* We wrap most of the open process in a mutex just to be safe */
4.126 + m_pOpenLock->Lock();
4.127 +
4.128 + /* Format our path */
4.129 + char path[PLATFORM_MAX_PATH];
4.130 + size_t len = libsys->PathFormat(path, sizeof(path), "sqlite/%s", info->database);
4.131 +
4.132 + /* Chop any filename off */
4.133 + for (size_t i = len-1;
4.134 + i >= 0 && i <= len-1;
4.135 + i--)
4.136 + {
4.137 + if (IsPathSepChar(path[i]))
4.138 + {
4.139 + path[i] = '\0';
4.140 + break;
4.141 + }
4.142 + }
4.143 +
4.144 + /* Test the full path */
4.145 + char fullpath[PLATFORM_MAX_PATH];
4.146 + g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "data/%s", path);
4.147 + if (!libsys->IsPathDirectory(fullpath))
4.148 + {
4.149 + /* Make sure the data folder exists */
4.150 + len = g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "data");
4.151 + if (!libsys->IsPathDirectory(fullpath))
4.152 + {
4.153 + if (!libsys->CreateFolder(fullpath))
4.154 + {
4.155 + strncopy(error, "Could not create or open \"data\" folder\"", maxlength);
4.156 + m_pOpenLock->Unlock();
4.157 + return NULL;
4.158 + }
4.159 + }
4.160 +
4.161 + /* The data folder exists - create each subdir as needed! */
4.162 + char *cur_ptr = path;
4.163 +
4.164 + do
4.165 + {
4.166 + /* Find the next suitable path */
4.167 + char *next_ptr = cur_ptr;
4.168 + while (*next_ptr != '\0')
4.169 + {
4.170 + if (IsPathSepChar(*next_ptr))
4.171 + {
4.172 + *next_ptr = '\0';
4.173 + next_ptr++;
4.174 + break;
4.175 + }
4.176 + next_ptr++;
4.177 + }
4.178 + if (*next_ptr == '\0')
4.179 + {
4.180 + next_ptr = NULL;
4.181 + }
4.182 + len += libsys->PathFormat(&fullpath[len], sizeof(fullpath)-len, "/%s", cur_ptr);
4.183 + if (!libsys->IsPathDirectory(fullpath) && !libsys->CreateFolder(fullpath))
4.184 + {
4.185 + break;
4.186 + }
4.187 + cur_ptr = next_ptr;
4.188 + } while (cur_ptr);
4.189 + }
4.190 +
4.191 + /* Build the FINAL path. */
4.192 + g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "data/sqlite/%s.sq3", info->database);
4.193 +
4.194 + /* If we're requesting a persistent connection, see if something is already open */
4.195 + if (persistent)
4.196 + {
4.197 + /* See if anything in the cache matches */
4.198 + List<SqDbInfo>::iterator iter;
4.199 + for (iter = m_Cache.begin(); iter != m_Cache.end(); iter++)
4.200 + {
4.201 + if ((*iter).path.compare(fullpath) == 0)
4.202 + {
4.203 + (*iter).db->IncReferenceCount();
4.204 + m_pOpenLock->Unlock();
4.205 + return (*iter).db;
4.206 + }
4.207 + }
4.208 + }
4.209 +
4.210 + /* Try to open a new connection */
4.211 + sqlite3 *sql;
4.212 + int err = sqlite3_open(fullpath, &sql);
4.213 + if (err != SQLITE_OK)
4.214 + {
4.215 + strncopy(error, sqlite3_errmsg(sql), maxlength);
4.216 + sqlite3_close(sql);
4.217 + m_pOpenLock->Unlock();
4.218 + return NULL;
4.219 + }
4.220 +
4.221 + SqDatabase *pdb = new SqDatabase(sql, persistent);
4.222 +
4.223 + if (persistent)
4.224 + {
4.225 + SqDbInfo pinfo;
4.226 + pinfo.path = fullpath;
4.227 + pinfo.db = pdb;
4.228 + m_Cache.push_back(pinfo);
4.229 + }
4.230 +
4.231 + m_pOpenLock->Unlock();
4.232 +
4.233 + return pdb;
4.234 +}
4.235 +
4.236 +void SqDriver::RemovePersistent(IDatabase *pdb)
4.237 +{
4.238 + List<SqDbInfo>::iterator iter;
4.239 + for (iter = m_Cache.begin(); iter != m_Cache.end(); iter++)
4.240 + {
4.241 + if ((*iter).db == pdb)
4.242 + {
4.243 + iter = m_Cache.erase(iter);
4.244 + return;
4.245 + }
4.246 + }
4.247 +}
5.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
5.2 +++ b/extensions/sqlite/driver/SqDriver.h Sun Jul 29 01:15:31 2007 +0000
5.3 @@ -0,0 +1,73 @@
5.4 +/**
5.5 + * vim: set ts=4 :
5.6 + * ===============================================================
5.7 + * SourceMod SQLite Driver Extension
5.8 + * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
5.9 + * ===============================================================
5.10 + *
5.11 + * This program is free software; you can redistribute it and/or
5.12 + * modify it under the terms of the GNU General Public License
5.13 + * as published by the Free Software Foundation; either version 2
5.14 + * of the License, or (at your option) any later version.
5.15 + * This program is distributed in the hope that it will be useful,
5.16 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
5.17 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
5.18 + * GNU General Public License for more details.
5.19 + *
5.20 + * You should have received a copy of the GNU General Public License
5.21 + * along with this program; if not, write to the Free Software
5.22 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
5.23 + *
5.24 + * Version: $Id$
5.25 + */
5.26 +
5.27 +#ifndef _INCLUDE_SQLITE_SOURCEMOD_DRIVER_H_
5.28 +#define _INCLUDE_SQLITE_SOURCEMOD_DRIVER_H_
5.29 +
5.30 +#include <IDBDriver.h>
5.31 +#include <IThreader.h>
5.32 +#include <sh_list.h>
5.33 +#include <sh_string.h>
5.34 +#include "sqlite-source/sqlite3.h"
5.35 +
5.36 +using namespace SourceMod;
5.37 +using namespace SourceHook;
5.38 +
5.39 +struct SqDbInfo
5.40 +{
5.41 + String path;
5.42 + IDatabase *db;
5.43 +};
5.44 +
5.45 +/**
5.46 + * Tee-hee.. sounds like "screw driver," except maybe if
5.47 + * Elmer Fudd was saying it.
5.48 + */
5.49 +class SqDriver : public IDBDriver
5.50 +{
5.51 +public:
5.52 + SqDriver();
5.53 + void Initialize();
5.54 + void Shutdown();
5.55 +public:
5.56 + IDatabase *Connect(const DatabaseInfo *info, bool persistent, char *error, size_t maxlength);
5.57 + const char *GetIdentifier();
5.58 + const char *GetProductName();
5.59 + Handle_t GetHandle();
5.60 + IdentityToken_t *GetIdentity();
5.61 + bool IsThreadSafe();
5.62 + bool InitializeThreadSafety();
5.63 + void ShutdownThreadSafety();
5.64 +public:
5.65 + void RemovePersistent(IDatabase *pdb);
5.66 +private:
5.67 + Handle_t m_Handle;
5.68 + IMutex *m_pOpenLock;
5.69 + List<SqDbInfo> m_Cache;
5.70 +};
5.71 +
5.72 +extern SqDriver g_SqDriver;
5.73 +
5.74 +unsigned int strncopy(char *dest, const char *src, size_t count);
5.75 +
5.76 +#endif //_INCLUDE_SQLITE_SOURCEMOD_DRIVER_H_
6.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
6.2 +++ b/extensions/sqlite/driver/SqQuery.cpp Sun Jul 29 01:15:31 2007 +0000
6.3 @@ -0,0 +1,186 @@
6.4 +/**
6.5 + * vim: set ts=4 :
6.6 + * ===============================================================
6.7 + * SourceMod SQLite Driver Extension
6.8 + * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
6.9 + * ===============================================================
6.10 + *
6.11 + * This program is free software; you can redistribute it and/or
6.12 + * modify it under the terms of the GNU General Public License
6.13 + * as published by the Free Software Foundation; either version 2
6.14 + * of the License, or (at your option) any later version.
6.15 + * This program is distributed in the hope that it will be useful,
6.16 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
6.17 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
6.18 + * GNU General Public License for more details.
6.19 + *
6.20 + * You should have received a copy of the GNU General Public License
6.21 + * along with this program; if not, write to the Free Software
6.22 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
6.23 + *
6.24 + * Version: $Id$
6.25 + */
6.26 +
6.27 +#include "SqQuery.h"
6.28 +
6.29 +SqQuery::SqQuery(SqDatabase *parent, sqlite3_stmt *stmt) :
6.30 + m_pParent(parent), m_pStmt(stmt), m_pResults(NULL), m_AffectedRows(0), m_InsertID(0)
6.31 +{
6.32 + m_ParamCount = sqlite3_bind_parameter_count(m_pStmt);
6.33 + m_pParent->IncReferenceCount();
6.34 +}
6.35 +
6.36 +SqQuery::~SqQuery()
6.37 +{
6.38 + delete m_pResults;
6.39 + sqlite3_finalize(m_pStmt);
6.40 + m_pParent->Close();
6.41 +}
6.42 +
6.43 +IResultSet *SqQuery::GetResultSet()
6.44 +{
6.45 + return m_pResults;
6.46 +}
6.47 +
6.48 +bool SqQuery::FetchMoreResults()
6.49 +{
6.50 + /* We never have multiple result sets */
6.51 + return false;
6.52 +}
6.53 +
6.54 +void SqQuery::Destroy()
6.55 +{
6.56 + delete this;
6.57 +}
6.58 +
6.59 +bool SqQuery::BindParamFloat(unsigned int param, float f)
6.60 +{
6.61 + /* SQLite is 1 indexed */
6.62 + param++;
6.63 +
6.64 + if (param > m_ParamCount)
6.65 + {
6.66 + return false;
6.67 + }
6.68 +
6.69 + return (sqlite3_bind_double(m_pStmt, param, (double)f) == SQLITE_OK);
6.70 +}
6.71 +
6.72 +bool SqQuery::BindParamNull(unsigned int param)
6.73 +{
6.74 + /* SQLite is 1 indexed */
6.75 + param++;
6.76 +
6.77 + if (param > m_ParamCount)
6.78 + {
6.79 + return false;
6.80 + }
6.81 +
6.82 + return (sqlite3_bind_null(m_pStmt, param) == SQLITE_OK);
6.83 +}
6.84 +
6.85 +bool SqQuery::BindParamString(unsigned int param, const char *text, bool copy)
6.86 +{
6.87 + /* SQLite is 1 indexed */
6.88 + param++;
6.89 +
6.90 + if (param > m_ParamCount)
6.91 + {
6.92 + return false;
6.93 + }
6.94 +
6.95 + return (sqlite3_bind_text(m_pStmt, param, text, -1, copy ? SQLITE_TRANSIENT : SQLITE_STATIC) == SQLITE_OK);
6.96 +}
6.97 +
6.98 +bool SqQuery::BindParamInt(unsigned int param, int num, bool signd/* =true */)
6.99 +{
6.100 + /* SQLite is 1 indexed */
6.101 + param++;
6.102 +
6.103 + if (param > m_ParamCount)
6.104 + {
6.105 + return false;
6.106 + }
6.107 +
6.108 + return (sqlite3_bind_int(m_pStmt, param, num) == SQLITE_OK);
6.109 +}
6.110 +
6.111 +bool SqQuery::BindParamBlob(unsigned int param, const void *data, size_t length, bool copy)
6.112 +{
6.113 + /* SQLite is 1 indexed */
6.114 + param++;
6.115 +
6.116 + if (param > m_ParamCount)
6.117 + {
6.118 + return false;
6.119 + }
6.120 +
6.121 + return (sqlite3_bind_blob(m_pStmt, param, data, length, copy ? SQLITE_TRANSIENT : SQLITE_STATIC) == SQLITE_OK);
6.122 +}
6.123 +
6.124 +sqlite3_stmt *SqQuery::GetStmt()
6.125 +{
6.126 + return m_pStmt;
6.127 +}
6.128 +
6.129 +bool SqQuery::Execute()
6.130 +{
6.131 + int rc;
6.132 +
6.133 + /* If we've got results, throw them away */
6.134 + if (m_pResults)
6.135 + {
6.136 + m_pResults->ResetResultCount();
6.137 + }
6.138 +
6.139 + while ((rc = sqlite3_step(m_pStmt)) == SQLITE_ROW)
6.140 + {
6.141 + /* Delay creation as long as possible... */
6.142 + if (!m_pResults)
6.143 + {
6.144 + m_pResults = new SqResults(this);
6.145 + }
6.146 + m_pResults->PushResult();
6.147 + }
6.148 +
6.149 + sqlite3 *db = m_pParent->GetDb();
6.150 + if (rc != SQLITE_OK && rc != SQLITE_DONE && rc == sqlite3_errcode(db))
6.151 + {
6.152 + /* Something happened... */
6.153 + m_LastErrorCode = rc;
6.154 + m_LastError.assign(sqlite3_errmsg(db));
6.155 + m_AffectedRows = 0;
6.156 + m_InsertID = 0;
6.157 + } else {
6.158 + m_LastErrorCode = SQLITE_OK;
6.159 + m_AffectedRows = (unsigned int)sqlite3_changes(db);
6.160 + m_InsertID = (unsigned int)sqlite3_last_insert_rowid(db);
6.161 + }
6.162 +
6.163 + /* Reset everything for the next execute */
6.164 + sqlite3_reset(m_pStmt);
6.165 + sqlite3_clear_bindings(m_pStmt);
6.166 +
6.167 + return (m_LastErrorCode == SQLITE_OK);
6.168 +}
6.169 +
6.170 +const char *SqQuery::GetError(int *errCode/* =NULL */)
6.171 +{
6.172 + if (errCode)
6.173 + {
6.174 + *errCode = m_LastErrorCode;
6.175 + }
6.176 + return m_LastError.c_str();
6.177 +}
6.178 +
6.179 +unsigned int SqQuery::GetAffectedRows()
6.180 +{
6.181 + return m_AffectedRows;
6.182 +}
6.183 +
6.184 +unsigned int SqQuery::GetInsertID()
6.185 +{
6.186 + return m_InsertID;
6.187 +}
6.188 +
6.189 +
7.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
7.2 +++ b/extensions/sqlite/driver/SqQuery.h Sun Jul 29 01:15:31 2007 +0000
7.3 @@ -0,0 +1,86 @@
7.4 +/**
7.5 + * vim: set ts=4 :
7.6 + * ===============================================================
7.7 + * SourceMod SQLite Driver Extension
7.8 + * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
7.9 + * ===============================================================
7.10 + *
7.11 + * This program is free software; you can redistribute it and/or
7.12 + * modify it under the terms of the GNU General Public License
7.13 + * as published by the Free Software Foundation; either version 2
7.14 + * of the License, or (at your option) any later version.
7.15 + * This program is distributed in the hope that it will be useful,
7.16 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
7.17 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7.18 + * GNU General Public License for more details.
7.19 + *
7.20 + * You should have received a copy of the GNU General Public License
7.21 + * along with this program; if not, write to the Free Software
7.22 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
7.23 + *
7.24 + * Version: $Id$
7.25 + */
7.26 +
7.27 +#ifndef _INCLUDE_SQLITE_SOURCEMOD_QUERY_H_
7.28 +#define _INCLUDE_SQLITE_SOURCEMOD_QUERY_H_
7.29 +
7.30 +#include "SqDatabase.h"
7.31 +#include "SqResults.h"
7.32 +
7.33 +class SqQuery :
7.34 + public IPreparedQuery
7.35 +{
7.36 +public:
7.37 + SqQuery(SqDatabase *parent, sqlite3_stmt *stmt);
7.38 + ~SqQuery();
7.39 +public: //IQuery
7.40 + IResultSet *GetResultSet();
7.41 + bool FetchMoreResults();
7.42 + void Destroy();
7.43 +public: //IPreparedQuery
7.44 + bool BindParamInt(unsigned int param, int num, bool signd=true);
7.45 + bool BindParamFloat(unsigned int param, float f);
7.46 + bool BindParamNull(unsigned int param);
7.47 + bool BindParamString(unsigned int param, const char *text, bool copy);
7.48 + bool BindParamBlob(unsigned int param, const void *data, size_t length, bool copy);
7.49 + bool Execute();
7.50 + const char *GetError(int *errCode=NULL);
7.51 + unsigned int GetAffectedRows();
7.52 + unsigned int GetInsertID();
7.53 +public: //IResultSet
7.54 + unsigned int GetRowCount();
7.55 + unsigned int GetFieldCount();
7.56 + const char *FieldNumToName(unsigned int columnId);
7.57 + bool FieldNameToNum(const char *name, unsigned int *columnId);
7.58 + bool MoreRows();
7.59 + IResultRow *FetchRow();
7.60 + IResultRow *CurrentRow();
7.61 + bool Rewind();
7.62 + DBType GetFieldType(unsigned int field);
7.63 + DBType GetFieldDataType(unsigned int field);
7.64 +public: //IResultRow
7.65 + DBResult GetString(unsigned int columnId, const char **pString, size_t *length);
7.66 + DBResult CopyString(unsigned int columnId,
7.67 + char *buffer,
7.68 + size_t maxlength,
7.69 + size_t *written);
7.70 + DBResult GetFloat(unsigned int columnId, float *pFloat);
7.71 + DBResult GetInt(unsigned int columnId, int *pInt);
7.72 + bool IsNull(unsigned int columnId);
7.73 + size_t GetDataSize(unsigned int columnId);
7.74 + DBResult GetBlob(unsigned int columnId, const void **pData, size_t *length);
7.75 + DBResult CopyBlob(unsigned int columnId, void *buffer, size_t maxlength, size_t *written);
7.76 +public:
7.77 + sqlite3_stmt *GetStmt();
7.78 +private:
7.79 + SqDatabase *m_pParent;
7.80 + sqlite3_stmt *m_pStmt;
7.81 + SqResults *m_pResults;
7.82 + unsigned int m_ParamCount;
7.83 + String m_LastError;
7.84 + int m_LastErrorCode;
7.85 + unsigned int m_AffectedRows;
7.86 + unsigned int m_InsertID;
7.87 +};
7.88 +
7.89 +#endif //_INCLUDE_SQLITE_SOURCEMOD_QUERY_H_
8.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
8.2 +++ b/extensions/sqlite/driver/SqResults.cpp Sun Jul 29 01:15:31 2007 +0000
8.3 @@ -0,0 +1,474 @@
8.4 +/**
8.5 + * vim: set ts=4 :
8.6 + * ===============================================================
8.7 + * SourceMod SQLite Driver Extension
8.8 + * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
8.9 + * ===============================================================
8.10 + *
8.11 + * This program is free software; you can redistribute it and/or
8.12 + * modify it under the terms of the GNU General Public License
8.13 + * as published by the Free Software Foundation; either version 2
8.14 + * of the License, or (at your option) any later version.
8.15 + * This program is distributed in the hope that it will be useful,
8.16 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
8.17 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
8.18 + * GNU General Public License for more details.
8.19 + *
8.20 + * You should have received a copy of the GNU General Public License
8.21 + * along with this program; if not, write to the Free Software
8.22 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
8.23 + *
8.24 + * Version: $Id$
8.25 + */
8.26 +
8.27 +#include <stdlib.h>
8.28 +#include "extension.h"
8.29 +#include "SqResults.h"
8.30 +#include "SqQuery.h"
8.31 +
8.32 +SqResults::SqResults(SqQuery *query) :
8.33 + m_pStmt(query->GetStmt()), m_Strings(1024),
8.34 + m_RowCount(0), m_MaxRows(0), m_Rows(NULL),
8.35 + m_CurRow(0), m_NextRow(0)
8.36 +{
8.37 + m_ColCount = sqlite3_column_count(m_pStmt);
8.38 + if (m_ColCount)
8.39 + {
8.40 + m_ColNames = new String[m_ColCount];
8.41 + for (unsigned int i=0; i<m_ColCount; i++)
8.42 + {
8.43 + m_ColNames[i].assign(sqlite3_column_name(m_pStmt, i));
8.44 + }
8.45 + } else {
8.46 + m_ColNames = NULL;
8.47 + }
8.48 +
8.49 + m_pMemory = m_Strings.GetMemTable();
8.50 +}
8.51 +
8.52 +SqResults::~SqResults()
8.53 +{
8.54 + delete [] m_ColNames;
8.55 + free(m_Rows);
8.56 +}
8.57 +
8.58 +unsigned int SqResults::GetRowCount()
8.59 +{
8.60 + return m_RowCount;
8.61 +}
8.62 +
8.63 +unsigned int SqResults::GetFieldCount()
8.64 +{
8.65 + return m_ColCount;
8.66 +}
8.67 +
8.68 +const char *SqResults::FieldNumToName(unsigned int columnId)
8.69 +{
8.70 + if (columnId >= m_ColCount)
8.71 + {
8.72 + return NULL;
8.73 + }
8.74 +
8.75 + return m_ColNames[columnId].c_str();
8.76 +}
8.77 +
8.78 +bool SqResults::FieldNameToNum(const char *name, unsigned int *columnId)
8.79 +{
8.80 + for (unsigned int i=0; i<m_ColCount; i++)
8.81 + {
8.82 + if (m_ColNames[i].compare(name) == 0)
8.83 + {
8.84 + if (columnId)
8.85 + {
8.86 + *columnId = i;
8.87 + }
8.88 + return true;
8.89 + }
8.90 + }
8.91 + return false;
8.92 +}
8.93 +
8.94 +void SqResults::ResetResultCount()
8.95 +{
8.96 + m_RowCount = 0;
8.97 + m_CurRow = 0;
8.98 + m_NextRow = 0;
8.99 + m_pMemory->Reset();
8.100 +}
8.101 +
8.102 +void SqResults::PushResult()
8.103 +{
8.104 + /* First make sure we can fit one more row */
8.105 + if (m_RowCount + 1 > m_MaxRows)
8.106 + {
8.107 + /* Create a new array */
8.108 + if (!m_Rows)
8.109 + {
8.110 + m_MaxRows = 8;
8.111 + m_Rows = (SqField *)malloc(sizeof(SqField) * m_ColCount * m_MaxRows);
8.112 + } else {
8.113 + m_MaxRows *= 2;
8.114 + m_Rows = (SqField *)realloc(m_Rows, sizeof(SqField) * m_ColCount * m_MaxRows);
8.115 + }
8.116 + }
8.117 +
8.118 + SqField *row = &m_Rows[m_RowCount * m_ColCount];
8.119 + for (unsigned int i=0; i<m_ColCount; i++)
8.120 + {
8.121 + row[i].type = sqlite3_column_type(m_pStmt, i);
8.122 + if (row[i].type == SQLITE_INTEGER)
8.123 + {
8.124 + row[i].u.idx = sqlite3_column_int(m_pStmt, i);
8.125 + row[i].size = sizeof(int);
8.126 + } else if (row[i].type == SQLITE_FLOAT) {
8.127 + row[i].u.f = (float)sqlite3_column_double(m_pStmt, i);
8.128 + row[i].size = sizeof(float);
8.129 + } else if (row[i].type == SQLITE_BLOB) {
8.130 + int bytes = sqlite3_column_bytes(m_pStmt, i);
8.131 + const void *pOrig;
8.132 + if ((pOrig = sqlite3_column_blob(m_pStmt, i)) != NULL)
8.133 + {
8.134 + void *pAddr;
8.135 + row[i].u.idx = m_pMemory->CreateMem(bytes, &pAddr);
8.136 + memcpy(pAddr, pOrig, bytes);
8.137 + } else {
8.138 + row[i].u.idx = -1;
8.139 + }
8.140 + row[i].size = sqlite3_column_bytes(m_pStmt, i);
8.141 + } else if (row[i].type == SQLITE_TEXT) {
8.142 + const char *str = (const char *)sqlite3_column_text(m_pStmt, i);
8.143 + if (str)
8.144 + {
8.145 + row[i].u.idx = m_Strings.AddString(str);
8.146 + } else {
8.147 + row[i].u.idx = -1;
8.148 + }
8.149 + row[i].size = sqlite3_column_bytes(m_pStmt, i);
8.150 + } else {
8.151 + row[i].size = 0;
8.152 + }
8.153 + }
8.154 +
8.155 + /* Finally, increase the row count */
8.156 + m_RowCount++;
8.157 +}
8.158 +
8.159 +bool SqResults::MoreRows()
8.160 +{
8.161 + return (m_CurRow < m_RowCount);
8.162 +}
8.163 +
8.164 +IResultRow *SqResults::FetchRow()
8.165 +{
8.166 + m_CurRow = m_NextRow;
8.167 + if (m_CurRow >= m_RowCount)
8.168 + {
8.169 + return NULL;
8.170 + }
8.171 + m_NextRow++;
8.172 + return this;
8.173 +}
8.174 +
8.175 +IResultRow *SqResults::CurrentRow()
8.176 +{
8.177 + if (!m_RowCount || m_CurRow >= m_RowCount)
8.178 + {
8.179 + return NULL;
8.180 + }
8.181 + return this;
8.182 +}
8.183 +
8.184 +bool SqResults::Rewind()
8.185 +{
8.186 + m_CurRow = 0;
8.187 + m_NextRow = 0;
8.188 + return true;
8.189 +}
8.190 +
8.191 +SqField *SqResults::GetField(unsigned int col)
8.192 +{
8.193 + if (m_CurRow >= m_RowCount || col >= m_ColCount)
8.194 + {
8.195 + return NULL;
8.196 + }
8.197 +
8.198 + return &m_Rows[(m_CurRow * m_ColCount) + col];
8.199 +}
8.200 +
8.201 +DBType SqResults::GetFieldType(unsigned int field)
8.202 +{
8.203 + /* Leaving unimplemented... */
8.204 + return DBType_Unknown;
8.205 +}
8.206 +
8.207 +DBType SqResults::GetFieldDataType(unsigned int field)
8.208 +{
8.209 + /* Leaving unimplemented... */
8.210 + return DBType_Unknown;
8.211 +}
8.212 +
8.213 +DBResult SqResults::GetString(unsigned int columnId, const char **pString, size_t *_length)
8.214 +{
8.215 + SqField *field = GetField(columnId);
8.216 + if (!field)
8.217 + {
8.218 + return DBVal_Error;
8.219 + }
8.220 +
8.221 + DBResult res = DBVal_Data;
8.222 + const char *ptr = NULL;
8.223 + size_t length = 0;
8.224 + if (field->type == SQLITE_TEXT || field->type == SQLITE_BLOB)
8.225 + {
8.226 + ptr = m_Strings.GetString(field->u.idx);
8.227 + length = field->size;
8.228 + } else if (field->type == SQLITE_INTEGER) {
8.229 + char number[24];
8.230 + field->size = UTIL_Format(number, sizeof(number), "%d", field->u.idx);
8.231 + field->type = SQLITE_TEXT;
8.232 + field->u.idx = m_Strings.AddString(number);
8.233 + ptr = m_Strings.GetString(field->u.idx);
8.234 + length = field->size;
8.235 + } else if (field->type == SQLITE_FLOAT) {
8.236 + char number[24];
8.237 + field->size = UTIL_Format(number, sizeof(number), "%f", field->u.f);
8.238 + field->type = SQLITE_TEXT;
8.239 + field->u.idx = m_Strings.AddString(number);
8.240 + ptr = m_Strings.GetString(field->u.idx);
8.241 + length = field->size;
8.242 + } else if (field->type == SQLITE_NULL) {
8.243 + res = DBVal_Null;
8.244 + }
8.245 +
8.246 + if (!ptr)
8.247 + {
8.248 + ptr = "";
8.249 + }
8.250 +
8.251 + if (*pString)
8.252 + {
8.253 + *pString = ptr;
8.254 + }
8.255 + if (_length)
8.256 + {
8.257 + *_length = length;
8.258 + }
8.259 +
8.260 + return res;
8.261 +}
8.262 +
8.263 +DBResult SqResults::CopyString(unsigned int columnId, char *buffer, size_t maxlength, size_t *written)
8.264 +{
8.265 + SqField *field = GetField(columnId);
8.266 + if (!field)
8.267 + {
8.268 + return DBVal_Error;
8.269 + }
8.270 +
8.271 + DBResult res = DBVal_Data;
8.272 + if (field->type == SQLITE_TEXT || field->type == SQLITE_BLOB)
8.273 + {
8.274 + const char *ptr = m_Strings.GetString(field->u.idx);
8.275 + if (!ptr)
8.276 + {
8.277 + ptr = "";
8.278 + field->type = SQLITE_TEXT;
8.279 + res = DBVal_Null;
8.280 + }
8.281 + size_t wr;
8.282 + if (field->type == SQLITE_TEXT)
8.283 + {
8.284 + wr = strncopy(buffer, ptr, maxlength);
8.285 + } else if (field->type == SQLITE_BLOB) {
8.286 + wr = (maxlength < field->size) ? maxlength : field->size;
8.287 + memcpy(buffer, ptr, wr);
8.288 + }
8.289 + if (written)
8.290 + {
8.291 + *written = wr;
8.292 + }
8.293 + return res;
8.294 + } else if (field->type == SQLITE_INTEGER) {
8.295 + size_t wr = 0;
8.296 + if (buffer)
8.297 + {
8.298 + wr = UTIL_Format(buffer, maxlength, "%d", field->u.idx);
8.299 + }
8.300 + if (written)
8.301 + {
8.302 + *written = wr;
8.303 + }
8.304 + return DBVal_Data;
8.305 + } else if (field->type == SQLITE_FLOAT) {
8.306 + size_t wr = 0;
8.307 + if (buffer)
8.308 + {
8.309 + wr = UTIL_Format(buffer, maxlength, "%f", field->u.f);
8.310 + }
8.311 + if (written)
8.312 + {
8.313 + *written = wr;
8.314 + }
8.315 + return DBVal_Data;
8.316 + }
8.317 +
8.318 + if (buffer)
8.319 + {
8.320 + strncopy(buffer, "", maxlength);
8.321 + }
8.322 + if (written)
8.323 + {
8.324 + *written = 0;
8.325 + }
8.326 +
8.327 + return DBVal_Null;
8.328 +}
8.329 +
8.330 +bool SqResults::IsNull(unsigned int columnId)
8.331 +{
8.332 + SqField *field = GetField(columnId);
8.333 + if (!field)
8.334 + {
8.335 + return true;
8.336 + }
8.337 +
8.338 + return (field->type == SQLITE_NULL);
8.339 +}
8.340 +
8.341 +unsigned int SqResults::GetDataSize(unsigned int columnId)
8.342 +{
8.343 + SqField *field = GetField(columnId);
8.344 + if (!field)
8.345 + {
8.346 + return 0;
8.347 + }
8.348 +
8.349 + return field->size;
8.350 +}
8.351 +
8.352 +DBResult SqResults::GetFloat(unsigned int columnId, float *pFloat)
8.353 +{
8.354 + SqField *field = GetField(columnId);
8.355 + if (!field)
8.356 + {
8.357 + return DBVal_Error;
8.358 + } else if (field->type == SQLITE_BLOB) {
8.359 + return DBVal_Error;
8.360 + }
8.361 +
8.362 + float fVal = 0.0f;
8.363 + if (field->type == SQLITE_FLOAT)
8.364 + {
8.365 + fVal = field->u.f;
8.366 + } else if (field->type == SQLITE_TEXT) {
8.367 + const char *ptr = m_Strings.GetString(field->u.idx);
8.368 + if (ptr)
8.369 + {
8.370 + fVal = (float)atof(ptr);
8.371 + }
8.372 + } else if (field->type == SQLITE_INTEGER) {
8.373 + fVal = (float)field->u.idx;
8.374 + }
8.375 +
8.376 + if (pFloat)
8.377 + {
8.378 + *pFloat = fVal;
8.379 + }
8.380 +
8.381 + return (field->type == SQLITE_NULL) ? DBVal_Null : DBVal_Data;
8.382 +}
8.383 +
8.384 +DBResult SqResults::GetInt(unsigned int columnId, int *pInt)
8.385 +{
8.386 + SqField *field = GetField(columnId);
8.387 + if (!field)
8.388 + {
8.389 + return DBVal_Error;
8.390 + } else if (field->type == SQLITE_BLOB) {
8.391 + return DBVal_Error;
8.392 + }
8.393 +
8.394 + int val = 0;
8.395 + if (field->type == SQLITE_INTEGER)
8.396 + {
8.397 + val = field->u.idx;
8.398 + } else if (field->type == SQLITE_TEXT) {
8.399 + const char *ptr = m_Strings.GetString(field->u.idx);
8.400 + if (ptr)
8.401 + {
8.402 + val = atoi(ptr);
8.403 + }
8.404 + } else if (field->type == SQLITE_FLOAT) {
8.405 + val = (int)field->u.f;
8.406 + }
8.407 +
8.408 + if (pInt)
8.409 + {
8.410 + *pInt = val;
8.411 + }
8.412 +
8.413 + return (field->type == SQLITE_NULL) ? DBVal_Null : DBVal_Data;
8.414 +}
8.415 +
8.416 +DBResult SqResults::GetBlob(unsigned int columnId, const void **pData, size_t *length)
8.417 +{
8.418 + SqField *field = GetField(columnId);
8.419 + if (!field)
8.420 + {
8.421 + return DBVal_Error;
8.422 + }
8.423 +
8.424 + void *addr = NULL;
8.425 +
8.426 + if (field->type == SQLITE_TEXT || field->type == SQLITE_BLOB)
8.427 + {
8.428 + addr = m_pMemory->GetAddress(field->u.idx);
8.429 + } else if (field->type == SQLITE_FLOAT || field->type == SQLITE_INTEGER) {
8.430 + addr = &(field->u);
8.431 + }
8.432 +
8.433 + if (pData)
8.434 + {
8.435 + *pData = addr;
8.436 + }
8.437 +
8.438 + if (length)
8.439 + {
8.440 + *length = field->size;
8.441 + }
8.442 +
8.443 + return (field->type == SQLITE_NULL) ? DBVal_Null : DBVal_Data;
8.444 +}
8.445 +
8.446 +DBResult SqResults::CopyBlob(unsigned int columnId, void *buffer, size_t maxlength, size_t *written)
8.447 +{
8.448 + SqField *field = GetField(columnId);
8.449 + if (!field)
8.450 + {
8.451 + return DBVal_Error;
8.452 + }
8.453 +
8.454 + void *addr = NULL;
8.455 +
8.456 + if (field->type == SQLITE_TEXT || field->type == SQLITE_BLOB)
8.457 + {
8.458 + addr = m_pMemory->GetAddress(field->u.idx);
8.459 + } else if (field->type == SQLITE_FLOAT || field->type == SQLITE_INTEGER) {
8.460 + addr = &(field->u);
8.461 + }
8.462 +
8.463 + size_t toCopy = field->size > maxlength ? maxlength : field->size;
8.464 + if (buffer && addr && toCopy)
8.465 + {
8.466 + memcpy(buffer, addr, toCopy);
8.467 + } else {
8.468 + toCopy = 0;
8.469 + }
8.470 +
8.471 + if (written)
8.472 + {
8.473 + *written = toCopy;
8.474 + }
8.475 +
8.476 + return (field->type == SQLITE_NULL) ? DBVal_Null : DBVal_Data;
8.477 +}
9.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
9.2 +++ b/extensions/sqlite/driver/SqResults.h Sun Jul 29 01:15:31 2007 +0000
9.3 @@ -0,0 +1,92 @@
9.4 +/**
9.5 + * vim: set ts=4 :
9.6 + * ===============================================================
9.7 + * SourceMod SQLite Driver Extension
9.8 + * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
9.9 + * ===============================================================
9.10 + *
9.11 + * This program is free software; you can redistribute it and/or
9.12 + * modify it under the terms of the GNU General Public License
9.13 + * as published by the Free Software Foundation; either version 2
9.14 + * of the License, or (at your option) any later version.
9.15 + * This program is distributed in the hope that it will be useful,
9.16 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
9.17 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9.18 + * GNU General Public License for more details.
9.19 + *
9.20 + * You should have received a copy of the GNU General Public License
9.21 + * along with this program; if not, write to the Free Software
9.22 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
9.23 + *
9.24 + * Version: $Id$
9.25 + */
9.26 +
9.27 +#ifndef _INCLUDE_SQLITE_SOURCEMOD_RESULT_SET_H_
9.28 +#define _INCLUDE_SQLITE_SOURCEMOD_RESULT_SET_H_
9.29 +
9.30 +#include "SqDriver.h"
9.31 +#include "sm_memtable.h"
9.32 +
9.33 +class SqQuery;
9.34 +
9.35 +struct SqField
9.36 +{
9.37 + int type;
9.38 + union
9.39 + {
9.40 + int idx;
9.41 + float f;
9.42 + } u;
9.43 + size_t size;
9.44 +};
9.45 +
9.46 +class SqResults :
9.47 + public IResultSet,
9.48 + public IResultRow
9.49 +{
9.50 + friend class SqQuery;
9.51 +public:
9.52 + SqResults(SqQuery *query);
9.53 + ~SqResults();
9.54 +public: //IResultSet
9.55 + unsigned int GetRowCount();
9.56 + unsigned int GetFieldCount();
9.57 + const char *FieldNumToName(unsigned int columnId);
9.58 + bool FieldNameToNum(const char *name, unsigned int *columnId);
9.59 + bool MoreRows();
9.60 + IResultRow *FetchRow();
9.61 + IResultRow *CurrentRow();
9.62 + bool Rewind();
9.63 + DBType GetFieldType(unsigned int field);
9.64 + DBType GetFieldDataType(unsigned int field);
9.65 +public: //IResultRow
9.66 + DBResult GetString(unsigned int columnId, const char **pString, size_t *length);
9.67 + DBResult CopyString(unsigned int columnId,
9.68 + char *buffer,
9.69 + size_t maxlength,
9.70 + size_t *written);
9.71 + DBResult GetFloat(unsigned int columnId, float *pFloat);
9.72 + DBResult GetInt(unsigned int columnId, int *pInt);
9.73 + bool IsNull(unsigned int columnId);
9.74 + size_t GetDataSize(unsigned int columnId);
9.75 + DBResult GetBlob(unsigned int columnId, const void **pData, size_t *length);
9.76 + DBResult CopyBlob(unsigned int columnId, void *buffer, size_t maxlength, size_t *written);
9.77 +public:
9.78 + void ResetResultCount();
9.79 + void PushResult();
9.80 +private:
9.81 + SqField *GetField(unsigned int col);
9.82 +private:
9.83 + sqlite3_stmt *m_pStmt; /** DOES NOT CHANGE */
9.84 + String *m_ColNames; /** DOES NOT CHANGE */
9.85 + unsigned int m_ColCount; /** DOES NOT CHANGE */
9.86 + unsigned int m_RowCount;
9.87 + unsigned int m_MaxRows;
9.88 + BaseMemTable *m_pMemory; /** DOES NOT CHANGE */
9.89 + BaseStringTable m_Strings; /** DOES NOT CHANGE */
9.90 + SqField *m_Rows;
9.91 + unsigned int m_CurRow;
9.92 + unsigned int m_NextRow;
9.93 +};
9.94 +
9.95 +#endif //_INCLUDE_SQLITE_SOURCEMOD_RESULT_SET_H_
11.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
11.2 +++ b/extensions/sqlite/extension.cpp Sun Jul 29 01:15:31 2007 +0000
11.3 @@ -0,0 +1,64 @@
11.4 +/**
11.5 + * vim: set ts=4 :
11.6 + * ===============================================================
11.7 + * SourceMod SQLite Driver Extension
11.8 + * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
11.9 + * ===============================================================
11.10 + *
11.11 + * This program is free software; you can redistribute it and/or
11.12 + * modify it under the terms of the GNU General Public License
11.13 + * as published by the Free Software Foundation; either version 2
11.14 + * of the License, or (at your option) any later version.
11.15 + * This program is distributed in the hope that it will be useful,
11.16 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
11.17 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11.18 + * GNU General Public License for more details.
11.19 + *
11.20 + * You should have received a copy of the GNU General Public License
11.21 + * along with this program; if not, write to the Free Software
11.22 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
11.23 + *
11.24 + * Version: $Id$
11.25 + */
11.26 +
11.27 +#include "extension.h"
11.28 +#include "driver/SqDriver.h"
11.29 +
11.30 +/**
11.31 + * @file extension.cpp
11.32 + * @brief Implement extension code here.
11.33 + */
11.34 +
11.35 +SqliteExt g_SqliteExt; /**< Global singleton for extension's main interface */
11.36 +
11.37 +SMEXT_LINK(&g_SqliteExt);
11.38 +
11.39 +bool SqliteExt::SDK_OnLoad(char *error, size_t maxlength, bool late)
11.40 +{
11.41 + g_SqDriver.Initialize();
11.42 + dbi->AddDriver(&g_SqDriver);
11.43 +
11.44 + return true;
11.45 +}
11.46 +
11.47 +void SqliteExt::SDK_OnUnload()
11.48 +{
11.49 + dbi->RemoveDriver(&g_SqDriver);
11.50 + g_SqDriver.Shutdown();
11.51 +}
11.52 +
11.53 +size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...)
11.54 +{
11.55 + va_list ap;
11.56 + va_start(ap, fmt);
11.57 + size_t len = vsnprintf(buffer, maxlength, fmt, ap);
11.58 + va_end(ap);
11.59 +
11.60 + if (len >= maxlength)
11.61 + {
11.62 + buffer[maxlength - 1] = '\0';
11.63 + return (maxlength - 1);
11.64 + } else {
11.65 + return len;
11.66 + }
11.67 +}
12.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
12.2 +++ b/extensions/sqlite/extension.h Sun Jul 29 01:15:31 2007 +0000
12.3 @@ -0,0 +1,113 @@
12.4 +/**
12.5 + * vim: set ts=4 :
12.6 + * ===============================================================
12.7 + * SourceMod SQLite Driver Extension
12.8 + * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
12.9 + * ===============================================================
12.10 + *
12.11 + * This program is free software; you can redistribute it and/or
12.12 + * modify it under the terms of the GNU General Public License
12.13 + * as published by the Free Software Foundation; either version 2
12.14 + * of the License, or (at your option) any later version.
12.15 + * This program is distributed in the hope that it will be useful,
12.16 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
12.17 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12.18 + * GNU General Public License for more details.
12.19 + *
12.20 + * You should have received a copy of the GNU General Public License
12.21 + * along with this program; if not, write to the Free Software
12.22 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
12.23 + *
12.24 + * Version: $Id$
12.25 + */
12.26 +
12.27 +#ifndef _INCLUDE_SOURCEMOD_EXTENSION_PROPER_H_
12.28 +#define _INCLUDE_SOURCEMOD_EXTENSION_PROPER_H_
12.29 +
12.30 +/**
12.31 + * @file extension.h
12.32 + * @brief Sample extension code header.
12.33 + */
12.34 +
12.35 +#include "smsdk_ext.h"
12.36 +
12.37 +
12.38 +/**
12.39 + * @brief Sample implementation of the SDK Extension.
12.40 + * Note: Uncomment one of the pre-defined virtual functions in order to use it.
12.41 + */
12.42 +class SqliteExt : public SDKExtension
12.43 +{
12.44 +public:
12.45 + /**
12.46 + * @brief This is called after the initial loading sequence has been processed.
12.47 + *
12.48 + * @param error Error message buffer.
12.49 + * @param maxlength Size of error message buffer.
12.50 + * @param late Whether or not the module was loaded after map load.
12.51 + * @return True to succeed loading, false to fail.
12.52 + */
12.53 + virtual bool SDK_OnLoad(char *error, size_t maxlength, bool late);
12.54 +
12.55 + /**
12.56 + * @brief This is called right before the extension is unloaded.
12.57 + */
12.58 + virtual void SDK_OnUnload();
12.59 +
12.60 + /**
12.61 + * @brief This is called once all known extensions have been loaded.
12.62 + * Note: It is is a good idea to add natives here, if any are provided.
12.63 + */
12.64 + //virtual void SDK_OnAllLoaded();
12.65 +
12.66 + /**
12.67 + * @brief Called when the pause state is changed.
12.68 + */
12.69 + //virtual void SDK_OnPauseChange(bool paused);
12.70 +
12.71 + /**
12.72 + * @brief this is called when Core wants to know if your extension is working.
12.73 + *
12.74 + * @param error Error message buffer.
12.75 + * @param maxlength Size of error message buffer.
12.76 + * @return True if working, false otherwise.
12.77 + */
12.78 + //virtual bool QueryRunning(char *error, size_t maxlength);
12.79 +public:
12.80 +#if defined SMEXT_CONF_METAMOD
12.81 + /**
12.82 + * @brief Called when Metamod is attached, before the extension version is called.
12.83 + *
12.84 + * @param error Error buffer.
12.85 + * @param maxlength Maximum size of error buffer.
12.86 + * @param late Whether or not Metamod considers this a late load.
12.87 + * @return True to succeed, false to fail.
12.88 + */
12.89 + //virtual bool SDK_OnMetamodLoad(ISmmAPI *ismm, char *error, size_t maxlength, bool late);
12.90 +
12.91 + /**
12.92 + * @brief Called when Metamod is detaching, after the extension version is called.
12.93 + * NOTE: By default this is blocked unless sent from SourceMod.
12.94 + *
12.95 + * @param error Error buffer.
12.96 + * @param maxlength Maximum size of error buffer.
12.97 + * @return True to succeed, false to fail.
12.98 + */
12.99 + //virtual bool SDK_OnMetamodUnload(char *error, size_t maxlength);
12.100 +
12.101 + /**
12.102 + * @brief Called when Metamod's pause state is changing.
12.103 + * NOTE: By default this is blocked unless sent from SourceMod.
12.104 + *
12.105 + * @param paused Pause state being set.
12.106 + * @param error Error buffer.
12.107 + * @param maxlength Maximum size of error buffer.
12.108 + * @return True to succeed, false to fail.
12.109 + */
12.110 + //virtual bool SDK_OnMetamodPauseChange(bool paused, char *error, size_t maxlength);
12.111 +#endif
12.112 +};
12.113 +
12.114 +size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...);
12.115 +
12.116 +#endif // _INCLUDE_SOURCEMOD_EXTENSION_PROPER_H_
13.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
13.2 +++ b/extensions/sqlite/msvc8/sm_sqlite.sln Sun Jul 29 01:15:31 2007 +0000
13.3 @@ -0,0 +1,20 @@
13.4 +
13.5 +Microsoft Visual Studio Solution File, Format Version 9.00
13.6 +# Visual Studio 2005
13.7 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sm_sqlite", "sm_sqlite.vcproj", "{B3E797CF-4E77-4C9D-B8A8-7589B6902206}"
13.8 +EndProject
13.9 +Global
13.10 + GlobalSection(SolutionConfigurationPlatforms) = preSolution
13.11 + Debug|Win32 = Debug|Win32
13.12 + Release|Win32 = Release|Win32
13.13 + EndGlobalSection
13.14 + GlobalSection(ProjectConfigurationPlatforms) = postSolution
13.15 + {B3E797CF-4E77-4C9D-B8A8-7589B6902206}.Debug|Win32.ActiveCfg = Debug|Win32
13.16 + {B3E797CF-4E77-4C9D-B8A8-7589B6902206}.Debug|Win32.Build.0 = Debug|Win32
13.17 + {B3E797CF-4E77-4C9D-B8A8-7589B6902206}.Release|Win32.ActiveCfg = Release|Win32
13.18 + {B3E797CF-4E77-4C9D-B8A8-7589B6902206}.Release|Win32.Build.0 = Release|Win32
13.19 + EndGlobalSection
13.20 + GlobalSection(SolutionProperties) = preSolution
13.21 + HideSolutionNode = FALSE
13.22 + EndGlobalSection
13.23 +EndGlobal
14.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
14.2 +++ b/extensions/sqlite/msvc8/sm_sqlite.vcproj Sun Jul 29 01:15:31 2007 +0000
14.3 @@ -0,0 +1,860 @@
14.4 +<?xml version="1.0" encoding="Windows-1252"?>
14.5 +<VisualStudioProject
14.6 + ProjectType="Visual C++"
14.7 + Version="8.00"
14.8 + Name="sm_sqlite"
14.9 + ProjectGUID="{B3E797CF-4E77-4C9D-B8A8-7589B6902206}"
14.10 + RootNamespace="sm_sqlite"
14.11 + Keyword="Win32Proj"
14.12 + >
14.13 + <Platforms>
14.14 + <Platform
14.15 + Name="Win32"
14.16 + />
14.17 + </Platforms>
14.18 + <ToolFiles>
14.19 + </ToolFiles>
14.20 + <Configurations>
14.21 + <Configuration
14.22 + Name="Debug|Win32"
14.23 + OutputDirectory="$(SolutionDir)$(ConfigurationName)"
14.24 + IntermediateDirectory="$(ConfigurationName)"
14.25 + ConfigurationType="2"
14.26 + CharacterSet="2"
14.27 + >
14.28 + <Tool
14.29 + Name="VCPreBuildEventTool"
14.30 + />
14.31 + <Tool
14.32 + Name="VCCustomBuildTool"
14.33 + />
14.34 + <Tool
14.35 + Name="VCXMLDataGeneratorTool"
14.36 + />
14.37 + <Tool
14.38 + Name="VCWebServiceProxyGeneratorTool"
14.39 + />
14.40 + <Tool
14.41 + Name="VCMIDLTool"
14.42 + />
14.43 + <Tool
14.44 + Name="VCCLCompilerTool"
14.45 + Optimization="0"
14.46 + AdditionalIncludeDirectories="..;..\sdk;..\..\..\public;..\..\..\public\sourcepawn"
14.47 + PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;SDK_EXPORTS;_CRT_SECURE_NO_DEPRECATE;SOURCEMOD_BUILD;THREADSAFE;SQLITE_OMIT_LOAD_EXTENSION"
14.48 + MinimalRebuild="true"
14.49 + BasicRuntimeChecks="3"
14.50 + RuntimeLibrary="1"
14.51 + RuntimeTypeInfo="false"
14.52 + UsePrecompiledHeader="0"
14.53 + WarningLevel="3"
14.54 + Detect64BitPortabilityProblems="false"
14.55 + DebugInformationFormat="4"
14.56 + />
14.57 + <Tool
14.58 + Name="VCManagedResourceCompilerTool"
14.59 + />
14.60 + <Tool
14.61 + Name="VCResourceCompilerTool"
14.62 + />
14.63 + <Tool
14.64 + Name="VCPreLinkEventTool"
14.65 + />
14.66 + <Tool
14.67 + Name="VCLinkerTool"
14.68 + OutputFile="$(OutDir)\dbi.sqlite.ext.dll"
14.69 + LinkIncremental="2"
14.70 + GenerateDebugInformation="true"
14.71 + SubSystem="2"
14.72 + TargetMachine="1"
14.73 + />
14.74 + <Tool
14.75 + Name="VCALinkTool"
14.76 + />
14.77 + <Tool
14.78 + Name="VCManifestTool"
14.79 + />
14.80 + <Tool
14.81 + Name="VCXDCMakeTool"
14.82 + />
14.83 + <Tool
14.84 + Name="VCBscMakeTool"
14.85 + />
14.86 + <Tool
14.87 + Name="VCFxCopTool"
14.88 + />
14.89 + <Tool
14.90 + Name="VCAppVerifierTool"
14.91 + />
14.92 + <Tool
14.93 + Name="VCWebDeploymentTool"
14.94 + />
14.95 + <Tool
14.96 + Name="VCPostBuildEventTool"
14.97 + />
14.98 + </Configuration>
14.99 + <Configuration
14.100 + Name="Release|Win32"
14.101 + OutputDirectory="$(SolutionDir)$(ConfigurationName)"
14.102 + IntermediateDirectory="$(ConfigurationName)"
14.103 + ConfigurationType="2"
14.104 + CharacterSet="2"
14.105 + WholeProgramOptimization="1"
14.106 + >
14.107 + <Tool
14.108 + Name="VCPreBuildEventTool"
14.109 + />
14.110 + <Tool
14.111 + Name="VCCustomBuildTool"
14.112 + />
14.113 + <Tool
14.114 + Name="VCXMLDataGeneratorTool"
14.115 + />
14.116 + <Tool
14.117 + Name="VCWebServiceProxyGeneratorTool"
14.118 + />
14.119 + <Tool
14.120 + Name="VCMIDLTool"
14.121 + />
14.122 + <Tool
14.123 + Name="VCCLCompilerTool"
14.124 + AdditionalIncludeDirectories="..;..\sdk;..\..\..\public;..\..\..\public\sourcepawn"
14.125 + PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;SDK_EXPORTS;_CRT_SECURE_NO_DEPRECATE;SOURCEMOD_BUILD;THREADSAFE;SQLITE_OMIT_LOAD_EXTENSION"
14.126 + RuntimeLibrary="0"
14.127 + RuntimeTypeInfo="false"
14.128 + UsePrecompiledHeader="0"
14.129 + WarningLevel="3"
14.130 + Detect64BitPortabilityProblems="false"
14.131 + DebugInformationFormat="3"
14.132 + />
14.133 + <Tool
14.134 + Name="VCManagedResourceCompilerTool"
14.135 + />
14.136 + <Tool
14.137 + Name="VCResourceCompilerTool"
14.138 + />
14.139 + <Tool
14.140 + Name="VCPreLinkEventTool"
14.141 + />
14.142 + <Tool
14.143 + Name="VCLinkerTool"
14.144 + OutputFile="$(OutDir)\dbi.sqlite.ext.dll"
14.145 + LinkIncremental="1"
14.146 + GenerateDebugInformation="true"
14.147 + SubSystem="2"
14.148 + OptimizeReferences="2"
14.149 + EnableCOMDATFolding="2"
14.150 + TargetMachine="1"
14.151 + />
14.152 + <Tool
14.153 + Name="VCALinkTool"
14.154 + />
14.155 + <Tool
14.156 + Name="VCManifestTool"
14.157 + />
14.158 + <Tool
14.159 + Name="VCXDCMakeTool"
14.160 + />
14.161 + <Tool
14.162 + Name="VCBscMakeTool"
14.163 + />
14.164 + <Tool
14.165 + Name="VCFxCopTool"
14.166 + />
14.167 + <Tool
14.168 + Name="VCAppVerifierTool"
14.169 + />
14.170 + <Tool
14.171 + Name="VCWebDeploymentTool"
14.172 + />
14.173 + <Tool
14.174 + Name="VCPostBuildEventTool"
14.175 + />
14.176 + </Configuration>
14.177 + </Configurations>
14.178 + <References>
14.179 + </References>
14.180 + <Files>
14.181 + <Filter
14.182 + Name="Source Files"
14.183 + Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
14.184 + UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
14.185 + >
14.186 + <File
14.187 + RelativePath="..\extension.cpp"
14.188 + >
14.189 + </File>
14.190 + <File
14.191 + RelativePath="..\sm_memtable.cpp"
14.192 + >
14.193 + </File>
14.194 + </Filter>
14.195 + <Filter
14.196 + Name="Header Files"
14.197 + Filter="h;hpp;hxx;hm;inl;inc;xsd"
14.198 + UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
14.199 + >
14.200 + <File
14.201 + RelativePath="..\extension.h"
14.202 + >
14.203 + </File>
14.204 + <File
14.205 + RelativePath="..\sm_memtable.h"
14.206 + >
14.207 + </File>
14.208 + </Filter>
14.209 + <Filter
14.210 + Name="Resource Files"
14.211 + Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
14.212 + UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
14.213 + >
14.214 + <File
14.215 + RelativePath="..\..\..\public\IDBDriver.h"
14.216 + >
14.217 + </File>
14.218 + <File
14.219 + RelativePath="..\version.rc"
14.220 + >
14.221 + </File>
14.222 + </Filter>
14.223 + <Filter
14.224 + Name="SourceMod SDK"
14.225 + UniqueIdentifier="{31958233-BB2D-4e41-A8F9-CE8A4684F436}"
14.226 + >
14.227 + <File
14.228 + RelativePath="..\sdk\smsdk_config.h"
14.229 + >
14.230 + </File>
14.231 + <File
14.232 + RelativePath="..\sdk\smsdk_ext.cpp"
14.233 + >
14.234 + </File>
14.235 + <File
14.236 + RelativePath="..\sdk\smsdk_ext.h"
14.237 + >
14.238 + </File>
14.239 + </Filter>
14.240 + <Filter
14.241 + Name="SQLite Source"
14.242 + >
14.243 + <Filter
14.244 + Name="Header Files"
14.245 + >
14.246 + <File
14.247 + RelativePath="..\sqlite-source\btree.h"
14.248 + >
14.249 + </File>
14.250 + <File
14.251 + RelativePath="..\sqlite-source\btreeInt.h"
14.252 + >
14.253 + </File>
14.254 + <File
14.255 + RelativePath="..\sqlite-source\hash.h"
14.256 + >
14.257 + </File>
14.258 + <File
14.259 + RelativePath="..\sqlite-source\keywordhash.h"
14.260 + >
14.261 + </File>
14.262 + <File
14.263 + RelativePath="..\sqlite-source\opcodes.h"
14.264 + >
14.265 + </File>
14.266 + <File
14.267 + RelativePath="..\sqlite-source\os.h"
14.268 + >
14.269 + </File>
14.270 + <File
14.271 + RelativePath="..\sqlite-source\os_common.h"
14.272 + >
14.273 + </File>
14.274 + <File
14.275 + RelativePath="..\sqlite-source\os_os2.h"
14.276 + >
14.277 + </File>
14.278 + <File
14.279 + RelativePath="..\sqlite-source\pager.h"
14.280 + >
14.281 + </File>
14.282 + <File
14.283 + RelativePath="..\sqlite-source\parse.h"
14.284 + >
14.285 + </File>
14.286 + <File
14.287 + RelativePath="..\sqlite-source\sqlite3.h"
14.288 + >
14.289 + </File>
14.290 + <File
14.291 + RelativePath="..\sqlite-source\sqliteInt.h"
14.292 + >
14.293 + </File>
14.294 + <File
14.295 + RelativePath="..\sqlite-source\sqliteLimit.h"
14.296 + >
14.297 + </File>
14.298 + <File
14.299 + RelativePath="..\sqlite-source\vdbe.h"
14.300 + >
14.301 + </File>
14.302 + <File
14.303 + RelativePath="..\sqlite-source\vdbeInt.h"
14.304 + >
14.305 + </File>
14.306 + </Filter>
14.307 + <Filter
14.308 + Name="Source Files"
14.309 + >
14.310 + <File
14.311 + RelativePath="..\sqlite-source\alter.c"
14.312 + >
14.313 + <FileConfiguration
14.314 + Name="Debug|Win32"
14.315 + >
14.316 + <Tool
14.317 + Name="VCCLCompilerTool"
14.318 + WarningLevel="2"
14.319 + />
14.320 + </FileConfiguration>
14.321 + </File>
14.322 + <File
14.323 + RelativePath="..\sqlite-source\analyze.c"
14.324 + >
14.325 + <FileConfiguration
14.326 + Name="Debug|Win32"
14.327 + >
14.328 + <Tool
14.329 + Name="VCCLCompilerTool"
14.330 + WarningLevel="2"
14.331 + />
14.332 + </FileConfiguration>
14.333 + </File>
14.334 + <File
14.335 + RelativePath="..\sqlite-source\attach.c"
14.336 + >
14.337 + <FileConfiguration
14.338 + Name="Debug|Win32"
14.339 + >
14.340 + <Tool
14.341 + Name="VCCLCompilerTool"
14.342 + WarningLevel="2"
14.343 + />
14.344 + </FileConfiguration>
14.345 + </File>
14.346 + <File
14.347 + RelativePath="..\sqlite-source\auth.c"
14.348 + >
14.349 + <FileConfiguration
14.350 + Name="Debug|Win32"
14.351 + >
14.352 + <Tool
14.353 + Name="VCCLCompilerTool"
14.354 + WarningLevel="2"
14.355 + />
14.356 + </FileConfiguration>
14.357 + </File>
14.358 + <File
14.359 + RelativePath="..\sqlite-source\btree.c"
14.360 + >
14.361 + <FileConfiguration
14.362 + Name="Debug|Win32"
14.363 + >
14.364 + <Tool
14.365 + Name="VCCLCompilerTool"
14.366 + WarningLevel="2"
14.367 + />
14.368 + </FileConfiguration>
14.369 + </File>
14.370 + <File
14.371 + RelativePath="..\sqlite-source\build.c"
14.372 + >
14.373 + <FileConfiguration
14.374 + Name="Debug|Win32"
14.375 + >
14.376 + <Tool
14.377 + Name="VCCLCompilerTool"
14.378 + WarningLevel="2"
14.379 + />
14.380 + </FileConfiguration>
14.381 + </File>
14.382 + <File
14.383 + RelativePath="..\sqlite-source\callback.c"
14.384 + >
14.385 + <FileConfiguration
14.386 + Name="Debug|Win32"
14.387 + >
14.388 + <Tool
14.389 + Name="VCCLCompilerTool"
14.390 + WarningLevel="2"
14.391 + />
14.392 + </FileConfiguration>
14.393 + </File>
14.394 + <File
14.395 + RelativePath="..\sqlite-source\complete.c"
14.396 + >
14.397 + <FileConfiguration
14.398 + Name="Debug|Win32"
14.399 + >
14.400 + <Tool
14.401 + Name="VCCLCompilerTool"
14.402 + WarningLevel="2"
14.403 + />
14.404 + </FileConfiguration>
14.405 + </File>
14.406 + <File
14.407 + RelativePath="..\sqlite-source\date.c"
14.408 + >
14.409 + <FileConfiguration
14.410 + Name="Debug|Win32"
14.411 + >
14.412 + <Tool
14.413 + Name="VCCLCompilerTool"
14.414 + WarningLevel="2"
14.415 + />
14.416 + </FileConfiguration>
14.417 + </File>
14.418 + <File
14.419 + RelativePath="..\sqlite-source\delete.c"
14.420 + >
14.421 + <FileConfiguration
14.422 + Name="Debug|Win32"
14.423 + >
14.424 + <Tool
14.425 + Name="VCCLCompilerTool"
14.426 + WarningLevel="2"
14.427 + />
14.428 + </FileConfiguration>
14.429 + </File>
14.430 + <File
14.431 + RelativePath="..\sqlite-source\expr.c"
14.432 + >
14.433 + <FileConfiguration
14.434 + Name="Debug|Win32"
14.435 + >
14.436 + <Tool
14.437 + Name="VCCLCompilerTool"
14.438 + WarningLevel="2"
14.439 + />
14.440 + </FileConfiguration>
14.441 + </File>
14.442 + <File
14.443 + RelativePath="..\sqlite-source\func.c"
14.444 + >
14.445 + <FileConfiguration
14.446 + Name="Debug|Win32"
14.447 + >
14.448 + <Tool
14.449 + Name="VCCLCompilerTool"
14.450 + WarningLevel="2"
14.451 + />
14.452 + </FileConfiguration>
14.453 + </File>
14.454 + <File
14.455 + RelativePath="..\sqlite-source\hash.c"
14.456 + >
14.457 + <FileConfiguration
14.458 + Name="Debug|Win32"
14.459 + >
14.460 + <Tool
14.461 + Name="VCCLCompilerTool"
14.462 + WarningLevel="2"
14.463 + />
14.464 + </FileConfiguration>
14.465 + </File>
14.466 + <File
14.467 + RelativePath="..\sqlite-source\insert.c"
14.468 + >
14.469 + <FileConfiguration
14.470 + Name="Debug|Win32"
14.471 + >
14.472 + <Tool
14.473 + Name="VCCLCompilerTool"
14.474 + WarningLevel="2"
14.475 + />
14.476 + </FileConfiguration>
14.477 + </File>
14.478 + <File
14.479 + RelativePath="..\sqlite-source\legacy.c"
14.480 + >
14.481 + <FileConfiguration
14.482 + Name="Debug|Win32"
14.483 + >
14.484 + <Tool
14.485 + Name="VCCLCompilerTool"
14.486 + WarningLevel="2"
14.487 + />
14.488 + </FileConfiguration>
14.489 + </File>
14.490 + <File
14.491 + RelativePath="..\sqlite-source\main.c"
14.492 + >
14.493 + <FileConfiguration
14.494 + Name="Debug|Win32"
14.495 + >
14.496 + <Tool
14.497 + Name="VCCLCompilerTool"
14.498 + WarningLevel="2"
14.499 + />
14.500 + </FileConfiguration>
14.501 + </File>
14.502 + <File
14.503 + RelativePath="..\sqlite-source\malloc.c"
14.504 + >
14.505 + <FileConfiguration
14.506 + Name="Debug|Win32"
14.507 + >
14.508 + <Tool
14.509 + Name="VCCLCompilerTool"
14.510 + WarningLevel="2"
14.511 + />
14.512 + </FileConfiguration>
14.513 + </File>
14.514 + <File
14.515 + RelativePath="..\sqlite-source\opcodes.c"
14.516 + >
14.517 + <FileConfiguration
14.518 + Name="Debug|Win32"
14.519 + >
14.520 + <Tool
14.521 + Name="VCCLCompilerTool"
14.522 + WarningLevel="2"
14.523 + />
14.524 + </FileConfiguration>
14.525 + </File>
14.526 + <File
14.527 + RelativePath="..\sqlite-source\os.c"
14.528 + >
14.529 + <FileConfiguration
14.530 + Name="Debug|Win32"
14.531 + >
14.532 + <Tool
14.533 + Name="VCCLCompilerTool"
14.534 + WarningLevel="2"
14.535 + />
14.536 + </FileConfiguration>
14.537 + </File>
14.538 + <File
14.539 + RelativePath="..\sqlite-source\os_win.c"
14.540 + >
14.541 + <FileConfiguration
14.542 + Name="Debug|Win32"
14.543 + >
14.544 + <Tool
14.545 + Name="VCCLCompilerTool"
14.546 + WarningLevel="2"
14.547 + />
14.548 + </FileConfiguration>
14.549 + </File>
14.550 + <File
14.551 + RelativePath="..\sqlite-source\pager.c"
14.552 + >
14.553 + <FileConfiguration
14.554 + Name="Debug|Win32"
14.555 + >
14.556 + <Tool
14.557 + Name="VCCLCompilerTool"
14.558 + WarningLevel="2"
14.559 + />
14.560 + </FileConfiguration>
14.561 + </File>
14.562 + <File
14.563 + RelativePath="..\sqlite-source\parse.c"
14.564 + >
14.565 + <FileConfiguration
14.566 + Name="Debug|Win32"
14.567 + >
14.568 + <Tool
14.569 + Name="VCCLCompilerTool"
14.570 + WarningLevel="2"
14.571 + />
14.572 + </FileConfiguration>
14.573 + </File>
14.574 + <File
14.575 + RelativePath="..\sqlite-source\pragma.c"
14.576 + >
14.577 + <FileConfiguration
14.578 + Name="Debug|Win32"
14.579 + >
14.580 + <Tool
14.581 + Name="VCCLCompilerTool"
14.582 + WarningLevel="2"
14.583 + />
14.584 + </FileConfiguration>
14.585 + </File>
14.586 + <File
14.587 + RelativePath="..\sqlite-source\prepare.c"
14.588 + >
14.589 + <FileConfiguration
14.590 + Name="Debug|Win32"
14.591 + >
14.592 + <Tool
14.593 + Name="VCCLCompilerTool"
14.594 + WarningLevel="2"
14.595 + />
14.596 + </FileConfiguration>
14.597 + </File>
14.598 + <File
14.599 + RelativePath="..\sqlite-source\printf.c"
14.600 + >
14.601 + <FileConfiguration
14.602 + Name="Debug|Win32"
14.603 + >
14.604 + <Tool
14.605 + Name="VCCLCompilerTool"
14.606 + WarningLevel="2"
14.607 + />
14.608 + </FileConfiguration>
14.609 + </File>
14.610 + <File
14.611 + RelativePath="..\sqlite-source\random.c"
14.612 + >
14.613 + <FileConfiguration
14.614 + Name="Debug|Win32"
14.615 + >
14.616 + <Tool
14.617 + Name="VCCLCompilerTool"
14.618 + WarningLevel="2"
14.619 + />
14.620 + </FileConfiguration>
14.621 + </File>
14.622 + <File
14.623 + RelativePath="..\sqlite-source\select.c"
14.624 + >
14.625 + <FileConfiguration
14.626 + Name="Debug|Win32"
14.627 + >
14.628 + <Tool
14.629 + Name="VCCLCompilerTool"
14.630 + WarningLevel="2"
14.631 + />
14.632 + </FileConfiguration>
14.633 + </File>
14.634 + <File
14.635 + RelativePath="..\sqlite-source\table.c"
14.636 + >
14.637 + <FileConfiguration
14.638 + Name="Debug|Win32"
14.639 + >
14.640 + <Tool
14.641 + Name="VCCLCompilerTool"
14.642 + WarningLevel="2"
14.643 + />
14.644 + </FileConfiguration>
14.645 + </File>
14.646 + <File
14.647 + RelativePath="..\sqlite-source\tokenize.c"
14.648 + >
14.649 + <FileConfiguration
14.650 + Name="Debug|Win32"
14.651 + >
14.652 + <Tool
14.653 + Name="VCCLCompilerTool"
14.654 + WarningLevel="2"
14.655 + />
14.656 + </FileConfiguration>
14.657 + </File>
14.658 + <File
14.659 + RelativePath="..\sqlite-source\trigger.c"
14.660 + >
14.661 + <FileConfiguration
14.662 + Name="Debug|Win32"
14.663 + >
14.664 + <Tool
14.665 + Name="VCCLCompilerTool"
14.666 + WarningLevel="2"
14.667 + />
14.668 + </FileConfiguration>
14.669 + </File>
14.670 + <File
14.671 + RelativePath="..\sqlite-source\update.c"
14.672 + >
14.673 + <FileConfiguration
14.674 + Name="Debug|Win32"
14.675 + >
14.676 + <Tool
14.677 + Name="VCCLCompilerTool"
14.678 + WarningLevel="2"
14.679 + />
14.680 + </FileConfiguration>
14.681 + </File>
14.682 + <File
14.683 + RelativePath="..\sqlite-source\utf.c"
14.684 + >
14.685 + <FileConfiguration
14.686 + Name="Debug|Win32"
14.687 + >
14.688 + <Tool
14.689 + Name="VCCLCompilerTool"
14.690 + WarningLevel="2"
14.691 + />
14.692 + </FileConfiguration>
14.693 + </File>
14.694 + <File
14.695 + RelativePath="..\sqlite-source\util.c"
14.696 + >
14.697 + <FileConfiguration
14.698 + Name="Debug|Win32"
14.699 + >
14.700 + <Tool
14.701 + Name="VCCLCompilerTool"
14.702 + WarningLevel="2"
14.703 + />
14.704 + </FileConfiguration>
14.705 + </File>
14.706 + <File
14.707 + RelativePath="..\sqlite-source\vacuum.c"
14.708 + >
14.709 + <FileConfiguration
14.710 + Name="Debug|Win32"
14.711 + >
14.712 + <Tool
14.713 + Name="VCCLCompilerTool"
14.714 + WarningLevel="2"
14.715 + />
14.716 + </FileConfiguration>
14.717 + </File>
14.718 + <File
14.719 + RelativePath="..\sqlite-source\vdbe.c"
14.720 + >
14.721 + <FileConfiguration
14.722 + Name="Debug|Win32"
14.723 + >
14.724 + <Tool
14.725 + Name="VCCLCompilerTool"
14.726 + WarningLevel="2"
14.727 + />
14.728 + </FileConfiguration>
14.729 + </File>
14.730 + <File
14.731 + RelativePath="..\sqlite-source\vdbeapi.c"
14.732 + >
14.733 + <FileConfiguration
14.734 + Name="Debug|Win32"
14.735 + >
14.736 + <Tool
14.737 + Name="VCCLCompilerTool"
14.738 + WarningLevel="2"
14.739 + />
14.740 + </FileConfiguration>
14.741 + </File>
14.742 + <File
14.743 + RelativePath="..\sqlite-source\vdbeaux.c"
14.744 + >
14.745 + <FileConfiguration
14.746 + Name="Debug|Win32"
14.747 + >
14.748 + <Tool
14.749 + Name="VCCLCompilerTool"
14.750 + WarningLevel="2"
14.751 + />
14.752 + </FileConfiguration>
14.753 + </File>
14.754 + <File
14.755 + RelativePath="..\sqlite-source\vdbeblob.c"
14.756 + >
14.757 + <FileConfiguration
14.758 + Name="Debug|Win32"
14.759 + >
14.760 + <Tool
14.761 + Name="VCCLCompilerTool"
14.762 + WarningLevel="2"
14.763 + />
14.764 + </FileConfiguration>
14.765 + </File>
14.766 + <File
14.767 + RelativePath="..\sqlite-source\vdbefifo.c"
14.768 + >
14.769 + <FileConfiguration
14.770 + Name="Debug|Win32"
14.771 + >
14.772 + <Tool
14.773 + Name="VCCLCompilerTool"
14.774 + WarningLevel="2"
14.775 + />
14.776 + </FileConfiguration>
14.777 + </File>
14.778 + <File
14.779 + RelativePath="..\sqlite-source\vdbemem.c"
14.780 + >
14.781 + <FileConfiguration
14.782 + Name="Debug|Win32"
14.783 + >
14.784 + <Tool
14.785 + Name="VCCLCompilerTool"
14.786 + WarningLevel="2"
14.787 + />
14.788 + </FileConfiguration>
14.789 + </File>
14.790 + <File
14.791 + RelativePath="..\sqlite-source\vtab.c"
14.792 + >
14.793 + <FileConfiguration
14.794 + Name="Debug|Win32"
14.795 + >
14.796 + <Tool
14.797 + Name="VCCLCompilerTool"
14.798 + WarningLevel="2"
14.799 + />
14.800 + </FileConfiguration>
14.801 + </File>
14.802 + <File
14.803 + RelativePath="..\sqlite-source\where.c"
14.804 + >
14.805 + <FileConfiguration
14.806 + Name="Debug|Win32"
14.807 + >
14.808 + <Tool
14.809 + Name="VCCLCompilerTool"
14.810 + WarningLevel="2"
14.811 + />
14.812 + </FileConfiguration>
14.813 + </File>
14.814 + </Filter>
14.815 + </Filter>
14.816 + <Filter
14.817 + Name="Driver"
14.818 + >
14.819 + <Filter
14.820 + Name="Source Files"
14.821 + >
14.822 + <File
14.823 + RelativePath="..\driver\SqDatabase.cpp"
14.824 + >
14.825 + </File>
14.826 + <File
14.827 + RelativePath="..\driver\SqDriver.cpp"
14.828 + >
14.829 + </File>
14.830 + <File
14.831 + RelativePath="..\driver\SqQuery.cpp"
14.832 + >
14.833 + </File>
14.834 + <File
14.835 + RelativePath="..\driver\SqResults.cpp"
14.836 + >
14.837 + </File>
14.838 + </Filter>
14.839 + <Filter
14.840 + Name="Header Files"
14.841 + >
14.842 + <File
14.843 + RelativePath="..\driver\SqDatabase.h"
14.844 + >
14.845 + </File>
14.846 + <File
14.847 + RelativePath="..\driver\SqDriver.h"
14.848 + >
14.849 + </File>
14.850 + <File
14.851 + RelativePath="..\driver\SqQuery.h"
14.852 + >
14.853 + </File>
14.854 + <File
14.855 + RelativePath="..\driver\SqResults.h"
14.856 + >
14.857 + </File>
14.858 + </Filter>
14.859 + </Filter>
14.860 + </Files>
14.861 + <Globals>
14.862 + </Globals>
14.863 +</VisualStudioProject>
15.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
15.2 +++ b/extensions/sqlite/sdk/smsdk_config.h Sun Jul 29 01:15:31 2007 +0000
15.3 @@ -0,0 +1,62 @@
15.4 +/**
15.5 + * vim: set ts=4 :
15.6 + * ===============================================================
15.7 + * SourceMod, Copyright (C) 2004-2007 AlliedModders LLC.
15.8 + * All rights reserved.
15.9 + * ===============================================================
15.10 + *
15.11 + * This file is part of the SourceMod/SourcePawn SDK. This file may only be
15.12 + * used or modified under the Terms and Conditions of its License Agreement,
15.13 + * which is found in public/licenses/LICENSE.txt. As of this notice, derivative
15.14 + * works must be licensed under the GNU General Public License (version 2 or
15.15 + * greater). A copy of the GPL is included under public/licenses/GPL.txt.
15.16 + *
15.17 + * To view the latest information, see: http://www.sourcemod.net/license.php
15.18 + *
15.19 + * Version: $Id$
15.20 + */
15.21 +
15.22 +#ifndef _INCLUDE_SOURCEMOD_EXTENSION_CONFIG_H_
15.23 +#define _INCLUDE_SOURCEMOD_EXTENSION_CONFIG_H_
15.24 +
15.25 +#include "svn_version.h"
15.26 +
15.27 +/**
15.28 + * @file smsdk_config.h
15.29 + * @brief Contains macros for configuring basic extension information.
15.30 + */
15.31 +
15.32 +/* Basic information exposed publicly */
15.33 +#define SMEXT_CONF_NAME "SQLite"
15.34 +#define SMEXT_CONF_DESCRIPTION "SQLite Driver"
15.35 +#define SMEXT_CONF_VERSION SVN_FULL_VERSION
15.36 +#define SMEXT_CONF_AUTHOR "AlliedModders"
15.37 +#define SMEXT_CONF_URL "http://www.sourcemod.net/"
15.38 +#define SMEXT_CONF_LOGTAG "SQLITE"
15.39 +#define SMEXT_CONF_LICENSE "GPL"
15.40 +#define SMEXT_CONF_DATESTRING __DATE__
15.41 +
15.42 +/**
15.43 + * @brief Exposes plugin's main interface.
15.44 + */
15.45 +#define SMEXT_LINK(name) SDKExtension *g_pExtensionIface = name;
15.46 +
15.47 +/**
15.48 + * @brief Sets whether or not this plugin required Metamod.
15.49 + * NOTE: Uncomment to enable, comment to disable.
15.50 + */
15.51 +//#define SMEXT_CONF_METAMOD
15.52 +
15.53 +/** Enable interfaces you want to use here by uncommenting lines */
15.54 +//#define SMEXT_ENABLE_FORWARDSYS
15.55 +//#define SMEXT_ENABLE_HANDLESYS
15.56 +//#define SMEXT_ENABLE_PLAYERHELPERS
15.57 +#define SMEXT_ENABLE_DBMANAGER
15.58 +//#define SMEXT_ENABLE_GAMECONF
15.59 +//#define SMEXT_ENABLE_MEMUTILS
15.60 +//#define SMEXT_ENABLE_GAMEHELPERS
15.61 +//#define SMEXT_ENABLE_TIMERSYS
15.62 +#define SMEXT_ENABLE_THREADER
15.63 +#define SMEXT_ENABLE_LIBSYS
15.64 +
15.65 +#endif // _INCLUDE_SOURCEMOD_EXTENSION_CONFIG_H_
16.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
16.2 +++ b/extensions/sqlite/sdk/smsdk_ext.cpp Sun Jul 29 01:15:31 2007 +0000
16.3 @@ -0,0 +1,403 @@
16.4 +/**
16.5 + * vim: set ts=4 :
16.6 + * ===============================================================
16.7 + * SourceMod, Copyright (C) 2004-2007 AlliedModders LLC.
16.8 + * All rights reserved.
16.9 + * ===============================================================
16.10 + *
16.11 + * This file is part of the SourceMod/SourcePawn SDK. This file may only be
16.12 + * used or modified under the Terms and Conditions of its License Agreement,
16.13 + * which is found in public/licenses/LICENSE.txt. As of this notice, derivative
16.14 + * works must be licensed under the GNU General Public License (version 2 or
16.15 + * greater). A copy of the GPL is included under public/licenses/GPL.txt.
16.16 + *
16.17 + * To view the latest information, see: http://www.sourcemod.net/license.php
16.18 + *
16.19 + * Version: $Id$
16.20 + */
16.21 +
16.22 +#include <stdio.h>
16.23 +#include <malloc.h>
16.24 +#include "smsdk_ext.h"
16.25 +
16.26 +/**
16.27 + * @file smsdk_ext.cpp
16.28 + * @brief Contains wrappers for making Extensions easier to write.
16.29 + */
16.30 +
16.31 +IExtension *myself = NULL; /**< Ourself */
16.32 +IShareSys *g_pShareSys = NULL; /**< Share system */
16.33 +IShareSys *sharesys = NULL; /**< Share system */
16.34 +ISourceMod *g_pSM = NULL; /**< SourceMod helpers */
16.35 +ISourceMod *smutils = NULL; /**< SourceMod helpers */
16.36 +
16.37 +#if defined SMEXT_ENABLE_FORWARDSYS
16.38 +IForwardManager *g_pForwards = NULL; /**< Forward system */
16.39 +IForwardManager *forwards = NULL; /**< Forward system */
16.40 +#endif
16.41 +#if defined SMEXT_ENABLE_HANDLESYS
16.42 +IHandleSys *g_pHandleSys = NULL; /**< Handle system */
16.43 +IHandleSys *handlesys = NULL; /**< Handle system */
16.44 +#endif
16.45 +#if defined SMEXT_ENABLE_PLAYERHELPERS
16.46 +IPlayerManager *playerhelpers = NULL; /**< Player helpers */
16.47 +#endif //SMEXT_ENABLE_PLAYERHELPERS
16.48 +#if defined SMEXT_ENABLE_DBMANAGER
16.49 +IDBManager *dbi = NULL; /**< DB Manager */
16.50 +#endif //SMEXT_ENABLE_DBMANAGER
16.51 +#if defined SMEXT_ENABLE_GAMECONF
16.52 +IGameConfigManager *gameconfs = NULL; /**< Game config manager */
16.53 +#endif //SMEXT_ENABLE_DBMANAGER
16.54 +#if defined SMEXT_ENABLE_MEMUTILS
16.55 +IMemoryUtils *memutils = NULL;
16.56 +#endif //SMEXT_ENABLE_DBMANAGER
16.57 +#if defined SMEXT_ENABLE_GAMEHELPERS
16.58 +IGameHelpers *gamehelpers = NULL;
16.59 +#endif
16.60 +#if defined SMEXT_ENABLE_TIMERSYS
16.61 +ITimerSystem *timersys = NULL;
16.62 +#endif
16.63 +#if defined SMEXT_ENABLE_ADTFACTORY
16.64 +IADTFactory *adtfactory = NULL;
16.65 +#endif
16.66 +#if defined SMEXT_ENABLE_THREADER
16.67 +IThreader *threader = NULL;
16.68 +#endif
16.69 +#if defined SMEXT_ENABLE_LIBSYS
16.70 +ILibrarySys *libsys = NULL;
16.71 +#endif
16.72 +
16.73 +/** Exports the main interface */
16.74 +PLATFORM_EXTERN_C IExtensionInterface *GetSMExtAPI()
16.75 +{
16.76 + return g_pExtensionIface;
16.77 +}
16.78 +
16.79 +SDKExtension::SDKExtension()
16.80 +{
16.81 +#if defined SMEXT_CONF_METAMOD
16.82 + m_SourceMMLoaded = false;
16.83 + m_WeAreUnloaded = false;
16.84 + m_WeGotPauseChange = false;
16.85 +#endif
16.86 +}
16.87 +
16.88 +bool SDKExtension::OnExtensionLoad(IExtension *me, IShareSys *sys, char *error, size_t maxlength, bool late)
16.89 +{
16.90 + g_pShareSys = sharesys = sys;
16.91 + myself = me;
16.92 +
16.93 +#if defined SMEXT_CONF_METAMOD
16.94 + m_WeAreUnloaded = true;
16.95 +
16.96 + if (!m_SourceMMLoaded)
16.97 + {
16.98 + if (error)
16.99 + {
16.100 + snprintf(error, maxlength, "Metamod attach failed");
16.101 + }
16.102 + return false;
16.103 + }
16.104 +#endif
16.105 + SM_GET_IFACE(SOURCEMOD, g_pSM);
16.106 + smutils = g_pSM;
16.107 +#if defined SMEXT_ENABLE_HANDLESYS
16.108 + SM_GET_IFACE(HANDLESYSTEM, g_pHandleSys);
16.109 + handlesys = g_pHandleSys;
16.110 +#endif
16.111 +#if defined SMEXT_ENABLE_FORWARDSYS
16.112 + SM_GET_IFACE(FORWARDMANAGER, g_pForwards);
16.113 + forwards = g_pForwards;
16.114 +#endif
16.115 +#if defined SMEXT_ENABLE_PLAYERHELPERS
16.116 + SM_GET_IFACE(PLAYERMANAGER, playerhelpers);
16.117 +#endif
16.118 +#if defined SMEXT_ENABLE_DBMANAGER
16.119 + SM_GET_IFACE(DBI, dbi);
16.120 +#endif
16.121 +#if defined SMEXT_ENABLE_GAMECONF
16.122 + SM_GET_IFACE(GAMECONFIG, gameconfs);
16.123 +#endif
16.124 +#if defined SMEXT_ENABLE_MEMUTILS
16.125 + SM_GET_IFACE(MEMORYUTILS, memutils);
16.126 +#endif
16.127 +#if defined SMEXT_ENABLE_GAMEHELPERS
16.128 + SM_GET_IFACE(GAMEHELPERS, gamehelpers);
16.129 +#endif
16.130 +#if defined SMEXT_ENABLE_TIMERSYS
16.131 + SM_GET_IFACE(TIMERSYS, timersys);
16.132 +#endif
16.133 +#if defined SMEXT_ENABLE_ADTFACTORY
16.134 + SM_GET_IFACE(ADTFACTORY, adtfactory);
16.135 +#endif
16.136 +#if defined SMEXT_ENABLE_THREADER
16.137 + SM_GET_IFACE(THREADER, threader);
16.138 +#endif
16.139 +#if defined SMEXT_ENABLE_LIBSYS
16.140 + SM_GET_IFACE(LIBRARYSYS, libsys);
16.141 +#endif
16.142 +
16.143 + if (SDK_OnLoad(error, maxlength, late))
16.144 + {
16.145 +#if defined SMEXT_CONF_METAMOD
16.146 + m_WeAreUnloaded = true;
16.147 +#endif
16.148 + return true;
16.149 + }
16.150 +
16.151 + return false;
16.152 +}
16.153 +
16.154 +bool SDKExtension::IsMetamodExtension()
16.155 +{
16.156 +#if defined SMEXT_CONF_METAMOD
16.157 + return true;
16.158 +#else
16.159 + return false;
16.160 +#endif
16.161 +}
16.162 +
16.163 +void SDKExtension::OnExtensionPauseChange(bool state)
16.164 +{
16.165 +#if defined SMEXT_CONF_METAMOD
16.166 + m_WeGotPauseChange = true;
16.167 +#endif
16.168 + SDK_OnPauseChange(state);
16.169 +}
16.170 +
16.171 +void SDKExtension::OnExtensionsAllLoaded()
16.172 +{
16.173 + SDK_OnAllLoaded();
16.174 +}
16.175 +
16.176 +void SDKExtension::OnExtensionUnload()
16.177 +{
16.178 +#if defined SMEXT_CONF_METAMOD
16.179 + m_WeAreUnloaded = true;
16.180 +#endif
16.181 + SDK_OnUnload();
16.182 +}
16.183 +
16.184 +const char *SDKExtension::GetExtensionAuthor()
16.185 +{
16.186 + return SMEXT_CONF_AUTHOR;
16.187 +}
16.188 +
16.189 +const char *SDKExtension::GetExtensionDateString()
16.190 +{
16.191 + return SMEXT_CONF_DATESTRING;
16.192 +}
16.193 +
16.194 +const char *SDKExtension::GetExtensionDescription()
16.195 +{
16.196 + return SMEXT_CONF_DESCRIPTION;
16.197 +}
16.198 +
16.199 +const char *SDKExtension::GetExtensionVerString()
16.200 +{
16.201 + return SMEXT_CONF_VERSION;
16.202 +}
16.203 +
16.204 +const char *SDKExtension::GetExtensionName()
16.205 +{
16.206 + return SMEXT_CONF_NAME;
16.207 +}
16.208 +
16.209 +const char *SDKExtension::GetExtensionTag()
16.210 +{
16.211 + return SMEXT_CONF_LOGTAG;
16.212 +}
16.213 +
16.214 +const char *SDKExtension::GetExtensionURL()
16.215 +{
16.216 + return SMEXT_CONF_URL;
16.217 +}
16.218 +
16.219 +bool SDKExtension::SDK_OnLoad(char *error, size_t maxlength, bool late)
16.220 +{
16.221 + return true;
16.222 +}
16.223 +
16.224 +void SDKExtension::SDK_OnUnload()
16.225 +{
16.226 +}
16.227 +
16.228 +void SDKExtension::SDK_OnPauseChange(bool paused)
16.229 +{
16.230 +}
16.231 +
16.232 +void SDKExtension::SDK_OnAllLoaded()
16.233 +{
16.234 +}
16.235 +
16.236 +#if defined SMEXT_CONF_METAMOD
16.237 +
16.238 +PluginId g_PLID = 0; /**< Metamod plugin ID */
16.239 +ISmmPlugin *g_PLAPI = NULL; /**< Metamod plugin API */
16.240 +SourceHook::ISourceHook *g_SHPtr = NULL; /**< SourceHook pointer */
16.241 +ISmmAPI *g_SMAPI = NULL; /**< SourceMM API pointer */
16.242 +
16.243 +IVEngineServer *engine = NULL; /**< IVEngineServer pointer */
16.244 +IServerGameDLL *gamedll = NULL; /**< IServerGameDLL pointer */
16.245 +
16.246 +/** Exposes the extension to Metamod */
16.247 +SMM_API void *PL_EXPOSURE(const char *name, int *code)
16.248 +{
16.249 + if (name && !strcmp(name, PLAPI_NAME))
16.250 + {
16.251 + if (code)
16.252 + {
16.253 + *code = IFACE_OK;
16.254 + }
16.255 + return static_cast<void *>(g_pExtensionIface);
16.256 + }
16.257 +
16.258 + if (code)
16.259 + {
16.260 + *code = IFACE_FAILED;
16.261 + }
16.262 +
16.263 + return NULL;
16.264 +}
16.265 +
16.266 +bool SDKExtension::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool late)
16.267 +{
16.268 + PLUGIN_SAVEVARS();
16.269 +
16.270 + GET_V_IFACE_ANY(serverFactory, gamedll, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL);
16.271 + GET_V_IFACE_CURRENT(engineFactory, engine, IVEngineServer, INTERFACEVERSION_VENGINESERVER);
16.272 +
16.273 + m_SourceMMLoaded = true;
16.274 +
16.275 + return SDK_OnMetamodLoad(ismm, error, maxlen, late);
16.276 +}
16.277 +
16.278 +bool SDKExtension::Unload(char *error, size_t maxlen)
16.279 +{
16.280 + if (!m_WeAreUnloaded)
16.281 + {
16.282 + if (error)
16.283 + {
16.284 + snprintf(error, maxlen, "This extension must be unloaded by SourceMod.");
16.285 + }
16.286 + return false;
16.287 + }
16.288 +
16.289 + return SDK_OnMetamodUnload(error, maxlen);
16.290 +}
16.291 +
16.292 +bool SDKExtension::Pause(char *error, size_t maxlen)
16.293 +{
16.294 + if (!m_WeGotPauseChange)
16.295 + {
16.296 + if (error)
16.297 + {
16.298 + snprintf(error, maxlen, "This extension must be paused by SourceMod.");
16.299 + }
16.300 + return false;
16.301 + }
16.302 +
16.303 + m_WeGotPauseChange = false;
16.304 +
16.305 + return SDK_OnMetamodPauseChange(true, error, maxlen);
16.306 +}
16.307 +
16.308 +bool SDKExtension::Unpause(char *error, size_t maxlen)
16.309 +{
16.310 + if (!m_WeGotPauseChange)
16.311 + {
16.312 + if (error)
16.313 + {
16.314 + snprintf(error, maxlen, "This extension must be unpaused by SourceMod.");
16.315 + }
16.316 + return false;
16.317 + }
16.318 +
16.319 + m_WeGotPauseChange = false;
16.320 +
16.321 + return SDK_OnMetamodPauseChange(false, error, maxlen);
16.322 +}
16.323 +
16.324 +const char *SDKExtension::GetAuthor()
16.325 +{
16.326 + return GetExtensionAuthor();
16.327 +}
16.328 +
16.329 +const char *SDKExtension::GetDate()
16.330 +{
16.331 + return GetExtensionDateString();
16.332 +}
16.333 +
16.334 +const char *SDKExtension::GetDescription()
16.335 +{
16.336 + return GetExtensionDescription();
16.337 +}
16.338 +
16.339 +const char *SDKExtension::GetLicense()
16.340 +{
16.341 + return SMEXT_CONF_LICENSE;
16.342 +}
16.343 +
16.344 +const char *SDKExtension::GetLogTag()
16.345 +{
16.346 + return GetExtensionTag();
16.347 +}
16.348 +
16.349 +const char *SDKExtension::GetName()
16.350 +{
16.351 + return GetExtensionName();
16.352 +}
16.353 +
16.354 +const char *SDKExtension::GetURL()
16.355 +{
16.356 + return GetExtensionURL();
16.357 +}
16.358 +
16.359 +const char *SDKExtension::GetVersion()
16.360 +{
16.361 + return GetExtensionVerString();
16.362 +}
16.363 +
16.364 +bool SDKExtension::SDK_OnMetamodLoad(ISmmAPI *ismm, char *error, size_t maxlength, bool late)
16.365 +{
16.366 + return true;
16.367 +}
16.368 +
16.369 +bool SDKExtension::SDK_OnMetamodUnload(char *error, size_t maxlength)
16.370 +{
16.371 + return true;
16.372 +}
16.373 +
16.374 +bool SDKExtension::SDK_OnMetamodPauseChange(bool paused, char *error, size_t maxlength)
16.375 +{
16.376 + return true;
16.377 +}
16.378 +
16.379 +#endif
16.380 +
16.381 +/* Overload a few things to prevent libstdc++ linking */
16.382 +#if defined __linux__
16.383 +extern "C" void __cxa_pure_virtual(void)
16.384 +{
16.385 +}
16.386 +
16.387 +void *operator new(size_t size)
16.388 +{
16.389 + return malloc(size);
16.390 +}
16.391 +
16.392 +void *operator new[](size_t size)
16.393 +{
16.394 + return malloc(size);
16.395 +}
16.396 +
16.397 +void operator delete(void *ptr)
16.398 +{
16.399 + free(ptr);
16.400 +}
16.401 +
16.402 +void operator delete[](void * ptr)
16.403 +{
16.404 + free(ptr);
16.405 +}
16.406 +#endif
17.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
17.2 +++ b/extensions/sqlite/sdk/smsdk_ext.h Sun Jul 29 01:15:31 2007 +0000
17.3 @@ -0,0 +1,279 @@
17.4 +/**
17.5 + * vim: set ts=4 :
17.6 + * ===============================================================
17.7 + * SourceMod, Copyright (C) 2004-2007 AlliedModders LLC.
17.8 + * All rights reserved.
17.9 + * ===============================================================
17.10 + *
17.11 + * This file is part of the SourceMod/SourcePawn SDK. This file may only be
17.12 + * used or modified under the Terms and Conditions of its License Agreement,
17.13 + * which is found in public/licenses/LICENSE.txt. As of this notice, derivative
17.14 + * works must be licensed under the GNU General Public License (version 2 or
17.15 + * greater). A copy of the GPL is included under public/licenses/GPL.txt.
17.16 + *
17.17 + * To view the latest information, see: http://www.sourcemod.net/license.php
17.18 + *
17.19 + * Version: $Id$
17.20 + */
17.21 +
17.22 +#ifndef _INCLUDE_SOURCEMOD_EXTENSION_BASESDK_H_
17.23 +#define _INCLUDE_SOURCEMOD_EXTENSION_BASESDK_H_
17.24 +
17.25 +/**
17.26 + * @file smsdk_ext.h
17.27 + * @brief Contains wrappers for making Extensions easier to write.
17.28 + */
17.29 +
17.30 +#include "smsdk_config.h"
17.31 +#include <IExtensionSys.h>
17.32 +#include <IHandleSys.h>
17.33 +#include <sp_vm_api.h>
17.34 +#include <sm_platform.h>
17.35 +#include <ISourceMod.h>
17.36 +#if defined SMEXT_ENABLE_FORWARDSYS
17.37 +#include <IForwardSys.h>
17.38 +#endif //SMEXT_ENABLE_FORWARDSYS
17.39 +#if defined SMEXT_ENABLE_PLAYERHELPERS
17.40 +#include <IPlayerHelpers.h>
17.41 +#endif //SMEXT_ENABLE_PlAYERHELPERS
17.42 +#if defined SMEXT_ENABLE_DBMANAGER
17.43 +#include <IDBDriver.h>
17.44 +#endif //SMEXT_ENABLE_DBMANAGER
17.45 +#if defined SMEXT_ENABLE_GAMECONF
17.46 +#include <IGameConfigs.h>
17.47 +#endif
17.48 +#if defined SMEXT_ENABLE_MEMUTILS
17.49 +#include <IMemoryUtils.h>
17.50 +#endif
17.51 +#if defined SMEXT_ENABLE_GAMEHELPERS
17.52 +#include <IGameHelpers.h>
17.53 +#endif
17.54 +#if defined SMEXT_ENABLE_TIMERSYS
17.55 +#include <ITimerSystem.h>
17.56 +#endif
17.57 +#if defined SMEXT_ENABLE_ADTFACTORY
17.58 +#include <IADTFactory.h>
17.59 +#endif
17.60 +#if defined SMEXT_ENABLE_THREADER
17.61 +#include <IThreader.h>
17.62 +#endif
17.63 +#if defined SMEXT_ENABLE_LIBSYS
17.64 +#include <ILibrarySys.h>
17.65 +#endif
17.66 +
17.67 +#if defined SMEXT_CONF_METAMOD
17.68 +#include <ISmmPlugin.h>
17.69 +#include <eiface.h>
17.70 +#endif
17.71 +
17.72 +using namespace SourceMod;
17.73 +using namespace SourcePawn;
17.74 +
17.75 +class SDKExtension :
17.76 +#if defined SMEXT_CONF_METAMOD
17.77 + public ISmmPlugin,
17.78 +#endif
17.79 + public IExtensionInterface
17.80 +{
17.81 +public:
17.82 + /** Constructor */
17.83 + SDKExtension();
17.84 +public:
17.85 + /**
17.86 + * @brief This is called after the initial loading sequence has been processed.
17.87 + *
17.88 + * @param error Error message buffer.
17.89 + * @param maxlength Size of error message buffer.
17.90 + * @param late Whether or not the module was loaded after map load.
17.91 + * @return True to succeed loading, false to fail.
17.92 + */
17.93 + virtual bool SDK_OnLoad(char *error, size_t maxlength, bool late);
17.94 +
17.95 + /**
17.96 + * @brief This is called right before the extension is unloaded.
17.97 + */
17.98 + virtual void SDK_OnUnload();
17.99 +
17.100 + /**
17.101 + * @brief This is called once all known extensions have been loaded.
17.102 + */
17.103 + virtual void SDK_OnAllLoaded();
17.104 +
17.105 + /**
17.106 + * @brief Called when the pause state is changed.
17.107 + */
17.108 + virtual void SDK_OnPauseChange(bool paused);
17.109 +
17.110 +#if defined SMEXT_CONF_METAMOD
17.111 + /**
17.112 + * @brief Called when Metamod is attached, before the extension version is called.
17.113 + *
17.114 + * @param error Error buffer.
17.115 + * @param maxlength Maximum size of error buffer.
17.116 + * @param late Whether or not Metamod considers this a late load.
17.117 + * @return True to succeed, false to fail.
17.118 + */
17.119 + virtual bool SDK_OnMetamodLoad(ISmmAPI *ismm, char *error, size_t maxlength, bool late);
17.120 +
17.121 + /**
17.122 + * @brief Called when Metamod is detaching, after the extension version is called.
17.123 + * NOTE: By default this is blocked unless sent from SourceMod.
17.124 + *
17.125 + * @param error Error buffer.
17.126 + * @param maxlength Maximum size of error buffer.
17.127 + * @return True to succeed, false to fail.
17.128 + */
17.129 + virtual bool SDK_OnMetamodUnload(char *error, size_t maxlength);
17.130 +
17.131 + /**
17.132 + * @brief Called when Metamod's pause state is changing.
17.133 + * NOTE: By default this is blocked unless sent from SourceMod.
17.134 + *
17.135 + * @param paused Pause state being set.
17.136 + * @param error Error buffer.
17.137 + * @param maxlength Maximum size of error buffer.
17.138 + * @return True to succeed, false to fail.
17.139 + */
17.140 + virtual bool SDK_OnMetamodPauseChange(bool paused, char *error, size_t maxlength);
17.141 +#endif
17.142 +
17.143 +public: //IExtensionInterface
17.144 + virtual bool OnExtensionLoad(IExtension *me, IShareSys *sys, char *error, size_t maxlength, bool late);
17.145 + virtual void OnExtensionUnload();
17.146 + virtual void OnExtensionsAllLoaded();
17.147 +
17.148 + /** Returns whether or not this is a Metamod-based extension */
17.149 + virtual bool IsMetamodExtension();
17.150 +
17.151 + /**
17.152 + * @brief Called when the pause state changes.
17.153 + *
17.154 + * @param state True if being paused, false if being unpaused.
17.155 + */
17.156 + virtual void OnExtensionPauseChange(bool state);
17.157 +
17.158 + /** Returns name */
17.159 + virtual const char *GetExtensionName();
17.160 + /** Returns URL */
17.161 + virtual const char *GetExtensionURL();
17.162 + /** Returns log tag */
17.163 + virtual const char *GetExtensionTag();
17.164 + /** Returns author */
17.165 + virtual const char *GetExtensionAuthor();
17.166 + /** Returns version string */
17.167 + virtual const char *GetExtensionVerString();
17.168 + /** Returns description string */
17.169 + virtual const char *GetExtensionDescription();
17.170 + /** Returns date string */
17.171 + virtual const char *GetExtensionDateString();
17.172 +#if defined SMEXT_CONF_METAMOD
17.173 +public: //ISmmPlugin
17.174 + /** Called when the extension is attached to Metamod. */
17.175 + virtual bool Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlength, bool late);
17.176 + /** Returns the author to MM */
17.177 + virtual const char *GetAuthor();
17.178 + /** Returns the name to MM */
17.179 + virtual const char *GetName();
17.180 + /** Returns the description to MM */
17.181 + virtual const char *GetDescription();
17.182 + /** Returns the URL to MM */
17.183 + virtual const char *GetURL();
17.184 + /** Returns the license to MM */
17.185 + virtual const char *GetLicense();
17.186 + /** Returns the version string to MM */
17.187 + virtual const char *GetVersion();
17.188 + /** Returns the date string to MM */
17.189 + virtual const char *GetDate();
17.190 + /** Returns the logtag to MM */
17.191 + virtual const char *GetLogTag();
17.192 + /** Called on unload */
17.193 + virtual bool Unload(char *error, size_t maxlength);
17.194 + /** Called on pause */
17.195 + virtual bool Pause(char *error, size_t maxlength);
17.196 + /** Called on unpause */
17.197 + virtual bool Unpause(char *error, size_t maxlength);
17.198 +private:
17.199 + bool m_SourceMMLoaded;
17.200 + bool m_WeAreUnloaded;
17.201 + bool m_WeGotPauseChange;
17.202 +#endif
17.203 +};
17.204 +
17.205 +extern SDKExtension *g_pExtensionIface;
17.206 +extern IExtension *myself;
17.207 +
17.208 +extern IShareSys *g_pShareSys;
17.209 +extern IShareSys *sharesys; /* Note: Newer name */
17.210 +extern ISourceMod *g_pSM;
17.211 +extern ISourceMod *smutils; /* Note: Newer name */
17.212 +
17.213 +/* Optional interfaces are below */
17.214 +#if defined SMEXT_ENABLE_FORWARDSYS
17.215 +extern IForwardManager *g_pForwards;
17.216 +extern IForwardManager *forwards; /* Note: Newer name */
17.217 +#endif //SMEXT_ENABLE_FORWARDSYS
17.218 +#if defined SMEXT_ENABLE_HANDLESYS
17.219 +extern IHandleSys *g_pHandleSys;
17.220 +extern IHandleSys *handlesys; /* Note: Newer name */
17.221 +#endif //SMEXT_ENABLE_HANDLESYS
17.222 +#if defined SMEXT_ENABLE_PLAYERHELPERS
17.223 +extern IPlayerManager *playerhelpers;
17.224 +#endif //SMEXT_ENABLE_PLAYERHELPERS
17.225 +#if defined SMEXT_ENABLE_DBMANAGER
17.226 +extern IDBManager *dbi;
17.227 +#endif //SMEXT_ENABLE_DBMANAGER
17.228 +#if defined SMEXT_ENABLE_GAMECONF
17.229 +extern IGameConfigManager *gameconfs;
17.230 +#endif //SMEXT_ENABLE_DBMANAGER
17.231 +#if defined SMEXT_ENABLE_MEMUTILS
17.232 +extern IMemoryUtils *memutils;
17.233 +#endif
17.234 +#if defined SMEXT_ENABLE_GAMEHELPERS
17.235 +extern IGameHelpers *gamehelpers;
17.236 +#endif
17.237 +#if defined SMEXT_ENABLE_TIMERSYS
17.238 +extern ITimerSystem *timersys;
17.239 +#endif
17.240 +#if defined SMEXT_ENABLE_ADTFACTORY
17.241 +extern IADTFactory *adtfactory;
17.242 +#endif
17.243 +#if defined SMEXT_ENABLE_THREADER
17.244 +extern IThreader *threader;
17.245 +#endif
17.246 +#if defined SMEXT_ENABLE_LIBSYS
17.247 +extern ILibrarySys *libsys;
17.248 +#endif
17.249 +
17.250 +#if defined SMEXT_CONF_METAMOD
17.251 +PLUGIN_GLOBALVARS();
17.252 +extern IVEngineServer *engine;
17.253 +extern IServerGameDLL *gamedll;
17.254 +#endif
17.255 +
17.256 +/** Creates a SourceMod interface macro pair */
17.257 +#define SM_MKIFACE(name) SMINTERFACE_##name##_NAME, SMINTERFACE_##name##_VERSION
17.258 +/** Automates retrieving SourceMod interfaces */
17.259 +#define SM_GET_IFACE(prefix, addr) \
17.260 + if (!g_pShareSys->RequestInterface(SM_MKIFACE(prefix), myself, (SMInterface **)&addr)) \
17.261 + { \
17.262 + if (error) \
17.263 + { \
17.264 + snprintf(error, maxlength, "Could not find interface: %s (version: %d)", SMINTERFACE_##prefix##_NAME, SMINTERFACE_##prefix##_VERSION); \
17.265 + return false; \
17.266 + } \
17.267 + }
17.268 +/** Automates retrieving SourceMod interfaces when needed outside of SDK_OnLoad() */
17.269 +#define SM_GET_LATE_IFACE(prefix, addr) \
17.270 + g_pShareSys->RequestInterface(SM_MKIFACE(prefix), myself, (SMInterface **)&addr)
17.271 +/** Validates a SourceMod interface pointer */
17.272 +#define SM_CHECK_IFACE(prefix, addr) \
17.273 + if (!addr) \
17.274 + { \
17.275 + if (error) \
17.276 + { \
17.277 + snprintf(error, maxlength, "Could not find interface: %s", SMINTERFACE_##prefix##_NAME); \
17.278 + return false; \
17.279 + } \
17.280 + }
17.281 +
17.282 +#endif // _INCLUDE_SOURCEMOD_EXTENSION_BASESDK_H_
18.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
18.2 +++ b/extensions/sqlite/sm_memtable.cpp Sun Jul 29 01:15:31 2007 +0000
18.3 @@ -0,0 +1,104 @@
18.4 +/**
18.5 + * vim: set ts=4 :
18.6 + * ===============================================================
18.7 + * SourceMod SQLite Driver Extension
18.8 + * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
18.9 + * ===============================================================
18.10 + *
18.11 + * This program is free software; you can redistribute it and/or
18.12 + * modify it under the terms of the GNU General Public License
18.13 + * as published by the Free Software Foundation; either version 2
18.14 + * of the License, or (at your option) any later version.
18.15 + * This program is distributed in the hope that it will be useful,
18.16 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
18.17 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18.18 + * GNU General Public License for more details.
18.19 + *
18.20 + * You should have received a copy of the GNU General Public License
18.21 + * along with this program; if not, write to the Free Software
18.22 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18.23 + *
18.24 + * Version: $Id$
18.25 + */
18.26 +
18.27 +#include <string.h>
18.28 +#include <malloc.h>
18.29 +#include "sm_memtable.h"
18.30 +
18.31 +BaseMemTable::BaseMemTable(unsigned int init_size)
18.32 +{
18.33 + membase = (unsigned char *)malloc(init_size);
18.34 + size = init_size;
18.35 + tail = 0;
18.36 +}
18.37 +
18.38 +BaseMemTable::~BaseMemTable()
18.39 +{
18.40 + free(membase);
18.41 + membase = NULL;
18.42 +}
18.43 +
18.44 +int BaseMemTable::CreateMem(unsigned int addsize, void **addr)
18.45 +{
18.46 + int idx = (int)tail;
18.47 +
18.48 + while (tail + addsize >= size)
18.49 + {
18.50 + size *= 2;
18.51 + membase = (unsigned char *)realloc(membase, size);
18.52 + }
18.53 +
18.54 + tail += addsize;
18.55 +
18.56 + if (addr)
18.57 + {
18.58 + *addr = (void *)&membase[idx];
18.59 + }
18.60 +
18.61 + return idx;
18.62 +}
18.63 +
18.64 +void *BaseMemTable::GetAddress(int index)
18.65 +{
18.66 + if (index < 0 || (unsigned int)index >= tail)
18.67 + {
18.68 + return NULL;
18.69 + }
18.70 +
18.71 + return &membase[index];
18.72 +}
18.73 +
18.74 +void BaseMemTable::Reset()
18.75 +{
18.76 + tail = 0;
18.77 +}
18.78 +
18.79 +BaseStringTable::BaseStringTable(unsigned int init_size) : m_table(init_size)
18.80 +{
18.81 +}
18.82 +
18.83 +BaseStringTable::~BaseStringTable()
18.84 +{
18.85 +}
18.86 +
18.87 +int BaseStringTable::AddString(const char *string)
18.88 +{
18.89 + size_t len = strlen(string) + 1;
18.90 + int idx;
18.91 + char *addr;
18.92 +
18.93 + idx = m_table.CreateMem(len, (void **)&addr);
18.94 + strcpy(addr, string);
18.95 +
18.96 + return idx;
18.97 +}
18.98 +
18.99 +/*const char *BaseStringTable::GetString(int str)
18.100 +{
18.101 + return (const char *)m_table.GetAddress(str);
18.102 +}*/
18.103 +
18.104 +void BaseStringTable::Reset()
18.105 +{
18.106 + m_table.Reset();
18.107 +}
19.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
19.2 +++ b/extensions/sqlite/sm_memtable.h Sun Jul 29 01:15:31 2007 +0000
19.3 @@ -0,0 +1,97 @@
19.4 +/**
19.5 + * vim: set ts=4 :
19.6 + * ===============================================================
19.7 + * SourceMod SQLite Driver Extension
19.8 + * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
19.9 + * ===============================================================
19.10 + *
19.11 + * This program is free software; you can redistribute it and/or
19.12 + * modify it under the terms of the GNU General Public License
19.13 + * as published by the Free Software Foundation; either version 2
19.14 + * of the License, or (at your option) any later version.
19.15 + * This program is distributed in the hope that it will be useful,
19.16 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
19.17 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19.18 + * GNU General Public License for more details.
19.19 + *
19.20 + * You should have received a copy of the GNU General Public License
19.21 + * along with this program; if not, write to the Free Software
19.22 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19.23 + *
19.24 + * Version: $Id$
19.25 + */
19.26 +
19.27 +#ifndef _INCLUDE_SOURCEMOD_CORE_STRINGTABLE_H_
19.28 +#define _INCLUDE_SOURCEMOD_CORE_STRINGTABLE_H_
19.29 +
19.30 +class BaseMemTable
19.31 +{
19.32 +public:
19.33 + BaseMemTable(unsigned int init_size);
19.34 + ~BaseMemTable();
19.35 +public:
19.36 + /**
19.37 + * Allocates 'size' bytes of memory.
19.38 + * Optionally outputs the address through 'addr'.
19.39 + * Returns an index >= 0 on success, < 0 on failure.
19.40 + */
19.41 + int CreateMem(unsigned int size, void **addr);
19.42 +
19.43 + /**
19.44 + * Given an index into the memory table, returns its address.
19.45 + * Returns NULL if invalid.
19.46 + */
19.47 + void *GetAddress(int index);
19.48 +
19.49 + /**
19.50 + * Scraps the memory table. For caching purposes, the memory
19.51 + * is not freed, however subsequent calls to CreateMem() will
19.52 + * begin at the first index again.
19.53 + */
19.54 + void Reset();
19.55 +
19.56 +
19.57 +private:
19.58 + unsigned char *membase;
19.59 + unsigned int size;
19.60 + unsigned int tail;
19.61 +};
19.62 +
19.63 +class BaseStringTable
19.64 +{
19.65 +public:
19.66 + BaseStringTable(unsigned int init_size);
19.67 + ~BaseStringTable();
19.68 +public:
19.69 + /**
19.70 + * Adds a string to the string table and returns its index.
19.71 + */
19.72 + int AddString(const char *string);
19.73 +
19.74 + /**
19.75 + * Given an index into the string table, returns the associated string.
19.76 + */
19.77 + inline const char *GetString(int str)
19.78 + {
19.79 + return (const char *)m_table.GetAddress(str);
19.80 + }
19.81 +
19.82 + /**
19.83 + * Scraps the string table. For caching purposes, the memory
19.84 + * is not freed, however subsequent calls to AddString() will
19.85 + * begin at the first index again.
19.86 + */
19.87 + void Reset();
19.88 +
19.89 + /**
19.90 + * Returns the parent BaseMemTable that this string table uses.
19.91 + */
19.92 + inline BaseMemTable *GetMemTable()
19.93 + {
19.94 + return &m_table;
19.95 + }
19.96 +private:
19.97 + BaseMemTable m_table;
19.98 +};
19.99 +
19.100 +#endif //_INCLUDE_SOURCEMOD_CORE_STRINGTABLE_H_
20.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
20.2 +++ b/extensions/sqlite/sqlite-source/alter.c Sun Jul 29 01:15:31 2007 +0000
20.3 @@ -0,0 +1,609 @@
20.4 +/*
20.5 +** 2005 February 15
20.6 +**
20.7 +** The author disclaims copyright to this source code. In place of
20.8 +** a legal notice, here is a blessing:
20.9 +**
20.10 +** May you do good and not evil.
20.11 +** May you find forgiveness for yourself and forgive others.
20.12 +** May you share freely, never taking more than you give.
20.13 +**
20.14 +*************************************************************************
20.15 +** This file contains C code routines that used to generate VDBE code
20.16 +** that implements the ALTER TABLE command.
20.17 +**
20.18 +** $Id$
20.19 +*/
20.20 +#include "sqliteInt.h"
20.21 +#include <ctype.h>
20.22 +
20.23 +/*
20.24 +** The code in this file only exists if we are not omitting the
20.25 +** ALTER TABLE logic from the build.
20.26 +*/
20.27 +#ifndef SQLITE_OMIT_ALTERTABLE
20.28 +
20.29 +
20.30 +/*
20.31 +** This function is used by SQL generated to implement the
20.32 +** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
20.33 +** CREATE INDEX command. The second is a table name. The table name in
20.34 +** the CREATE TABLE or CREATE INDEX statement is replaced with the third
20.35 +** argument and the result returned. Examples:
20.36 +**
20.37 +** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
20.38 +** -> 'CREATE TABLE def(a, b, c)'
20.39 +**
20.40 +** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
20.41 +** -> 'CREATE INDEX i ON def(a, b, c)'
20.42 +*/
20.43 +static void renameTableFunc(
20.44 + sqlite3_context *context,
20.45 + int argc,
20.46 + sqlite3_value **argv
20.47 +){
20.48 + unsigned char const *zSql = sqlite3_value_text(argv[0]);
20.49 + unsigned char const *zTableName = sqlite3_value_text(argv[1]);
20.50 +
20.51 + int token;
20.52 + Token tname;
20.53 + unsigned char const *zCsr = zSql;
20.54 + int len = 0;
20.55 + char *zRet;
20.56 +
20.57 + /* The principle used to locate the table name in the CREATE TABLE
20.58 + ** statement is that the table name is the first token that is immediatedly
20.59 + ** followed by a left parenthesis - TK_LP - or "USING" TK_USING.
20.60 + */
20.61 + if( zSql ){
20.62 + do {
20.63 + if( !*zCsr ){
20.64 + /* Ran out of input before finding an opening bracket. Return NULL. */
20.65 + return;
20.66 + }
20.67 +
20.68 + /* Store the token that zCsr points to in tname. */
20.69 + tname.z = zCsr;
20.70 + tname.n = len;
20.71 +
20.72 + /* Advance zCsr to the next token. Store that token type in 'token',
20.73 + ** and it's length in 'len' (to be used next iteration of this loop).
20.74 + */
20.75 + do {
20.76 + zCsr += len;
20.77 + len = sqlite3GetToken(zCsr, &token);
20.78 + } while( token==TK_SPACE );
20.79 + assert( len>0 );
20.80 + } while( token!=TK_LP && token!=TK_USING );
20.81 +
20.82 + zRet = sqlite3MPrintf("%.*s%Q%s", tname.z - zSql, zSql,
20.83 + zTableName, tname.z+tname.n);
20.84 + sqlite3_result_text(context, zRet, -1, sqlite3FreeX);
20.85 + }
20.86 +}
20.87 +
20.88 +#ifndef SQLITE_OMIT_TRIGGER
20.89 +/* This function is used by SQL generated to implement the
20.90 +** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
20.91 +** statement. The second is a table name. The table name in the CREATE
20.92 +** TRIGGER statement is replaced with the third argument and the result
20.93 +** returned. This is analagous to renameTableFunc() above, except for CREATE
20.94 +** TRIGGER, not CREATE INDEX and CREATE TABLE.
20.95 +*/
20.96 +static void renameTriggerFunc(
20.97 + sqlite3_context *context,
20.98 + int argc,
20.99 + sqlite3_value **argv
20.100 +){
20.101 + unsigned char const *zSql = sqlite3_value_text(argv[0]);
20.102 + unsigned char const *zTableName = sqlite3_value_text(argv[1]);
20.103 +
20.104 + int token;
20.105 + Token tname;
20.106 + int dist = 3;
20.107 + unsigned char const *zCsr = zSql;
20.108 + int len = 0;
20.109 + char *zRet;
20.110 +
20.111 + /* The principle used to locate the table name in the CREATE TRIGGER
20.112 + ** statement is that the table name is the first token that is immediatedly
20.113 + ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
20.114 + ** of TK_WHEN, TK_BEGIN or TK_FOR.
20.115 + */
20.116 + if( zSql ){
20.117 + do {
20.118 +
20.119 + if( !*zCsr ){
20.120 + /* Ran out of input before finding the table name. Return NULL. */
20.121 + return;
20.122 + }
20.123 +
20.124 + /* Store the token that zCsr points to in tname. */
20.125 + tname.z = zCsr;
20.126 + tname.n = len;
20.127 +
20.128 + /* Advance zCsr to the next token. Store that token type in 'token',
20.129 + ** and it's length in 'len' (to be used next iteration of this loop).
20.130 + */
20.131 + do {
20.132 + zCsr += len;
20.133 + len = sqlite3GetToken(zCsr, &token);
20.134 + }while( token==TK_SPACE );
20.135 + assert( len>0 );
20.136 +
20.137 + /* Variable 'dist' stores the number of tokens read since the most
20.138 + ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
20.139 + ** token is read and 'dist' equals 2, the condition stated above
20.140 + ** to be met.
20.141 + **
20.142 + ** Note that ON cannot be a database, table or column name, so
20.143 + ** there is no need to worry about syntax like
20.144 + ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
20.145 + */
20.146 + dist++;
20.147 + if( token==TK_DOT || token==TK_ON ){
20.148 + dist = 0;
20.149 + }
20.150 + } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
20.151 +
20.152 + /* Variable tname now contains the token that is the old table-name
20.153 + ** in the CREATE TRIGGER statement.
20.154 + */
20.155 + zRet = sqlite3MPrintf("%.*s%Q%s", tname.z - zSql, zSql,
20.156 + zTableName, tname.z+tname.n);
20.157 + sqlite3_result_text(context, zRet, -1, sqlite3FreeX);
20.158 + }
20.159 +}
20.160 +#endif /* !SQLITE_OMIT_TRIGGER */
20.161 +
20.162 +/*
20.163 +** Register built-in functions used to help implement ALTER TABLE
20.164 +*/
20.165 +void sqlite3AlterFunctions(sqlite3 *db){
20.166 + static const struct {
20.167 + char *zName;
20.168 + signed char nArg;
20.169 + void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
20.170 + } aFuncs[] = {
20.171 + { "sqlite_rename_table", 2, renameTableFunc},
20.172 +#ifndef SQLITE_OMIT_TRIGGER
20.173 + { "sqlite_rename_trigger", 2, renameTriggerFunc},
20.174 +#endif
20.175 + };
20.176 + int i;
20.177 +
20.178 + for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
20.179 + sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
20.180 + SQLITE_UTF8, 0, aFuncs[i].xFunc, 0, 0);
20.181 + }
20.182 +}
20.183 +
20.184 +/*
20.185 +** Generate the text of a WHERE expression which can be used to select all
20.186 +** temporary triggers on table pTab from the sqlite_temp_master table. If
20.187 +** table pTab has no temporary triggers, or is itself stored in the
20.188 +** temporary database, NULL is returned.
20.189 +*/
20.190 +static char *whereTempTriggers(Parse *pParse, Table *pTab){
20.191 + Trigger *pTrig;
20.192 + char *zWhere = 0;
20.193 + char *tmp = 0;
20.194 + const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
20.195 +
20.196 + /* If the table is not located in the temp-db (in which case NULL is
20.197 + ** returned, loop through the tables list of triggers. For each trigger
20.198 + ** that is not part of the temp-db schema, add a clause to the WHERE
20.199 + ** expression being built up in zWhere.
20.200 + */
20.201 + if( pTab->pSchema!=pTempSchema ){
20.202 + for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
20.203 + if( pTrig->pSchema==pTempSchema ){
20.204 + if( !zWhere ){
20.205 + zWhere = sqlite3MPrintf("name=%Q", pTrig->name);
20.206 + }else{
20.207 + tmp = zWhere;
20.208 + zWhere = sqlite3MPrintf("%s OR name=%Q", zWhere, pTrig->name);
20.209 + sqliteFree(tmp);
20.210 + }
20.211 + }
20.212 + }
20.213 + }
20.214 + return zWhere;
20.215 +}
20.216 +
20.217 +/*
20.218 +** Generate code to drop and reload the internal representation of table
20.219 +** pTab from the database, including triggers and temporary triggers.
20.220 +** Argument zName is the name of the table in the database schema at
20.221 +** the time the generated code is executed. This can be different from
20.222 +** pTab->zName if this function is being called to code part of an
20.223 +** "ALTER TABLE RENAME TO" statement.
20.224 +*/
20.225 +static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
20.226 + Vdbe *v;
20.227 + char *zWhere;
20.228 + int iDb; /* Index of database containing pTab */
20.229 +#ifndef SQLITE_OMIT_TRIGGER
20.230 + Trigger *pTrig;
20.231 +#endif
20.232 +
20.233 + v = sqlite3GetVdbe(pParse);
20.234 + if( !v ) return;
20.235 + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
20.236 + assert( iDb>=0 );
20.237 +
20.238 +#ifndef SQLITE_OMIT_TRIGGER
20.239 + /* Drop any table triggers from the internal schema. */
20.240 + for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){
20.241 + int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
20.242 + assert( iTrigDb==iDb || iTrigDb==1 );
20.243 + sqlite3VdbeOp3(v, OP_DropTrigger, iTrigDb, 0, pTrig->name, 0);
20.244 + }
20.245 +#endif
20.246 +
20.247 + /* Drop the table and index from the internal schema */
20.248 + sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
20.249 +
20.250 + /* Reload the table, index and permanent trigger schemas. */
20.251 + zWhere = sqlite3MPrintf("tbl_name=%Q", zName);
20.252 + if( !zWhere ) return;
20.253 + sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, zWhere, P3_DYNAMIC);
20.254 +
20.255 +#ifndef SQLITE_OMIT_TRIGGER
20.256 + /* Now, if the table is not stored in the temp database, reload any temp
20.257 + ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
20.258 + */
20.259 + if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
20.260 + sqlite3VdbeOp3(v, OP_ParseSchema, 1, 0, zWhere, P3_DYNAMIC);
20.261 + }
20.262 +#endif
20.263 +}
20.264 +
20.265 +/*
20.266 +** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
20.267 +** command.
20.268 +*/
20.269 +void sqlite3AlterRenameTable(
20.270 + Parse *pParse, /* Parser context. */
20.271 + SrcList *pSrc, /* The table to rename. */
20.272 + Token *pName /* The new table name. */
20.273 +){
20.274 + int iDb; /* Database that contains the table */
20.275 + char *zDb; /* Name of database iDb */
20.276 + Table *pTab; /* Table being renamed */
20.277 + char *zName = 0; /* NULL-terminated version of pName */
20.278 + sqlite3 *db = pParse->db; /* Database connection */
20.279 + int nTabName; /* Number of UTF-8 characters in zTabName */
20.280 + const char *zTabName; /* Original name of the table */
20.281 + Vdbe *v;
20.282 +#ifndef SQLITE_OMIT_TRIGGER
20.283 + char *zWhere = 0; /* Where clause to locate temp triggers */
20.284 +#endif
20.285 + int isVirtualRename = 0; /* True if this is a v-table with an xRename() */
20.286 +
20.287 + if( sqlite3MallocFailed() ) goto exit_rename_table;
20.288 + assert( pSrc->nSrc==1 );
20.289 +
20.290 + pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
20.291 + if( !pTab ) goto exit_rename_table;
20.292 + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
20.293 + zDb = db->aDb[iDb].zName;
20.294 +
20.295 + /* Get a NULL terminated version of the new table name. */
20.296 + zName = sqlite3NameFromToken(pName);
20.297 + if( !zName ) goto exit_rename_table;
20.298 +
20.299 + /* Check that a table or index named 'zName' does not already exist
20.300 + ** in database iDb. If so, this is an error.
20.301 + */
20.302 + if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
20.303 + sqlite3ErrorMsg(pParse,
20.304 + "there is already another table or index with this name: %s", zName);
20.305 + goto exit_rename_table;
20.306 + }
20.307 +
20.308 + /* Make sure it is not a system table being altered, or a reserved name
20.309 + ** that the table is being renamed to.
20.310 + */
20.311 + if( strlen(pTab->zName)>6 && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ){
20.312 + sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
20.313 + goto exit_rename_table;
20.314 + }
20.315 + if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
20.316 + goto exit_rename_table;
20.317 + }
20.318 +
20.319 +#ifndef SQLITE_OMIT_AUTHORIZATION
20.320 + /* Invoke the authorization callback. */
20.321 + if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
20.322 + goto exit_rename_table;
20.323 + }
20.324 +#endif
20.325 +
20.326 +#ifndef SQLITE_OMIT_VIRTUALTABLE
20.327 + if( sqlite3ViewGetColumnNames(pParse, pTab) ){
20.328 + goto exit_rename_table;
20.329 + }
20.330 + if( IsVirtual(pTab) && pTab->pMod->pModule->xRename ){
20.331 + isVirtualRename = 1;
20.332 + }
20.333 +#endif
20.334 +
20.335 + /* Begin a transaction and code the VerifyCookie for database iDb.
20.336 + ** Then modify the schema cookie (since the ALTER TABLE modifies the
20.337 + ** schema). Open a statement transaction if the table is a virtual
20.338 + ** table.
20.339 + */
20.340 + v = sqlite3GetVdbe(pParse);
20.341 + if( v==0 ){
20.342 + goto exit_rename_table;
20.343 + }
20.344 + sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb);
20.345 + sqlite3ChangeCookie(db, v, iDb);
20.346 +
20.347 + /* If this is a virtual table, invoke the xRename() function if
20.348 + ** one is defined. The xRename() callback will modify the names
20.349 + ** of any resources used by the v-table implementation (including other
20.350 + ** SQLite tables) that are identified by the name of the virtual table.
20.351 + */
20.352 +#ifndef SQLITE_OMIT_VIRTUALTABLE
20.353 + if( isVirtualRename ){
20.354 + sqlite3VdbeOp3(v, OP_String8, 0, 0, zName, 0);
20.355 + sqlite3VdbeOp3(v, OP_VRename, 0, 0, (const char*)pTab->pVtab, P3_VTAB);
20.356 + }
20.357 +#endif
20.358 +
20.359 + /* figure out how many UTF-8 characters are in zName */
20.360 + zTabName = pTab->zName;
20.361 + nTabName = sqlite3Utf8CharLen(zTabName, -1);
20.362 +
20.363 + /* Modify the sqlite_master table to use the new table name. */
20.364 + sqlite3NestedParse(pParse,
20.365 + "UPDATE %Q.%s SET "
20.366 +#ifdef SQLITE_OMIT_TRIGGER
20.367 + "sql = sqlite_rename_table(sql, %Q), "
20.368 +#else
20.369 + "sql = CASE "
20.370 + "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
20.371 + "ELSE sqlite_rename_table(sql, %Q) END, "
20.372 +#endif
20.373 + "tbl_name = %Q, "
20.374 + "name = CASE "
20.375 + "WHEN type='table' THEN %Q "
20.376 + "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
20.377 + "'sqlite_autoindex_' || %Q || substr(name,%d+18,10) "
20.378 + "ELSE name END "
20.379 + "WHERE tbl_name=%Q AND "
20.380 + "(type='table' OR type='index' OR type='trigger');",
20.381 + zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
20.382 +#ifndef SQLITE_OMIT_TRIGGER
20.383 + zName,
20.384 +#endif
20.385 + zName, nTabName, zTabName
20.386 + );
20.387 +
20.388 +#ifndef SQLITE_OMIT_AUTOINCREMENT
20.389 + /* If the sqlite_sequence table exists in this database, then update
20.390 + ** it with the new table name.
20.391 + */
20.392 + if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
20.393 + sqlite3NestedParse(pParse,
20.394 + "UPDATE %Q.sqlite_sequence set name = %Q WHERE name = %Q",
20.395 + zDb, zName, pTab->zName);
20.396 + }
20.397 +#endif
20.398 +
20.399 +#ifndef SQLITE_OMIT_TRIGGER
20.400 + /* If there are TEMP triggers on this table, modify the sqlite_temp_master
20.401 + ** table. Don't do this if the table being ALTERed is itself located in
20.402 + ** the temp database.
20.403 + */
20.404 + if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
20.405 + sqlite3NestedParse(pParse,
20.406 + "UPDATE sqlite_temp_master SET "
20.407 + "sql = sqlite_rename_trigger(sql, %Q), "
20.408 + "tbl_name = %Q "
20.409 + "WHERE %s;", zName, zName, zWhere);
20.410 + sqliteFree(zWhere);
20.411 + }
20.412 +#endif
20.413 +
20.414 + /* Drop and reload the internal table schema. */
20.415 + reloadTableSchema(pParse, pTab, zName);
20.416 +
20.417 +exit_rename_table:
20.418 + sqlite3SrcListDelete(pSrc);
20.419 + sqliteFree(zName);
20.420 +}
20.421 +
20.422 +
20.423 +/*
20.424 +** This function is called after an "ALTER TABLE ... ADD" statement
20.425 +** has been parsed. Argument pColDef contains the text of the new
20.426 +** column definition.
20.427 +**
20.428 +** The Table structure pParse->pNewTable was extended to include
20.429 +** the new column during parsing.
20.430 +*/
20.431 +void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
20.432 + Table *pNew; /* Copy of pParse->pNewTable */
20.433 + Table *pTab; /* Table being altered */
20.434 + int iDb; /* Database number */
20.435 + const char *zDb; /* Database name */
20.436 + const char *zTab; /* Table name */
20.437 + char *zCol; /* Null-terminated column definition */
20.438 + Column *pCol; /* The new column */
20.439 + Expr *pDflt; /* Default value for the new column */
20.440 +
20.441 + if( pParse->nErr ) return;
20.442 + pNew = pParse->pNewTable;
20.443 + assert( pNew );
20.444 +
20.445 + iDb = sqlite3SchemaToIndex(pParse->db, pNew->pSchema);
20.446 + zDb = pParse->db->aDb[iDb].zName;
20.447 + zTab = pNew->zName;
20.448 + pCol = &pNew->aCol[pNew->nCol-1];
20.449 + pDflt = pCol->pDflt;
20.450 + pTab = sqlite3FindTable(pParse->db, zTab, zDb);
20.451 + assert( pTab );
20.452 +
20.453 +#ifndef SQLITE_OMIT_AUTHORIZATION
20.454 + /* Invoke the authorization callback. */
20.455 + if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
20.456 + return;
20.457 + }
20.458 +#endif
20.459 +
20.460 + /* If the default value for the new column was specified with a
20.461 + ** literal NULL, then set pDflt to 0. This simplifies checking
20.462 + ** for an SQL NULL default below.
20.463 + */
20.464 + if( pDflt && pDflt->op==TK_NULL ){
20.465 + pDflt = 0;
20.466 + }
20.467 +
20.468 + /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
20.469 + ** If there is a NOT NULL constraint, then the default value for the
20.470 + ** column must not be NULL.
20.471 + */
20.472 + if( pCol->isPrimKey ){
20.473 + sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
20.474 + return;
20.475 + }
20.476 + if( pNew->pIndex ){
20.477 + sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
20.478 + return;
20.479 + }
20.480 + if( pCol->notNull && !pDflt ){
20.481 + sqlite3ErrorMsg(pParse,
20.482 + "Cannot add a NOT NULL column with default value NULL");
20.483 + return;
20.484 + }
20.485 +
20.486 + /* Ensure the default expression is something that sqlite3ValueFromExpr()
20.487 + ** can handle (i.e. not CURRENT_TIME etc.)
20.488 + */
20.489 + if( pDflt ){
20.490 + sqlite3_value *pVal;
20.491 + if( sqlite3ValueFromExpr(pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
20.492 + /* malloc() has failed */
20.493 + return;
20.494 + }
20.495 + if( !pVal ){
20.496 + sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
20.497 + return;
20.498 + }
20.499 + sqlite3ValueFree(pVal);
20.500 + }
20.501 +
20.502 + /* Modify the CREATE TABLE statement. */
20.503 + zCol = sqliteStrNDup((char*)pColDef->z, pColDef->n);
20.504 + if( zCol ){
20.505 + char *zEnd = &zCol[pColDef->n-1];
20.506 + while( (zEnd>zCol && *zEnd==';') || isspace(*(unsigned char *)zEnd) ){
20.507 + *zEnd-- = '\0';
20.508 + }
20.509 + sqlite3NestedParse(pParse,
20.510 + "UPDATE %Q.%s SET "
20.511 + "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d,length(sql)) "
20.512 + "WHERE type = 'table' AND name = %Q",
20.513 + zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
20.514 + zTab
20.515 + );
20.516 + sqliteFree(zCol);
20.517 + }
20.518 +
20.519 + /* If the default value of the new column is NULL, then set the file
20.520 + ** format to 2. If the default value of the new column is not NULL,
20.521 + ** the file format becomes 3.
20.522 + */
20.523 + sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
20.524 +
20.525 + /* Reload the schema of the modified table. */
20.526 + reloadTableSchema(pParse, pTab, pTab->zName);
20.527 +}
20.528 +
20.529 +/*
20.530 +** This function is called by the parser after the table-name in
20.531 +** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
20.532 +** pSrc is the full-name of the table being altered.
20.533 +**
20.534 +** This routine makes a (partial) copy of the Table structure
20.535 +** for the table being altered and sets Parse.pNewTable to point
20.536 +** to it. Routines called by the parser as the column definition
20.537 +** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
20.538 +** the copy. The copy of the Table structure is deleted by tokenize.c
20.539 +** after parsing is finished.
20.540 +**
20.541 +** Routine sqlite3AlterFinishAddColumn() will be called to complete
20.542 +** coding the "ALTER TABLE ... ADD" statement.
20.543 +*/
20.544 +void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
20.545 + Table *pNew;
20.546 + Table *pTab;
20.547 + Vdbe *v;
20.548 + int iDb;
20.549 + int i;
20.550 + int nAlloc;
20.551 +
20.552 + /* Look up the table being altered. */
20.553 + assert( pParse->pNewTable==0 );
20.554 + if( sqlite3MallocFailed() ) goto exit_begin_add_column;
20.555 + pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
20.556 + if( !pTab ) goto exit_begin_add_column;
20.557 +
20.558 +#ifndef SQLITE_OMIT_VIRTUALTABLE
20.559 + if( IsVirtual(pTab) ){
20.560 + sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
20.561 + goto exit_begin_add_column;
20.562 + }
20.563 +#endif
20.564 +
20.565 + /* Make sure this is not an attempt to ALTER a view. */
20.566 + if( pTab->pSelect ){
20.567 + sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
20.568 + goto exit_begin_add_column;
20.569 + }
20.570 +
20.571 + assert( pTab->addColOffset>0 );
20.572 + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
20.573 +
20.574 + /* Put a copy of the Table struct in Parse.pNewTable for the
20.575 + ** sqlite3AddColumn() function and friends to modify.
20.576 + */
20.577 + pNew = (Table *)sqliteMalloc(sizeof(Table));
20.578 + if( !pNew ) goto exit_begin_add_column;
20.579 + pParse->pNewTable = pNew;
20.580 + pNew->nRef = 1;
20.581 + pNew->nCol = pTab->nCol;
20.582 + assert( pNew->nCol>0 );
20.583 + nAlloc = (((pNew->nCol-1)/8)*8)+8;
20.584 + assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
20.585 + pNew->aCol = (Column *)sqliteMalloc(sizeof(Column)*nAlloc);
20.586 + pNew->zName = sqliteStrDup(pTab->zName);
20.587 + if( !pNew->aCol || !pNew->zName ){
20.588 + goto exit_begin_add_column;
20.589 + }
20.590 + memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
20.591 + for(i=0; i<pNew->nCol; i++){
20.592 + Column *pCol = &pNew->aCol[i];
20.593 + pCol->zName = sqliteStrDup(pCol->zName);
20.594 + pCol->zColl = 0;
20.595 + pCol->zType = 0;
20.596 + pCol->pDflt = 0;
20.597 + }
20.598 + pNew->pSchema = pParse->db->aDb[iDb].pSchema;
20.599 + pNew->addColOffset = pTab->addColOffset;
20.600 + pNew->nRef = 1;
20.601 +
20.602 + /* Begin a transaction and increment the schema cookie. */
20.603 + sqlite3BeginWriteOperation(pParse, 0, iDb);
20.604 + v = sqlite3GetVdbe(pParse);
20.605 + if( !v ) goto exit_begin_add_column;
20.606 + sqlite3ChangeCookie(pParse->db, v, iDb);
20.607 +
20.608 +exit_begin_add_column:
20.609 + sqlite3SrcListDelete(pSrc);
20.610 + return;
20.611 +}
20.612 +#endif /* SQLITE_ALTER_TABLE */
21.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
21.2 +++ b/extensions/sqlite/sqlite-source/analyze.c Sun Jul 29 01:15:31 2007 +0000
21.3 @@ -0,0 +1,410 @@
21.4 +/*
21.5 +** 2005 July 8
21.6 +**
21.7 +** The author disclaims copyright to this source code. In place of
21.8 +** a legal notice, here is a blessing:
21.9 +**
21.10 +** May you do good and not evil.
21.11 +** May you find forgiveness for yourself and forgive others.
21.12 +** May you share freely, never taking more than you give.
21.13 +**
21.14 +*************************************************************************
21.15 +** This file contains code associated with the ANALYZE command.
21.16 +**
21.17 +** @(#) $Id$
21.18 +*/
21.19 +#ifndef SQLITE_OMIT_ANALYZE
21.20 +#include "sqliteInt.h"
21.21 +
21.22 +/*
21.23 +** This routine generates code that opens the sqlite_stat1 table on cursor
21.24 +** iStatCur.
21.25 +**
21.26 +** If the sqlite_stat1 tables does not previously exist, it is created.
21.27 +** If it does previously exist, all entires associated with table zWhere
21.28 +** are removed. If zWhere==0 then all entries are removed.
21.29 +*/
21.30 +static void openStatTable(
21.31 + Parse *pParse, /* Parsing context */
21.32 + int iDb, /* The database we are looking in */
21.33 + int iStatCur, /* Open the sqlite_stat1 table on this cursor */
21.34 + const char *zWhere /* Delete entries associated with this table */
21.35 +){
21.36 + sqlite3 *db = pParse->db;
21.37 + Db *pDb;
21.38 + int iRootPage;
21.39 + Table *pStat;
21.40 + Vdbe *v = sqlite3GetVdbe(pParse);
21.41 +
21.42 + if( v==0 ) return;
21.43 + pDb = &db->aDb[iDb];
21.44 + if( (pStat = sqlite3FindTable(db, "sqlite_stat1", pDb->zName))==0 ){
21.45 + /* The sqlite_stat1 tables does not exist. Create it.
21.46 + ** Note that a side-effect of the CREATE TABLE statement is to leave
21.47 + ** the rootpage of the new table on the top of the stack. This is
21.48 + ** important because the OpenWrite opcode below will be needing it. */
21.49 + sqlite3NestedParse(pParse,
21.50 + "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)",
21.51 + pDb->zName
21.52 + );
21.53 + iRootPage = 0; /* Cause rootpage to be taken from top of stack */
21.54 + }else if( zWhere ){
21.55 + /* The sqlite_stat1 table exists. Delete all entries associated with
21.56 + ** the table zWhere. */
21.57 + sqlite3NestedParse(pParse,
21.58 + "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q",
21.59 + pDb->zName, zWhere
21.60 + );
21.61 + iRootPage = pStat->tnum;
21.62 + }else{
21.63 + /* The sqlite_stat1 table already exists. Delete all rows. */
21.64 + iRootPage = pStat->tnum;
21.65 + sqlite3VdbeAddOp(v, OP_Clear, pStat->tnum, iDb);
21.66 + }
21.67 +
21.68 + /* Open the sqlite_stat1 table for writing. Unless it was created
21.69 + ** by this vdbe program, lock it for writing at the shared-cache level.
21.70 + ** If this vdbe did create the sqlite_stat1 table, then it must have
21.71 + ** already obtained a schema-lock, making the write-lock redundant.
21.72 + */
21.73 + if( iRootPage>0 ){
21.74 + sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1");
21.75 + }
21.76 + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
21.77 + sqlite3VdbeAddOp(v, OP_OpenWrite, iStatCur, iRootPage);
21.78 + sqlite3VdbeAddOp(v, OP_SetNumColumns, iStatCur, 3);
21.79 +}
21.80 +
21.81 +/*
21.82 +** Generate code to do an analysis of all indices associated with
21.83 +** a single table.
21.84 +*/
21.85 +static void analyzeOneTable(
21.86 + Parse *pParse, /* Parser context */
21.87 + Table *pTab, /* Table whose indices are to be analyzed */
21.88 + int iStatCur, /* Cursor that writes to the sqlite_stat1 table */
21.89 + int iMem /* Available memory locations begin here */
21.90 +){
21.91 + Index *pIdx; /* An index to being analyzed */
21.92 + int iIdxCur; /* Cursor number for index being analyzed */
21.93 + int nCol; /* Number of columns in the index */
21.94 + Vdbe *v; /* The virtual machine being built up */
21.95 + int i; /* Loop counter */
21.96 + int topOfLoop; /* The top of the loop */
21.97 + int endOfLoop; /* The end of the loop */
21.98 + int addr; /* The address of an instruction */
21.99 + int iDb; /* Index of database containing pTab */
21.100 +
21.101 + v = sqlite3GetVdbe(pParse);
21.102 + if( v==0 || pTab==0 || pTab->pIndex==0 ){
21.103 + /* Do no analysis for tables that have no indices */
21.104 + return;
21.105 + }
21.106 +
21.107 + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
21.108 + assert( iDb>=0 );
21.109 +#ifndef SQLITE_OMIT_AUTHORIZATION
21.110 + if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
21.111 + pParse->db->aDb[iDb].zName ) ){
21.112 + return;
21.113 + }
21.114 +#endif
21.115 +
21.116 + /* Establish a read-lock on the table at the shared-cache level. */
21.117 + sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
21.118 +
21.119 + iIdxCur = pParse->nTab;
21.120 + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
21.121 + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
21.122 +
21.123 + /* Open a cursor to the index to be analyzed
21.124 + */
21.125 + assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) );
21.126 + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
21.127 + VdbeComment((v, "# %s", pIdx->zName));
21.128 + sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum,
21.129 + (char *)pKey, P3_KEYINFO_HANDOFF);
21.130 + nCol = pIdx->nColumn;
21.131 + if( iMem+nCol*2>=pParse->nMem ){
21.132 + pParse->nMem = iMem+nCol*2+1;
21.133 + }
21.134 + sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, nCol+1);
21.135 +
21.136 + /* Memory cells are used as follows:
21.137 + **
21.138 + ** mem[iMem]: The total number of rows in the table.
21.139 + ** mem[iMem+1]: Number of distinct values in column 1
21.140 + ** ...
21.141 + ** mem[iMem+nCol]: Number of distinct values in column N
21.142 + ** mem[iMem+nCol+1] Last observed value of column 1
21.143 + ** ...
21.144 + ** mem[iMem+nCol+nCol]: Last observed value of column N
21.145 + **
21.146 + ** Cells iMem through iMem+nCol are initialized to 0. The others
21.147 + ** are initialized to NULL.
21.148 + */
21.149 + for(i=0; i<=nCol; i++){
21.150 + sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem+i);
21.151 + }
21.152 + for(i=0; i<nCol; i++){
21.153 + sqlite3VdbeAddOp(v, OP_MemNull, iMem+nCol+i+1, 0);
21.154 + }
21.155 +
21.156 + /* Do the analysis.
21.157 + */
21.158 + endOfLoop = sqlite3VdbeMakeLabel(v);
21.159 + sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, endOfLoop);
21.160 + topOfLoop = sqlite3VdbeCurrentAddr(v);
21.161 + sqlite3VdbeAddOp(v, OP_MemIncr, 1, iMem);
21.162 + for(i=0; i<nCol; i++){
21.163 + sqlite3VdbeAddOp(v, OP_Column, iIdxCur, i);
21.164 + sqlite3VdbeAddOp(v, OP_MemLoad, iMem+nCol+i+1, 0);
21.165 + sqlite3VdbeAddOp(v, OP_Ne, 0x100, 0);
21.166 + }
21.167 + sqlite3VdbeAddOp(v, OP_Goto, 0, endOfLoop);
21.168 + for(i=0; i<nCol; i++){
21.169 + addr = sqlite3VdbeAddOp(v, OP_MemIncr, 1, iMem+i+1);
21.170 + sqlite3VdbeChangeP2(v, topOfLoop + 3*i + 3, addr);
21.171 + sqlite3VdbeAddOp(v, OP_Column, iIdxCur, i);
21.172 + sqlite3VdbeAddOp(v, OP_MemStore, iMem+nCol+i+1, 1);
21.173 + }
21.174 + sqlite3VdbeResolveLabel(v, endOfLoop);
21.175 + sqlite3VdbeAddOp(v, OP_Next, iIdxCur, topOfLoop);
21.176 + sqlite3VdbeAddOp(v, OP_Close, iIdxCur, 0);
21.177 +
21.178 + /* Store the results.
21.179 + **
21.180 + ** The result is a single row of the sqlite_stat1 table. The first
21.181 + ** two columns are the names of the table and index. The third column
21.182 + ** is a string composed of a list of integer statistics about the
21.183 + ** index. The first integer in the list is the total number of entires
21.184 + ** in the index. There is one additional integer in the list for each
21.185 + ** column of the table. This additional integer is a guess of how many
21.186 + ** rows of the table the index will select. If D is the count of distinct
21.187 + ** values and K is the total number of rows, then the integer is computed
21.188 + ** as:
21.189 + **
21.190 + ** I = (K+D-1)/D
21.191 + **
21.192 + ** If K==0 then no entry is made into the sqlite_stat1 table.
21.193 + ** If K>0 then it is always the case the D>0 so division by zero
21.194 + ** is never possible.
21.195 + */
21.196 + sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
21.197 + addr = sqlite3VdbeAddOp(v, OP_IfNot, 0, 0);
21.198 + sqlite3VdbeAddOp(v, OP_NewRowid, iStatCur, 0);
21.199 + sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
21.200 + sqlite3VdbeOp3(v, OP_String8, 0, 0, pIdx->zName, 0);
21.201 + sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
21.202 + sqlite3VdbeOp3(v, OP_String8, 0, 0, " ", 0);
21.203 + for(i=0; i<nCol; i++){
21.204 + sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
21.205 + sqlite3VdbeAddOp(v, OP_MemLoad, iMem+i+1, 0);
21.206 + sqlite3VdbeAddOp(v, OP_Add, 0, 0);
21.207 + sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
21.208 + sqlite3VdbeAddOp(v, OP_MemLoad, iMem+i+1, 0);
21.209 + sqlite3VdbeAddOp(v, OP_Divide, 0, 0);
21.210 + sqlite3VdbeAddOp(v, OP_ToInt, 0, 0);
21.211 + if( i==nCol-1 ){
21.212 + sqlite3VdbeAddOp(v, OP_Concat, nCol*2-1, 0);
21.213 + }else{
21.214 + sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
21.215 + }
21.216 + }
21.217 + sqlite3VdbeOp3(v, OP_MakeRecord, 3, 0, "aaa", 0);
21.218 + sqlite3VdbeAddOp(v, OP_Insert, iStatCur, OPFLAG_APPEND);
21.219 + sqlite3VdbeJumpHere(v, addr);
21.220 + }
21.221 +}
21.222 +
21.223 +/*
21.224 +** Generate code that will cause the most recent index analysis to
21.225 +** be laoded into internal hash tables where is can be used.
21.226 +*/
21.227 +static void loadAnalysis(Parse *pParse, int iDb){
21.228 + Vdbe *v = sqlite3GetVdbe(pParse);
21.229 + if( v ){
21.230 + sqlite3VdbeAddOp(v, OP_LoadAnalysis, iDb, 0);
21.231 + }
21.232 +}
21.233 +
21.234 +/*
21.235 +** Generate code that will do an analysis of an entire database
21.236 +*/
21.237 +static void analyzeDatabase(Parse *pParse, int iDb){
21.238 + sqlite3 *db = pParse->db;
21.239 + Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
21.240 + HashElem *k;
21.241 + int iStatCur;
21.242 + int iMem;
21.243 +
21.244 + sqlite3BeginWriteOperation(pParse, 0, iDb);
21.245 + iStatCur = pParse->nTab++;
21.246 + openStatTable(pParse, iDb, iStatCur, 0);
21.247 + iMem = pParse->nMem;
21.248 + for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
21.249 + Table *pTab = (Table*)sqliteHashData(k);
21.250 + analyzeOneTable(pParse, pTab, iStatCur, iMem);
21.251 + }
21.252 + loadAnalysis(pParse, iDb);
21.253 +}
21.254 +
21.255 +/*
21.256 +** Generate code that will do an analysis of a single table in
21.257 +** a database.
21.258 +*/
21.259 +static void analyzeTable(Parse *pParse, Table *pTab){
21.260 + int iDb;
21.261 + int iStatCur;
21.262 +
21.263 + assert( pTab!=0 );
21.264 + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
21.265 + sqlite3BeginWriteOperation(pParse, 0, iDb);
21.266 + iStatCur = pParse->nTab++;
21.267 + openStatTable(pParse, iDb, iStatCur, pTab->zName);
21.268 + analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem);
21.269 + loadAnalysis(pParse, iDb);
21.270 +}
21.271 +
21.272 +/*
21.273 +** Generate code for the ANALYZE command. The parser calls this routine
21.274 +** when it recognizes an ANALYZE command.
21.275 +**
21.276 +** ANALYZE -- 1
21.277 +** ANALYZE <database> -- 2
21.278 +** ANALYZE ?<database>.?<tablename> -- 3
21.279 +**
21.280 +** Form 1 causes all indices in all attached databases to be analyzed.
21.281 +** Form 2 analyzes all indices the single database named.
21.282 +** Form 3 analyzes all indices associated with the named table.
21.283 +*/
21.284 +void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
21.285 + sqlite3 *db = pParse->db;
21.286 + int iDb;
21.287 + int i;
21.288 + char *z, *zDb;
21.289 + Table *pTab;
21.290 + Token *pTableName;
21.291 +
21.292 + /* Read the database schema. If an error occurs, leave an error message
21.293 + ** and code in pParse and return NULL. */
21.294 + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
21.295 + return;
21.296 + }
21.297 +
21.298 + if( pName1==0 ){
21.299 + /* Form 1: Analyze everything */
21.300 + for(i=0; i<db->nDb; i++){
21.301 + if( i==1 ) continue; /* Do not analyze the TEMP database */
21.302 + analyzeDatabase(pParse, i);
21.303 + }
21.304 + }else if( pName2==0 || pName2->n==0 ){
21.305 + /* Form 2: Analyze the database or table named */
21.306 + iDb = sqlite3FindDb(db, pName1);
21.307 + if( iDb>=0 ){
21.308 + analyzeDatabase(pParse, iDb);
21.309 + }else{
21.310 + z = sqlite3NameFromToken(pName1);
21.311 + pTab = sqlite3LocateTable(pParse, z, 0);
21.312 + sqliteFree(z);
21.313 + if( pTab ){
21.314 + analyzeTable(pParse, pTab);
21.315 + }
21.316 + }
21.317 + }else{
21.318 + /* Form 3: Analyze the fully qualified table name */
21.319 + iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
21.320 + if( iDb>=0 ){
21.321 + zDb = db->aDb[iDb].zName;
21.322 + z = sqlite3NameFromToken(pTableName);
21.323 + if( z ){
21.324 + pTab = sqlite3LocateTable(pParse, z, zDb);
21.325 + sqliteFree(z);
21.326 + if( pTab ){
21.327 + analyzeTable(pParse, pTab);
21.328 + }
21.329 + }
21.330 + }
21.331 + }
21.332 +}
21.333 +
21.334 +/*
21.335 +** Used to pass information from the analyzer reader through to the
21.336 +** callback routine.
21.337 +*/
21.338 +typedef struct analysisInfo analysisInfo;
21.339 +struct analysisInfo {
21.340 + sqlite3 *db;
21.341 + const char *zDatabase;
21.342 +};
21.343 +
21.344 +/*
21.345 +** This callback is invoked once for each index when reading the
21.346 +** sqlite_stat1 table.
21.347 +**
21.348 +** argv[0] = name of the index
21.349 +** argv[1] = results of analysis - on integer for each column
21.350 +*/
21.351 +static int analysisLoader(void *pData, int argc, char **argv, char **azNotUsed){
21.352 + analysisInfo *pInfo = (analysisInfo*)pData;
21.353 + Index *pIndex;
21.354 + int i, c;
21.355 + unsigned int v;
21.356 + const char *z;
21.357 +
21.358 + assert( argc==2 );
21.359 + if( argv==0 || argv[0]==0 || argv[1]==0 ){
21.360 + return 0;
21.361 + }
21.362 + pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
21.363 + if( pIndex==0 ){
21.364 + return 0;
21.365 + }
21.366 + z = argv[1];
21.367 + for(i=0; *z && i<=pIndex->nColumn; i++){
21.368 + v = 0;
21.369 + while( (c=z[0])>='0' && c<='9' ){
21.370 + v = v*10 + c - '0';
21.371 + z++;
21.372 + }
21.373 + pIndex->aiRowEst[i] = v;
21.374 + if( *z==' ' ) z++;
21.375 + }
21.376 + return 0;
21.377 +}
21.378 +
21.379 +/*
21.380 +** Load the content of the sqlite_stat1 table into the index hash tables.
21.381 +*/
21.382 +int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
21.383 + analysisInfo sInfo;
21.384 + HashElem *i;
21.385 + char *zSql;
21.386 + int rc;
21.387 +
21.388 + /* Clear any prior statistics */
21.389 + for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
21.390 + Index *pIdx = sqliteHashData(i);
21.391 + sqlite3DefaultRowEst(pIdx);
21.392 + }
21.393 +
21.394 + /* Check to make sure the sqlite_stat1 table existss */
21.395 + sInfo.db = db;
21.396 + sInfo.zDatabase = db->aDb[iDb].zName;
21.397 + if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
21.398 + return SQLITE_ERROR;
21.399 + }
21.400 +
21.401 +
21.402 + /* Load new statistics out of the sqlite_stat1 table */
21.403 + zSql = sqlite3MPrintf("SELECT idx, stat FROM %Q.sqlite_stat1",
21.404 + sInfo.zDatabase);
21.405 + sqlite3SafetyOff(db);
21.406 + rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
21.407 + sqlite3SafetyOn(db);
21.408 + sqliteFree(zSql);
21.409 + return rc;
21.410 +}
21.411 +
21.412 +
21.413 +#endif /* SQLITE_OMIT_ANALYZE */
22.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
22.2 +++ b/extensions/sqlite/sqlite-source/attach.c Sun Jul 29 01:15:31 2007 +0000
22.3 @@ -0,0 +1,516 @@
22.4 +/*
22.5 +** 2003 April 6
22.6 +**
22.7 +** The author disclaims copyright to this source code. In place of
22.8 +** a legal notice, here is a blessing:
22.9 +**
22.10 +** May you do good and not evil.
22.11 +** May you find forgiveness for yourself and forgive others.
22.12 +** May you share freely, never taking more than you give.
22.13 +**
22.14 +*************************************************************************
22.15 +** This file contains code used to implement the ATTACH and DETACH commands.
22.16 +**
22.17 +** $Id$
22.18 +*/
22.19 +#include "sqliteInt.h"
22.20 +
22.21 +#ifndef SQLITE_OMIT_ATTACH
22.22 +/*
22.23 +** Resolve an expression that was part of an ATTACH or DETACH statement. This
22.24 +** is slightly different from resolving a normal SQL expression, because simple
22.25 +** identifiers are treated as strings, not possible column names or aliases.
22.26 +**
22.27 +** i.e. if the parser sees:
22.28 +**
22.29 +** ATTACH DATABASE abc AS def
22.30 +**
22.31 +** it treats the two expressions as literal strings 'abc' and 'def' instead of
22.32 +** looking for columns of the same name.
22.33 +**
22.34 +** This only applies to the root node of pExpr, so the statement:
22.35 +**
22.36 +** ATTACH DATABASE abc||def AS 'db2'
22.37 +**
22.38 +** will fail because neither abc or def can be resolved.
22.39 +*/
22.40 +static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
22.41 +{
22.42 + int rc = SQLITE_OK;
22.43 + if( pExpr ){
22.44 + if( pExpr->op!=TK_ID ){
22.45 + rc = sqlite3ExprResolveNames(pName, pExpr);
22.46 + if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
22.47 + sqlite3ErrorMsg(pName->pParse, "invalid name: \"%T\"", &pExpr->span);
22.48 + return SQLITE_ERROR;
22.49 + }
22.50 + }else{
22.51 + pExpr->op = TK_STRING;
22.52 + }
22.53 + }
22.54 + return rc;
22.55 +}
22.56 +
22.57 +/*
22.58 +** An SQL user-function registered to do the work of an ATTACH statement. The
22.59 +** three arguments to the function come directly from an attach statement:
22.60 +**
22.61 +** ATTACH DATABASE x AS y KEY z
22.62 +**
22.63 +** SELECT sqlite_attach(x, y, z)
22.64 +**
22.65 +** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
22.66 +** third argument.
22.67 +*/
22.68 +static void attachFunc(
22.69 + sqlite3_context *context,
22.70 + int argc,
22.71 + sqlite3_value **argv
22.72 +){
22.73 + int i;
22.74 + int rc = 0;
22.75 + sqlite3 *db = sqlite3_user_data(context);
22.76 + const char *zName;
22.77 + const char *zFile;
22.78 + Db *aNew;
22.79 + char zErr[128];
22.80 + char *zErrDyn = 0;
22.81 +
22.82 + zFile = (const char *)sqlite3_value_text(argv[0]);
22.83 + zName = (const char *)sqlite3_value_text(argv[1]);
22.84 + if( zFile==0 ) zFile = "";
22.85 + if( zName==0 ) zName = "";
22.86 +
22.87 + /* Check for the following errors:
22.88 + **
22.89 + ** * Too many attached databases,
22.90 + ** * Transaction currently open
22.91 + ** * Specified database name already being used.
22.92 + */
22.93 + if( db->nDb>=SQLITE_MAX_ATTACHED+2 ){
22.94 + sqlite3_snprintf(
22.95 + sizeof(zErr), zErr, "too many attached databases - max %d",
22.96 + SQLITE_MAX_ATTACHED
22.97 + );
22.98 + goto attach_error;
22.99 + }
22.100 + if( !db->autoCommit ){
22.101 + sqlite3_snprintf(sizeof(zErr), zErr,
22.102 + "cannot ATTACH database within transaction");
22.103 + goto attach_error;
22.104 + }
22.105 + for(i=0; i<db->nDb; i++){
22.106 + char *z = db->aDb[i].zName;
22.107 + if( z && zName && sqlite3StrICmp(z, zName)==0 ){
22.108 + sqlite3_snprintf(sizeof(zErr), zErr, "database %s is already in use", zName);
22.109 + goto attach_error;
22.110 + }
22.111 + }
22.112 +
22.113 + /* Allocate the new entry in the db->aDb[] array and initialise the schema
22.114 + ** hash tables.
22.115 + */
22.116 + if( db->aDb==db->aDbStatic ){
22.117 + aNew = sqliteMalloc( sizeof(db->aDb[0])*3 );
22.118 + if( aNew==0 ){
22.119 + return;
22.120 + }
22.121 + memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
22.122 + }else{
22.123 + aNew = sqliteRealloc(db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
22.124 + if( aNew==0 ){
22.125 + return;
22.126 + }
22.127 + }
22.128 + db->aDb = aNew;
22.129 + aNew = &db->aDb[db->nDb++];
22.130 + memset(aNew, 0, sizeof(*aNew));
22.131 +
22.132 + /* Open the database file. If the btree is successfully opened, use
22.133 + ** it to obtain the database schema. At this point the schema may
22.134 + ** or may not be initialised.
22.135 + */
22.136 + rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE, &aNew->pBt);
22.137 + if( rc==SQLITE_OK ){
22.138 + aNew->pSchema = sqlite3SchemaGet(aNew->pBt);
22.139 + if( !aNew->pSchema ){
22.140 + rc = SQLITE_NOMEM;
22.141 + }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
22.142 + sqlite3_snprintf(sizeof(zErr), zErr,
22.143 + "attached databases must use the same text encoding as main database");
22.144 + goto attach_error;
22.145 + }
22.146 + sqlite3PagerLockingMode(sqlite3BtreePager(aNew->pBt), db->dfltLockMode);
22.147 + }
22.148 + aNew->zName = sqliteStrDup(zName);
22.149 + aNew->safety_level = 3;
22.150 +
22.151 +#if SQLITE_HAS_CODEC
22.152 + {
22.153 + extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
22.154 + extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
22.155 + int nKey;
22.156 + char *zKey;
22.157 + int t = sqlite3_value_type(argv[2]);
22.158 + switch( t ){
22.159 + case SQLITE_INTEGER:
22.160 + case SQLITE_FLOAT:
22.161 + zErrDyn = sqliteStrDup("Invalid key value");
22.162 + rc = SQLITE_ERROR;
22.163 + break;
22.164 +
22.165 + case SQLITE_TEXT:
22.166 + case SQLITE_BLOB:
22.167 + nKey = sqlite3_value_bytes(argv[2]);
22.168 + zKey = (char *)sqlite3_value_blob(argv[2]);
22.169 + sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
22.170 + break;
22.171 +
22.172 + case SQLITE_NULL:
22.173 + /* No key specified. Use the key from the main database */
22.174 + sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
22.175 + sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
22.176 + break;
22.177 + }
22.178 + }
22.179 +#endif
22.180 +
22.181 + /* If the file was opened successfully, read the schema for the new database.
22.182 + ** If this fails, or if opening the file failed, then close the file and
22.183 + ** remove the entry from the db->aDb[] array. i.e. put everything back the way
22.184 + ** we found it.
22.185 + */
22.186 + if( rc==SQLITE_OK ){
22.187 + sqlite3SafetyOn(db);
22.188 + rc = sqlite3Init(db, &zErrDyn);
22.189 + sqlite3SafetyOff(db);
22.190 + }
22.191 + if( rc ){
22.192 + int iDb = db->nDb - 1;
22.193 + assert( iDb>=2 );
22.194 + if( db->aDb[iDb].pBt ){
22.195 + sqlite3BtreeClose(db->aDb[iDb].pBt);
22.196 + db->aDb[iDb].pBt = 0;
22.197 + db->aDb[iDb].pSchema = 0;
22.198 + }
22.199 + sqlite3ResetInternalSchema(db, 0);
22.200 + db->nDb = iDb;
22.201 + if( rc==SQLITE_NOMEM ){
22.202 + sqlite3FailedMalloc();
22.203 + sqlite3_snprintf(sizeof(zErr),zErr, "out of memory");
22.204 + }else{
22.205 + sqlite3_snprintf(sizeof(zErr),zErr, "unable to open database: %s", zFile);
22.206 + }
22.207 + goto attach_error;
22.208 + }
22.209 +
22.210 + return;
22.211 +
22.212 +attach_error:
22.213 + /* Return an error if we get here */
22.214 + if( zErrDyn ){
22.215 + sqlite3_result_error(context, zErrDyn, -1);
22.216 + sqliteFree(zErrDyn);
22.217 + }else{
22.218 + zErr[sizeof(zErr)-1] = 0;
22.219 + sqlite3_result_error(context, zErr, -1);
22.220 + }
22.221 +}
22.222 +
22.223 +/*
22.224 +** An SQL user-function registered to do the work of an DETACH statement. The
22.225 +** three arguments to the function come directly from a detach statement:
22.226 +**
22.227 +** DETACH DATABASE x
22.228 +**
22.229 +** SELECT sqlite_detach(x)
22.230 +*/
22.231 +static void detachFunc(
22.232 + sqlite3_context *context,
22.233 + int argc,
22.234 + sqlite3_value **argv
22.235 +){
22.236 + const char *zName = (const char *)sqlite3_value_text(argv[0]);
22.237 + sqlite3 *db = sqlite3_user_data(context);
22.238 + int i;
22.239 + Db *pDb = 0;
22.240 + char zErr[128];
22.241 +
22.242 + if( zName==0 ) zName = "";
22.243 + for(i=0; i<db->nDb; i++){
22.244 + pDb = &db->aDb[i];
22.245 + if( pDb->pBt==0 ) continue;
22.246 + if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
22.247 + }
22.248 +
22.249 + if( i>=db->nDb ){
22.250 + sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
22.251 + goto detach_error;
22.252 + }
22.253 + if( i<2 ){
22.254 + sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
22.255 + goto detach_error;
22.256 + }
22.257 + if( !db->autoCommit ){
22.258 + sqlite3_snprintf(sizeof(zErr), zErr,
22.259 + "cannot DETACH database within transaction");
22.260 + goto detach_error;
22.261 + }
22.262 + if( sqlite3BtreeIsInReadTrans(pDb->pBt) ){
22.263 + sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
22.264 + goto detach_error;
22.265 + }
22.266 +
22.267 + sqlite3BtreeClose(pDb->pBt);
22.268 + pDb->pBt = 0;
22.269 + pDb->pSchema = 0;
22.270 + sqlite3ResetInternalSchema(db, 0);
22.271 + return;
22.272 +
22.273 +detach_error:
22.274 + sqlite3_result_error(context, zErr, -1);
22.275 +}
22.276 +
22.277 +/*
22.278 +** This procedure generates VDBE code for a single invocation of either the
22.279 +** sqlite_detach() or sqlite_attach() SQL user functions.
22.280 +*/
22.281 +static void codeAttach(
22.282 + Parse *pParse, /* The parser context */
22.283 + int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
22.284 + const char *zFunc, /* Either "sqlite_attach" or "sqlite_detach */
22.285 + int nFunc, /* Number of args to pass to zFunc */
22.286 + Expr *pAuthArg, /* Expression to pass to authorization callback */
22.287 + Expr *pFilename, /* Name of database file */
22.288 + Expr *pDbname, /* Name of the database to use internally */
22.289 + Expr *pKey /* Database key for encryption extension */
22.290 +){
22.291 + int rc;
22.292 + NameContext sName;
22.293 + Vdbe *v;
22.294 + FuncDef *pFunc;
22.295 + sqlite3* db = pParse->db;
22.296 +
22.297 +#ifndef SQLITE_OMIT_AUTHORIZATION
22.298 + assert( sqlite3MallocFailed() || pAuthArg );
22.299 + if( pAuthArg ){
22.300 + char *zAuthArg = sqlite3NameFromToken(&pAuthArg->span);
22.301 + if( !zAuthArg ){
22.302 + goto attach_end;
22.303 + }
22.304 + rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
22.305 + sqliteFree(zAuthArg);
22.306 + if(rc!=SQLITE_OK ){
22.307 + goto attach_end;
22.308 + }
22.309 + }
22.310 +#endif /* SQLITE_OMIT_AUTHORIZATION */
22.311 +
22.312 + memset(&sName, 0, sizeof(NameContext));
22.313 + sName.pParse = pParse;
22.314 +
22.315 + if(
22.316 + SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
22.317 + SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
22.318 + SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
22.319 + ){
22.320 + pParse->nErr++;
22.321 + goto attach_end;
22.322 + }
22.323 +
22.324 + v = sqlite3GetVdbe(pParse);
22.325 + sqlite3ExprCode(pParse, pFilename);
22.326 + sqlite3ExprCode(pParse, pDbname);
22.327 + sqlite3ExprCode(pParse, pKey);
22.328 +
22.329 + assert( v || sqlite3MallocFailed() );
22.330 + if( v ){
22.331 + sqlite3VdbeAddOp(v, OP_Function, 0, nFunc);
22.332 + pFunc = sqlite3FindFunction(db, zFunc, strlen(zFunc), nFunc, SQLITE_UTF8,0);
22.333 + sqlite3VdbeChangeP3(v, -1, (char *)pFunc, P3_FUNCDEF);
22.334 +
22.335 + /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
22.336 + ** statement only). For DETACH, set it to false (expire all existing
22.337 + ** statements).
22.338 + */
22.339 + sqlite3VdbeAddOp(v, OP_Expire, (type==SQLITE_ATTACH), 0);
22.340 + }
22.341 +
22.342 +attach_end:
22.343 + sqlite3ExprDelete(pFilename);
22.344 + sqlite3ExprDelete(pDbname);
22.345 + sqlite3ExprDelete(pKey);
22.346 +}
22.347 +
22.348 +/*
22.349 +** Called by the parser to compile a DETACH statement.
22.350 +**
22.351 +** DETACH pDbname
22.352 +*/
22.353 +void sqlite3Detach(Parse *pParse, Expr *pDbname){
22.354 + codeAttach(pParse, SQLITE_DETACH, "sqlite_detach", 1, pDbname, 0, 0, pDbname);
22.355 +}
22.356 +
22.357 +/*
22.358 +** Called by the parser to compile an ATTACH statement.
22.359 +**
22.360 +** ATTACH p AS pDbname KEY pKey
22.361 +*/
22.362 +void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
22.363 + codeAttach(pParse, SQLITE_ATTACH, "sqlite_attach", 3, p, p, pDbname, pKey);
22.364 +}
22.365 +#endif /* SQLITE_OMIT_ATTACH */
22.366 +
22.367 +/*
22.368 +** Register the functions sqlite_attach and sqlite_detach.
22.369 +*/
22.370 +void sqlite3AttachFunctions(sqlite3 *db){
22.371 +#ifndef SQLITE_OMIT_ATTACH
22.372 + static const int enc = SQLITE_UTF8;
22.373 + sqlite3CreateFunc(db, "sqlite_attach", 3, enc, db, attachFunc, 0, 0);
22.374 + sqlite3CreateFunc(db, "sqlite_detach", 1, enc, db, detachFunc, 0, 0);
22.375 +#endif
22.376 +}
22.377 +
22.378 +/*
22.379 +** Initialize a DbFixer structure. This routine must be called prior
22.380 +** to passing the structure to one of the sqliteFixAAAA() routines below.
22.381 +**
22.382 +** The return value indicates whether or not fixation is required. TRUE
22.383 +** means we do need to fix the database references, FALSE means we do not.
22.384 +*/
22.385 +int sqlite3FixInit(
22.386 + DbFixer *pFix, /* The fixer to be initialized */
22.387 + Parse *pParse, /* Error messages will be written here */
22.388 + int iDb, /* This is the database that must be used */
22.389 + const char *zType, /* "view", "trigger", or "index" */
22.390 + const Token *pName /* Name of the view, trigger, or index */
22.391 +){
22.392 + sqlite3 *db;
22.393 +
22.394 + if( iDb<0 || iDb==1 ) return 0;
22.395 + db = pParse->db;
22.396 + assert( db->nDb>iDb );
22.397 + pFix->pParse = pParse;
22.398 + pFix->zDb = db->aDb[iDb].zName;
22.399 + pFix->zType = zType;
22.400 + pFix->pName = pName;
22.401 + return 1;
22.402 +}
22.403 +
22.404 +/*
22.405 +** The following set of routines walk through the parse tree and assign
22.406 +** a specific database to all table references where the database name
22.407 +** was left unspecified in the original SQL statement. The pFix structure
22.408 +** must have been initialized by a prior call to sqlite3FixInit().
22.409 +**
22.410 +** These routines are used to make sure that an index, trigger, or
22.411 +** view in one database does not refer to objects in a different database.
22.412 +** (Exception: indices, triggers, and views in the TEMP database are
22.413 +** allowed to refer to anything.) If a reference is explicitly made
22.414 +** to an object in a different database, an error message is added to
22.415 +** pParse->zErrMsg and these routines return non-zero. If everything
22.416 +** checks out, these routines return 0.
22.417 +*/
22.418 +int sqlite3FixSrcList(
22.419 + DbFixer *pFix, /* Context of the fixation */
22.420 + SrcList *pList /* The Source list to check and modify */
22.421 +){
22.422 + int i;
22.423 + const char *zDb;
22.424 + struct SrcList_item *pItem;
22.425 +
22.426 + if( pList==0 ) return 0;
22.427 + zDb = pFix->zDb;
22.428 + for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
22.429 + if( pItem->zDatabase==0 ){
22.430 + pItem->zDatabase = sqliteStrDup(zDb);
22.431 + }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
22.432 + sqlite3ErrorMsg(pFix->pParse,
22.433 + "%s %T cannot reference objects in database %s",
22.434 + pFix->zType, pFix->pName, pItem->zDatabase);
22.435 + return 1;
22.436 + }
22.437 +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
22.438 + if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
22.439 + if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
22.440 +#endif
22.441 + }
22.442 + return 0;
22.443 +}
22.444 +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
22.445 +int sqlite3FixSelect(
22.446 + DbFixer *pFix, /* Context of the fixation */
22.447 + Select *pSelect /* The SELECT statement to be fixed to one database */
22.448 +){
22.449 + while( pSelect ){
22.450 + if( sqlite3FixExprList(pFix, pSelect->pEList) ){
22.451 + return 1;
22.452 + }
22.453 + if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
22.454 + return 1;
22.455 + }
22.456 + if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
22.457 + return 1;
22.458 + }
22.459 + if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
22.460 + return 1;
22.461 + }
22.462 + pSelect = pSelect->pPrior;
22.463 + }
22.464 + return 0;
22.465 +}
22.466 +int sqlite3FixExpr(
22.467 + DbFixer *pFix, /* Context of the fixation */
22.468 + Expr *pExpr /* The expression to be fixed to one database */
22.469 +){
22.470 + while( pExpr ){
22.471 + if( sqlite3FixSelect(pFix, pExpr->pSelect) ){
22.472 + return 1;
22.473 + }
22.474 + if( sqlite3FixExprList(pFix, pExpr->pList) ){
22.475 + return 1;
22.476 + }
22.477 + if( sqlite3FixExpr(pFix, pExpr->pRight) ){
22.478 + return 1;
22.479 + }
22.480 + pExpr = pExpr->pLeft;
22.481 + }
22.482 + return 0;
22.483 +}
22.484 +int sqlite3FixExprList(
22.485 + DbFixer *pFix, /* Context of the fixation */
22.486 + ExprList *pList /* The expression to be fixed to one database */
22.487 +){
22.488 + int i;
22.489 + struct ExprList_item *pItem;
22.490 + if( pList==0 ) return 0;
22.491 + for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
22.492 + if( sqlite3FixExpr(pFix, pItem->pExpr) ){
22.493 + return 1;
22.494 + }
22.495 + }
22.496 + return 0;
22.497 +}
22.498 +#endif
22.499 +
22.500 +#ifndef SQLITE_OMIT_TRIGGER
22.501 +int sqlite3FixTriggerStep(
22.502 + DbFixer *pFix, /* Context of the fixation */
22.503 + TriggerStep *pStep /* The trigger step be fixed to one database */
22.504 +){
22.505 + while( pStep ){
22.506 + if( sqlite3FixSelect(pFix, pStep->pSelect) ){
22.507 + return 1;
22.508 + }
22.509 + if( sqlite3FixExpr(pFix, pStep->pWhere) ){
22.510 + return 1;
22.511 + }
22.512 + if( sqlite3FixExprList(pFix, pStep->pExprList) ){
22.513 + return 1;
22.514 + }
22.515 + pStep = pStep->pNext;
22.516 + }
22.517 + return 0;
22.518 +}
22.519 +#endif
23.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
23.2 +++ b/extensions/sqlite/sqlite-source/auth.c Sun Jul 29 01:15:31 2007 +0000
23.3 @@ -0,0 +1,233 @@
23.4 +/*
23.5 +** 2003 January 11
23.6 +**
23.7 +** The author disclaims copyright to this source code. In place of
23.8 +** a legal notice, here is a blessing:
23.9 +**
23.10 +** May you do good and not evil.
23.11 +** May you find forgiveness for yourself and forgive others.
23.12 +** May you share freely, never taking more than you give.
23.13 +**
23.14 +*************************************************************************
23.15 +** This file contains code used to implement the sqlite3_set_authorizer()
23.16 +** API. This facility is an optional feature of the library. Embedded
23.17 +** systems that do not need this facility may omit it by recompiling
23.18 +** the library with -DSQLITE_OMIT_AUTHORIZATION=1
23.19 +**
23.20 +** $Id$
23.21 +*/
23.22 +#include "sqliteInt.h"
23.23 +
23.24 +/*
23.25 +** All of the code in this file may be omitted by defining a single
23.26 +** macro.
23.27 +*/
23.28 +#ifndef SQLITE_OMIT_AUTHORIZATION
23.29 +
23.30 +/*
23.31 +** Set or clear the access authorization function.
23.32 +**
23.33 +** The access authorization function is be called during the compilation
23.34 +** phase to verify that the user has read and/or write access permission on
23.35 +** various fields of the database. The first argument to the auth function
23.36 +** is a copy of the 3rd argument to this routine. The second argument
23.37 +** to the auth function is one of these constants:
23.38 +**
23.39 +** SQLITE_CREATE_INDEX
23.40 +** SQLITE_CREATE_TABLE
23.41 +** SQLITE_CREATE_TEMP_INDEX
23.42 +** SQLITE_CREATE_TEMP_TABLE
23.43 +** SQLITE_CREATE_TEMP_TRIGGER
23.44 +** SQLITE_CREATE_TEMP_VIEW
23.45 +** SQLITE_CREATE_TRIGGER
23.46 +** SQLITE_CREATE_VIEW
23.47 +** SQLITE_DELETE
23.48 +** SQLITE_DROP_INDEX
23.49 +** SQLITE_DROP_TABLE
23.50 +** SQLITE_DROP_TEMP_INDEX
23.51 +** SQLITE_DROP_TEMP_TABLE
23.52 +** SQLITE_DROP_TEMP_TRIGGER
23.53 +** SQLITE_DROP_TEMP_VIEW
23.54 +** SQLITE_DROP_TRIGGER
23.55 +** SQLITE_DROP_VIEW
23.56 +** SQLITE_INSERT
23.57 +** SQLITE_PRAGMA
23.58 +** SQLITE_READ
23.59 +** SQLITE_SELECT
23.60 +** SQLITE_TRANSACTION
23.61 +** SQLITE_UPDATE
23.62 +**
23.63 +** The third and fourth arguments to the auth function are the name of
23.64 +** the table and the column that are being accessed. The auth function
23.65 +** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
23.66 +** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
23.67 +** means that the SQL statement will never-run - the sqlite3_exec() call
23.68 +** will return with an error. SQLITE_IGNORE means that the SQL statement
23.69 +** should run but attempts to read the specified column will return NULL
23.70 +** and attempts to write the column will be ignored.
23.71 +**
23.72 +** Setting the auth function to NULL disables this hook. The default
23.73 +** setting of the auth function is NULL.
23.74 +*/
23.75 +int sqlite3_set_authorizer(
23.76 + sqlite3 *db,
23.77 + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
23.78 + void *pArg
23.79 +){
23.80 + db->xAuth = xAuth;
23.81 + db->pAuthArg = pArg;
23.82 + sqlite3ExpirePreparedStatements(db);
23.83 + return SQLITE_OK;
23.84 +}
23.85 +
23.86 +/*
23.87 +** Write an error message into pParse->zErrMsg that explains that the
23.88 +** user-supplied authorization function returned an illegal value.
23.89 +*/
23.90 +static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
23.91 + sqlite3ErrorMsg(pParse, "illegal return value (%d) from the "
23.92 + "authorization function - should be SQLITE_OK, SQLITE_IGNORE, "
23.93 + "or SQLITE_DENY", rc);
23.94 + pParse->rc = SQLITE_ERROR;
23.95 +}
23.96 +
23.97 +/*
23.98 +** The pExpr should be a TK_COLUMN expression. The table referred to
23.99 +** is in pTabList or else it is the NEW or OLD table of a trigger.
23.100 +** Check to see if it is OK to read this particular column.
23.101 +**
23.102 +** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
23.103 +** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
23.104 +** then generate an error.
23.105 +*/
23.106 +void sqlite3AuthRead(
23.107 + Parse *pParse, /* The parser context */
23.108 + Expr *pExpr, /* The expression to check authorization on */
23.109 + SrcList *pTabList /* All table that pExpr might refer to */
23.110 +){
23.111 + sqlite3 *db = pParse->db;
23.112 + int rc;
23.113 + Table *pTab; /* The table being read */
23.114 + const char *zCol; /* Name of the column of the table */
23.115 + int iSrc; /* Index in pTabList->a[] of table being read */
23.116 + const char *zDBase; /* Name of database being accessed */
23.117 + TriggerStack *pStack; /* The stack of current triggers */
23.118 + int iDb; /* The index of the database the expression refers to */
23.119 +
23.120 + if( db->xAuth==0 ) return;
23.121 + if( pExpr->op!=TK_COLUMN ) return;
23.122 + iDb = sqlite3SchemaToIndex(pParse->db, pExpr->pSchema);
23.123 + if( iDb<0 ){
23.124 + /* An attempt to read a column out of a subquery or other
23.125 + ** temporary table. */
23.126 + return;
23.127 + }
23.128 + for(iSrc=0; pTabList && iSrc<pTabList->nSrc; iSrc++){
23.129 + if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
23.130 + }
23.131 + if( iSrc>=0 && pTabList && iSrc<pTabList->nSrc ){
23.132 + pTab = pTabList->a[iSrc].pTab;
23.133 + }else if( (pStack = pParse->trigStack)!=0 ){
23.134 + /* This must be an attempt to read the NEW or OLD pseudo-tables
23.135 + ** of a trigger.
23.136 + */
23.137 + assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
23.138 + pTab = pStack->pTab;
23.139 + }else{
23.140 + return;
23.141 + }
23.142 + if( pTab==0 ) return;
23.143 + if( pExpr->iColumn>=0 ){
23.144 + assert( pExpr->iColumn<pTab->nCol );
23.145 + zCol = pTab->aCol[pExpr->iColumn].zName;
23.146 + }else if( pTab->iPKey>=0 ){
23.147 + assert( pTab->iPKey<pTab->nCol );
23.148 + zCol = pTab->aCol[pTab->iPKey].zName;
23.149 + }else{
23.150 + zCol = "ROWID";
23.151 + }
23.152 + assert( iDb>=0 && iDb<db->nDb );
23.153 + zDBase = db->aDb[iDb].zName;
23.154 + rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase,
23.155 + pParse->zAuthContext);
23.156 + if( rc==SQLITE_IGNORE ){
23.157 + pExpr->op = TK_NULL;
23.158 + }else if( rc==SQLITE_DENY ){
23.159 + if( db->nDb>2 || iDb!=0 ){
23.160 + sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",
23.161 + zDBase, pTab->zName, zCol);
23.162 + }else{
23.163 + sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol);
23.164 + }
23.165 + pParse->rc = SQLITE_AUTH;
23.166 + }else if( rc!=SQLITE_OK ){
23.167 + sqliteAuthBadReturnCode(pParse, rc);
23.168 + }
23.169 +}
23.170 +
23.171 +/*
23.172 +** Do an authorization check using the code and arguments given. Return
23.173 +** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
23.174 +** is returned, then the error count and error message in pParse are
23.175 +** modified appropriately.
23.176 +*/
23.177 +int sqlite3AuthCheck(
23.178 + Parse *pParse,
23.179 + int code,
23.180 + const char *zArg1,
23.181 + const char *zArg2,
23.182 + const char *zArg3
23.183 +){
23.184 + sqlite3 *db = pParse->db;
23.185 + int rc;
23.186 +
23.187 + /* Don't do any authorization checks if the database is initialising
23.188 + ** or if the parser is being invoked from within sqlite3_declare_vtab.
23.189 + */
23.190 + if( db->init.busy || IN_DECLARE_VTAB ){
23.191 + return SQLITE_OK;
23.192 + }
23.193 +
23.194 + if( db->xAuth==0 ){
23.195 + return SQLITE_OK;
23.196 + }
23.197 + rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
23.198 + if( rc==SQLITE_DENY ){
23.199 + sqlite3ErrorMsg(pParse, "not authorized");
23.200 + pParse->rc = SQLITE_AUTH;
23.201 + }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
23.202 + rc = SQLITE_DENY;
23.203 + sqliteAuthBadReturnCode(pParse, rc);
23.204 + }
23.205 + return rc;
23.206 +}
23.207 +
23.208 +/*
23.209 +** Push an authorization context. After this routine is called, the
23.210 +** zArg3 argument to authorization callbacks will be zContext until
23.211 +** popped. Or if pParse==0, this routine is a no-op.
23.212 +*/
23.213 +void sqlite3AuthContextPush(
23.214 + Parse *pParse,
23.215 + AuthContext *pContext,
23.216 + const char *zContext
23.217 +){
23.218 + pContext->pParse = pParse;
23.219 + if( pParse ){
23.220 + pContext->zAuthContext = pParse->zAuthContext;
23.221 + pParse->zAuthContext = zContext;
23.222 + }
23.223 +}
23.224 +
23.225 +/*
23.226 +** Pop an authorization context that was previously pushed
23.227 +** by sqlite3AuthContextPush
23.228 +*/
23.229 +void sqlite3AuthContextPop(AuthContext *pContext){
23.230 + if( pContext->pParse ){
23.231 + pContext->pParse->zAuthContext = pContext->zAuthContext;
23.232 + pContext->pParse = 0;
23.233 + }
23.234 +}
23.235 +
23.236 +#endif /* SQLITE_OMIT_AUTHORIZATION */
24.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
24.2 +++ b/extensions/sqlite/sqlite-source/btree.c Sun Jul 29 01:15:31 2007 +0000
24.3 @@ -0,0 +1,6370 @@
24.4 +/*
24.5 +** 2004 April 6
24.6 +**
24.7 +** The author disclaims copyright to this source code. In place of
24.8 +** a legal notice, here is a blessing:
24.9 +**
24.10 +** May you do good and not evil.
24.11 +** May you find forgiveness for yourself and forgive others.
24.12 +** May you share freely, never taking more than you give.
24.13 +**
24.14 +*************************************************************************
24.15 +** $Id$
24.16 +**
24.17 +** This file implements a external (disk-based) database using BTrees.
24.18 +** See the header comment on "btreeInt.h" for additional information.
24.19 +** Including a description of file format and an overview of operation.
24.20 +*/
24.21 +#include "btreeInt.h"
24.22 +
24.23 +/*
24.24 +** The header string that appears at the beginning of every
24.25 +** SQLite database.
24.26 +*/
24.27 +static const char zMagicHeader[] = SQLITE_FILE_HEADER;
24.28 +
24.29 +
24.30 +/*
24.31 +** Set this global variable to 1 to enable tracing using the TRACE
24.32 +** macro.
24.33 +*/
24.34 +#if SQLITE_TEST
24.35 +int sqlite3_btree_trace=0; /* True to enable tracing */
24.36 +#endif
24.37 +
24.38 +/*
24.39 +** Forward declaration
24.40 +*/
24.41 +static int checkReadLocks(Btree*,Pgno,BtCursor*);
24.42 +
24.43 +
24.44 +#ifdef SQLITE_OMIT_SHARED_CACHE
24.45 + /*
24.46 + ** The functions queryTableLock(), lockTable() and unlockAllTables()
24.47 + ** manipulate entries in the BtShared.pLock linked list used to store
24.48 + ** shared-cache table level locks. If the library is compiled with the
24.49 + ** shared-cache feature disabled, then there is only ever one user
24.50 + ** of each BtShared structure and so this locking is not necessary.
24.51 + ** So define the lock related functions as no-ops.
24.52 + */
24.53 + #define queryTableLock(a,b,c) SQLITE_OK
24.54 + #define lockTable(a,b,c) SQLITE_OK
24.55 + #define unlockAllTables(a)
24.56 +#else
24.57 +
24.58 +/*
24.59 +** Query to see if btree handle p may obtain a lock of type eLock
24.60 +** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
24.61 +** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
24.62 +** SQLITE_LOCKED if not.
24.63 +*/
24.64 +static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
24.65 + BtShared *pBt = p->pBt;
24.66 + BtLock *pIter;
24.67 +
24.68 + /* This is a no-op if the shared-cache is not enabled */
24.69 + if( 0==sqlite3ThreadDataReadOnly()->useSharedData ){
24.70 + return SQLITE_OK;
24.71 + }
24.72 +
24.73 + /* This (along with lockTable()) is where the ReadUncommitted flag is
24.74 + ** dealt with. If the caller is querying for a read-lock and the flag is
24.75 + ** set, it is unconditionally granted - even if there are write-locks
24.76 + ** on the table. If a write-lock is requested, the ReadUncommitted flag
24.77 + ** is not considered.
24.78 + **
24.79 + ** In function lockTable(), if a read-lock is demanded and the
24.80 + ** ReadUncommitted flag is set, no entry is added to the locks list
24.81 + ** (BtShared.pLock).
24.82 + **
24.83 + ** To summarize: If the ReadUncommitted flag is set, then read cursors do
24.84 + ** not create or respect table locks. The locking procedure for a
24.85 + ** write-cursor does not change.
24.86 + */
24.87 + if(
24.88 + !p->pSqlite ||
24.89 + 0==(p->pSqlite->flags&SQLITE_ReadUncommitted) ||
24.90 + eLock==WRITE_LOCK ||
24.91 + iTab==MASTER_ROOT
24.92 + ){
24.93 + for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
24.94 + if( pIter->pBtree!=p && pIter->iTable==iTab &&
24.95 + (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
24.96 + return SQLITE_LOCKED;
24.97 + }
24.98 + }
24.99 + }
24.100 + return SQLITE_OK;
24.101 +}
24.102 +
24.103 +/*
24.104 +** Add a lock on the table with root-page iTable to the shared-btree used
24.105 +** by Btree handle p. Parameter eLock must be either READ_LOCK or
24.106 +** WRITE_LOCK.
24.107 +**
24.108 +** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
24.109 +** SQLITE_NOMEM may also be returned.
24.110 +*/
24.111 +static int lockTable(Btree *p, Pgno iTable, u8 eLock){
24.112 + BtShared *pBt = p->pBt;
24.113 + BtLock *pLock = 0;
24.114 + BtLock *pIter;
24.115 +
24.116 + /* This is a no-op if the shared-cache is not enabled */
24.117 + if( 0==sqlite3ThreadDataReadOnly()->useSharedData ){
24.118 + return SQLITE_OK;
24.119 + }
24.120 +
24.121 + assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
24.122 +
24.123 + /* If the read-uncommitted flag is set and a read-lock is requested,
24.124 + ** return early without adding an entry to the BtShared.pLock list. See
24.125 + ** comment in function queryTableLock() for more info on handling
24.126 + ** the ReadUncommitted flag.
24.127 + */
24.128 + if(
24.129 + (p->pSqlite) &&
24.130 + (p->pSqlite->flags&SQLITE_ReadUncommitted) &&
24.131 + (eLock==READ_LOCK) &&
24.132 + iTable!=MASTER_ROOT
24.133 + ){
24.134 + return SQLITE_OK;
24.135 + }
24.136 +
24.137 + /* First search the list for an existing lock on this table. */
24.138 + for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
24.139 + if( pIter->iTable==iTable && pIter->pBtree==p ){
24.140 + pLock = pIter;
24.141 + break;
24.142 + }
24.143 + }
24.144 +
24.145 + /* If the above search did not find a BtLock struct associating Btree p
24.146 + ** with table iTable, allocate one and link it into the list.
24.147 + */
24.148 + if( !pLock ){
24.149 + pLock = (BtLock *)sqliteMalloc(sizeof(BtLock));
24.150 + if( !pLock ){
24.151 + return SQLITE_NOMEM;
24.152 + }
24.153 + pLock->iTable = iTable;
24.154 + pLock->pBtree = p;
24.155 + pLock->pNext = pBt->pLock;
24.156 + pBt->pLock = pLock;
24.157 + }
24.158 +
24.159 + /* Set the BtLock.eLock variable to the maximum of the current lock
24.160 + ** and the requested lock. This means if a write-lock was already held
24.161 + ** and a read-lock requested, we don't incorrectly downgrade the lock.
24.162 + */
24.163 + assert( WRITE_LOCK>READ_LOCK );
24.164 + if( eLock>pLock->eLock ){
24.165 + pLock->eLock = eLock;
24.166 + }
24.167 +
24.168 + return SQLITE_OK;
24.169 +}
24.170 +
24.171 +/*
24.172 +** Release all the table locks (locks obtained via calls to the lockTable()
24.173 +** procedure) held by Btree handle p.
24.174 +*/
24.175 +static void unlockAllTables(Btree *p){
24.176 + BtLock **ppIter = &p->pBt->pLock;
24.177 +
24.178 + /* If the shared-cache extension is not enabled, there should be no
24.179 + ** locks in the BtShared.pLock list, making this procedure a no-op. Assert
24.180 + ** that this is the case.
24.181 + */
24.182 + assert( sqlite3ThreadDataReadOnly()->useSharedData || 0==*ppIter );
24.183 +
24.184 + while( *ppIter ){
24.185 + BtLock *pLock = *ppIter;
24.186 + if( pLock->pBtree==p ){
24.187 + *ppIter = pLock->pNext;
24.188 + sqliteFree(pLock);
24.189 + }else{
24.190 + ppIter = &pLock->pNext;
24.191 + }
24.192 + }
24.193 +}
24.194 +#endif /* SQLITE_OMIT_SHARED_CACHE */
24.195 +
24.196 +static void releasePage(MemPage *pPage); /* Forward reference */
24.197 +
24.198 +#ifndef SQLITE_OMIT_INCRBLOB
24.199 +/*
24.200 +** Invalidate the overflow page-list cache for cursor pCur, if any.
24.201 +*/
24.202 +static void invalidateOverflowCache(BtCursor *pCur){
24.203 + sqliteFree(pCur->aOverflow);
24.204 + pCur->aOverflow = 0;
24.205 +}
24.206 +
24.207 +/*
24.208 +** Invalidate the overflow page-list cache for all cursors opened
24.209 +** on the shared btree structure pBt.
24.210 +*/
24.211 +static void invalidateAllOverflowCache(BtShared *pBt){
24.212 + BtCursor *p;
24.213 + for(p=pBt->pCursor; p; p=p->pNext){
24.214 + invalidateOverflowCache(p);
24.215 + }
24.216 +}
24.217 +#else
24.218 + #define invalidateOverflowCache(x)
24.219 + #define invalidateAllOverflowCache(x)
24.220 +#endif
24.221 +
24.222 +/*
24.223 +** Save the current cursor position in the variables BtCursor.nKey
24.224 +** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
24.225 +*/
24.226 +static int saveCursorPosition(BtCursor *pCur){
24.227 + int rc;
24.228 +
24.229 + assert( CURSOR_VALID==pCur->eState );
24.230 + assert( 0==pCur->pKey );
24.231 +
24.232 + rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
24.233 +
24.234 + /* If this is an intKey table, then the above call to BtreeKeySize()
24.235 + ** stores the integer key in pCur->nKey. In this case this value is
24.236 + ** all that is required. Otherwise, if pCur is not open on an intKey
24.237 + ** table, then malloc space for and store the pCur->nKey bytes of key
24.238 + ** data.
24.239 + */
24.240 + if( rc==SQLITE_OK && 0==pCur->pPage->intKey){
24.241 + void *pKey = sqliteMalloc((int)pCur->nKey);
24.242 + if( pKey ){
24.243 + rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
24.244 + if( rc==SQLITE_OK ){
24.245 + pCur->pKey = pKey;
24.246 + }else{
24.247 + sqliteFree(pKey);
24.248 + }
24.249 + }else{
24.250 + rc = SQLITE_NOMEM;
24.251 + }
24.252 + }
24.253 + assert( !pCur->pPage->intKey || !pCur->pKey );
24.254 +
24.255 + if( rc==SQLITE_OK ){
24.256 + releasePage(pCur->pPage);
24.257 + pCur->pPage = 0;
24.258 + pCur->eState = CURSOR_REQUIRESEEK;
24.259 + }
24.260 +
24.261 + invalidateOverflowCache(pCur);
24.262 + return rc;
24.263 +}
24.264 +
24.265 +/*
24.266 +** Save the positions of all cursors except pExcept open on the table
24.267 +** with root-page iRoot. Usually, this is called just before cursor
24.268 +** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
24.269 +*/
24.270 +static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
24.271 + BtCursor *p;
24.272 + for(p=pBt->pCursor; p; p=p->pNext){
24.273 + if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
24.274 + p->eState==CURSOR_VALID ){
24.275 + int rc = saveCursorPosition(p);
24.276 + if( SQLITE_OK!=rc ){
24.277 + return rc;
24.278 + }
24.279 + }
24.280 + }
24.281 + return SQLITE_OK;
24.282 +}
24.283 +
24.284 +/*
24.285 +** Clear the current cursor position.
24.286 +*/
24.287 +static void clearCursorPosition(BtCursor *pCur){
24.288 + sqliteFree(pCur->pKey);
24.289 + pCur->pKey = 0;
24.290 + pCur->eState = CURSOR_INVALID;
24.291 +}
24.292 +
24.293 +/*
24.294 +** Restore the cursor to the position it was in (or as close to as possible)
24.295 +** when saveCursorPosition() was called. Note that this call deletes the
24.296 +** saved position info stored by saveCursorPosition(), so there can be
24.297 +** at most one effective restoreOrClearCursorPosition() call after each
24.298 +** saveCursorPosition().
24.299 +**
24.300 +** If the second argument argument - doSeek - is false, then instead of
24.301 +** returning the cursor to it's saved position, any saved position is deleted
24.302 +** and the cursor state set to CURSOR_INVALID.
24.303 +*/
24.304 +int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur){
24.305 + int rc;
24.306 + assert( pCur->eState==CURSOR_REQUIRESEEK );
24.307 +#ifndef SQLITE_OMIT_INCRBLOB
24.308 + if( pCur->isIncrblobHandle ){
24.309 + return SQLITE_ABORT;
24.310 + }
24.311 +#endif
24.312 + pCur->eState = CURSOR_INVALID;
24.313 + rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
24.314 + if( rc==SQLITE_OK ){
24.315 + sqliteFree(pCur->pKey);
24.316 + pCur->pKey = 0;
24.317 + assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
24.318 + }
24.319 + return rc;
24.320 +}
24.321 +
24.322 +#define restoreOrClearCursorPosition(p) \
24.323 + (p->eState==CURSOR_REQUIRESEEK ? \
24.324 + sqlite3BtreeRestoreOrClearCursorPosition(p) : \
24.325 + SQLITE_OK)
24.326 +
24.327 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.328 +/*
24.329 +** Given a page number of a regular database page, return the page
24.330 +** number for the pointer-map page that contains the entry for the
24.331 +** input page number.
24.332 +*/
24.333 +static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
24.334 + int nPagesPerMapPage = (pBt->usableSize/5)+1;
24.335 + int iPtrMap = (pgno-2)/nPagesPerMapPage;
24.336 + int ret = (iPtrMap*nPagesPerMapPage) + 2;
24.337 + if( ret==PENDING_BYTE_PAGE(pBt) ){
24.338 + ret++;
24.339 + }
24.340 + return ret;
24.341 +}
24.342 +
24.343 +/*
24.344 +** Write an entry into the pointer map.
24.345 +**
24.346 +** This routine updates the pointer map entry for page number 'key'
24.347 +** so that it maps to type 'eType' and parent page number 'pgno'.
24.348 +** An error code is returned if something goes wrong, otherwise SQLITE_OK.
24.349 +*/
24.350 +static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
24.351 + DbPage *pDbPage; /* The pointer map page */
24.352 + u8 *pPtrmap; /* The pointer map data */
24.353 + Pgno iPtrmap; /* The pointer map page number */
24.354 + int offset; /* Offset in pointer map page */
24.355 + int rc;
24.356 +
24.357 + /* The master-journal page number must never be used as a pointer map page */
24.358 + assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
24.359 +
24.360 + assert( pBt->autoVacuum );
24.361 + if( key==0 ){
24.362 + return SQLITE_CORRUPT_BKPT;
24.363 + }
24.364 + iPtrmap = PTRMAP_PAGENO(pBt, key);
24.365 + rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
24.366 + if( rc!=SQLITE_OK ){
24.367 + return rc;
24.368 + }
24.369 + offset = PTRMAP_PTROFFSET(pBt, key);
24.370 + pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
24.371 +
24.372 + if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
24.373 + TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
24.374 + rc = sqlite3PagerWrite(pDbPage);
24.375 + if( rc==SQLITE_OK ){
24.376 + pPtrmap[offset] = eType;
24.377 + put4byte(&pPtrmap[offset+1], parent);
24.378 + }
24.379 + }
24.380 +
24.381 + sqlite3PagerUnref(pDbPage);
24.382 + return rc;
24.383 +}
24.384 +
24.385 +/*
24.386 +** Read an entry from the pointer map.
24.387 +**
24.388 +** This routine retrieves the pointer map entry for page 'key', writing
24.389 +** the type and parent page number to *pEType and *pPgno respectively.
24.390 +** An error code is returned if something goes wrong, otherwise SQLITE_OK.
24.391 +*/
24.392 +static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
24.393 + DbPage *pDbPage; /* The pointer map page */
24.394 + int iPtrmap; /* Pointer map page index */
24.395 + u8 *pPtrmap; /* Pointer map page data */
24.396 + int offset; /* Offset of entry in pointer map */
24.397 + int rc;
24.398 +
24.399 + iPtrmap = PTRMAP_PAGENO(pBt, key);
24.400 + rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
24.401 + if( rc!=0 ){
24.402 + return rc;
24.403 + }
24.404 + pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
24.405 +
24.406 + offset = PTRMAP_PTROFFSET(pBt, key);
24.407 + assert( pEType!=0 );
24.408 + *pEType = pPtrmap[offset];
24.409 + if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
24.410 +
24.411 + sqlite3PagerUnref(pDbPage);
24.412 + if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
24.413 + return SQLITE_OK;
24.414 +}
24.415 +
24.416 +#endif /* SQLITE_OMIT_AUTOVACUUM */
24.417 +
24.418 +/*
24.419 +** Given a btree page and a cell index (0 means the first cell on
24.420 +** the page, 1 means the second cell, and so forth) return a pointer
24.421 +** to the cell content.
24.422 +**
24.423 +** This routine works only for pages that do not contain overflow cells.
24.424 +*/
24.425 +#define findCell(pPage, iCell) \
24.426 + ((pPage)->aData + get2byte(&(pPage)->aData[(pPage)->cellOffset+2*(iCell)]))
24.427 +u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell){
24.428 + assert( iCell>=0 );
24.429 + assert( iCell<get2byte(&pPage->aData[pPage->hdrOffset+3]) );
24.430 + return findCell(pPage, iCell);
24.431 +}
24.432 +
24.433 +/*
24.434 +** This a more complex version of sqlite3BtreeFindCell() that works for
24.435 +** pages that do contain overflow cells. See insert
24.436 +*/
24.437 +static u8 *findOverflowCell(MemPage *pPage, int iCell){
24.438 + int i;
24.439 + for(i=pPage->nOverflow-1; i>=0; i--){
24.440 + int k;
24.441 + struct _OvflCell *pOvfl;
24.442 + pOvfl = &pPage->aOvfl[i];
24.443 + k = pOvfl->idx;
24.444 + if( k<=iCell ){
24.445 + if( k==iCell ){
24.446 + return pOvfl->pCell;
24.447 + }
24.448 + iCell--;
24.449 + }
24.450 + }
24.451 + return findCell(pPage, iCell);
24.452 +}
24.453 +
24.454 +/*
24.455 +** Parse a cell content block and fill in the CellInfo structure. There
24.456 +** are two versions of this function. sqlite3BtreeParseCell() takes a
24.457 +** cell index as the second argument and sqlite3BtreeParseCellPtr()
24.458 +** takes a pointer to the body of the cell as its second argument.
24.459 +**
24.460 +** Within this file, the parseCell() macro can be called instead of
24.461 +** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
24.462 +*/
24.463 +void sqlite3BtreeParseCellPtr(
24.464 + MemPage *pPage, /* Page containing the cell */
24.465 + u8 *pCell, /* Pointer to the cell text. */
24.466 + CellInfo *pInfo /* Fill in this structure */
24.467 +){
24.468 + int n; /* Number bytes in cell content header */
24.469 + u32 nPayload; /* Number of bytes of cell payload */
24.470 +
24.471 + pInfo->pCell = pCell;
24.472 + assert( pPage->leaf==0 || pPage->leaf==1 );
24.473 + n = pPage->childPtrSize;
24.474 + assert( n==4-4*pPage->leaf );
24.475 + if( pPage->hasData ){
24.476 + n += getVarint32(&pCell[n], &nPayload);
24.477 + }else{
24.478 + nPayload = 0;
24.479 + }
24.480 + pInfo->nData = nPayload;
24.481 + if( pPage->intKey ){
24.482 + n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
24.483 + }else{
24.484 + u32 x;
24.485 + n += getVarint32(&pCell[n], &x);
24.486 + pInfo->nKey = x;
24.487 + nPayload += x;
24.488 + }
24.489 + pInfo->nPayload = nPayload;
24.490 + pInfo->nHeader = n;
24.491 + if( nPayload<=pPage->maxLocal ){
24.492 + /* This is the (easy) common case where the entire payload fits
24.493 + ** on the local page. No overflow is required.
24.494 + */
24.495 + int nSize; /* Total size of cell content in bytes */
24.496 + pInfo->nLocal = nPayload;
24.497 + pInfo->iOverflow = 0;
24.498 + nSize = nPayload + n;
24.499 + if( nSize<4 ){
24.500 + nSize = 4; /* Minimum cell size is 4 */
24.501 + }
24.502 + pInfo->nSize = nSize;
24.503 + }else{
24.504 + /* If the payload will not fit completely on the local page, we have
24.505 + ** to decide how much to store locally and how much to spill onto
24.506 + ** overflow pages. The strategy is to minimize the amount of unused
24.507 + ** space on overflow pages while keeping the amount of local storage
24.508 + ** in between minLocal and maxLocal.
24.509 + **
24.510 + ** Warning: changing the way overflow payload is distributed in any
24.511 + ** way will result in an incompatible file format.
24.512 + */
24.513 + int minLocal; /* Minimum amount of payload held locally */
24.514 + int maxLocal; /* Maximum amount of payload held locally */
24.515 + int surplus; /* Overflow payload available for local storage */
24.516 +
24.517 + minLocal = pPage->minLocal;
24.518 + maxLocal = pPage->maxLocal;
24.519 + surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
24.520 + if( surplus <= maxLocal ){
24.521 + pInfo->nLocal = surplus;
24.522 + }else{
24.523 + pInfo->nLocal = minLocal;
24.524 + }
24.525 + pInfo->iOverflow = pInfo->nLocal + n;
24.526 + pInfo->nSize = pInfo->iOverflow + 4;
24.527 + }
24.528 +}
24.529 +#define parseCell(pPage, iCell, pInfo) \
24.530 + sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
24.531 +void sqlite3BtreeParseCell(
24.532 + MemPage *pPage, /* Page containing the cell */
24.533 + int iCell, /* The cell index. First cell is 0 */
24.534 + CellInfo *pInfo /* Fill in this structure */
24.535 +){
24.536 + parseCell(pPage, iCell, pInfo);
24.537 +}
24.538 +
24.539 +/*
24.540 +** Compute the total number of bytes that a Cell needs in the cell
24.541 +** data area of the btree-page. The return number includes the cell
24.542 +** data header and the local payload, but not any overflow page or
24.543 +** the space used by the cell pointer.
24.544 +*/
24.545 +#ifndef NDEBUG
24.546 +static int cellSize(MemPage *pPage, int iCell){
24.547 + CellInfo info;
24.548 + sqlite3BtreeParseCell(pPage, iCell, &info);
24.549 + return info.nSize;
24.550 +}
24.551 +#endif
24.552 +static int cellSizePtr(MemPage *pPage, u8 *pCell){
24.553 + CellInfo info;
24.554 + sqlite3BtreeParseCellPtr(pPage, pCell, &info);
24.555 + return info.nSize;
24.556 +}
24.557 +
24.558 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.559 +/*
24.560 +** If the cell pCell, part of page pPage contains a pointer
24.561 +** to an overflow page, insert an entry into the pointer-map
24.562 +** for the overflow page.
24.563 +*/
24.564 +static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
24.565 + if( pCell ){
24.566 + CellInfo info;
24.567 + sqlite3BtreeParseCellPtr(pPage, pCell, &info);
24.568 + assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
24.569 + if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
24.570 + Pgno ovfl = get4byte(&pCell[info.iOverflow]);
24.571 + return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
24.572 + }
24.573 + }
24.574 + return SQLITE_OK;
24.575 +}
24.576 +/*
24.577 +** If the cell with index iCell on page pPage contains a pointer
24.578 +** to an overflow page, insert an entry into the pointer-map
24.579 +** for the overflow page.
24.580 +*/
24.581 +static int ptrmapPutOvfl(MemPage *pPage, int iCell){
24.582 + u8 *pCell;
24.583 + pCell = findOverflowCell(pPage, iCell);
24.584 + return ptrmapPutOvflPtr(pPage, pCell);
24.585 +}
24.586 +#endif
24.587 +
24.588 +
24.589 +/*
24.590 +** Defragment the page given. All Cells are moved to the
24.591 +** end of the page and all free space is collected into one
24.592 +** big FreeBlk that occurs in between the header and cell
24.593 +** pointer array and the cell content area.
24.594 +*/
24.595 +static int defragmentPage(MemPage *pPage){
24.596 + int i; /* Loop counter */
24.597 + int pc; /* Address of a i-th cell */
24.598 + int addr; /* Offset of first byte after cell pointer array */
24.599 + int hdr; /* Offset to the page header */
24.600 + int size; /* Size of a cell */
24.601 + int usableSize; /* Number of usable bytes on a page */
24.602 + int cellOffset; /* Offset to the cell pointer array */
24.603 + int brk; /* Offset to the cell content area */
24.604 + int nCell; /* Number of cells on the page */
24.605 + unsigned char *data; /* The page data */
24.606 + unsigned char *temp; /* Temp area for cell content */
24.607 +
24.608 + assert( sqlite3PagerIswriteable(pPage->pDbPage) );
24.609 + assert( pPage->pBt!=0 );
24.610 + assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
24.611 + assert( pPage->nOverflow==0 );
24.612 + temp = sqliteMalloc( pPage->pBt->pageSize );
24.613 + if( temp==0 ) return SQLITE_NOMEM;
24.614 + data = pPage->aData;
24.615 + hdr = pPage->hdrOffset;
24.616 + cellOffset = pPage->cellOffset;
24.617 + nCell = pPage->nCell;
24.618 + assert( nCell==get2byte(&data[hdr+3]) );
24.619 + usableSize = pPage->pBt->usableSize;
24.620 + brk = get2byte(&data[hdr+5]);
24.621 + memcpy(&temp[brk], &data[brk], usableSize - brk);
24.622 + brk = usableSize;
24.623 + for(i=0; i<nCell; i++){
24.624 + u8 *pAddr; /* The i-th cell pointer */
24.625 + pAddr = &data[cellOffset + i*2];
24.626 + pc = get2byte(pAddr);
24.627 + assert( pc<pPage->pBt->usableSize );
24.628 + size = cellSizePtr(pPage, &temp[pc]);
24.629 + brk -= size;
24.630 + memcpy(&data[brk], &temp[pc], size);
24.631 + put2byte(pAddr, brk);
24.632 + }
24.633 + assert( brk>=cellOffset+2*nCell );
24.634 + put2byte(&data[hdr+5], brk);
24.635 + data[hdr+1] = 0;
24.636 + data[hdr+2] = 0;
24.637 + data[hdr+7] = 0;
24.638 + addr = cellOffset+2*nCell;
24.639 + memset(&data[addr], 0, brk-addr);
24.640 + sqliteFree(temp);
24.641 + return SQLITE_OK;
24.642 +}
24.643 +
24.644 +/*
24.645 +** Allocate nByte bytes of space on a page.
24.646 +**
24.647 +** Return the index into pPage->aData[] of the first byte of
24.648 +** the new allocation. Or return 0 if there is not enough free
24.649 +** space on the page to satisfy the allocation request.
24.650 +**
24.651 +** If the page contains nBytes of free space but does not contain
24.652 +** nBytes of contiguous free space, then this routine automatically
24.653 +** calls defragementPage() to consolidate all free space before
24.654 +** allocating the new chunk.
24.655 +*/
24.656 +static int allocateSpace(MemPage *pPage, int nByte){
24.657 + int addr, pc, hdr;
24.658 + int size;
24.659 + int nFrag;
24.660 + int top;
24.661 + int nCell;
24.662 + int cellOffset;
24.663 + unsigned char *data;
24.664 +
24.665 + data = pPage->aData;
24.666 + assert( sqlite3PagerIswriteable(pPage->pDbPage) );
24.667 + assert( pPage->pBt );
24.668 + if( nByte<4 ) nByte = 4;
24.669 + if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
24.670 + pPage->nFree -= nByte;
24.671 + hdr = pPage->hdrOffset;
24.672 +
24.673 + nFrag = data[hdr+7];
24.674 + if( nFrag<60 ){
24.675 + /* Search the freelist looking for a slot big enough to satisfy the
24.676 + ** space request. */
24.677 + addr = hdr+1;
24.678 + while( (pc = get2byte(&data[addr]))>0 ){
24.679 + size = get2byte(&data[pc+2]);
24.680 + if( size>=nByte ){
24.681 + if( size<nByte+4 ){
24.682 + memcpy(&data[addr], &data[pc], 2);
24.683 + data[hdr+7] = nFrag + size - nByte;
24.684 + return pc;
24.685 + }else{
24.686 + put2byte(&data[pc+2], size-nByte);
24.687 + return pc + size - nByte;
24.688 + }
24.689 + }
24.690 + addr = pc;
24.691 + }
24.692 + }
24.693 +
24.694 + /* Allocate memory from the gap in between the cell pointer array
24.695 + ** and the cell content area.
24.696 + */
24.697 + top = get2byte(&data[hdr+5]);
24.698 + nCell = get2byte(&data[hdr+3]);
24.699 + cellOffset = pPage->cellOffset;
24.700 + if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
24.701 + if( defragmentPage(pPage) ) return 0;
24.702 + top = get2byte(&data[hdr+5]);
24.703 + }
24.704 + top -= nByte;
24.705 + assert( cellOffset + 2*nCell <= top );
24.706 + put2byte(&data[hdr+5], top);
24.707 + return top;
24.708 +}
24.709 +
24.710 +/*
24.711 +** Return a section of the pPage->aData to the freelist.
24.712 +** The first byte of the new free block is pPage->aDisk[start]
24.713 +** and the size of the block is "size" bytes.
24.714 +**
24.715 +** Most of the effort here is involved in coalesing adjacent
24.716 +** free blocks into a single big free block.
24.717 +*/
24.718 +static void freeSpace(MemPage *pPage, int start, int size){
24.719 + int addr, pbegin, hdr;
24.720 + unsigned char *data = pPage->aData;
24.721 +
24.722 + assert( pPage->pBt!=0 );
24.723 + assert( sqlite3PagerIswriteable(pPage->pDbPage) );
24.724 + assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
24.725 + assert( (start + size)<=pPage->pBt->usableSize );
24.726 + if( size<4 ) size = 4;
24.727 +
24.728 +#ifdef SQLITE_SECURE_DELETE
24.729 + /* Overwrite deleted information with zeros when the SECURE_DELETE
24.730 + ** option is enabled at compile-time */
24.731 + memset(&data[start], 0, size);
24.732 +#endif
24.733 +
24.734 + /* Add the space back into the linked list of freeblocks */
24.735 + hdr = pPage->hdrOffset;
24.736 + addr = hdr + 1;
24.737 + while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
24.738 + assert( pbegin<=pPage->pBt->usableSize-4 );
24.739 + assert( pbegin>addr );
24.740 + addr = pbegin;
24.741 + }
24.742 + assert( pbegin<=pPage->pBt->usableSize-4 );
24.743 + assert( pbegin>addr || pbegin==0 );
24.744 + put2byte(&data[addr], start);
24.745 + put2byte(&data[start], pbegin);
24.746 + put2byte(&data[start+2], size);
24.747 + pPage->nFree += size;
24.748 +
24.749 + /* Coalesce adjacent free blocks */
24.750 + addr = pPage->hdrOffset + 1;
24.751 + while( (pbegin = get2byte(&data[addr]))>0 ){
24.752 + int pnext, psize;
24.753 + assert( pbegin>addr );
24.754 + assert( pbegin<=pPage->pBt->usableSize-4 );
24.755 + pnext = get2byte(&data[pbegin]);
24.756 + psize = get2byte(&data[pbegin+2]);
24.757 + if( pbegin + psize + 3 >= pnext && pnext>0 ){
24.758 + int frag = pnext - (pbegin+psize);
24.759 + assert( frag<=data[pPage->hdrOffset+7] );
24.760 + data[pPage->hdrOffset+7] -= frag;
24.761 + put2byte(&data[pbegin], get2byte(&data[pnext]));
24.762 + put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
24.763 + }else{
24.764 + addr = pbegin;
24.765 + }
24.766 + }
24.767 +
24.768 + /* If the cell content area begins with a freeblock, remove it. */
24.769 + if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
24.770 + int top;
24.771 + pbegin = get2byte(&data[hdr+1]);
24.772 + memcpy(&data[hdr+1], &data[pbegin], 2);
24.773 + top = get2byte(&data[hdr+5]);
24.774 + put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
24.775 + }
24.776 +}
24.777 +
24.778 +/*
24.779 +** Decode the flags byte (the first byte of the header) for a page
24.780 +** and initialize fields of the MemPage structure accordingly.
24.781 +*/
24.782 +static void decodeFlags(MemPage *pPage, int flagByte){
24.783 + BtShared *pBt; /* A copy of pPage->pBt */
24.784 +
24.785 + assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
24.786 + pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
24.787 + pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
24.788 + pPage->leaf = (flagByte & PTF_LEAF)!=0;
24.789 + pPage->childPtrSize = 4*(pPage->leaf==0);
24.790 + pBt = pPage->pBt;
24.791 + if( flagByte & PTF_LEAFDATA ){
24.792 + pPage->leafData = 1;
24.793 + pPage->maxLocal = pBt->maxLeaf;
24.794 + pPage->minLocal = pBt->minLeaf;
24.795 + }else{
24.796 + pPage->leafData = 0;
24.797 + pPage->maxLocal = pBt->maxLocal;
24.798 + pPage->minLocal = pBt->minLocal;
24.799 + }
24.800 + pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
24.801 +}
24.802 +
24.803 +/*
24.804 +** Initialize the auxiliary information for a disk block.
24.805 +**
24.806 +** The pParent parameter must be a pointer to the MemPage which
24.807 +** is the parent of the page being initialized. The root of a
24.808 +** BTree has no parent and so for that page, pParent==NULL.
24.809 +**
24.810 +** Return SQLITE_OK on success. If we see that the page does
24.811 +** not contain a well-formed database page, then return
24.812 +** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
24.813 +** guarantee that the page is well-formed. It only shows that
24.814 +** we failed to detect any corruption.
24.815 +*/
24.816 +int sqlite3BtreeInitPage(
24.817 + MemPage *pPage, /* The page to be initialized */
24.818 + MemPage *pParent /* The parent. Might be NULL */
24.819 +){
24.820 + int pc; /* Address of a freeblock within pPage->aData[] */
24.821 + int hdr; /* Offset to beginning of page header */
24.822 + u8 *data; /* Equal to pPage->aData */
24.823 + BtShared *pBt; /* The main btree structure */
24.824 + int usableSize; /* Amount of usable space on each page */
24.825 + int cellOffset; /* Offset from start of page to first cell pointer */
24.826 + int nFree; /* Number of unused bytes on the page */
24.827 + int top; /* First byte of the cell content area */
24.828 +
24.829 + pBt = pPage->pBt;
24.830 + assert( pBt!=0 );
24.831 + assert( pParent==0 || pParent->pBt==pBt );
24.832 + assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
24.833 + assert( pPage->aData == &((unsigned char*)pPage)[-pBt->pageSize] );
24.834 + if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
24.835 + /* The parent page should never change unless the file is corrupt */
24.836 + return SQLITE_CORRUPT_BKPT;
24.837 + }
24.838 + if( pPage->isInit ) return SQLITE_OK;
24.839 + if( pPage->pParent==0 && pParent!=0 ){
24.840 + pPage->pParent = pParent;
24.841 + sqlite3PagerRef(pParent->pDbPage);
24.842 + }
24.843 + hdr = pPage->hdrOffset;
24.844 + data = pPage->aData;
24.845 + decodeFlags(pPage, data[hdr]);
24.846 + pPage->nOverflow = 0;
24.847 + pPage->idxShift = 0;
24.848 + usableSize = pBt->usableSize;
24.849 + pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
24.850 + top = get2byte(&data[hdr+5]);
24.851 + pPage->nCell = get2byte(&data[hdr+3]);
24.852 + if( pPage->nCell>MX_CELL(pBt) ){
24.853 + /* To many cells for a single page. The page must be corrupt */
24.854 + return SQLITE_CORRUPT_BKPT;
24.855 + }
24.856 + if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
24.857 + /* All pages must have at least one cell, except for root pages */
24.858 + return SQLITE_CORRUPT_BKPT;
24.859 + }
24.860 +
24.861 + /* Compute the total free space on the page */
24.862 + pc = get2byte(&data[hdr+1]);
24.863 + nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
24.864 + while( pc>0 ){
24.865 + int next, size;
24.866 + if( pc>usableSize-4 ){
24.867 + /* Free block is off the page */
24.868 + return SQLITE_CORRUPT_BKPT;
24.869 + }
24.870 + next = get2byte(&data[pc]);
24.871 + size = get2byte(&data[pc+2]);
24.872 + if( next>0 && next<=pc+size+3 ){
24.873 + /* Free blocks must be in accending order */
24.874 + return SQLITE_CORRUPT_BKPT;
24.875 + }
24.876 + nFree += size;
24.877 + pc = next;
24.878 + }
24.879 + pPage->nFree = nFree;
24.880 + if( nFree>=usableSize ){
24.881 + /* Free space cannot exceed total page size */
24.882 + return SQLITE_CORRUPT_BKPT;
24.883 + }
24.884 +
24.885 + pPage->isInit = 1;
24.886 + return SQLITE_OK;
24.887 +}
24.888 +
24.889 +/*
24.890 +** Set up a raw page so that it looks like a database page holding
24.891 +** no entries.
24.892 +*/
24.893 +static void zeroPage(MemPage *pPage, int flags){
24.894 + unsigned char *data = pPage->aData;
24.895 + BtShared *pBt = pPage->pBt;
24.896 + int hdr = pPage->hdrOffset;
24.897 + int first;
24.898 +
24.899 + assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
24.900 + assert( &data[pBt->pageSize] == (unsigned char*)pPage );
24.901 + assert( sqlite3PagerIswriteable(pPage->pDbPage) );
24.902 + memset(&data[hdr], 0, pBt->usableSize - hdr);
24.903 + data[hdr] = flags;
24.904 + first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
24.905 + memset(&data[hdr+1], 0, 4);
24.906 + data[hdr+7] = 0;
24.907 + put2byte(&data[hdr+5], pBt->usableSize);
24.908 + pPage->nFree = pBt->usableSize - first;
24.909 + decodeFlags(pPage, flags);
24.910 + pPage->hdrOffset = hdr;
24.911 + pPage->cellOffset = first;
24.912 + pPage->nOverflow = 0;
24.913 + pPage->idxShift = 0;
24.914 + pPage->nCell = 0;
24.915 + pPage->isInit = 1;
24.916 +}
24.917 +
24.918 +/*
24.919 +** Get a page from the pager. Initialize the MemPage.pBt and
24.920 +** MemPage.aData elements if needed.
24.921 +**
24.922 +** If the noContent flag is set, it means that we do not care about
24.923 +** the content of the page at this time. So do not go to the disk
24.924 +** to fetch the content. Just fill in the content with zeros for now.
24.925 +** If in the future we call sqlite3PagerWrite() on this page, that
24.926 +** means we have started to be concerned about content and the disk
24.927 +** read should occur at that point.
24.928 +*/
24.929 +int sqlite3BtreeGetPage(
24.930 + BtShared *pBt, /* The btree */
24.931 + Pgno pgno, /* Number of the page to fetch */
24.932 + MemPage **ppPage, /* Return the page in this parameter */
24.933 + int noContent /* Do not load page content if true */
24.934 +){
24.935 + int rc;
24.936 + MemPage *pPage;
24.937 + DbPage *pDbPage;
24.938 +
24.939 + rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
24.940 + if( rc ) return rc;
24.941 + pPage = (MemPage *)sqlite3PagerGetExtra(pDbPage);
24.942 + pPage->aData = sqlite3PagerGetData(pDbPage);
24.943 + pPage->pDbPage = pDbPage;
24.944 + pPage->pBt = pBt;
24.945 + pPage->pgno = pgno;
24.946 + pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
24.947 + *ppPage = pPage;
24.948 + return SQLITE_OK;
24.949 +}
24.950 +
24.951 +/*
24.952 +** Get a page from the pager and initialize it. This routine
24.953 +** is just a convenience wrapper around separate calls to
24.954 +** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
24.955 +*/
24.956 +static int getAndInitPage(
24.957 + BtShared *pBt, /* The database file */
24.958 + Pgno pgno, /* Number of the page to get */
24.959 + MemPage **ppPage, /* Write the page pointer here */
24.960 + MemPage *pParent /* Parent of the page */
24.961 +){
24.962 + int rc;
24.963 + if( pgno==0 ){
24.964 + return SQLITE_CORRUPT_BKPT;
24.965 + }
24.966 + rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
24.967 + if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
24.968 + rc = sqlite3BtreeInitPage(*ppPage, pParent);
24.969 + }
24.970 + return rc;
24.971 +}
24.972 +
24.973 +/*
24.974 +** Release a MemPage. This should be called once for each prior
24.975 +** call to sqlite3BtreeGetPage.
24.976 +*/
24.977 +static void releasePage(MemPage *pPage){
24.978 + if( pPage ){
24.979 + assert( pPage->aData );
24.980 + assert( pPage->pBt );
24.981 + assert( &pPage->aData[pPage->pBt->pageSize]==(unsigned char*)pPage );
24.982 + sqlite3PagerUnref(pPage->pDbPage);
24.983 + }
24.984 +}
24.985 +
24.986 +/*
24.987 +** This routine is called when the reference count for a page
24.988 +** reaches zero. We need to unref the pParent pointer when that
24.989 +** happens.
24.990 +*/
24.991 +static void pageDestructor(DbPage *pData, int pageSize){
24.992 + MemPage *pPage;
24.993 + assert( (pageSize & 7)==0 );
24.994 + pPage = (MemPage *)sqlite3PagerGetExtra(pData);
24.995 + if( pPage->pParent ){
24.996 + MemPage *pParent = pPage->pParent;
24.997 + pPage->pParent = 0;
24.998 + releasePage(pParent);
24.999 + }
24.1000 + pPage->isInit = 0;
24.1001 +}
24.1002 +
24.1003 +/*
24.1004 +** During a rollback, when the pager reloads information into the cache
24.1005 +** so that the cache is restored to its original state at the start of
24.1006 +** the transaction, for each page restored this routine is called.
24.1007 +**
24.1008 +** This routine needs to reset the extra data section at the end of the
24.1009 +** page to agree with the restored data.
24.1010 +*/
24.1011 +static void pageReinit(DbPage *pData, int pageSize){
24.1012 + MemPage *pPage;
24.1013 + assert( (pageSize & 7)==0 );
24.1014 + pPage = (MemPage *)sqlite3PagerGetExtra(pData);
24.1015 + if( pPage->isInit ){
24.1016 + pPage->isInit = 0;
24.1017 + sqlite3BtreeInitPage(pPage, pPage->pParent);
24.1018 + }
24.1019 +}
24.1020 +
24.1021 +/*
24.1022 +** Open a database file.
24.1023 +**
24.1024 +** zFilename is the name of the database file. If zFilename is NULL
24.1025 +** a new database with a random name is created. This randomly named
24.1026 +** database file will be deleted when sqlite3BtreeClose() is called.
24.1027 +*/
24.1028 +int sqlite3BtreeOpen(
24.1029 + const char *zFilename, /* Name of the file containing the BTree database */
24.1030 + sqlite3 *pSqlite, /* Associated database handle */
24.1031 + Btree **ppBtree, /* Pointer to new Btree object written here */
24.1032 + int flags /* Options */
24.1033 +){
24.1034 + BtShared *pBt; /* Shared part of btree structure */
24.1035 + Btree *p; /* Handle to return */
24.1036 + int rc = SQLITE_OK;
24.1037 + int nReserve;
24.1038 + unsigned char zDbHeader[100];
24.1039 +#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
24.1040 + const ThreadData *pTsdro;
24.1041 +#endif
24.1042 +
24.1043 + /* Set the variable isMemdb to true for an in-memory database, or
24.1044 + ** false for a file-based database. This symbol is only required if
24.1045 + ** either of the shared-data or autovacuum features are compiled
24.1046 + ** into the library.
24.1047 + */
24.1048 +#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
24.1049 + #ifdef SQLITE_OMIT_MEMORYDB
24.1050 + const int isMemdb = 0;
24.1051 + #else
24.1052 + const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
24.1053 + #endif
24.1054 +#endif
24.1055 +
24.1056 + p = sqliteMalloc(sizeof(Btree));
24.1057 + if( !p ){
24.1058 + return SQLITE_NOMEM;
24.1059 + }
24.1060 + p->inTrans = TRANS_NONE;
24.1061 + p->pSqlite = pSqlite;
24.1062 +
24.1063 + /* Try to find an existing Btree structure opened on zFilename. */
24.1064 +#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
24.1065 + pTsdro = sqlite3ThreadDataReadOnly();
24.1066 + if( pTsdro->useSharedData && zFilename && !isMemdb ){
24.1067 + char *zFullPathname = sqlite3OsFullPathname(zFilename);
24.1068 + if( !zFullPathname ){
24.1069 + sqliteFree(p);
24.1070 + return SQLITE_NOMEM;
24.1071 + }
24.1072 + for(pBt=pTsdro->pBtree; pBt; pBt=pBt->pNext){
24.1073 + assert( pBt->nRef>0 );
24.1074 + if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager)) ){
24.1075 + p->pBt = pBt;
24.1076 + *ppBtree = p;
24.1077 + pBt->nRef++;
24.1078 + sqliteFree(zFullPathname);
24.1079 + return SQLITE_OK;
24.1080 + }
24.1081 + }
24.1082 + sqliteFree(zFullPathname);
24.1083 + }
24.1084 +#endif
24.1085 +
24.1086 + /*
24.1087 + ** The following asserts make sure that structures used by the btree are
24.1088 + ** the right size. This is to guard against size changes that result
24.1089 + ** when compiling on a different architecture.
24.1090 + */
24.1091 + assert( sizeof(i64)==8 || sizeof(i64)==4 );
24.1092 + assert( sizeof(u64)==8 || sizeof(u64)==4 );
24.1093 + assert( sizeof(u32)==4 );
24.1094 + assert( sizeof(u16)==2 );
24.1095 + assert( sizeof(Pgno)==4 );
24.1096 +
24.1097 + pBt = sqliteMalloc( sizeof(*pBt) );
24.1098 + if( pBt==0 ){
24.1099 + rc = SQLITE_NOMEM;
24.1100 + goto btree_open_out;
24.1101 + }
24.1102 + rc = sqlite3PagerOpen(&pBt->pPager, zFilename, EXTRA_SIZE, flags);
24.1103 + if( rc==SQLITE_OK ){
24.1104 + rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
24.1105 + }
24.1106 + if( rc!=SQLITE_OK ){
24.1107 + goto btree_open_out;
24.1108 + }
24.1109 + p->pBt = pBt;
24.1110 +
24.1111 + sqlite3PagerSetDestructor(pBt->pPager, pageDestructor);
24.1112 + sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
24.1113 + pBt->pCursor = 0;
24.1114 + pBt->pPage1 = 0;
24.1115 + pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
24.1116 + pBt->pageSize = get2byte(&zDbHeader[16]);
24.1117 + if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
24.1118 + || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
24.1119 + pBt->pageSize = SQLITE_DEFAULT_PAGE_SIZE;
24.1120 + pBt->maxEmbedFrac = 64; /* 25% */
24.1121 + pBt->minEmbedFrac = 32; /* 12.5% */
24.1122 + pBt->minLeafFrac = 32; /* 12.5% */
24.1123 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.1124 + /* If the magic name ":memory:" will create an in-memory database, then
24.1125 + ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
24.1126 + ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
24.1127 + ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
24.1128 + ** regular file-name. In this case the auto-vacuum applies as per normal.
24.1129 + */
24.1130 + if( zFilename && !isMemdb ){
24.1131 + pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
24.1132 + pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
24.1133 + }
24.1134 +#endif
24.1135 + nReserve = 0;
24.1136 + }else{
24.1137 + nReserve = zDbHeader[20];
24.1138 + pBt->maxEmbedFrac = zDbHeader[21];
24.1139 + pBt->minEmbedFrac = zDbHeader[22];
24.1140 + pBt->minLeafFrac = zDbHeader[23];
24.1141 + pBt->pageSizeFixed = 1;
24.1142 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.1143 + pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
24.1144 + pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
24.1145 +#endif
24.1146 + }
24.1147 + pBt->usableSize = pBt->pageSize - nReserve;
24.1148 + assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
24.1149 + sqlite3PagerSetPagesize(pBt->pPager, pBt->pageSize);
24.1150 +
24.1151 +#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
24.1152 + /* Add the new btree to the linked list starting at ThreadData.pBtree.
24.1153 + ** There is no chance that a malloc() may fail inside of the
24.1154 + ** sqlite3ThreadData() call, as the ThreadData structure must have already
24.1155 + ** been allocated for pTsdro->useSharedData to be non-zero.
24.1156 + */
24.1157 + if( pTsdro->useSharedData && zFilename && !isMemdb ){
24.1158 + pBt->pNext = pTsdro->pBtree;
24.1159 + sqlite3ThreadData()->pBtree = pBt;
24.1160 + }
24.1161 +#endif
24.1162 + pBt->nRef = 1;
24.1163 + *ppBtree = p;
24.1164 +
24.1165 +btree_open_out:
24.1166 + if( rc!=SQLITE_OK ){
24.1167 + if( pBt && pBt->pPager ){
24.1168 + sqlite3PagerClose(pBt->pPager);
24.1169 + }
24.1170 + sqliteFree(pBt);
24.1171 + sqliteFree(p);
24.1172 + *ppBtree = 0;
24.1173 + }
24.1174 + return rc;
24.1175 +}
24.1176 +
24.1177 +/*
24.1178 +** Close an open database and invalidate all cursors.
24.1179 +*/
24.1180 +int sqlite3BtreeClose(Btree *p){
24.1181 + BtShared *pBt = p->pBt;
24.1182 + BtCursor *pCur;
24.1183 +
24.1184 +#ifndef SQLITE_OMIT_SHARED_CACHE
24.1185 + ThreadData *pTsd;
24.1186 +#endif
24.1187 +
24.1188 + /* Close all cursors opened via this handle. */
24.1189 + pCur = pBt->pCursor;
24.1190 + while( pCur ){
24.1191 + BtCursor *pTmp = pCur;
24.1192 + pCur = pCur->pNext;
24.1193 + if( pTmp->pBtree==p ){
24.1194 + sqlite3BtreeCloseCursor(pTmp);
24.1195 + }
24.1196 + }
24.1197 +
24.1198 + /* Rollback any active transaction and free the handle structure.
24.1199 + ** The call to sqlite3BtreeRollback() drops any table-locks held by
24.1200 + ** this handle.
24.1201 + */
24.1202 + sqlite3BtreeRollback(p);
24.1203 + sqliteFree(p);
24.1204 +
24.1205 +#ifndef SQLITE_OMIT_SHARED_CACHE
24.1206 + /* If there are still other outstanding references to the shared-btree
24.1207 + ** structure, return now. The remainder of this procedure cleans
24.1208 + ** up the shared-btree.
24.1209 + */
24.1210 + assert( pBt->nRef>0 );
24.1211 + pBt->nRef--;
24.1212 + if( pBt->nRef ){
24.1213 + return SQLITE_OK;
24.1214 + }
24.1215 +
24.1216 + /* Remove the shared-btree from the thread wide list. Call
24.1217 + ** ThreadDataReadOnly() and then cast away the const property of the
24.1218 + ** pointer to avoid allocating thread data if it is not really required.
24.1219 + */
24.1220 + pTsd = (ThreadData *)sqlite3ThreadDataReadOnly();
24.1221 + if( pTsd->pBtree==pBt ){
24.1222 + assert( pTsd==sqlite3ThreadData() );
24.1223 + pTsd->pBtree = pBt->pNext;
24.1224 + }else{
24.1225 + BtShared *pPrev;
24.1226 + for(pPrev=pTsd->pBtree; pPrev && pPrev->pNext!=pBt; pPrev=pPrev->pNext){}
24.1227 + if( pPrev ){
24.1228 + assert( pTsd==sqlite3ThreadData() );
24.1229 + pPrev->pNext = pBt->pNext;
24.1230 + }
24.1231 + }
24.1232 +#endif
24.1233 +
24.1234 + /* Close the pager and free the shared-btree structure */
24.1235 + assert( !pBt->pCursor );
24.1236 + sqlite3PagerClose(pBt->pPager);
24.1237 + if( pBt->xFreeSchema && pBt->pSchema ){
24.1238 + pBt->xFreeSchema(pBt->pSchema);
24.1239 + }
24.1240 + sqliteFree(pBt->pSchema);
24.1241 + sqliteFree(pBt);
24.1242 + return SQLITE_OK;
24.1243 +}
24.1244 +
24.1245 +/*
24.1246 +** Change the busy handler callback function.
24.1247 +*/
24.1248 +int sqlite3BtreeSetBusyHandler(Btree *p, BusyHandler *pHandler){
24.1249 + BtShared *pBt = p->pBt;
24.1250 + pBt->pBusyHandler = pHandler;
24.1251 + sqlite3PagerSetBusyhandler(pBt->pPager, pHandler);
24.1252 + return SQLITE_OK;
24.1253 +}
24.1254 +
24.1255 +/*
24.1256 +** Change the limit on the number of pages allowed in the cache.
24.1257 +**
24.1258 +** The maximum number of cache pages is set to the absolute
24.1259 +** value of mxPage. If mxPage is negative, the pager will
24.1260 +** operate asynchronously - it will not stop to do fsync()s
24.1261 +** to insure data is written to the disk surface before
24.1262 +** continuing. Transactions still work if synchronous is off,
24.1263 +** and the database cannot be corrupted if this program
24.1264 +** crashes. But if the operating system crashes or there is
24.1265 +** an abrupt power failure when synchronous is off, the database
24.1266 +** could be left in an inconsistent and unrecoverable state.
24.1267 +** Synchronous is on by default so database corruption is not
24.1268 +** normally a worry.
24.1269 +*/
24.1270 +int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
24.1271 + BtShared *pBt = p->pBt;
24.1272 + sqlite3PagerSetCachesize(pBt->pPager, mxPage);
24.1273 + return SQLITE_OK;
24.1274 +}
24.1275 +
24.1276 +/*
24.1277 +** Change the way data is synced to disk in order to increase or decrease
24.1278 +** how well the database resists damage due to OS crashes and power
24.1279 +** failures. Level 1 is the same as asynchronous (no syncs() occur and
24.1280 +** there is a high probability of damage) Level 2 is the default. There
24.1281 +** is a very low but non-zero probability of damage. Level 3 reduces the
24.1282 +** probability of damage to near zero but with a write performance reduction.
24.1283 +*/
24.1284 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
24.1285 +int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
24.1286 + BtShared *pBt = p->pBt;
24.1287 + sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
24.1288 + return SQLITE_OK;
24.1289 +}
24.1290 +#endif
24.1291 +
24.1292 +/*
24.1293 +** Return TRUE if the given btree is set to safety level 1. In other
24.1294 +** words, return TRUE if no sync() occurs on the disk files.
24.1295 +*/
24.1296 +int sqlite3BtreeSyncDisabled(Btree *p){
24.1297 + BtShared *pBt = p->pBt;
24.1298 + assert( pBt && pBt->pPager );
24.1299 + return sqlite3PagerNosync(pBt->pPager);
24.1300 +}
24.1301 +
24.1302 +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
24.1303 +/*
24.1304 +** Change the default pages size and the number of reserved bytes per page.
24.1305 +**
24.1306 +** The page size must be a power of 2 between 512 and 65536. If the page
24.1307 +** size supplied does not meet this constraint then the page size is not
24.1308 +** changed.
24.1309 +**
24.1310 +** Page sizes are constrained to be a power of two so that the region
24.1311 +** of the database file used for locking (beginning at PENDING_BYTE,
24.1312 +** the first byte past the 1GB boundary, 0x40000000) needs to occur
24.1313 +** at the beginning of a page.
24.1314 +**
24.1315 +** If parameter nReserve is less than zero, then the number of reserved
24.1316 +** bytes per page is left unchanged.
24.1317 +*/
24.1318 +int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
24.1319 + BtShared *pBt = p->pBt;
24.1320 + if( pBt->pageSizeFixed ){
24.1321 + return SQLITE_READONLY;
24.1322 + }
24.1323 + if( nReserve<0 ){
24.1324 + nReserve = pBt->pageSize - pBt->usableSize;
24.1325 + }
24.1326 + if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
24.1327 + ((pageSize-1)&pageSize)==0 ){
24.1328 + assert( (pageSize & 7)==0 );
24.1329 + assert( !pBt->pPage1 && !pBt->pCursor );
24.1330 + pBt->pageSize = sqlite3PagerSetPagesize(pBt->pPager, pageSize);
24.1331 + }
24.1332 + pBt->usableSize = pBt->pageSize - nReserve;
24.1333 + return SQLITE_OK;
24.1334 +}
24.1335 +
24.1336 +/*
24.1337 +** Return the currently defined page size
24.1338 +*/
24.1339 +int sqlite3BtreeGetPageSize(Btree *p){
24.1340 + return p->pBt->pageSize;
24.1341 +}
24.1342 +int sqlite3BtreeGetReserve(Btree *p){
24.1343 + return p->pBt->pageSize - p->pBt->usableSize;
24.1344 +}
24.1345 +
24.1346 +/*
24.1347 +** Set the maximum page count for a database if mxPage is positive.
24.1348 +** No changes are made if mxPage is 0 or negative.
24.1349 +** Regardless of the value of mxPage, return the maximum page count.
24.1350 +*/
24.1351 +int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
24.1352 + return sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
24.1353 +}
24.1354 +#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
24.1355 +
24.1356 +/*
24.1357 +** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
24.1358 +** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
24.1359 +** is disabled. The default value for the auto-vacuum property is
24.1360 +** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
24.1361 +*/
24.1362 +int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
24.1363 +#ifdef SQLITE_OMIT_AUTOVACUUM
24.1364 + return SQLITE_READONLY;
24.1365 +#else
24.1366 + BtShared *pBt = p->pBt;
24.1367 + int av = (autoVacuum?1:0);
24.1368 + if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
24.1369 + return SQLITE_READONLY;
24.1370 + }
24.1371 + pBt->autoVacuum = av;
24.1372 + return SQLITE_OK;
24.1373 +#endif
24.1374 +}
24.1375 +
24.1376 +/*
24.1377 +** Return the value of the 'auto-vacuum' property. If auto-vacuum is
24.1378 +** enabled 1 is returned. Otherwise 0.
24.1379 +*/
24.1380 +int sqlite3BtreeGetAutoVacuum(Btree *p){
24.1381 +#ifdef SQLITE_OMIT_AUTOVACUUM
24.1382 + return BTREE_AUTOVACUUM_NONE;
24.1383 +#else
24.1384 + return (
24.1385 + (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
24.1386 + (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
24.1387 + BTREE_AUTOVACUUM_INCR
24.1388 + );
24.1389 +#endif
24.1390 +}
24.1391 +
24.1392 +
24.1393 +/*
24.1394 +** Get a reference to pPage1 of the database file. This will
24.1395 +** also acquire a readlock on that file.
24.1396 +**
24.1397 +** SQLITE_OK is returned on success. If the file is not a
24.1398 +** well-formed database file, then SQLITE_CORRUPT is returned.
24.1399 +** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
24.1400 +** is returned if we run out of memory.
24.1401 +*/
24.1402 +static int lockBtree(BtShared *pBt){
24.1403 + int rc, pageSize;
24.1404 + MemPage *pPage1;
24.1405 + if( pBt->pPage1 ) return SQLITE_OK;
24.1406 + rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
24.1407 + if( rc!=SQLITE_OK ) return rc;
24.1408 +
24.1409 +
24.1410 + /* Do some checking to help insure the file we opened really is
24.1411 + ** a valid database file.
24.1412 + */
24.1413 + rc = SQLITE_NOTADB;
24.1414 + if( sqlite3PagerPagecount(pBt->pPager)>0 ){
24.1415 + u8 *page1 = pPage1->aData;
24.1416 + if( memcmp(page1, zMagicHeader, 16)!=0 ){
24.1417 + goto page1_init_failed;
24.1418 + }
24.1419 + if( page1[18]>1 ){
24.1420 + pBt->readOnly = 1;
24.1421 + }
24.1422 + if( page1[19]>1 ){
24.1423 + goto page1_init_failed;
24.1424 + }
24.1425 + pageSize = get2byte(&page1[16]);
24.1426 + if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ){
24.1427 + goto page1_init_failed;
24.1428 + }
24.1429 + assert( (pageSize & 7)==0 );
24.1430 + pBt->pageSize = pageSize;
24.1431 + pBt->usableSize = pageSize - page1[20];
24.1432 + if( pBt->usableSize<500 ){
24.1433 + goto page1_init_failed;
24.1434 + }
24.1435 + pBt->maxEmbedFrac = page1[21];
24.1436 + pBt->minEmbedFrac = page1[22];
24.1437 + pBt->minLeafFrac = page1[23];
24.1438 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.1439 + pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
24.1440 + pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
24.1441 +#endif
24.1442 + }
24.1443 +
24.1444 + /* maxLocal is the maximum amount of payload to store locally for
24.1445 + ** a cell. Make sure it is small enough so that at least minFanout
24.1446 + ** cells can will fit on one page. We assume a 10-byte page header.
24.1447 + ** Besides the payload, the cell must store:
24.1448 + ** 2-byte pointer to the cell
24.1449 + ** 4-byte child pointer
24.1450 + ** 9-byte nKey value
24.1451 + ** 4-byte nData value
24.1452 + ** 4-byte overflow page pointer
24.1453 + ** So a cell consists of a 2-byte poiner, a header which is as much as
24.1454 + ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
24.1455 + ** page pointer.
24.1456 + */
24.1457 + pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
24.1458 + pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
24.1459 + pBt->maxLeaf = pBt->usableSize - 35;
24.1460 + pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
24.1461 + if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
24.1462 + goto page1_init_failed;
24.1463 + }
24.1464 + assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
24.1465 + pBt->pPage1 = pPage1;
24.1466 + return SQLITE_OK;
24.1467 +
24.1468 +page1_init_failed:
24.1469 + releasePage(pPage1);
24.1470 + pBt->pPage1 = 0;
24.1471 + return rc;
24.1472 +}
24.1473 +
24.1474 +/*
24.1475 +** This routine works like lockBtree() except that it also invokes the
24.1476 +** busy callback if there is lock contention.
24.1477 +*/
24.1478 +static int lockBtreeWithRetry(Btree *pRef){
24.1479 + int rc = SQLITE_OK;
24.1480 + if( pRef->inTrans==TRANS_NONE ){
24.1481 + u8 inTransaction = pRef->pBt->inTransaction;
24.1482 + btreeIntegrity(pRef);
24.1483 + rc = sqlite3BtreeBeginTrans(pRef, 0);
24.1484 + pRef->pBt->inTransaction = inTransaction;
24.1485 + pRef->inTrans = TRANS_NONE;
24.1486 + if( rc==SQLITE_OK ){
24.1487 + pRef->pBt->nTransaction--;
24.1488 + }
24.1489 + btreeIntegrity(pRef);
24.1490 + }
24.1491 + return rc;
24.1492 +}
24.1493 +
24.1494 +
24.1495 +/*
24.1496 +** If there are no outstanding cursors and we are not in the middle
24.1497 +** of a transaction but there is a read lock on the database, then
24.1498 +** this routine unrefs the first page of the database file which
24.1499 +** has the effect of releasing the read lock.
24.1500 +**
24.1501 +** If there are any outstanding cursors, this routine is a no-op.
24.1502 +**
24.1503 +** If there is a transaction in progress, this routine is a no-op.
24.1504 +*/
24.1505 +static void unlockBtreeIfUnused(BtShared *pBt){
24.1506 + if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
24.1507 + if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
24.1508 + if( pBt->pPage1->aData==0 ){
24.1509 + MemPage *pPage = pBt->pPage1;
24.1510 + pPage->aData = &((u8*)pPage)[-pBt->pageSize];
24.1511 + pPage->pBt = pBt;
24.1512 + pPage->pgno = 1;
24.1513 + }
24.1514 + releasePage(pBt->pPage1);
24.1515 + }
24.1516 + pBt->pPage1 = 0;
24.1517 + pBt->inStmt = 0;
24.1518 + }
24.1519 +}
24.1520 +
24.1521 +/*
24.1522 +** Create a new database by initializing the first page of the
24.1523 +** file.
24.1524 +*/
24.1525 +static int newDatabase(BtShared *pBt){
24.1526 + MemPage *pP1;
24.1527 + unsigned char *data;
24.1528 + int rc;
24.1529 + if( sqlite3PagerPagecount(pBt->pPager)>0 ) return SQLITE_OK;
24.1530 + pP1 = pBt->pPage1;
24.1531 + assert( pP1!=0 );
24.1532 + data = pP1->aData;
24.1533 + rc = sqlite3PagerWrite(pP1->pDbPage);
24.1534 + if( rc ) return rc;
24.1535 + memcpy(data, zMagicHeader, sizeof(zMagicHeader));
24.1536 + assert( sizeof(zMagicHeader)==16 );
24.1537 + put2byte(&data[16], pBt->pageSize);
24.1538 + data[18] = 1;
24.1539 + data[19] = 1;
24.1540 + data[20] = pBt->pageSize - pBt->usableSize;
24.1541 + data[21] = pBt->maxEmbedFrac;
24.1542 + data[22] = pBt->minEmbedFrac;
24.1543 + data[23] = pBt->minLeafFrac;
24.1544 + memset(&data[24], 0, 100-24);
24.1545 + zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
24.1546 + pBt->pageSizeFixed = 1;
24.1547 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.1548 + assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
24.1549 + assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
24.1550 + put4byte(&data[36 + 4*4], pBt->autoVacuum);
24.1551 + put4byte(&data[36 + 7*4], pBt->incrVacuum);
24.1552 +#endif
24.1553 + return SQLITE_OK;
24.1554 +}
24.1555 +
24.1556 +/*
24.1557 +** Attempt to start a new transaction. A write-transaction
24.1558 +** is started if the second argument is nonzero, otherwise a read-
24.1559 +** transaction. If the second argument is 2 or more and exclusive
24.1560 +** transaction is started, meaning that no other process is allowed
24.1561 +** to access the database. A preexisting transaction may not be
24.1562 +** upgraded to exclusive by calling this routine a second time - the
24.1563 +** exclusivity flag only works for a new transaction.
24.1564 +**
24.1565 +** A write-transaction must be started before attempting any
24.1566 +** changes to the database. None of the following routines
24.1567 +** will work unless a transaction is started first:
24.1568 +**
24.1569 +** sqlite3BtreeCreateTable()
24.1570 +** sqlite3BtreeCreateIndex()
24.1571 +** sqlite3BtreeClearTable()
24.1572 +** sqlite3BtreeDropTable()
24.1573 +** sqlite3BtreeInsert()
24.1574 +** sqlite3BtreeDelete()
24.1575 +** sqlite3BtreeUpdateMeta()
24.1576 +**
24.1577 +** If an initial attempt to acquire the lock fails because of lock contention
24.1578 +** and the database was previously unlocked, then invoke the busy handler
24.1579 +** if there is one. But if there was previously a read-lock, do not
24.1580 +** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
24.1581 +** returned when there is already a read-lock in order to avoid a deadlock.
24.1582 +**
24.1583 +** Suppose there are two processes A and B. A has a read lock and B has
24.1584 +** a reserved lock. B tries to promote to exclusive but is blocked because
24.1585 +** of A's read lock. A tries to promote to reserved but is blocked by B.
24.1586 +** One or the other of the two processes must give way or there can be
24.1587 +** no progress. By returning SQLITE_BUSY and not invoking the busy callback
24.1588 +** when A already has a read lock, we encourage A to give up and let B
24.1589 +** proceed.
24.1590 +*/
24.1591 +int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
24.1592 + BtShared *pBt = p->pBt;
24.1593 + int rc = SQLITE_OK;
24.1594 +
24.1595 + btreeIntegrity(p);
24.1596 +
24.1597 + /* If the btree is already in a write-transaction, or it
24.1598 + ** is already in a read-transaction and a read-transaction
24.1599 + ** is requested, this is a no-op.
24.1600 + */
24.1601 + if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
24.1602 + return SQLITE_OK;
24.1603 + }
24.1604 +
24.1605 + /* Write transactions are not possible on a read-only database */
24.1606 + if( pBt->readOnly && wrflag ){
24.1607 + return SQLITE_READONLY;
24.1608 + }
24.1609 +
24.1610 + /* If another database handle has already opened a write transaction
24.1611 + ** on this shared-btree structure and a second write transaction is
24.1612 + ** requested, return SQLITE_BUSY.
24.1613 + */
24.1614 + if( pBt->inTransaction==TRANS_WRITE && wrflag ){
24.1615 + return SQLITE_BUSY;
24.1616 + }
24.1617 +
24.1618 + do {
24.1619 + if( pBt->pPage1==0 ){
24.1620 + rc = lockBtree(pBt);
24.1621 + }
24.1622 +
24.1623 + if( rc==SQLITE_OK && wrflag ){
24.1624 + if( pBt->readOnly ){
24.1625 + rc = SQLITE_READONLY;
24.1626 + }else{
24.1627 + rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
24.1628 + if( rc==SQLITE_OK ){
24.1629 + rc = newDatabase(pBt);
24.1630 + }
24.1631 + }
24.1632 + }
24.1633 +
24.1634 + if( rc==SQLITE_OK ){
24.1635 + if( wrflag ) pBt->inStmt = 0;
24.1636 + }else{
24.1637 + unlockBtreeIfUnused(pBt);
24.1638 + }
24.1639 + }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
24.1640 + sqlite3InvokeBusyHandler(pBt->pBusyHandler) );
24.1641 +
24.1642 + if( rc==SQLITE_OK ){
24.1643 + if( p->inTrans==TRANS_NONE ){
24.1644 + pBt->nTransaction++;
24.1645 + }
24.1646 + p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
24.1647 + if( p->inTrans>pBt->inTransaction ){
24.1648 + pBt->inTransaction = p->inTrans;
24.1649 + }
24.1650 + }
24.1651 +
24.1652 + btreeIntegrity(p);
24.1653 + return rc;
24.1654 +}
24.1655 +
24.1656 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.1657 +
24.1658 +/*
24.1659 +** Set the pointer-map entries for all children of page pPage. Also, if
24.1660 +** pPage contains cells that point to overflow pages, set the pointer
24.1661 +** map entries for the overflow pages as well.
24.1662 +*/
24.1663 +static int setChildPtrmaps(MemPage *pPage){
24.1664 + int i; /* Counter variable */
24.1665 + int nCell; /* Number of cells in page pPage */
24.1666 + int rc; /* Return code */
24.1667 + BtShared *pBt = pPage->pBt;
24.1668 + int isInitOrig = pPage->isInit;
24.1669 + Pgno pgno = pPage->pgno;
24.1670 +
24.1671 + rc = sqlite3BtreeInitPage(pPage, pPage->pParent);
24.1672 + if( rc!=SQLITE_OK ){
24.1673 + goto set_child_ptrmaps_out;
24.1674 + }
24.1675 + nCell = pPage->nCell;
24.1676 +
24.1677 + for(i=0; i<nCell; i++){
24.1678 + u8 *pCell = findCell(pPage, i);
24.1679 +
24.1680 + rc = ptrmapPutOvflPtr(pPage, pCell);
24.1681 + if( rc!=SQLITE_OK ){
24.1682 + goto set_child_ptrmaps_out;
24.1683 + }
24.1684 +
24.1685 + if( !pPage->leaf ){
24.1686 + Pgno childPgno = get4byte(pCell);
24.1687 + rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
24.1688 + if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
24.1689 + }
24.1690 + }
24.1691 +
24.1692 + if( !pPage->leaf ){
24.1693 + Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
24.1694 + rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
24.1695 + }
24.1696 +
24.1697 +set_child_ptrmaps_out:
24.1698 + pPage->isInit = isInitOrig;
24.1699 + return rc;
24.1700 +}
24.1701 +
24.1702 +/*
24.1703 +** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
24.1704 +** page, is a pointer to page iFrom. Modify this pointer so that it points to
24.1705 +** iTo. Parameter eType describes the type of pointer to be modified, as
24.1706 +** follows:
24.1707 +**
24.1708 +** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
24.1709 +** page of pPage.
24.1710 +**
24.1711 +** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
24.1712 +** page pointed to by one of the cells on pPage.
24.1713 +**
24.1714 +** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
24.1715 +** overflow page in the list.
24.1716 +*/
24.1717 +static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
24.1718 + if( eType==PTRMAP_OVERFLOW2 ){
24.1719 + /* The pointer is always the first 4 bytes of the page in this case. */
24.1720 + if( get4byte(pPage->aData)!=iFrom ){
24.1721 + return SQLITE_CORRUPT_BKPT;
24.1722 + }
24.1723 + put4byte(pPage->aData, iTo);
24.1724 + }else{
24.1725 + int isInitOrig = pPage->isInit;
24.1726 + int i;
24.1727 + int nCell;
24.1728 +
24.1729 + sqlite3BtreeInitPage(pPage, 0);
24.1730 + nCell = pPage->nCell;
24.1731 +
24.1732 + for(i=0; i<nCell; i++){
24.1733 + u8 *pCell = findCell(pPage, i);
24.1734 + if( eType==PTRMAP_OVERFLOW1 ){
24.1735 + CellInfo info;
24.1736 + sqlite3BtreeParseCellPtr(pPage, pCell, &info);
24.1737 + if( info.iOverflow ){
24.1738 + if( iFrom==get4byte(&pCell[info.iOverflow]) ){
24.1739 + put4byte(&pCell[info.iOverflow], iTo);
24.1740 + break;
24.1741 + }
24.1742 + }
24.1743 + }else{
24.1744 + if( get4byte(pCell)==iFrom ){
24.1745 + put4byte(pCell, iTo);
24.1746 + break;
24.1747 + }
24.1748 + }
24.1749 + }
24.1750 +
24.1751 + if( i==nCell ){
24.1752 + if( eType!=PTRMAP_BTREE ||
24.1753 + get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
24.1754 + return SQLITE_CORRUPT_BKPT;
24.1755 + }
24.1756 + put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
24.1757 + }
24.1758 +
24.1759 + pPage->isInit = isInitOrig;
24.1760 + }
24.1761 + return SQLITE_OK;
24.1762 +}
24.1763 +
24.1764 +
24.1765 +/*
24.1766 +** Move the open database page pDbPage to location iFreePage in the
24.1767 +** database. The pDbPage reference remains valid.
24.1768 +*/
24.1769 +static int relocatePage(
24.1770 + BtShared *pBt, /* Btree */
24.1771 + MemPage *pDbPage, /* Open page to move */
24.1772 + u8 eType, /* Pointer map 'type' entry for pDbPage */
24.1773 + Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
24.1774 + Pgno iFreePage /* The location to move pDbPage to */
24.1775 +){
24.1776 + MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
24.1777 + Pgno iDbPage = pDbPage->pgno;
24.1778 + Pager *pPager = pBt->pPager;
24.1779 + int rc;
24.1780 +
24.1781 + assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
24.1782 + eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
24.1783 +
24.1784 + /* Move page iDbPage from it's current location to page number iFreePage */
24.1785 + TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
24.1786 + iDbPage, iFreePage, iPtrPage, eType));
24.1787 + rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage);
24.1788 + if( rc!=SQLITE_OK ){
24.1789 + return rc;
24.1790 + }
24.1791 + pDbPage->pgno = iFreePage;
24.1792 +
24.1793 + /* If pDbPage was a btree-page, then it may have child pages and/or cells
24.1794 + ** that point to overflow pages. The pointer map entries for all these
24.1795 + ** pages need to be changed.
24.1796 + **
24.1797 + ** If pDbPage is an overflow page, then the first 4 bytes may store a
24.1798 + ** pointer to a subsequent overflow page. If this is the case, then
24.1799 + ** the pointer map needs to be updated for the subsequent overflow page.
24.1800 + */
24.1801 + if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
24.1802 + rc = setChildPtrmaps(pDbPage);
24.1803 + if( rc!=SQLITE_OK ){
24.1804 + return rc;
24.1805 + }
24.1806 + }else{
24.1807 + Pgno nextOvfl = get4byte(pDbPage->aData);
24.1808 + if( nextOvfl!=0 ){
24.1809 + rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
24.1810 + if( rc!=SQLITE_OK ){
24.1811 + return rc;
24.1812 + }
24.1813 + }
24.1814 + }
24.1815 +
24.1816 + /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
24.1817 + ** that it points at iFreePage. Also fix the pointer map entry for
24.1818 + ** iPtrPage.
24.1819 + */
24.1820 + if( eType!=PTRMAP_ROOTPAGE ){
24.1821 + rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
24.1822 + if( rc!=SQLITE_OK ){
24.1823 + return rc;
24.1824 + }
24.1825 + rc = sqlite3PagerWrite(pPtrPage->pDbPage);
24.1826 + if( rc!=SQLITE_OK ){
24.1827 + releasePage(pPtrPage);
24.1828 + return rc;
24.1829 + }
24.1830 + rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
24.1831 + releasePage(pPtrPage);
24.1832 + if( rc==SQLITE_OK ){
24.1833 + rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
24.1834 + }
24.1835 + }
24.1836 + return rc;
24.1837 +}
24.1838 +
24.1839 +/* Forward declaration required by incrVacuumStep(). */
24.1840 +static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
24.1841 +
24.1842 +/*
24.1843 +** Perform a single step of an incremental-vacuum. If successful,
24.1844 +** return SQLITE_OK. If there is no work to do (and therefore no
24.1845 +** point in calling this function again), return SQLITE_DONE.
24.1846 +**
24.1847 +** More specificly, this function attempts to re-organize the
24.1848 +** database so that the last page of the file currently in use
24.1849 +** is no longer in use.
24.1850 +**
24.1851 +** If the nFin parameter is non-zero, the implementation assumes
24.1852 +** that the caller will keep calling incrVacuumStep() until
24.1853 +** it returns SQLITE_DONE or an error, and that nFin is the
24.1854 +** number of pages the database file will contain after this
24.1855 +** process is complete.
24.1856 +*/
24.1857 +static int incrVacuumStep(BtShared *pBt, Pgno nFin){
24.1858 + Pgno iLastPg; /* Last page in the database */
24.1859 + Pgno nFreeList; /* Number of pages still on the free-list */
24.1860 +
24.1861 + iLastPg = pBt->nTrunc;
24.1862 + if( iLastPg==0 ){
24.1863 + iLastPg = sqlite3PagerPagecount(pBt->pPager);
24.1864 + }
24.1865 +
24.1866 + if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
24.1867 + int rc;
24.1868 + u8 eType;
24.1869 + Pgno iPtrPage;
24.1870 +
24.1871 + nFreeList = get4byte(&pBt->pPage1->aData[36]);
24.1872 + if( nFreeList==0 || nFin==iLastPg ){
24.1873 + return SQLITE_DONE;
24.1874 + }
24.1875 +
24.1876 + rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
24.1877 + if( rc!=SQLITE_OK ){
24.1878 + return rc;
24.1879 + }
24.1880 + if( eType==PTRMAP_ROOTPAGE ){
24.1881 + return SQLITE_CORRUPT_BKPT;
24.1882 + }
24.1883 +
24.1884 + if( eType==PTRMAP_FREEPAGE ){
24.1885 + if( nFin==0 ){
24.1886 + /* Remove the page from the files free-list. This is not required
24.1887 + ** if nFin is non-zero. In that case, the free-list will be
24.1888 + ** truncated to zero after this function returns, so it doesn't
24.1889 + ** matter if it still contains some garbage entries.
24.1890 + */
24.1891 + Pgno iFreePg;
24.1892 + MemPage *pFreePg;
24.1893 + rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
24.1894 + if( rc!=SQLITE_OK ){
24.1895 + return rc;
24.1896 + }
24.1897 + assert( iFreePg==iLastPg );
24.1898 + releasePage(pFreePg);
24.1899 + }
24.1900 + } else {
24.1901 + Pgno iFreePg; /* Index of free page to move pLastPg to */
24.1902 + MemPage *pLastPg;
24.1903 +
24.1904 + rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
24.1905 + if( rc!=SQLITE_OK ){
24.1906 + return rc;
24.1907 + }
24.1908 +
24.1909 + /* If nFin is zero, this loop runs exactly once and page pLastPg
24.1910 + ** is swapped with the first free page pulled off the free list.
24.1911 + **
24.1912 + ** On the other hand, if nFin is greater than zero, then keep
24.1913 + ** looping until a free-page located within the first nFin pages
24.1914 + ** of the file is found.
24.1915 + */
24.1916 + do {
24.1917 + MemPage *pFreePg;
24.1918 + rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
24.1919 + if( rc!=SQLITE_OK ){
24.1920 + releasePage(pLastPg);
24.1921 + return rc;
24.1922 + }
24.1923 + releasePage(pFreePg);
24.1924 + }while( nFin!=0 && iFreePg>nFin );
24.1925 + assert( iFreePg<iLastPg );
24.1926 +
24.1927 + rc = sqlite3PagerWrite(pLastPg->pDbPage);
24.1928 + if( rc!=SQLITE_OK ){
24.1929 + return rc;
24.1930 + }
24.1931 + rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg);
24.1932 + releasePage(pLastPg);
24.1933 + if( rc!=SQLITE_OK ){
24.1934 + return rc;
24.1935 + }
24.1936 + }
24.1937 + }
24.1938 +
24.1939 + pBt->nTrunc = iLastPg - 1;
24.1940 + while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
24.1941 + pBt->nTrunc--;
24.1942 + }
24.1943 + return SQLITE_OK;
24.1944 +}
24.1945 +
24.1946 +/*
24.1947 +** A write-transaction must be opened before calling this function.
24.1948 +** It performs a single unit of work towards an incremental vacuum.
24.1949 +**
24.1950 +** If the incremental vacuum is finished after this function has run,
24.1951 +** SQLITE_DONE is returned. If it is not finished, but no error occured,
24.1952 +** SQLITE_OK is returned. Otherwise an SQLite error code.
24.1953 +*/
24.1954 +int sqlite3BtreeIncrVacuum(Btree *p){
24.1955 + BtShared *pBt = p->pBt;
24.1956 + assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
24.1957 + if( !pBt->autoVacuum ){
24.1958 + return SQLITE_DONE;
24.1959 + }
24.1960 + invalidateAllOverflowCache(pBt);
24.1961 + return incrVacuumStep(pBt, 0);
24.1962 +}
24.1963 +
24.1964 +/*
24.1965 +** This routine is called prior to sqlite3PagerCommit when a transaction
24.1966 +** is commited for an auto-vacuum database.
24.1967 +**
24.1968 +** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
24.1969 +** the database file should be truncated to during the commit process.
24.1970 +** i.e. the database has been reorganized so that only the first *pnTrunc
24.1971 +** pages are in use.
24.1972 +*/
24.1973 +static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
24.1974 + int rc = SQLITE_OK;
24.1975 + Pager *pPager = pBt->pPager;
24.1976 +#ifndef NDEBUG
24.1977 + int nRef = sqlite3PagerRefcount(pPager);
24.1978 +#endif
24.1979 +
24.1980 + invalidateAllOverflowCache(pBt);
24.1981 + assert(pBt->autoVacuum);
24.1982 + if( !pBt->incrVacuum ){
24.1983 + Pgno nFin = 0;
24.1984 +
24.1985 + if( pBt->nTrunc==0 ){
24.1986 + Pgno nFree;
24.1987 + Pgno nPtrmap;
24.1988 + const int pgsz = pBt->pageSize;
24.1989 + Pgno nOrig = sqlite3PagerPagecount(pBt->pPager);
24.1990 +
24.1991 + if( PTRMAP_ISPAGE(pBt, nOrig) ){
24.1992 + return SQLITE_CORRUPT_BKPT;
24.1993 + }
24.1994 + if( nOrig==PENDING_BYTE_PAGE(pBt) ){
24.1995 + nOrig--;
24.1996 + }
24.1997 + nFree = get4byte(&pBt->pPage1->aData[36]);
24.1998 + nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
24.1999 + nFin = nOrig - nFree - nPtrmap;
24.2000 + if( nOrig>(unsigned)PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
24.2001 + nFin--;
24.2002 + }
24.2003 + while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
24.2004 + nFin--;
24.2005 + }
24.2006 + }
24.2007 +
24.2008 + while( rc==SQLITE_OK ){
24.2009 + rc = incrVacuumStep(pBt, nFin);
24.2010 + }
24.2011 + if( rc==SQLITE_DONE ){
24.2012 + assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
24.2013 + rc = SQLITE_OK;
24.2014 + if( pBt->nTrunc ){
24.2015 + sqlite3PagerWrite(pBt->pPage1->pDbPage);
24.2016 + put4byte(&pBt->pPage1->aData[32], 0);
24.2017 + put4byte(&pBt->pPage1->aData[36], 0);
24.2018 + pBt->nTrunc = nFin;
24.2019 + }
24.2020 + }
24.2021 + if( rc!=SQLITE_OK ){
24.2022 + sqlite3PagerRollback(pPager);
24.2023 + }
24.2024 + }
24.2025 +
24.2026 + if( rc==SQLITE_OK ){
24.2027 + *pnTrunc = pBt->nTrunc;
24.2028 + pBt->nTrunc = 0;
24.2029 + }
24.2030 + assert( nRef==sqlite3PagerRefcount(pPager) );
24.2031 + return rc;
24.2032 +}
24.2033 +
24.2034 +#endif
24.2035 +
24.2036 +/*
24.2037 +** This routine does the first phase of a two-phase commit. This routine
24.2038 +** causes a rollback journal to be created (if it does not already exist)
24.2039 +** and populated with enough information so that if a power loss occurs
24.2040 +** the database can be restored to its original state by playing back
24.2041 +** the journal. Then the contents of the journal are flushed out to
24.2042 +** the disk. After the journal is safely on oxide, the changes to the
24.2043 +** database are written into the database file and flushed to oxide.
24.2044 +** At the end of this call, the rollback journal still exists on the
24.2045 +** disk and we are still holding all locks, so the transaction has not
24.2046 +** committed. See sqlite3BtreeCommit() for the second phase of the
24.2047 +** commit process.
24.2048 +**
24.2049 +** This call is a no-op if no write-transaction is currently active on pBt.
24.2050 +**
24.2051 +** Otherwise, sync the database file for the btree pBt. zMaster points to
24.2052 +** the name of a master journal file that should be written into the
24.2053 +** individual journal file, or is NULL, indicating no master journal file
24.2054 +** (single database transaction).
24.2055 +**
24.2056 +** When this is called, the master journal should already have been
24.2057 +** created, populated with this journal pointer and synced to disk.
24.2058 +**
24.2059 +** Once this is routine has returned, the only thing required to commit
24.2060 +** the write-transaction for this database file is to delete the journal.
24.2061 +*/
24.2062 +int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
24.2063 + int rc = SQLITE_OK;
24.2064 + if( p->inTrans==TRANS_WRITE ){
24.2065 + BtShared *pBt = p->pBt;
24.2066 + Pgno nTrunc = 0;
24.2067 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.2068 + if( pBt->autoVacuum ){
24.2069 + rc = autoVacuumCommit(pBt, &nTrunc);
24.2070 + if( rc!=SQLITE_OK ){
24.2071 + return rc;
24.2072 + }
24.2073 + }
24.2074 +#endif
24.2075 + rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc);
24.2076 + }
24.2077 + return rc;
24.2078 +}
24.2079 +
24.2080 +/*
24.2081 +** Commit the transaction currently in progress.
24.2082 +**
24.2083 +** This routine implements the second phase of a 2-phase commit. The
24.2084 +** sqlite3BtreeSync() routine does the first phase and should be invoked
24.2085 +** prior to calling this routine. The sqlite3BtreeSync() routine did
24.2086 +** all the work of writing information out to disk and flushing the
24.2087 +** contents so that they are written onto the disk platter. All this
24.2088 +** routine has to do is delete or truncate the rollback journal
24.2089 +** (which causes the transaction to commit) and drop locks.
24.2090 +**
24.2091 +** This will release the write lock on the database file. If there
24.2092 +** are no active cursors, it also releases the read lock.
24.2093 +*/
24.2094 +int sqlite3BtreeCommitPhaseTwo(Btree *p){
24.2095 + BtShared *pBt = p->pBt;
24.2096 +
24.2097 + btreeIntegrity(p);
24.2098 +
24.2099 + /* If the handle has a write-transaction open, commit the shared-btrees
24.2100 + ** transaction and set the shared state to TRANS_READ.
24.2101 + */
24.2102 + if( p->inTrans==TRANS_WRITE ){
24.2103 + int rc;
24.2104 + assert( pBt->inTransaction==TRANS_WRITE );
24.2105 + assert( pBt->nTransaction>0 );
24.2106 + rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
24.2107 + if( rc!=SQLITE_OK ){
24.2108 + return rc;
24.2109 + }
24.2110 + pBt->inTransaction = TRANS_READ;
24.2111 + pBt->inStmt = 0;
24.2112 + }
24.2113 + unlockAllTables(p);
24.2114 +
24.2115 + /* If the handle has any kind of transaction open, decrement the transaction
24.2116 + ** count of the shared btree. If the transaction count reaches 0, set
24.2117 + ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
24.2118 + ** will unlock the pager.
24.2119 + */
24.2120 + if( p->inTrans!=TRANS_NONE ){
24.2121 + pBt->nTransaction--;
24.2122 + if( 0==pBt->nTransaction ){
24.2123 + pBt->inTransaction = TRANS_NONE;
24.2124 + }
24.2125 + }
24.2126 +
24.2127 + /* Set the handles current transaction state to TRANS_NONE and unlock
24.2128 + ** the pager if this call closed the only read or write transaction.
24.2129 + */
24.2130 + p->inTrans = TRANS_NONE;
24.2131 + unlockBtreeIfUnused(pBt);
24.2132 +
24.2133 + btreeIntegrity(p);
24.2134 + return SQLITE_OK;
24.2135 +}
24.2136 +
24.2137 +/*
24.2138 +** Do both phases of a commit.
24.2139 +*/
24.2140 +int sqlite3BtreeCommit(Btree *p){
24.2141 + int rc;
24.2142 + rc = sqlite3BtreeCommitPhaseOne(p, 0);
24.2143 + if( rc==SQLITE_OK ){
24.2144 + rc = sqlite3BtreeCommitPhaseTwo(p);
24.2145 + }
24.2146 + return rc;
24.2147 +}
24.2148 +
24.2149 +#ifndef NDEBUG
24.2150 +/*
24.2151 +** Return the number of write-cursors open on this handle. This is for use
24.2152 +** in assert() expressions, so it is only compiled if NDEBUG is not
24.2153 +** defined.
24.2154 +*/
24.2155 +static int countWriteCursors(BtShared *pBt){
24.2156 + BtCursor *pCur;
24.2157 + int r = 0;
24.2158 + for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
24.2159 + if( pCur->wrFlag ) r++;
24.2160 + }
24.2161 + return r;
24.2162 +}
24.2163 +#endif
24.2164 +
24.2165 +/*
24.2166 +** Rollback the transaction in progress. All cursors will be
24.2167 +** invalided by this operation. Any attempt to use a cursor
24.2168 +** that was open at the beginning of this operation will result
24.2169 +** in an error.
24.2170 +**
24.2171 +** This will release the write lock on the database file. If there
24.2172 +** are no active cursors, it also releases the read lock.
24.2173 +*/
24.2174 +int sqlite3BtreeRollback(Btree *p){
24.2175 + int rc;
24.2176 + BtShared *pBt = p->pBt;
24.2177 + MemPage *pPage1;
24.2178 +
24.2179 + rc = saveAllCursors(pBt, 0, 0);
24.2180 +#ifndef SQLITE_OMIT_SHARED_CACHE
24.2181 + if( rc!=SQLITE_OK ){
24.2182 + /* This is a horrible situation. An IO or malloc() error occured whilst
24.2183 + ** trying to save cursor positions. If this is an automatic rollback (as
24.2184 + ** the result of a constraint, malloc() failure or IO error) then
24.2185 + ** the cache may be internally inconsistent (not contain valid trees) so
24.2186 + ** we cannot simply return the error to the caller. Instead, abort
24.2187 + ** all queries that may be using any of the cursors that failed to save.
24.2188 + */
24.2189 + while( pBt->pCursor ){
24.2190 + sqlite3 *db = pBt->pCursor->pBtree->pSqlite;
24.2191 + if( db ){
24.2192 + sqlite3AbortOtherActiveVdbes(db, 0);
24.2193 + }
24.2194 + }
24.2195 + }
24.2196 +#endif
24.2197 + btreeIntegrity(p);
24.2198 + unlockAllTables(p);
24.2199 +
24.2200 + if( p->inTrans==TRANS_WRITE ){
24.2201 + int rc2;
24.2202 +
24.2203 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.2204 + pBt->nTrunc = 0;
24.2205 +#endif
24.2206 +
24.2207 + assert( TRANS_WRITE==pBt->inTransaction );
24.2208 + rc2 = sqlite3PagerRollback(pBt->pPager);
24.2209 + if( rc2!=SQLITE_OK ){
24.2210 + rc = rc2;
24.2211 + }
24.2212 +
24.2213 + /* The rollback may have destroyed the pPage1->aData value. So
24.2214 + ** call sqlite3BtreeGetPage() on page 1 again to make
24.2215 + ** sure pPage1->aData is set correctly. */
24.2216 + if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
24.2217 + releasePage(pPage1);
24.2218 + }
24.2219 + assert( countWriteCursors(pBt)==0 );
24.2220 + pBt->inTransaction = TRANS_READ;
24.2221 + }
24.2222 +
24.2223 + if( p->inTrans!=TRANS_NONE ){
24.2224 + assert( pBt->nTransaction>0 );
24.2225 + pBt->nTransaction--;
24.2226 + if( 0==pBt->nTransaction ){
24.2227 + pBt->inTransaction = TRANS_NONE;
24.2228 + }
24.2229 + }
24.2230 +
24.2231 + p->inTrans = TRANS_NONE;
24.2232 + pBt->inStmt = 0;
24.2233 + unlockBtreeIfUnused(pBt);
24.2234 +
24.2235 + btreeIntegrity(p);
24.2236 + return rc;
24.2237 +}
24.2238 +
24.2239 +/*
24.2240 +** Start a statement subtransaction. The subtransaction can
24.2241 +** can be rolled back independently of the main transaction.
24.2242 +** You must start a transaction before starting a subtransaction.
24.2243 +** The subtransaction is ended automatically if the main transaction
24.2244 +** commits or rolls back.
24.2245 +**
24.2246 +** Only one subtransaction may be active at a time. It is an error to try
24.2247 +** to start a new subtransaction if another subtransaction is already active.
24.2248 +**
24.2249 +** Statement subtransactions are used around individual SQL statements
24.2250 +** that are contained within a BEGIN...COMMIT block. If a constraint
24.2251 +** error occurs within the statement, the effect of that one statement
24.2252 +** can be rolled back without having to rollback the entire transaction.
24.2253 +*/
24.2254 +int sqlite3BtreeBeginStmt(Btree *p){
24.2255 + int rc;
24.2256 + BtShared *pBt = p->pBt;
24.2257 + if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
24.2258 + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
24.2259 + }
24.2260 + assert( pBt->inTransaction==TRANS_WRITE );
24.2261 + rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
24.2262 + pBt->inStmt = 1;
24.2263 + return rc;
24.2264 +}
24.2265 +
24.2266 +
24.2267 +/*
24.2268 +** Commit the statment subtransaction currently in progress. If no
24.2269 +** subtransaction is active, this is a no-op.
24.2270 +*/
24.2271 +int sqlite3BtreeCommitStmt(Btree *p){
24.2272 + int rc;
24.2273 + BtShared *pBt = p->pBt;
24.2274 + if( pBt->inStmt && !pBt->readOnly ){
24.2275 + rc = sqlite3PagerStmtCommit(pBt->pPager);
24.2276 + }else{
24.2277 + rc = SQLITE_OK;
24.2278 + }
24.2279 + pBt->inStmt = 0;
24.2280 + return rc;
24.2281 +}
24.2282 +
24.2283 +/*
24.2284 +** Rollback the active statement subtransaction. If no subtransaction
24.2285 +** is active this routine is a no-op.
24.2286 +**
24.2287 +** All cursors will be invalidated by this operation. Any attempt
24.2288 +** to use a cursor that was open at the beginning of this operation
24.2289 +** will result in an error.
24.2290 +*/
24.2291 +int sqlite3BtreeRollbackStmt(Btree *p){
24.2292 + int rc = SQLITE_OK;
24.2293 + BtShared *pBt = p->pBt;
24.2294 + sqlite3MallocDisallow();
24.2295 + if( pBt->inStmt && !pBt->readOnly ){
24.2296 + rc = sqlite3PagerStmtRollback(pBt->pPager);
24.2297 + assert( countWriteCursors(pBt)==0 );
24.2298 + pBt->inStmt = 0;
24.2299 + }
24.2300 + sqlite3MallocAllow();
24.2301 + return rc;
24.2302 +}
24.2303 +
24.2304 +/*
24.2305 +** Default key comparison function to be used if no comparison function
24.2306 +** is specified on the sqlite3BtreeCursor() call.
24.2307 +*/
24.2308 +static int dfltCompare(
24.2309 + void *NotUsed, /* User data is not used */
24.2310 + int n1, const void *p1, /* First key to compare */
24.2311 + int n2, const void *p2 /* Second key to compare */
24.2312 +){
24.2313 + int c;
24.2314 + c = memcmp(p1, p2, n1<n2 ? n1 : n2);
24.2315 + if( c==0 ){
24.2316 + c = n1 - n2;
24.2317 + }
24.2318 + return c;
24.2319 +}
24.2320 +
24.2321 +/*
24.2322 +** Create a new cursor for the BTree whose root is on the page
24.2323 +** iTable. The act of acquiring a cursor gets a read lock on
24.2324 +** the database file.
24.2325 +**
24.2326 +** If wrFlag==0, then the cursor can only be used for reading.
24.2327 +** If wrFlag==1, then the cursor can be used for reading or for
24.2328 +** writing if other conditions for writing are also met. These
24.2329 +** are the conditions that must be met in order for writing to
24.2330 +** be allowed:
24.2331 +**
24.2332 +** 1: The cursor must have been opened with wrFlag==1
24.2333 +**
24.2334 +** 2: Other database connections that share the same pager cache
24.2335 +** but which are not in the READ_UNCOMMITTED state may not have
24.2336 +** cursors open with wrFlag==0 on the same table. Otherwise
24.2337 +** the changes made by this write cursor would be visible to
24.2338 +** the read cursors in the other database connection.
24.2339 +**
24.2340 +** 3: The database must be writable (not on read-only media)
24.2341 +**
24.2342 +** 4: There must be an active transaction.
24.2343 +**
24.2344 +** No checking is done to make sure that page iTable really is the
24.2345 +** root page of a b-tree. If it is not, then the cursor acquired
24.2346 +** will not work correctly.
24.2347 +**
24.2348 +** The comparison function must be logically the same for every cursor
24.2349 +** on a particular table. Changing the comparison function will result
24.2350 +** in incorrect operations. If the comparison function is NULL, a
24.2351 +** default comparison function is used. The comparison function is
24.2352 +** always ignored for INTKEY tables.
24.2353 +*/
24.2354 +int sqlite3BtreeCursor(
24.2355 + Btree *p, /* The btree */
24.2356 + int iTable, /* Root page of table to open */
24.2357 + int wrFlag, /* 1 to write. 0 read-only */
24.2358 + int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
24.2359 + void *pArg, /* First arg to xCompare() */
24.2360 + BtCursor **ppCur /* Write new cursor here */
24.2361 +){
24.2362 + int rc;
24.2363 + BtCursor *pCur;
24.2364 + BtShared *pBt = p->pBt;
24.2365 +
24.2366 + *ppCur = 0;
24.2367 + if( wrFlag ){
24.2368 + if( pBt->readOnly ){
24.2369 + return SQLITE_READONLY;
24.2370 + }
24.2371 + if( checkReadLocks(p, iTable, 0) ){
24.2372 + return SQLITE_LOCKED;
24.2373 + }
24.2374 + }
24.2375 +
24.2376 + if( pBt->pPage1==0 ){
24.2377 + rc = lockBtreeWithRetry(p);
24.2378 + if( rc!=SQLITE_OK ){
24.2379 + return rc;
24.2380 + }
24.2381 + if( pBt->readOnly && wrFlag ){
24.2382 + return SQLITE_READONLY;
24.2383 + }
24.2384 + }
24.2385 + pCur = sqliteMalloc( sizeof(*pCur) );
24.2386 + if( pCur==0 ){
24.2387 + rc = SQLITE_NOMEM;
24.2388 + goto create_cursor_exception;
24.2389 + }
24.2390 + pCur->pgnoRoot = (Pgno)iTable;
24.2391 + if( iTable==1 && sqlite3PagerPagecount(pBt->pPager)==0 ){
24.2392 + rc = SQLITE_EMPTY;
24.2393 + goto create_cursor_exception;
24.2394 + }
24.2395 + rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
24.2396 + if( rc!=SQLITE_OK ){
24.2397 + goto create_cursor_exception;
24.2398 + }
24.2399 +
24.2400 + /* Now that no other errors can occur, finish filling in the BtCursor
24.2401 + ** variables, link the cursor into the BtShared list and set *ppCur (the
24.2402 + ** output argument to this function).
24.2403 + */
24.2404 + pCur->xCompare = xCmp ? xCmp : dfltCompare;
24.2405 + pCur->pArg = pArg;
24.2406 + pCur->pBtree = p;
24.2407 + pCur->wrFlag = wrFlag;
24.2408 + pCur->pNext = pBt->pCursor;
24.2409 + if( pCur->pNext ){
24.2410 + pCur->pNext->pPrev = pCur;
24.2411 + }
24.2412 + pBt->pCursor = pCur;
24.2413 + pCur->eState = CURSOR_INVALID;
24.2414 + *ppCur = pCur;
24.2415 +
24.2416 + return SQLITE_OK;
24.2417 +create_cursor_exception:
24.2418 + if( pCur ){
24.2419 + releasePage(pCur->pPage);
24.2420 + sqliteFree(pCur);
24.2421 + }
24.2422 + unlockBtreeIfUnused(pBt);
24.2423 + return rc;
24.2424 +}
24.2425 +
24.2426 +/*
24.2427 +** Close a cursor. The read lock on the database file is released
24.2428 +** when the last cursor is closed.
24.2429 +*/
24.2430 +int sqlite3BtreeCloseCursor(BtCursor *pCur){
24.2431 + BtShared *pBt = pCur->pBtree->pBt;
24.2432 + clearCursorPosition(pCur);
24.2433 + if( pCur->pPrev ){
24.2434 + pCur->pPrev->pNext = pCur->pNext;
24.2435 + }else{
24.2436 + pBt->pCursor = pCur->pNext;
24.2437 + }
24.2438 + if( pCur->pNext ){
24.2439 + pCur->pNext->pPrev = pCur->pPrev;
24.2440 + }
24.2441 + releasePage(pCur->pPage);
24.2442 + unlockBtreeIfUnused(pBt);
24.2443 + invalidateOverflowCache(pCur);
24.2444 + sqliteFree(pCur);
24.2445 + return SQLITE_OK;
24.2446 +}
24.2447 +
24.2448 +/*
24.2449 +** Make a temporary cursor by filling in the fields of pTempCur.
24.2450 +** The temporary cursor is not on the cursor list for the Btree.
24.2451 +*/
24.2452 +void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
24.2453 + memcpy(pTempCur, pCur, sizeof(*pCur));
24.2454 + pTempCur->pNext = 0;
24.2455 + pTempCur->pPrev = 0;
24.2456 + if( pTempCur->pPage ){
24.2457 + sqlite3PagerRef(pTempCur->pPage->pDbPage);
24.2458 + }
24.2459 +}
24.2460 +
24.2461 +/*
24.2462 +** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
24.2463 +** function above.
24.2464 +*/
24.2465 +void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
24.2466 + if( pCur->pPage ){
24.2467 + sqlite3PagerUnref(pCur->pPage->pDbPage);
24.2468 + }
24.2469 +}
24.2470 +
24.2471 +/*
24.2472 +** Make sure the BtCursor* given in the argument has a valid
24.2473 +** BtCursor.info structure. If it is not already valid, call
24.2474 +** sqlite3BtreeParseCell() to fill it in.
24.2475 +**
24.2476 +** BtCursor.info is a cache of the information in the current cell.
24.2477 +** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
24.2478 +**
24.2479 +** 2007-06-25: There is a bug in some versions of MSVC that cause the
24.2480 +** compiler to crash when getCellInfo() is implemented as a macro.
24.2481 +** But there is a measureable speed advantage to using the macro on gcc
24.2482 +** (when less compiler optimizations like -Os or -O0 are used and the
24.2483 +** compiler is not doing agressive inlining.) So we use a real function
24.2484 +** for MSVC and a macro for everything else. Ticket #2457.
24.2485 +*/
24.2486 +#ifndef NDEBUG
24.2487 + static void assertCellInfo(BtCursor *pCur){
24.2488 + CellInfo info;
24.2489 + memset(&info, 0, sizeof(info));
24.2490 + sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &info);
24.2491 + assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
24.2492 + }
24.2493 +#else
24.2494 + #define assertCellInfo(x)
24.2495 +#endif
24.2496 +#ifdef _MSC_VER
24.2497 + /* Use a real function in MSVC to work around bugs in that compiler. */
24.2498 + static void getCellInfo(BtCursor *pCur){
24.2499 + if( pCur->info.nSize==0 ){
24.2500 + sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);
24.2501 + }else{
24.2502 + assertCellInfo(pCur);
24.2503 + }
24.2504 + }
24.2505 +#else /* if not _MSC_VER */
24.2506 + /* Use a macro in all other compilers so that the function is inlined */
24.2507 +#define getCellInfo(pCur) \
24.2508 + if( pCur->info.nSize==0 ){ \
24.2509 + sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info); \
24.2510 + }else{ \
24.2511 + assertCellInfo(pCur); \
24.2512 + }
24.2513 +#endif /* _MSC_VER */
24.2514 +
24.2515 +/*
24.2516 +** Set *pSize to the size of the buffer needed to hold the value of
24.2517 +** the key for the current entry. If the cursor is not pointing
24.2518 +** to a valid entry, *pSize is set to 0.
24.2519 +**
24.2520 +** For a table with the INTKEY flag set, this routine returns the key
24.2521 +** itself, not the number of bytes in the key.
24.2522 +*/
24.2523 +int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
24.2524 + int rc = restoreOrClearCursorPosition(pCur);
24.2525 + if( rc==SQLITE_OK ){
24.2526 + assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
24.2527 + if( pCur->eState==CURSOR_INVALID ){
24.2528 + *pSize = 0;
24.2529 + }else{
24.2530 + getCellInfo(pCur);
24.2531 + *pSize = pCur->info.nKey;
24.2532 + }
24.2533 + }
24.2534 + return rc;
24.2535 +}
24.2536 +
24.2537 +/*
24.2538 +** Set *pSize to the number of bytes of data in the entry the
24.2539 +** cursor currently points to. Always return SQLITE_OK.
24.2540 +** Failure is not possible. If the cursor is not currently
24.2541 +** pointing to an entry (which can happen, for example, if
24.2542 +** the database is empty) then *pSize is set to 0.
24.2543 +*/
24.2544 +int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
24.2545 + int rc = restoreOrClearCursorPosition(pCur);
24.2546 + if( rc==SQLITE_OK ){
24.2547 + assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
24.2548 + if( pCur->eState==CURSOR_INVALID ){
24.2549 + /* Not pointing at a valid entry - set *pSize to 0. */
24.2550 + *pSize = 0;
24.2551 + }else{
24.2552 + getCellInfo(pCur);
24.2553 + *pSize = pCur->info.nData;
24.2554 + }
24.2555 + }
24.2556 + return rc;
24.2557 +}
24.2558 +
24.2559 +/*
24.2560 +** Given the page number of an overflow page in the database (parameter
24.2561 +** ovfl), this function finds the page number of the next page in the
24.2562 +** linked list of overflow pages. If possible, it uses the auto-vacuum
24.2563 +** pointer-map data instead of reading the content of page ovfl to do so.
24.2564 +**
24.2565 +** If an error occurs an SQLite error code is returned. Otherwise:
24.2566 +**
24.2567 +** Unless pPgnoNext is NULL, the page number of the next overflow
24.2568 +** page in the linked list is written to *pPgnoNext. If page ovfl
24.2569 +** is the last page in it's linked list, *pPgnoNext is set to zero.
24.2570 +**
24.2571 +** If ppPage is not NULL, *ppPage is set to the MemPage* handle
24.2572 +** for page ovfl. The underlying pager page may have been requested
24.2573 +** with the noContent flag set, so the page data accessable via
24.2574 +** this handle may not be trusted.
24.2575 +*/
24.2576 +static int getOverflowPage(
24.2577 + BtShared *pBt,
24.2578 + Pgno ovfl, /* Overflow page */
24.2579 + MemPage **ppPage, /* OUT: MemPage handle */
24.2580 + Pgno *pPgnoNext /* OUT: Next overflow page number */
24.2581 +){
24.2582 + Pgno next = 0;
24.2583 + int rc;
24.2584 +
24.2585 + /* One of these must not be NULL. Otherwise, why call this function? */
24.2586 + assert(ppPage || pPgnoNext);
24.2587 +
24.2588 + /* If pPgnoNext is NULL, then this function is being called to obtain
24.2589 + ** a MemPage* reference only. No page-data is required in this case.
24.2590 + */
24.2591 + if( !pPgnoNext ){
24.2592 + return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
24.2593 + }
24.2594 +
24.2595 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.2596 + /* Try to find the next page in the overflow list using the
24.2597 + ** autovacuum pointer-map pages. Guess that the next page in
24.2598 + ** the overflow list is page number (ovfl+1). If that guess turns
24.2599 + ** out to be wrong, fall back to loading the data of page
24.2600 + ** number ovfl to determine the next page number.
24.2601 + */
24.2602 + if( pBt->autoVacuum ){
24.2603 + Pgno pgno;
24.2604 + Pgno iGuess = ovfl+1;
24.2605 + u8 eType;
24.2606 +
24.2607 + while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
24.2608 + iGuess++;
24.2609 + }
24.2610 +
24.2611 + if( iGuess<=sqlite3PagerPagecount(pBt->pPager) ){
24.2612 + rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
24.2613 + if( rc!=SQLITE_OK ){
24.2614 + return rc;
24.2615 + }
24.2616 + if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
24.2617 + next = iGuess;
24.2618 + }
24.2619 + }
24.2620 + }
24.2621 +#endif
24.2622 +
24.2623 + if( next==0 || ppPage ){
24.2624 + MemPage *pPage = 0;
24.2625 +
24.2626 + rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
24.2627 + assert(rc==SQLITE_OK || pPage==0);
24.2628 + if( next==0 && rc==SQLITE_OK ){
24.2629 + next = get4byte(pPage->aData);
24.2630 + }
24.2631 +
24.2632 + if( ppPage ){
24.2633 + *ppPage = pPage;
24.2634 + }else{
24.2635 + releasePage(pPage);
24.2636 + }
24.2637 + }
24.2638 + *pPgnoNext = next;
24.2639 +
24.2640 + return rc;
24.2641 +}
24.2642 +
24.2643 +/*
24.2644 +** Copy data from a buffer to a page, or from a page to a buffer.
24.2645 +**
24.2646 +** pPayload is a pointer to data stored on database page pDbPage.
24.2647 +** If argument eOp is false, then nByte bytes of data are copied
24.2648 +** from pPayload to the buffer pointed at by pBuf. If eOp is true,
24.2649 +** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
24.2650 +** of data are copied from the buffer pBuf to pPayload.
24.2651 +**
24.2652 +** SQLITE_OK is returned on success, otherwise an error code.
24.2653 +*/
24.2654 +static int copyPayload(
24.2655 + void *pPayload, /* Pointer to page data */
24.2656 + void *pBuf, /* Pointer to buffer */
24.2657 + int nByte, /* Number of bytes to copy */
24.2658 + int eOp, /* 0 -> copy from page, 1 -> copy to page */
24.2659 + DbPage *pDbPage /* Page containing pPayload */
24.2660 +){
24.2661 + if( eOp ){
24.2662 + /* Copy data from buffer to page (a write operation) */
24.2663 + int rc = sqlite3PagerWrite(pDbPage);
24.2664 + if( rc!=SQLITE_OK ){
24.2665 + return rc;
24.2666 + }
24.2667 + memcpy(pPayload, pBuf, nByte);
24.2668 + }else{
24.2669 + /* Copy data from page to buffer (a read operation) */
24.2670 + memcpy(pBuf, pPayload, nByte);
24.2671 + }
24.2672 + return SQLITE_OK;
24.2673 +}
24.2674 +
24.2675 +/*
24.2676 +** This function is used to read or overwrite payload information
24.2677 +** for the entry that the pCur cursor is pointing to. If the eOp
24.2678 +** parameter is 0, this is a read operation (data copied into
24.2679 +** buffer pBuf). If it is non-zero, a write (data copied from
24.2680 +** buffer pBuf).
24.2681 +**
24.2682 +** A total of "amt" bytes are read or written beginning at "offset".
24.2683 +** Data is read to or from the buffer pBuf.
24.2684 +**
24.2685 +** This routine does not make a distinction between key and data.
24.2686 +** It just reads or writes bytes from the payload area. Data might
24.2687 +** appear on the main page or be scattered out on multiple overflow
24.2688 +** pages.
24.2689 +**
24.2690 +** If the BtCursor.isIncrblobHandle flag is set, and the current
24.2691 +** cursor entry uses one or more overflow pages, this function
24.2692 +** allocates space for and lazily popluates the overflow page-list
24.2693 +** cache array (BtCursor.aOverflow). Subsequent calls use this
24.2694 +** cache to make seeking to the supplied offset more efficient.
24.2695 +**
24.2696 +** Once an overflow page-list cache has been allocated, it may be
24.2697 +** invalidated if some other cursor writes to the same table, or if
24.2698 +** the cursor is moved to a different row. Additionally, in auto-vacuum
24.2699 +** mode, the following events may invalidate an overflow page-list cache.
24.2700 +**
24.2701 +** * An incremental vacuum,
24.2702 +** * A commit in auto_vacuum="full" mode,
24.2703 +** * Creating a table (may require moving an overflow page).
24.2704 +*/
24.2705 +static int accessPayload(
24.2706 + BtCursor *pCur, /* Cursor pointing to entry to read from */
24.2707 + int offset, /* Begin reading this far into payload */
24.2708 + int amt, /* Read this many bytes */
24.2709 + unsigned char *pBuf, /* Write the bytes into this buffer */
24.2710 + int skipKey, /* offset begins at data if this is true */
24.2711 + int eOp /* zero to read. non-zero to write. */
24.2712 +){
24.2713 + unsigned char *aPayload;
24.2714 + int rc = SQLITE_OK;
24.2715 + u32 nKey;
24.2716 + int iIdx = 0;
24.2717 + MemPage *pPage = pCur->pPage; /* Btree page of current cursor entry */
24.2718 + BtShared *pBt = pCur->pBtree->pBt; /* Btree this cursor belongs to */
24.2719 +
24.2720 + assert( pPage );
24.2721 + assert( pCur->eState==CURSOR_VALID );
24.2722 + assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
24.2723 + assert( offset>=0 );
24.2724 +
24.2725 + getCellInfo(pCur);
24.2726 + aPayload = pCur->info.pCell + pCur->info.nHeader;
24.2727 + nKey = (pPage->intKey ? 0 : pCur->info.nKey);
24.2728 +
24.2729 + if( skipKey ){
24.2730 + offset += nKey;
24.2731 + }
24.2732 + if( offset+amt > nKey+pCur->info.nData ){
24.2733 + /* Trying to read or write past the end of the data is an error */
24.2734 + return SQLITE_ERROR;
24.2735 + }
24.2736 +
24.2737 + /* Check if data must be read/written to/from the btree page itself. */
24.2738 + if( offset<pCur->info.nLocal ){
24.2739 + int a = amt;
24.2740 + if( a+offset>pCur->info.nLocal ){
24.2741 + a = pCur->info.nLocal - offset;
24.2742 + }
24.2743 + rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
24.2744 + offset = 0;
24.2745 + pBuf += a;
24.2746 + amt -= a;
24.2747 + }else{
24.2748 + offset -= pCur->info.nLocal;
24.2749 + }
24.2750 +
24.2751 + if( rc==SQLITE_OK && amt>0 ){
24.2752 + const int ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
24.2753 + Pgno nextPage;
24.2754 +
24.2755 + nextPage = get4byte(&aPayload[pCur->info.nLocal]);
24.2756 +
24.2757 +#ifndef SQLITE_OMIT_INCRBLOB
24.2758 + /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
24.2759 + ** has not been allocated, allocate it now. The array is sized at
24.2760 + ** one entry for each overflow page in the overflow chain. The
24.2761 + ** page number of the first overflow page is stored in aOverflow[0],
24.2762 + ** etc. A value of 0 in the aOverflow[] array means "not yet known"
24.2763 + ** (the cache is lazily populated).
24.2764 + */
24.2765 + if( pCur->isIncrblobHandle && !pCur->aOverflow ){
24.2766 + int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
24.2767 + pCur->aOverflow = (Pgno *)sqliteMalloc(sizeof(Pgno)*nOvfl);
24.2768 + if( nOvfl && !pCur->aOverflow ){
24.2769 + rc = SQLITE_NOMEM;
24.2770 + }
24.2771 + }
24.2772 +
24.2773 + /* If the overflow page-list cache has been allocated and the
24.2774 + ** entry for the first required overflow page is valid, skip
24.2775 + ** directly to it.
24.2776 + */
24.2777 + if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
24.2778 + iIdx = (offset/ovflSize);
24.2779 + nextPage = pCur->aOverflow[iIdx];
24.2780 + offset = (offset%ovflSize);
24.2781 + }
24.2782 +#endif
24.2783 +
24.2784 + for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
24.2785 +
24.2786 +#ifndef SQLITE_OMIT_INCRBLOB
24.2787 + /* If required, populate the overflow page-list cache. */
24.2788 + if( pCur->aOverflow ){
24.2789 + assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
24.2790 + pCur->aOverflow[iIdx] = nextPage;
24.2791 + }
24.2792 +#endif
24.2793 +
24.2794 + if( offset>=ovflSize ){
24.2795 + /* The only reason to read this page is to obtain the page
24.2796 + ** number for the next page in the overflow chain. The page
24.2797 + ** data is not required. So first try to lookup the overflow
24.2798 + ** page-list cache, if any, then fall back to the getOverflowPage()
24.2799 + ** function.
24.2800 + */
24.2801 +#ifndef SQLITE_OMIT_INCRBLOB
24.2802 + if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
24.2803 + nextPage = pCur->aOverflow[iIdx+1];
24.2804 + } else
24.2805 +#endif
24.2806 + rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
24.2807 + offset -= ovflSize;
24.2808 + }else{
24.2809 + /* Need to read this page properly. It contains some of the
24.2810 + ** range of data that is being read (eOp==0) or written (eOp!=0).
24.2811 + */
24.2812 + DbPage *pDbPage;
24.2813 + int a = amt;
24.2814 + rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
24.2815 + if( rc==SQLITE_OK ){
24.2816 + aPayload = sqlite3PagerGetData(pDbPage);
24.2817 + nextPage = get4byte(aPayload);
24.2818 + if( a + offset > ovflSize ){
24.2819 + a = ovflSize - offset;
24.2820 + }
24.2821 + rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
24.2822 + sqlite3PagerUnref(pDbPage);
24.2823 + offset = 0;
24.2824 + amt -= a;
24.2825 + pBuf += a;
24.2826 + }
24.2827 + }
24.2828 + }
24.2829 + }
24.2830 +
24.2831 + if( rc==SQLITE_OK && amt>0 ){
24.2832 + return SQLITE_CORRUPT_BKPT;
24.2833 + }
24.2834 + return rc;
24.2835 +}
24.2836 +
24.2837 +/*
24.2838 +** Read part of the key associated with cursor pCur. Exactly
24.2839 +** "amt" bytes will be transfered into pBuf[]. The transfer
24.2840 +** begins at "offset".
24.2841 +**
24.2842 +** Return SQLITE_OK on success or an error code if anything goes
24.2843 +** wrong. An error is returned if "offset+amt" is larger than
24.2844 +** the available payload.
24.2845 +*/
24.2846 +int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
24.2847 + int rc = restoreOrClearCursorPosition(pCur);
24.2848 + if( rc==SQLITE_OK ){
24.2849 + assert( pCur->eState==CURSOR_VALID );
24.2850 + assert( pCur->pPage!=0 );
24.2851 + if( pCur->pPage->intKey ){
24.2852 + return SQLITE_CORRUPT_BKPT;
24.2853 + }
24.2854 + assert( pCur->pPage->intKey==0 );
24.2855 + assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
24.2856 + rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
24.2857 + }
24.2858 + return rc;
24.2859 +}
24.2860 +
24.2861 +/*
24.2862 +** Read part of the data associated with cursor pCur. Exactly
24.2863 +** "amt" bytes will be transfered into pBuf[]. The transfer
24.2864 +** begins at "offset".
24.2865 +**
24.2866 +** Return SQLITE_OK on success or an error code if anything goes
24.2867 +** wrong. An error is returned if "offset+amt" is larger than
24.2868 +** the available payload.
24.2869 +*/
24.2870 +int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
24.2871 + int rc = restoreOrClearCursorPosition(pCur);
24.2872 + if( rc==SQLITE_OK ){
24.2873 + assert( pCur->eState==CURSOR_VALID );
24.2874 + assert( pCur->pPage!=0 );
24.2875 + assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
24.2876 + rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
24.2877 + }
24.2878 + return rc;
24.2879 +}
24.2880 +
24.2881 +/*
24.2882 +** Return a pointer to payload information from the entry that the
24.2883 +** pCur cursor is pointing to. The pointer is to the beginning of
24.2884 +** the key if skipKey==0 and it points to the beginning of data if
24.2885 +** skipKey==1. The number of bytes of available key/data is written
24.2886 +** into *pAmt. If *pAmt==0, then the value returned will not be
24.2887 +** a valid pointer.
24.2888 +**
24.2889 +** This routine is an optimization. It is common for the entire key
24.2890 +** and data to fit on the local page and for there to be no overflow
24.2891 +** pages. When that is so, this routine can be used to access the
24.2892 +** key and data without making a copy. If the key and/or data spills
24.2893 +** onto overflow pages, then accessPayload() must be used to reassembly
24.2894 +** the key/data and copy it into a preallocated buffer.
24.2895 +**
24.2896 +** The pointer returned by this routine looks directly into the cached
24.2897 +** page of the database. The data might change or move the next time
24.2898 +** any btree routine is called.
24.2899 +*/
24.2900 +static const unsigned char *fetchPayload(
24.2901 + BtCursor *pCur, /* Cursor pointing to entry to read from */
24.2902 + int *pAmt, /* Write the number of available bytes here */
24.2903 + int skipKey /* read beginning at data if this is true */
24.2904 +){
24.2905 + unsigned char *aPayload;
24.2906 + MemPage *pPage;
24.2907 + u32 nKey;
24.2908 + int nLocal;
24.2909 +
24.2910 + assert( pCur!=0 && pCur->pPage!=0 );
24.2911 + assert( pCur->eState==CURSOR_VALID );
24.2912 + pPage = pCur->pPage;
24.2913 + assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
24.2914 + getCellInfo(pCur);
24.2915 + aPayload = pCur->info.pCell;
24.2916 + aPayload += pCur->info.nHeader;
24.2917 + if( pPage->intKey ){
24.2918 + nKey = 0;
24.2919 + }else{
24.2920 + nKey = pCur->info.nKey;
24.2921 + }
24.2922 + if( skipKey ){
24.2923 + aPayload += nKey;
24.2924 + nLocal = pCur->info.nLocal - nKey;
24.2925 + }else{
24.2926 + nLocal = pCur->info.nLocal;
24.2927 + if( nLocal>nKey ){
24.2928 + nLocal = nKey;
24.2929 + }
24.2930 + }
24.2931 + *pAmt = nLocal;
24.2932 + return aPayload;
24.2933 +}
24.2934 +
24.2935 +
24.2936 +/*
24.2937 +** For the entry that cursor pCur is point to, return as
24.2938 +** many bytes of the key or data as are available on the local
24.2939 +** b-tree page. Write the number of available bytes into *pAmt.
24.2940 +**
24.2941 +** The pointer returned is ephemeral. The key/data may move
24.2942 +** or be destroyed on the next call to any Btree routine.
24.2943 +**
24.2944 +** These routines is used to get quick access to key and data
24.2945 +** in the common case where no overflow pages are used.
24.2946 +*/
24.2947 +const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
24.2948 + if( pCur->eState==CURSOR_VALID ){
24.2949 + return (const void*)fetchPayload(pCur, pAmt, 0);
24.2950 + }
24.2951 + return 0;
24.2952 +}
24.2953 +const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
24.2954 + if( pCur->eState==CURSOR_VALID ){
24.2955 + return (const void*)fetchPayload(pCur, pAmt, 1);
24.2956 + }
24.2957 + return 0;
24.2958 +}
24.2959 +
24.2960 +
24.2961 +/*
24.2962 +** Move the cursor down to a new child page. The newPgno argument is the
24.2963 +** page number of the child page to move to.
24.2964 +*/
24.2965 +static int moveToChild(BtCursor *pCur, u32 newPgno){
24.2966 + int rc;
24.2967 + MemPage *pNewPage;
24.2968 + MemPage *pOldPage;
24.2969 + BtShared *pBt = pCur->pBtree->pBt;
24.2970 +
24.2971 + assert( pCur->eState==CURSOR_VALID );
24.2972 + rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
24.2973 + if( rc ) return rc;
24.2974 + pNewPage->idxParent = pCur->idx;
24.2975 + pOldPage = pCur->pPage;
24.2976 + pOldPage->idxShift = 0;
24.2977 + releasePage(pOldPage);
24.2978 + pCur->pPage = pNewPage;
24.2979 + pCur->idx = 0;
24.2980 + pCur->info.nSize = 0;
24.2981 + if( pNewPage->nCell<1 ){
24.2982 + return SQLITE_CORRUPT_BKPT;
24.2983 + }
24.2984 + return SQLITE_OK;
24.2985 +}
24.2986 +
24.2987 +/*
24.2988 +** Return true if the page is the virtual root of its table.
24.2989 +**
24.2990 +** The virtual root page is the root page for most tables. But
24.2991 +** for the table rooted on page 1, sometime the real root page
24.2992 +** is empty except for the right-pointer. In such cases the
24.2993 +** virtual root page is the page that the right-pointer of page
24.2994 +** 1 is pointing to.
24.2995 +*/
24.2996 +int sqlite3BtreeIsRootPage(MemPage *pPage){
24.2997 + MemPage *pParent = pPage->pParent;
24.2998 + if( pParent==0 ) return 1;
24.2999 + if( pParent->pgno>1 ) return 0;
24.3000 + if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
24.3001 + return 0;
24.3002 +}
24.3003 +
24.3004 +/*
24.3005 +** Move the cursor up to the parent page.
24.3006 +**
24.3007 +** pCur->idx is set to the cell index that contains the pointer
24.3008 +** to the page we are coming from. If we are coming from the
24.3009 +** right-most child page then pCur->idx is set to one more than
24.3010 +** the largest cell index.
24.3011 +*/
24.3012 +void sqlite3BtreeMoveToParent(BtCursor *pCur){
24.3013 + MemPage *pParent;
24.3014 + MemPage *pPage;
24.3015 + int idxParent;
24.3016 +
24.3017 + assert( pCur->eState==CURSOR_VALID );
24.3018 + pPage = pCur->pPage;
24.3019 + assert( pPage!=0 );
24.3020 + assert( !sqlite3BtreeIsRootPage(pPage) );
24.3021 + pParent = pPage->pParent;
24.3022 + assert( pParent!=0 );
24.3023 + idxParent = pPage->idxParent;
24.3024 + sqlite3PagerRef(pParent->pDbPage);
24.3025 + releasePage(pPage);
24.3026 + pCur->pPage = pParent;
24.3027 + pCur->info.nSize = 0;
24.3028 + assert( pParent->idxShift==0 );
24.3029 + pCur->idx = idxParent;
24.3030 +}
24.3031 +
24.3032 +/*
24.3033 +** Move the cursor to the root page
24.3034 +*/
24.3035 +static int moveToRoot(BtCursor *pCur){
24.3036 + MemPage *pRoot;
24.3037 + int rc = SQLITE_OK;
24.3038 + BtShared *pBt = pCur->pBtree->pBt;
24.3039 +
24.3040 + if( pCur->eState==CURSOR_REQUIRESEEK ){
24.3041 + clearCursorPosition(pCur);
24.3042 + }
24.3043 + pRoot = pCur->pPage;
24.3044 + if( pRoot && pRoot->pgno==pCur->pgnoRoot ){
24.3045 + assert( pRoot->isInit );
24.3046 + }else{
24.3047 + if(
24.3048 + SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0))
24.3049 + ){
24.3050 + pCur->eState = CURSOR_INVALID;
24.3051 + return rc;
24.3052 + }
24.3053 + releasePage(pCur->pPage);
24.3054 + pCur->pPage = pRoot;
24.3055 + }
24.3056 + pCur->idx = 0;
24.3057 + pCur->info.nSize = 0;
24.3058 + if( pRoot->nCell==0 && !pRoot->leaf ){
24.3059 + Pgno subpage;
24.3060 + assert( pRoot->pgno==1 );
24.3061 + subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
24.3062 + assert( subpage>0 );
24.3063 + pCur->eState = CURSOR_VALID;
24.3064 + rc = moveToChild(pCur, subpage);
24.3065 + }
24.3066 + pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
24.3067 + return rc;
24.3068 +}
24.3069 +
24.3070 +/*
24.3071 +** Move the cursor down to the left-most leaf entry beneath the
24.3072 +** entry to which it is currently pointing.
24.3073 +**
24.3074 +** The left-most leaf is the one with the smallest key - the first
24.3075 +** in ascending order.
24.3076 +*/
24.3077 +static int moveToLeftmost(BtCursor *pCur){
24.3078 + Pgno pgno;
24.3079 + int rc;
24.3080 + MemPage *pPage;
24.3081 +
24.3082 + assert( pCur->eState==CURSOR_VALID );
24.3083 + while( !(pPage = pCur->pPage)->leaf ){
24.3084 + assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
24.3085 + pgno = get4byte(findCell(pPage, pCur->idx));
24.3086 + rc = moveToChild(pCur, pgno);
24.3087 + if( rc ) return rc;
24.3088 + }
24.3089 + return SQLITE_OK;
24.3090 +}
24.3091 +
24.3092 +/*
24.3093 +** Move the cursor down to the right-most leaf entry beneath the
24.3094 +** page to which it is currently pointing. Notice the difference
24.3095 +** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
24.3096 +** finds the left-most entry beneath the *entry* whereas moveToRightmost()
24.3097 +** finds the right-most entry beneath the *page*.
24.3098 +**
24.3099 +** The right-most entry is the one with the largest key - the last
24.3100 +** key in ascending order.
24.3101 +*/
24.3102 +static int moveToRightmost(BtCursor *pCur){
24.3103 + Pgno pgno;
24.3104 + int rc;
24.3105 + MemPage *pPage;
24.3106 +
24.3107 + assert( pCur->eState==CURSOR_VALID );
24.3108 + while( !(pPage = pCur->pPage)->leaf ){
24.3109 + pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
24.3110 + pCur->idx = pPage->nCell;
24.3111 + rc = moveToChild(pCur, pgno);
24.3112 + if( rc ) return rc;
24.3113 + }
24.3114 + pCur->idx = pPage->nCell - 1;
24.3115 + pCur->info.nSize = 0;
24.3116 + return SQLITE_OK;
24.3117 +}
24.3118 +
24.3119 +/* Move the cursor to the first entry in the table. Return SQLITE_OK
24.3120 +** on success. Set *pRes to 0 if the cursor actually points to something
24.3121 +** or set *pRes to 1 if the table is empty.
24.3122 +*/
24.3123 +int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
24.3124 + int rc;
24.3125 + rc = moveToRoot(pCur);
24.3126 + if( rc ) return rc;
24.3127 + if( pCur->eState==CURSOR_INVALID ){
24.3128 + assert( pCur->pPage->nCell==0 );
24.3129 + *pRes = 1;
24.3130 + return SQLITE_OK;
24.3131 + }
24.3132 + assert( pCur->pPage->nCell>0 );
24.3133 + *pRes = 0;
24.3134 + rc = moveToLeftmost(pCur);
24.3135 + return rc;
24.3136 +}
24.3137 +
24.3138 +/* Move the cursor to the last entry in the table. Return SQLITE_OK
24.3139 +** on success. Set *pRes to 0 if the cursor actually points to something
24.3140 +** or set *pRes to 1 if the table is empty.
24.3141 +*/
24.3142 +int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
24.3143 + int rc;
24.3144 + rc = moveToRoot(pCur);
24.3145 + if( rc ) return rc;
24.3146 + if( CURSOR_INVALID==pCur->eState ){
24.3147 + assert( pCur->pPage->nCell==0 );
24.3148 + *pRes = 1;
24.3149 + return SQLITE_OK;
24.3150 + }
24.3151 + assert( pCur->eState==CURSOR_VALID );
24.3152 + *pRes = 0;
24.3153 + rc = moveToRightmost(pCur);
24.3154 + return rc;
24.3155 +}
24.3156 +
24.3157 +/* Move the cursor so that it points to an entry near pKey/nKey.
24.3158 +** Return a success code.
24.3159 +**
24.3160 +** For INTKEY tables, only the nKey parameter is used. pKey is
24.3161 +** ignored. For other tables, nKey is the number of bytes of data
24.3162 +** in pKey. The comparison function specified when the cursor was
24.3163 +** created is used to compare keys.
24.3164 +**
24.3165 +** If an exact match is not found, then the cursor is always
24.3166 +** left pointing at a leaf page which would hold the entry if it
24.3167 +** were present. The cursor might point to an entry that comes
24.3168 +** before or after the key.
24.3169 +**
24.3170 +** The result of comparing the key with the entry to which the
24.3171 +** cursor is written to *pRes if pRes!=NULL. The meaning of
24.3172 +** this value is as follows:
24.3173 +**
24.3174 +** *pRes<0 The cursor is left pointing at an entry that
24.3175 +** is smaller than pKey or if the table is empty
24.3176 +** and the cursor is therefore left point to nothing.
24.3177 +**
24.3178 +** *pRes==0 The cursor is left pointing at an entry that
24.3179 +** exactly matches pKey.
24.3180 +**
24.3181 +** *pRes>0 The cursor is left pointing at an entry that
24.3182 +** is larger than pKey.
24.3183 +*/
24.3184 +int sqlite3BtreeMoveto(
24.3185 + BtCursor *pCur, /* The cursor to be moved */
24.3186 + const void *pKey, /* The key content for indices. Not used by tables */
24.3187 + i64 nKey, /* Size of pKey. Or the key for tables */
24.3188 + int biasRight, /* If true, bias the search to the high end */
24.3189 + int *pRes /* Search result flag */
24.3190 +){
24.3191 + int rc;
24.3192 + rc = moveToRoot(pCur);
24.3193 + if( rc ) return rc;
24.3194 + assert( pCur->pPage );
24.3195 + assert( pCur->pPage->isInit );
24.3196 + if( pCur->eState==CURSOR_INVALID ){
24.3197 + *pRes = -1;
24.3198 + assert( pCur->pPage->nCell==0 );
24.3199 + return SQLITE_OK;
24.3200 + }
24.3201 + for(;;){
24.3202 + int lwr, upr;
24.3203 + Pgno chldPg;
24.3204 + MemPage *pPage = pCur->pPage;
24.3205 + int c = -1; /* pRes return if table is empty must be -1 */
24.3206 + lwr = 0;
24.3207 + upr = pPage->nCell-1;
24.3208 + if( !pPage->intKey && pKey==0 ){
24.3209 + return SQLITE_CORRUPT_BKPT;
24.3210 + }
24.3211 + if( biasRight ){
24.3212 + pCur->idx = upr;
24.3213 + }else{
24.3214 + pCur->idx = (upr+lwr)/2;
24.3215 + }
24.3216 + if( lwr<=upr ) for(;;){
24.3217 + void *pCellKey;
24.3218 + i64 nCellKey;
24.3219 + pCur->info.nSize = 0;
24.3220 + if( pPage->intKey ){
24.3221 + u8 *pCell;
24.3222 + pCell = findCell(pPage, pCur->idx) + pPage->childPtrSize;
24.3223 + if( pPage->hasData ){
24.3224 + u32 dummy;
24.3225 + pCell += getVarint32(pCell, &dummy);
24.3226 + }
24.3227 + getVarint(pCell, (u64 *)&nCellKey);
24.3228 + if( nCellKey<nKey ){
24.3229 + c = -1;
24.3230 + }else if( nCellKey>nKey ){
24.3231 + c = +1;
24.3232 + }else{
24.3233 + c = 0;
24.3234 + }
24.3235 + }else{
24.3236 + int available;
24.3237 + pCellKey = (void *)fetchPayload(pCur, &available, 0);
24.3238 + nCellKey = pCur->info.nKey;
24.3239 + if( available>=nCellKey ){
24.3240 + c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
24.3241 + }else{
24.3242 + pCellKey = sqliteMallocRaw( nCellKey );
24.3243 + if( pCellKey==0 ) return SQLITE_NOMEM;
24.3244 + rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
24.3245 + c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
24.3246 + sqliteFree(pCellKey);
24.3247 + if( rc ) return rc;
24.3248 + }
24.3249 + }
24.3250 + if( c==0 ){
24.3251 + if( pPage->leafData && !pPage->leaf ){
24.3252 + lwr = pCur->idx;
24.3253 + upr = lwr - 1;
24.3254 + break;
24.3255 + }else{
24.3256 + if( pRes ) *pRes = 0;
24.3257 + return SQLITE_OK;
24.3258 + }
24.3259 + }
24.3260 + if( c<0 ){
24.3261 + lwr = pCur->idx+1;
24.3262 + }else{
24.3263 + upr = pCur->idx-1;
24.3264 + }
24.3265 + if( lwr>upr ){
24.3266 + break;
24.3267 + }
24.3268 + pCur->idx = (lwr+upr)/2;
24.3269 + }
24.3270 + assert( lwr==upr+1 );
24.3271 + assert( pPage->isInit );
24.3272 + if( pPage->leaf ){
24.3273 + chldPg = 0;
24.3274 + }else if( lwr>=pPage->nCell ){
24.3275 + chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
24.3276 + }else{
24.3277 + chldPg = get4byte(findCell(pPage, lwr));
24.3278 + }
24.3279 + if( chldPg==0 ){
24.3280 + assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
24.3281 + if( pRes ) *pRes = c;
24.3282 + return SQLITE_OK;
24.3283 + }
24.3284 + pCur->idx = lwr;
24.3285 + pCur->info.nSize = 0;
24.3286 + rc = moveToChild(pCur, chldPg);
24.3287 + if( rc ){
24.3288 + return rc;
24.3289 + }
24.3290 + }
24.3291 + /* NOT REACHED */
24.3292 +}
24.3293 +
24.3294 +/*
24.3295 +** Return TRUE if the cursor is not pointing at an entry of the table.
24.3296 +**
24.3297 +** TRUE will be returned after a call to sqlite3BtreeNext() moves
24.3298 +** past the last entry in the table or sqlite3BtreePrev() moves past
24.3299 +** the first entry. TRUE is also returned if the table is empty.
24.3300 +*/
24.3301 +int sqlite3BtreeEof(BtCursor *pCur){
24.3302 + /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
24.3303 + ** have been deleted? This API will need to change to return an error code
24.3304 + ** as well as the boolean result value.
24.3305 + */
24.3306 + return (CURSOR_VALID!=pCur->eState);
24.3307 +}
24.3308 +
24.3309 +/*
24.3310 +** Advance the cursor to the next entry in the database. If
24.3311 +** successful then set *pRes=0. If the cursor
24.3312 +** was already pointing to the last entry in the database before
24.3313 +** this routine was called, then set *pRes=1.
24.3314 +*/
24.3315 +int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
24.3316 + int rc;
24.3317 + MemPage *pPage;
24.3318 +
24.3319 + rc = restoreOrClearCursorPosition(pCur);
24.3320 + if( rc!=SQLITE_OK ){
24.3321 + return rc;
24.3322 + }
24.3323 + assert( pRes!=0 );
24.3324 + pPage = pCur->pPage;
24.3325 + if( CURSOR_INVALID==pCur->eState ){
24.3326 + *pRes = 1;
24.3327 + return SQLITE_OK;
24.3328 + }
24.3329 + if( pCur->skip>0 ){
24.3330 + pCur->skip = 0;
24.3331 + *pRes = 0;
24.3332 + return SQLITE_OK;
24.3333 + }
24.3334 + pCur->skip = 0;
24.3335 +
24.3336 + assert( pPage->isInit );
24.3337 + assert( pCur->idx<pPage->nCell );
24.3338 +
24.3339 + pCur->idx++;
24.3340 + pCur->info.nSize = 0;
24.3341 + if( pCur->idx>=pPage->nCell ){
24.3342 + if( !pPage->leaf ){
24.3343 + rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
24.3344 + if( rc ) return rc;
24.3345 + rc = moveToLeftmost(pCur);
24.3346 + *pRes = 0;
24.3347 + return rc;
24.3348 + }
24.3349 + do{
24.3350 + if( sqlite3BtreeIsRootPage(pPage) ){
24.3351 + *pRes = 1;
24.3352 + pCur->eState = CURSOR_INVALID;
24.3353 + return SQLITE_OK;
24.3354 + }
24.3355 + sqlite3BtreeMoveToParent(pCur);
24.3356 + pPage = pCur->pPage;
24.3357 + }while( pCur->idx>=pPage->nCell );
24.3358 + *pRes = 0;
24.3359 + if( pPage->leafData ){
24.3360 + rc = sqlite3BtreeNext(pCur, pRes);
24.3361 + }else{
24.3362 + rc = SQLITE_OK;
24.3363 + }
24.3364 + return rc;
24.3365 + }
24.3366 + *pRes = 0;
24.3367 + if( pPage->leaf ){
24.3368 + return SQLITE_OK;
24.3369 + }
24.3370 + rc = moveToLeftmost(pCur);
24.3371 + return rc;
24.3372 +}
24.3373 +
24.3374 +/*
24.3375 +** Step the cursor to the back to the previous entry in the database. If
24.3376 +** successful then set *pRes=0. If the cursor
24.3377 +** was already pointing to the first entry in the database before
24.3378 +** this routine was called, then set *pRes=1.
24.3379 +*/
24.3380 +int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
24.3381 + int rc;
24.3382 + Pgno pgno;
24.3383 + MemPage *pPage;
24.3384 +
24.3385 + rc = restoreOrClearCursorPosition(pCur);
24.3386 + if( rc!=SQLITE_OK ){
24.3387 + return rc;
24.3388 + }
24.3389 + if( CURSOR_INVALID==pCur->eState ){
24.3390 + *pRes = 1;
24.3391 + return SQLITE_OK;
24.3392 + }
24.3393 + if( pCur->skip<0 ){
24.3394 + pCur->skip = 0;
24.3395 + *pRes = 0;
24.3396 + return SQLITE_OK;
24.3397 + }
24.3398 + pCur->skip = 0;
24.3399 +
24.3400 + pPage = pCur->pPage;
24.3401 + assert( pPage->isInit );
24.3402 + assert( pCur->idx>=0 );
24.3403 + if( !pPage->leaf ){
24.3404 + pgno = get4byte( findCell(pPage, pCur->idx) );
24.3405 + rc = moveToChild(pCur, pgno);
24.3406 + if( rc ) return rc;
24.3407 + rc = moveToRightmost(pCur);
24.3408 + }else{
24.3409 + while( pCur->idx==0 ){
24.3410 + if( sqlite3BtreeIsRootPage(pPage) ){
24.3411 + pCur->eState = CURSOR_INVALID;
24.3412 + *pRes = 1;
24.3413 + return SQLITE_OK;
24.3414 + }
24.3415 + sqlite3BtreeMoveToParent(pCur);
24.3416 + pPage = pCur->pPage;
24.3417 + }
24.3418 + pCur->idx--;
24.3419 + pCur->info.nSize = 0;
24.3420 + if( pPage->leafData && !pPage->leaf ){
24.3421 + rc = sqlite3BtreePrevious(pCur, pRes);
24.3422 + }else{
24.3423 + rc = SQLITE_OK;
24.3424 + }
24.3425 + }
24.3426 + *pRes = 0;
24.3427 + return rc;
24.3428 +}
24.3429 +
24.3430 +/*
24.3431 +** Allocate a new page from the database file.
24.3432 +**
24.3433 +** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
24.3434 +** has already been called on the new page.) The new page has also
24.3435 +** been referenced and the calling routine is responsible for calling
24.3436 +** sqlite3PagerUnref() on the new page when it is done.
24.3437 +**
24.3438 +** SQLITE_OK is returned on success. Any other return value indicates
24.3439 +** an error. *ppPage and *pPgno are undefined in the event of an error.
24.3440 +** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
24.3441 +**
24.3442 +** If the "nearby" parameter is not 0, then a (feeble) effort is made to
24.3443 +** locate a page close to the page number "nearby". This can be used in an
24.3444 +** attempt to keep related pages close to each other in the database file,
24.3445 +** which in turn can make database access faster.
24.3446 +**
24.3447 +** If the "exact" parameter is not 0, and the page-number nearby exists
24.3448 +** anywhere on the free-list, then it is guarenteed to be returned. This
24.3449 +** is only used by auto-vacuum databases when allocating a new table.
24.3450 +*/
24.3451 +static int allocateBtreePage(
24.3452 + BtShared *pBt,
24.3453 + MemPage **ppPage,
24.3454 + Pgno *pPgno,
24.3455 + Pgno nearby,
24.3456 + u8 exact
24.3457 +){
24.3458 + MemPage *pPage1;
24.3459 + int rc;
24.3460 + int n; /* Number of pages on the freelist */
24.3461 + int k; /* Number of leaves on the trunk of the freelist */
24.3462 + MemPage *pTrunk = 0;
24.3463 + MemPage *pPrevTrunk = 0;
24.3464 +
24.3465 + pPage1 = pBt->pPage1;
24.3466 + n = get4byte(&pPage1->aData[36]);
24.3467 + if( n>0 ){
24.3468 + /* There are pages on the freelist. Reuse one of those pages. */
24.3469 + Pgno iTrunk;
24.3470 + u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
24.3471 +
24.3472 + /* If the 'exact' parameter was true and a query of the pointer-map
24.3473 + ** shows that the page 'nearby' is somewhere on the free-list, then
24.3474 + ** the entire-list will be searched for that page.
24.3475 + */
24.3476 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.3477 + if( exact && nearby<=sqlite3PagerPagecount(pBt->pPager) ){
24.3478 + u8 eType;
24.3479 + assert( nearby>0 );
24.3480 + assert( pBt->autoVacuum );
24.3481 + rc = ptrmapGet(pBt, nearby, &eType, 0);
24.3482 + if( rc ) return rc;
24.3483 + if( eType==PTRMAP_FREEPAGE ){
24.3484 + searchList = 1;
24.3485 + }
24.3486 + *pPgno = nearby;
24.3487 + }
24.3488 +#endif
24.3489 +
24.3490 + /* Decrement the free-list count by 1. Set iTrunk to the index of the
24.3491 + ** first free-list trunk page. iPrevTrunk is initially 1.
24.3492 + */
24.3493 + rc = sqlite3PagerWrite(pPage1->pDbPage);
24.3494 + if( rc ) return rc;
24.3495 + put4byte(&pPage1->aData[36], n-1);
24.3496 +
24.3497 + /* The code within this loop is run only once if the 'searchList' variable
24.3498 + ** is not true. Otherwise, it runs once for each trunk-page on the
24.3499 + ** free-list until the page 'nearby' is located.
24.3500 + */
24.3501 + do {
24.3502 + pPrevTrunk = pTrunk;
24.3503 + if( pPrevTrunk ){
24.3504 + iTrunk = get4byte(&pPrevTrunk->aData[0]);
24.3505 + }else{
24.3506 + iTrunk = get4byte(&pPage1->aData[32]);
24.3507 + }
24.3508 + rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
24.3509 + if( rc ){
24.3510 + pTrunk = 0;
24.3511 + goto end_allocate_page;
24.3512 + }
24.3513 +
24.3514 + k = get4byte(&pTrunk->aData[4]);
24.3515 + if( k==0 && !searchList ){
24.3516 + /* The trunk has no leaves and the list is not being searched.
24.3517 + ** So extract the trunk page itself and use it as the newly
24.3518 + ** allocated page */
24.3519 + assert( pPrevTrunk==0 );
24.3520 + rc = sqlite3PagerWrite(pTrunk->pDbPage);
24.3521 + if( rc ){
24.3522 + goto end_allocate_page;
24.3523 + }
24.3524 + *pPgno = iTrunk;
24.3525 + memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
24.3526 + *ppPage = pTrunk;
24.3527 + pTrunk = 0;
24.3528 + TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
24.3529 + }else if( k>pBt->usableSize/4 - 8 ){
24.3530 + /* Value of k is out of range. Database corruption */
24.3531 + rc = SQLITE_CORRUPT_BKPT;
24.3532 + goto end_allocate_page;
24.3533 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.3534 + }else if( searchList && nearby==iTrunk ){
24.3535 + /* The list is being searched and this trunk page is the page
24.3536 + ** to allocate, regardless of whether it has leaves.
24.3537 + */
24.3538 + assert( *pPgno==iTrunk );
24.3539 + *ppPage = pTrunk;
24.3540 + searchList = 0;
24.3541 + rc = sqlite3PagerWrite(pTrunk->pDbPage);
24.3542 + if( rc ){
24.3543 + goto end_allocate_page;
24.3544 + }
24.3545 + if( k==0 ){
24.3546 + if( !pPrevTrunk ){
24.3547 + memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
24.3548 + }else{
24.3549 + memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
24.3550 + }
24.3551 + }else{
24.3552 + /* The trunk page is required by the caller but it contains
24.3553 + ** pointers to free-list leaves. The first leaf becomes a trunk
24.3554 + ** page in this case.
24.3555 + */
24.3556 + MemPage *pNewTrunk;
24.3557 + Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
24.3558 + rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
24.3559 + if( rc!=SQLITE_OK ){
24.3560 + goto end_allocate_page;
24.3561 + }
24.3562 + rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
24.3563 + if( rc!=SQLITE_OK ){
24.3564 + releasePage(pNewTrunk);
24.3565 + goto end_allocate_page;
24.3566 + }
24.3567 + memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
24.3568 + put4byte(&pNewTrunk->aData[4], k-1);
24.3569 + memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
24.3570 + releasePage(pNewTrunk);
24.3571 + if( !pPrevTrunk ){
24.3572 + put4byte(&pPage1->aData[32], iNewTrunk);
24.3573 + }else{
24.3574 + rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
24.3575 + if( rc ){
24.3576 + goto end_allocate_page;
24.3577 + }
24.3578 + put4byte(&pPrevTrunk->aData[0], iNewTrunk);
24.3579 + }
24.3580 + }
24.3581 + pTrunk = 0;
24.3582 + TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
24.3583 +#endif
24.3584 + }else{
24.3585 + /* Extract a leaf from the trunk */
24.3586 + int closest;
24.3587 + Pgno iPage;
24.3588 + unsigned char *aData = pTrunk->aData;
24.3589 + rc = sqlite3PagerWrite(pTrunk->pDbPage);
24.3590 + if( rc ){
24.3591 + goto end_allocate_page;
24.3592 + }
24.3593 + if( nearby>0 ){
24.3594 + int i, dist;
24.3595 + closest = 0;
24.3596 + dist = get4byte(&aData[8]) - nearby;
24.3597 + if( dist<0 ) dist = -dist;
24.3598 + for(i=1; i<k; i++){
24.3599 + int d2 = get4byte(&aData[8+i*4]) - nearby;
24.3600 + if( d2<0 ) d2 = -d2;
24.3601 + if( d2<dist ){
24.3602 + closest = i;
24.3603 + dist = d2;
24.3604 + }
24.3605 + }
24.3606 + }else{
24.3607 + closest = 0;
24.3608 + }
24.3609 +
24.3610 + iPage = get4byte(&aData[8+closest*4]);
24.3611 + if( !searchList || iPage==nearby ){
24.3612 + *pPgno = iPage;
24.3613 + if( *pPgno>sqlite3PagerPagecount(pBt->pPager) ){
24.3614 + /* Free page off the end of the file */
24.3615 + return SQLITE_CORRUPT_BKPT;
24.3616 + }
24.3617 + TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
24.3618 + ": %d more free pages\n",
24.3619 + *pPgno, closest+1, k, pTrunk->pgno, n-1));
24.3620 + if( closest<k-1 ){
24.3621 + memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
24.3622 + }
24.3623 + put4byte(&aData[4], k-1);
24.3624 + rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
24.3625 + if( rc==SQLITE_OK ){
24.3626 + sqlite3PagerDontRollback((*ppPage)->pDbPage);
24.3627 + rc = sqlite3PagerWrite((*ppPage)->pDbPage);
24.3628 + if( rc!=SQLITE_OK ){
24.3629 + releasePage(*ppPage);
24.3630 + }
24.3631 + }
24.3632 + searchList = 0;
24.3633 + }
24.3634 + }
24.3635 + releasePage(pPrevTrunk);
24.3636 + pPrevTrunk = 0;
24.3637 + }while( searchList );
24.3638 + }else{
24.3639 + /* There are no pages on the freelist, so create a new page at the
24.3640 + ** end of the file */
24.3641 + *pPgno = sqlite3PagerPagecount(pBt->pPager) + 1;
24.3642 +
24.3643 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.3644 + if( pBt->nTrunc ){
24.3645 + /* An incr-vacuum has already run within this transaction. So the
24.3646 + ** page to allocate is not from the physical end of the file, but
24.3647 + ** at pBt->nTrunc.
24.3648 + */
24.3649 + *pPgno = pBt->nTrunc+1;
24.3650 + if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
24.3651 + (*pPgno)++;
24.3652 + }
24.3653 + }
24.3654 + if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
24.3655 + /* If *pPgno refers to a pointer-map page, allocate two new pages
24.3656 + ** at the end of the file instead of one. The first allocated page
24.3657 + ** becomes a new pointer-map page, the second is used by the caller.
24.3658 + */
24.3659 + TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
24.3660 + assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
24.3661 + (*pPgno)++;
24.3662 + }
24.3663 + if( pBt->nTrunc ){
24.3664 + pBt->nTrunc = *pPgno;
24.3665 + }
24.3666 +#endif
24.3667 +
24.3668 + assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
24.3669 + rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
24.3670 + if( rc ) return rc;
24.3671 + rc = sqlite3PagerWrite((*ppPage)->pDbPage);
24.3672 + if( rc!=SQLITE_OK ){
24.3673 + releasePage(*ppPage);
24.3674 + }
24.3675 + TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
24.3676 + }
24.3677 +
24.3678 + assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
24.3679 +
24.3680 +end_allocate_page:
24.3681 + releasePage(pTrunk);
24.3682 + releasePage(pPrevTrunk);
24.3683 + return rc;
24.3684 +}
24.3685 +
24.3686 +/*
24.3687 +** Add a page of the database file to the freelist.
24.3688 +**
24.3689 +** sqlite3PagerUnref() is NOT called for pPage.
24.3690 +*/
24.3691 +static int freePage(MemPage *pPage){
24.3692 + BtShared *pBt = pPage->pBt;
24.3693 + MemPage *pPage1 = pBt->pPage1;
24.3694 + int rc, n, k;
24.3695 +
24.3696 + /* Prepare the page for freeing */
24.3697 + assert( pPage->pgno>1 );
24.3698 + pPage->isInit = 0;
24.3699 + releasePage(pPage->pParent);
24.3700 + pPage->pParent = 0;
24.3701 +
24.3702 + /* Increment the free page count on pPage1 */
24.3703 + rc = sqlite3PagerWrite(pPage1->pDbPage);
24.3704 + if( rc ) return rc;
24.3705 + n = get4byte(&pPage1->aData[36]);
24.3706 + put4byte(&pPage1->aData[36], n+1);
24.3707 +
24.3708 +#ifdef SQLITE_SECURE_DELETE
24.3709 + /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
24.3710 + ** always fully overwrite deleted information with zeros.
24.3711 + */
24.3712 + rc = sqlite3PagerWrite(pPage->pDbPage);
24.3713 + if( rc ) return rc;
24.3714 + memset(pPage->aData, 0, pPage->pBt->pageSize);
24.3715 +#endif
24.3716 +
24.3717 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.3718 + /* If the database supports auto-vacuum, write an entry in the pointer-map
24.3719 + ** to indicate that the page is free.
24.3720 + */
24.3721 + if( pBt->autoVacuum ){
24.3722 + rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
24.3723 + if( rc ) return rc;
24.3724 + }
24.3725 +#endif
24.3726 +
24.3727 + if( n==0 ){
24.3728 + /* This is the first free page */
24.3729 + rc = sqlite3PagerWrite(pPage->pDbPage);
24.3730 + if( rc ) return rc;
24.3731 + memset(pPage->aData, 0, 8);
24.3732 + put4byte(&pPage1->aData[32], pPage->pgno);
24.3733 + TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
24.3734 + }else{
24.3735 + /* Other free pages already exist. Retrive the first trunk page
24.3736 + ** of the freelist and find out how many leaves it has. */
24.3737 + MemPage *pTrunk;
24.3738 + rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
24.3739 + if( rc ) return rc;
24.3740 + k = get4byte(&pTrunk->aData[4]);
24.3741 + if( k>=pBt->usableSize/4 - 8 ){
24.3742 + /* The trunk is full. Turn the page being freed into a new
24.3743 + ** trunk page with no leaves. */
24.3744 + rc = sqlite3PagerWrite(pPage->pDbPage);
24.3745 + if( rc ) return rc;
24.3746 + put4byte(pPage->aData, pTrunk->pgno);
24.3747 + put4byte(&pPage->aData[4], 0);
24.3748 + put4byte(&pPage1->aData[32], pPage->pgno);
24.3749 + TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
24.3750 + pPage->pgno, pTrunk->pgno));
24.3751 + }else{
24.3752 + /* Add the newly freed page as a leaf on the current trunk */
24.3753 + rc = sqlite3PagerWrite(pTrunk->pDbPage);
24.3754 + if( rc==SQLITE_OK ){
24.3755 + put4byte(&pTrunk->aData[4], k+1);
24.3756 + put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
24.3757 +#ifndef SQLITE_SECURE_DELETE
24.3758 + sqlite3PagerDontWrite(pPage->pDbPage);
24.3759 +#endif
24.3760 + }
24.3761 + TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
24.3762 + }
24.3763 + releasePage(pTrunk);
24.3764 + }
24.3765 + return rc;
24.3766 +}
24.3767 +
24.3768 +/*
24.3769 +** Free any overflow pages associated with the given Cell.
24.3770 +*/
24.3771 +static int clearCell(MemPage *pPage, unsigned char *pCell){
24.3772 + BtShared *pBt = pPage->pBt;
24.3773 + CellInfo info;
24.3774 + Pgno ovflPgno;
24.3775 + int rc;
24.3776 + int nOvfl;
24.3777 + int ovflPageSize;
24.3778 +
24.3779 + sqlite3BtreeParseCellPtr(pPage, pCell, &info);
24.3780 + if( info.iOverflow==0 ){
24.3781 + return SQLITE_OK; /* No overflow pages. Return without doing anything */
24.3782 + }
24.3783 + ovflPgno = get4byte(&pCell[info.iOverflow]);
24.3784 + ovflPageSize = pBt->usableSize - 4;
24.3785 + nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
24.3786 + assert( ovflPgno==0 || nOvfl>0 );
24.3787 + while( nOvfl-- ){
24.3788 + MemPage *pOvfl;
24.3789 + if( ovflPgno==0 || ovflPgno>sqlite3PagerPagecount(pBt->pPager) ){
24.3790 + return SQLITE_CORRUPT_BKPT;
24.3791 + }
24.3792 +
24.3793 + rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
24.3794 + if( rc ) return rc;
24.3795 + rc = freePage(pOvfl);
24.3796 + sqlite3PagerUnref(pOvfl->pDbPage);
24.3797 + if( rc ) return rc;
24.3798 + }
24.3799 + return SQLITE_OK;
24.3800 +}
24.3801 +
24.3802 +/*
24.3803 +** Create the byte sequence used to represent a cell on page pPage
24.3804 +** and write that byte sequence into pCell[]. Overflow pages are
24.3805 +** allocated and filled in as necessary. The calling procedure
24.3806 +** is responsible for making sure sufficient space has been allocated
24.3807 +** for pCell[].
24.3808 +**
24.3809 +** Note that pCell does not necessary need to point to the pPage->aData
24.3810 +** area. pCell might point to some temporary storage. The cell will
24.3811 +** be constructed in this temporary area then copied into pPage->aData
24.3812 +** later.
24.3813 +*/
24.3814 +static int fillInCell(
24.3815 + MemPage *pPage, /* The page that contains the cell */
24.3816 + unsigned char *pCell, /* Complete text of the cell */
24.3817 + const void *pKey, i64 nKey, /* The key */
24.3818 + const void *pData,int nData, /* The data */
24.3819 + int nZero, /* Extra zero bytes to append to pData */
24.3820 + int *pnSize /* Write cell size here */
24.3821 +){
24.3822 + int nPayload;
24.3823 + const u8 *pSrc;
24.3824 + int nSrc, n, rc;
24.3825 + int spaceLeft;
24.3826 + MemPage *pOvfl = 0;
24.3827 + MemPage *pToRelease = 0;
24.3828 + unsigned char *pPrior;
24.3829 + unsigned char *pPayload;
24.3830 + BtShared *pBt = pPage->pBt;
24.3831 + Pgno pgnoOvfl = 0;
24.3832 + int nHeader;
24.3833 + CellInfo info;
24.3834 +
24.3835 + /* Fill in the header. */
24.3836 + nHeader = 0;
24.3837 + if( !pPage->leaf ){
24.3838 + nHeader += 4;
24.3839 + }
24.3840 + if( pPage->hasData ){
24.3841 + nHeader += putVarint(&pCell[nHeader], nData+nZero);
24.3842 + }else{
24.3843 + nData = nZero = 0;
24.3844 + }
24.3845 + nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
24.3846 + sqlite3BtreeParseCellPtr(pPage, pCell, &info);
24.3847 + assert( info.nHeader==nHeader );
24.3848 + assert( info.nKey==nKey );
24.3849 + assert( info.nData==nData+nZero );
24.3850 +
24.3851 + /* Fill in the payload */
24.3852 + nPayload = nData + nZero;
24.3853 + if( pPage->intKey ){
24.3854 + pSrc = pData;
24.3855 + nSrc = nData;
24.3856 + nData = 0;
24.3857 + }else{
24.3858 + nPayload += nKey;
24.3859 + pSrc = pKey;
24.3860 + nSrc = nKey;
24.3861 + }
24.3862 + *pnSize = info.nSize;
24.3863 + spaceLeft = info.nLocal;
24.3864 + pPayload = &pCell[nHeader];
24.3865 + pPrior = &pCell[info.iOverflow];
24.3866 +
24.3867 + while( nPayload>0 ){
24.3868 + if( spaceLeft==0 ){
24.3869 + int isExact = 0;
24.3870 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.3871 + Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
24.3872 + if( pBt->autoVacuum ){
24.3873 + do{
24.3874 + pgnoOvfl++;
24.3875 + } while(
24.3876 + PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
24.3877 + );
24.3878 + if( pgnoOvfl>1 ){
24.3879 + /* isExact = 1; */
24.3880 + }
24.3881 + }
24.3882 +#endif
24.3883 + rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact);
24.3884 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.3885 + /* If the database supports auto-vacuum, and the second or subsequent
24.3886 + ** overflow page is being allocated, add an entry to the pointer-map
24.3887 + ** for that page now.
24.3888 + **
24.3889 + ** If this is the first overflow page, then write a partial entry
24.3890 + ** to the pointer-map. If we write nothing to this pointer-map slot,
24.3891 + ** then the optimistic overflow chain processing in clearCell()
24.3892 + ** may misinterpret the uninitialised values and delete the
24.3893 + ** wrong pages from the database.
24.3894 + */
24.3895 + if( pBt->autoVacuum && rc==SQLITE_OK ){
24.3896 + u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
24.3897 + rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
24.3898 + if( rc ){
24.3899 + releasePage(pOvfl);
24.3900 + }
24.3901 + }
24.3902 +#endif
24.3903 + if( rc ){
24.3904 + releasePage(pToRelease);
24.3905 + return rc;
24.3906 + }
24.3907 + put4byte(pPrior, pgnoOvfl);
24.3908 + releasePage(pToRelease);
24.3909 + pToRelease = pOvfl;
24.3910 + pPrior = pOvfl->aData;
24.3911 + put4byte(pPrior, 0);
24.3912 + pPayload = &pOvfl->aData[4];
24.3913 + spaceLeft = pBt->usableSize - 4;
24.3914 + }
24.3915 + n = nPayload;
24.3916 + if( n>spaceLeft ) n = spaceLeft;
24.3917 + if( nSrc>0 ){
24.3918 + if( n>nSrc ) n = nSrc;
24.3919 + assert( pSrc );
24.3920 + memcpy(pPayload, pSrc, n);
24.3921 + }else{
24.3922 + memset(pPayload, 0, n);
24.3923 + }
24.3924 + nPayload -= n;
24.3925 + pPayload += n;
24.3926 + pSrc += n;
24.3927 + nSrc -= n;
24.3928 + spaceLeft -= n;
24.3929 + if( nSrc==0 ){
24.3930 + nSrc = nData;
24.3931 + pSrc = pData;
24.3932 + }
24.3933 + }
24.3934 + releasePage(pToRelease);
24.3935 + return SQLITE_OK;
24.3936 +}
24.3937 +
24.3938 +/*
24.3939 +** Change the MemPage.pParent pointer on the page whose number is
24.3940 +** given in the second argument so that MemPage.pParent holds the
24.3941 +** pointer in the third argument.
24.3942 +*/
24.3943 +static int reparentPage(BtShared *pBt, Pgno pgno, MemPage *pNewParent, int idx){
24.3944 + MemPage *pThis;
24.3945 + DbPage *pDbPage;
24.3946 +
24.3947 + assert( pNewParent!=0 );
24.3948 + if( pgno==0 ) return SQLITE_OK;
24.3949 + assert( pBt->pPager!=0 );
24.3950 + pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
24.3951 + if( pDbPage ){
24.3952 + pThis = (MemPage *)sqlite3PagerGetExtra(pDbPage);
24.3953 + if( pThis->isInit ){
24.3954 + assert( pThis->aData==(sqlite3PagerGetData(pDbPage)) );
24.3955 + if( pThis->pParent!=pNewParent ){
24.3956 + if( pThis->pParent ) sqlite3PagerUnref(pThis->pParent->pDbPage);
24.3957 + pThis->pParent = pNewParent;
24.3958 + sqlite3PagerRef(pNewParent->pDbPage);
24.3959 + }
24.3960 + pThis->idxParent = idx;
24.3961 + }
24.3962 + sqlite3PagerUnref(pDbPage);
24.3963 + }
24.3964 +
24.3965 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.3966 + if( pBt->autoVacuum ){
24.3967 + return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
24.3968 + }
24.3969 +#endif
24.3970 + return SQLITE_OK;
24.3971 +}
24.3972 +
24.3973 +
24.3974 +
24.3975 +/*
24.3976 +** Change the pParent pointer of all children of pPage to point back
24.3977 +** to pPage.
24.3978 +**
24.3979 +** In other words, for every child of pPage, invoke reparentPage()
24.3980 +** to make sure that each child knows that pPage is its parent.
24.3981 +**
24.3982 +** This routine gets called after you memcpy() one page into
24.3983 +** another.
24.3984 +*/
24.3985 +static int reparentChildPages(MemPage *pPage){
24.3986 + int i;
24.3987 + BtShared *pBt = pPage->pBt;
24.3988 + int rc = SQLITE_OK;
24.3989 +
24.3990 + if( pPage->leaf ) return SQLITE_OK;
24.3991 +
24.3992 + for(i=0; i<pPage->nCell; i++){
24.3993 + u8 *pCell = findCell(pPage, i);
24.3994 + if( !pPage->leaf ){
24.3995 + rc = reparentPage(pBt, get4byte(pCell), pPage, i);
24.3996 + if( rc!=SQLITE_OK ) return rc;
24.3997 + }
24.3998 + }
24.3999 + if( !pPage->leaf ){
24.4000 + rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]),
24.4001 + pPage, i);
24.4002 + pPage->idxShift = 0;
24.4003 + }
24.4004 + return rc;
24.4005 +}
24.4006 +
24.4007 +/*
24.4008 +** Remove the i-th cell from pPage. This routine effects pPage only.
24.4009 +** The cell content is not freed or deallocated. It is assumed that
24.4010 +** the cell content has been copied someplace else. This routine just
24.4011 +** removes the reference to the cell from pPage.
24.4012 +**
24.4013 +** "sz" must be the number of bytes in the cell.
24.4014 +*/
24.4015 +static void dropCell(MemPage *pPage, int idx, int sz){
24.4016 + int i; /* Loop counter */
24.4017 + int pc; /* Offset to cell content of cell being deleted */
24.4018 + u8 *data; /* pPage->aData */
24.4019 + u8 *ptr; /* Used to move bytes around within data[] */
24.4020 +
24.4021 + assert( idx>=0 && idx<pPage->nCell );
24.4022 + assert( sz==cellSize(pPage, idx) );
24.4023 + assert( sqlite3PagerIswriteable(pPage->pDbPage) );
24.4024 + data = pPage->aData;
24.4025 + ptr = &data[pPage->cellOffset + 2*idx];
24.4026 + pc = get2byte(ptr);
24.4027 + assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
24.4028 + freeSpace(pPage, pc, sz);
24.4029 + for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
24.4030 + ptr[0] = ptr[2];
24.4031 + ptr[1] = ptr[3];
24.4032 + }
24.4033 + pPage->nCell--;
24.4034 + put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
24.4035 + pPage->nFree += 2;
24.4036 + pPage->idxShift = 1;
24.4037 +}
24.4038 +
24.4039 +/*
24.4040 +** Insert a new cell on pPage at cell index "i". pCell points to the
24.4041 +** content of the cell.
24.4042 +**
24.4043 +** If the cell content will fit on the page, then put it there. If it
24.4044 +** will not fit, then make a copy of the cell content into pTemp if
24.4045 +** pTemp is not null. Regardless of pTemp, allocate a new entry
24.4046 +** in pPage->aOvfl[] and make it point to the cell content (either
24.4047 +** in pTemp or the original pCell) and also record its index.
24.4048 +** Allocating a new entry in pPage->aCell[] implies that
24.4049 +** pPage->nOverflow is incremented.
24.4050 +**
24.4051 +** If nSkip is non-zero, then do not copy the first nSkip bytes of the
24.4052 +** cell. The caller will overwrite them after this function returns. If
24.4053 +** nSkip is non-zero, then pCell may not point to an invalid memory location
24.4054 +** (but pCell+nSkip is always valid).
24.4055 +*/
24.4056 +static int insertCell(
24.4057 + MemPage *pPage, /* Page into which we are copying */
24.4058 + int i, /* New cell becomes the i-th cell of the page */
24.4059 + u8 *pCell, /* Content of the new cell */
24.4060 + int sz, /* Bytes of content in pCell */
24.4061 + u8 *pTemp, /* Temp storage space for pCell, if needed */
24.4062 + u8 nSkip /* Do not write the first nSkip bytes of the cell */
24.4063 +){
24.4064 + int idx; /* Where to write new cell content in data[] */
24.4065 + int j; /* Loop counter */
24.4066 + int top; /* First byte of content for any cell in data[] */
24.4067 + int end; /* First byte past the last cell pointer in data[] */
24.4068 + int ins; /* Index in data[] where new cell pointer is inserted */
24.4069 + int hdr; /* Offset into data[] of the page header */
24.4070 + int cellOffset; /* Address of first cell pointer in data[] */
24.4071 + u8 *data; /* The content of the whole page */
24.4072 + u8 *ptr; /* Used for moving information around in data[] */
24.4073 +
24.4074 + assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
24.4075 + assert( sz==cellSizePtr(pPage, pCell) );
24.4076 + assert( sqlite3PagerIswriteable(pPage->pDbPage) );
24.4077 + if( pPage->nOverflow || sz+2>pPage->nFree ){
24.4078 + if( pTemp ){
24.4079 + memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
24.4080 + pCell = pTemp;
24.4081 + }
24.4082 + j = pPage->nOverflow++;
24.4083 + assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
24.4084 + pPage->aOvfl[j].pCell = pCell;
24.4085 + pPage->aOvfl[j].idx = i;
24.4086 + pPage->nFree = 0;
24.4087 + }else{
24.4088 + data = pPage->aData;
24.4089 + hdr = pPage->hdrOffset;
24.4090 + top = get2byte(&data[hdr+5]);
24.4091 + cellOffset = pPage->cellOffset;
24.4092 + end = cellOffset + 2*pPage->nCell + 2;
24.4093 + ins = cellOffset + 2*i;
24.4094 + if( end > top - sz ){
24.4095 + int rc = defragmentPage(pPage);
24.4096 + if( rc!=SQLITE_OK ) return rc;
24.4097 + top = get2byte(&data[hdr+5]);
24.4098 + assert( end + sz <= top );
24.4099 + }
24.4100 + idx = allocateSpace(pPage, sz);
24.4101 + assert( idx>0 );
24.4102 + assert( end <= get2byte(&data[hdr+5]) );
24.4103 + pPage->nCell++;
24.4104 + pPage->nFree -= 2;
24.4105 + memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
24.4106 + for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
24.4107 + ptr[0] = ptr[-2];
24.4108 + ptr[1] = ptr[-1];
24.4109 + }
24.4110 + put2byte(&data[ins], idx);
24.4111 + put2byte(&data[hdr+3], pPage->nCell);
24.4112 + pPage->idxShift = 1;
24.4113 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.4114 + if( pPage->pBt->autoVacuum ){
24.4115 + /* The cell may contain a pointer to an overflow page. If so, write
24.4116 + ** the entry for the overflow page into the pointer map.
24.4117 + */
24.4118 + CellInfo info;
24.4119 + sqlite3BtreeParseCellPtr(pPage, pCell, &info);
24.4120 + assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
24.4121 + if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
24.4122 + Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
24.4123 + int rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
24.4124 + if( rc!=SQLITE_OK ) return rc;
24.4125 + }
24.4126 + }
24.4127 +#endif
24.4128 + }
24.4129 +
24.4130 + return SQLITE_OK;
24.4131 +}
24.4132 +
24.4133 +/*
24.4134 +** Add a list of cells to a page. The page should be initially empty.
24.4135 +** The cells are guaranteed to fit on the page.
24.4136 +*/
24.4137 +static void assemblePage(
24.4138 + MemPage *pPage, /* The page to be assemblied */
24.4139 + int nCell, /* The number of cells to add to this page */
24.4140 + u8 **apCell, /* Pointers to cell bodies */
24.4141 + int *aSize /* Sizes of the cells */
24.4142 +){
24.4143 + int i; /* Loop counter */
24.4144 + int totalSize; /* Total size of all cells */
24.4145 + int hdr; /* Index of page header */
24.4146 + int cellptr; /* Address of next cell pointer */
24.4147 + int cellbody; /* Address of next cell body */
24.4148 + u8 *data; /* Data for the page */
24.4149 +
24.4150 + assert( pPage->nOverflow==0 );
24.4151 + totalSize = 0;
24.4152 + for(i=0; i<nCell; i++){
24.4153 + totalSize += aSize[i];
24.4154 + }
24.4155 + assert( totalSize+2*nCell<=pPage->nFree );
24.4156 + assert( pPage->nCell==0 );
24.4157 + cellptr = pPage->cellOffset;
24.4158 + data = pPage->aData;
24.4159 + hdr = pPage->hdrOffset;
24.4160 + put2byte(&data[hdr+3], nCell);
24.4161 + if( nCell ){
24.4162 + cellbody = allocateSpace(pPage, totalSize);
24.4163 + assert( cellbody>0 );
24.4164 + assert( pPage->nFree >= 2*nCell );
24.4165 + pPage->nFree -= 2*nCell;
24.4166 + for(i=0; i<nCell; i++){
24.4167 + put2byte(&data[cellptr], cellbody);
24.4168 + memcpy(&data[cellbody], apCell[i], aSize[i]);
24.4169 + cellptr += 2;
24.4170 + cellbody += aSize[i];
24.4171 + }
24.4172 + assert( cellbody==pPage->pBt->usableSize );
24.4173 + }
24.4174 + pPage->nCell = nCell;
24.4175 +}
24.4176 +
24.4177 +/*
24.4178 +** The following parameters determine how many adjacent pages get involved
24.4179 +** in a balancing operation. NN is the number of neighbors on either side
24.4180 +** of the page that participate in the balancing operation. NB is the
24.4181 +** total number of pages that participate, including the target page and
24.4182 +** NN neighbors on either side.
24.4183 +**
24.4184 +** The minimum value of NN is 1 (of course). Increasing NN above 1
24.4185 +** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
24.4186 +** in exchange for a larger degradation in INSERT and UPDATE performance.
24.4187 +** The value of NN appears to give the best results overall.
24.4188 +*/
24.4189 +#define NN 1 /* Number of neighbors on either side of pPage */
24.4190 +#define NB (NN*2+1) /* Total pages involved in the balance */
24.4191 +
24.4192 +/* Forward reference */
24.4193 +static int balance(MemPage*, int);
24.4194 +
24.4195 +#ifndef SQLITE_OMIT_QUICKBALANCE
24.4196 +/*
24.4197 +** This version of balance() handles the common special case where
24.4198 +** a new entry is being inserted on the extreme right-end of the
24.4199 +** tree, in other words, when the new entry will become the largest
24.4200 +** entry in the tree.
24.4201 +**
24.4202 +** Instead of trying balance the 3 right-most leaf pages, just add
24.4203 +** a new page to the right-hand side and put the one new entry in
24.4204 +** that page. This leaves the right side of the tree somewhat
24.4205 +** unbalanced. But odds are that we will be inserting new entries
24.4206 +** at the end soon afterwards so the nearly empty page will quickly
24.4207 +** fill up. On average.
24.4208 +**
24.4209 +** pPage is the leaf page which is the right-most page in the tree.
24.4210 +** pParent is its parent. pPage must have a single overflow entry
24.4211 +** which is also the right-most entry on the page.
24.4212 +*/
24.4213 +static int balance_quick(MemPage *pPage, MemPage *pParent){
24.4214 + int rc;
24.4215 + MemPage *pNew;
24.4216 + Pgno pgnoNew;
24.4217 + u8 *pCell;
24.4218 + int szCell;
24.4219 + CellInfo info;
24.4220 + BtShared *pBt = pPage->pBt;
24.4221 + int parentIdx = pParent->nCell; /* pParent new divider cell index */
24.4222 + int parentSize; /* Size of new divider cell */
24.4223 + u8 parentCell[64]; /* Space for the new divider cell */
24.4224 +
24.4225 + /* Allocate a new page. Insert the overflow cell from pPage
24.4226 + ** into it. Then remove the overflow cell from pPage.
24.4227 + */
24.4228 + rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
24.4229 + if( rc!=SQLITE_OK ){
24.4230 + return rc;
24.4231 + }
24.4232 + pCell = pPage->aOvfl[0].pCell;
24.4233 + szCell = cellSizePtr(pPage, pCell);
24.4234 + zeroPage(pNew, pPage->aData[0]);
24.4235 + assemblePage(pNew, 1, &pCell, &szCell);
24.4236 + pPage->nOverflow = 0;
24.4237 +
24.4238 + /* Set the parent of the newly allocated page to pParent. */
24.4239 + pNew->pParent = pParent;
24.4240 + sqlite3PagerRef(pParent->pDbPage);
24.4241 +
24.4242 + /* pPage is currently the right-child of pParent. Change this
24.4243 + ** so that the right-child is the new page allocated above and
24.4244 + ** pPage is the next-to-right child.
24.4245 + */
24.4246 + assert( pPage->nCell>0 );
24.4247 + pCell = findCell(pPage, pPage->nCell-1);
24.4248 + sqlite3BtreeParseCellPtr(pPage, pCell, &info);
24.4249 + rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
24.4250 + if( rc!=SQLITE_OK ){
24.4251 + return rc;
24.4252 + }
24.4253 + assert( parentSize<64 );
24.4254 + rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
24.4255 + if( rc!=SQLITE_OK ){
24.4256 + return rc;
24.4257 + }
24.4258 + put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
24.4259 + put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
24.4260 +
24.4261 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.4262 + /* If this is an auto-vacuum database, update the pointer map
24.4263 + ** with entries for the new page, and any pointer from the
24.4264 + ** cell on the page to an overflow page.
24.4265 + */
24.4266 + if( pBt->autoVacuum ){
24.4267 + rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
24.4268 + if( rc==SQLITE_OK ){
24.4269 + rc = ptrmapPutOvfl(pNew, 0);
24.4270 + }
24.4271 + if( rc!=SQLITE_OK ){
24.4272 + releasePage(pNew);
24.4273 + return rc;
24.4274 + }
24.4275 + }
24.4276 +#endif
24.4277 +
24.4278 + /* Release the reference to the new page and balance the parent page,
24.4279 + ** in case the divider cell inserted caused it to become overfull.
24.4280 + */
24.4281 + releasePage(pNew);
24.4282 + return balance(pParent, 0);
24.4283 +}
24.4284 +#endif /* SQLITE_OMIT_QUICKBALANCE */
24.4285 +
24.4286 +/*
24.4287 +** This routine redistributes Cells on pPage and up to NN*2 siblings
24.4288 +** of pPage so that all pages have about the same amount of free space.
24.4289 +** Usually NN siblings on either side of pPage is used in the balancing,
24.4290 +** though more siblings might come from one side if pPage is the first
24.4291 +** or last child of its parent. If pPage has fewer than 2*NN siblings
24.4292 +** (something which can only happen if pPage is the root page or a
24.4293 +** child of root) then all available siblings participate in the balancing.
24.4294 +**
24.4295 +** The number of siblings of pPage might be increased or decreased by one or
24.4296 +** two in an effort to keep pages nearly full but not over full. The root page
24.4297 +** is special and is allowed to be nearly empty. If pPage is
24.4298 +** the root page, then the depth of the tree might be increased
24.4299 +** or decreased by one, as necessary, to keep the root page from being
24.4300 +** overfull or completely empty.
24.4301 +**
24.4302 +** Note that when this routine is called, some of the Cells on pPage
24.4303 +** might not actually be stored in pPage->aData[]. This can happen
24.4304 +** if the page is overfull. Part of the job of this routine is to
24.4305 +** make sure all Cells for pPage once again fit in pPage->aData[].
24.4306 +**
24.4307 +** In the course of balancing the siblings of pPage, the parent of pPage
24.4308 +** might become overfull or underfull. If that happens, then this routine
24.4309 +** is called recursively on the parent.
24.4310 +**
24.4311 +** If this routine fails for any reason, it might leave the database
24.4312 +** in a corrupted state. So if this routine fails, the database should
24.4313 +** be rolled back.
24.4314 +*/
24.4315 +static int balance_nonroot(MemPage *pPage){
24.4316 + MemPage *pParent; /* The parent of pPage */
24.4317 + BtShared *pBt; /* The whole database */
24.4318 + int nCell = 0; /* Number of cells in apCell[] */
24.4319 + int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
24.4320 + int nOld; /* Number of pages in apOld[] */
24.4321 + int nNew; /* Number of pages in apNew[] */
24.4322 + int nDiv; /* Number of cells in apDiv[] */
24.4323 + int i, j, k; /* Loop counters */
24.4324 + int idx; /* Index of pPage in pParent->aCell[] */
24.4325 + int nxDiv; /* Next divider slot in pParent->aCell[] */
24.4326 + int rc; /* The return code */
24.4327 + int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
24.4328 + int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
24.4329 + int usableSpace; /* Bytes in pPage beyond the header */
24.4330 + int pageFlags; /* Value of pPage->aData[0] */
24.4331 + int subtotal; /* Subtotal of bytes in cells on one page */
24.4332 + int iSpace = 0; /* First unused byte of aSpace[] */
24.4333 + MemPage *apOld[NB]; /* pPage and up to two siblings */
24.4334 + Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
24.4335 + MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
24.4336 + MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
24.4337 + Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
24.4338 + u8 *apDiv[NB]; /* Divider cells in pParent */
24.4339 + int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
24.4340 + int szNew[NB+2]; /* Combined size of cells place on i-th page */
24.4341 + u8 **apCell = 0; /* All cells begin balanced */
24.4342 + int *szCell; /* Local size of all cells in apCell[] */
24.4343 + u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
24.4344 + u8 *aSpace; /* Space to hold copies of dividers cells */
24.4345 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.4346 + u8 *aFrom = 0;
24.4347 +#endif
24.4348 +
24.4349 + /*
24.4350 + ** Find the parent page.
24.4351 + */
24.4352 + assert( pPage->isInit );
24.4353 + assert( sqlite3PagerIswriteable(pPage->pDbPage) );
24.4354 + pBt = pPage->pBt;
24.4355 + pParent = pPage->pParent;
24.4356 + assert( pParent );
24.4357 + if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
24.4358 + return rc;
24.4359 + }
24.4360 + TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
24.4361 +
24.4362 +#ifndef SQLITE_OMIT_QUICKBALANCE
24.4363 + /*
24.4364 + ** A special case: If a new entry has just been inserted into a
24.4365 + ** table (that is, a btree with integer keys and all data at the leaves)
24.4366 + ** and the new entry is the right-most entry in the tree (it has the
24.4367 + ** largest key) then use the special balance_quick() routine for
24.4368 + ** balancing. balance_quick() is much faster and results in a tighter
24.4369 + ** packing of data in the common case.
24.4370 + */
24.4371 + if( pPage->leaf &&
24.4372 + pPage->intKey &&
24.4373 + pPage->leafData &&
24.4374 + pPage->nOverflow==1 &&
24.4375 + pPage->aOvfl[0].idx==pPage->nCell &&
24.4376 + pPage->pParent->pgno!=1 &&
24.4377 + get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
24.4378 + ){
24.4379 + /*
24.4380 + ** TODO: Check the siblings to the left of pPage. It may be that
24.4381 + ** they are not full and no new page is required.
24.4382 + */
24.4383 + return balance_quick(pPage, pParent);
24.4384 + }
24.4385 +#endif
24.4386 +
24.4387 + /*
24.4388 + ** Find the cell in the parent page whose left child points back
24.4389 + ** to pPage. The "idx" variable is the index of that cell. If pPage
24.4390 + ** is the rightmost child of pParent then set idx to pParent->nCell
24.4391 + */
24.4392 + if( pParent->idxShift ){
24.4393 + Pgno pgno;
24.4394 + pgno = pPage->pgno;
24.4395 + assert( pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
24.4396 + for(idx=0; idx<pParent->nCell; idx++){
24.4397 + if( get4byte(findCell(pParent, idx))==pgno ){
24.4398 + break;
24.4399 + }
24.4400 + }
24.4401 + assert( idx<pParent->nCell
24.4402 + || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
24.4403 + }else{
24.4404 + idx = pPage->idxParent;
24.4405 + }
24.4406 +
24.4407 + /*
24.4408 + ** Initialize variables so that it will be safe to jump
24.4409 + ** directly to balance_cleanup at any moment.
24.4410 + */
24.4411 + nOld = nNew = 0;
24.4412 + sqlite3PagerRef(pParent->pDbPage);
24.4413 +
24.4414 + /*
24.4415 + ** Find sibling pages to pPage and the cells in pParent that divide
24.4416 + ** the siblings. An attempt is made to find NN siblings on either
24.4417 + ** side of pPage. More siblings are taken from one side, however, if
24.4418 + ** pPage there are fewer than NN siblings on the other side. If pParent
24.4419 + ** has NB or fewer children then all children of pParent are taken.
24.4420 + */
24.4421 + nxDiv = idx - NN;
24.4422 + if( nxDiv + NB > pParent->nCell ){
24.4423 + nxDiv = pParent->nCell - NB + 1;
24.4424 + }
24.4425 + if( nxDiv<0 ){
24.4426 + nxDiv = 0;
24.4427 + }
24.4428 + nDiv = 0;
24.4429 + for(i=0, k=nxDiv; i<NB; i++, k++){
24.4430 + if( k<pParent->nCell ){
24.4431 + apDiv[i] = findCell(pParent, k);
24.4432 + nDiv++;
24.4433 + assert( !pParent->leaf );
24.4434 + pgnoOld[i] = get4byte(apDiv[i]);
24.4435 + }else if( k==pParent->nCell ){
24.4436 + pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
24.4437 + }else{
24.4438 + break;
24.4439 + }
24.4440 + rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
24.4441 + if( rc ) goto balance_cleanup;
24.4442 + apOld[i]->idxParent = k;
24.4443 + apCopy[i] = 0;
24.4444 + assert( i==nOld );
24.4445 + nOld++;
24.4446 + nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
24.4447 + }
24.4448 +
24.4449 + /* Make nMaxCells a multiple of 2 in order to preserve 8-byte
24.4450 + ** alignment */
24.4451 + nMaxCells = (nMaxCells + 1)&~1;
24.4452 +
24.4453 + /*
24.4454 + ** Allocate space for memory structures
24.4455 + */
24.4456 + apCell = sqliteMallocRaw(
24.4457 + nMaxCells*sizeof(u8*) /* apCell */
24.4458 + + nMaxCells*sizeof(int) /* szCell */
24.4459 + + ROUND8(sizeof(MemPage))*NB /* aCopy */
24.4460 + + pBt->pageSize*(5+NB) /* aSpace */
24.4461 + + (ISAUTOVACUUM ? nMaxCells : 0) /* aFrom */
24.4462 + );
24.4463 + if( apCell==0 ){
24.4464 + rc = SQLITE_NOMEM;
24.4465 + goto balance_cleanup;
24.4466 + }
24.4467 + szCell = (int*)&apCell[nMaxCells];
24.4468 + aCopy[0] = (u8*)&szCell[nMaxCells];
24.4469 + assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
24.4470 + for(i=1; i<NB; i++){
24.4471 + aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
24.4472 + assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
24.4473 + }
24.4474 + aSpace = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
24.4475 + assert( ((aSpace - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
24.4476 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.4477 + if( pBt->autoVacuum ){
24.4478 + aFrom = &aSpace[5*pBt->pageSize];
24.4479 + }
24.4480 +#endif
24.4481 +
24.4482 + /*
24.4483 + ** Make copies of the content of pPage and its siblings into aOld[].
24.4484 + ** The rest of this function will use data from the copies rather
24.4485 + ** that the original pages since the original pages will be in the
24.4486 + ** process of being overwritten.
24.4487 + */
24.4488 + for(i=0; i<nOld; i++){
24.4489 + MemPage *p = apCopy[i] = (MemPage*)&aCopy[i][pBt->pageSize];
24.4490 + p->aData = &((u8*)p)[-pBt->pageSize];
24.4491 + memcpy(p->aData, apOld[i]->aData, pBt->pageSize + sizeof(MemPage));
24.4492 + /* The memcpy() above changes the value of p->aData so we have to
24.4493 + ** set it again. */
24.4494 + p->aData = &((u8*)p)[-pBt->pageSize];
24.4495 + }
24.4496 +
24.4497 + /*
24.4498 + ** Load pointers to all cells on sibling pages and the divider cells
24.4499 + ** into the local apCell[] array. Make copies of the divider cells
24.4500 + ** into space obtained form aSpace[] and remove the the divider Cells
24.4501 + ** from pParent.
24.4502 + **
24.4503 + ** If the siblings are on leaf pages, then the child pointers of the
24.4504 + ** divider cells are stripped from the cells before they are copied
24.4505 + ** into aSpace[]. In this way, all cells in apCell[] are without
24.4506 + ** child pointers. If siblings are not leaves, then all cell in
24.4507 + ** apCell[] include child pointers. Either way, all cells in apCell[]
24.4508 + ** are alike.
24.4509 + **
24.4510 + ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
24.4511 + ** leafData: 1 if pPage holds key+data and pParent holds only keys.
24.4512 + */
24.4513 + nCell = 0;
24.4514 + leafCorrection = pPage->leaf*4;
24.4515 + leafData = pPage->leafData && pPage->leaf;
24.4516 + for(i=0; i<nOld; i++){
24.4517 + MemPage *pOld = apCopy[i];
24.4518 + int limit = pOld->nCell+pOld->nOverflow;
24.4519 + for(j=0; j<limit; j++){
24.4520 + assert( nCell<nMaxCells );
24.4521 + apCell[nCell] = findOverflowCell(pOld, j);
24.4522 + szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
24.4523 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.4524 + if( pBt->autoVacuum ){
24.4525 + int a;
24.4526 + aFrom[nCell] = i;
24.4527 + for(a=0; a<pOld->nOverflow; a++){
24.4528 + if( pOld->aOvfl[a].pCell==apCell[nCell] ){
24.4529 + aFrom[nCell] = 0xFF;
24.4530 + break;
24.4531 + }
24.4532 + }
24.4533 + }
24.4534 +#endif
24.4535 + nCell++;
24.4536 + }
24.4537 + if( i<nOld-1 ){
24.4538 + int sz = cellSizePtr(pParent, apDiv[i]);
24.4539 + if( leafData ){
24.4540 + /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
24.4541 + ** are duplicates of keys on the child pages. We need to remove
24.4542 + ** the divider cells from pParent, but the dividers cells are not
24.4543 + ** added to apCell[] because they are duplicates of child cells.
24.4544 + */
24.4545 + dropCell(pParent, nxDiv, sz);
24.4546 + }else{
24.4547 + u8 *pTemp;
24.4548 + assert( nCell<nMaxCells );
24.4549 + szCell[nCell] = sz;
24.4550 + pTemp = &aSpace[iSpace];
24.4551 + iSpace += sz;
24.4552 + assert( iSpace<=pBt->pageSize*5 );
24.4553 + memcpy(pTemp, apDiv[i], sz);
24.4554 + apCell[nCell] = pTemp+leafCorrection;
24.4555 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.4556 + if( pBt->autoVacuum ){
24.4557 + aFrom[nCell] = 0xFF;
24.4558 + }
24.4559 +#endif
24.4560 + dropCell(pParent, nxDiv, sz);
24.4561 + szCell[nCell] -= leafCorrection;
24.4562 + assert( get4byte(pTemp)==pgnoOld[i] );
24.4563 + if( !pOld->leaf ){
24.4564 + assert( leafCorrection==0 );
24.4565 + /* The right pointer of the child page pOld becomes the left
24.4566 + ** pointer of the divider cell */
24.4567 + memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
24.4568 + }else{
24.4569 + assert( leafCorrection==4 );
24.4570 + if( szCell[nCell]<4 ){
24.4571 + /* Do not allow any cells smaller than 4 bytes. */
24.4572 + szCell[nCell] = 4;
24.4573 + }
24.4574 + }
24.4575 + nCell++;
24.4576 + }
24.4577 + }
24.4578 + }
24.4579 +
24.4580 + /*
24.4581 + ** Figure out the number of pages needed to hold all nCell cells.
24.4582 + ** Store this number in "k". Also compute szNew[] which is the total
24.4583 + ** size of all cells on the i-th page and cntNew[] which is the index
24.4584 + ** in apCell[] of the cell that divides page i from page i+1.
24.4585 + ** cntNew[k] should equal nCell.
24.4586 + **
24.4587 + ** Values computed by this block:
24.4588 + **
24.4589 + ** k: The total number of sibling pages
24.4590 + ** szNew[i]: Spaced used on the i-th sibling page.
24.4591 + ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
24.4592 + ** the right of the i-th sibling page.
24.4593 + ** usableSpace: Number of bytes of space available on each sibling.
24.4594 + **
24.4595 + */
24.4596 + usableSpace = pBt->usableSize - 12 + leafCorrection;
24.4597 + for(subtotal=k=i=0; i<nCell; i++){
24.4598 + assert( i<nMaxCells );
24.4599 + subtotal += szCell[i] + 2;
24.4600 + if( subtotal > usableSpace ){
24.4601 + szNew[k] = subtotal - szCell[i];
24.4602 + cntNew[k] = i;
24.4603 + if( leafData ){ i--; }
24.4604 + subtotal = 0;
24.4605 + k++;
24.4606 + }
24.4607 + }
24.4608 + szNew[k] = subtotal;
24.4609 + cntNew[k] = nCell;
24.4610 + k++;
24.4611 +
24.4612 + /*
24.4613 + ** The packing computed by the previous block is biased toward the siblings
24.4614 + ** on the left side. The left siblings are always nearly full, while the
24.4615 + ** right-most sibling might be nearly empty. This block of code attempts
24.4616 + ** to adjust the packing of siblings to get a better balance.
24.4617 + **
24.4618 + ** This adjustment is more than an optimization. The packing above might
24.4619 + ** be so out of balance as to be illegal. For example, the right-most
24.4620 + ** sibling might be completely empty. This adjustment is not optional.
24.4621 + */
24.4622 + for(i=k-1; i>0; i--){
24.4623 + int szRight = szNew[i]; /* Size of sibling on the right */
24.4624 + int szLeft = szNew[i-1]; /* Size of sibling on the left */
24.4625 + int r; /* Index of right-most cell in left sibling */
24.4626 + int d; /* Index of first cell to the left of right sibling */
24.4627 +
24.4628 + r = cntNew[i-1] - 1;
24.4629 + d = r + 1 - leafData;
24.4630 + assert( d<nMaxCells );
24.4631 + assert( r<nMaxCells );
24.4632 + while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
24.4633 + szRight += szCell[d] + 2;
24.4634 + szLeft -= szCell[r] + 2;
24.4635 + cntNew[i-1]--;
24.4636 + r = cntNew[i-1] - 1;
24.4637 + d = r + 1 - leafData;
24.4638 + }
24.4639 + szNew[i] = szRight;
24.4640 + szNew[i-1] = szLeft;
24.4641 + }
24.4642 +
24.4643 + /* Either we found one or more cells (cntnew[0])>0) or we are the
24.4644 + ** a virtual root page. A virtual root page is when the real root
24.4645 + ** page is page 1 and we are the only child of that page.
24.4646 + */
24.4647 + assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
24.4648 +
24.4649 + /*
24.4650 + ** Allocate k new pages. Reuse old pages where possible.
24.4651 + */
24.4652 + assert( pPage->pgno>1 );
24.4653 + pageFlags = pPage->aData[0];
24.4654 + for(i=0; i<k; i++){
24.4655 + MemPage *pNew;
24.4656 + if( i<nOld ){
24.4657 + pNew = apNew[i] = apOld[i];
24.4658 + pgnoNew[i] = pgnoOld[i];
24.4659 + apOld[i] = 0;
24.4660 + rc = sqlite3PagerWrite(pNew->pDbPage);
24.4661 + nNew++;
24.4662 + if( rc ) goto balance_cleanup;
24.4663 + }else{
24.4664 + assert( i>0 );
24.4665 + rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
24.4666 + if( rc ) goto balance_cleanup;
24.4667 + apNew[i] = pNew;
24.4668 + nNew++;
24.4669 + }
24.4670 + zeroPage(pNew, pageFlags);
24.4671 + }
24.4672 +
24.4673 + /* Free any old pages that were not reused as new pages.
24.4674 + */
24.4675 + while( i<nOld ){
24.4676 + rc = freePage(apOld[i]);
24.4677 + if( rc ) goto balance_cleanup;
24.4678 + releasePage(apOld[i]);
24.4679 + apOld[i] = 0;
24.4680 + i++;
24.4681 + }
24.4682 +
24.4683 + /*
24.4684 + ** Put the new pages in accending order. This helps to
24.4685 + ** keep entries in the disk file in order so that a scan
24.4686 + ** of the table is a linear scan through the file. That
24.4687 + ** in turn helps the operating system to deliver pages
24.4688 + ** from the disk more rapidly.
24.4689 + **
24.4690 + ** An O(n^2) insertion sort algorithm is used, but since
24.4691 + ** n is never more than NB (a small constant), that should
24.4692 + ** not be a problem.
24.4693 + **
24.4694 + ** When NB==3, this one optimization makes the database
24.4695 + ** about 25% faster for large insertions and deletions.
24.4696 + */
24.4697 + for(i=0; i<k-1; i++){
24.4698 + int minV = pgnoNew[i];
24.4699 + int minI = i;
24.4700 + for(j=i+1; j<k; j++){
24.4701 + if( pgnoNew[j]<(unsigned)minV ){
24.4702 + minI = j;
24.4703 + minV = pgnoNew[j];
24.4704 + }
24.4705 + }
24.4706 + if( minI>i ){
24.4707 + int t;
24.4708 + MemPage *pT;
24.4709 + t = pgnoNew[i];
24.4710 + pT = apNew[i];
24.4711 + pgnoNew[i] = pgnoNew[minI];
24.4712 + apNew[i] = apNew[minI];
24.4713 + pgnoNew[minI] = t;
24.4714 + apNew[minI] = pT;
24.4715 + }
24.4716 + }
24.4717 + TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
24.4718 + pgnoOld[0],
24.4719 + nOld>=2 ? pgnoOld[1] : 0,
24.4720 + nOld>=3 ? pgnoOld[2] : 0,
24.4721 + pgnoNew[0], szNew[0],
24.4722 + nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
24.4723 + nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
24.4724 + nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
24.4725 + nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
24.4726 +
24.4727 + /*
24.4728 + ** Evenly distribute the data in apCell[] across the new pages.
24.4729 + ** Insert divider cells into pParent as necessary.
24.4730 + */
24.4731 + j = 0;
24.4732 + for(i=0; i<nNew; i++){
24.4733 + /* Assemble the new sibling page. */
24.4734 + MemPage *pNew = apNew[i];
24.4735 + assert( j<nMaxCells );
24.4736 + assert( pNew->pgno==pgnoNew[i] );
24.4737 + assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
24.4738 + assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
24.4739 + assert( pNew->nOverflow==0 );
24.4740 +
24.4741 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.4742 + /* If this is an auto-vacuum database, update the pointer map entries
24.4743 + ** that point to the siblings that were rearranged. These can be: left
24.4744 + ** children of cells, the right-child of the page, or overflow pages
24.4745 + ** pointed to by cells.
24.4746 + */
24.4747 + if( pBt->autoVacuum ){
24.4748 + for(k=j; k<cntNew[i]; k++){
24.4749 + assert( k<nMaxCells );
24.4750 + if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
24.4751 + rc = ptrmapPutOvfl(pNew, k-j);
24.4752 + if( rc!=SQLITE_OK ){
24.4753 + goto balance_cleanup;
24.4754 + }
24.4755 + }
24.4756 + }
24.4757 + }
24.4758 +#endif
24.4759 +
24.4760 + j = cntNew[i];
24.4761 +
24.4762 + /* If the sibling page assembled above was not the right-most sibling,
24.4763 + ** insert a divider cell into the parent page.
24.4764 + */
24.4765 + if( i<nNew-1 && j<nCell ){
24.4766 + u8 *pCell;
24.4767 + u8 *pTemp;
24.4768 + int sz;
24.4769 +
24.4770 + assert( j<nMaxCells );
24.4771 + pCell = apCell[j];
24.4772 + sz = szCell[j] + leafCorrection;
24.4773 + if( !pNew->leaf ){
24.4774 + memcpy(&pNew->aData[8], pCell, 4);
24.4775 + pTemp = 0;
24.4776 + }else if( leafData ){
24.4777 + /* If the tree is a leaf-data tree, and the siblings are leaves,
24.4778 + ** then there is no divider cell in apCell[]. Instead, the divider
24.4779 + ** cell consists of the integer key for the right-most cell of
24.4780 + ** the sibling-page assembled above only.
24.4781 + */
24.4782 + CellInfo info;
24.4783 + j--;
24.4784 + sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
24.4785 + pCell = &aSpace[iSpace];
24.4786 + fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
24.4787 + iSpace += sz;
24.4788 + assert( iSpace<=pBt->pageSize*5 );
24.4789 + pTemp = 0;
24.4790 + }else{
24.4791 + pCell -= 4;
24.4792 + pTemp = &aSpace[iSpace];
24.4793 + iSpace += sz;
24.4794 + assert( iSpace<=pBt->pageSize*5 );
24.4795 + /* Obscure case for non-leaf-data trees: If the cell at pCell was
24.4796 + ** previously stored on a leaf node, and it's reported size was 4
24.4797 + ** bytes, then it may actually be smaller than this
24.4798 + ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
24.4799 + ** any cell). But it's important to pass the correct size to
24.4800 + ** insertCell(), so reparse the cell now.
24.4801 + **
24.4802 + ** Note that this can never happen in an SQLite data file, as all
24.4803 + ** cells are at least 4 bytes. It only happens in b-trees used
24.4804 + ** to evaluate "IN (SELECT ...)" and similar clauses.
24.4805 + */
24.4806 + if( szCell[j]==4 ){
24.4807 + assert(leafCorrection==4);
24.4808 + sz = cellSizePtr(pParent, pCell);
24.4809 + }
24.4810 + }
24.4811 + rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
24.4812 + if( rc!=SQLITE_OK ) goto balance_cleanup;
24.4813 + put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
24.4814 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.4815 + /* If this is an auto-vacuum database, and not a leaf-data tree,
24.4816 + ** then update the pointer map with an entry for the overflow page
24.4817 + ** that the cell just inserted points to (if any).
24.4818 + */
24.4819 + if( pBt->autoVacuum && !leafData ){
24.4820 + rc = ptrmapPutOvfl(pParent, nxDiv);
24.4821 + if( rc!=SQLITE_OK ){
24.4822 + goto balance_cleanup;
24.4823 + }
24.4824 + }
24.4825 +#endif
24.4826 + j++;
24.4827 + nxDiv++;
24.4828 + }
24.4829 + }
24.4830 + assert( j==nCell );
24.4831 + assert( nOld>0 );
24.4832 + assert( nNew>0 );
24.4833 + if( (pageFlags & PTF_LEAF)==0 ){
24.4834 + memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
24.4835 + }
24.4836 + if( nxDiv==pParent->nCell+pParent->nOverflow ){
24.4837 + /* Right-most sibling is the right-most child of pParent */
24.4838 + put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
24.4839 + }else{
24.4840 + /* Right-most sibling is the left child of the first entry in pParent
24.4841 + ** past the right-most divider entry */
24.4842 + put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
24.4843 + }
24.4844 +
24.4845 + /*
24.4846 + ** Reparent children of all cells.
24.4847 + */
24.4848 + for(i=0; i<nNew; i++){
24.4849 + rc = reparentChildPages(apNew[i]);
24.4850 + if( rc!=SQLITE_OK ) goto balance_cleanup;
24.4851 + }
24.4852 + rc = reparentChildPages(pParent);
24.4853 + if( rc!=SQLITE_OK ) goto balance_cleanup;
24.4854 +
24.4855 + /*
24.4856 + ** Balance the parent page. Note that the current page (pPage) might
24.4857 + ** have been added to the freelist so it might no longer be initialized.
24.4858 + ** But the parent page will always be initialized.
24.4859 + */
24.4860 + assert( pParent->isInit );
24.4861 + rc = balance(pParent, 0);
24.4862 +
24.4863 + /*
24.4864 + ** Cleanup before returning.
24.4865 + */
24.4866 +balance_cleanup:
24.4867 + sqliteFree(apCell);
24.4868 + for(i=0; i<nOld; i++){
24.4869 + releasePage(apOld[i]);
24.4870 + }
24.4871 + for(i=0; i<nNew; i++){
24.4872 + releasePage(apNew[i]);
24.4873 + }
24.4874 + releasePage(pParent);
24.4875 + TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
24.4876 + pPage->pgno, nOld, nNew, nCell));
24.4877 + return rc;
24.4878 +}
24.4879 +
24.4880 +/*
24.4881 +** This routine is called for the root page of a btree when the root
24.4882 +** page contains no cells. This is an opportunity to make the tree
24.4883 +** shallower by one level.
24.4884 +*/
24.4885 +static int balance_shallower(MemPage *pPage){
24.4886 + MemPage *pChild; /* The only child page of pPage */
24.4887 + Pgno pgnoChild; /* Page number for pChild */
24.4888 + int rc = SQLITE_OK; /* Return code from subprocedures */
24.4889 + BtShared *pBt; /* The main BTree structure */
24.4890 + int mxCellPerPage; /* Maximum number of cells per page */
24.4891 + u8 **apCell; /* All cells from pages being balanced */
24.4892 + int *szCell; /* Local size of all cells */
24.4893 +
24.4894 + assert( pPage->pParent==0 );
24.4895 + assert( pPage->nCell==0 );
24.4896 + pBt = pPage->pBt;
24.4897 + mxCellPerPage = MX_CELL(pBt);
24.4898 + apCell = sqliteMallocRaw( mxCellPerPage*(sizeof(u8*)+sizeof(int)) );
24.4899 + if( apCell==0 ) return SQLITE_NOMEM;
24.4900 + szCell = (int*)&apCell[mxCellPerPage];
24.4901 + if( pPage->leaf ){
24.4902 + /* The table is completely empty */
24.4903 + TRACE(("BALANCE: empty table %d\n", pPage->pgno));
24.4904 + }else{
24.4905 + /* The root page is empty but has one child. Transfer the
24.4906 + ** information from that one child into the root page if it
24.4907 + ** will fit. This reduces the depth of the tree by one.
24.4908 + **
24.4909 + ** If the root page is page 1, it has less space available than
24.4910 + ** its child (due to the 100 byte header that occurs at the beginning
24.4911 + ** of the database fle), so it might not be able to hold all of the
24.4912 + ** information currently contained in the child. If this is the
24.4913 + ** case, then do not do the transfer. Leave page 1 empty except
24.4914 + ** for the right-pointer to the child page. The child page becomes
24.4915 + ** the virtual root of the tree.
24.4916 + */
24.4917 + pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
24.4918 + assert( pgnoChild>0 );
24.4919 + assert( pgnoChild<=sqlite3PagerPagecount(pPage->pBt->pPager) );
24.4920 + rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
24.4921 + if( rc ) goto end_shallow_balance;
24.4922 + if( pPage->pgno==1 ){
24.4923 + rc = sqlite3BtreeInitPage(pChild, pPage);
24.4924 + if( rc ) goto end_shallow_balance;
24.4925 + assert( pChild->nOverflow==0 );
24.4926 + if( pChild->nFree>=100 ){
24.4927 + /* The child information will fit on the root page, so do the
24.4928 + ** copy */
24.4929 + int i;
24.4930 + zeroPage(pPage, pChild->aData[0]);
24.4931 + for(i=0; i<pChild->nCell; i++){
24.4932 + apCell[i] = findCell(pChild,i);
24.4933 + szCell[i] = cellSizePtr(pChild, apCell[i]);
24.4934 + }
24.4935 + assemblePage(pPage, pChild->nCell, apCell, szCell);
24.4936 + /* Copy the right-pointer of the child to the parent. */
24.4937 + put4byte(&pPage->aData[pPage->hdrOffset+8],
24.4938 + get4byte(&pChild->aData[pChild->hdrOffset+8]));
24.4939 + freePage(pChild);
24.4940 + TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
24.4941 + }else{
24.4942 + /* The child has more information that will fit on the root.
24.4943 + ** The tree is already balanced. Do nothing. */
24.4944 + TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
24.4945 + }
24.4946 + }else{
24.4947 + memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
24.4948 + pPage->isInit = 0;
24.4949 + pPage->pParent = 0;
24.4950 + rc = sqlite3BtreeInitPage(pPage, 0);
24.4951 + assert( rc==SQLITE_OK );
24.4952 + freePage(pChild);
24.4953 + TRACE(("BALANCE: transfer child %d into root %d\n",
24.4954 + pChild->pgno, pPage->pgno));
24.4955 + }
24.4956 + rc = reparentChildPages(pPage);
24.4957 + assert( pPage->nOverflow==0 );
24.4958 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.4959 + if( pBt->autoVacuum ){
24.4960 + int i;
24.4961 + for(i=0; i<pPage->nCell; i++){
24.4962 + rc = ptrmapPutOvfl(pPage, i);
24.4963 + if( rc!=SQLITE_OK ){
24.4964 + goto end_shallow_balance;
24.4965 + }
24.4966 + }
24.4967 + }
24.4968 +#endif
24.4969 + if( rc!=SQLITE_OK ) goto end_shallow_balance;
24.4970 + releasePage(pChild);
24.4971 + }
24.4972 +end_shallow_balance:
24.4973 + sqliteFree(apCell);
24.4974 + return rc;
24.4975 +}
24.4976 +
24.4977 +
24.4978 +/*
24.4979 +** The root page is overfull
24.4980 +**
24.4981 +** When this happens, Create a new child page and copy the
24.4982 +** contents of the root into the child. Then make the root
24.4983 +** page an empty page with rightChild pointing to the new
24.4984 +** child. Finally, call balance_internal() on the new child
24.4985 +** to cause it to split.
24.4986 +*/
24.4987 +static int balance_deeper(MemPage *pPage){
24.4988 + int rc; /* Return value from subprocedures */
24.4989 + MemPage *pChild; /* Pointer to a new child page */
24.4990 + Pgno pgnoChild; /* Page number of the new child page */
24.4991 + BtShared *pBt; /* The BTree */
24.4992 + int usableSize; /* Total usable size of a page */
24.4993 + u8 *data; /* Content of the parent page */
24.4994 + u8 *cdata; /* Content of the child page */
24.4995 + int hdr; /* Offset to page header in parent */
24.4996 + int brk; /* Offset to content of first cell in parent */
24.4997 +
24.4998 + assert( pPage->pParent==0 );
24.4999 + assert( pPage->nOverflow>0 );
24.5000 + pBt = pPage->pBt;
24.5001 + rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
24.5002 + if( rc ) return rc;
24.5003 + assert( sqlite3PagerIswriteable(pChild->pDbPage) );
24.5004 + usableSize = pBt->usableSize;
24.5005 + data = pPage->aData;
24.5006 + hdr = pPage->hdrOffset;
24.5007 + brk = get2byte(&data[hdr+5]);
24.5008 + cdata = pChild->aData;
24.5009 + memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
24.5010 + memcpy(&cdata[brk], &data[brk], usableSize-brk);
24.5011 + assert( pChild->isInit==0 );
24.5012 + rc = sqlite3BtreeInitPage(pChild, pPage);
24.5013 + if( rc ) goto balancedeeper_out;
24.5014 + memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
24.5015 + pChild->nOverflow = pPage->nOverflow;
24.5016 + if( pChild->nOverflow ){
24.5017 + pChild->nFree = 0;
24.5018 + }
24.5019 + assert( pChild->nCell==pPage->nCell );
24.5020 + zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
24.5021 + put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
24.5022 + TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
24.5023 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.5024 + if( pBt->autoVacuum ){
24.5025 + int i;
24.5026 + rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
24.5027 + if( rc ) goto balancedeeper_out;
24.5028 + for(i=0; i<pChild->nCell; i++){
24.5029 + rc = ptrmapPutOvfl(pChild, i);
24.5030 + if( rc!=SQLITE_OK ){
24.5031 + return rc;
24.5032 + }
24.5033 + }
24.5034 + }
24.5035 +#endif
24.5036 + rc = balance_nonroot(pChild);
24.5037 +
24.5038 +balancedeeper_out:
24.5039 + releasePage(pChild);
24.5040 + return rc;
24.5041 +}
24.5042 +
24.5043 +/*
24.5044 +** Decide if the page pPage needs to be balanced. If balancing is
24.5045 +** required, call the appropriate balancing routine.
24.5046 +*/
24.5047 +static int balance(MemPage *pPage, int insert){
24.5048 + int rc = SQLITE_OK;
24.5049 + if( pPage->pParent==0 ){
24.5050 + if( pPage->nOverflow>0 ){
24.5051 + rc = balance_deeper(pPage);
24.5052 + }
24.5053 + if( rc==SQLITE_OK && pPage->nCell==0 ){
24.5054 + rc = balance_shallower(pPage);
24.5055 + }
24.5056 + }else{
24.5057 + if( pPage->nOverflow>0 ||
24.5058 + (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
24.5059 + rc = balance_nonroot(pPage);
24.5060 + }
24.5061 + }
24.5062 + return rc;
24.5063 +}
24.5064 +
24.5065 +/*
24.5066 +** This routine checks all cursors that point to table pgnoRoot.
24.5067 +** If any of those cursors were opened with wrFlag==0 in a different
24.5068 +** database connection (a database connection that shares the pager
24.5069 +** cache with the current connection) and that other connection
24.5070 +** is not in the ReadUncommmitted state, then this routine returns
24.5071 +** SQLITE_LOCKED.
24.5072 +**
24.5073 +** In addition to checking for read-locks (where a read-lock
24.5074 +** means a cursor opened with wrFlag==0) this routine also moves
24.5075 +** all write cursors so that they are pointing to the
24.5076 +** first Cell on the root page. This is necessary because an insert
24.5077 +** or delete might change the number of cells on a page or delete
24.5078 +** a page entirely and we do not want to leave any cursors
24.5079 +** pointing to non-existant pages or cells.
24.5080 +*/
24.5081 +static int checkReadLocks(Btree *pBtree, Pgno pgnoRoot, BtCursor *pExclude){
24.5082 + BtCursor *p;
24.5083 + BtShared *pBt = pBtree->pBt;
24.5084 + sqlite3 *db = pBtree->pSqlite;
24.5085 + for(p=pBt->pCursor; p; p=p->pNext){
24.5086 + if( p==pExclude ) continue;
24.5087 + if( p->eState!=CURSOR_VALID ) continue;
24.5088 + if( p->pgnoRoot!=pgnoRoot ) continue;
24.5089 + if( p->wrFlag==0 ){
24.5090 + sqlite3 *dbOther = p->pBtree->pSqlite;
24.5091 + if( dbOther==0 ||
24.5092 + (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
24.5093 + return SQLITE_LOCKED;
24.5094 + }
24.5095 + }else if( p->pPage->pgno!=p->pgnoRoot ){
24.5096 + moveToRoot(p);
24.5097 + }
24.5098 + }
24.5099 + return SQLITE_OK;
24.5100 +}
24.5101 +
24.5102 +/*
24.5103 +** Insert a new record into the BTree. The key is given by (pKey,nKey)
24.5104 +** and the data is given by (pData,nData). The cursor is used only to
24.5105 +** define what table the record should be inserted into. The cursor
24.5106 +** is left pointing at a random location.
24.5107 +**
24.5108 +** For an INTKEY table, only the nKey value of the key is used. pKey is
24.5109 +** ignored. For a ZERODATA table, the pData and nData are both ignored.
24.5110 +*/
24.5111 +int sqlite3BtreeInsert(
24.5112 + BtCursor *pCur, /* Insert data into the table of this cursor */
24.5113 + const void *pKey, i64 nKey, /* The key of the new record */
24.5114 + const void *pData, int nData, /* The data of the new record */
24.5115 + int nZero, /* Number of extra 0 bytes to append to data */
24.5116 + int appendBias /* True if this is likely an append */
24.5117 +){
24.5118 + int rc;
24.5119 + int loc;
24.5120 + int szNew;
24.5121 + MemPage *pPage;
24.5122 + BtShared *pBt = pCur->pBtree->pBt;
24.5123 + unsigned char *oldCell;
24.5124 + unsigned char *newCell = 0;
24.5125 +
24.5126 + if( pBt->inTransaction!=TRANS_WRITE ){
24.5127 + /* Must start a transaction before doing an insert */
24.5128 + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
24.5129 + }
24.5130 + assert( !pBt->readOnly );
24.5131 + if( !pCur->wrFlag ){
24.5132 + return SQLITE_PERM; /* Cursor not open for writing */
24.5133 + }
24.5134 + if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
24.5135 + return SQLITE_LOCKED; /* The table pCur points to has a read lock */
24.5136 + }
24.5137 +
24.5138 + /* Save the positions of any other cursors open on this table */
24.5139 + clearCursorPosition(pCur);
24.5140 + if(
24.5141 + SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
24.5142 + SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
24.5143 + ){
24.5144 + return rc;
24.5145 + }
24.5146 +
24.5147 + pPage = pCur->pPage;
24.5148 + assert( pPage->intKey || nKey>=0 );
24.5149 + assert( pPage->leaf || !pPage->leafData );
24.5150 + TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
24.5151 + pCur->pgnoRoot, nKey, nData, pPage->pgno,
24.5152 + loc==0 ? "overwrite" : "new entry"));
24.5153 + assert( pPage->isInit );
24.5154 + rc = sqlite3PagerWrite(pPage->pDbPage);
24.5155 + if( rc ) return rc;
24.5156 + newCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
24.5157 + if( newCell==0 ) return SQLITE_NOMEM;
24.5158 + rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
24.5159 + if( rc ) goto end_insert;
24.5160 + assert( szNew==cellSizePtr(pPage, newCell) );
24.5161 + assert( szNew<=MX_CELL_SIZE(pBt) );
24.5162 + if( loc==0 && CURSOR_VALID==pCur->eState ){
24.5163 + int szOld;
24.5164 + assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
24.5165 + oldCell = findCell(pPage, pCur->idx);
24.5166 + if( !pPage->leaf ){
24.5167 + memcpy(newCell, oldCell, 4);
24.5168 + }
24.5169 + szOld = cellSizePtr(pPage, oldCell);
24.5170 + rc = clearCell(pPage, oldCell);
24.5171 + if( rc ) goto end_insert;
24.5172 + dropCell(pPage, pCur->idx, szOld);
24.5173 + }else if( loc<0 && pPage->nCell>0 ){
24.5174 + assert( pPage->leaf );
24.5175 + pCur->idx++;
24.5176 + pCur->info.nSize = 0;
24.5177 + }else{
24.5178 + assert( pPage->leaf );
24.5179 + }
24.5180 + rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
24.5181 + if( rc!=SQLITE_OK ) goto end_insert;
24.5182 + rc = balance(pPage, 1);
24.5183 + /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
24.5184 + /* fflush(stdout); */
24.5185 + if( rc==SQLITE_OK ){
24.5186 + moveToRoot(pCur);
24.5187 + }
24.5188 +end_insert:
24.5189 + sqliteFree(newCell);
24.5190 + return rc;
24.5191 +}
24.5192 +
24.5193 +/*
24.5194 +** Delete the entry that the cursor is pointing to. The cursor
24.5195 +** is left pointing at a random location.
24.5196 +*/
24.5197 +int sqlite3BtreeDelete(BtCursor *pCur){
24.5198 + MemPage *pPage = pCur->pPage;
24.5199 + unsigned char *pCell;
24.5200 + int rc;
24.5201 + Pgno pgnoChild = 0;
24.5202 + BtShared *pBt = pCur->pBtree->pBt;
24.5203 +
24.5204 + assert( pPage->isInit );
24.5205 + if( pBt->inTransaction!=TRANS_WRITE ){
24.5206 + /* Must start a transaction before doing a delete */
24.5207 + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
24.5208 + }
24.5209 + assert( !pBt->readOnly );
24.5210 + if( pCur->idx >= pPage->nCell ){
24.5211 + return SQLITE_ERROR; /* The cursor is not pointing to anything */
24.5212 + }
24.5213 + if( !pCur->wrFlag ){
24.5214 + return SQLITE_PERM; /* Did not open this cursor for writing */
24.5215 + }
24.5216 + if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
24.5217 + return SQLITE_LOCKED; /* The table pCur points to has a read lock */
24.5218 + }
24.5219 +
24.5220 + /* Restore the current cursor position (a no-op if the cursor is not in
24.5221 + ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
24.5222 + ** open on the same table. Then call sqlite3PagerWrite() on the page
24.5223 + ** that the entry will be deleted from.
24.5224 + */
24.5225 + if(
24.5226 + (rc = restoreOrClearCursorPosition(pCur))!=0 ||
24.5227 + (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
24.5228 + (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
24.5229 + ){
24.5230 + return rc;
24.5231 + }
24.5232 +
24.5233 + /* Locate the cell within it's page and leave pCell pointing to the
24.5234 + ** data. The clearCell() call frees any overflow pages associated with the
24.5235 + ** cell. The cell itself is still intact.
24.5236 + */
24.5237 + pCell = findCell(pPage, pCur->idx);
24.5238 + if( !pPage->leaf ){
24.5239 + pgnoChild = get4byte(pCell);
24.5240 + }
24.5241 + rc = clearCell(pPage, pCell);
24.5242 + if( rc ) return rc;
24.5243 +
24.5244 + if( !pPage->leaf ){
24.5245 + /*
24.5246 + ** The entry we are about to delete is not a leaf so if we do not
24.5247 + ** do something we will leave a hole on an internal page.
24.5248 + ** We have to fill the hole by moving in a cell from a leaf. The
24.5249 + ** next Cell after the one to be deleted is guaranteed to exist and
24.5250 + ** to be a leaf so we can use it.
24.5251 + */
24.5252 + BtCursor leafCur;
24.5253 + unsigned char *pNext;
24.5254 + int szNext; /* The compiler warning is wrong: szNext is always
24.5255 + ** initialized before use. Adding an extra initialization
24.5256 + ** to silence the compiler slows down the code. */
24.5257 + int notUsed;
24.5258 + unsigned char *tempCell = 0;
24.5259 + assert( !pPage->leafData );
24.5260 + sqlite3BtreeGetTempCursor(pCur, &leafCur);
24.5261 + rc = sqlite3BtreeNext(&leafCur, ¬Used);
24.5262 + if( rc==SQLITE_OK ){
24.5263 + rc = sqlite3PagerWrite(leafCur.pPage->pDbPage);
24.5264 + }
24.5265 + if( rc==SQLITE_OK ){
24.5266 + TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
24.5267 + pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
24.5268 + dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
24.5269 + pNext = findCell(leafCur.pPage, leafCur.idx);
24.5270 + szNext = cellSizePtr(leafCur.pPage, pNext);
24.5271 + assert( MX_CELL_SIZE(pBt)>=szNext+4 );
24.5272 + tempCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
24.5273 + if( tempCell==0 ){
24.5274 + rc = SQLITE_NOMEM;
24.5275 + }
24.5276 + }
24.5277 + if( rc==SQLITE_OK ){
24.5278 + rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
24.5279 + }
24.5280 + if( rc==SQLITE_OK ){
24.5281 + put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
24.5282 + rc = balance(pPage, 0);
24.5283 + }
24.5284 + if( rc==SQLITE_OK ){
24.5285 + dropCell(leafCur.pPage, leafCur.idx, szNext);
24.5286 + rc = balance(leafCur.pPage, 0);
24.5287 + }
24.5288 + sqliteFree(tempCell);
24.5289 + sqlite3BtreeReleaseTempCursor(&leafCur);
24.5290 + }else{
24.5291 + TRACE(("DELETE: table=%d delete from leaf %d\n",
24.5292 + pCur->pgnoRoot, pPage->pgno));
24.5293 + dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
24.5294 + rc = balance(pPage, 0);
24.5295 + }
24.5296 + if( rc==SQLITE_OK ){
24.5297 + moveToRoot(pCur);
24.5298 + }
24.5299 + return rc;
24.5300 +}
24.5301 +
24.5302 +/*
24.5303 +** Create a new BTree table. Write into *piTable the page
24.5304 +** number for the root page of the new table.
24.5305 +**
24.5306 +** The type of type is determined by the flags parameter. Only the
24.5307 +** following values of flags are currently in use. Other values for
24.5308 +** flags might not work:
24.5309 +**
24.5310 +** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
24.5311 +** BTREE_ZERODATA Used for SQL indices
24.5312 +*/
24.5313 +int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
24.5314 + BtShared *pBt = p->pBt;
24.5315 + MemPage *pRoot;
24.5316 + Pgno pgnoRoot;
24.5317 + int rc;
24.5318 + if( pBt->inTransaction!=TRANS_WRITE ){
24.5319 + /* Must start a transaction first */
24.5320 + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
24.5321 + }
24.5322 + assert( !pBt->readOnly );
24.5323 +
24.5324 +#ifdef SQLITE_OMIT_AUTOVACUUM
24.5325 + rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
24.5326 + if( rc ) return rc;
24.5327 +#else
24.5328 + if( pBt->autoVacuum ){
24.5329 + Pgno pgnoMove; /* Move a page here to make room for the root-page */
24.5330 + MemPage *pPageMove; /* The page to move to. */
24.5331 +
24.5332 + /* Creating a new table may probably require moving an existing database
24.5333 + ** to make room for the new tables root page. In case this page turns
24.5334 + ** out to be an overflow page, delete all overflow page-map caches
24.5335 + ** held by open cursors.
24.5336 + */
24.5337 + invalidateAllOverflowCache(pBt);
24.5338 +
24.5339 + /* Read the value of meta[3] from the database to determine where the
24.5340 + ** root page of the new table should go. meta[3] is the largest root-page
24.5341 + ** created so far, so the new root-page is (meta[3]+1).
24.5342 + */
24.5343 + rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
24.5344 + if( rc!=SQLITE_OK ) return rc;
24.5345 + pgnoRoot++;
24.5346 +
24.5347 + /* The new root-page may not be allocated on a pointer-map page, or the
24.5348 + ** PENDING_BYTE page.
24.5349 + */
24.5350 + if( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
24.5351 + pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
24.5352 + pgnoRoot++;
24.5353 + }
24.5354 + assert( pgnoRoot>=3 );
24.5355 +
24.5356 + /* Allocate a page. The page that currently resides at pgnoRoot will
24.5357 + ** be moved to the allocated page (unless the allocated page happens
24.5358 + ** to reside at pgnoRoot).
24.5359 + */
24.5360 + rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
24.5361 + if( rc!=SQLITE_OK ){
24.5362 + return rc;
24.5363 + }
24.5364 +
24.5365 + if( pgnoMove!=pgnoRoot ){
24.5366 + /* pgnoRoot is the page that will be used for the root-page of
24.5367 + ** the new table (assuming an error did not occur). But we were
24.5368 + ** allocated pgnoMove. If required (i.e. if it was not allocated
24.5369 + ** by extending the file), the current page at position pgnoMove
24.5370 + ** is already journaled.
24.5371 + */
24.5372 + u8 eType;
24.5373 + Pgno iPtrPage;
24.5374 +
24.5375 + releasePage(pPageMove);
24.5376 +
24.5377 + /* Move the page currently at pgnoRoot to pgnoMove. */
24.5378 + rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
24.5379 + if( rc!=SQLITE_OK ){
24.5380 + return rc;
24.5381 + }
24.5382 + rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
24.5383 + if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
24.5384 + releasePage(pRoot);
24.5385 + return rc;
24.5386 + }
24.5387 + assert( eType!=PTRMAP_ROOTPAGE );
24.5388 + assert( eType!=PTRMAP_FREEPAGE );
24.5389 + rc = sqlite3PagerWrite(pRoot->pDbPage);
24.5390 + if( rc!=SQLITE_OK ){
24.5391 + releasePage(pRoot);
24.5392 + return rc;
24.5393 + }
24.5394 + rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
24.5395 + releasePage(pRoot);
24.5396 +
24.5397 + /* Obtain the page at pgnoRoot */
24.5398 + if( rc!=SQLITE_OK ){
24.5399 + return rc;
24.5400 + }
24.5401 + rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
24.5402 + if( rc!=SQLITE_OK ){
24.5403 + return rc;
24.5404 + }
24.5405 + rc = sqlite3PagerWrite(pRoot->pDbPage);
24.5406 + if( rc!=SQLITE_OK ){
24.5407 + releasePage(pRoot);
24.5408 + return rc;
24.5409 + }
24.5410 + }else{
24.5411 + pRoot = pPageMove;
24.5412 + }
24.5413 +
24.5414 + /* Update the pointer-map and meta-data with the new root-page number. */
24.5415 + rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
24.5416 + if( rc ){
24.5417 + releasePage(pRoot);
24.5418 + return rc;
24.5419 + }
24.5420 + rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
24.5421 + if( rc ){
24.5422 + releasePage(pRoot);
24.5423 + return rc;
24.5424 + }
24.5425 +
24.5426 + }else{
24.5427 + rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
24.5428 + if( rc ) return rc;
24.5429 + }
24.5430 +#endif
24.5431 + assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
24.5432 + zeroPage(pRoot, flags | PTF_LEAF);
24.5433 + sqlite3PagerUnref(pRoot->pDbPage);
24.5434 + *piTable = (int)pgnoRoot;
24.5435 + return SQLITE_OK;
24.5436 +}
24.5437 +
24.5438 +/*
24.5439 +** Erase the given database page and all its children. Return
24.5440 +** the page to the freelist.
24.5441 +*/
24.5442 +static int clearDatabasePage(
24.5443 + BtShared *pBt, /* The BTree that contains the table */
24.5444 + Pgno pgno, /* Page number to clear */
24.5445 + MemPage *pParent, /* Parent page. NULL for the root */
24.5446 + int freePageFlag /* Deallocate page if true */
24.5447 +){
24.5448 + MemPage *pPage = 0;
24.5449 + int rc;
24.5450 + unsigned char *pCell;
24.5451 + int i;
24.5452 +
24.5453 + if( pgno>sqlite3PagerPagecount(pBt->pPager) ){
24.5454 + return SQLITE_CORRUPT_BKPT;
24.5455 + }
24.5456 +
24.5457 + rc = getAndInitPage(pBt, pgno, &pPage, pParent);
24.5458 + if( rc ) goto cleardatabasepage_out;
24.5459 + for(i=0; i<pPage->nCell; i++){
24.5460 + pCell = findCell(pPage, i);
24.5461 + if( !pPage->leaf ){
24.5462 + rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
24.5463 + if( rc ) goto cleardatabasepage_out;
24.5464 + }
24.5465 + rc = clearCell(pPage, pCell);
24.5466 + if( rc ) goto cleardatabasepage_out;
24.5467 + }
24.5468 + if( !pPage->leaf ){
24.5469 + rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
24.5470 + if( rc ) goto cleardatabasepage_out;
24.5471 + }
24.5472 + if( freePageFlag ){
24.5473 + rc = freePage(pPage);
24.5474 + }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
24.5475 + zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
24.5476 + }
24.5477 +
24.5478 +cleardatabasepage_out:
24.5479 + releasePage(pPage);
24.5480 + return rc;
24.5481 +}
24.5482 +
24.5483 +/*
24.5484 +** Delete all information from a single table in the database. iTable is
24.5485 +** the page number of the root of the table. After this routine returns,
24.5486 +** the root page is empty, but still exists.
24.5487 +**
24.5488 +** This routine will fail with SQLITE_LOCKED if there are any open
24.5489 +** read cursors on the table. Open write cursors are moved to the
24.5490 +** root of the table.
24.5491 +*/
24.5492 +int sqlite3BtreeClearTable(Btree *p, int iTable){
24.5493 + int rc;
24.5494 + BtShared *pBt = p->pBt;
24.5495 + if( p->inTrans!=TRANS_WRITE ){
24.5496 + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
24.5497 + }
24.5498 + rc = checkReadLocks(p, iTable, 0);
24.5499 + if( rc ){
24.5500 + return rc;
24.5501 + }
24.5502 +
24.5503 + /* Save the position of all cursors open on this table */
24.5504 + if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
24.5505 + return rc;
24.5506 + }
24.5507 +
24.5508 + return clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
24.5509 +}
24.5510 +
24.5511 +/*
24.5512 +** Erase all information in a table and add the root of the table to
24.5513 +** the freelist. Except, the root of the principle table (the one on
24.5514 +** page 1) is never added to the freelist.
24.5515 +**
24.5516 +** This routine will fail with SQLITE_LOCKED if there are any open
24.5517 +** cursors on the table.
24.5518 +**
24.5519 +** If AUTOVACUUM is enabled and the page at iTable is not the last
24.5520 +** root page in the database file, then the last root page
24.5521 +** in the database file is moved into the slot formerly occupied by
24.5522 +** iTable and that last slot formerly occupied by the last root page
24.5523 +** is added to the freelist instead of iTable. In this say, all
24.5524 +** root pages are kept at the beginning of the database file, which
24.5525 +** is necessary for AUTOVACUUM to work right. *piMoved is set to the
24.5526 +** page number that used to be the last root page in the file before
24.5527 +** the move. If no page gets moved, *piMoved is set to 0.
24.5528 +** The last root page is recorded in meta[3] and the value of
24.5529 +** meta[3] is updated by this procedure.
24.5530 +*/
24.5531 +int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
24.5532 + int rc;
24.5533 + MemPage *pPage = 0;
24.5534 + BtShared *pBt = p->pBt;
24.5535 +
24.5536 + if( p->inTrans!=TRANS_WRITE ){
24.5537 + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
24.5538 + }
24.5539 +
24.5540 + /* It is illegal to drop a table if any cursors are open on the
24.5541 + ** database. This is because in auto-vacuum mode the backend may
24.5542 + ** need to move another root-page to fill a gap left by the deleted
24.5543 + ** root page. If an open cursor was using this page a problem would
24.5544 + ** occur.
24.5545 + */
24.5546 + if( pBt->pCursor ){
24.5547 + return SQLITE_LOCKED;
24.5548 + }
24.5549 +
24.5550 + rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
24.5551 + if( rc ) return rc;
24.5552 + rc = sqlite3BtreeClearTable(p, iTable);
24.5553 + if( rc ){
24.5554 + releasePage(pPage);
24.5555 + return rc;
24.5556 + }
24.5557 +
24.5558 + *piMoved = 0;
24.5559 +
24.5560 + if( iTable>1 ){
24.5561 +#ifdef SQLITE_OMIT_AUTOVACUUM
24.5562 + rc = freePage(pPage);
24.5563 + releasePage(pPage);
24.5564 +#else
24.5565 + if( pBt->autoVacuum ){
24.5566 + Pgno maxRootPgno;
24.5567 + rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
24.5568 + if( rc!=SQLITE_OK ){
24.5569 + releasePage(pPage);
24.5570 + return rc;
24.5571 + }
24.5572 +
24.5573 + if( iTable==maxRootPgno ){
24.5574 + /* If the table being dropped is the table with the largest root-page
24.5575 + ** number in the database, put the root page on the free list.
24.5576 + */
24.5577 + rc = freePage(pPage);
24.5578 + releasePage(pPage);
24.5579 + if( rc!=SQLITE_OK ){
24.5580 + return rc;
24.5581 + }
24.5582 + }else{
24.5583 + /* The table being dropped does not have the largest root-page
24.5584 + ** number in the database. So move the page that does into the
24.5585 + ** gap left by the deleted root-page.
24.5586 + */
24.5587 + MemPage *pMove;
24.5588 + releasePage(pPage);
24.5589 + rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
24.5590 + if( rc!=SQLITE_OK ){
24.5591 + return rc;
24.5592 + }
24.5593 + rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
24.5594 + releasePage(pMove);
24.5595 + if( rc!=SQLITE_OK ){
24.5596 + return rc;
24.5597 + }
24.5598 + rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
24.5599 + if( rc!=SQLITE_OK ){
24.5600 + return rc;
24.5601 + }
24.5602 + rc = freePage(pMove);
24.5603 + releasePage(pMove);
24.5604 + if( rc!=SQLITE_OK ){
24.5605 + return rc;
24.5606 + }
24.5607 + *piMoved = maxRootPgno;
24.5608 + }
24.5609 +
24.5610 + /* Set the new 'max-root-page' value in the database header. This
24.5611 + ** is the old value less one, less one more if that happens to
24.5612 + ** be a root-page number, less one again if that is the
24.5613 + ** PENDING_BYTE_PAGE.
24.5614 + */
24.5615 + maxRootPgno--;
24.5616 + if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
24.5617 + maxRootPgno--;
24.5618 + }
24.5619 + if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
24.5620 + maxRootPgno--;
24.5621 + }
24.5622 + assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
24.5623 +
24.5624 + rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
24.5625 + }else{
24.5626 + rc = freePage(pPage);
24.5627 + releasePage(pPage);
24.5628 + }
24.5629 +#endif
24.5630 + }else{
24.5631 + /* If sqlite3BtreeDropTable was called on page 1. */
24.5632 + zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
24.5633 + releasePage(pPage);
24.5634 + }
24.5635 + return rc;
24.5636 +}
24.5637 +
24.5638 +
24.5639 +/*
24.5640 +** Read the meta-information out of a database file. Meta[0]
24.5641 +** is the number of free pages currently in the database. Meta[1]
24.5642 +** through meta[15] are available for use by higher layers. Meta[0]
24.5643 +** is read-only, the others are read/write.
24.5644 +**
24.5645 +** The schema layer numbers meta values differently. At the schema
24.5646 +** layer (and the SetCookie and ReadCookie opcodes) the number of
24.5647 +** free pages is not visible. So Cookie[0] is the same as Meta[1].
24.5648 +*/
24.5649 +int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
24.5650 + DbPage *pDbPage;
24.5651 + int rc;
24.5652 + unsigned char *pP1;
24.5653 + BtShared *pBt = p->pBt;
24.5654 +
24.5655 + /* Reading a meta-data value requires a read-lock on page 1 (and hence
24.5656 + ** the sqlite_master table. We grab this lock regardless of whether or
24.5657 + ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
24.5658 + ** 1 is treated as a special case by queryTableLock() and lockTable()).
24.5659 + */
24.5660 + rc = queryTableLock(p, 1, READ_LOCK);
24.5661 + if( rc!=SQLITE_OK ){
24.5662 + return rc;
24.5663 + }
24.5664 +
24.5665 + assert( idx>=0 && idx<=15 );
24.5666 + rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
24.5667 + if( rc ) return rc;
24.5668 + pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
24.5669 + *pMeta = get4byte(&pP1[36 + idx*4]);
24.5670 + sqlite3PagerUnref(pDbPage);
24.5671 +
24.5672 + /* If autovacuumed is disabled in this build but we are trying to
24.5673 + ** access an autovacuumed database, then make the database readonly.
24.5674 + */
24.5675 +#ifdef SQLITE_OMIT_AUTOVACUUM
24.5676 + if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
24.5677 +#endif
24.5678 +
24.5679 + /* Grab the read-lock on page 1. */
24.5680 + rc = lockTable(p, 1, READ_LOCK);
24.5681 + return rc;
24.5682 +}
24.5683 +
24.5684 +/*
24.5685 +** Write meta-information back into the database. Meta[0] is
24.5686 +** read-only and may not be written.
24.5687 +*/
24.5688 +int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
24.5689 + BtShared *pBt = p->pBt;
24.5690 + unsigned char *pP1;
24.5691 + int rc;
24.5692 + assert( idx>=1 && idx<=15 );
24.5693 + if( p->inTrans!=TRANS_WRITE ){
24.5694 + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
24.5695 + }
24.5696 + assert( pBt->pPage1!=0 );
24.5697 + pP1 = pBt->pPage1->aData;
24.5698 + rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
24.5699 + if( rc ) return rc;
24.5700 + put4byte(&pP1[36 + idx*4], iMeta);
24.5701 + if( idx==7 ){
24.5702 + assert( pBt->autoVacuum || iMeta==0 );
24.5703 + assert( iMeta==0 || iMeta==1 );
24.5704 + pBt->incrVacuum = iMeta;
24.5705 + }
24.5706 + return SQLITE_OK;
24.5707 +}
24.5708 +
24.5709 +/*
24.5710 +** Return the flag byte at the beginning of the page that the cursor
24.5711 +** is currently pointing to.
24.5712 +*/
24.5713 +int sqlite3BtreeFlags(BtCursor *pCur){
24.5714 + /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
24.5715 + ** restoreOrClearCursorPosition() here.
24.5716 + */
24.5717 + MemPage *pPage = pCur->pPage;
24.5718 + return pPage ? pPage->aData[pPage->hdrOffset] : 0;
24.5719 +}
24.5720 +
24.5721 +
24.5722 +/*
24.5723 +** Return the pager associated with a BTree. This routine is used for
24.5724 +** testing and debugging only.
24.5725 +*/
24.5726 +Pager *sqlite3BtreePager(Btree *p){
24.5727 + return p->pBt->pPager;
24.5728 +}
24.5729 +
24.5730 +#ifndef SQLITE_OMIT_INTEGRITY_CHECK
24.5731 +/*
24.5732 +** Append a message to the error message string.
24.5733 +*/
24.5734 +static void checkAppendMsg(
24.5735 + IntegrityCk *pCheck,
24.5736 + char *zMsg1,
24.5737 + const char *zFormat,
24.5738 + ...
24.5739 +){
24.5740 + va_list ap;
24.5741 + char *zMsg2;
24.5742 + if( !pCheck->mxErr ) return;
24.5743 + pCheck->mxErr--;
24.5744 + pCheck->nErr++;
24.5745 + va_start(ap, zFormat);
24.5746 + zMsg2 = sqlite3VMPrintf(zFormat, ap);
24.5747 + va_end(ap);
24.5748 + if( zMsg1==0 ) zMsg1 = "";
24.5749 + if( pCheck->zErrMsg ){
24.5750 + char *zOld = pCheck->zErrMsg;
24.5751 + pCheck->zErrMsg = 0;
24.5752 + sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
24.5753 + sqliteFree(zOld);
24.5754 + }else{
24.5755 + sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
24.5756 + }
24.5757 + sqliteFree(zMsg2);
24.5758 +}
24.5759 +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
24.5760 +
24.5761 +#ifndef SQLITE_OMIT_INTEGRITY_CHECK
24.5762 +/*
24.5763 +** Add 1 to the reference count for page iPage. If this is the second
24.5764 +** reference to the page, add an error message to pCheck->zErrMsg.
24.5765 +** Return 1 if there are 2 ore more references to the page and 0 if
24.5766 +** if this is the first reference to the page.
24.5767 +**
24.5768 +** Also check that the page number is in bounds.
24.5769 +*/
24.5770 +static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
24.5771 + if( iPage==0 ) return 1;
24.5772 + if( iPage>pCheck->nPage || iPage<0 ){
24.5773 + checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
24.5774 + return 1;
24.5775 + }
24.5776 + if( pCheck->anRef[iPage]==1 ){
24.5777 + checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
24.5778 + return 1;
24.5779 + }
24.5780 + return (pCheck->anRef[iPage]++)>1;
24.5781 +}
24.5782 +
24.5783 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.5784 +/*
24.5785 +** Check that the entry in the pointer-map for page iChild maps to
24.5786 +** page iParent, pointer type ptrType. If not, append an error message
24.5787 +** to pCheck.
24.5788 +*/
24.5789 +static void checkPtrmap(
24.5790 + IntegrityCk *pCheck, /* Integrity check context */
24.5791 + Pgno iChild, /* Child page number */
24.5792 + u8 eType, /* Expected pointer map type */
24.5793 + Pgno iParent, /* Expected pointer map parent page number */
24.5794 + char *zContext /* Context description (used for error msg) */
24.5795 +){
24.5796 + int rc;
24.5797 + u8 ePtrmapType;
24.5798 + Pgno iPtrmapParent;
24.5799 +
24.5800 + rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
24.5801 + if( rc!=SQLITE_OK ){
24.5802 + checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
24.5803 + return;
24.5804 + }
24.5805 +
24.5806 + if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
24.5807 + checkAppendMsg(pCheck, zContext,
24.5808 + "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
24.5809 + iChild, eType, iParent, ePtrmapType, iPtrmapParent);
24.5810 + }
24.5811 +}
24.5812 +#endif
24.5813 +
24.5814 +/*
24.5815 +** Check the integrity of the freelist or of an overflow page list.
24.5816 +** Verify that the number of pages on the list is N.
24.5817 +*/
24.5818 +static void checkList(
24.5819 + IntegrityCk *pCheck, /* Integrity checking context */
24.5820 + int isFreeList, /* True for a freelist. False for overflow page list */
24.5821 + int iPage, /* Page number for first page in the list */
24.5822 + int N, /* Expected number of pages in the list */
24.5823 + char *zContext /* Context for error messages */
24.5824 +){
24.5825 + int i;
24.5826 + int expected = N;
24.5827 + int iFirst = iPage;
24.5828 + while( N-- > 0 && pCheck->mxErr ){
24.5829 + DbPage *pOvflPage;
24.5830 + unsigned char *pOvflData;
24.5831 + if( iPage<1 ){
24.5832 + checkAppendMsg(pCheck, zContext,
24.5833 + "%d of %d pages missing from overflow list starting at %d",
24.5834 + N+1, expected, iFirst);
24.5835 + break;
24.5836 + }
24.5837 + if( checkRef(pCheck, iPage, zContext) ) break;
24.5838 + if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
24.5839 + checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
24.5840 + break;
24.5841 + }
24.5842 + pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
24.5843 + if( isFreeList ){
24.5844 + int n = get4byte(&pOvflData[4]);
24.5845 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.5846 + if( pCheck->pBt->autoVacuum ){
24.5847 + checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
24.5848 + }
24.5849 +#endif
24.5850 + if( n>pCheck->pBt->usableSize/4-8 ){
24.5851 + checkAppendMsg(pCheck, zContext,
24.5852 + "freelist leaf count too big on page %d", iPage);
24.5853 + N--;
24.5854 + }else{
24.5855 + for(i=0; i<n; i++){
24.5856 + Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
24.5857 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.5858 + if( pCheck->pBt->autoVacuum ){
24.5859 + checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
24.5860 + }
24.5861 +#endif
24.5862 + checkRef(pCheck, iFreePage, zContext);
24.5863 + }
24.5864 + N -= n;
24.5865 + }
24.5866 + }
24.5867 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.5868 + else{
24.5869 + /* If this database supports auto-vacuum and iPage is not the last
24.5870 + ** page in this overflow list, check that the pointer-map entry for
24.5871 + ** the following page matches iPage.
24.5872 + */
24.5873 + if( pCheck->pBt->autoVacuum && N>0 ){
24.5874 + i = get4byte(pOvflData);
24.5875 + checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
24.5876 + }
24.5877 + }
24.5878 +#endif
24.5879 + iPage = get4byte(pOvflData);
24.5880 + sqlite3PagerUnref(pOvflPage);
24.5881 + }
24.5882 +}
24.5883 +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
24.5884 +
24.5885 +#ifndef SQLITE_OMIT_INTEGRITY_CHECK
24.5886 +/*
24.5887 +** Do various sanity checks on a single page of a tree. Return
24.5888 +** the tree depth. Root pages return 0. Parents of root pages
24.5889 +** return 1, and so forth.
24.5890 +**
24.5891 +** These checks are done:
24.5892 +**
24.5893 +** 1. Make sure that cells and freeblocks do not overlap
24.5894 +** but combine to completely cover the page.
24.5895 +** NO 2. Make sure cell keys are in order.
24.5896 +** NO 3. Make sure no key is less than or equal to zLowerBound.
24.5897 +** NO 4. Make sure no key is greater than or equal to zUpperBound.
24.5898 +** 5. Check the integrity of overflow pages.
24.5899 +** 6. Recursively call checkTreePage on all children.
24.5900 +** 7. Verify that the depth of all children is the same.
24.5901 +** 8. Make sure this page is at least 33% full or else it is
24.5902 +** the root of the tree.
24.5903 +*/
24.5904 +static int checkTreePage(
24.5905 + IntegrityCk *pCheck, /* Context for the sanity check */
24.5906 + int iPage, /* Page number of the page to check */
24.5907 + MemPage *pParent, /* Parent page */
24.5908 + char *zParentContext /* Parent context */
24.5909 +){
24.5910 + MemPage *pPage;
24.5911 + int i, rc, depth, d2, pgno, cnt;
24.5912 + int hdr, cellStart;
24.5913 + int nCell;
24.5914 + u8 *data;
24.5915 + BtShared *pBt;
24.5916 + int usableSize;
24.5917 + char zContext[100];
24.5918 + char *hit;
24.5919 +
24.5920 + sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
24.5921 +
24.5922 + /* Check that the page exists
24.5923 + */
24.5924 + pBt = pCheck->pBt;
24.5925 + usableSize = pBt->usableSize;
24.5926 + if( iPage==0 ) return 0;
24.5927 + if( checkRef(pCheck, iPage, zParentContext) ) return 0;
24.5928 + if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
24.5929 + checkAppendMsg(pCheck, zContext,
24.5930 + "unable to get the page. error code=%d", rc);
24.5931 + return 0;
24.5932 + }
24.5933 + if( (rc = sqlite3BtreeInitPage(pPage, pParent))!=0 ){
24.5934 + checkAppendMsg(pCheck, zContext,
24.5935 + "sqlite3BtreeInitPage() returns error code %d", rc);
24.5936 + releasePage(pPage);
24.5937 + return 0;
24.5938 + }
24.5939 +
24.5940 + /* Check out all the cells.
24.5941 + */
24.5942 + depth = 0;
24.5943 + for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
24.5944 + u8 *pCell;
24.5945 + int sz;
24.5946 + CellInfo info;
24.5947 +
24.5948 + /* Check payload overflow pages
24.5949 + */
24.5950 + sqlite3_snprintf(sizeof(zContext), zContext,
24.5951 + "On tree page %d cell %d: ", iPage, i);
24.5952 + pCell = findCell(pPage,i);
24.5953 + sqlite3BtreeParseCellPtr(pPage, pCell, &info);
24.5954 + sz = info.nData;
24.5955 + if( !pPage->intKey ) sz += info.nKey;
24.5956 + assert( sz==info.nPayload );
24.5957 + if( sz>info.nLocal ){
24.5958 + int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
24.5959 + Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
24.5960 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.5961 + if( pBt->autoVacuum ){
24.5962 + checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
24.5963 + }
24.5964 +#endif
24.5965 + checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
24.5966 + }
24.5967 +
24.5968 + /* Check sanity of left child page.
24.5969 + */
24.5970 + if( !pPage->leaf ){
24.5971 + pgno = get4byte(pCell);
24.5972 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.5973 + if( pBt->autoVacuum ){
24.5974 + checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
24.5975 + }
24.5976 +#endif
24.5977 + d2 = checkTreePage(pCheck,pgno,pPage,zContext);
24.5978 + if( i>0 && d2!=depth ){
24.5979 + checkAppendMsg(pCheck, zContext, "Child page depth differs");
24.5980 + }
24.5981 + depth = d2;
24.5982 + }
24.5983 + }
24.5984 + if( !pPage->leaf ){
24.5985 + pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
24.5986 + sqlite3_snprintf(sizeof(zContext), zContext,
24.5987 + "On page %d at right child: ", iPage);
24.5988 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.5989 + if( pBt->autoVacuum ){
24.5990 + checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
24.5991 + }
24.5992 +#endif
24.5993 + checkTreePage(pCheck, pgno, pPage, zContext);
24.5994 + }
24.5995 +
24.5996 + /* Check for complete coverage of the page
24.5997 + */
24.5998 + data = pPage->aData;
24.5999 + hdr = pPage->hdrOffset;
24.6000 + hit = sqliteMalloc( usableSize );
24.6001 + if( hit ){
24.6002 + memset(hit, 1, get2byte(&data[hdr+5]));
24.6003 + nCell = get2byte(&data[hdr+3]);
24.6004 + cellStart = hdr + 12 - 4*pPage->leaf;
24.6005 + for(i=0; i<nCell; i++){
24.6006 + int pc = get2byte(&data[cellStart+i*2]);
24.6007 + int size = cellSizePtr(pPage, &data[pc]);
24.6008 + int j;
24.6009 + if( (pc+size-1)>=usableSize || pc<0 ){
24.6010 + checkAppendMsg(pCheck, 0,
24.6011 + "Corruption detected in cell %d on page %d",i,iPage,0);
24.6012 + }else{
24.6013 + for(j=pc+size-1; j>=pc; j--) hit[j]++;
24.6014 + }
24.6015 + }
24.6016 + for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
24.6017 + cnt++){
24.6018 + int size = get2byte(&data[i+2]);
24.6019 + int j;
24.6020 + if( (i+size-1)>=usableSize || i<0 ){
24.6021 + checkAppendMsg(pCheck, 0,
24.6022 + "Corruption detected in cell %d on page %d",i,iPage,0);
24.6023 + }else{
24.6024 + for(j=i+size-1; j>=i; j--) hit[j]++;
24.6025 + }
24.6026 + i = get2byte(&data[i]);
24.6027 + }
24.6028 + for(i=cnt=0; i<usableSize; i++){
24.6029 + if( hit[i]==0 ){
24.6030 + cnt++;
24.6031 + }else if( hit[i]>1 ){
24.6032 + checkAppendMsg(pCheck, 0,
24.6033 + "Multiple uses for byte %d of page %d", i, iPage);
24.6034 + break;
24.6035 + }
24.6036 + }
24.6037 + if( cnt!=data[hdr+7] ){
24.6038 + checkAppendMsg(pCheck, 0,
24.6039 + "Fragmented space is %d byte reported as %d on page %d",
24.6040 + cnt, data[hdr+7], iPage);
24.6041 + }
24.6042 + }
24.6043 + sqliteFree(hit);
24.6044 +
24.6045 + releasePage(pPage);
24.6046 + return depth+1;
24.6047 +}
24.6048 +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
24.6049 +
24.6050 +#ifndef SQLITE_OMIT_INTEGRITY_CHECK
24.6051 +/*
24.6052 +** This routine does a complete check of the given BTree file. aRoot[] is
24.6053 +** an array of pages numbers were each page number is the root page of
24.6054 +** a table. nRoot is the number of entries in aRoot.
24.6055 +**
24.6056 +** If everything checks out, this routine returns NULL. If something is
24.6057 +** amiss, an error message is written into memory obtained from malloc()
24.6058 +** and a pointer to that error message is returned. The calling function
24.6059 +** is responsible for freeing the error message when it is done.
24.6060 +*/
24.6061 +char *sqlite3BtreeIntegrityCheck(
24.6062 + Btree *p, /* The btree to be checked */
24.6063 + int *aRoot, /* An array of root pages numbers for individual trees */
24.6064 + int nRoot, /* Number of entries in aRoot[] */
24.6065 + int mxErr, /* Stop reporting errors after this many */
24.6066 + int *pnErr /* Write number of errors seen to this variable */
24.6067 +){
24.6068 + int i;
24.6069 + int nRef;
24.6070 + IntegrityCk sCheck;
24.6071 + BtShared *pBt = p->pBt;
24.6072 +
24.6073 + nRef = sqlite3PagerRefcount(pBt->pPager);
24.6074 + if( lockBtreeWithRetry(p)!=SQLITE_OK ){
24.6075 + return sqliteStrDup("Unable to acquire a read lock on the database");
24.6076 + }
24.6077 + sCheck.pBt = pBt;
24.6078 + sCheck.pPager = pBt->pPager;
24.6079 + sCheck.nPage = sqlite3PagerPagecount(sCheck.pPager);
24.6080 + sCheck.mxErr = mxErr;
24.6081 + sCheck.nErr = 0;
24.6082 + *pnErr = 0;
24.6083 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.6084 + if( pBt->nTrunc!=0 ){
24.6085 + sCheck.nPage = pBt->nTrunc;
24.6086 + }
24.6087 +#endif
24.6088 + if( sCheck.nPage==0 ){
24.6089 + unlockBtreeIfUnused(pBt);
24.6090 + return 0;
24.6091 + }
24.6092 + sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
24.6093 + if( !sCheck.anRef ){
24.6094 + unlockBtreeIfUnused(pBt);
24.6095 + *pnErr = 1;
24.6096 + return sqlite3MPrintf("Unable to malloc %d bytes",
24.6097 + (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
24.6098 + }
24.6099 + for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
24.6100 + i = PENDING_BYTE_PAGE(pBt);
24.6101 + if( i<=sCheck.nPage ){
24.6102 + sCheck.anRef[i] = 1;
24.6103 + }
24.6104 + sCheck.zErrMsg = 0;
24.6105 +
24.6106 + /* Check the integrity of the freelist
24.6107 + */
24.6108 + checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
24.6109 + get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
24.6110 +
24.6111 + /* Check all the tables.
24.6112 + */
24.6113 + for(i=0; i<nRoot && sCheck.mxErr; i++){
24.6114 + if( aRoot[i]==0 ) continue;
24.6115 +#ifndef SQLITE_OMIT_AUTOVACUUM
24.6116 + if( pBt->autoVacuum && aRoot[i]>1 ){
24.6117 + checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
24.6118 + }
24.6119 +#endif
24.6120 + checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ");
24.6121 + }
24.6122 +
24.6123 + /* Make sure every page in the file is referenced
24.6124 + */
24.6125 + for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
24.6126 +#ifdef SQLITE_OMIT_AUTOVACUUM
24.6127 + if( sCheck.anRef[i]==0 ){
24.6128 + checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
24.6129 + }
24.6130 +#else
24.6131 + /* If the database supports auto-vacuum, make sure no tables contain
24.6132 + ** references to pointer-map pages.
24.6133 + */
24.6134 + if( sCheck.anRef[i]==0 &&
24.6135 + (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
24.6136 + checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
24.6137 + }
24.6138 + if( sCheck.anRef[i]!=0 &&
24.6139 + (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
24.6140 + checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
24.6141 + }
24.6142 +#endif
24.6143 + }
24.6144 +
24.6145 + /* Make sure this analysis did not leave any unref() pages
24.6146 + */
24.6147 + unlockBtreeIfUnused(pBt);
24.6148 + if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
24.6149 + checkAppendMsg(&sCheck, 0,
24.6150 + "Outstanding page count goes from %d to %d during this analysis",
24.6151 + nRef, sqlite3PagerRefcount(pBt->pPager)
24.6152 + );
24.6153 + }
24.6154 +
24.6155 + /* Clean up and report errors.
24.6156 + */
24.6157 + sqliteFree(sCheck.anRef);
24.6158 + *pnErr = sCheck.nErr;
24.6159 + return sCheck.zErrMsg;
24.6160 +}
24.6161 +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
24.6162 +
24.6163 +/*
24.6164 +** Return the full pathname of the underlying database file.
24.6165 +*/
24.6166 +const char *sqlite3BtreeGetFilename(Btree *p){
24.6167 + assert( p->pBt->pPager!=0 );
24.6168 + return sqlite3PagerFilename(p->pBt->pPager);
24.6169 +}
24.6170 +
24.6171 +/*
24.6172 +** Return the pathname of the directory that contains the database file.
24.6173 +*/
24.6174 +const char *sqlite3BtreeGetDirname(Btree *p){
24.6175 + assert( p->pBt->pPager!=0 );
24.6176 + return sqlite3PagerDirname(p->pBt->pPager);
24.6177 +}
24.6178 +
24.6179 +/*
24.6180 +** Return the pathname of the journal file for this database. The return
24.6181 +** value of this routine is the same regardless of whether the journal file
24.6182 +** has been created or not.
24.6183 +*/
24.6184 +const char *sqlite3BtreeGetJournalname(Btree *p){
24.6185 + assert( p->pBt->pPager!=0 );
24.6186 + return sqlite3PagerJournalname(p->pBt->pPager);
24.6187 +}
24.6188 +
24.6189 +#ifndef SQLITE_OMIT_VACUUM
24.6190 +/*
24.6191 +** Copy the complete content of pBtFrom into pBtTo. A transaction
24.6192 +** must be active for both files.
24.6193 +**
24.6194 +** The size of file pBtFrom may be reduced by this operation.
24.6195 +** If anything goes wrong, the transaction on pBtFrom is rolled back.
24.6196 +*/
24.6197 +int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
24.6198 + int rc = SQLITE_OK;
24.6199 + Pgno i, nPage, nToPage, iSkip;
24.6200 +
24.6201 + BtShared *pBtTo = pTo->pBt;
24.6202 + BtShared *pBtFrom = pFrom->pBt;
24.6203 +
24.6204 + if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
24.6205 + return SQLITE_ERROR;
24.6206 + }
24.6207 + if( pBtTo->pCursor ) return SQLITE_BUSY;
24.6208 + nToPage = sqlite3PagerPagecount(pBtTo->pPager);
24.6209 + nPage = sqlite3PagerPagecount(pBtFrom->pPager);
24.6210 + iSkip = PENDING_BYTE_PAGE(pBtTo);
24.6211 + for(i=1; rc==SQLITE_OK && i<=nPage; i++){
24.6212 + DbPage *pDbPage;
24.6213 + if( i==iSkip ) continue;
24.6214 + rc = sqlite3PagerGet(pBtFrom->pPager, i, &pDbPage);
24.6215 + if( rc ) break;
24.6216 + rc = sqlite3PagerOverwrite(pBtTo->pPager, i, sqlite3PagerGetData(pDbPage));
24.6217 + sqlite3PagerUnref(pDbPage);
24.6218 + }
24.6219 +
24.6220 + /* If the file is shrinking, journal the pages that are being truncated
24.6221 + ** so that they can be rolled back if the commit fails.
24.6222 + */
24.6223 + for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
24.6224 + DbPage *pDbPage;
24.6225 + if( i==iSkip ) continue;
24.6226 + rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
24.6227 + if( rc ) break;
24.6228 + rc = sqlite3PagerWrite(pDbPage);
24.6229 + sqlite3PagerDontWrite(pDbPage);
24.6230 + /* Yeah. It seems wierd to call DontWrite() right after Write(). But
24.6231 + ** that is because the names of those procedures do not exactly
24.6232 + ** represent what they do. Write() really means "put this page in the
24.6233 + ** rollback journal and mark it as dirty so that it will be written
24.6234 + ** to the database file later." DontWrite() undoes the second part of
24.6235 + ** that and prevents the page from being written to the database. The
24.6236 + ** page is still on the rollback journal, though. And that is the whole
24.6237 + ** point of this loop: to put pages on the rollback journal. */
24.6238 + sqlite3PagerUnref(pDbPage);
24.6239 + }
24.6240 + if( !rc && nPage<nToPage ){
24.6241 + rc = sqlite3PagerTruncate(pBtTo->pPager, nPage);
24.6242 + }
24.6243 +
24.6244 + if( rc ){
24.6245 + sqlite3BtreeRollback(pTo);
24.6246 + }
24.6247 + return rc;
24.6248 +}
24.6249 +#endif /* SQLITE_OMIT_VACUUM */
24.6250 +
24.6251 +/*
24.6252 +** Return non-zero if a transaction is active.
24.6253 +*/
24.6254 +int sqlite3BtreeIsInTrans(Btree *p){
24.6255 + return (p && (p->inTrans==TRANS_WRITE));
24.6256 +}
24.6257 +
24.6258 +/*
24.6259 +** Return non-zero if a statement transaction is active.
24.6260 +*/
24.6261 +int sqlite3BtreeIsInStmt(Btree *p){
24.6262 + return (p->pBt && p->pBt->inStmt);
24.6263 +}
24.6264 +
24.6265 +/*
24.6266 +** Return non-zero if a read (or write) transaction is active.
24.6267 +*/
24.6268 +int sqlite3BtreeIsInReadTrans(Btree *p){
24.6269 + return (p && (p->inTrans!=TRANS_NONE));
24.6270 +}
24.6271 +
24.6272 +/*
24.6273 +** This function returns a pointer to a blob of memory associated with
24.6274 +** a single shared-btree. The memory is used by client code for it's own
24.6275 +** purposes (for example, to store a high-level schema associated with
24.6276 +** the shared-btree). The btree layer manages reference counting issues.
24.6277 +**
24.6278 +** The first time this is called on a shared-btree, nBytes bytes of memory
24.6279 +** are allocated, zeroed, and returned to the caller. For each subsequent
24.6280 +** call the nBytes parameter is ignored and a pointer to the same blob
24.6281 +** of memory returned.
24.6282 +**
24.6283 +** Just before the shared-btree is closed, the function passed as the
24.6284 +** xFree argument when the memory allocation was made is invoked on the
24.6285 +** blob of allocated memory. This function should not call sqliteFree()
24.6286 +** on the memory, the btree layer does that.
24.6287 +*/
24.6288 +void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
24.6289 + BtShared *pBt = p->pBt;
24.6290 + if( !pBt->pSchema ){
24.6291 + pBt->pSchema = sqliteMalloc(nBytes);
24.6292 + pBt->xFreeSchema = xFree;
24.6293 + }
24.6294 + return pBt->pSchema;
24.6295 +}
24.6296 +
24.6297 +/*
24.6298 +** Return true if another user of the same shared btree as the argument
24.6299 +** handle holds an exclusive lock on the sqlite_master table.
24.6300 +*/
24.6301 +int sqlite3BtreeSchemaLocked(Btree *p){
24.6302 + return (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
24.6303 +}
24.6304 +
24.6305 +
24.6306 +#ifndef SQLITE_OMIT_SHARED_CACHE
24.6307 +/*
24.6308 +** Obtain a lock on the table whose root page is iTab. The
24.6309 +** lock is a write lock if isWritelock is true or a read lock
24.6310 +** if it is false.
24.6311 +*/
24.6312 +int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
24.6313 + int rc = SQLITE_OK;
24.6314 + u8 lockType = (isWriteLock?WRITE_LOCK:READ_LOCK);
24.6315 + rc = queryTableLock(p, iTab, lockType);
24.6316 + if( rc==SQLITE_OK ){
24.6317 + rc = lockTable(p, iTab, lockType);
24.6318 + }
24.6319 + return rc;
24.6320 +}
24.6321 +#endif
24.6322 +
24.6323 +#ifndef SQLITE_OMIT_INCRBLOB
24.6324 +/*
24.6325 +** Argument pCsr must be a cursor opened for writing on an
24.6326 +** INTKEY table currently pointing at a valid table entry.
24.6327 +** This function modifies the data stored as part of that entry.
24.6328 +** Only the data content may only be modified, it is not possible
24.6329 +** to change the length of the data stored.
24.6330 +*/
24.6331 +int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
24.6332 +
24.6333 + assert(pCsr->isIncrblobHandle);
24.6334 + if( pCsr->eState==CURSOR_REQUIRESEEK ){
24.6335 + return SQLITE_ABORT;
24.6336 + }
24.6337 +
24.6338 + /* Check some preconditions:
24.6339 + ** (a) the cursor is open for writing,
24.6340 + ** (b) there is no read-lock on the table being modified and
24.6341 + ** (c) the cursor points at a valid row of an intKey table.
24.6342 + */
24.6343 + if( !pCsr->wrFlag ){
24.6344 + return SQLITE_READONLY;
24.6345 + }
24.6346 + assert( !pCsr->pBtree->pBt->readOnly
24.6347 + && pCsr->pBtree->pBt->inTransaction==TRANS_WRITE );
24.6348 + if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr) ){
24.6349 + return SQLITE_LOCKED; /* The table pCur points to has a read lock */
24.6350 + }
24.6351 + if( pCsr->eState==CURSOR_INVALID || !pCsr->pPage->intKey ){
24.6352 + return SQLITE_ERROR;
24.6353 + }
24.6354 +
24.6355 + return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
24.6356 +}
24.6357 +
24.6358 +/*
24.6359 +** Set a flag on this cursor to cache the locations of pages from the
24.6360 +** overflow list for the current row. This is used by cursors opened
24.6361 +** for incremental blob IO only.
24.6362 +**
24.6363 +** This function sets a flag only. The actual page location cache
24.6364 +** (stored in BtCursor.aOverflow[]) is allocated and used by function
24.6365 +** accessPayload() (the worker function for sqlite3BtreeData() and
24.6366 +** sqlite3BtreePutData()).
24.6367 +*/
24.6368 +void sqlite3BtreeCacheOverflow(BtCursor *pCur){
24.6369 + assert(!pCur->isIncrblobHandle);
24.6370 + assert(!pCur->aOverflow);
24.6371 + pCur->isIncrblobHandle = 1;
24.6372 +}
24.6373 +#endif
25.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
25.2 +++ b/extensions/sqlite/sqlite-source/btree.h Sun Jul 29 01:15:31 2007 +0000
25.3 @@ -0,0 +1,149 @@
25.4 +/*
25.5 +** 2001 September 15
25.6 +**
25.7 +** The author disclaims copyright to this source code. In place of
25.8 +** a legal notice, here is a blessing:
25.9 +**
25.10 +** May you do good and not evil.
25.11 +** May you find forgiveness for yourself and forgive others.
25.12 +** May you share freely, never taking more than you give.
25.13 +**
25.14 +*************************************************************************
25.15 +** This header file defines the interface that the sqlite B-Tree file
25.16 +** subsystem. See comments in the source code for a detailed description
25.17 +** of what each interface routine does.
25.18 +**
25.19 +** @(#) $Id$
25.20 +*/
25.21 +#ifndef _BTREE_H_
25.22 +#define _BTREE_H_
25.23 +
25.24 +/* TODO: This definition is just included so other modules compile. It
25.25 +** needs to be revisited.
25.26 +*/
25.27 +#define SQLITE_N_BTREE_META 10
25.28 +
25.29 +/*
25.30 +** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
25.31 +** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
25.32 +*/
25.33 +#ifndef SQLITE_DEFAULT_AUTOVACUUM
25.34 + #define SQLITE_DEFAULT_AUTOVACUUM 0
25.35 +#endif
25.36 +
25.37 +#define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
25.38 +#define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
25.39 +#define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
25.40 +
25.41 +/*
25.42 +** Forward declarations of structure
25.43 +*/
25.44 +typedef struct Btree Btree;
25.45 +typedef struct BtCursor BtCursor;
25.46 +typedef struct BtShared BtShared;
25.47 +
25.48 +
25.49 +int sqlite3BtreeOpen(
25.50 + const char *zFilename, /* Name of database file to open */
25.51 + sqlite3 *db, /* Associated database connection */
25.52 + Btree **, /* Return open Btree* here */
25.53 + int flags /* Flags */
25.54 +);
25.55 +
25.56 +/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
25.57 +** following values.
25.58 +**
25.59 +** NOTE: These values must match the corresponding PAGER_ values in
25.60 +** pager.h.
25.61 +*/
25.62 +#define BTREE_OMIT_JOURNAL 1 /* Do not use journal. No argument */
25.63 +#define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */
25.64 +#define BTREE_MEMORY 4 /* In-memory DB. No argument */
25.65 +
25.66 +int sqlite3BtreeClose(Btree*);
25.67 +int sqlite3BtreeSetBusyHandler(Btree*,BusyHandler*);
25.68 +int sqlite3BtreeSetCacheSize(Btree*,int);
25.69 +int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
25.70 +int sqlite3BtreeSyncDisabled(Btree*);
25.71 +int sqlite3BtreeSetPageSize(Btree*,int,int);
25.72 +int sqlite3BtreeGetPageSize(Btree*);
25.73 +int sqlite3BtreeMaxPageCount(Btree*,int);
25.74 +int sqlite3BtreeGetReserve(Btree*);
25.75 +int sqlite3BtreeSetAutoVacuum(Btree *, int);
25.76 +int sqlite3BtreeGetAutoVacuum(Btree *);
25.77 +int sqlite3BtreeBeginTrans(Btree*,int);
25.78 +int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
25.79 +int sqlite3BtreeCommitPhaseTwo(Btree*);
25.80 +int sqlite3BtreeCommit(Btree*);
25.81 +int sqlite3BtreeRollback(Btree*);
25.82 +int sqlite3BtreeBeginStmt(Btree*);
25.83 +int sqlite3BtreeCommitStmt(Btree*);
25.84 +int sqlite3BtreeRollbackStmt(Btree*);
25.85 +int sqlite3BtreeCreateTable(Btree*, int*, int flags);
25.86 +int sqlite3BtreeIsInTrans(Btree*);
25.87 +int sqlite3BtreeIsInStmt(Btree*);
25.88 +int sqlite3BtreeIsInReadTrans(Btree*);
25.89 +void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
25.90 +int sqlite3BtreeSchemaLocked(Btree *);
25.91 +int sqlite3BtreeLockTable(Btree *, int, u8);
25.92 +
25.93 +const char *sqlite3BtreeGetFilename(Btree *);
25.94 +const char *sqlite3BtreeGetDirname(Btree *);
25.95 +const char *sqlite3BtreeGetJournalname(Btree *);
25.96 +int sqlite3BtreeCopyFile(Btree *, Btree *);
25.97 +
25.98 +int sqlite3BtreeIncrVacuum(Btree *);
25.99 +
25.100 +/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
25.101 +** of the following flags:
25.102 +*/
25.103 +#define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
25.104 +#define BTREE_ZERODATA 2 /* Table has keys only - no data */
25.105 +#define BTREE_LEAFDATA 4 /* Data stored in leaves only. Implies INTKEY */
25.106 +
25.107 +int sqlite3BtreeDropTable(Btree*, int, int*);
25.108 +int sqlite3BtreeClearTable(Btree*, int);
25.109 +int sqlite3BtreeGetMeta(Btree*, int idx, u32 *pValue);
25.110 +int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
25.111 +
25.112 +int sqlite3BtreeCursor(
25.113 + Btree*, /* BTree containing table to open */
25.114 + int iTable, /* Index of root page */
25.115 + int wrFlag, /* 1 for writing. 0 for read-only */
25.116 + int(*)(void*,int,const void*,int,const void*), /* Key comparison function */
25.117 + void*, /* First argument to compare function */
25.118 + BtCursor **ppCursor /* Returned cursor */
25.119 +);
25.120 +
25.121 +int sqlite3BtreeCloseCursor(BtCursor*);
25.122 +int sqlite3BtreeMoveto(BtCursor*,const void *pKey,i64 nKey,int bias,int *pRes);
25.123 +int sqlite3BtreeDelete(BtCursor*);
25.124 +int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
25.125 + const void *pData, int nData,
25.126 + int nZero, int bias);
25.127 +int sqlite3BtreeFirst(BtCursor*, int *pRes);
25.128 +int sqlite3BtreeLast(BtCursor*, int *pRes);
25.129 +int sqlite3BtreeNext(BtCursor*, int *pRes);
25.130 +int sqlite3BtreeEof(BtCursor*);
25.131 +int sqlite3BtreeFlags(BtCursor*);
25.132 +int sqlite3BtreePrevious(BtCursor*, int *pRes);
25.133 +int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
25.134 +int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
25.135 +const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
25.136 +const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
25.137 +int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
25.138 +int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
25.139 +
25.140 +char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
25.141 +struct Pager *sqlite3BtreePager(Btree*);
25.142 +
25.143 +int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
25.144 +void sqlite3BtreeCacheOverflow(BtCursor *);
25.145 +
25.146 +#ifdef SQLITE_TEST
25.147 +int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
25.148 +void sqlite3BtreeCursorList(Btree*);
25.149 +int sqlite3BtreePageDump(Btree*, int, int recursive);
25.150 +#endif
25.151 +
25.152 +#endif /* _BTREE_H_ */
26.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
26.2 +++ b/extensions/sqlite/sqlite-source/btreeInt.h Sun Jul 29 01:15:31 2007 +0000
26.3 @@ -0,0 +1,588 @@
26.4 +/*
26.5 +** 2004 April 6
26.6 +**
26.7 +** The author disclaims copyright to this source code. In place of
26.8 +** a legal notice, here is a blessing:
26.9 +**
26.10 +** May you do good and not evil.
26.11 +** May you find forgiveness for yourself and forgive others.
26.12 +** May you share freely, never taking more than you give.
26.13 +**
26.14 +*************************************************************************
26.15 +** $Id$
26.16 +**
26.17 +** This file implements a external (disk-based) database using BTrees.
26.18 +** For a detailed discussion of BTrees, refer to
26.19 +**
26.20 +** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
26.21 +** "Sorting And Searching", pages 473-480. Addison-Wesley
26.22 +** Publishing Company, Reading, Massachusetts.
26.23 +**
26.24 +** The basic idea is that each page of the file contains N database
26.25 +** entries and N+1 pointers to subpages.
26.26 +**
26.27 +** ----------------------------------------------------------------
26.28 +** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
26.29 +** ----------------------------------------------------------------
26.30 +**
26.31 +** All of the keys on the page that Ptr(0) points to have values less
26.32 +** than Key(0). All of the keys on page Ptr(1) and its subpages have
26.33 +** values greater than Key(0) and less than Key(1). All of the keys
26.34 +** on Ptr(N) and its subpages have values greater than Key(N-1). And
26.35 +** so forth.
26.36 +**
26.37 +** Finding a particular key requires reading O(log(M)) pages from the
26.38 +** disk where M is the number of entries in the tree.
26.39 +**
26.40 +** In this implementation, a single file can hold one or more separate
26.41 +** BTrees. Each BTree is identified by the index of its root page. The
26.42 +** key and data for any entry are combined to form the "payload". A
26.43 +** fixed amount of payload can be carried directly on the database
26.44 +** page. If the payload is larger than the preset amount then surplus
26.45 +** bytes are stored on overflow pages. The payload for an entry
26.46 +** and the preceding pointer are combined to form a "Cell". Each
26.47 +** page has a small header which contains the Ptr(N) pointer and other
26.48 +** information such as the size of key and data.
26.49 +**
26.50 +** FORMAT DETAILS
26.51 +**
26.52 +** The file is divided into pages. The first page is called page 1,
26.53 +** the second is page 2, and so forth. A page number of zero indicates
26.54 +** "no such page". The page size can be anything between 512 and 65536.
26.55 +** Each page can be either a btree page, a freelist page or an overflow
26.56 +** page.
26.57 +**
26.58 +** The first page is always a btree page. The first 100 bytes of the first
26.59 +** page contain a special header (the "file header") that describes the file.
26.60 +** The format of the file header is as follows:
26.61 +**
26.62 +** OFFSET SIZE DESCRIPTION
26.63 +** 0 16 Header string: "SQLite format 3\000"
26.64 +** 16 2 Page size in bytes.
26.65 +** 18 1 File format write version
26.66 +** 19 1 File format read version
26.67 +** 20 1 Bytes of unused space at the end of each page
26.68 +** 21 1 Max embedded payload fraction
26.69 +** 22 1 Min embedded payload fraction
26.70 +** 23 1 Min leaf payload fraction
26.71 +** 24 4 File change counter
26.72 +** 28 4 Reserved for future use
26.73 +** 32 4 First freelist page
26.74 +** 36 4 Number of freelist pages in the file
26.75 +** 40 60 15 4-byte meta values passed to higher layers
26.76 +**
26.77 +** All of the integer values are big-endian (most significant byte first).
26.78 +**
26.79 +** The file change counter is incremented when the database is changed
26.80 +** This counter allows other processes to know when the file has changed
26.81 +** and thus when they need to flush their cache.
26.82 +**
26.83 +** The max embedded payload fraction is the amount of the total usable
26.84 +** space in a page that can be consumed by a single cell for standard
26.85 +** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
26.86 +** is to limit the maximum cell size so that at least 4 cells will fit
26.87 +** on one page. Thus the default max embedded payload fraction is 64.
26.88 +**
26.89 +** If the payload for a cell is larger than the max payload, then extra
26.90 +** payload is spilled to overflow pages. Once an overflow page is allocated,
26.91 +** as many bytes as possible are moved into the overflow pages without letting
26.92 +** the cell size drop below the min embedded payload fraction.
26.93 +**
26.94 +** The min leaf payload fraction is like the min embedded payload fraction
26.95 +** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
26.96 +** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
26.97 +** not specified in the header.
26.98 +**
26.99 +** Each btree pages is divided into three sections: The header, the
26.100 +** cell pointer array, and the cell content area. Page 1 also has a 100-byte
26.101 +** file header that occurs before the page header.
26.102 +**
26.103 +** |----------------|
26.104 +** | file header | 100 bytes. Page 1 only.
26.105 +** |----------------|
26.106 +** | page header | 8 bytes for leaves. 12 bytes for interior nodes
26.107 +** |----------------|
26.108 +** | cell pointer | | 2 bytes per cell. Sorted order.
26.109 +** | array | | Grows downward
26.110 +** | | v
26.111 +** |----------------|
26.112 +** | unallocated |
26.113 +** | space |
26.114 +** |----------------| ^ Grows upwards
26.115 +** | cell content | | Arbitrary order interspersed with freeblocks.
26.116 +** | area | | and free space fragments.
26.117 +** |----------------|
26.118 +**
26.119 +** The page headers looks like this:
26.120 +**
26.121 +** OFFSET SIZE DESCRIPTION
26.122 +** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
26.123 +** 1 2 byte offset to the first freeblock
26.124 +** 3 2 number of cells on this page
26.125 +** 5 2 first byte of the cell content area
26.126 +** 7 1 number of fragmented free bytes
26.127 +** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
26.128 +**
26.129 +** The flags define the format of this btree page. The leaf flag means that
26.130 +** this page has no children. The zerodata flag means that this page carries
26.131 +** only keys and no data. The intkey flag means that the key is a integer
26.132 +** which is stored in the key size entry of the cell header rather than in
26.133 +** the payload area.
26.134 +**
26.135 +** The cell pointer array begins on the first byte after the page header.
26.136 +** The cell pointer array contains zero or more 2-byte numbers which are
26.137 +** offsets from the beginning of the page to the cell content in the cell
26.138 +** content area. The cell pointers occur in sorted order. The system strives
26.139 +** to keep free space after the last cell pointer so that new cells can
26.140 +** be easily added without having to defragment the page.
26.141 +**
26.142 +** Cell content is stored at the very end of the page and grows toward the
26.143 +** beginning of the page.
26.144 +**
26.145 +** Unused space within the cell content area is collected into a linked list of
26.146 +** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
26.147 +** to the first freeblock is given in the header. Freeblocks occur in
26.148 +** increasing order. Because a freeblock must be at least 4 bytes in size,
26.149 +** any group of 3 or fewer unused bytes in the cell content area cannot
26.150 +** exist on the freeblock chain. A group of 3 or fewer free bytes is called
26.151 +** a fragment. The total number of bytes in all fragments is recorded.
26.152 +** in the page header at offset 7.
26.153 +**
26.154 +** SIZE DESCRIPTION
26.155 +** 2 Byte offset of the next freeblock
26.156 +** 2 Bytes in this freeblock
26.157 +**
26.158 +** Cells are of variable length. Cells are stored in the cell content area at
26.159 +** the end of the page. Pointers to the cells are in the cell pointer array
26.160 +** that immediately follows the page header. Cells is not necessarily
26.161 +** contiguous or in order, but cell pointers are contiguous and in order.
26.162 +**
26.163 +** Cell content makes use of variable length integers. A variable
26.164 +** length integer is 1 to 9 bytes where the lower 7 bits of each
26.165 +** byte are used. The integer consists of all bytes that have bit 8 set and
26.166 +** the first byte with bit 8 clear. The most significant byte of the integer
26.167 +** appears first. A variable-length integer may not be more than 9 bytes long.
26.168 +** As a special case, all 8 bytes of the 9th byte are used as data. This
26.169 +** allows a 64-bit integer to be encoded in 9 bytes.
26.170 +**
26.171 +** 0x00 becomes 0x00000000
26.172 +** 0x7f becomes 0x0000007f
26.173 +** 0x81 0x00 becomes 0x00000080
26.174 +** 0x82 0x00 becomes 0x00000100
26.175 +** 0x80 0x7f becomes 0x0000007f
26.176 +** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
26.177 +** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
26.178 +**
26.179 +** Variable length integers are used for rowids and to hold the number of
26.180 +** bytes of key and data in a btree cell.
26.181 +**
26.182 +** The content of a cell looks like this:
26.183 +**
26.184 +** SIZE DESCRIPTION
26.185 +** 4 Page number of the left child. Omitted if leaf flag is set.
26.186 +** var Number of bytes of data. Omitted if the zerodata flag is set.
26.187 +** var Number of bytes of key. Or the key itself if intkey flag is set.
26.188 +** * Payload
26.189 +** 4 First page of the overflow chain. Omitted if no overflow
26.190 +**
26.191 +** Overflow pages form a linked list. Each page except the last is completely
26.192 +** filled with data (pagesize - 4 bytes). The last page can have as little
26.193 +** as 1 byte of data.
26.194 +**
26.195 +** SIZE DESCRIPTION
26.196 +** 4 Page number of next overflow page
26.197 +** * Data
26.198 +**
26.199 +** Freelist pages come in two subtypes: trunk pages and leaf pages. The
26.200 +** file header points to the first in a linked list of trunk page. Each trunk
26.201 +** page points to multiple leaf pages. The content of a leaf page is
26.202 +** unspecified. A trunk page looks like this:
26.203 +**
26.204 +** SIZE DESCRIPTION
26.205 +** 4 Page number of next trunk page
26.206 +** 4 Number of leaf pointers on this page
26.207 +** * zero or more pages numbers of leaves
26.208 +*/
26.209 +#include "sqliteInt.h"
26.210 +#include "pager.h"
26.211 +#include "btree.h"
26.212 +#include "os.h"
26.213 +#include <assert.h>
26.214 +
26.215 +/* Round up a number to the next larger multiple of 8. This is used
26.216 +** to force 8-byte alignment on 64-bit architectures.
26.217 +*/
26.218 +#define ROUND8(x) ((x+7)&~7)
26.219 +
26.220 +
26.221 +/* The following value is the maximum cell size assuming a maximum page
26.222 +** size give above.
26.223 +*/
26.224 +#define MX_CELL_SIZE(pBt) (pBt->pageSize-8)
26.225 +
26.226 +/* The maximum number of cells on a single page of the database. This
26.227 +** assumes a minimum cell size of 3 bytes. Such small cells will be
26.228 +** exceedingly rare, but they are possible.
26.229 +*/
26.230 +#define MX_CELL(pBt) ((pBt->pageSize-8)/3)
26.231 +
26.232 +/* Forward declarations */
26.233 +typedef struct MemPage MemPage;
26.234 +typedef struct BtLock BtLock;
26.235 +
26.236 +/*
26.237 +** This is a magic string that appears at the beginning of every
26.238 +** SQLite database in order to identify the file as a real database.
26.239 +**
26.240 +** You can change this value at compile-time by specifying a
26.241 +** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
26.242 +** header must be exactly 16 bytes including the zero-terminator so
26.243 +** the string itself should be 15 characters long. If you change
26.244 +** the header, then your custom library will not be able to read
26.245 +** databases generated by the standard tools and the standard tools
26.246 +** will not be able to read databases created by your custom library.
26.247 +*/
26.248 +#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
26.249 +# define SQLITE_FILE_HEADER "SQLite format 3"
26.250 +#endif
26.251 +
26.252 +/*
26.253 +** Page type flags. An ORed combination of these flags appear as the
26.254 +** first byte of every BTree page.
26.255 +*/
26.256 +#define PTF_INTKEY 0x01
26.257 +#define PTF_ZERODATA 0x02
26.258 +#define PTF_LEAFDATA 0x04
26.259 +#define PTF_LEAF 0x08
26.260 +
26.261 +/*
26.262 +** As each page of the file is loaded into memory, an instance of the following
26.263 +** structure is appended and initialized to zero. This structure stores
26.264 +** information about the page that is decoded from the raw file page.
26.265 +**
26.266 +** The pParent field points back to the parent page. This allows us to
26.267 +** walk up the BTree from any leaf to the root. Care must be taken to
26.268 +** unref() the parent page pointer when this page is no longer referenced.
26.269 +** The pageDestructor() routine handles that chore.
26.270 +*/
26.271 +struct MemPage {
26.272 + u8 isInit; /* True if previously initialized. MUST BE FIRST! */
26.273 + u8 idxShift; /* True if Cell indices have changed */
26.274 + u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
26.275 + u8 intKey; /* True if intkey flag is set */
26.276 + u8 leaf; /* True if leaf flag is set */
26.277 + u8 zeroData; /* True if table stores keys only */
26.278 + u8 leafData; /* True if tables stores data on leaves only */
26.279 + u8 hasData; /* True if this page stores data */
26.280 + u8 hdrOffset; /* 100 for page 1. 0 otherwise */
26.281 + u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
26.282 + u16 maxLocal; /* Copy of Btree.maxLocal or Btree.maxLeaf */
26.283 + u16 minLocal; /* Copy of Btree.minLocal or Btree.minLeaf */
26.284 + u16 cellOffset; /* Index in aData of first cell pointer */
26.285 + u16 idxParent; /* Index in parent of this node */
26.286 + u16 nFree; /* Number of free bytes on the page */
26.287 + u16 nCell; /* Number of cells on this page, local and ovfl */
26.288 + struct _OvflCell { /* Cells that will not fit on aData[] */
26.289 + u8 *pCell; /* Pointers to the body of the overflow cell */
26.290 + u16 idx; /* Insert this cell before idx-th non-overflow cell */
26.291 + } aOvfl[5];
26.292 + BtShared *pBt; /* Pointer back to BTree structure */
26.293 + u8 *aData; /* Pointer back to the start of the page */
26.294 + DbPage *pDbPage; /* Pager page handle */
26.295 + Pgno pgno; /* Page number for this page */
26.296 + MemPage *pParent; /* The parent of this page. NULL for root */
26.297 +};
26.298 +
26.299 +/*
26.300 +** The in-memory image of a disk page has the auxiliary information appended
26.301 +** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
26.302 +** that extra information.
26.303 +*/
26.304 +#define EXTRA_SIZE sizeof(MemPage)
26.305 +
26.306 +/* Btree handle */
26.307 +struct Btree {
26.308 + sqlite3 *pSqlite;
26.309 + BtShared *pBt;
26.310 + u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
26.311 +};
26.312 +
26.313 +/*
26.314 +** Btree.inTrans may take one of the following values.
26.315 +**
26.316 +** If the shared-data extension is enabled, there may be multiple users
26.317 +** of the Btree structure. At most one of these may open a write transaction,
26.318 +** but any number may have active read transactions. Variable Btree.pDb
26.319 +** points to the handle that owns any current write-transaction.
26.320 +*/
26.321 +#define TRANS_NONE 0
26.322 +#define TRANS_READ 1
26.323 +#define TRANS_WRITE 2
26.324 +
26.325 +/*
26.326 +** Everything we need to know about an open database
26.327 +*/
26.328 +struct BtShared {
26.329 + Pager *pPager; /* The page cache */
26.330 + BtCursor *pCursor; /* A list of all open cursors */
26.331 + MemPage *pPage1; /* First page of the database */
26.332 + u8 inStmt; /* True if we are in a statement subtransaction */
26.333 + u8 readOnly; /* True if the underlying file is readonly */
26.334 + u8 maxEmbedFrac; /* Maximum payload as % of total page size */
26.335 + u8 minEmbedFrac; /* Minimum payload as % of total page size */
26.336 + u8 minLeafFrac; /* Minimum leaf payload as % of total page size */
26.337 + u8 pageSizeFixed; /* True if the page size can no longer be changed */
26.338 +#ifndef SQLITE_OMIT_AUTOVACUUM
26.339 + u8 autoVacuum; /* True if auto-vacuum is enabled */
26.340 + u8 incrVacuum; /* True if incr-vacuum is enabled */
26.341 + Pgno nTrunc; /* Non-zero if the db will be truncated (incr vacuum) */
26.342 +#endif
26.343 + u16 pageSize; /* Total number of bytes on a page */
26.344 + u16 usableSize; /* Number of usable bytes on each page */
26.345 + int maxLocal; /* Maximum local payload in non-LEAFDATA tables */
26.346 + int minLocal; /* Minimum local payload in non-LEAFDATA tables */
26.347 + int maxLeaf; /* Maximum local payload in a LEAFDATA table */
26.348 + int minLeaf; /* Minimum local payload in a LEAFDATA table */
26.349 + BusyHandler *pBusyHandler; /* Callback for when there is lock contention */
26.350 + u8 inTransaction; /* Transaction state */
26.351 + int nRef; /* Number of references to this structure */
26.352 + int nTransaction; /* Number of open transactions (read + write) */
26.353 + void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
26.354 + void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
26.355 +#ifndef SQLITE_OMIT_SHARED_CACHE
26.356 + BtLock *pLock; /* List of locks held on this shared-btree struct */
26.357 + BtShared *pNext; /* Next in ThreadData.pBtree linked list */
26.358 +#endif
26.359 +};
26.360 +
26.361 +/*
26.362 +** An instance of the following structure is used to hold information
26.363 +** about a cell. The parseCellPtr() function fills in this structure
26.364 +** based on information extract from the raw disk page.
26.365 +*/
26.366 +typedef struct CellInfo CellInfo;
26.367 +struct CellInfo {
26.368 + u8 *pCell; /* Pointer to the start of cell content */
26.369 + i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
26.370 + u32 nData; /* Number of bytes of data */
26.371 + u32 nPayload; /* Total amount of payload */
26.372 + u16 nHeader; /* Size of the cell content header in bytes */
26.373 + u16 nLocal; /* Amount of payload held locally */
26.374 + u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
26.375 + u16 nSize; /* Size of the cell content on the main b-tree page */
26.376 +};
26.377 +
26.378 +/*
26.379 +** A cursor is a pointer to a particular entry in the BTree.
26.380 +** The entry is identified by its MemPage and the index in
26.381 +** MemPage.aCell[] of the entry.
26.382 +*/
26.383 +struct BtCursor {
26.384 + Btree *pBtree; /* The Btree to which this cursor belongs */
26.385 + BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
26.386 + int (*xCompare)(void*,int,const void*,int,const void*); /* Key comp func */
26.387 + void *pArg; /* First arg to xCompare() */
26.388 + Pgno pgnoRoot; /* The root page of this tree */
26.389 + MemPage *pPage; /* Page that contains the entry */
26.390 + int idx; /* Index of the entry in pPage->aCell[] */
26.391 + CellInfo info; /* A parse of the cell we are pointing at */
26.392 + u8 wrFlag; /* True if writable */
26.393 + u8 eState; /* One of the CURSOR_XXX constants (see below) */
26.394 + void *pKey; /* Saved key that was cursor's last known position */
26.395 + i64 nKey; /* Size of pKey, or last integer key */
26.396 + int skip; /* (skip<0) -> Prev() is a no-op. (skip>0) -> Next() is */
26.397 +#ifndef SQLITE_OMIT_INCRBLOB
26.398 + u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
26.399 + Pgno *aOverflow; /* Cache of overflow page locations */
26.400 +#endif
26.401 +};
26.402 +
26.403 +/*
26.404 +** Potential values for BtCursor.eState.
26.405 +**
26.406 +** CURSOR_VALID:
26.407 +** Cursor points to a valid entry. getPayload() etc. may be called.
26.408 +**
26.409 +** CURSOR_INVALID:
26.410 +** Cursor does not point to a valid entry. This can happen (for example)
26.411 +** because the table is empty or because BtreeCursorFirst() has not been
26.412 +** called.
26.413 +**
26.414 +** CURSOR_REQUIRESEEK:
26.415 +** The table that this cursor was opened on still exists, but has been
26.416 +** modified since the cursor was last used. The cursor position is saved
26.417 +** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
26.418 +** this state, restoreOrClearCursorPosition() can be called to attempt to
26.419 +** seek the cursor to the saved position.
26.420 +*/
26.421 +#define CURSOR_INVALID 0
26.422 +#define CURSOR_VALID 1
26.423 +#define CURSOR_REQUIRESEEK 2
26.424 +
26.425 +/*
26.426 +** The TRACE macro will print high-level status information about the
26.427 +** btree operation when the global variable sqlite3_btree_trace is
26.428 +** enabled.
26.429 +*/
26.430 +#if SQLITE_TEST
26.431 +# define TRACE(X) if( sqlite3_btree_trace ){ printf X; fflush(stdout); }
26.432 +#else
26.433 +# define TRACE(X)
26.434 +#endif
26.435 +
26.436 +/*
26.437 +** Routines to read and write variable-length integers. These used to
26.438 +** be defined locally, but now we use the varint routines in the util.c
26.439 +** file.
26.440 +*/
26.441 +#define getVarint sqlite3GetVarint
26.442 +#define getVarint32(A,B) ((*B=*(A))<=0x7f?1:sqlite3GetVarint32(A,B))
26.443 +#define putVarint sqlite3PutVarint
26.444 +
26.445 +/* The database page the PENDING_BYTE occupies. This page is never used.
26.446 +** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
26.447 +** should possibly be consolidated (presumably in pager.h).
26.448 +**
26.449 +** If disk I/O is omitted (meaning that the database is stored purely
26.450 +** in memory) then there is no pending byte.
26.451 +*/
26.452 +#ifdef SQLITE_OMIT_DISKIO
26.453 +# define PENDING_BYTE_PAGE(pBt) 0x7fffffff
26.454 +#else
26.455 +# define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1)
26.456 +#endif
26.457 +
26.458 +/*
26.459 +** A linked list of the following structures is stored at BtShared.pLock.
26.460 +** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
26.461 +** is opened on the table with root page BtShared.iTable. Locks are removed
26.462 +** from this list when a transaction is committed or rolled back, or when
26.463 +** a btree handle is closed.
26.464 +*/
26.465 +struct BtLock {
26.466 + Btree *pBtree; /* Btree handle holding this lock */
26.467 + Pgno iTable; /* Root page of table */
26.468 + u8 eLock; /* READ_LOCK or WRITE_LOCK */
26.469 + BtLock *pNext; /* Next in BtShared.pLock list */
26.470 +};
26.471 +
26.472 +/* Candidate values for BtLock.eLock */
26.473 +#define READ_LOCK 1
26.474 +#define WRITE_LOCK 2
26.475 +
26.476 +/*
26.477 +** These macros define the location of the pointer-map entry for a
26.478 +** database page. The first argument to each is the number of usable
26.479 +** bytes on each page of the database (often 1024). The second is the
26.480 +** page number to look up in the pointer map.
26.481 +**
26.482 +** PTRMAP_PAGENO returns the database page number of the pointer-map
26.483 +** page that stores the required pointer. PTRMAP_PTROFFSET returns
26.484 +** the offset of the requested map entry.
26.485 +**
26.486 +** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
26.487 +** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
26.488 +** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
26.489 +** this test.
26.490 +*/
26.491 +#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
26.492 +#define PTRMAP_PTROFFSET(pBt, pgno) (5*(pgno-ptrmapPageno(pBt, pgno)-1))
26.493 +#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
26.494 +
26.495 +/*
26.496 +** The pointer map is a lookup table that identifies the parent page for
26.497 +** each child page in the database file. The parent page is the page that
26.498 +** contains a pointer to the child. Every page in the database contains
26.499 +** 0 or 1 parent pages. (In this context 'database page' refers
26.500 +** to any page that is not part of the pointer map itself.) Each pointer map
26.501 +** entry consists of a single byte 'type' and a 4 byte parent page number.
26.502 +** The PTRMAP_XXX identifiers below are the valid types.
26.503 +**
26.504 +** The purpose of the pointer map is to facility moving pages from one
26.505 +** position in the file to another as part of autovacuum. When a page
26.506 +** is moved, the pointer in its parent must be updated to point to the
26.507 +** new location. The pointer map is used to locate the parent page quickly.
26.508 +**
26.509 +** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
26.510 +** used in this case.
26.511 +**
26.512 +** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
26.513 +** is not used in this case.
26.514 +**
26.515 +** PTRMAP_OVERFLOW1: The database page is the first page in a list of
26.516 +** overflow pages. The page number identifies the page that
26.517 +** contains the cell with a pointer to this overflow page.
26.518 +**
26.519 +** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
26.520 +** overflow pages. The page-number identifies the previous
26.521 +** page in the overflow page list.
26.522 +**
26.523 +** PTRMAP_BTREE: The database page is a non-root btree page. The page number
26.524 +** identifies the parent page in the btree.
26.525 +*/
26.526 +#define PTRMAP_ROOTPAGE 1
26.527 +#define PTRMAP_FREEPAGE 2
26.528 +#define PTRMAP_OVERFLOW1 3
26.529 +#define PTRMAP_OVERFLOW2 4
26.530 +#define PTRMAP_BTREE 5
26.531 +
26.532 +/* A bunch of assert() statements to check the transaction state variables
26.533 +** of handle p (type Btree*) are internally consistent.
26.534 +*/
26.535 +#define btreeIntegrity(p) \
26.536 + assert( p->inTrans!=TRANS_NONE || p->pBt->nTransaction<p->pBt->nRef ); \
26.537 + assert( p->pBt->nTransaction<=p->pBt->nRef ); \
26.538 + assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
26.539 + assert( p->pBt->inTransaction>=p->inTrans );
26.540 +
26.541 +
26.542 +/*
26.543 +** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
26.544 +** if the database supports auto-vacuum or not. Because it is used
26.545 +** within an expression that is an argument to another macro
26.546 +** (sqliteMallocRaw), it is not possible to use conditional compilation.
26.547 +** So, this macro is defined instead.
26.548 +*/
26.549 +#ifndef SQLITE_OMIT_AUTOVACUUM
26.550 +#define ISAUTOVACUUM (pBt->autoVacuum)
26.551 +#else
26.552 +#define ISAUTOVACUUM 0
26.553 +#endif
26.554 +
26.555 +
26.556 +/*
26.557 +** This structure is passed around through all the sanity checking routines
26.558 +** in order to keep track of some global state information.
26.559 +*/
26.560 +typedef struct IntegrityCk IntegrityCk;
26.561 +struct IntegrityCk {
26.562 + BtShared *pBt; /* The tree being checked out */
26.563 + Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
26.564 + int nPage; /* Number of pages in the database */
26.565 + int *anRef; /* Number of times each page is referenced */
26.566 + int mxErr; /* Stop accumulating errors when this reaches zero */
26.567 + char *zErrMsg; /* An error message. NULL if no errors seen. */
26.568 + int nErr; /* Number of messages written to zErrMsg so far */
26.569 +};
26.570 +
26.571 +/*
26.572 +** Read or write a two- and four-byte big-endian integer values.
26.573 +*/
26.574 +#define get2byte(x) ((x)[0]<<8 | (x)[1])
26.575 +#define put2byte(p,v) ((p)[0] = (v)>>8, (p)[1] = (v))
26.576 +#define get4byte sqlite3Get4byte
26.577 +#define put4byte sqlite3Put4byte
26.578 +
26.579 +/*
26.580 +** Internal routines that should be accessed by the btree layer only.
26.581 +*/
26.582 +int sqlite3BtreeGetPage(BtShared*, Pgno, MemPage**, int);
26.583 +int sqlite3BtreeInitPage(MemPage *pPage, MemPage *pParent);
26.584 +void sqlite3BtreeParseCellPtr(MemPage*, u8*, CellInfo*);
26.585 +void sqlite3BtreeParseCell(MemPage*, int, CellInfo*);
26.586 +u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell);
26.587 +int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur);
26.588 +void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur);
26.589 +void sqlite3BtreeReleaseTempCursor(BtCursor *pCur);
26.590 +int sqlite3BtreeIsRootPage(MemPage *pPage);
26.591 +void sqlite3BtreeMoveToParent(BtCursor *pCur);
27.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
27.2 +++ b/extensions/sqlite/sqlite-source/build.c Sun Jul 29 01:15:31 2007 +0000
27.3 @@ -0,0 +1,3361 @@
27.4 +/*
27.5 +** 2001 September 15
27.6 +**
27.7 +** The author disclaims copyright to this source code. In place of
27.8 +** a legal notice, here is a blessing:
27.9 +**
27.10 +** May you do good and not evil.
27.11 +** May you find forgiveness for yourself and forgive others.
27.12 +** May you share freely, never taking more than you give.
27.13 +**
27.14 +*************************************************************************
27.15 +** This file contains C code routines that are called by the SQLite parser
27.16 +** when syntax rules are reduced. The routines in this file handle the
27.17 +** following kinds of SQL syntax:
27.18 +**
27.19 +** CREATE TABLE
27.20 +** DROP TABLE
27.21 +** CREATE INDEX
27.22 +** DROP INDEX
27.23 +** creating ID lists
27.24 +** BEGIN TRANSACTION
27.25 +** COMMIT
27.26 +** ROLLBACK
27.27 +**
27.28 +** $Id$
27.29 +*/
27.30 +#include "sqliteInt.h"
27.31 +#include <ctype.h>
27.32 +
27.33 +/*
27.34 +** This routine is called when a new SQL statement is beginning to
27.35 +** be parsed. Initialize the pParse structure as needed.
27.36 +*/
27.37 +void sqlite3BeginParse(Parse *pParse, int explainFlag){
27.38 + pParse->explain = explainFlag;
27.39 + pParse->nVar = 0;
27.40 +}
27.41 +
27.42 +#ifndef SQLITE_OMIT_SHARED_CACHE
27.43 +/*
27.44 +** The TableLock structure is only used by the sqlite3TableLock() and
27.45 +** codeTableLocks() functions.
27.46 +*/
27.47 +struct TableLock {
27.48 + int iDb; /* The database containing the table to be locked */
27.49 + int iTab; /* The root page of the table to be locked */
27.50 + u8 isWriteLock; /* True for write lock. False for a read lock */
27.51 + const char *zName; /* Name of the table */
27.52 +};
27.53 +
27.54 +/*
27.55 +** Record the fact that we want to lock a table at run-time.
27.56 +**
27.57 +** The table to be locked has root page iTab and is found in database iDb.
27.58 +** A read or a write lock can be taken depending on isWritelock.
27.59 +**
27.60 +** This routine just records the fact that the lock is desired. The
27.61 +** code to make the lock occur is generated by a later call to
27.62 +** codeTableLocks() which occurs during sqlite3FinishCoding().
27.63 +*/
27.64 +void sqlite3TableLock(
27.65 + Parse *pParse, /* Parsing context */
27.66 + int iDb, /* Index of the database containing the table to lock */
27.67 + int iTab, /* Root page number of the table to be locked */
27.68 + u8 isWriteLock, /* True for a write lock */
27.69 + const char *zName /* Name of the table to be locked */
27.70 +){
27.71 + int i;
27.72 + int nBytes;
27.73 + TableLock *p;
27.74 +
27.75 + if( 0==sqlite3ThreadDataReadOnly()->useSharedData || iDb<0 ){
27.76 + return;
27.77 + }
27.78 +
27.79 + for(i=0; i<pParse->nTableLock; i++){
27.80 + p = &pParse->aTableLock[i];
27.81 + if( p->iDb==iDb && p->iTab==iTab ){
27.82 + p->isWriteLock = (p->isWriteLock || isWriteLock);
27.83 + return;
27.84 + }
27.85 + }
27.86 +
27.87 + nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
27.88 + pParse->aTableLock = sqliteReallocOrFree(pParse->aTableLock, nBytes);
27.89 + if( pParse->aTableLock ){
27.90 + p = &pParse->aTableLock[pParse->nTableLock++];
27.91 + p->iDb = iDb;
27.92 + p->iTab = iTab;
27.93 + p->isWriteLock = isWriteLock;
27.94 + p->zName = zName;
27.95 + }
27.96 +}
27.97 +
27.98 +/*
27.99 +** Code an OP_TableLock instruction for each table locked by the
27.100 +** statement (configured by calls to sqlite3TableLock()).
27.101 +*/
27.102 +static void codeTableLocks(Parse *pParse){
27.103 + int i;
27.104 + Vdbe *pVdbe;
27.105 + assert( sqlite3ThreadDataReadOnly()->useSharedData || pParse->nTableLock==0 );
27.106 +
27.107 + if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
27.108 + return;
27.109 + }
27.110 +
27.111 + for(i=0; i<pParse->nTableLock; i++){
27.112 + TableLock *p = &pParse->aTableLock[i];
27.113 + int p1 = p->iDb;
27.114 + if( p->isWriteLock ){
27.115 + p1 = -1*(p1+1);
27.116 + }
27.117 + sqlite3VdbeOp3(pVdbe, OP_TableLock, p1, p->iTab, p->zName, P3_STATIC);
27.118 + }
27.119 +}
27.120 +#else
27.121 + #define codeTableLocks(x)
27.122 +#endif
27.123 +
27.124 +/*
27.125 +** This routine is called after a single SQL statement has been
27.126 +** parsed and a VDBE program to execute that statement has been
27.127 +** prepared. This routine puts the finishing touches on the
27.128 +** VDBE program and resets the pParse structure for the next
27.129 +** parse.
27.130 +**
27.131 +** Note that if an error occurred, it might be the case that
27.132 +** no VDBE code was generated.
27.133 +*/
27.134 +void sqlite3FinishCoding(Parse *pParse){
27.135 + sqlite3 *db;
27.136 + Vdbe *v;
27.137 +
27.138 + if( sqlite3MallocFailed() ) return;
27.139 + if( pParse->nested ) return;
27.140 + if( !pParse->pVdbe ){
27.141 + if( pParse->rc==SQLITE_OK && pParse->nErr ){
27.142 + pParse->rc = SQLITE_ERROR;
27.143 + return;
27.144 + }
27.145 + }
27.146 +
27.147 + /* Begin by generating some termination code at the end of the
27.148 + ** vdbe program
27.149 + */
27.150 + db = pParse->db;
27.151 + v = sqlite3GetVdbe(pParse);
27.152 + if( v ){
27.153 + sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
27.154 +
27.155 + /* The cookie mask contains one bit for each database file open.
27.156 + ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
27.157 + ** set for each database that is used. Generate code to start a
27.158 + ** transaction on each used database and to verify the schema cookie
27.159 + ** on each used database.
27.160 + */
27.161 + if( pParse->cookieGoto>0 ){
27.162 + u32 mask;
27.163 + int iDb;
27.164 + sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
27.165 + for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
27.166 + if( (mask & pParse->cookieMask)==0 ) continue;
27.167 + sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
27.168 + sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
27.169 + }
27.170 +#ifndef SQLITE_OMIT_VIRTUALTABLE
27.171 + if( pParse->pVirtualLock ){
27.172 + char *vtab = (char *)pParse->pVirtualLock->pVtab;
27.173 + sqlite3VdbeOp3(v, OP_VBegin, 0, 0, vtab, P3_VTAB);
27.174 + }
27.175 +#endif
27.176 +
27.177 + /* Once all the cookies have been verified and transactions opened,
27.178 + ** obtain the required table-locks. This is a no-op unless the
27.179 + ** shared-cache feature is enabled.
27.180 + */
27.181 + codeTableLocks(pParse);
27.182 + sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto);
27.183 + }
27.184 +
27.185 +#ifndef SQLITE_OMIT_TRACE
27.186 + /* Add a No-op that contains the complete text of the compiled SQL
27.187 + ** statement as its P3 argument. This does not change the functionality
27.188 + ** of the program.
27.189 + **
27.190 + ** This is used to implement sqlite3_trace().
27.191 + */
27.192 + sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql);
27.193 +#endif /* SQLITE_OMIT_TRACE */
27.194 + }
27.195 +
27.196 +
27.197 + /* Get the VDBE program ready for execution
27.198 + */
27.199 + if( v && pParse->nErr==0 && !sqlite3MallocFailed() ){
27.200 +#ifdef SQLITE_DEBUG
27.201 + FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
27.202 + sqlite3VdbeTrace(v, trace);
27.203 +#endif
27.204 + sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
27.205 + pParse->nTab+3, pParse->explain);
27.206 + pParse->rc = SQLITE_DONE;
27.207 + pParse->colNamesSet = 0;
27.208 + }else if( pParse->rc==SQLITE_OK ){
27.209 + pParse->rc = SQLITE_ERROR;
27.210 + }
27.211 + pParse->nTab = 0;
27.212 + pParse->nMem = 0;
27.213 + pParse->nSet = 0;
27.214 + pParse->nVar = 0;
27.215 + pParse->cookieMask = 0;
27.216 + pParse->cookieGoto = 0;
27.217 +}
27.218 +
27.219 +/*
27.220 +** Run the parser and code generator recursively in order to generate
27.221 +** code for the SQL statement given onto the end of the pParse context
27.222 +** currently under construction. When the parser is run recursively
27.223 +** this way, the final OP_Halt is not appended and other initialization
27.224 +** and finalization steps are omitted because those are handling by the
27.225 +** outermost parser.
27.226 +**
27.227 +** Not everything is nestable. This facility is designed to permit
27.228 +** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
27.229 +** care if you decide to try to use this routine for some other purposes.
27.230 +*/
27.231 +void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
27.232 + va_list ap;
27.233 + char *zSql;
27.234 +# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
27.235 + char saveBuf[SAVE_SZ];
27.236 +
27.237 + if( pParse->nErr ) return;
27.238 + assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
27.239 + va_start(ap, zFormat);
27.240 + zSql = sqlite3VMPrintf(zFormat, ap);
27.241 + va_end(ap);
27.242 + if( zSql==0 ){
27.243 + return; /* A malloc must have failed */
27.244 + }
27.245 + pParse->nested++;
27.246 + memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
27.247 + memset(&pParse->nVar, 0, SAVE_SZ);
27.248 + sqlite3RunParser(pParse, zSql, 0);
27.249 + sqliteFree(zSql);
27.250 + memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
27.251 + pParse->nested--;
27.252 +}
27.253 +
27.254 +/*
27.255 +** Locate the in-memory structure that describes a particular database
27.256 +** table given the name of that table and (optionally) the name of the
27.257 +** database containing the table. Return NULL if not found.
27.258 +**
27.259 +** If zDatabase is 0, all databases are searched for the table and the
27.260 +** first matching table is returned. (No checking for duplicate table
27.261 +** names is done.) The search order is TEMP first, then MAIN, then any
27.262 +** auxiliary databases added using the ATTACH command.
27.263 +**
27.264 +** See also sqlite3LocateTable().
27.265 +*/
27.266 +Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
27.267 + Table *p = 0;
27.268 + int i;
27.269 + assert( zName!=0 );
27.270 + for(i=OMIT_TEMPDB; i<db->nDb; i++){
27.271 + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
27.272 + if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
27.273 + p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1);
27.274 + if( p ) break;
27.275 + }
27.276 + return p;
27.277 +}
27.278 +
27.279 +/*
27.280 +** Locate the in-memory structure that describes a particular database
27.281 +** table given the name of that table and (optionally) the name of the
27.282 +** database containing the table. Return NULL if not found. Also leave an
27.283 +** error message in pParse->zErrMsg.
27.284 +**
27.285 +** The difference between this routine and sqlite3FindTable() is that this
27.286 +** routine leaves an error message in pParse->zErrMsg where
27.287 +** sqlite3FindTable() does not.
27.288 +*/
27.289 +Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
27.290 + Table *p;
27.291 +
27.292 + /* Read the database schema. If an error occurs, leave an error message
27.293 + ** and code in pParse and return NULL. */
27.294 + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
27.295 + return 0;
27.296 + }
27.297 +
27.298 + p = sqlite3FindTable(pParse->db, zName, zDbase);
27.299 + if( p==0 ){
27.300 + if( zDbase ){
27.301 + sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
27.302 + }else{
27.303 + sqlite3ErrorMsg(pParse, "no such table: %s", zName);
27.304 + }
27.305 + pParse->checkSchema = 1;
27.306 + }
27.307 + return p;
27.308 +}
27.309 +
27.310 +/*
27.311 +** Locate the in-memory structure that describes
27.312 +** a particular index given the name of that index
27.313 +** and the name of the database that contains the index.
27.314 +** Return NULL if not found.
27.315 +**
27.316 +** If zDatabase is 0, all databases are searched for the
27.317 +** table and the first matching index is returned. (No checking
27.318 +** for duplicate index names is done.) The search order is
27.319 +** TEMP first, then MAIN, then any auxiliary databases added
27.320 +** using the ATTACH command.
27.321 +*/
27.322 +Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
27.323 + Index *p = 0;
27.324 + int i;
27.325 + for(i=OMIT_TEMPDB; i<db->nDb; i++){
27.326 + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
27.327 + Schema *pSchema = db->aDb[j].pSchema;
27.328 + if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
27.329 + assert( pSchema || (j==1 && !db->aDb[1].pBt) );
27.330 + if( pSchema ){
27.331 + p = sqlite3HashFind(&pSchema->idxHash, zName, strlen(zName)+1);
27.332 + }
27.333 + if( p ) break;
27.334 + }
27.335 + return p;
27.336 +}
27.337 +
27.338 +/*
27.339 +** Reclaim the memory used by an index
27.340 +*/
27.341 +static void freeIndex(Index *p){
27.342 + sqliteFree(p->zColAff);
27.343 + sqliteFree(p);
27.344 +}
27.345 +
27.346 +/*
27.347 +** Remove the given index from the index hash table, and free
27.348 +** its memory structures.
27.349 +**
27.350 +** The index is removed from the database hash tables but
27.351 +** it is not unlinked from the Table that it indexes.
27.352 +** Unlinking from the Table must be done by the calling function.
27.353 +*/
27.354 +static void sqliteDeleteIndex(Index *p){
27.355 + Index *pOld;
27.356 + const char *zName = p->zName;
27.357 +
27.358 + pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen( zName)+1, 0);
27.359 + assert( pOld==0 || pOld==p );
27.360 + freeIndex(p);
27.361 +}
27.362 +
27.363 +/*
27.364 +** For the index called zIdxName which is found in the database iDb,
27.365 +** unlike that index from its Table then remove the index from
27.366 +** the index hash table and free all memory structures associated
27.367 +** with the index.
27.368 +*/
27.369 +void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
27.370 + Index *pIndex;
27.371 + int len;
27.372 + Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
27.373 +
27.374 + len = strlen(zIdxName);
27.375 + pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
27.376 + if( pIndex ){
27.377 + if( pIndex->pTable->pIndex==pIndex ){
27.378 + pIndex->pTable->pIndex = pIndex->pNext;
27.379 + }else{
27.380 + Index *p;
27.381 + for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
27.382 + if( p && p->pNext==pIndex ){
27.383 + p->pNext = pIndex->pNext;
27.384 + }
27.385 + }
27.386 + freeIndex(pIndex);
27.387 + }
27.388 + db->flags |= SQLITE_InternChanges;
27.389 +}
27.390 +
27.391 +/*
27.392 +** Erase all schema information from the in-memory hash tables of
27.393 +** a single database. This routine is called to reclaim memory
27.394 +** before the database closes. It is also called during a rollback
27.395 +** if there were schema changes during the transaction or if a
27.396 +** schema-cookie mismatch occurs.
27.397 +**
27.398 +** If iDb<=0 then reset the internal schema tables for all database
27.399 +** files. If iDb>=2 then reset the internal schema for only the
27.400 +** single file indicated.
27.401 +*/
27.402 +void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
27.403 + int i, j;
27.404 +
27.405 + assert( iDb>=0 && iDb<db->nDb );
27.406 + for(i=iDb; i<db->nDb; i++){
27.407 + Db *pDb = &db->aDb[i];
27.408 + if( pDb->pSchema ){
27.409 + sqlite3SchemaFree(pDb->pSchema);
27.410 + }
27.411 + if( iDb>0 ) return;
27.412 + }
27.413 + assert( iDb==0 );
27.414 + db->flags &= ~SQLITE_InternChanges;
27.415 +
27.416 + /* If one or more of the auxiliary database files has been closed,
27.417 + ** then remove them from the auxiliary database list. We take the
27.418 + ** opportunity to do this here since we have just deleted all of the
27.419 + ** schema hash tables and therefore do not have to make any changes
27.420 + ** to any of those tables.
27.421 + */
27.422 + for(i=0; i<db->nDb; i++){
27.423 + struct Db *pDb = &db->aDb[i];
27.424 + if( pDb->pBt==0 ){
27.425 + if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
27.426 + pDb->pAux = 0;
27.427 + }
27.428 + }
27.429 + for(i=j=2; i<db->nDb; i++){
27.430 + struct Db *pDb = &db->aDb[i];
27.431 + if( pDb->pBt==0 ){
27.432 + sqliteFree(pDb->zName);
27.433 + pDb->zName = 0;
27.434 + continue;
27.435 + }
27.436 + if( j<i ){
27.437 + db->aDb[j] = db->aDb[i];
27.438 + }
27.439 + j++;
27.440 + }
27.441 + memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
27.442 + db->nDb = j;
27.443 + if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
27.444 + memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
27.445 + sqliteFree(db->aDb);
27.446 + db->aDb = db->aDbStatic;
27.447 + }
27.448 +}
27.449 +
27.450 +/*
27.451 +** This routine is called when a commit occurs.
27.452 +*/
27.453 +void sqlite3CommitInternalChanges(sqlite3 *db){
27.454 + db->flags &= ~SQLITE_InternChanges;
27.455 +}
27.456 +
27.457 +/*
27.458 +** Clear the column names from a table or view.
27.459 +*/
27.460 +static void sqliteResetColumnNames(Table *pTable){
27.461 + int i;
27.462 + Column *pCol;
27.463 + assert( pTable!=0 );
27.464 + if( (pCol = pTable->aCol)!=0 ){
27.465 + for(i=0; i<pTable->nCol; i++, pCol++){
27.466 + sqliteFree(pCol->zName);
27.467 + sqlite3ExprDelete(pCol->pDflt);
27.468 + sqliteFree(pCol->zType);
27.469 + sqliteFree(pCol->zColl);
27.470 + }
27.471 + sqliteFree(pTable->aCol);
27.472 + }
27.473 + pTable->aCol = 0;
27.474 + pTable->nCol = 0;
27.475 +}
27.476 +
27.477 +/*
27.478 +** Remove the memory data structures associated with the given
27.479 +** Table. No changes are made to disk by this routine.
27.480 +**
27.481 +** This routine just deletes the data structure. It does not unlink
27.482 +** the table data structure from the hash table. Nor does it remove
27.483 +** foreign keys from the sqlite.aFKey hash table. But it does destroy
27.484 +** memory structures of the indices and foreign keys associated with
27.485 +** the table.
27.486 +*/
27.487 +void sqlite3DeleteTable(Table *pTable){
27.488 + Index *pIndex, *pNext;
27.489 + FKey *pFKey, *pNextFKey;
27.490 +
27.491 + if( pTable==0 ) return;
27.492 +
27.493 + /* Do not delete the table until the reference count reaches zero. */
27.494 + pTable->nRef--;
27.495 + if( pTable->nRef>0 ){
27.496 + return;
27.497 + }
27.498 + assert( pTable->nRef==0 );
27.499 +
27.500 + /* Delete all indices associated with this table
27.501 + */
27.502 + for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
27.503 + pNext = pIndex->pNext;
27.504 + assert( pIndex->pSchema==pTable->pSchema );
27.505 + sqliteDeleteIndex(pIndex);
27.506 + }
27.507 +
27.508 +#ifndef SQLITE_OMIT_FOREIGN_KEY
27.509 + /* Delete all foreign keys associated with this table. The keys
27.510 + ** should have already been unlinked from the pSchema->aFKey hash table
27.511 + */
27.512 + for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
27.513 + pNextFKey = pFKey->pNextFrom;
27.514 + assert( sqlite3HashFind(&pTable->pSchema->aFKey,
27.515 + pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
27.516 + sqliteFree(pFKey);
27.517 + }
27.518 +#endif
27.519 +
27.520 + /* Delete the Table structure itself.
27.521 + */
27.522 + sqliteResetColumnNames(pTable);
27.523 + sqliteFree(pTable->zName);
27.524 + sqliteFree(pTable->zColAff);
27.525 + sqlite3SelectDelete(pTable->pSelect);
27.526 +#ifndef SQLITE_OMIT_CHECK
27.527 + sqlite3ExprDelete(pTable->pCheck);
27.528 +#endif
27.529 + sqlite3VtabClear(pTable);
27.530 + sqliteFree(pTable);
27.531 +}
27.532 +
27.533 +/*
27.534 +** Unlink the given table from the hash tables and the delete the
27.535 +** table structure with all its indices and foreign keys.
27.536 +*/
27.537 +void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
27.538 + Table *p;
27.539 + FKey *pF1, *pF2;
27.540 + Db *pDb;
27.541 +
27.542 + assert( db!=0 );
27.543 + assert( iDb>=0 && iDb<db->nDb );
27.544 + assert( zTabName && zTabName[0] );
27.545 + pDb = &db->aDb[iDb];
27.546 + p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
27.547 + if( p ){
27.548 +#ifndef SQLITE_OMIT_FOREIGN_KEY
27.549 + for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
27.550 + int nTo = strlen(pF1->zTo) + 1;
27.551 + pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
27.552 + if( pF2==pF1 ){
27.553 + sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
27.554 + }else{
27.555 + while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
27.556 + if( pF2 ){
27.557 + pF2->pNextTo = pF1->pNextTo;
27.558 + }
27.559 + }
27.560 + }
27.561 +#endif
27.562 + sqlite3DeleteTable(p);
27.563 + }
27.564 + db->flags |= SQLITE_InternChanges;
27.565 +}
27.566 +
27.567 +/*
27.568 +** Given a token, return a string that consists of the text of that
27.569 +** token with any quotations removed. Space to hold the returned string
27.570 +** is obtained from sqliteMalloc() and must be freed by the calling
27.571 +** function.
27.572 +**
27.573 +** Tokens are often just pointers into the original SQL text and so
27.574 +** are not \000 terminated and are not persistent. The returned string
27.575 +** is \000 terminated and is persistent.
27.576 +*/
27.577 +char *sqlite3NameFromToken(Token *pName){
27.578 + char *zName;
27.579 + if( pName ){
27.580 + zName = sqliteStrNDup((char*)pName->z, pName->n);
27.581 + sqlite3Dequote(zName);
27.582 + }else{
27.583 + zName = 0;
27.584 + }
27.585 + return zName;
27.586 +}
27.587 +
27.588 +/*
27.589 +** Open the sqlite_master table stored in database number iDb for
27.590 +** writing. The table is opened using cursor 0.
27.591 +*/
27.592 +void sqlite3OpenMasterTable(Parse *p, int iDb){
27.593 + Vdbe *v = sqlite3GetVdbe(p);
27.594 + sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
27.595 + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
27.596 + sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
27.597 + sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
27.598 +}
27.599 +
27.600 +/*
27.601 +** The token *pName contains the name of a database (either "main" or
27.602 +** "temp" or the name of an attached db). This routine returns the
27.603 +** index of the named database in db->aDb[], or -1 if the named db
27.604 +** does not exist.
27.605 +*/
27.606 +int sqlite3FindDb(sqlite3 *db, Token *pName){
27.607 + int i = -1; /* Database number */
27.608 + int n; /* Number of characters in the name */
27.609 + Db *pDb; /* A database whose name space is being searched */
27.610 + char *zName; /* Name we are searching for */
27.611 +
27.612 + zName = sqlite3NameFromToken(pName);
27.613 + if( zName ){
27.614 + n = strlen(zName);
27.615 + for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
27.616 + if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) &&
27.617 + 0==sqlite3StrICmp(pDb->zName, zName) ){
27.618 + break;
27.619 + }
27.620 + }
27.621 + sqliteFree(zName);
27.622 + }
27.623 + return i;
27.624 +}
27.625 +
27.626 +/* The table or view or trigger name is passed to this routine via tokens
27.627 +** pName1 and pName2. If the table name was fully qualified, for example:
27.628 +**
27.629 +** CREATE TABLE xxx.yyy (...);
27.630 +**
27.631 +** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
27.632 +** the table name is not fully qualified, i.e.:
27.633 +**
27.634 +** CREATE TABLE yyy(...);
27.635 +**
27.636 +** Then pName1 is set to "yyy" and pName2 is "".
27.637 +**
27.638 +** This routine sets the *ppUnqual pointer to point at the token (pName1 or
27.639 +** pName2) that stores the unqualified table name. The index of the
27.640 +** database "xxx" is returned.
27.641 +*/
27.642 +int sqlite3TwoPartName(
27.643 + Parse *pParse, /* Parsing and code generating context */
27.644 + Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
27.645 + Token *pName2, /* The "yyy" in the name "xxx.yyy" */
27.646 + Token **pUnqual /* Write the unqualified object name here */
27.647 +){
27.648 + int iDb; /* Database holding the object */
27.649 + sqlite3 *db = pParse->db;
27.650 +
27.651 + if( pName2 && pName2->n>0 ){
27.652 + assert( !db->init.busy );
27.653 + *pUnqual = pName2;
27.654 + iDb = sqlite3FindDb(db, pName1);
27.655 + if( iDb<0 ){
27.656 + sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
27.657 + pParse->nErr++;
27.658 + return -1;
27.659 + }
27.660 + }else{
27.661 + assert( db->init.iDb==0 || db->init.busy );
27.662 + iDb = db->init.iDb;
27.663 + *pUnqual = pName1;
27.664 + }
27.665 + return iDb;
27.666 +}
27.667 +
27.668 +/*
27.669 +** This routine is used to check if the UTF-8 string zName is a legal
27.670 +** unqualified name for a new schema object (table, index, view or
27.671 +** trigger). All names are legal except those that begin with the string
27.672 +** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
27.673 +** is reserved for internal use.
27.674 +*/
27.675 +int sqlite3CheckObjectName(Parse *pParse, const char *zName){
27.676 + if( !pParse->db->init.busy && pParse->nested==0
27.677 + && (pParse->db->flags & SQLITE_WriteSchema)==0
27.678 + && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
27.679 + sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
27.680 + return SQLITE_ERROR;
27.681 + }
27.682 + return SQLITE_OK;
27.683 +}
27.684 +
27.685 +/*
27.686 +** Begin constructing a new table representation in memory. This is
27.687 +** the first of several action routines that get called in response
27.688 +** to a CREATE TABLE statement. In particular, this routine is called
27.689 +** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
27.690 +** flag is true if the table should be stored in the auxiliary database
27.691 +** file instead of in the main database file. This is normally the case
27.692 +** when the "TEMP" or "TEMPORARY" keyword occurs in between
27.693 +** CREATE and TABLE.
27.694 +**
27.695 +** The new table record is initialized and put in pParse->pNewTable.
27.696 +** As more of the CREATE TABLE statement is parsed, additional action
27.697 +** routines will be called to add more information to this record.
27.698 +** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
27.699 +** is called to complete the construction of the new table record.
27.700 +*/
27.701 +void sqlite3StartTable(
27.702 + Parse *pParse, /* Parser context */
27.703 + Token *pName1, /* First part of the name of the table or view */
27.704 + Token *pName2, /* Second part of the name of the table or view */
27.705 + int isTemp, /* True if this is a TEMP table */
27.706 + int isView, /* True if this is a VIEW */
27.707 + int isVirtual, /* True if this is a VIRTUAL table */
27.708 + int noErr /* Do nothing if table already exists */
27.709 +){
27.710 + Table *pTable;
27.711 + char *zName = 0; /* The name of the new table */
27.712 + sqlite3 *db = pParse->db;
27.713 + Vdbe *v;
27.714 + int iDb; /* Database number to create the table in */
27.715 + Token *pName; /* Unqualified name of the table to create */
27.716 +
27.717 + /* The table or view name to create is passed to this routine via tokens
27.718 + ** pName1 and pName2. If the table name was fully qualified, for example:
27.719 + **
27.720 + ** CREATE TABLE xxx.yyy (...);
27.721 + **
27.722 + ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
27.723 + ** the table name is not fully qualified, i.e.:
27.724 + **
27.725 + ** CREATE TABLE yyy(...);
27.726 + **
27.727 + ** Then pName1 is set to "yyy" and pName2 is "".
27.728 + **
27.729 + ** The call below sets the pName pointer to point at the token (pName1 or
27.730 + ** pName2) that stores the unqualified table name. The variable iDb is
27.731 + ** set to the index of the database that the table or view is to be
27.732 + ** created in.
27.733 + */
27.734 + iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
27.735 + if( iDb<0 ) return;
27.736 + if( !OMIT_TEMPDB && isTemp && iDb>1 ){
27.737 + /* If creating a temp table, the name may not be qualified */
27.738 + sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
27.739 + return;
27.740 + }
27.741 + if( !OMIT_TEMPDB && isTemp ) iDb = 1;
27.742 +
27.743 + pParse->sNameToken = *pName;
27.744 + zName = sqlite3NameFromToken(pName);
27.745 + if( zName==0 ) return;
27.746 + if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
27.747 + goto begin_table_error;
27.748 + }
27.749 + if( db->init.iDb==1 ) isTemp = 1;
27.750 +#ifndef SQLITE_OMIT_AUTHORIZATION
27.751 + assert( (isTemp & 1)==isTemp );
27.752 + {
27.753 + int code;
27.754 + char *zDb = db->aDb[iDb].zName;
27.755 + if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
27.756 + goto begin_table_error;
27.757 + }
27.758 + if( isView ){
27.759 + if( !OMIT_TEMPDB && isTemp ){
27.760 + code = SQLITE_CREATE_TEMP_VIEW;
27.761 + }else{
27.762 + code = SQLITE_CREATE_VIEW;
27.763 + }
27.764 + }else{
27.765 + if( !OMIT_TEMPDB && isTemp ){
27.766 + code = SQLITE_CREATE_TEMP_TABLE;
27.767 + }else{
27.768 + code = SQLITE_CREATE_TABLE;
27.769 + }
27.770 + }
27.771 + if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
27.772 + goto begin_table_error;
27.773 + }
27.774 + }
27.775 +#endif
27.776 +
27.777 + /* Make sure the new table name does not collide with an existing
27.778 + ** index or table name in the same database. Issue an error message if
27.779 + ** it does. The exception is if the statement being parsed was passed
27.780 + ** to an sqlite3_declare_vtab() call. In that case only the column names
27.781 + ** and types will be used, so there is no need to test for namespace
27.782 + ** collisions.
27.783 + */
27.784 + if( !IN_DECLARE_VTAB ){
27.785 + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
27.786 + goto begin_table_error;
27.787 + }
27.788 + pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
27.789 + if( pTable ){
27.790 + if( !noErr ){
27.791 + sqlite3ErrorMsg(pParse, "table %T already exists", pName);
27.792 + }
27.793 + goto begin_table_error;
27.794 + }
27.795 + if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
27.796 + sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
27.797 + goto begin_table_error;
27.798 + }
27.799 + }
27.800 +
27.801 + pTable = sqliteMalloc( sizeof(Table) );
27.802 + if( pTable==0 ){
27.803 + pParse->rc = SQLITE_NOMEM;
27.804 + pParse->nErr++;
27.805 + goto begin_table_error;
27.806 + }
27.807 + pTable->zName = zName;
27.808 + pTable->iPKey = -1;
27.809 + pTable->pSchema = db->aDb[iDb].pSchema;
27.810 + pTable->nRef = 1;
27.811 + if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
27.812 + pParse->pNewTable = pTable;
27.813 +
27.814 + /* If this is the magic sqlite_sequence table used by autoincrement,
27.815 + ** then record a pointer to this table in the main database structure
27.816 + ** so that INSERT can find the table easily.
27.817 + */
27.818 +#ifndef SQLITE_OMIT_AUTOINCREMENT
27.819 + if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
27.820 + pTable->pSchema->pSeqTab = pTable;
27.821 + }
27.822 +#endif
27.823 +
27.824 + /* Begin generating the code that will insert the table record into
27.825 + ** the SQLITE_MASTER table. Note in particular that we must go ahead
27.826 + ** and allocate the record number for the table entry now. Before any
27.827 + ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
27.828 + ** indices to be created and the table record must come before the
27.829 + ** indices. Hence, the record number for the table must be allocated
27.830 + ** now.
27.831 + */
27.832 + if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
27.833 + int lbl;
27.834 + int fileFormat;
27.835 + sqlite3BeginWriteOperation(pParse, 0, iDb);
27.836 +
27.837 +#ifndef SQLITE_OMIT_VIRTUALTABLE
27.838 + if( isVirtual ){
27.839 + sqlite3VdbeAddOp(v, OP_VBegin, 0, 0);
27.840 + }
27.841 +#endif
27.842 +
27.843 + /* If the file format and encoding in the database have not been set,
27.844 + ** set them now.
27.845 + */
27.846 + sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /* file_format */
27.847 + lbl = sqlite3VdbeMakeLabel(v);
27.848 + sqlite3VdbeAddOp(v, OP_If, 0, lbl);
27.849 + fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
27.850 + 1 : SQLITE_MAX_FILE_FORMAT;
27.851 + sqlite3VdbeAddOp(v, OP_Integer, fileFormat, 0);
27.852 + sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
27.853 + sqlite3VdbeAddOp(v, OP_Integer, ENC(db), 0);
27.854 + sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
27.855 + sqlite3VdbeResolveLabel(v, lbl);
27.856 +
27.857 + /* This just creates a place-holder record in the sqlite_master table.
27.858 + ** The record created does not contain anything yet. It will be replaced
27.859 + ** by the real entry in code generated at sqlite3EndTable().
27.860 + **
27.861 + ** The rowid for the new entry is left on the top of the stack.
27.862 + ** The rowid value is needed by the code that sqlite3EndTable will
27.863 + ** generate.
27.864 + */
27.865 +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
27.866 + if( isView || isVirtual ){
27.867 + sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
27.868 + }else
27.869 +#endif
27.870 + {
27.871 + sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0);
27.872 + }
27.873 + sqlite3OpenMasterTable(pParse, iDb);
27.874 + sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0);
27.875 + sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
27.876 + sqlite3VdbeAddOp(v, OP_Null, 0, 0);
27.877 + sqlite3VdbeAddOp(v, OP_Insert, 0, OPFLAG_APPEND);
27.878 + sqlite3VdbeAddOp(v, OP_Close, 0, 0);
27.879 + sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
27.880 + }
27.881 +
27.882 + /* Normal (non-error) return. */
27.883 + return;
27.884 +
27.885 + /* If an error occurs, we jump here */
27.886 +begin_table_error:
27.887 + sqliteFree(zName);
27.888 + return;
27.889 +}
27.890 +
27.891 +/*
27.892 +** This macro is used to compare two strings in a case-insensitive manner.
27.893 +** It is slightly faster than calling sqlite3StrICmp() directly, but
27.894 +** produces larger code.
27.895 +**
27.896 +** WARNING: This macro is not compatible with the strcmp() family. It
27.897 +** returns true if the two strings are equal, otherwise false.
27.898 +*/
27.899 +#define STRICMP(x, y) (\
27.900 +sqlite3UpperToLower[*(unsigned char *)(x)]== \
27.901 +sqlite3UpperToLower[*(unsigned char *)(y)] \
27.902 +&& sqlite3StrICmp((x)+1,(y)+1)==0 )
27.903 +
27.904 +/*
27.905 +** Add a new column to the table currently being constructed.
27.906 +**
27.907 +** The parser calls this routine once for each column declaration
27.908 +** in a CREATE TABLE statement. sqlite3StartTable() gets called
27.909 +** first to get things going. Then this routine is called for each
27.910 +** column.
27.911 +*/
27.912 +void sqlite3AddColumn(Parse *pParse, Token *pName){
27.913 + Table *p;
27.914 + int i;
27.915 + char *z;
27.916 + Column *pCol;
27.917 + if( (p = pParse->pNewTable)==0 ) return;
27.918 + if( p->nCol+1>SQLITE_MAX_COLUMN ){
27.919 + sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
27.920 + return;
27.921 + }
27.922 + z = sqlite3NameFromToken(pName);
27.923 + if( z==0 ) return;
27.924 + for(i=0; i<p->nCol; i++){
27.925 + if( STRICMP(z, p->aCol[i].zName) ){
27.926 + sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
27.927 + sqliteFree(z);
27.928 + return;
27.929 + }
27.930 + }
27.931 + if( (p->nCol & 0x7)==0 ){
27.932 + Column *aNew;
27.933 + aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
27.934 + if( aNew==0 ){
27.935 + sqliteFree(z);
27.936 + return;
27.937 + }
27.938 + p->aCol = aNew;
27.939 + }
27.940 + pCol = &p->aCol[p->nCol];
27.941 + memset(pCol, 0, sizeof(p->aCol[0]));
27.942 + pCol->zName = z;
27.943 +
27.944 + /* If there is no type specified, columns have the default affinity
27.945 + ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
27.946 + ** be called next to set pCol->affinity correctly.
27.947 + */
27.948 + pCol->affinity = SQLITE_AFF_NONE;
27.949 + p->nCol++;
27.950 +}
27.951 +
27.952 +/*
27.953 +** This routine is called by the parser while in the middle of
27.954 +** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
27.955 +** been seen on a column. This routine sets the notNull flag on
27.956 +** the column currently under construction.
27.957 +*/
27.958 +void sqlite3AddNotNull(Parse *pParse, int onError){
27.959 + Table *p;
27.960 + int i;
27.961 + if( (p = pParse->pNewTable)==0 ) return;
27.962 + i = p->nCol-1;
27.963 + if( i>=0 ) p->aCol[i].notNull = onError;
27.964 +}
27.965 +
27.966 +/*
27.967 +** Scan the column type name zType (length nType) and return the
27.968 +** associated affinity type.
27.969 +**
27.970 +** This routine does a case-independent search of zType for the
27.971 +** substrings in the following table. If one of the substrings is
27.972 +** found, the corresponding affinity is returned. If zType contains
27.973 +** more than one of the substrings, entries toward the top of
27.974 +** the table take priority. For example, if zType is 'BLOBINT',
27.975 +** SQLITE_AFF_INTEGER is returned.
27.976 +**
27.977 +** Substring | Affinity
27.978 +** --------------------------------
27.979 +** 'INT' | SQLITE_AFF_INTEGER
27.980 +** 'CHAR' | SQLITE_AFF_TEXT
27.981 +** 'CLOB' | SQLITE_AFF_TEXT
27.982 +** 'TEXT' | SQLITE_AFF_TEXT
27.983 +** 'BLOB' | SQLITE_AFF_NONE
27.984 +** 'REAL' | SQLITE_AFF_REAL
27.985 +** 'FLOA' | SQLITE_AFF_REAL
27.986 +** 'DOUB' | SQLITE_AFF_REAL
27.987 +**
27.988 +** If none of the substrings in the above table are found,
27.989 +** SQLITE_AFF_NUMERIC is returned.
27.990 +*/
27.991 +char sqlite3AffinityType(const Token *pType){
27.992 + u32 h = 0;
27.993 + char aff = SQLITE_AFF_NUMERIC;
27.994 + const unsigned char *zIn = pType->z;
27.995 + const unsigned char *zEnd = &pType->z[pType->n];
27.996 +
27.997 + while( zIn!=zEnd ){
27.998 + h = (h<<8) + sqlite3UpperToLower[*zIn];
27.999 + zIn++;
27.1000 + if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
27.1001 + aff = SQLITE_AFF_TEXT;
27.1002 + }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
27.1003 + aff = SQLITE_AFF_TEXT;
27.1004 + }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
27.1005 + aff = SQLITE_AFF_TEXT;
27.1006 + }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
27.1007 + && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
27.1008 + aff = SQLITE_AFF_NONE;
27.1009 +#ifndef SQLITE_OMIT_FLOATING_POINT
27.1010 + }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
27.1011 + && aff==SQLITE_AFF_NUMERIC ){
27.1012 + aff = SQLITE_AFF_REAL;
27.1013 + }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
27.1014 + && aff==SQLITE_AFF_NUMERIC ){
27.1015 + aff = SQLITE_AFF_REAL;
27.1016 + }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
27.1017 + && aff==SQLITE_AFF_NUMERIC ){
27.1018 + aff = SQLITE_AFF_REAL;
27.1019 +#endif
27.1020 + }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
27.1021 + aff = SQLITE_AFF_INTEGER;
27.1022 + break;
27.1023 + }
27.1024 + }
27.1025 +
27.1026 + return aff;
27.1027 +}
27.1028 +
27.1029 +/*
27.1030 +** This routine is called by the parser while in the middle of
27.1031 +** parsing a CREATE TABLE statement. The pFirst token is the first
27.1032 +** token in the sequence of tokens that describe the type of the
27.1033 +** column currently under construction. pLast is the last token
27.1034 +** in the sequence. Use this information to construct a string
27.1035 +** that contains the typename of the column and store that string
27.1036 +** in zType.
27.1037 +*/
27.1038 +void sqlite3AddColumnType(Parse *pParse, Token *pType){
27.1039 + Table *p;
27.1040 + int i;
27.1041 + Column *pCol;
27.1042 +
27.1043 + if( (p = pParse->pNewTable)==0 ) return;
27.1044 + i = p->nCol-1;
27.1045 + if( i<0 ) return;
27.1046 + pCol = &p->aCol[i];
27.1047 + sqliteFree(pCol->zType);
27.1048 + pCol->zType = sqlite3NameFromToken(pType);
27.1049 + pCol->affinity = sqlite3AffinityType(pType);
27.1050 +}
27.1051 +
27.1052 +/*
27.1053 +** The expression is the default value for the most recently added column
27.1054 +** of the table currently under construction.
27.1055 +**
27.1056 +** Default value expressions must be constant. Raise an exception if this
27.1057 +** is not the case.
27.1058 +**
27.1059 +** This routine is called by the parser while in the middle of
27.1060 +** parsing a CREATE TABLE statement.
27.1061 +*/
27.1062 +void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
27.1063 + Table *p;
27.1064 + Column *pCol;
27.1065 + if( (p = pParse->pNewTable)!=0 ){
27.1066 + pCol = &(p->aCol[p->nCol-1]);
27.1067 + if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
27.1068 + sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
27.1069 + pCol->zName);
27.1070 + }else{
27.1071 + Expr *pCopy;
27.1072 + sqlite3ExprDelete(pCol->pDflt);
27.1073 + pCol->pDflt = pCopy = sqlite3ExprDup(pExpr);
27.1074 + if( pCopy ){
27.1075 + sqlite3TokenCopy(&pCopy->span, &pExpr->span);
27.1076 + }
27.1077 + }
27.1078 + }
27.1079 + sqlite3ExprDelete(pExpr);
27.1080 +}
27.1081 +
27.1082 +/*
27.1083 +** Designate the PRIMARY KEY for the table. pList is a list of names
27.1084 +** of columns that form the primary key. If pList is NULL, then the
27.1085 +** most recently added column of the table is the primary key.
27.1086 +**
27.1087 +** A table can have at most one primary key. If the table already has
27.1088 +** a primary key (and this is the second primary key) then create an
27.1089 +** error.
27.1090 +**
27.1091 +** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
27.1092 +** then we will try to use that column as the rowid. Set the Table.iPKey
27.1093 +** field of the table under construction to be the index of the
27.1094 +** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
27.1095 +** no INTEGER PRIMARY KEY.
27.1096 +**
27.1097 +** If the key is not an INTEGER PRIMARY KEY, then create a unique
27.1098 +** index for the key. No index is created for INTEGER PRIMARY KEYs.
27.1099 +*/
27.1100 +void sqlite3AddPrimaryKey(
27.1101 + Parse *pParse, /* Parsing context */
27.1102 + ExprList *pList, /* List of field names to be indexed */
27.1103 + int onError, /* What to do with a uniqueness conflict */
27.1104 + int autoInc, /* True if the AUTOINCREMENT keyword is present */
27.1105 + int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
27.1106 +){
27.1107 + Table *pTab = pParse->pNewTable;
27.1108 + char *zType = 0;
27.1109 + int iCol = -1, i;
27.1110 + if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
27.1111 + if( pTab->hasPrimKey ){
27.1112 + sqlite3ErrorMsg(pParse,
27.1113 + "table \"%s\" has more than one primary key", pTab->zName);
27.1114 + goto primary_key_exit;
27.1115 + }
27.1116 + pTab->hasPrimKey = 1;
27.1117 + if( pList==0 ){
27.1118 + iCol = pTab->nCol - 1;
27.1119 + pTab->aCol[iCol].isPrimKey = 1;
27.1120 + }else{
27.1121 + for(i=0; i<pList->nExpr; i++){
27.1122 + for(iCol=0; iCol<pTab->nCol; iCol++){
27.1123 + if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
27.1124 + break;
27.1125 + }
27.1126 + }
27.1127 + if( iCol<pTab->nCol ){
27.1128 + pTab->aCol[iCol].isPrimKey = 1;
27.1129 + }
27.1130 + }
27.1131 + if( pList->nExpr>1 ) iCol = -1;
27.1132 + }
27.1133 + if( iCol>=0 && iCol<pTab->nCol ){
27.1134 + zType = pTab->aCol[iCol].zType;
27.1135 + }
27.1136 + if( zType && sqlite3StrICmp(zType, "INTEGER")==0
27.1137 + && sortOrder==SQLITE_SO_ASC ){
27.1138 + pTab->iPKey = iCol;
27.1139 + pTab->keyConf = onError;
27.1140 + pTab->autoInc = autoInc;
27.1141 + }else if( autoInc ){
27.1142 +#ifndef SQLITE_OMIT_AUTOINCREMENT
27.1143 + sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
27.1144 + "INTEGER PRIMARY KEY");
27.1145 +#endif
27.1146 + }else{
27.1147 + sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
27.1148 + pList = 0;
27.1149 + }
27.1150 +
27.1151 +primary_key_exit:
27.1152 + sqlite3ExprListDelete(pList);
27.1153 + return;
27.1154 +}
27.1155 +
27.1156 +/*
27.1157 +** Add a new CHECK constraint to the table currently under construction.
27.1158 +*/
27.1159 +void sqlite3AddCheckConstraint(
27.1160 + Parse *pParse, /* Parsing context */
27.1161 + Expr *pCheckExpr /* The check expression */
27.1162 +){
27.1163 +#ifndef SQLITE_OMIT_CHECK
27.1164 + Table *pTab = pParse->pNewTable;
27.1165 + if( pTab && !IN_DECLARE_VTAB ){
27.1166 + /* The CHECK expression must be duplicated so that tokens refer
27.1167 + ** to malloced space and not the (ephemeral) text of the CREATE TABLE
27.1168 + ** statement */
27.1169 + pTab->pCheck = sqlite3ExprAnd(pTab->pCheck, sqlite3ExprDup(pCheckExpr));
27.1170 + }
27.1171 +#endif
27.1172 + sqlite3ExprDelete(pCheckExpr);
27.1173 +}
27.1174 +
27.1175 +/*
27.1176 +** Set the collation function of the most recently parsed table column
27.1177 +** to the CollSeq given.
27.1178 +*/
27.1179 +void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
27.1180 + Table *p;
27.1181 + int i;
27.1182 +
27.1183 + if( (p = pParse->pNewTable)==0 ) return;
27.1184 + i = p->nCol-1;
27.1185 +
27.1186 + if( sqlite3LocateCollSeq(pParse, zType, nType) ){
27.1187 + Index *pIdx;
27.1188 + p->aCol[i].zColl = sqliteStrNDup(zType, nType);
27.1189 +
27.1190 + /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
27.1191 + ** then an index may have been created on this column before the
27.1192 + ** collation type was added. Correct this if it is the case.
27.1193 + */
27.1194 + for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
27.1195 + assert( pIdx->nColumn==1 );
27.1196 + if( pIdx->aiColumn[0]==i ){
27.1197 + pIdx->azColl[0] = p->aCol[i].zColl;
27.1198 + }
27.1199 + }
27.1200 + }
27.1201 +}
27.1202 +
27.1203 +/*
27.1204 +** This function returns the collation sequence for database native text
27.1205 +** encoding identified by the string zName, length nName.
27.1206 +**
27.1207 +** If the requested collation sequence is not available, or not available
27.1208 +** in the database native encoding, the collation factory is invoked to
27.1209 +** request it. If the collation factory does not supply such a sequence,
27.1210 +** and the sequence is available in another text encoding, then that is
27.1211 +** returned instead.
27.1212 +**
27.1213 +** If no versions of the requested collations sequence are available, or
27.1214 +** another error occurs, NULL is returned and an error message written into
27.1215 +** pParse.
27.1216 +**
27.1217 +** This routine is a wrapper around sqlite3FindCollSeq(). This routine
27.1218 +** invokes the collation factory if the named collation cannot be found
27.1219 +** and generates an error message.
27.1220 +*/
27.1221 +CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
27.1222 + sqlite3 *db = pParse->db;
27.1223 + u8 enc = ENC(db);
27.1224 + u8 initbusy = db->init.busy;
27.1225 + CollSeq *pColl;
27.1226 +
27.1227 + pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
27.1228 + if( !initbusy && (!pColl || !pColl->xCmp) ){
27.1229 + pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
27.1230 + if( !pColl ){
27.1231 + if( nName<0 ){
27.1232 + nName = strlen(zName);
27.1233 + }
27.1234 + sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
27.1235 + pColl = 0;
27.1236 + }
27.1237 + }
27.1238 +
27.1239 + return pColl;
27.1240 +}
27.1241 +
27.1242 +
27.1243 +/*
27.1244 +** Generate code that will increment the schema cookie.
27.1245 +**
27.1246 +** The schema cookie is used to determine when the schema for the
27.1247 +** database changes. After each schema change, the cookie value
27.1248 +** changes. When a process first reads the schema it records the
27.1249 +** cookie. Thereafter, whenever it goes to access the database,
27.1250 +** it checks the cookie to make sure the schema has not changed
27.1251 +** since it was last read.
27.1252 +**
27.1253 +** This plan is not completely bullet-proof. It is possible for
27.1254 +** the schema to change multiple times and for the cookie to be
27.1255 +** set back to prior value. But schema changes are infrequent
27.1256 +** and the probability of hitting the same cookie value is only
27.1257 +** 1 chance in 2^32. So we're safe enough.
27.1258 +*/
27.1259 +void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
27.1260 + sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, 0);
27.1261 + sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
27.1262 +}
27.1263 +
27.1264 +/*
27.1265 +** Measure the number of characters needed to output the given
27.1266 +** identifier. The number returned includes any quotes used
27.1267 +** but does not include the null terminator.
27.1268 +**
27.1269 +** The estimate is conservative. It might be larger that what is
27.1270 +** really needed.
27.1271 +*/
27.1272 +static int identLength(const char *z){
27.1273 + int n;
27.1274 + for(n=0; *z; n++, z++){
27.1275 + if( *z=='"' ){ n++; }
27.1276 + }
27.1277 + return n + 2;
27.1278 +}
27.1279 +
27.1280 +/*
27.1281 +** Write an identifier onto the end of the given string. Add
27.1282 +** quote characters as needed.
27.1283 +*/
27.1284 +static void identPut(char *z, int *pIdx, char *zSignedIdent){
27.1285 + unsigned char *zIdent = (unsigned char*)zSignedIdent;
27.1286 + int i, j, needQuote;
27.1287 + i = *pIdx;
27.1288 + for(j=0; zIdent[j]; j++){
27.1289 + if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
27.1290 + }
27.1291 + needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
27.1292 + || sqlite3KeywordCode(zIdent, j)!=TK_ID;
27.1293 + if( needQuote ) z[i++] = '"';
27.1294 + for(j=0; zIdent[j]; j++){
27.1295 + z[i++] = zIdent[j];
27.1296 + if( zIdent[j]=='"' ) z[i++] = '"';
27.1297 + }
27.1298 + if( needQuote ) z[i++] = '"';
27.1299 + z[i] = 0;
27.1300 + *pIdx = i;
27.1301 +}
27.1302 +
27.1303 +/*
27.1304 +** Generate a CREATE TABLE statement appropriate for the given
27.1305 +** table. Memory to hold the text of the statement is obtained
27.1306 +** from sqliteMalloc() and must be freed by the calling function.
27.1307 +*/
27.1308 +static char *createTableStmt(Table *p, int isTemp){
27.1309 + int i, k, n;
27.1310 + char *zStmt;
27.1311 + char *zSep, *zSep2, *zEnd, *z;
27.1312 + Column *pCol;
27.1313 + n = 0;
27.1314 + for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
27.1315 + n += identLength(pCol->zName);
27.1316 + z = pCol->zType;
27.1317 + if( z ){
27.1318 + n += (strlen(z) + 1);
27.1319 + }
27.1320 + }
27.1321 + n += identLength(p->zName);
27.1322 + if( n<50 ){
27.1323 + zSep = "";
27.1324 + zSep2 = ",";
27.1325 + zEnd = ")";
27.1326 + }else{
27.1327 + zSep = "\n ";
27.1328 + zSep2 = ",\n ";
27.1329 + zEnd = "\n)";
27.1330 + }
27.1331 + n += 35 + 6*p->nCol;
27.1332 + zStmt = sqliteMallocRaw( n );
27.1333 + if( zStmt==0 ) return 0;
27.1334 + sqlite3_snprintf(n, zStmt,
27.1335 + !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
27.1336 + k = strlen(zStmt);
27.1337 + identPut(zStmt, &k, p->zName);
27.1338 + zStmt[k++] = '(';
27.1339 + for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
27.1340 + sqlite3_snprintf(n-k, &zStmt[k], zSep);
27.1341 + k += strlen(&zStmt[k]);
27.1342 + zSep = zSep2;
27.1343 + identPut(zStmt, &k, pCol->zName);
27.1344 + if( (z = pCol->zType)!=0 ){
27.1345 + zStmt[k++] = ' ';
27.1346 + assert( strlen(z)+k+1<=n );
27.1347 + sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
27.1348 + k += strlen(z);
27.1349 + }
27.1350 + }
27.1351 + sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
27.1352 + return zStmt;
27.1353 +}
27.1354 +
27.1355 +/*
27.1356 +** This routine is called to report the final ")" that terminates
27.1357 +** a CREATE TABLE statement.
27.1358 +**
27.1359 +** The table structure that other action routines have been building
27.1360 +** is added to the internal hash tables, assuming no errors have
27.1361 +** occurred.
27.1362 +**
27.1363 +** An entry for the table is made in the master table on disk, unless
27.1364 +** this is a temporary table or db->init.busy==1. When db->init.busy==1
27.1365 +** it means we are reading the sqlite_master table because we just
27.1366 +** connected to the database or because the sqlite_master table has
27.1367 +** recently changed, so the entry for this table already exists in
27.1368 +** the sqlite_master table. We do not want to create it again.
27.1369 +**
27.1370 +** If the pSelect argument is not NULL, it means that this routine
27.1371 +** was called to create a table generated from a
27.1372 +** "CREATE TABLE ... AS SELECT ..." statement. The column names of
27.1373 +** the new table will match the result set of the SELECT.
27.1374 +*/
27.1375 +void sqlite3EndTable(
27.1376 + Parse *pParse, /* Parse context */
27.1377 + Token *pCons, /* The ',' token after the last column defn. */
27.1378 + Token *pEnd, /* The final ')' token in the CREATE TABLE */
27.1379 + Select *pSelect /* Select from a "CREATE ... AS SELECT" */
27.1380 +){
27.1381 + Table *p;
27.1382 + sqlite3 *db = pParse->db;
27.1383 + int iDb;
27.1384 +
27.1385 + if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3MallocFailed() ) {
27.1386 + return;
27.1387 + }
27.1388 + p = pParse->pNewTable;
27.1389 + if( p==0 ) return;
27.1390 +
27.1391 + assert( !db->init.busy || !pSelect );
27.1392 +
27.1393 + iDb = sqlite3SchemaToIndex(db, p->pSchema);
27.1394 +
27.1395 +#ifndef SQLITE_OMIT_CHECK
27.1396 + /* Resolve names in all CHECK constraint expressions.
27.1397 + */
27.1398 + if( p->pCheck ){
27.1399 + SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
27.1400 + NameContext sNC; /* Name context for pParse->pNewTable */
27.1401 +
27.1402 + memset(&sNC, 0, sizeof(sNC));
27.1403 + memset(&sSrc, 0, sizeof(sSrc));
27.1404 + sSrc.nSrc = 1;
27.1405 + sSrc.a[0].zName = p->zName;
27.1406 + sSrc.a[0].pTab = p;
27.1407 + sSrc.a[0].iCursor = -1;
27.1408 + sNC.pParse = pParse;
27.1409 + sNC.pSrcList = &sSrc;
27.1410 + sNC.isCheck = 1;
27.1411 + if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){
27.1412 + return;
27.1413 + }
27.1414 + }
27.1415 +#endif /* !defined(SQLITE_OMIT_CHECK) */
27.1416 +
27.1417 + /* If the db->init.busy is 1 it means we are reading the SQL off the
27.1418 + ** "sqlite_master" or "sqlite_temp_master" table on the disk.
27.1419 + ** So do not write to the disk again. Extract the root page number
27.1420 + ** for the table from the db->init.newTnum field. (The page number
27.1421 + ** should have been put there by the sqliteOpenCb routine.)
27.1422 + */
27.1423 + if( db->init.busy ){
27.1424 + p->tnum = db->init.newTnum;
27.1425 + }
27.1426 +
27.1427 + /* If not initializing, then create a record for the new table
27.1428 + ** in the SQLITE_MASTER table of the database. The record number
27.1429 + ** for the new table entry should already be on the stack.
27.1430 + **
27.1431 + ** If this is a TEMPORARY table, write the entry into the auxiliary
27.1432 + ** file instead of into the main database file.
27.1433 + */
27.1434 + if( !db->init.busy ){
27.1435 + int n;
27.1436 + Vdbe *v;
27.1437 + char *zType; /* "view" or "table" */
27.1438 + char *zType2; /* "VIEW" or "TABLE" */
27.1439 + char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
27.1440 +
27.1441 + v = sqlite3GetVdbe(pParse);
27.1442 + if( v==0 ) return;
27.1443 +
27.1444 + sqlite3VdbeAddOp(v, OP_Close, 0, 0);
27.1445 +
27.1446 + /* Create the rootpage for the new table and push it onto the stack.
27.1447 + ** A view has no rootpage, so just push a zero onto the stack for
27.1448 + ** views. Initialize zType at the same time.
27.1449 + */
27.1450 + if( p->pSelect==0 ){
27.1451 + /* A regular table */
27.1452 + zType = "table";
27.1453 + zType2 = "TABLE";
27.1454 +#ifndef SQLITE_OMIT_VIEW
27.1455 + }else{
27.1456 + /* A view */
27.1457 + zType = "view";
27.1458 + zType2 = "VIEW";
27.1459 +#endif
27.1460 + }
27.1461 +
27.1462 + /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
27.1463 + ** statement to populate the new table. The root-page number for the
27.1464 + ** new table is on the top of the vdbe stack.
27.1465 + **
27.1466 + ** Once the SELECT has been coded by sqlite3Select(), it is in a
27.1467 + ** suitable state to query for the column names and types to be used
27.1468 + ** by the new table.
27.1469 + **
27.1470 + ** A shared-cache write-lock is not required to write to the new table,
27.1471 + ** as a schema-lock must have already been obtained to create it. Since
27.1472 + ** a schema-lock excludes all other database users, the write-lock would
27.1473 + ** be redundant.
27.1474 + */
27.1475 + if( pSelect ){
27.1476 + Table *pSelTab;
27.1477 + sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
27.1478 + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
27.1479 + sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
27.1480 + pParse->nTab = 2;
27.1481 + sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
27.1482 + sqlite3VdbeAddOp(v, OP_Close, 1, 0);
27.1483 + if( pParse->nErr==0 ){
27.1484 + pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
27.1485 + if( pSelTab==0 ) return;
27.1486 + assert( p->aCol==0 );
27.1487 + p->nCol = pSelTab->nCol;
27.1488 + p->aCol = pSelTab->aCol;
27.1489 + pSelTab->nCol = 0;
27.1490 + pSelTab->aCol = 0;
27.1491 + sqlite3DeleteTable(pSelTab);
27.1492 + }
27.1493 + }
27.1494 +
27.1495 + /* Compute the complete text of the CREATE statement */
27.1496 + if( pSelect ){
27.1497 + zStmt = createTableStmt(p, p->pSchema==pParse->db->aDb[1].pSchema);
27.1498 + }else{
27.1499 + n = pEnd->z - pParse->sNameToken.z + 1;
27.1500 + zStmt = sqlite3MPrintf("CREATE %s %.*s", zType2, n, pParse->sNameToken.z);
27.1501 + }
27.1502 +
27.1503 + /* A slot for the record has already been allocated in the
27.1504 + ** SQLITE_MASTER table. We just need to update that slot with all
27.1505 + ** the information we've collected. The rowid for the preallocated
27.1506 + ** slot is the 2nd item on the stack. The top of the stack is the
27.1507 + ** root page for the new table (or a 0 if this is a view).
27.1508 + */
27.1509 + sqlite3NestedParse(pParse,
27.1510 + "UPDATE %Q.%s "
27.1511 + "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q "
27.1512 + "WHERE rowid=#1",
27.1513 + db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
27.1514 + zType,
27.1515 + p->zName,
27.1516 + p->zName,
27.1517 + zStmt
27.1518 + );
27.1519 + sqliteFree(zStmt);
27.1520 + sqlite3ChangeCookie(db, v, iDb);
27.1521 +
27.1522 +#ifndef SQLITE_OMIT_AUTOINCREMENT
27.1523 + /* Check to see if we need to create an sqlite_sequence table for
27.1524 + ** keeping track of autoincrement keys.
27.1525 + */
27.1526 + if( p->autoInc ){
27.1527 + Db *pDb = &db->aDb[iDb];
27.1528 + if( pDb->pSchema->pSeqTab==0 ){
27.1529 + sqlite3NestedParse(pParse,
27.1530 + "CREATE TABLE %Q.sqlite_sequence(name,seq)",
27.1531 + pDb->zName
27.1532 + );
27.1533 + }
27.1534 + }
27.1535 +#endif
27.1536 +
27.1537 + /* Reparse everything to update our internal data structures */
27.1538 + sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
27.1539 + sqlite3MPrintf("tbl_name='%q'",p->zName), P3_DYNAMIC);
27.1540 + }
27.1541 +
27.1542 +
27.1543 + /* Add the table to the in-memory representation of the database.
27.1544 + */
27.1545 + if( db->init.busy && pParse->nErr==0 ){
27.1546 + Table *pOld;
27.1547 + FKey *pFKey;
27.1548 + Schema *pSchema = p->pSchema;
27.1549 + pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
27.1550 + if( pOld ){
27.1551 + assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
27.1552 + return;
27.1553 + }
27.1554 +#ifndef SQLITE_OMIT_FOREIGN_KEY
27.1555 + for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
27.1556 + int nTo = strlen(pFKey->zTo) + 1;
27.1557 + pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
27.1558 + sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
27.1559 + }
27.1560 +#endif
27.1561 + pParse->pNewTable = 0;
27.1562 + db->nTable++;
27.1563 + db->flags |= SQLITE_InternChanges;
27.1564 +
27.1565 +#ifndef SQLITE_OMIT_ALTERTABLE
27.1566 + if( !p->pSelect ){
27.1567 + const char *zName = (const char *)pParse->sNameToken.z;
27.1568 + int nName;
27.1569 + assert( !pSelect && pCons && pEnd );
27.1570 + if( pCons->z==0 ){
27.1571 + pCons = pEnd;
27.1572 + }
27.1573 + nName = (const char *)pCons->z - zName;
27.1574 + p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
27.1575 + }
27.1576 +#endif
27.1577 + }
27.1578 +}
27.1579 +
27.1580 +#ifndef SQLITE_OMIT_VIEW
27.1581 +/*
27.1582 +** The parser calls this routine in order to create a new VIEW
27.1583 +*/
27.1584 +void sqlite3CreateView(
27.1585 + Parse *pParse, /* The parsing context */
27.1586 + Token *pBegin, /* The CREATE token that begins the statement */
27.1587 + Token *pName1, /* The token that holds the name of the view */
27.1588 + Token *pName2, /* The token that holds the name of the view */
27.1589 + Select *pSelect, /* A SELECT statement that will become the new view */
27.1590 + int isTemp, /* TRUE for a TEMPORARY view */
27.1591 + int noErr /* Suppress error messages if VIEW already exists */
27.1592 +){
27.1593 + Table *p;
27.1594 + int n;
27.1595 + const unsigned char *z;
27.1596 + Token sEnd;
27.1597 + DbFixer sFix;
27.1598 + Token *pName;
27.1599 + int iDb;
27.1600 +
27.1601 + if( pParse->nVar>0 ){
27.1602 + sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
27.1603 + sqlite3SelectDelete(pSelect);
27.1604 + return;
27.1605 + }
27.1606 + sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
27.1607 + p = pParse->pNewTable;
27.1608 + if( p==0 || pParse->nErr ){
27.1609 + sqlite3SelectDelete(pSelect);
27.1610 + return;
27.1611 + }
27.1612 + sqlite3TwoPartName(pParse, pName1, pName2, &pName);
27.1613 + iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
27.1614 + if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
27.1615 + && sqlite3FixSelect(&sFix, pSelect)
27.1616 + ){
27.1617 + sqlite3SelectDelete(pSelect);
27.1618 + return;
27.1619 + }
27.1620 +
27.1621 + /* Make a copy of the entire SELECT statement that defines the view.
27.1622 + ** This will force all the Expr.token.z values to be dynamically
27.1623 + ** allocated rather than point to the input string - which means that
27.1624 + ** they will persist after the current sqlite3_exec() call returns.
27.1625 + */
27.1626 + p->pSelect = sqlite3SelectDup(pSelect);
27.1627 + sqlite3SelectDelete(pSelect);
27.1628 + if( sqlite3MallocFailed() ){
27.1629 + return;
27.1630 + }
27.1631 + if( !pParse->db->init.busy ){
27.1632 + sqlite3ViewGetColumnNames(pParse, p);
27.1633 + }
27.1634 +
27.1635 + /* Locate the end of the CREATE VIEW statement. Make sEnd point to
27.1636 + ** the end.
27.1637 + */
27.1638 + sEnd = pParse->sLastToken;
27.1639 + if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
27.1640 + sEnd.z += sEnd.n;
27.1641 + }
27.1642 + sEnd.n = 0;
27.1643 + n = sEnd.z - pBegin->z;
27.1644 + z = (const unsigned char*)pBegin->z;
27.1645 + while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
27.1646 + sEnd.z = &z[n-1];
27.1647 + sEnd.n = 1;
27.1648 +
27.1649 + /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
27.1650 + sqlite3EndTable(pParse, 0, &sEnd, 0);
27.1651 + return;
27.1652 +}
27.1653 +#endif /* SQLITE_OMIT_VIEW */
27.1654 +
27.1655 +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
27.1656 +/*
27.1657 +** The Table structure pTable is really a VIEW. Fill in the names of
27.1658 +** the columns of the view in the pTable structure. Return the number
27.1659 +** of errors. If an error is seen leave an error message in pParse->zErrMsg.
27.1660 +*/
27.1661 +int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
27.1662 + Table *pSelTab; /* A fake table from which we get the result set */
27.1663 + Select *pSel; /* Copy of the SELECT that implements the view */
27.1664 + int nErr = 0; /* Number of errors encountered */
27.1665 + int n; /* Temporarily holds the number of cursors assigned */
27.1666 +
27.1667 + assert( pTable );
27.1668 +
27.1669 +#ifndef SQLITE_OMIT_VIRTUALTABLE
27.1670 + if( sqlite3VtabCallConnect(pParse, pTable) ){
27.1671 + return SQLITE_ERROR;
27.1672 + }
27.1673 + if( IsVirtual(pTable) ) return 0;
27.1674 +#endif
27.1675 +
27.1676 +#ifndef SQLITE_OMIT_VIEW
27.1677 + /* A positive nCol means the columns names for this view are
27.1678 + ** already known.
27.1679 + */
27.1680 + if( pTable->nCol>0 ) return 0;
27.1681 +
27.1682 + /* A negative nCol is a special marker meaning that we are currently
27.1683 + ** trying to compute the column names. If we enter this routine with
27.1684 + ** a negative nCol, it means two or more views form a loop, like this:
27.1685 + **
27.1686 + ** CREATE VIEW one AS SELECT * FROM two;
27.1687 + ** CREATE VIEW two AS SELECT * FROM one;
27.1688 + **
27.1689 + ** Actually, this error is caught previously and so the following test
27.1690 + ** should always fail. But we will leave it in place just to be safe.
27.1691 + */
27.1692 + if( pTable->nCol<0 ){
27.1693 + sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
27.1694 + return 1;
27.1695 + }
27.1696 + assert( pTable->nCol>=0 );
27.1697 +
27.1698 + /* If we get this far, it means we need to compute the table names.
27.1699 + ** Note that the call to sqlite3ResultSetOfSelect() will expand any
27.1700 + ** "*" elements in the results set of the view and will assign cursors
27.1701 + ** to the elements of the FROM clause. But we do not want these changes
27.1702 + ** to be permanent. So the computation is done on a copy of the SELECT
27.1703 + ** statement that defines the view.
27.1704 + */
27.1705 + assert( pTable->pSelect );
27.1706 + pSel = sqlite3SelectDup(pTable->pSelect);
27.1707 + if( pSel ){
27.1708 + n = pParse->nTab;
27.1709 + sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
27.1710 + pTable->nCol = -1;
27.1711 + pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
27.1712 + pParse->nTab = n;
27.1713 + if( pSelTab ){
27.1714 + assert( pTable->aCol==0 );
27.1715 + pTable->nCol = pSelTab->nCol;
27.1716 + pTable->aCol = pSelTab->aCol;
27.1717 + pSelTab->nCol = 0;
27.1718 + pSelTab->aCol = 0;
27.1719 + sqlite3DeleteTable(pSelTab);
27.1720 + pTable->pSchema->flags |= DB_UnresetViews;
27.1721 + }else{
27.1722 + pTable->nCol = 0;
27.1723 + nErr++;
27.1724 + }
27.1725 + sqlite3SelectDelete(pSel);
27.1726 + } else {
27.1727 + nErr++;
27.1728 + }
27.1729 +#endif /* SQLITE_OMIT_VIEW */
27.1730 + return nErr;
27.1731 +}
27.1732 +#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
27.1733 +
27.1734 +#ifndef SQLITE_OMIT_VIEW
27.1735 +/*
27.1736 +** Clear the column names from every VIEW in database idx.
27.1737 +*/
27.1738 +static void sqliteViewResetAll(sqlite3 *db, int idx){
27.1739 + HashElem *i;
27.1740 + if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
27.1741 + for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
27.1742 + Table *pTab = sqliteHashData(i);
27.1743 + if( pTab->pSelect ){
27.1744 + sqliteResetColumnNames(pTab);
27.1745 + }
27.1746 + }
27.1747 + DbClearProperty(db, idx, DB_UnresetViews);
27.1748 +}
27.1749 +#else
27.1750 +# define sqliteViewResetAll(A,B)
27.1751 +#endif /* SQLITE_OMIT_VIEW */
27.1752 +
27.1753 +/*
27.1754 +** This function is called by the VDBE to adjust the internal schema
27.1755 +** used by SQLite when the btree layer moves a table root page. The
27.1756 +** root-page of a table or index in database iDb has changed from iFrom
27.1757 +** to iTo.
27.1758 +**
27.1759 +** Ticket #1728: The symbol table might still contain information
27.1760 +** on tables and/or indices that are the process of being deleted.
27.1761 +** If you are unlucky, one of those deleted indices or tables might
27.1762 +** have the same rootpage number as the real table or index that is
27.1763 +** being moved. So we cannot stop searching after the first match
27.1764 +** because the first match might be for one of the deleted indices
27.1765 +** or tables and not the table/index that is actually being moved.
27.1766 +** We must continue looping until all tables and indices with
27.1767 +** rootpage==iFrom have been converted to have a rootpage of iTo
27.1768 +** in order to be certain that we got the right one.
27.1769 +*/
27.1770 +#ifndef SQLITE_OMIT_AUTOVACUUM
27.1771 +void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
27.1772 + HashElem *pElem;
27.1773 + Hash *pHash;
27.1774 +
27.1775 + pHash = &pDb->pSchema->tblHash;
27.1776 + for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
27.1777 + Table *pTab = sqliteHashData(pElem);
27.1778 + if( pTab->tnum==iFrom ){
27.1779 + pTab->tnum = iTo;
27.1780 + }
27.1781 + }
27.1782 + pHash = &pDb->pSchema->idxHash;
27.1783 + for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
27.1784 + Index *pIdx = sqliteHashData(pElem);
27.1785 + if( pIdx->tnum==iFrom ){
27.1786 + pIdx->tnum = iTo;
27.1787 + }
27.1788 + }
27.1789 +}
27.1790 +#endif
27.1791 +
27.1792 +/*
27.1793 +** Write code to erase the table with root-page iTable from database iDb.
27.1794 +** Also write code to modify the sqlite_master table and internal schema
27.1795 +** if a root-page of another table is moved by the btree-layer whilst
27.1796 +** erasing iTable (this can happen with an auto-vacuum database).
27.1797 +*/
27.1798 +static void destroyRootPage(Parse *pParse, int iTable, int iDb){
27.1799 + Vdbe *v = sqlite3GetVdbe(pParse);
27.1800 + sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb);
27.1801 +#ifndef SQLITE_OMIT_AUTOVACUUM
27.1802 + /* OP_Destroy pushes an integer onto the stack. If this integer
27.1803 + ** is non-zero, then it is the root page number of a table moved to
27.1804 + ** location iTable. The following code modifies the sqlite_master table to
27.1805 + ** reflect this.
27.1806 + **
27.1807 + ** The "#0" in the SQL is a special constant that means whatever value
27.1808 + ** is on the top of the stack. See sqlite3RegisterExpr().
27.1809 + */
27.1810 + sqlite3NestedParse(pParse,
27.1811 + "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0",
27.1812 + pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable);
27.1813 +#endif
27.1814 +}
27.1815 +
27.1816 +/*
27.1817 +** Write VDBE code to erase table pTab and all associated indices on disk.
27.1818 +** Code to update the sqlite_master tables and internal schema definitions
27.1819 +** in case a root-page belonging to another table is moved by the btree layer
27.1820 +** is also added (this can happen with an auto-vacuum database).
27.1821 +*/
27.1822 +static void destroyTable(Parse *pParse, Table *pTab){
27.1823 +#ifdef SQLITE_OMIT_AUTOVACUUM
27.1824 + Index *pIdx;
27.1825 + int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
27.1826 + destroyRootPage(pParse, pTab->tnum, iDb);
27.1827 + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
27.1828 + destroyRootPage(pParse, pIdx->tnum, iDb);
27.1829 + }
27.1830 +#else
27.1831 + /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
27.1832 + ** is not defined), then it is important to call OP_Destroy on the
27.1833 + ** table and index root-pages in order, starting with the numerically
27.1834 + ** largest root-page number. This guarantees that none of the root-pages
27.1835 + ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
27.1836 + ** following were coded:
27.1837 + **
27.1838 + ** OP_Destroy 4 0
27.1839 + ** ...
27.1840 + ** OP_Destroy 5 0
27.1841 + **
27.1842 + ** and root page 5 happened to be the largest root-page number in the
27.1843 + ** database, then root page 5 would be moved to page 4 by the
27.1844 + ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
27.1845 + ** a free-list page.
27.1846 + */
27.1847 + int iTab = pTab->tnum;
27.1848 + int iDestroyed = 0;
27.1849 +
27.1850 + while( 1 ){
27.1851 + Index *pIdx;
27.1852 + int iLargest = 0;
27.1853 +
27.1854 + if( iDestroyed==0 || iTab<iDestroyed ){
27.1855 + iLargest = iTab;
27.1856 + }
27.1857 + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
27.1858 + int iIdx = pIdx->tnum;
27.1859 + assert( pIdx->pSchema==pTab->pSchema );
27.1860 + if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
27.1861 + iLargest = iIdx;
27.1862 + }
27.1863 + }
27.1864 + if( iLargest==0 ){
27.1865 + return;
27.1866 + }else{
27.1867 + int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
27.1868 + destroyRootPage(pParse, iLargest, iDb);
27.1869 + iDestroyed = iLargest;
27.1870 + }
27.1871 + }
27.1872 +#endif
27.1873 +}
27.1874 +
27.1875 +/*
27.1876 +** This routine is called to do the work of a DROP TABLE statement.
27.1877 +** pName is the name of the table to be dropped.
27.1878 +*/
27.1879 +void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
27.1880 + Table *pTab;
27.1881 + Vdbe *v;
27.1882 + sqlite3 *db = pParse->db;
27.1883 + int iDb;
27.1884 +
27.1885 + if( pParse->nErr || sqlite3MallocFailed() ){
27.1886 + goto exit_drop_table;
27.1887 + }
27.1888 + assert( pName->nSrc==1 );
27.1889 + pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
27.1890 +
27.1891 + if( pTab==0 ){
27.1892 + if( noErr ){
27.1893 + sqlite3ErrorClear(pParse);
27.1894 + }
27.1895 + goto exit_drop_table;
27.1896 + }
27.1897 + iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
27.1898 + assert( iDb>=0 && iDb<db->nDb );
27.1899 +#ifndef SQLITE_OMIT_AUTHORIZATION
27.1900 + {
27.1901 + int code;
27.1902 + const char *zTab = SCHEMA_TABLE(iDb);
27.1903 + const char *zDb = db->aDb[iDb].zName;
27.1904 + const char *zArg2 = 0;
27.1905 + if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
27.1906 + goto exit_drop_table;
27.1907 + }
27.1908 + if( isView ){
27.1909 + if( !OMIT_TEMPDB && iDb==1 ){
27.1910 + code = SQLITE_DROP_TEMP_VIEW;
27.1911 + }else{
27.1912 + code = SQLITE_DROP_VIEW;
27.1913 + }
27.1914 +#ifndef SQLITE_OMIT_VIRTUALTABLE
27.1915 + }else if( IsVirtual(pTab) ){
27.1916 + if( sqlite3ViewGetColumnNames(pParse, pTab) ){
27.1917 + goto exit_drop_table;
27.1918 + }
27.1919 + code = SQLITE_DROP_VTABLE;
27.1920 + zArg2 = pTab->pMod->zName;
27.1921 +#endif
27.1922 + }else{
27.1923 + if( !OMIT_TEMPDB && iDb==1 ){
27.1924 + code = SQLITE_DROP_TEMP_TABLE;
27.1925 + }else{
27.1926 + code = SQLITE_DROP_TABLE;
27.1927 + }
27.1928 + }
27.1929 + if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
27.1930 + goto exit_drop_table;
27.1931 + }
27.1932 + if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
27.1933 + goto exit_drop_table;
27.1934 + }
27.1935 + }
27.1936 +#endif
27.1937 + if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){
27.1938 + sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
27.1939 + goto exit_drop_table;
27.1940 + }
27.1941 +
27.1942 +#ifndef SQLITE_OMIT_VIEW
27.1943 + /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
27.1944 + ** on a table.
27.1945 + */
27.1946 + if( isView && pTab->pSelect==0 ){
27.1947 + sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
27.1948 + goto exit_drop_table;
27.1949 + }
27.1950 + if( !isView && pTab->pSelect ){
27.1951 + sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
27.1952 + goto exit_drop_table;
27.1953 + }
27.1954 +#endif
27.1955 +
27.1956 + /* Generate code to remove the table from the master table
27.1957 + ** on disk.
27.1958 + */
27.1959 + v = sqlite3GetVdbe(pParse);
27.1960 + if( v ){
27.1961 + Trigger *pTrigger;
27.1962 + Db *pDb = &db->aDb[iDb];
27.1963 + sqlite3BeginWriteOperation(pParse, 0, iDb);
27.1964 +
27.1965 +#ifndef SQLITE_OMIT_VIRTUALTABLE
27.1966 + if( IsVirtual(pTab) ){
27.1967 + Vdbe *v = sqlite3GetVdbe(pParse);
27.1968 + if( v ){
27.1969 + sqlite3VdbeAddOp(v, OP_VBegin, 0, 0);
27.1970 + }
27.1971 + }
27.1972 +#endif
27.1973 +
27.1974 + /* Drop all triggers associated with the table being dropped. Code
27.1975 + ** is generated to remove entries from sqlite_master and/or
27.1976 + ** sqlite_temp_master if required.
27.1977 + */
27.1978 + pTrigger = pTab->pTrigger;
27.1979 + while( pTrigger ){
27.1980 + assert( pTrigger->pSchema==pTab->pSchema ||
27.1981 + pTrigger->pSchema==db->aDb[1].pSchema );
27.1982 + sqlite3DropTriggerPtr(pParse, pTrigger);
27.1983 + pTrigger = pTrigger->pNext;
27.1984 + }
27.1985 +
27.1986 +#ifndef SQLITE_OMIT_AUTOINCREMENT
27.1987 + /* Remove any entries of the sqlite_sequence table associated with
27.1988 + ** the table being dropped. This is done before the table is dropped
27.1989 + ** at the btree level, in case the sqlite_sequence table needs to
27.1990 + ** move as a result of the drop (can happen in auto-vacuum mode).
27.1991 + */
27.1992 + if( pTab->autoInc ){
27.1993 + sqlite3NestedParse(pParse,
27.1994 + "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
27.1995 + pDb->zName, pTab->zName
27.1996 + );
27.1997 + }
27.1998 +#endif
27.1999 +
27.2000 + /* Drop all SQLITE_MASTER table and index entries that refer to the
27.2001 + ** table. The program name loops through the master table and deletes
27.2002 + ** every row that refers to a table of the same name as the one being
27.2003 + ** dropped. Triggers are handled seperately because a trigger can be
27.2004 + ** created in the temp database that refers to a table in another
27.2005 + ** database.
27.2006 + */
27.2007 + sqlite3NestedParse(pParse,
27.2008 + "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
27.2009 + pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
27.2010 + if( !isView && !IsVirtual(pTab) ){
27.2011 + destroyTable(pParse, pTab);
27.2012 + }
27.2013 +
27.2014 + /* Remove the table entry from SQLite's internal schema and modify
27.2015 + ** the schema cookie.
27.2016 + */
27.2017 + if( IsVirtual(pTab) ){
27.2018 + sqlite3VdbeOp3(v, OP_VDestroy, iDb, 0, pTab->zName, 0);
27.2019 + }
27.2020 + sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
27.2021 + sqlite3ChangeCookie(db, v, iDb);
27.2022 + }
27.2023 + sqliteViewResetAll(db, iDb);
27.2024 +
27.2025 +exit_drop_table:
27.2026 + sqlite3SrcListDelete(pName);
27.2027 +}
27.2028 +
27.2029 +/*
27.2030 +** This routine is called to create a new foreign key on the table
27.2031 +** currently under construction. pFromCol determines which columns
27.2032 +** in the current table point to the foreign key. If pFromCol==0 then
27.2033 +** connect the key to the last column inserted. pTo is the name of
27.2034 +** the table referred to. pToCol is a list of tables in the other
27.2035 +** pTo table that the foreign key points to. flags contains all
27.2036 +** information about the conflict resolution algorithms specified
27.2037 +** in the ON DELETE, ON UPDATE and ON INSERT clauses.
27.2038 +**
27.2039 +** An FKey structure is created and added to the table currently
27.2040 +** under construction in the pParse->pNewTable field. The new FKey
27.2041 +** is not linked into db->aFKey at this point - that does not happen
27.2042 +** until sqlite3EndTable().
27.2043 +**
27.2044 +** The foreign key is set for IMMEDIATE processing. A subsequent call
27.2045 +** to sqlite3DeferForeignKey() might change this to DEFERRED.
27.2046 +*/
27.2047 +void sqlite3CreateForeignKey(
27.2048 + Parse *pParse, /* Parsing context */
27.2049 + ExprList *pFromCol, /* Columns in this table that point to other table */
27.2050 + Token *pTo, /* Name of the other table */
27.2051 + ExprList *pToCol, /* Columns in the other table */
27.2052 + int flags /* Conflict resolution algorithms. */
27.2053 +){
27.2054 +#ifndef SQLITE_OMIT_FOREIGN_KEY
27.2055 + FKey *pFKey = 0;
27.2056 + Table *p = pParse->pNewTable;
27.2057 + int nByte;
27.2058 + int i;
27.2059 + int nCol;
27.2060 + char *z;
27.2061 +
27.2062 + assert( pTo!=0 );
27.2063 + if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
27.2064 + if( pFromCol==0 ){
27.2065 + int iCol = p->nCol-1;
27.2066 + if( iCol<0 ) goto fk_end;
27.2067 + if( pToCol && pToCol->nExpr!=1 ){
27.2068 + sqlite3ErrorMsg(pParse, "foreign key on %s"
27.2069 + " should reference only one column of table %T",
27.2070 + p->aCol[iCol].zName, pTo);
27.2071 + goto fk_end;
27.2072 + }
27.2073 + nCol = 1;
27.2074 + }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
27.2075 + sqlite3ErrorMsg(pParse,
27.2076 + "number of columns in foreign key does not match the number of "
27.2077 + "columns in the referenced table");
27.2078 + goto fk_end;
27.2079 + }else{
27.2080 + nCol = pFromCol->nExpr;
27.2081 + }
27.2082 + nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
27.2083 + if( pToCol ){
27.2084 + for(i=0; i<pToCol->nExpr; i++){
27.2085 + nByte += strlen(pToCol->a[i].zName) + 1;
27.2086 + }
27.2087 + }
27.2088 + pFKey = sqliteMalloc( nByte );
27.2089 + if( pFKey==0 ) goto fk_end;
27.2090 + pFKey->pFrom = p;
27.2091 + pFKey->pNextFrom = p->pFKey;
27.2092 + z = (char*)&pFKey[1];
27.2093 + pFKey->aCol = (struct sColMap*)z;
27.2094 + z += sizeof(struct sColMap)*nCol;
27.2095 + pFKey->zTo = z;
27.2096 + memcpy(z, pTo->z, pTo->n);
27.2097 + z[pTo->n] = 0;
27.2098 + z += pTo->n+1;
27.2099 + pFKey->pNextTo = 0;
27.2100 + pFKey->nCol = nCol;
27.2101 + if( pFromCol==0 ){
27.2102 + pFKey->aCol[0].iFrom = p->nCol-1;
27.2103 + }else{
27.2104 + for(i=0; i<nCol; i++){
27.2105 + int j;
27.2106 + for(j=0; j<p->nCol; j++){
27.2107 + if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
27.2108 + pFKey->aCol[i].iFrom = j;
27.2109 + break;
27.2110 + }
27.2111 + }
27.2112 + if( j>=p->nCol ){
27.2113 + sqlite3ErrorMsg(pParse,
27.2114 + "unknown column \"%s\" in foreign key definition",
27.2115 + pFromCol->a[i].zName);
27.2116 + goto fk_end;
27.2117 + }
27.2118 + }
27.2119 + }
27.2120 + if( pToCol ){
27.2121 + for(i=0; i<nCol; i++){
27.2122 + int n = strlen(pToCol->a[i].zName);
27.2123 + pFKey->aCol[i].zCol = z;
27.2124 + memcpy(z, pToCol->a[i].zName, n);
27.2125 + z[n] = 0;
27.2126 + z += n+1;
27.2127 + }
27.2128 + }
27.2129 + pFKey->isDeferred = 0;
27.2130 + pFKey->deleteConf = flags & 0xff;
27.2131 + pFKey->updateConf = (flags >> 8 ) & 0xff;
27.2132 + pFKey->insertConf = (flags >> 16 ) & 0xff;
27.2133 +
27.2134 + /* Link the foreign key to the table as the last step.
27.2135 + */
27.2136 + p->pFKey = pFKey;
27.2137 + pFKey = 0;
27.2138 +
27.2139 +fk_end:
27.2140 + sqliteFree(pFKey);
27.2141 +#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
27.2142 + sqlite3ExprListDelete(pFromCol);
27.2143 + sqlite3ExprListDelete(pToCol);
27.2144 +}
27.2145 +
27.2146 +/*
27.2147 +** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
27.2148 +** clause is seen as part of a foreign key definition. The isDeferred
27.2149 +** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
27.2150 +** The behavior of the most recently created foreign key is adjusted
27.2151 +** accordingly.
27.2152 +*/
27.2153 +void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
27.2154 +#ifndef SQLITE_OMIT_FOREIGN_KEY
27.2155 + Table *pTab;
27.2156 + FKey *pFKey;
27.2157 + if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
27.2158 + pFKey->isDeferred = isDeferred;
27.2159 +#endif
27.2160 +}
27.2161 +
27.2162 +/*
27.2163 +** Generate code that will erase and refill index *pIdx. This is
27.2164 +** used to initialize a newly created index or to recompute the
27.2165 +** content of an index in response to a REINDEX command.
27.2166 +**
27.2167 +** if memRootPage is not negative, it means that the index is newly
27.2168 +** created. The memory cell specified by memRootPage contains the
27.2169 +** root page number of the index. If memRootPage is negative, then
27.2170 +** the index already exists and must be cleared before being refilled and
27.2171 +** the root page number of the index is taken from pIndex->tnum.
27.2172 +*/
27.2173 +static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
27.2174 + Table *pTab = pIndex->pTable; /* The table that is indexed */
27.2175 + int iTab = pParse->nTab; /* Btree cursor used for pTab */
27.2176 + int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */
27.2177 + int addr1; /* Address of top of loop */
27.2178 + int tnum; /* Root page of index */
27.2179 + Vdbe *v; /* Generate code into this virtual machine */
27.2180 + KeyInfo *pKey; /* KeyInfo for index */
27.2181 + int iDb = sqlite3SchemaToIndex(pParse->db, pIndex->pSchema);
27.2182 +
27.2183 +#ifndef SQLITE_OMIT_AUTHORIZATION
27.2184 + if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
27.2185 + pParse->db->aDb[iDb].zName ) ){
27.2186 + return;
27.2187 + }
27.2188 +#endif
27.2189 +
27.2190 + /* Require a write-lock on the table to perform this operation */
27.2191 + sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
27.2192 +
27.2193 + v = sqlite3GetVdbe(pParse);
27.2194 + if( v==0 ) return;
27.2195 + if( memRootPage>=0 ){
27.2196 + sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0);
27.2197 + tnum = 0;
27.2198 + }else{
27.2199 + tnum = pIndex->tnum;
27.2200 + sqlite3VdbeAddOp(v, OP_Clear, tnum, iDb);
27.2201 + }
27.2202 + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
27.2203 + pKey = sqlite3IndexKeyinfo(pParse, pIndex);
27.2204 + sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum, (char *)pKey, P3_KEYINFO_HANDOFF);
27.2205 + sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
27.2206 + addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
27.2207 + sqlite3GenerateIndexKey(v, pIndex, iTab);
27.2208 + if( pIndex->onError!=OE_None ){
27.2209 + int curaddr = sqlite3VdbeCurrentAddr(v);
27.2210 + int addr2 = curaddr+4;
27.2211 + sqlite3VdbeChangeP2(v, curaddr-1, addr2);
27.2212 + sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0);
27.2213 + sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
27.2214 + sqlite3VdbeAddOp(v, OP_IsUnique, iIdx, addr2);
27.2215 + sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort,
27.2216 + "indexed columns are not unique", P3_STATIC);
27.2217 + assert( sqlite3MallocFailed() || addr2==sqlite3VdbeCurrentAddr(v) );
27.2218 + }
27.2219 + sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0);
27.2220 + sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1);
27.2221 + sqlite3VdbeJumpHere(v, addr1);
27.2222 + sqlite3VdbeAddOp(v, OP_Close, iTab, 0);
27.2223 + sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
27.2224 +}
27.2225 +
27.2226 +/*
27.2227 +** Create a new index for an SQL table. pName1.pName2 is the name of the index
27.2228 +** and pTblList is the name of the table that is to be indexed. Both will
27.2229 +** be NULL for a primary key or an index that is created to satisfy a
27.2230 +** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
27.2231 +** as the table to be indexed. pParse->pNewTable is a table that is
27.2232 +** currently being constructed by a CREATE TABLE statement.
27.2233 +**
27.2234 +** pList is a list of columns to be indexed. pList will be NULL if this
27.2235 +** is a primary key or unique-constraint on the most recent column added
27.2236 +** to the table currently under construction.
27.2237 +*/
27.2238 +void sqlite3CreateIndex(
27.2239 + Parse *pParse, /* All information about this parse */
27.2240 + Token *pName1, /* First part of index name. May be NULL */
27.2241 + Token *pName2, /* Second part of index name. May be NULL */
27.2242 + SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
27.2243 + ExprList *pList, /* A list of columns to be indexed */
27.2244 + int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
27.2245 + Token *pStart, /* The CREATE token that begins this statement */
27.2246 + Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
27.2247 + int sortOrder, /* Sort order of primary key when pList==NULL */
27.2248 + int ifNotExist /* Omit error if index already exists */
27.2249 +){
27.2250 + Table *pTab = 0; /* Table to be indexed */
27.2251 + Index *pIndex = 0; /* The index to be created */
27.2252 + char *zName = 0; /* Name of the index */
27.2253 + int nName; /* Number of characters in zName */
27.2254 + int i, j;
27.2255 + Token nullId; /* Fake token for an empty ID list */
27.2256 + DbFixer sFix; /* For assigning database names to pTable */
27.2257 + int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
27.2258 + sqlite3 *db = pParse->db;
27.2259 + Db *pDb; /* The specific table containing the indexed database */
27.2260 + int iDb; /* Index of the database that is being written */
27.2261 + Token *pName = 0; /* Unqualified name of the index to create */
27.2262 + struct ExprList_item *pListItem; /* For looping over pList */
27.2263 + int nCol;
27.2264 + int nExtra = 0;
27.2265 + char *zExtra;
27.2266 +
27.2267 + if( pParse->nErr || sqlite3MallocFailed() || IN_DECLARE_VTAB ){
27.2268 + goto exit_create_index;
27.2269 + }
27.2270 +
27.2271 + /*
27.2272 + ** Find the table that is to be indexed. Return early if not found.
27.2273 + */
27.2274 + if( pTblName!=0 ){
27.2275 +
27.2276 + /* Use the two-part index name to determine the database
27.2277 + ** to search for the table. 'Fix' the table name to this db
27.2278 + ** before looking up the table.
27.2279 + */
27.2280 + assert( pName1 && pName2 );
27.2281 + iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
27.2282 + if( iDb<0 ) goto exit_create_index;
27.2283 +
27.2284 +#ifndef SQLITE_OMIT_TEMPDB
27.2285 + /* If the index name was unqualified, check if the the table
27.2286 + ** is a temp table. If so, set the database to 1.
27.2287 + */
27.2288 + pTab = sqlite3SrcListLookup(pParse, pTblName);
27.2289 + if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
27.2290 + iDb = 1;
27.2291 + }
27.2292 +#endif
27.2293 +
27.2294 + if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
27.2295 + sqlite3FixSrcList(&sFix, pTblName)
27.2296 + ){
27.2297 + /* Because the parser constructs pTblName from a single identifier,
27.2298 + ** sqlite3FixSrcList can never fail. */
27.2299 + assert(0);
27.2300 + }
27.2301 + pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName,
27.2302 + pTblName->a[0].zDatabase);
27.2303 + if( !pTab ) goto exit_create_index;
27.2304 + assert( db->aDb[iDb].pSchema==pTab->pSchema );
27.2305 + }else{
27.2306 + assert( pName==0 );
27.2307 + pTab = pParse->pNewTable;
27.2308 + if( !pTab ) goto exit_create_index;
27.2309 + iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
27.2310 + }
27.2311 + pDb = &db->aDb[iDb];
27.2312 +
27.2313 + if( pTab==0 || pParse->nErr ) goto exit_create_index;
27.2314 + if( pTab->readOnly ){
27.2315 + sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
27.2316 + goto exit_create_index;
27.2317 + }
27.2318 +#ifndef SQLITE_OMIT_VIEW
27.2319 + if( pTab->pSelect ){
27.2320 + sqlite3ErrorMsg(pParse, "views may not be indexed");
27.2321 + goto exit_create_index;
27.2322 + }
27.2323 +#endif
27.2324 +#ifndef SQLITE_OMIT_VIRTUALTABLE
27.2325 + if( IsVirtual(pTab) ){
27.2326 + sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
27.2327 + goto exit_create_index;
27.2328 + }
27.2329 +#endif
27.2330 +
27.2331 + /*
27.2332 + ** Find the name of the index. Make sure there is not already another
27.2333 + ** index or table with the same name.
27.2334 + **
27.2335 + ** Exception: If we are reading the names of permanent indices from the
27.2336 + ** sqlite_master table (because some other process changed the schema) and
27.2337 + ** one of the index names collides with the name of a temporary table or
27.2338 + ** index, then we will continue to process this index.
27.2339 + **
27.2340 + ** If pName==0 it means that we are
27.2341 + ** dealing with a primary key or UNIQUE constraint. We have to invent our
27.2342 + ** own name.
27.2343 + */
27.2344 + if( pName ){
27.2345 + zName = sqlite3NameFromToken(pName);
27.2346 + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
27.2347 + if( zName==0 ) goto exit_create_index;
27.2348 + if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
27.2349 + goto exit_create_index;
27.2350 + }
27.2351 + if( !db->init.busy ){
27.2352 + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
27.2353 + if( sqlite3FindTable(db, zName, 0)!=0 ){
27.2354 + sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
27.2355 + goto exit_create_index;
27.2356 + }
27.2357 + }
27.2358 + if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
27.2359 + if( !ifNotExist ){
27.2360 + sqlite3ErrorMsg(pParse, "index %s already exists", zName);
27.2361 + }
27.2362 + goto exit_create_index;
27.2363 + }
27.2364 + }else{
27.2365 + char zBuf[30];
27.2366 + int n;
27.2367 + Index *pLoop;
27.2368 + for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
27.2369 + sqlite3_snprintf(sizeof(zBuf),zBuf,"_%d",n);
27.2370 + zName = 0;
27.2371 + sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
27.2372 + if( zName==0 ) goto exit_create_index;
27.2373 + }
27.2374 +
27.2375 + /* Check for authorization to create an index.
27.2376 + */
27.2377 +#ifndef SQLITE_OMIT_AUTHORIZATION
27.2378 + {
27.2379 + const char *zDb = pDb->zName;
27.2380 + if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
27.2381 + goto exit_create_index;
27.2382 + }
27.2383 + i = SQLITE_CREATE_INDEX;
27.2384 + if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
27.2385 + if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
27.2386 + goto exit_create_index;
27.2387 + }
27.2388 + }
27.2389 +#endif
27.2390 +
27.2391 + /* If pList==0, it means this routine was called to make a primary
27.2392 + ** key out of the last column added to the table under construction.
27.2393 + ** So create a fake list to simulate this.
27.2394 + */
27.2395 + if( pList==0 ){
27.2396 + nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
27.2397 + nullId.n = strlen((char*)nullId.z);
27.2398 + pList = sqlite3ExprListAppend(0, 0, &nullId);
27.2399 + if( pList==0 ) goto exit_create_index;
27.2400 + pList->a[0].sortOrder = sortOrder;
27.2401 + }
27.2402 +
27.2403 + /* Figure out how many bytes of space are required to store explicitly
27.2404 + ** specified collation sequence names.
27.2405 + */
27.2406 + for(i=0; i<pList->nExpr; i++){
27.2407 + Expr *pExpr = pList->a[i].pExpr;
27.2408 + if( pExpr ){
27.2409 + nExtra += (1 + strlen(pExpr->pColl->zName));
27.2410 + }
27.2411 + }
27.2412 +
27.2413 + /*
27.2414 + ** Allocate the index structure.
27.2415 + */
27.2416 + nName = strlen(zName);
27.2417 + nCol = pList->nExpr;
27.2418 + pIndex = sqliteMalloc(
27.2419 + sizeof(Index) + /* Index structure */
27.2420 + sizeof(int)*nCol + /* Index.aiColumn */
27.2421 + sizeof(int)*(nCol+1) + /* Index.aiRowEst */
27.2422 + sizeof(char *)*nCol + /* Index.azColl */
27.2423 + sizeof(u8)*nCol + /* Index.aSortOrder */
27.2424 + nName + 1 + /* Index.zName */
27.2425 + nExtra /* Collation sequence names */
27.2426 + );
27.2427 + if( sqlite3MallocFailed() ) goto exit_create_index;
27.2428 + pIndex->azColl = (char**)(&pIndex[1]);
27.2429 + pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
27.2430 + pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
27.2431 + pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
27.2432 + pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
27.2433 + zExtra = (char *)(&pIndex->zName[nName+1]);
27.2434 + memcpy(pIndex->zName, zName, nName+1);
27.2435 + pIndex->pTable = pTab;
27.2436 + pIndex->nColumn = pList->nExpr;
27.2437 + pIndex->onError = onError;
27.2438 + pIndex->autoIndex = pName==0;
27.2439 + pIndex->pSchema = db->aDb[iDb].pSchema;
27.2440 +
27.2441 + /* Check to see if we should honor DESC requests on index columns
27.2442 + */
27.2443 + if( pDb->pSchema->file_format>=4 ){
27.2444 + sortOrderMask = -1; /* Honor DESC */
27.2445 + }else{
27.2446 + sortOrderMask = 0; /* Ignore DESC */
27.2447 + }
27.2448 +
27.2449 + /* Scan the names of the columns of the table to be indexed and
27.2450 + ** load the column indices into the Index structure. Report an error
27.2451 + ** if any column is not found.
27.2452 + */
27.2453 + for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
27.2454 + const char *zColName = pListItem->zName;
27.2455 + Column *pTabCol;
27.2456 + int requestedSortOrder;
27.2457 + char *zColl; /* Collation sequence name */
27.2458 +
27.2459 + for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
27.2460 + if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
27.2461 + }
27.2462 + if( j>=pTab->nCol ){
27.2463 + sqlite3ErrorMsg(pParse, "table %s has no column named %s",
27.2464 + pTab->zName, zColName);
27.2465 + goto exit_create_index;
27.2466 + }
27.2467 + /* TODO: Add a test to make sure that the same column is not named
27.2468 + ** more than once within the same index. Only the first instance of
27.2469 + ** the column will ever be used by the optimizer. Note that using the
27.2470 + ** same column more than once cannot be an error because that would
27.2471 + ** break backwards compatibility - it needs to be a warning.
27.2472 + */
27.2473 + pIndex->aiColumn[i] = j;
27.2474 + if( pListItem->pExpr ){
27.2475 + assert( pListItem->pExpr->pColl );
27.2476 + zColl = zExtra;
27.2477 + sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
27.2478 + zExtra += (strlen(zColl) + 1);
27.2479 + }else{
27.2480 + zColl = pTab->aCol[j].zColl;
27.2481 + if( !zColl ){
27.2482 + zColl = db->pDfltColl->zName;
27.2483 + }
27.2484 + }
27.2485 + if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
27.2486 + goto exit_create_index;
27.2487 + }
27.2488 + pIndex->azColl[i] = zColl;
27.2489 + requestedSortOrder = pListItem->sortOrder & sortOrderMask;
27.2490 + pIndex->aSortOrder[i] = requestedSortOrder;
27.2491 + }
27.2492 + sqlite3DefaultRowEst(pIndex);
27.2493 +
27.2494 + if( pTab==pParse->pNewTable ){
27.2495 + /* This routine has been called to create an automatic index as a
27.2496 + ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
27.2497 + ** a PRIMARY KEY or UNIQUE clause following the column definitions.
27.2498 + ** i.e. one of:
27.2499 + **
27.2500 + ** CREATE TABLE t(x PRIMARY KEY, y);
27.2501 + ** CREATE TABLE t(x, y, UNIQUE(x, y));
27.2502 + **
27.2503 + ** Either way, check to see if the table already has such an index. If
27.2504 + ** so, don't bother creating this one. This only applies to
27.2505 + ** automatically created indices. Users can do as they wish with
27.2506 + ** explicit indices.
27.2507 + */
27.2508 + Index *pIdx;
27.2509 + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
27.2510 + int k;
27.2511 + assert( pIdx->onError!=OE_None );
27.2512 + assert( pIdx->autoIndex );
27.2513 + assert( pIndex->onError!=OE_None );
27.2514 +
27.2515 + if( pIdx->nColumn!=pIndex->nColumn ) continue;
27.2516 + for(k=0; k<pIdx->nColumn; k++){
27.2517 + const char *z1 = pIdx->azColl[k];
27.2518 + const char *z2 = pIndex->azColl[k];
27.2519 + if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
27.2520 + if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
27.2521 + if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
27.2522 + }
27.2523 + if( k==pIdx->nColumn ){
27.2524 + if( pIdx->onError!=pIndex->onError ){
27.2525 + /* This constraint creates the same index as a previous
27.2526 + ** constraint specified somewhere in the CREATE TABLE statement.
27.2527 + ** However the ON CONFLICT clauses are different. If both this
27.2528 + ** constraint and the previous equivalent constraint have explicit
27.2529 + ** ON CONFLICT clauses this is an error. Otherwise, use the
27.2530 + ** explicitly specified behaviour for the index.
27.2531 + */
27.2532 + if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
27.2533 + sqlite3ErrorMsg(pParse,
27.2534 + "conflicting ON CONFLICT clauses specified", 0);
27.2535 + }
27.2536 + if( pIdx->onError==OE_Default ){
27.2537 + pIdx->onError = pIndex->onError;
27.2538 + }
27.2539 + }
27.2540 + goto exit_create_index;
27.2541 + }
27.2542 + }
27.2543 + }
27.2544 +
27.2545 + /* Link the new Index structure to its table and to the other
27.2546 + ** in-memory database structures.
27.2547 + */
27.2548 + if( db->init.busy ){
27.2549 + Index *p;
27.2550 + p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
27.2551 + pIndex->zName, strlen(pIndex->zName)+1, pIndex);
27.2552 + if( p ){
27.2553 + assert( p==pIndex ); /* Malloc must have failed */
27.2554 + goto exit_create_index;
27.2555 + }
27.2556 + db->flags |= SQLITE_InternChanges;
27.2557 + if( pTblName!=0 ){
27.2558 + pIndex->tnum = db->init.newTnum;
27.2559 + }
27.2560 + }
27.2561 +
27.2562 + /* If the db->init.busy is 0 then create the index on disk. This
27.2563 + ** involves writing the index into the master table and filling in the
27.2564 + ** index with the current table contents.
27.2565 + **
27.2566 + ** The db->init.busy is 0 when the user first enters a CREATE INDEX
27.2567 + ** command. db->init.busy is 1 when a database is opened and
27.2568 + ** CREATE INDEX statements are read out of the master table. In
27.2569 + ** the latter case the index already exists on disk, which is why
27.2570 + ** we don't want to recreate it.
27.2571 + **
27.2572 + ** If pTblName==0 it means this index is generated as a primary key
27.2573 + ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
27.2574 + ** has just been created, it contains no data and the index initialization
27.2575 + ** step can be skipped.
27.2576 + */
27.2577 + else if( db->init.busy==0 ){
27.2578 + Vdbe *v;
27.2579 + char *zStmt;
27.2580 + int iMem = pParse->nMem++;
27.2581 +
27.2582 + v = sqlite3GetVdbe(pParse);
27.2583 + if( v==0 ) goto exit_create_index;
27.2584 +
27.2585 +
27.2586 + /* Create the rootpage for the index
27.2587 + */
27.2588 + sqlite3BeginWriteOperation(pParse, 1, iDb);
27.2589 + sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0);
27.2590 + sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
27.2591 +
27.2592 + /* Gather the complete text of the CREATE INDEX statement into
27.2593 + ** the zStmt variable
27.2594 + */
27.2595 + if( pStart && pEnd ){
27.2596 + /* A named index with an explicit CREATE INDEX statement */
27.2597 + zStmt = sqlite3MPrintf("CREATE%s INDEX %.*s",
27.2598 + onError==OE_None ? "" : " UNIQUE",
27.2599 + pEnd->z - pName->z + 1,
27.2600 + pName->z);
27.2601 + }else{
27.2602 + /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
27.2603 + /* zStmt = sqlite3MPrintf(""); */
27.2604 + zStmt = 0;
27.2605 + }
27.2606 +
27.2607 + /* Add an entry in sqlite_master for this index
27.2608 + */
27.2609 + sqlite3NestedParse(pParse,
27.2610 + "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);",
27.2611 + db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
27.2612 + pIndex->zName,
27.2613 + pTab->zName,
27.2614 + zStmt
27.2615 + );
27.2616 + sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
27.2617 + sqliteFree(zStmt);
27.2618 +
27.2619 + /* Fill the index with data and reparse the schema. Code an OP_Expire
27.2620 + ** to invalidate all pre-compiled statements.
27.2621 + */
27.2622 + if( pTblName ){
27.2623 + sqlite3RefillIndex(pParse, pIndex, iMem);
27.2624 + sqlite3ChangeCookie(db, v, iDb);
27.2625 + sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
27.2626 + sqlite3MPrintf("name='%q'", pIndex->zName), P3_DYNAMIC);
27.2627 + sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
27.2628 + }
27.2629 + }
27.2630 +
27.2631 + /* When adding an index to the list of indices for a table, make
27.2632 + ** sure all indices labeled OE_Replace come after all those labeled
27.2633 + ** OE_Ignore. This is necessary for the correct operation of UPDATE
27.2634 + ** and INSERT.
27.2635 + */
27.2636 + if( db->init.busy || pTblName==0 ){
27.2637 + if( onError!=OE_Replace || pTab->pIndex==0
27.2638 + || pTab->pIndex->onError==OE_Replace){
27.2639 + pIndex->pNext = pTab->pIndex;
27.2640 + pTab->pIndex = pIndex;
27.2641 + }else{
27.2642 + Index *pOther = pTab->pIndex;
27.2643 + while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
27.2644 + pOther = pOther->pNext;
27.2645 + }
27.2646 + pIndex->pNext = pOther->pNext;
27.2647 + pOther->pNext = pIndex;
27.2648 + }
27.2649 + pIndex = 0;
27.2650 + }
27.2651 +
27.2652 + /* Clean up before exiting */
27.2653 +exit_create_index:
27.2654 + if( pIndex ){
27.2655 + freeIndex(pIndex);
27.2656 + }
27.2657 + sqlite3ExprListDelete(pList);
27.2658 + sqlite3SrcListDelete(pTblName);
27.2659 + sqliteFree(zName);
27.2660 + return;
27.2661 +}
27.2662 +
27.2663 +/*
27.2664 +** Generate code to make sure the file format number is at least minFormat.
27.2665 +** The generated code will increase the file format number if necessary.
27.2666 +*/
27.2667 +void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
27.2668 + Vdbe *v;
27.2669 + v = sqlite3GetVdbe(pParse);
27.2670 + if( v ){
27.2671 + sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);
27.2672 + sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
27.2673 + sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3);
27.2674 + sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
27.2675 + sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
27.2676 + }
27.2677 +}
27.2678 +
27.2679 +/*
27.2680 +** Fill the Index.aiRowEst[] array with default information - information
27.2681 +** to be used when we have not run the ANALYZE command.
27.2682 +**
27.2683 +** aiRowEst[0] is suppose to contain the number of elements in the index.
27.2684 +** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
27.2685 +** number of rows in the table that match any particular value of the
27.2686 +** first column of the index. aiRowEst[2] is an estimate of the number
27.2687 +** of rows that match any particular combiniation of the first 2 columns
27.2688 +** of the index. And so forth. It must always be the case that
27.2689 +*
27.2690 +** aiRowEst[N]<=aiRowEst[N-1]
27.2691 +** aiRowEst[N]>=1
27.2692 +**
27.2693 +** Apart from that, we have little to go on besides intuition as to
27.2694 +** how aiRowEst[] should be initialized. The numbers generated here
27.2695 +** are based on typical values found in actual indices.
27.2696 +*/
27.2697 +void sqlite3DefaultRowEst(Index *pIdx){
27.2698 + unsigned *a = pIdx->aiRowEst;
27.2699 + int i;
27.2700 + assert( a!=0 );
27.2701 + a[0] = 1000000;
27.2702 + for(i=pIdx->nColumn; i>=5; i--){
27.2703 + a[i] = 5;
27.2704 + }
27.2705 + while( i>=1 ){
27.2706 + a[i] = 11 - i;
27.2707 + i--;
27.2708 + }
27.2709 + if( pIdx->onError!=OE_None ){
27.2710 + a[pIdx->nColumn] = 1;
27.2711 + }
27.2712 +}
27.2713 +
27.2714 +/*
27.2715 +** This routine will drop an existing named index. This routine
27.2716 +** implements the DROP INDEX statement.
27.2717 +*/
27.2718 +void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
27.2719 + Index *pIndex;
27.2720 + Vdbe *v;
27.2721 + sqlite3 *db = pParse->db;
27.2722 + int iDb;
27.2723 +
27.2724 + if( pParse->nErr || sqlite3MallocFailed() ){
27.2725 + goto exit_drop_index;
27.2726 + }
27.2727 + assert( pName->nSrc==1 );
27.2728 + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
27.2729 + goto exit_drop_index;
27.2730 + }
27.2731 + pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
27.2732 + if( pIndex==0 ){
27.2733 + if( !ifExists ){
27.2734 + sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
27.2735 + }
27.2736 + pParse->checkSchema = 1;
27.2737 + goto exit_drop_index;
27.2738 + }
27.2739 + if( pIndex->autoIndex ){
27.2740 + sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
27.2741 + "or PRIMARY KEY constraint cannot be dropped", 0);
27.2742 + goto exit_drop_index;
27.2743 + }
27.2744 + iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
27.2745 +#ifndef SQLITE_OMIT_AUTHORIZATION
27.2746 + {
27.2747 + int code = SQLITE_DROP_INDEX;
27.2748 + Table *pTab = pIndex->pTable;
27.2749 + const char *zDb = db->aDb[iDb].zName;
27.2750 + const char *zTab = SCHEMA_TABLE(iDb);
27.2751 + if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
27.2752 + goto exit_drop_index;
27.2753 + }
27.2754 + if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
27.2755 + if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
27.2756 + goto exit_drop_index;
27.2757 + }
27.2758 + }
27.2759 +#endif
27.2760 +
27.2761 + /* Generate code to remove the index and from the master table */
27.2762 + v = sqlite3GetVdbe(pParse);
27.2763 + if( v ){
27.2764 + sqlite3NestedParse(pParse,
27.2765 + "DELETE FROM %Q.%s WHERE name=%Q",
27.2766 + db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
27.2767 + pIndex->zName
27.2768 + );
27.2769 + sqlite3ChangeCookie(db, v, iDb);
27.2770 + destroyRootPage(pParse, pIndex->tnum, iDb);
27.2771 + sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0);
27.2772 + }
27.2773 +
27.2774 +exit_drop_index:
27.2775 + sqlite3SrcListDelete(pName);
27.2776 +}
27.2777 +
27.2778 +/*
27.2779 +** pArray is a pointer to an array of objects. Each object in the
27.2780 +** array is szEntry bytes in size. This routine allocates a new
27.2781 +** object on the end of the array.
27.2782 +**
27.2783 +** *pnEntry is the number of entries already in use. *pnAlloc is
27.2784 +** the previously allocated size of the array. initSize is the
27.2785 +** suggested initial array size allocation.
27.2786 +**
27.2787 +** The index of the new entry is returned in *pIdx.
27.2788 +**
27.2789 +** This routine returns a pointer to the array of objects. This
27.2790 +** might be the same as the pArray parameter or it might be a different
27.2791 +** pointer if the array was resized.
27.2792 +*/
27.2793 +void *sqlite3ArrayAllocate(
27.2794 + void *pArray, /* Array of objects. Might be reallocated */
27.2795 + int szEntry, /* Size of each object in the array */
27.2796 + int initSize, /* Suggested initial allocation, in elements */
27.2797 + int *pnEntry, /* Number of objects currently in use */
27.2798 + int *pnAlloc, /* Current size of the allocation, in elements */
27.2799 + int *pIdx /* Write the index of a new slot here */
27.2800 +){
27.2801 + char *z;
27.2802 + if( *pnEntry >= *pnAlloc ){
27.2803 + void *pNew;
27.2804 + int newSize;
27.2805 + newSize = (*pnAlloc)*2 + initSize;
27.2806 + pNew = sqliteRealloc(pArray, newSize*szEntry);
27.2807 + if( pNew==0 ){
27.2808 + *pIdx = -1;
27.2809 + return pArray;
27.2810 + }
27.2811 + *pnAlloc = newSize;
27.2812 + pArray = pNew;
27.2813 + }
27.2814 + z = (char*)pArray;
27.2815 + memset(&z[*pnEntry * szEntry], 0, szEntry);
27.2816 + *pIdx = *pnEntry;
27.2817 + ++*pnEntry;
27.2818 + return pArray;
27.2819 +}
27.2820 +
27.2821 +/*
27.2822 +** Append a new element to the given IdList. Create a new IdList if
27.2823 +** need be.
27.2824 +**
27.2825 +** A new IdList is returned, or NULL if malloc() fails.
27.2826 +*/
27.2827 +IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){
27.2828 + int i;
27.2829 + if( pList==0 ){
27.2830 + pList = sqliteMalloc( sizeof(IdList) );
27.2831 + if( pList==0 ) return 0;
27.2832 + pList->nAlloc = 0;
27.2833 + }
27.2834 + pList->a = sqlite3ArrayAllocate(
27.2835 + pList->a,
27.2836 + sizeof(pList->a[0]),
27.2837 + 5,
27.2838 + &pList->nId,
27.2839 + &pList->nAlloc,
27.2840 + &i
27.2841 + );
27.2842 + if( i<0 ){
27.2843 + sqlite3IdListDelete(pList);
27.2844 + return 0;
27.2845 + }
27.2846 + pList->a[i].zName = sqlite3NameFromToken(pToken);
27.2847 + return pList;
27.2848 +}
27.2849 +
27.2850 +/*
27.2851 +** Delete an IdList.
27.2852 +*/
27.2853 +void sqlite3IdListDelete(IdList *pList){
27.2854 + int i;
27.2855 + if( pList==0 ) return;
27.2856 + for(i=0; i<pList->nId; i++){
27.2857 + sqliteFree(pList->a[i].zName);
27.2858 + }
27.2859 + sqliteFree(pList->a);
27.2860 + sqliteFree(pList);
27.2861 +}
27.2862 +
27.2863 +/*
27.2864 +** Return the index in pList of the identifier named zId. Return -1
27.2865 +** if not found.
27.2866 +*/
27.2867 +int sqlite3IdListIndex(IdList *pList, const char *zName){
27.2868 + int i;
27.2869 + if( pList==0 ) return -1;
27.2870 + for(i=0; i<pList->nId; i++){
27.2871 + if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
27.2872 + }
27.2873 + return -1;
27.2874 +}
27.2875 +
27.2876 +/*
27.2877 +** Append a new table name to the given SrcList. Create a new SrcList if
27.2878 +** need be. A new entry is created in the SrcList even if pToken is NULL.
27.2879 +**
27.2880 +** A new SrcList is returned, or NULL if malloc() fails.
27.2881 +**
27.2882 +** If pDatabase is not null, it means that the table has an optional
27.2883 +** database name prefix. Like this: "database.table". The pDatabase
27.2884 +** points to the table name and the pTable points to the database name.
27.2885 +** The SrcList.a[].zName field is filled with the table name which might
27.2886 +** come from pTable (if pDatabase is NULL) or from pDatabase.
27.2887 +** SrcList.a[].zDatabase is filled with the database name from pTable,
27.2888 +** or with NULL if no database is specified.
27.2889 +**
27.2890 +** In other words, if call like this:
27.2891 +**
27.2892 +** sqlite3SrcListAppend(A,B,0);
27.2893 +**
27.2894 +** Then B is a table name and the database name is unspecified. If called
27.2895 +** like this:
27.2896 +**
27.2897 +** sqlite3SrcListAppend(A,B,C);
27.2898 +**
27.2899 +** Then C is the table name and B is the database name.
27.2900 +*/
27.2901 +SrcList *sqlite3SrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
27.2902 + struct SrcList_item *pItem;
27.2903 + if( pList==0 ){
27.2904 + pList = sqliteMalloc( sizeof(SrcList) );
27.2905 + if( pList==0 ) return 0;
27.2906 + pList->nAlloc = 1;
27.2907 + }
27.2908 + if( pList->nSrc>=pList->nAlloc ){
27.2909 + SrcList *pNew;
27.2910 + pList->nAlloc *= 2;
27.2911 + pNew = sqliteRealloc(pList,
27.2912 + sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
27.2913 + if( pNew==0 ){
27.2914 + sqlite3SrcListDelete(pList);
27.2915 + return 0;
27.2916 + }
27.2917 + pList = pNew;
27.2918 + }
27.2919 + pItem = &pList->a[pList->nSrc];
27.2920 + memset(pItem, 0, sizeof(pList->a[0]));
27.2921 + if( pDatabase && pDatabase->z==0 ){
27.2922 + pDatabase = 0;
27.2923 + }
27.2924 + if( pDatabase && pTable ){
27.2925 + Token *pTemp = pDatabase;
27.2926 + pDatabase = pTable;
27.2927 + pTable = pTemp;
27.2928 + }
27.2929 + pItem->zName = sqlite3NameFromToken(pTable);
27.2930 + pItem->zDatabase = sqlite3NameFromToken(pDatabase);
27.2931 + pItem->iCursor = -1;
27.2932 + pItem->isPopulated = 0;
27.2933 + pList->nSrc++;
27.2934 + return pList;
27.2935 +}
27.2936 +
27.2937 +/*
27.2938 +** Assign cursors to all tables in a SrcList
27.2939 +*/
27.2940 +void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
27.2941 + int i;
27.2942 + struct SrcList_item *pItem;
27.2943 + assert(pList || sqlite3MallocFailed() );
27.2944 + if( pList ){
27.2945 + for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
27.2946 + if( pItem->iCursor>=0 ) break;
27.2947 + pItem->iCursor = pParse->nTab++;
27.2948 + if( pItem->pSelect ){
27.2949 + sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
27.2950 + }
27.2951 + }
27.2952 + }
27.2953 +}
27.2954 +
27.2955 +/*
27.2956 +** Delete an entire SrcList including all its substructure.
27.2957 +*/
27.2958 +void sqlite3SrcListDelete(SrcList *pList){
27.2959 + int i;
27.2960 + struct SrcList_item *pItem;
27.2961 + if( pList==0 ) return;
27.2962 + for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
27.2963 + sqliteFree(pItem->zDatabase);
27.2964 + sqliteFree(pItem->zName);
27.2965 + sqliteFree(pItem->zAlias);
27.2966 + sqlite3DeleteTable(pItem->pTab);
27.2967 + sqlite3SelectDelete(pItem->pSelect);
27.2968 + sqlite3ExprDelete(pItem->pOn);
27.2969 + sqlite3IdListDelete(pItem->pUsing);
27.2970 + }
27.2971 + sqliteFree(pList);
27.2972 +}
27.2973 +
27.2974 +/*
27.2975 +** This routine is called by the parser to add a new term to the
27.2976 +** end of a growing FROM clause. The "p" parameter is the part of
27.2977 +** the FROM clause that has already been constructed. "p" is NULL
27.2978 +** if this is the first term of the FROM clause. pTable and pDatabase
27.2979 +** are the name of the table and database named in the FROM clause term.
27.2980 +** pDatabase is NULL if the database name qualifier is missing - the
27.2981 +** usual case. If the term has a alias, then pAlias points to the
27.2982 +** alias token. If the term is a subquery, then pSubquery is the
27.2983 +** SELECT statement that the subquery encodes. The pTable and
27.2984 +** pDatabase parameters are NULL for subqueries. The pOn and pUsing
27.2985 +** parameters are the content of the ON and USING clauses.
27.2986 +**
27.2987 +** Return a new SrcList which encodes is the FROM with the new
27.2988 +** term added.
27.2989 +*/
27.2990 +SrcList *sqlite3SrcListAppendFromTerm(
27.2991 + SrcList *p, /* The left part of the FROM clause already seen */
27.2992 + Token *pTable, /* Name of the table to add to the FROM clause */
27.2993 + Token *pDatabase, /* Name of the database containing pTable */
27.2994 + Token *pAlias, /* The right-hand side of the AS subexpression */
27.2995 + Select *pSubquery, /* A subquery used in place of a table name */
27.2996 + Expr *pOn, /* The ON clause of a join */
27.2997 + IdList *pUsing /* The USING clause of a join */
27.2998 +){
27.2999 + struct SrcList_item *pItem;
27.3000 + p = sqlite3SrcListAppend(p, pTable, pDatabase);
27.3001 + if( p==0 || p->nSrc==0 ){
27.3002 + sqlite3ExprDelete(pOn);
27.3003 + sqlite3IdListDelete(pUsing);
27.3004 + sqlite3SelectDelete(pSubquery);
27.3005 + return p;
27.3006 + }
27.3007 + pItem = &p->a[p->nSrc-1];
27.3008 + if( pAlias && pAlias->n ){
27.3009 + pItem->zAlias = sqlite3NameFromToken(pAlias);
27.3010 + }
27.3011 + pItem->pSelect = pSubquery;
27.3012 + pItem->pOn = pOn;
27.3013 + pItem->pUsing = pUsing;
27.3014 + return p;
27.3015 +}
27.3016 +
27.3017 +/*
27.3018 +** When building up a FROM clause in the parser, the join operator
27.3019 +** is initially attached to the left operand. But the code generator
27.3020 +** expects the join operator to be on the right operand. This routine
27.3021 +** Shifts all join operators from left to right for an entire FROM
27.3022 +** clause.
27.3023 +**
27.3024 +** Example: Suppose the join is like this:
27.3025 +**
27.3026 +** A natural cross join B
27.3027 +**
27.3028 +** The operator is "natural cross join". The A and B operands are stored
27.3029 +** in p->a[0] and p->a[1], respectively. The parser initially stores the
27.3030 +** operator with A. This routine shifts that operator over to B.
27.3031 +*/
27.3032 +void sqlite3SrcListShiftJoinType(SrcList *p){
27.3033 + if( p && p->a ){
27.3034 + int i;
27.3035 + for(i=p->nSrc-1; i>0; i--){
27.3036 + p->a[i].jointype = p->a[i-1].jointype;
27.3037 + }
27.3038 + p->a[0].jointype = 0;
27.3039 + }
27.3040 +}
27.3041 +
27.3042 +/*
27.3043 +** Begin a transaction
27.3044 +*/
27.3045 +void sqlite3BeginTransaction(Parse *pParse, int type){
27.3046 + sqlite3 *db;
27.3047 + Vdbe *v;
27.3048 + int i;
27.3049 +
27.3050 + if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
27.3051 + if( pParse->nErr || sqlite3MallocFailed() ) return;
27.3052 + if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
27.3053 +
27.3054 + v = sqlite3GetVdbe(pParse);
27.3055 + if( !v ) return;
27.3056 + if( type!=TK_DEFERRED ){
27.3057 + for(i=0; i<db->nDb; i++){
27.3058 + sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
27.3059 + }
27.3060 + }
27.3061 + sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
27.3062 +}
27.3063 +
27.3064 +/*
27.3065 +** Commit a transaction
27.3066 +*/
27.3067 +void sqlite3CommitTransaction(Parse *pParse){
27.3068 + sqlite3 *db;
27.3069 + Vdbe *v;
27.3070 +
27.3071 + if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
27.3072 + if( pParse->nErr || sqlite3MallocFailed() ) return;
27.3073 + if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
27.3074 +
27.3075 + v = sqlite3GetVdbe(pParse);
27.3076 + if( v ){
27.3077 + sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
27.3078 + }
27.3079 +}
27.3080 +
27.3081 +/*
27.3082 +** Rollback a transaction
27.3083 +*/
27.3084 +void sqlite3RollbackTransaction(Parse *pParse){
27.3085 + sqlite3 *db;
27.3086 + Vdbe *v;
27.3087 +
27.3088 + if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
27.3089 + if( pParse->nErr || sqlite3MallocFailed() ) return;
27.3090 + if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
27.3091 +
27.3092 + v = sqlite3GetVdbe(pParse);
27.3093 + if( v ){
27.3094 + sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
27.3095 + }
27.3096 +}
27.3097 +
27.3098 +/*
27.3099 +** Make sure the TEMP database is open and available for use. Return
27.3100 +** the number of errors. Leave any error messages in the pParse structure.
27.3101 +*/
27.3102 +int sqlite3OpenTempDatabase(Parse *pParse){
27.3103 + sqlite3 *db = pParse->db;
27.3104 + if( db->aDb[1].pBt==0 && !pParse->explain ){
27.3105 + int rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE,
27.3106 + &db->aDb[1].pBt);
27.3107 + if( rc!=SQLITE_OK ){
27.3108 + sqlite3ErrorMsg(pParse, "unable to open a temporary database "
27.3109 + "file for storing temporary tables");
27.3110 + pParse->rc = rc;
27.3111 + return 1;
27.3112 + }
27.3113 + if( db->flags & !db->autoCommit ){
27.3114 + rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1);
27.3115 + if( rc!=SQLITE_OK ){
27.3116 + sqlite3ErrorMsg(pParse, "unable to get a write lock on "
27.3117 + "the temporary database file");
27.3118 + pParse->rc = rc;
27.3119 + return 1;
27.3120 + }
27.3121 + }
27.3122 + assert( db->aDb[1].pSchema );
27.3123 + }
27.3124 + return 0;
27.3125 +}
27.3126 +
27.3127 +/*
27.3128 +** Generate VDBE code that will verify the schema cookie and start
27.3129 +** a read-transaction for all named database files.
27.3130 +**
27.3131 +** It is important that all schema cookies be verified and all
27.3132 +** read transactions be started before anything else happens in
27.3133 +** the VDBE program. But this routine can be called after much other
27.3134 +** code has been generated. So here is what we do:
27.3135 +**
27.3136 +** The first time this routine is called, we code an OP_Goto that
27.3137 +** will jump to a subroutine at the end of the program. Then we
27.3138 +** record every database that needs its schema verified in the
27.3139 +** pParse->cookieMask field. Later, after all other code has been
27.3140 +** generated, the subroutine that does the cookie verifications and
27.3141 +** starts the transactions will be coded and the OP_Goto P2 value
27.3142 +** will be made to point to that subroutine. The generation of the
27.3143 +** cookie verification subroutine code happens in sqlite3FinishCoding().
27.3144 +**
27.3145 +** If iDb<0 then code the OP_Goto only - don't set flag to verify the
27.3146 +** schema on any databases. This can be used to position the OP_Goto
27.3147 +** early in the code, before we know if any database tables will be used.
27.3148 +*/
27.3149 +void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
27.3150 + sqlite3 *db;
27.3151 + Vdbe *v;
27.3152 + int mask;
27.3153 +
27.3154 + v = sqlite3GetVdbe(pParse);
27.3155 + if( v==0 ) return; /* This only happens if there was a prior error */
27.3156 + db = pParse->db;
27.3157 + if( pParse->cookieGoto==0 ){
27.3158 + pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1;
27.3159 + }
27.3160 + if( iDb>=0 ){
27.3161 + assert( iDb<db->nDb );
27.3162 + assert( db->aDb[iDb].pBt!=0 || iDb==1 );
27.3163 + assert( iDb<SQLITE_MAX_ATTACHED+2 );
27.3164 + mask = 1<<iDb;
27.3165 + if( (pParse->cookieMask & mask)==0 ){
27.3166 + pParse->cookieMask |= mask;
27.3167 + pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
27.3168 + if( !OMIT_TEMPDB && iDb==1 ){
27.3169 + sqlite3OpenTempDatabase(pParse);
27.3170 + }
27.3171 + }
27.3172 + }
27.3173 +}
27.3174 +
27.3175 +/*
27.3176 +** Generate VDBE code that prepares for doing an operation that
27.3177 +** might change the database.
27.3178 +**
27.3179 +** This routine starts a new transaction if we are not already within
27.3180 +** a transaction. If we are already within a transaction, then a checkpoint
27.3181 +** is set if the setStatement parameter is true. A checkpoint should
27.3182 +** be set for operations that might fail (due to a constraint) part of
27.3183 +** the way through and which will need to undo some writes without having to
27.3184 +** rollback the whole transaction. For operations where all constraints
27.3185 +** can be checked before any changes are made to the database, it is never
27.3186 +** necessary to undo a write and the checkpoint should not be set.
27.3187 +**
27.3188 +** Only database iDb and the temp database are made writable by this call.
27.3189 +** If iDb==0, then the main and temp databases are made writable. If
27.3190 +** iDb==1 then only the temp database is made writable. If iDb>1 then the
27.3191 +** specified auxiliary database and the temp database are made writable.
27.3192 +*/
27.3193 +void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
27.3194 + Vdbe *v = sqlite3GetVdbe(pParse);
27.3195 + if( v==0 ) return;
27.3196 + sqlite3CodeVerifySchema(pParse, iDb);
27.3197 + pParse->writeMask |= 1<<iDb;
27.3198 + if( setStatement && pParse->nested==0 ){
27.3199 + sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
27.3200 + }
27.3201 + if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
27.3202 + sqlite3BeginWriteOperation(pParse, setStatement, 1);
27.3203 + }
27.3204 +}
27.3205 +
27.3206 +/*
27.3207 +** Check to see if pIndex uses the collating sequence pColl. Return
27.3208 +** true if it does and false if it does not.
27.3209 +*/
27.3210 +#ifndef SQLITE_OMIT_REINDEX
27.3211 +static int collationMatch(const char *zColl, Index *pIndex){
27.3212 + int i;
27.3213 + for(i=0; i<pIndex->nColumn; i++){
27.3214 + const char *z = pIndex->azColl[i];
27.3215 + if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
27.3216 + return 1;
27.3217 + }
27.3218 + }
27.3219 + return 0;
27.3220 +}
27.3221 +#endif
27.3222 +
27.3223 +/*
27.3224 +** Recompute all indices of pTab that use the collating sequence pColl.
27.3225 +** If pColl==0 then recompute all indices of pTab.
27.3226 +*/
27.3227 +#ifndef SQLITE_OMIT_REINDEX
27.3228 +static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
27.3229 + Index *pIndex; /* An index associated with pTab */
27.3230 +
27.3231 + for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
27.3232 + if( zColl==0 || collationMatch(zColl, pIndex) ){
27.3233 + int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
27.3234 + sqlite3BeginWriteOperation(pParse, 0, iDb);
27.3235 + sqlite3RefillIndex(pParse, pIndex, -1);
27.3236 + }
27.3237 + }
27.3238 +}
27.3239 +#endif
27.3240 +
27.3241 +/*
27.3242 +** Recompute all indices of all tables in all databases where the
27.3243 +** indices use the collating sequence pColl. If pColl==0 then recompute
27.3244 +** all indices everywhere.
27.3245 +*/
27.3246 +#ifndef SQLITE_OMIT_REINDEX
27.3247 +static void reindexDatabases(Parse *pParse, char const *zColl){
27.3248 + Db *pDb; /* A single database */
27.3249 + int iDb; /* The database index number */
27.3250 + sqlite3 *db = pParse->db; /* The database connection */
27.3251 + HashElem *k; /* For looping over tables in pDb */
27.3252 + Table *pTab; /* A table in the database */
27.3253 +
27.3254 + for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
27.3255 + assert( pDb!=0 );
27.3256 + for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
27.3257 + pTab = (Table*)sqliteHashData(k);
27.3258 + reindexTable(pParse, pTab, zColl);
27.3259 + }
27.3260 + }
27.3261 +}
27.3262 +#endif
27.3263 +
27.3264 +/*
27.3265 +** Generate code for the REINDEX command.
27.3266 +**
27.3267 +** REINDEX -- 1
27.3268 +** REINDEX <collation> -- 2
27.3269 +** REINDEX ?<database>.?<tablename> -- 3
27.3270 +** REINDEX ?<database>.?<indexname> -- 4
27.3271 +**
27.3272 +** Form 1 causes all indices in all attached databases to be rebuilt.
27.3273 +** Form 2 rebuilds all indices in all databases that use the named
27.3274 +** collating function. Forms 3 and 4 rebuild the named index or all
27.3275 +** indices associated with the named table.
27.3276 +*/
27.3277 +#ifndef SQLITE_OMIT_REINDEX
27.3278 +void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
27.3279 + CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
27.3280 + char *z; /* Name of a table or index */
27.3281 + const char *zDb; /* Name of the database */
27.3282 + Table *pTab; /* A table in the database */
27.3283 + Index *pIndex; /* An index associated with pTab */
27.3284 + int iDb; /* The database index number */
27.3285 + sqlite3 *db = pParse->db; /* The database connection */
27.3286 + Token *pObjName; /* Name of the table or index to be reindexed */
27.3287 +
27.3288 + /* Read the database schema. If an error occurs, leave an error message
27.3289 + ** and code in pParse and return NULL. */
27.3290 + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
27.3291 + return;
27.3292 + }
27.3293 +
27.3294 + if( pName1==0 || pName1->z==0 ){
27.3295 + reindexDatabases(pParse, 0);
27.3296 + return;
27.3297 + }else if( pName2==0 || pName2->z==0 ){
27.3298 + assert( pName1->z );
27.3299 + pColl = sqlite3FindCollSeq(db, ENC(db), (char*)pName1->z, pName1->n, 0);
27.3300 + if( pColl ){
27.3301 + char *zColl = sqliteStrNDup((const char *)pName1->z, pName1->n);
27.3302 + if( zColl ){
27.3303 + reindexDatabases(pParse, zColl);
27.3304 + sqliteFree(zColl);
27.3305 + }
27.3306 + return;
27.3307 + }
27.3308 + }
27.3309 + iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
27.3310 + if( iDb<0 ) return;
27.3311 + z = sqlite3NameFromToken(pObjName);
27.3312 + if( z==0 ) return;
27.3313 + zDb = db->aDb[iDb].zName;
27.3314 + pTab = sqlite3FindTable(db, z, zDb);
27.3315 + if( pTab ){
27.3316 + reindexTable(pParse, pTab, 0);
27.3317 + sqliteFree(z);
27.3318 + return;
27.3319 + }
27.3320 + pIndex = sqlite3FindIndex(db, z, zDb);
27.3321 + sqliteFree(z);
27.3322 + if( pIndex ){
27.3323 + sqlite3BeginWriteOperation(pParse, 0, iDb);
27.3324 + sqlite3RefillIndex(pParse, pIndex, -1);
27.3325 + return;
27.3326 + }
27.3327 + sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
27.3328 +}
27.3329 +#endif
27.3330 +
27.3331 +/*
27.3332 +** Return a dynamicly allocated KeyInfo structure that can be used
27.3333 +** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
27.3334 +**
27.3335 +** If successful, a pointer to the new structure is returned. In this case
27.3336 +** the caller is responsible for calling sqliteFree() on the returned
27.3337 +** pointer. If an error occurs (out of memory or missing collation
27.3338 +** sequence), NULL is returned and the state of pParse updated to reflect
27.3339 +** the error.
27.3340 +*/
27.3341 +KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
27.3342 + int i;
27.3343 + int nCol = pIdx->nColumn;
27.3344 + int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
27.3345 + KeyInfo *pKey = (KeyInfo *)sqliteMalloc(nBytes);
27.3346 +
27.3347 + if( pKey ){
27.3348 + pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
27.3349 + assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
27.3350 + for(i=0; i<nCol; i++){
27.3351 + char *zColl = pIdx->azColl[i];
27.3352 + assert( zColl );
27.3353 + pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
27.3354 + pKey->aSortOrder[i] = pIdx->aSortOrder[i];
27.3355 + }
27.3356 + pKey->nField = nCol;
27.3357 + }
27.3358 +
27.3359 + if( pParse->nErr ){
27.3360 + sqliteFree(pKey);
27.3361 + pKey = 0;
27.3362 + }
27.3363 + return pKey;
27.3364 +}
28.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
28.2 +++ b/extensions/sqlite/sqlite-source/callback.c Sun Jul 29 01:15:31 2007 +0000
28.3 @@ -0,0 +1,374 @@
28.4 +/*
28.5 +** 2005 May 23
28.6 +**
28.7 +** The author disclaims copyright to this source code. In place of
28.8 +** a legal notice, here is a blessing:
28.9 +**
28.10 +** May you do good and not evil.
28.11 +** May you find forgiveness for yourself and forgive others.
28.12 +** May you share freely, never taking more than you give.
28.13 +**
28.14 +*************************************************************************
28.15 +**
28.16 +** This file contains functions used to access the internal hash tables
28.17 +** of user defined functions and collation sequences.
28.18 +**
28.19 +** $Id$
28.20 +*/
28.21 +
28.22 +#include "sqliteInt.h"
28.23 +
28.24 +/*
28.25 +** Invoke the 'collation needed' callback to request a collation sequence
28.26 +** in the database text encoding of name zName, length nName.
28.27 +** If the collation sequence
28.28 +*/
28.29 +static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
28.30 + assert( !db->xCollNeeded || !db->xCollNeeded16 );
28.31 + if( nName<0 ) nName = strlen(zName);
28.32 + if( db->xCollNeeded ){
28.33 + char *zExternal = sqliteStrNDup(zName, nName);
28.34 + if( !zExternal ) return;
28.35 + db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
28.36 + sqliteFree(zExternal);
28.37 + }
28.38 +#ifndef SQLITE_OMIT_UTF16
28.39 + if( db->xCollNeeded16 ){
28.40 + char const *zExternal;
28.41 + sqlite3_value *pTmp = sqlite3ValueNew();
28.42 + sqlite3ValueSetStr(pTmp, nName, zName, SQLITE_UTF8, SQLITE_STATIC);
28.43 + zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
28.44 + if( zExternal ){
28.45 + db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
28.46 + }
28.47 + sqlite3ValueFree(pTmp);
28.48 + }
28.49 +#endif
28.50 +}
28.51 +
28.52 +/*
28.53 +** This routine is called if the collation factory fails to deliver a
28.54 +** collation function in the best encoding but there may be other versions
28.55 +** of this collation function (for other text encodings) available. Use one
28.56 +** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
28.57 +** possible.
28.58 +*/
28.59 +static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
28.60 + CollSeq *pColl2;
28.61 + char *z = pColl->zName;
28.62 + int n = strlen(z);
28.63 + int i;
28.64 + static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
28.65 + for(i=0; i<3; i++){
28.66 + pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, n, 0);
28.67 + if( pColl2->xCmp!=0 ){
28.68 + memcpy(pColl, pColl2, sizeof(CollSeq));
28.69 + pColl->xDel = 0; /* Do not copy the destructor */
28.70 + return SQLITE_OK;
28.71 + }
28.72 + }
28.73 + return SQLITE_ERROR;
28.74 +}
28.75 +
28.76 +/*
28.77 +** This function is responsible for invoking the collation factory callback
28.78 +** or substituting a collation sequence of a different encoding when the
28.79 +** requested collation sequence is not available in the database native
28.80 +** encoding.
28.81 +**
28.82 +** If it is not NULL, then pColl must point to the database native encoding
28.83 +** collation sequence with name zName, length nName.
28.84 +**
28.85 +** The return value is either the collation sequence to be used in database
28.86 +** db for collation type name zName, length nName, or NULL, if no collation
28.87 +** sequence can be found.
28.88 +*/
28.89 +CollSeq *sqlite3GetCollSeq(
28.90 + sqlite3* db,
28.91 + CollSeq *pColl,
28.92 + const char *zName,
28.93 + int nName
28.94 +){
28.95 + CollSeq *p;
28.96 +
28.97 + p = pColl;
28.98 + if( !p ){
28.99 + p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
28.100 + }
28.101 + if( !p || !p->xCmp ){
28.102 + /* No collation sequence of this type for this encoding is registered.
28.103 + ** Call the collation factory to see if it can supply us with one.
28.104 + */
28.105 + callCollNeeded(db, zName, nName);
28.106 + p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
28.107 + }
28.108 + if( p && !p->xCmp && synthCollSeq(db, p) ){
28.109 + p = 0;
28.110 + }
28.111 + assert( !p || p->xCmp );
28.112 + return p;
28.113 +}
28.114 +
28.115 +/*
28.116 +** This routine is called on a collation sequence before it is used to
28.117 +** check that it is defined. An undefined collation sequence exists when
28.118 +** a database is loaded that contains references to collation sequences
28.119 +** that have not been defined by sqlite3_create_collation() etc.
28.120 +**
28.121 +** If required, this routine calls the 'collation needed' callback to
28.122 +** request a definition of the collating sequence. If this doesn't work,
28.123 +** an equivalent collating sequence that uses a text encoding different
28.124 +** from the main database is substituted, if one is available.
28.125 +*/
28.126 +int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
28.127 + if( pColl ){
28.128 + const char *zName = pColl->zName;
28.129 + CollSeq *p = sqlite3GetCollSeq(pParse->db, pColl, zName, -1);
28.130 + if( !p ){
28.131 + if( pParse->nErr==0 ){
28.132 + sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
28.133 + }
28.134 + pParse->nErr++;
28.135 + return SQLITE_ERROR;
28.136 + }
28.137 + assert( p==pColl );
28.138 + }
28.139 + return SQLITE_OK;
28.140 +}
28.141 +
28.142 +
28.143 +
28.144 +/*
28.145 +** Locate and return an entry from the db.aCollSeq hash table. If the entry
28.146 +** specified by zName and nName is not found and parameter 'create' is
28.147 +** true, then create a new entry. Otherwise return NULL.
28.148 +**
28.149 +** Each pointer stored in the sqlite3.aCollSeq hash table contains an
28.150 +** array of three CollSeq structures. The first is the collation sequence
28.151 +** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
28.152 +**
28.153 +** Stored immediately after the three collation sequences is a copy of
28.154 +** the collation sequence name. A pointer to this string is stored in
28.155 +** each collation sequence structure.
28.156 +*/
28.157 +static CollSeq *findCollSeqEntry(
28.158 + sqlite3 *db,
28.159 + const char *zName,
28.160 + int nName,
28.161 + int create
28.162 +){
28.163 + CollSeq *pColl;
28.164 + if( nName<0 ) nName = strlen(zName);
28.165 + pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
28.166 +
28.167 + if( 0==pColl && create ){
28.168 + pColl = sqliteMalloc( 3*sizeof(*pColl) + nName + 1 );
28.169 + if( pColl ){
28.170 + CollSeq *pDel = 0;
28.171 + pColl[0].zName = (char*)&pColl[3];
28.172 + pColl[0].enc = SQLITE_UTF8;
28.173 + pColl[1].zName = (char*)&pColl[3];
28.174 + pColl[1].enc = SQLITE_UTF16LE;
28.175 + pColl[2].zName = (char*)&pColl[3];
28.176 + pColl[2].enc = SQLITE_UTF16BE;
28.177 + memcpy(pColl[0].zName, zName, nName);
28.178 + pColl[0].zName[nName] = 0;
28.179 + pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
28.180 +
28.181 + /* If a malloc() failure occured in sqlite3HashInsert(), it will
28.182 + ** return the pColl pointer to be deleted (because it wasn't added
28.183 + ** to the hash table).
28.184 + */
28.185 + assert( !pDel || (sqlite3MallocFailed() && pDel==pColl) );
28.186 + if( pDel ){
28.187 + sqliteFree(pDel);
28.188 + pColl = 0;
28.189 + }
28.190 + }
28.191 + }
28.192 + return pColl;
28.193 +}
28.194 +
28.195 +/*
28.196 +** Parameter zName points to a UTF-8 encoded string nName bytes long.
28.197 +** Return the CollSeq* pointer for the collation sequence named zName
28.198 +** for the encoding 'enc' from the database 'db'.
28.199 +**
28.200 +** If the entry specified is not found and 'create' is true, then create a
28.201 +** new entry. Otherwise return NULL.
28.202 +**
28.203 +** A separate function sqlite3LocateCollSeq() is a wrapper around
28.204 +** this routine. sqlite3LocateCollSeq() invokes the collation factory
28.205 +** if necessary and generates an error message if the collating sequence
28.206 +** cannot be found.
28.207 +*/
28.208 +CollSeq *sqlite3FindCollSeq(
28.209 + sqlite3 *db,
28.210 + u8 enc,
28.211 + const char *zName,
28.212 + int nName,
28.213 + int create
28.214 +){
28.215 + CollSeq *pColl;
28.216 + if( zName ){
28.217 + pColl = findCollSeqEntry(db, zName, nName, create);
28.218 + }else{
28.219 + pColl = db->pDfltColl;
28.220 + }
28.221 + assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
28.222 + assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
28.223 + if( pColl ) pColl += enc-1;
28.224 + return pColl;
28.225 +}
28.226 +
28.227 +/*
28.228 +** Locate a user function given a name, a number of arguments and a flag
28.229 +** indicating whether the function prefers UTF-16 over UTF-8. Return a
28.230 +** pointer to the FuncDef structure that defines that function, or return
28.231 +** NULL if the function does not exist.
28.232 +**
28.233 +** If the createFlag argument is true, then a new (blank) FuncDef
28.234 +** structure is created and liked into the "db" structure if a
28.235 +** no matching function previously existed. When createFlag is true
28.236 +** and the nArg parameter is -1, then only a function that accepts
28.237 +** any number of arguments will be returned.
28.238 +**
28.239 +** If createFlag is false and nArg is -1, then the first valid
28.240 +** function found is returned. A function is valid if either xFunc
28.241 +** or xStep is non-zero.
28.242 +**
28.243 +** If createFlag is false, then a function with the required name and
28.244 +** number of arguments may be returned even if the eTextRep flag does not
28.245 +** match that requested.
28.246 +*/
28.247 +FuncDef *sqlite3FindFunction(
28.248 + sqlite3 *db, /* An open database */
28.249 + const char *zName, /* Name of the function. Not null-terminated */
28.250 + int nName, /* Number of characters in the name */
28.251 + int nArg, /* Number of arguments. -1 means any number */
28.252 + u8 enc, /* Preferred text encoding */
28.253 + int createFlag /* Create new entry if true and does not otherwise exist */
28.254 +){
28.255 + FuncDef *p; /* Iterator variable */
28.256 + FuncDef *pFirst; /* First function with this name */
28.257 + FuncDef *pBest = 0; /* Best match found so far */
28.258 + int bestmatch = 0;
28.259 +
28.260 +
28.261 + assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
28.262 + if( nArg<-1 ) nArg = -1;
28.263 +
28.264 + pFirst = (FuncDef*)sqlite3HashFind(&db->aFunc, zName, nName);
28.265 + for(p=pFirst; p; p=p->pNext){
28.266 + /* During the search for the best function definition, bestmatch is set
28.267 + ** as follows to indicate the quality of the match with the definition
28.268 + ** pointed to by pBest:
28.269 + **
28.270 + ** 0: pBest is NULL. No match has been found.
28.271 + ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
28.272 + ** encoding is requested, or vice versa.
28.273 + ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
28.274 + ** requested, or vice versa.
28.275 + ** 3: A variable arguments function using the same text encoding.
28.276 + ** 4: A function with the exact number of arguments requested that
28.277 + ** prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
28.278 + ** 5: A function with the exact number of arguments requested that
28.279 + ** prefers UTF-16LE when UTF-16BE is requested, or vice versa.
28.280 + ** 6: An exact match.
28.281 + **
28.282 + ** A larger value of 'matchqual' indicates a more desirable match.
28.283 + */
28.284 + if( p->nArg==-1 || p->nArg==nArg || nArg==-1 ){
28.285 + int match = 1; /* Quality of this match */
28.286 + if( p->nArg==nArg || nArg==-1 ){
28.287 + match = 4;
28.288 + }
28.289 + if( enc==p->iPrefEnc ){
28.290 + match += 2;
28.291 + }
28.292 + else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
28.293 + (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
28.294 + match += 1;
28.295 + }
28.296 +
28.297 + if( match>bestmatch ){
28.298 + pBest = p;
28.299 + bestmatch = match;
28.300 + }
28.301 + }
28.302 + }
28.303 +
28.304 + /* If the createFlag parameter is true, and the seach did not reveal an
28.305 + ** exact match for the name, number of arguments and encoding, then add a
28.306 + ** new entry to the hash table and return it.
28.307 + */
28.308 + if( createFlag && bestmatch<6 &&
28.309 + (pBest = sqliteMalloc(sizeof(*pBest)+nName))!=0 ){
28.310 + pBest->nArg = nArg;
28.311 + pBest->pNext = pFirst;
28.312 + pBest->iPrefEnc = enc;
28.313 + memcpy(pBest->zName, zName, nName);
28.314 + pBest->zName[nName] = 0;
28.315 + if( pBest==sqlite3HashInsert(&db->aFunc,pBest->zName,nName,(void*)pBest) ){
28.316 + sqliteFree(pBest);
28.317 + return 0;
28.318 + }
28.319 + }
28.320 +
28.321 + if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
28.322 + return pBest;
28.323 + }
28.324 + return 0;
28.325 +}
28.326 +
28.327 +/*
28.328 +** Free all resources held by the schema structure. The void* argument points
28.329 +** at a Schema struct. This function does not call sqliteFree() on the
28.330 +** pointer itself, it just cleans up subsiduary resources (i.e. the contents
28.331 +** of the schema hash tables).
28.332 +*/
28.333 +void sqlite3SchemaFree(void *p){
28.334 + Hash temp1;
28.335 + Hash temp2;
28.336 + HashElem *pElem;
28.337 + Schema *pSchema = (Schema *)p;
28.338 +
28.339 + temp1 = pSchema->tblHash;
28.340 + temp2 = pSchema->trigHash;
28.341 + sqlite3HashInit(&pSchema->trigHash, SQLITE_HASH_STRING, 0);
28.342 + sqlite3HashClear(&pSchema->aFKey);
28.343 + sqlite3HashClear(&pSchema->idxHash);
28.344 + for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
28.345 + sqlite3DeleteTrigger((Trigger*)sqliteHashData(pElem));
28.346 + }
28.347 + sqlite3HashClear(&temp2);
28.348 + sqlite3HashInit(&pSchema->tblHash, SQLITE_HASH_STRING, 0);
28.349 + for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
28.350 + Table *pTab = sqliteHashData(pElem);
28.351 + sqlite3DeleteTable(pTab);
28.352 + }
28.353 + sqlite3HashClear(&temp1);
28.354 + pSchema->pSeqTab = 0;
28.355 + pSchema->flags &= ~DB_SchemaLoaded;
28.356 +}
28.357 +
28.358 +/*
28.359 +** Find and return the schema associated with a BTree. Create
28.360 +** a new one if necessary.
28.361 +*/
28.362 +Schema *sqlite3SchemaGet(Btree *pBt){
28.363 + Schema * p;
28.364 + if( pBt ){
28.365 + p = (Schema *)sqlite3BtreeSchema(pBt,sizeof(Schema),sqlite3SchemaFree);
28.366 + }else{
28.367 + p = (Schema *)sqliteMalloc(sizeof(Schema));
28.368 + }
28.369 + if( p && 0==p->file_format ){
28.370 + sqlite3HashInit(&p->tblHash, SQLITE_HASH_STRING, 0);
28.371 + sqlite3HashInit(&p->idxHash, SQLITE_HASH_STRING, 0);
28.372 + sqlite3HashInit(&p->trigHash, SQLITE_HASH_STRING, 0);
28.373 + sqlite3HashInit(&p->aFKey, SQLITE_HASH_STRING, 1);
28.374 + p->enc = SQLITE_UTF8;
28.375 + }
28.376 + return p;
28.377 +}
29.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
29.2 +++ b/extensions/sqlite/sqlite-source/complete.c Sun Jul 29 01:15:31 2007 +0000
29.3 @@ -0,0 +1,263 @@
29.4 +/*
29.5 +** 2001 September 15
29.6 +**
29.7 +** The author disclaims copyright to this source code. In place of
29.8 +** a legal notice, here is a blessing:
29.9 +**
29.10 +** May you do good and not evil.
29.11 +** May you find forgiveness for yourself and forgive others.
29.12 +** May you share freely, never taking more than you give.
29.13 +**
29.14 +*************************************************************************
29.15 +** An tokenizer for SQL
29.16 +**
29.17 +** This file contains C code that implements the sqlite3_complete() API.
29.18 +** This code used to be part of the tokenizer.c source file. But by
29.19 +** separating it out, the code will be automatically omitted from
29.20 +** static links that do not use it.
29.21 +**
29.22 +** $Id$
29.23 +*/
29.24 +#include "sqliteInt.h"
29.25 +#ifndef SQLITE_OMIT_COMPLETE
29.26 +
29.27 +/*
29.28 +** This is defined in tokenize.c. We just have to import the definition.
29.29 +*/
29.30 +extern const char sqlite3IsIdChar[];
29.31 +#define IdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsIdChar[c-0x20]))
29.32 +
29.33 +
29.34 +/*
29.35 +** Token types used by the sqlite3_complete() routine. See the header
29.36 +** comments on that procedure for additional information.
29.37 +*/
29.38 +#define tkSEMI 0
29.39 +#define tkWS 1
29.40 +#define tkOTHER 2
29.41 +#define tkEXPLAIN 3
29.42 +#define tkCREATE 4
29.43 +#define tkTEMP 5
29.44 +#define tkTRIGGER 6
29.45 +#define tkEND 7
29.46 +
29.47 +/*
29.48 +** Return TRUE if the given SQL string ends in a semicolon.
29.49 +**
29.50 +** Special handling is require for CREATE TRIGGER statements.
29.51 +** Whenever the CREATE TRIGGER keywords are seen, the statement
29.52 +** must end with ";END;".
29.53 +**
29.54 +** This implementation uses a state machine with 7 states:
29.55 +**
29.56 +** (0) START At the beginning or end of an SQL statement. This routine
29.57 +** returns 1 if it ends in the START state and 0 if it ends
29.58 +** in any other state.
29.59 +**
29.60 +** (1) NORMAL We are in the middle of statement which ends with a single
29.61 +** semicolon.
29.62 +**
29.63 +** (2) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
29.64 +** a statement.
29.65 +**
29.66 +** (3) CREATE The keyword CREATE has been seen at the beginning of a
29.67 +** statement, possibly preceeded by EXPLAIN and/or followed by
29.68 +** TEMP or TEMPORARY
29.69 +**
29.70 +** (4) TRIGGER We are in the middle of a trigger definition that must be
29.71 +** ended by a semicolon, the keyword END, and another semicolon.
29.72 +**
29.73 +** (5) SEMI We've seen the first semicolon in the ";END;" that occurs at
29.74 +** the end of a trigger definition.
29.75 +**
29.76 +** (6) END We've seen the ";END" of the ";END;" that occurs at the end
29.77 +** of a trigger difinition.
29.78 +**
29.79 +** Transitions between states above are determined by tokens extracted
29.80 +** from the input. The following tokens are significant:
29.81 +**
29.82 +** (0) tkSEMI A semicolon.
29.83 +** (1) tkWS Whitespace
29.84 +** (2) tkOTHER Any other SQL token.
29.85 +** (3) tkEXPLAIN The "explain" keyword.
29.86 +** (4) tkCREATE The "create" keyword.
29.87 +** (5) tkTEMP The "temp" or "temporary" keyword.
29.88 +** (6) tkTRIGGER The "trigger" keyword.
29.89 +** (7) tkEND The "end" keyword.
29.90 +**
29.91 +** Whitespace never causes a state transition and is always ignored.
29.92 +**
29.93 +** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
29.94 +** to recognize the end of a trigger can be omitted. All we have to do
29.95 +** is look for a semicolon that is not part of an string or comment.
29.96 +*/
29.97 +int sqlite3_complete(const char *zSql){
29.98 + u8 state = 0; /* Current state, using numbers defined in header comment */
29.99 + u8 token; /* Value of the next token */
29.100 +
29.101 +#ifndef SQLITE_OMIT_TRIGGER
29.102 + /* A complex statement machine used to detect the end of a CREATE TRIGGER
29.103 + ** statement. This is the normal case.
29.104 + */
29.105 + static const u8 trans[7][8] = {
29.106 + /* Token: */
29.107 + /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
29.108 + /* 0 START: */ { 0, 0, 1, 2, 3, 1, 1, 1, },
29.109 + /* 1 NORMAL: */ { 0, 1, 1, 1, 1, 1, 1, 1, },
29.110 + /* 2 EXPLAIN: */ { 0, 2, 1, 1, 3, 1, 1, 1, },
29.111 + /* 3 CREATE: */ { 0, 3, 1, 1, 1, 3, 4, 1, },
29.112 + /* 4 TRIGGER: */ { 5, 4, 4, 4, 4, 4, 4, 4, },
29.113 + /* 5 SEMI: */ { 5, 5, 4, 4, 4, 4, 4, 6, },
29.114 + /* 6 END: */ { 0, 6, 4, 4, 4, 4, 4, 4, },
29.115 + };
29.116 +#else
29.117 + /* If triggers are not suppored by this compile then the statement machine
29.118 + ** used to detect the end of a statement is much simplier
29.119 + */
29.120 + static const u8 trans[2][3] = {
29.121 + /* Token: */
29.122 + /* State: ** SEMI WS OTHER */
29.123 + /* 0 START: */ { 0, 0, 1, },
29.124 + /* 1 NORMAL: */ { 0, 1, 1, },
29.125 + };
29.126 +#endif /* SQLITE_OMIT_TRIGGER */
29.127 +
29.128 + while( *zSql ){
29.129 + switch( *zSql ){
29.130 + case ';': { /* A semicolon */
29.131 + token = tkSEMI;
29.132 + break;
29.133 + }
29.134 + case ' ':
29.135 + case '\r':
29.136 + case '\t':
29.137 + case '\n':
29.138 + case '\f': { /* White space is ignored */
29.139 + token = tkWS;
29.140 + break;
29.141 + }
29.142 + case '/': { /* C-style comments */
29.143 + if( zSql[1]!='*' ){
29.144 + token = tkOTHER;
29.145 + break;
29.146 + }
29.147 + zSql += 2;
29.148 + while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
29.149 + if( zSql[0]==0 ) return 0;
29.150 + zSql++;
29.151 + token = tkWS;
29.152 + break;
29.153 + }
29.154 + case '-': { /* SQL-style comments from "--" to end of line */
29.155 + if( zSql[1]!='-' ){
29.156 + token = tkOTHER;
29.157 + break;
29.158 + }
29.159 + while( *zSql && *zSql!='\n' ){ zSql++; }
29.160 + if( *zSql==0 ) return state==0;
29.161 + token = tkWS;
29.162 + break;
29.163 + }
29.164 + case '[': { /* Microsoft-style identifiers in [...] */
29.165 + zSql++;
29.166 + while( *zSql && *zSql!=']' ){ zSql++; }
29.167 + if( *zSql==0 ) return 0;
29.168 + token = tkOTHER;
29.169 + break;
29.170 + }
29.171 + case '`': /* Grave-accent quoted symbols used by MySQL */
29.172 + case '"': /* single- and double-quoted strings */
29.173 + case '\'': {
29.174 + int c = *zSql;
29.175 + zSql++;
29.176 + while( *zSql && *zSql!=c ){ zSql++; }
29.177 + if( *zSql==0 ) return 0;
29.178 + token = tkOTHER;
29.179 + break;
29.180 + }
29.181 + default: {
29.182 + int c;
29.183 + if( IdChar((u8)*zSql) ){
29.184 + /* Keywords and unquoted identifiers */
29.185 + int nId;
29.186 + for(nId=1; IdChar(zSql[nId]); nId++){}
29.187 +#ifdef SQLITE_OMIT_TRIGGER
29.188 + token = tkOTHER;
29.189 +#else
29.190 + switch( *zSql ){
29.191 + case 'c': case 'C': {
29.192 + if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
29.193 + token = tkCREATE;
29.194 + }else{
29.195 + token = tkOTHER;
29.196 + }
29.197 + break;
29.198 + }
29.199 + case 't': case 'T': {
29.200 + if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
29.201 + token = tkTRIGGER;
29.202 + }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
29.203 + token = tkTEMP;
29.204 + }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
29.205 + token = tkTEMP;
29.206 + }else{
29.207 + token = tkOTHER;
29.208 + }
29.209 + break;
29.210 + }
29.211 + case 'e': case 'E': {
29.212 + if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
29.213 + token = tkEND;
29.214 + }else
29.215 +#ifndef SQLITE_OMIT_EXPLAIN
29.216 + if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
29.217 + token = tkEXPLAIN;
29.218 + }else
29.219 +#endif
29.220 + {
29.221 + token = tkOTHER;
29.222 + }
29.223 + break;
29.224 + }
29.225 + default: {
29.226 + token = tkOTHER;
29.227 + break;
29.228 + }
29.229 + }
29.230 +#endif /* SQLITE_OMIT_TRIGGER */
29.231 + zSql += nId-1;
29.232 + }else{
29.233 + /* Operators and special symbols */
29.234 + token = tkOTHER;
29.235 + }
29.236 + break;
29.237 + }
29.238 + }
29.239 + state = trans[state][token];
29.240 + zSql++;
29.241 + }
29.242 + return state==0;
29.243 +}
29.244 +
29.245 +#ifndef SQLITE_OMIT_UTF16
29.246 +/*
29.247 +** This routine is the same as the sqlite3_complete() routine described
29.248 +** above, except that the parameter is required to be UTF-16 encoded, not
29.249 +** UTF-8.
29.250 +*/
29.251 +int sqlite3_complete16(const void *zSql){
29.252 + sqlite3_value *pVal;
29.253 + char const *zSql8;
29.254 + int rc = 0;
29.255 +
29.256 + pVal = sqlite3ValueNew();
29.257 + sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
29.258 + zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
29.259 + if( zSql8 ){
29.260 + rc = sqlite3_complete(zSql8);
29.261 + }
29.262 + sqlite3ValueFree(pVal);
29.263 + return sqlite3ApiExit(0, rc);
29.264 +}
29.265 +#endif /* SQLITE_OMIT_UTF16 */
29.266 +#endif /* SQLITE_OMIT_COMPLETE */
30.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
30.2 +++ b/extensions/sqlite/sqlite-source/date.c Sun Jul 29 01:15:31 2007 +0000
30.3 @@ -0,0 +1,1036 @@
30.4 +/*
30.5 +** 2003 October 31
30.6 +**
30.7 +** The author disclaims copyright to this source code. In place of
30.8 +** a legal notice, here is a blessing:
30.9 +**
30.10 +** May you do good and not evil.
30.11 +** May you find forgiveness for yourself and forgive others.
30.12 +** May you share freely, never taking more than you give.
30.13 +**
30.14 +*************************************************************************
30.15 +** This file contains the C functions that implement date and time
30.16 +** functions for SQLite.
30.17 +**
30.18 +** There is only one exported symbol in this file - the function
30.19 +** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
30.20 +** All other code has file scope.
30.21 +**
30.22 +** $Id$
30.23 +**
30.24 +** SQLite processes all times and dates as Julian Day numbers. The
30.25 +** dates and times are stored as the number of days since noon
30.26 +** in Greenwich on November 24, 4714 B.C. according to the Gregorian
30.27 +** calendar system.
30.28 +**
30.29 +** 1970-01-01 00:00:00 is JD 2440587.5
30.30 +** 2000-01-01 00:00:00 is JD 2451544.5
30.31 +**
30.32 +** This implemention requires years to be expressed as a 4-digit number
30.33 +** which means that only dates between 0000-01-01 and 9999-12-31 can
30.34 +** be represented, even though julian day numbers allow a much wider
30.35 +** range of dates.
30.36 +**
30.37 +** The Gregorian calendar system is used for all dates and times,
30.38 +** even those that predate the Gregorian calendar. Historians usually
30.39 +** use the Julian calendar for dates prior to 1582-10-15 and for some
30.40 +** dates afterwards, depending on locale. Beware of this difference.
30.41 +**
30.42 +** The conversion algorithms are implemented based on descriptions
30.43 +** in the following text:
30.44 +**
30.45 +** Jean Meeus
30.46 +** Astronomical Algorithms, 2nd Edition, 1998
30.47 +** ISBM 0-943396-61-1
30.48 +** Willmann-Bell, Inc
30.49 +** Richmond, Virginia (USA)
30.50 +*/
30.51 +#include "sqliteInt.h"
30.52 +#include "os.h"
30.53 +#include <ctype.h>
30.54 +#include <stdlib.h>
30.55 +#include <assert.h>
30.56 +#include <time.h>
30.57 +
30.58 +#ifndef SQLITE_OMIT_DATETIME_FUNCS
30.59 +
30.60 +/*
30.61 +** A structure for holding a single date and time.
30.62 +*/
30.63 +typedef struct DateTime DateTime;
30.64 +struct DateTime {
30.65 + double rJD; /* The julian day number */
30.66 + int Y, M, D; /* Year, month, and day */
30.67 + int h, m; /* Hour and minutes */
30.68 + int tz; /* Timezone offset in minutes */
30.69 + double s; /* Seconds */
30.70 + char validYMD; /* True if Y,M,D are valid */
30.71 + char validHMS; /* True if h,m,s are valid */
30.72 + char validJD; /* True if rJD is valid */
30.73 + char validTZ; /* True if tz is valid */
30.74 +};
30.75 +
30.76 +
30.77 +/*
30.78 +** Convert zDate into one or more integers. Additional arguments
30.79 +** come in groups of 5 as follows:
30.80 +**
30.81 +** N number of digits in the integer
30.82 +** min minimum allowed value of the integer
30.83 +** max maximum allowed value of the integer
30.84 +** nextC first character after the integer
30.85 +** pVal where to write the integers value.
30.86 +**
30.87 +** Conversions continue until one with nextC==0 is encountered.
30.88 +** The function returns the number of successful conversions.
30.89 +*/
30.90 +static int getDigits(const char *zDate, ...){
30.91 + va_list ap;
30.92 + int val;
30.93 + int N;
30.94 + int min;
30.95 + int max;
30.96 + int nextC;
30.97 + int *pVal;
30.98 + int cnt = 0;
30.99 + va_start(ap, zDate);
30.100 + do{
30.101 + N = va_arg(ap, int);
30.102 + min = va_arg(ap, int);
30.103 + max = va_arg(ap, int);
30.104 + nextC = va_arg(ap, int);
30.105 + pVal = va_arg(ap, int*);
30.106 + val = 0;
30.107 + while( N-- ){
30.108 + if( !isdigit(*(u8*)zDate) ){
30.109 + goto end_getDigits;
30.110 + }
30.111 + val = val*10 + *zDate - '0';
30.112 + zDate++;
30.113 + }
30.114 + if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
30.115 + goto end_getDigits;
30.116 + }
30.117 + *pVal = val;
30.118 + zDate++;
30.119 + cnt++;
30.120 + }while( nextC );
30.121 +end_getDigits:
30.122 + va_end(ap);
30.123 + return cnt;
30.124 +}
30.125 +
30.126 +/*
30.127 +** Read text from z[] and convert into a floating point number. Return
30.128 +** the number of digits converted.
30.129 +*/
30.130 +#define getValue sqlite3AtoF
30.131 +
30.132 +/*
30.133 +** Parse a timezone extension on the end of a date-time.
30.134 +** The extension is of the form:
30.135 +**
30.136 +** (+/-)HH:MM
30.137 +**
30.138 +** If the parse is successful, write the number of minutes
30.139 +** of change in *pnMin and return 0. If a parser error occurs,
30.140 +** return 0.
30.141 +**
30.142 +** A missing specifier is not considered an error.
30.143 +*/
30.144 +static int parseTimezone(const char *zDate, DateTime *p){
30.145 + int sgn = 0;
30.146 + int nHr, nMn;
30.147 + while( isspace(*(u8*)zDate) ){ zDate++; }
30.148 + p->tz = 0;
30.149 + if( *zDate=='-' ){
30.150 + sgn = -1;
30.151 + }else if( *zDate=='+' ){
30.152 + sgn = +1;
30.153 + }else{
30.154 + return *zDate!=0;
30.155 + }
30.156 + zDate++;
30.157 + if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
30.158 + return 1;
30.159 + }
30.160 + zDate += 5;
30.161 + p->tz = sgn*(nMn + nHr*60);
30.162 + while( isspace(*(u8*)zDate) ){ zDate++; }
30.163 + return *zDate!=0;
30.164 +}
30.165 +
30.166 +/*
30.167 +** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
30.168 +** The HH, MM, and SS must each be exactly 2 digits. The
30.169 +** fractional seconds FFFF can be one or more digits.
30.170 +**
30.171 +** Return 1 if there is a parsing error and 0 on success.
30.172 +*/
30.173 +static int parseHhMmSs(const char *zDate, DateTime *p){
30.174 + int h, m, s;
30.175 + double ms = 0.0;
30.176 + if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
30.177 + return 1;
30.178 + }
30.179 + zDate += 5;
30.180 + if( *zDate==':' ){
30.181 + zDate++;
30.182 + if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
30.183 + return 1;
30.184 + }
30.185 + zDate += 2;
30.186 + if( *zDate=='.' && isdigit((u8)zDate[1]) ){
30.187 + double rScale = 1.0;
30.188 + zDate++;
30.189 + while( isdigit(*(u8*)zDate) ){
30.190 + ms = ms*10.0 + *zDate - '0';
30.191 + rScale *= 10.0;
30.192 + zDate++;
30.193 + }
30.194 + ms /= rScale;
30.195 + }
30.196 + }else{
30.197 + s = 0;
30.198 + }
30.199 + p->validJD = 0;
30.200 + p->validHMS = 1;
30.201 + p->h = h;
30.202 + p->m = m;
30.203 + p->s = s + ms;
30.204 + if( parseTimezone(zDate, p) ) return 1;
30.205 + p->validTZ = p->tz!=0;
30.206 + return 0;
30.207 +}
30.208 +
30.209 +/*
30.210 +** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
30.211 +** that the YYYY-MM-DD is according to the Gregorian calendar.
30.212 +**
30.213 +** Reference: Meeus page 61
30.214 +*/
30.215 +static void computeJD(DateTime *p){
30.216 + int Y, M, D, A, B, X1, X2;
30.217 +
30.218 + if( p->validJD ) return;
30.219 + if( p->validYMD ){
30.220 + Y = p->Y;
30.221 + M = p->M;
30.222 + D = p->D;
30.223 + }else{
30.224 + Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
30.225 + M = 1;
30.226 + D = 1;
30.227 + }
30.228 + if( M<=2 ){
30.229 + Y--;
30.230 + M += 12;
30.231 + }
30.232 + A = Y/100;
30.233 + B = 2 - A + (A/4);
30.234 + X1 = 365.25*(Y+4716);
30.235 + X2 = 30.6001*(M+1);
30.236 + p->rJD = X1 + X2 + D + B - 1524.5;
30.237 + p->validJD = 1;
30.238 + if( p->validHMS ){
30.239 + p->rJD += (p->h*3600.0 + p->m*60.0 + p->s)/86400.0;
30.240 + if( p->validTZ ){
30.241 + p->rJD -= p->tz*60/86400.0;
30.242 + p->validYMD = 0;
30.243 + p->validHMS = 0;
30.244 + p->validTZ = 0;
30.245 + }
30.246 + }
30.247 +}
30.248 +
30.249 +/*
30.250 +** Parse dates of the form
30.251 +**
30.252 +** YYYY-MM-DD HH:MM:SS.FFF
30.253 +** YYYY-MM-DD HH:MM:SS
30.254 +** YYYY-MM-DD HH:MM
30.255 +** YYYY-MM-DD
30.256 +**
30.257 +** Write the result into the DateTime structure and return 0
30.258 +** on success and 1 if the input string is not a well-formed
30.259 +** date.
30.260 +*/
30.261 +static int parseYyyyMmDd(const char *zDate, DateTime *p){
30.262 + int Y, M, D, neg;
30.263 +
30.264 + if( zDate[0]=='-' ){
30.265 + zDate++;
30.266 + neg = 1;
30.267 + }else{
30.268 + neg = 0;
30.269 + }
30.270 + if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
30.271 + return 1;
30.272 + }
30.273 + zDate += 10;
30.274 + while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
30.275 + if( parseHhMmSs(zDate, p)==0 ){
30.276 + /* We got the time */
30.277 + }else if( *zDate==0 ){
30.278 + p->validHMS = 0;
30.279 + }else{
30.280 + return 1;
30.281 + }
30.282 + p->validJD = 0;
30.283 + p->validYMD = 1;
30.284 + p->Y = neg ? -Y : Y;
30.285 + p->M = M;
30.286 + p->D = D;
30.287 + if( p->validTZ ){
30.288 + computeJD(p);
30.289 + }
30.290 + return 0;
30.291 +}
30.292 +
30.293 +/*
30.294 +** Attempt to parse the given string into a Julian Day Number. Return
30.295 +** the number of errors.
30.296 +**
30.297 +** The following are acceptable forms for the input string:
30.298 +**
30.299 +** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
30.300 +** DDDD.DD
30.301 +** now
30.302 +**
30.303 +** In the first form, the +/-HH:MM is always optional. The fractional
30.304 +** seconds extension (the ".FFF") is optional. The seconds portion
30.305 +** (":SS.FFF") is option. The year and date can be omitted as long
30.306 +** as there is a time string. The time string can be omitted as long
30.307 +** as there is a year and date.
30.308 +*/
30.309 +static int parseDateOrTime(const char *zDate, DateTime *p){
30.310 + memset(p, 0, sizeof(*p));
30.311 + if( parseYyyyMmDd(zDate,p)==0 ){
30.312 + return 0;
30.313 + }else if( parseHhMmSs(zDate, p)==0 ){
30.314 + return 0;
30.315 + }else if( sqlite3StrICmp(zDate,"now")==0){
30.316 + double r;
30.317 + sqlite3OsCurrentTime(&r);
30.318 + p->rJD = r;
30.319 + p->validJD = 1;
30.320 + return 0;
30.321 + }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
30.322 + getValue(zDate, &p->rJD);
30.323 + p->validJD = 1;
30.324 + return 0;
30.325 + }
30.326 + return 1;
30.327 +}
30.328 +
30.329 +/*
30.330 +** Compute the Year, Month, and Day from the julian day number.
30.331 +*/
30.332 +static void computeYMD(DateTime *p){
30.333 + int Z, A, B, C, D, E, X1;
30.334 + if( p->validYMD ) return;
30.335 + if( !p->validJD ){
30.336 + p->Y = 2000;
30.337 + p->M = 1;
30.338 + p->D = 1;
30.339 + }else{
30.340 + Z = p->rJD + 0.5;
30.341 + A = (Z - 1867216.25)/36524.25;
30.342 + A = Z + 1 + A - (A/4);
30.343 + B = A + 1524;
30.344 + C = (B - 122.1)/365.25;
30.345 + D = 365.25*C;
30.346 + E = (B-D)/30.6001;
30.347 + X1 = 30.6001*E;
30.348 + p->D = B - D - X1;
30.349 + p->M = E<14 ? E-1 : E-13;
30.350 + p->Y = p->M>2 ? C - 4716 : C - 4715;
30.351 + }
30.352 + p->validYMD = 1;
30.353 +}
30.354 +
30.355 +/*
30.356 +** Compute the Hour, Minute, and Seconds from the julian day number.
30.357 +*/
30.358 +static void computeHMS(DateTime *p){
30.359 + int Z, s;
30.360 + if( p->validHMS ) return;
30.361 + computeJD(p);
30.362 + Z = p->rJD + 0.5;
30.363 + s = (p->rJD + 0.5 - Z)*86400000.0 + 0.5;
30.364 + p->s = 0.001*s;
30.365 + s = p->s;
30.366 + p->s -= s;
30.367 + p->h = s/3600;
30.368 + s -= p->h*3600;
30.369 + p->m = s/60;
30.370 + p->s += s - p->m*60;
30.371 + p->validHMS = 1;
30.372 +}
30.373 +
30.374 +/*
30.375 +** Compute both YMD and HMS
30.376 +*/
30.377 +static void computeYMD_HMS(DateTime *p){
30.378 + computeYMD(p);
30.379 + computeHMS(p);
30.380 +}
30.381 +
30.382 +/*
30.383 +** Clear the YMD and HMS and the TZ
30.384 +*/
30.385 +static void clearYMD_HMS_TZ(DateTime *p){
30.386 + p->validYMD = 0;
30.387 + p->validHMS = 0;
30.388 + p->validTZ = 0;
30.389 +}
30.390 +
30.391 +/*
30.392 +** Compute the difference (in days) between localtime and UTC (a.k.a. GMT)
30.393 +** for the time value p where p is in UTC.
30.394 +*/
30.395 +static double localtimeOffset(DateTime *p){
30.396 + DateTime x, y;
30.397 + time_t t;
30.398 + x = *p;
30.399 + computeYMD_HMS(&x);
30.400 + if( x.Y<1971 || x.Y>=2038 ){
30.401 + x.Y = 2000;
30.402 + x.M = 1;
30.403 + x.D = 1;
30.404 + x.h = 0;
30.405 + x.m = 0;
30.406 + x.s = 0.0;
30.407 + } else {
30.408 + int s = x.s + 0.5;
30.409 + x.s = s;
30.410 + }
30.411 + x.tz = 0;
30.412 + x.validJD = 0;
30.413 + computeJD(&x);
30.414 + t = (x.rJD-2440587.5)*86400.0 + 0.5;
30.415 +#ifdef HAVE_LOCALTIME_R
30.416 + {
30.417 + struct tm sLocal;
30.418 + localtime_r(&t, &sLocal);
30.419 + y.Y = sLocal.tm_year + 1900;
30.420 + y.M = sLocal.tm_mon + 1;
30.421 + y.D = sLocal.tm_mday;
30.422 + y.h = sLocal.tm_hour;
30.423 + y.m = sLocal.tm_min;
30.424 + y.s = sLocal.tm_sec;
30.425 + }
30.426 +#else
30.427 + {
30.428 + struct tm *pTm;
30.429 + sqlite3OsEnterMutex();
30.430 + pTm = localtime(&t);
30.431 + y.Y = pTm->tm_year + 1900;
30.432 + y.M = pTm->tm_mon + 1;
30.433 + y.D = pTm->tm_mday;
30.434 + y.h = pTm->tm_hour;
30.435 + y.m = pTm->tm_min;
30.436 + y.s = pTm->tm_sec;
30.437 + sqlite3OsLeaveMutex();
30.438 + }
30.439 +#endif
30.440 + y.validYMD = 1;
30.441 + y.validHMS = 1;
30.442 + y.validJD = 0;
30.443 + y.validTZ = 0;
30.444 + computeJD(&y);
30.445 + return y.rJD - x.rJD;
30.446 +}
30.447 +
30.448 +/*
30.449 +** Process a modifier to a date-time stamp. The modifiers are
30.450 +** as follows:
30.451 +**
30.452 +** NNN days
30.453 +** NNN hours
30.454 +** NNN minutes
30.455 +** NNN.NNNN seconds
30.456 +** NNN months
30.457 +** NNN years
30.458 +** start of month
30.459 +** start of year
30.460 +** start of week
30.461 +** start of day
30.462 +** weekday N
30.463 +** unixepoch
30.464 +** localtime
30.465 +** utc
30.466 +**
30.467 +** Return 0 on success and 1 if there is any kind of error.
30.468 +*/
30.469 +static int parseModifier(const char *zMod, DateTime *p){
30.470 + int rc = 1;
30.471 + int n;
30.472 + double r;
30.473 + char *z, zBuf[30];
30.474 + z = zBuf;
30.475 + for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
30.476 + z[n] = tolower(zMod[n]);
30.477 + }
30.478 + z[n] = 0;
30.479 + switch( z[0] ){
30.480 + case 'l': {
30.481 + /* localtime
30.482 + **
30.483 + ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
30.484 + ** show local time.
30.485 + */
30.486 + if( strcmp(z, "localtime")==0 ){
30.487 + computeJD(p);
30.488 + p->rJD += localtimeOffset(p);
30.489 + clearYMD_HMS_TZ(p);
30.490 + rc = 0;
30.491 + }
30.492 + break;
30.493 + }
30.494 + case 'u': {
30.495 + /*
30.496 + ** unixepoch
30.497 + **
30.498 + ** Treat the current value of p->rJD as the number of
30.499 + ** seconds since 1970. Convert to a real julian day number.
30.500 + */
30.501 + if( strcmp(z, "unixepoch")==0 && p->validJD ){
30.502 + p->rJD = p->rJD/86400.0 + 2440587.5;
30.503 + clearYMD_HMS_TZ(p);
30.504 + rc = 0;
30.505 + }else if( strcmp(z, "utc")==0 ){
30.506 + double c1;
30.507 + computeJD(p);
30.508 + c1 = localtimeOffset(p);
30.509 + p->rJD -= c1;
30.510 + clearYMD_HMS_TZ(p);
30.511 + p->rJD += c1 - localtimeOffset(p);
30.512 + rc = 0;
30.513 + }
30.514 + break;
30.515 + }
30.516 + case 'w': {
30.517 + /*
30.518 + ** weekday N
30.519 + **
30.520 + ** Move the date to the same time on the next occurrence of
30.521 + ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
30.522 + ** date is already on the appropriate weekday, this is a no-op.
30.523 + */
30.524 + if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
30.525 + && (n=r)==r && n>=0 && r<7 ){
30.526 + int Z;
30.527 + computeYMD_HMS(p);
30.528 + p->validTZ = 0;
30.529 + p->validJD = 0;
30.530 + computeJD(p);
30.531 + Z = p->rJD + 1.5;
30.532 + Z %= 7;
30.533 + if( Z>n ) Z -= 7;
30.534 + p->rJD += n - Z;
30.535 + clearYMD_HMS_TZ(p);
30.536 + rc = 0;
30.537 + }
30.538 + break;
30.539 + }
30.540 + case 's': {
30.541 + /*
30.542 + ** start of TTTTT
30.543 + **
30.544 + ** Move the date backwards to the beginning of the current day,
30.545 + ** or month or year.
30.546 + */
30.547 + if( strncmp(z, "start of ", 9)!=0 ) break;
30.548 + z += 9;
30.549 + computeYMD(p);
30.550 + p->validHMS = 1;
30.551 + p->h = p->m = 0;
30.552 + p->s = 0.0;
30.553 + p->validTZ = 0;
30.554 + p->validJD = 0;
30.555 + if( strcmp(z,"month")==0 ){
30.556 + p->D = 1;
30.557 + rc = 0;
30.558 + }else if( strcmp(z,"year")==0 ){
30.559 + computeYMD(p);
30.560 + p->M = 1;
30.561 + p->D = 1;
30.562 + rc = 0;
30.563 + }else if( strcmp(z,"day")==0 ){
30.564 + rc = 0;
30.565 + }
30.566 + break;
30.567 + }
30.568 + case '+':
30.569 + case '-':
30.570 + case '0':
30.571 + case '1':
30.572 + case '2':
30.573 + case '3':
30.574 + case '4':
30.575 + case '5':
30.576 + case '6':
30.577 + case '7':
30.578 + case '8':
30.579 + case '9': {
30.580 + n = getValue(z, &r);
30.581 + assert( n>=1 );
30.582 + if( z[n]==':' ){
30.583 + /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
30.584 + ** specified number of hours, minutes, seconds, and fractional seconds
30.585 + ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
30.586 + ** omitted.
30.587 + */
30.588 + const char *z2 = z;
30.589 + DateTime tx;
30.590 + int day;
30.591 + if( !isdigit(*(u8*)z2) ) z2++;
30.592 + memset(&tx, 0, sizeof(tx));
30.593 + if( parseHhMmSs(z2, &tx) ) break;
30.594 + computeJD(&tx);
30.595 + tx.rJD -= 0.5;
30.596 + day = (int)tx.rJD;
30.597 + tx.rJD -= day;
30.598 + if( z[0]=='-' ) tx.rJD = -tx.rJD;
30.599 + computeJD(p);
30.600 + clearYMD_HMS_TZ(p);
30.601 + p->rJD += tx.rJD;
30.602 + rc = 0;
30.603 + break;
30.604 + }
30.605 + z += n;
30.606 + while( isspace(*(u8*)z) ) z++;
30.607 + n = strlen(z);
30.608 + if( n>10 || n<3 ) break;
30.609 + if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
30.610 + computeJD(p);
30.611 + rc = 0;
30.612 + if( n==3 && strcmp(z,"day")==0 ){
30.613 + p->rJD += r;
30.614 + }else if( n==4 && strcmp(z,"hour")==0 ){
30.615 + p->rJD += r/24.0;
30.616 + }else if( n==6 && strcmp(z,"minute")==0 ){
30.617 + p->rJD += r/(24.0*60.0);
30.618 + }else if( n==6 && strcmp(z,"second")==0 ){
30.619 + p->rJD += r/(24.0*60.0*60.0);
30.620 + }else if( n==5 && strcmp(z,"month")==0 ){
30.621 + int x, y;
30.622 + computeYMD_HMS(p);
30.623 + p->M += r;
30.624 + x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
30.625 + p->Y += x;
30.626 + p->M -= x*12;
30.627 + p->validJD = 0;
30.628 + computeJD(p);
30.629 + y = r;
30.630 + if( y!=r ){
30.631 + p->rJD += (r - y)*30.0;
30.632 + }
30.633 + }else if( n==4 && strcmp(z,"year")==0 ){
30.634 + computeYMD_HMS(p);
30.635 + p->Y += r;
30.636 + p->validJD = 0;
30.637 + computeJD(p);
30.638 + }else{
30.639 + rc = 1;
30.640 + }
30.641 + clearYMD_HMS_TZ(p);
30.642 + break;
30.643 + }
30.644 + default: {
30.645 + break;
30.646 + }
30.647 + }
30.648 + return rc;
30.649 +}
30.650 +
30.651 +/*
30.652 +** Process time function arguments. argv[0] is a date-time stamp.
30.653 +** argv[1] and following are modifiers. Parse them all and write
30.654 +** the resulting time into the DateTime structure p. Return 0
30.655 +** on success and 1 if there are any errors.
30.656 +*/
30.657 +static int isDate(int argc, sqlite3_value **argv, DateTime *p){
30.658 + int i;
30.659 + const unsigned char *z;
30.660 + if( argc==0 ) return 1;
30.661 + if( (z = sqlite3_value_text(argv[0]))==0 || parseDateOrTime((char*)z, p) ){
30.662 + return 1;
30.663 + }
30.664 + for(i=1; i<argc; i++){
30.665 + if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
30.666 + return 1;
30.667 + }
30.668 + }
30.669 + return 0;
30.670 +}
30.671 +
30.672 +
30.673 +/*
30.674 +** The following routines implement the various date and time functions
30.675 +** of SQLite.
30.676 +*/
30.677 +
30.678 +/*
30.679 +** julianday( TIMESTRING, MOD, MOD, ...)
30.680 +**
30.681 +** Return the julian day number of the date specified in the arguments
30.682 +*/
30.683 +static void juliandayFunc(
30.684 + sqlite3_context *context,
30.685 + int argc,
30.686 + sqlite3_value **argv
30.687 +){
30.688 + DateTime x;
30.689 + if( isDate(argc, argv, &x)==0 ){
30.690 + computeJD(&x);
30.691 + sqlite3_result_double(context, x.rJD);
30.692 + }
30.693 +}
30.694 +
30.695 +/*
30.696 +** datetime( TIMESTRING, MOD, MOD, ...)
30.697 +**
30.698 +** Return YYYY-MM-DD HH:MM:SS
30.699 +*/
30.700 +static void datetimeFunc(
30.701 + sqlite3_context *context,
30.702 + int argc,
30.703 + sqlite3_value **argv
30.704 +){
30.705 + DateTime x;
30.706 + if( isDate(argc, argv, &x)==0 ){
30.707 + char zBuf[100];
30.708 + computeYMD_HMS(&x);
30.709 + sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
30.710 + x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
30.711 + sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
30.712 + }
30.713 +}
30.714 +
30.715 +/*
30.716 +** time( TIMESTRING, MOD, MOD, ...)
30.717 +**
30.718 +** Return HH:MM:SS
30.719 +*/
30.720 +static void timeFunc(
30.721 + sqlite3_context *context,
30.722 + int argc,
30.723 + sqlite3_value **argv
30.724 +){
30.725 + DateTime x;
30.726 + if( isDate(argc, argv, &x)==0 ){
30.727 + char zBuf[100];
30.728 + computeHMS(&x);
30.729 + sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
30.730 + sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
30.731 + }
30.732 +}
30.733 +
30.734 +/*
30.735 +** date( TIMESTRING, MOD, MOD, ...)
30.736 +**
30.737 +** Return YYYY-MM-DD
30.738 +*/
30.739 +static void dateFunc(
30.740 + sqlite3_context *context,
30.741 + int argc,
30.742 + sqlite3_value **argv
30.743 +){
30.744 + DateTime x;
30.745 + if( isDate(argc, argv, &x)==0 ){
30.746 + char zBuf[100];
30.747 + computeYMD(&x);
30.748 + sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
30.749 + sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
30.750 + }
30.751 +}
30.752 +
30.753 +/*
30.754 +** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
30.755 +**
30.756 +** Return a string described by FORMAT. Conversions as follows:
30.757 +**
30.758 +** %d day of month
30.759 +** %f ** fractional seconds SS.SSS
30.760 +** %H hour 00-24
30.761 +** %j day of year 000-366
30.762 +** %J ** Julian day number
30.763 +** %m month 01-12
30.764 +** %M minute 00-59
30.765 +** %s seconds since 1970-01-01
30.766 +** %S seconds 00-59
30.767 +** %w day of week 0-6 sunday==0
30.768 +** %W week of year 00-53
30.769 +** %Y year 0000-9999
30.770 +** %% %
30.771 +*/
30.772 +static void strftimeFunc(
30.773 + sqlite3_context *context,
30.774 + int argc,
30.775 + sqlite3_value **argv
30.776 +){
30.777 + DateTime x;
30.778 + u64 n;
30.779 + int i, j;
30.780 + char *z;
30.781 + const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
30.782 + char zBuf[100];
30.783 + if( zFmt==0 || isDate(argc-1, argv+1, &x) ) return;
30.784 + for(i=0, n=1; zFmt[i]; i++, n++){
30.785 + if( zFmt[i]=='%' ){
30.786 + switch( zFmt[i+1] ){
30.787 + case 'd':
30.788 + case 'H':
30.789 + case 'm':
30.790 + case 'M':
30.791 + case 'S':
30.792 + case 'W':
30.793 + n++;
30.794 + /* fall thru */
30.795 + case 'w':
30.796 + case '%':
30.797 + break;
30.798 + case 'f':
30.799 + n += 8;
30.800 + break;
30.801 + case 'j':
30.802 + n += 3;
30.803 + break;
30.804 + case 'Y':
30.805 + n += 8;
30.806 + break;
30.807 + case 's':
30.808 + case 'J':
30.809 + n += 50;
30.810 + break;
30.811 + default:
30.812 + return; /* ERROR. return a NULL */
30.813 + }
30.814 + i++;
30.815 + }
30.816 + }
30.817 + if( n<sizeof(zBuf) ){
30.818 + z = zBuf;
30.819 + }else if( n>SQLITE_MAX_LENGTH ){
30.820 + sqlite3_result_error_toobig(context);
30.821 + return;
30.822 + }else{
30.823 + z = sqliteMalloc( n );
30.824 + if( z==0 ) return;
30.825 + }
30.826 + computeJD(&x);
30.827 + computeYMD_HMS(&x);
30.828 + for(i=j=0; zFmt[i]; i++){
30.829 + if( zFmt[i]!='%' ){
30.830 + z[j++] = zFmt[i];
30.831 + }else{
30.832 + i++;
30.833 + switch( zFmt[i] ){
30.834 + case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
30.835 + case 'f': {
30.836 + double s = x.s;
30.837 + if( s>59.999 ) s = 59.999;
30.838 + sqlite3_snprintf(7, &z[j],"%06.3f", s);
30.839 + j += strlen(&z[j]);
30.840 + break;
30.841 + }
30.842 + case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
30.843 + case 'W': /* Fall thru */
30.844 + case 'j': {
30.845 + int nDay; /* Number of days since 1st day of year */
30.846 + DateTime y = x;
30.847 + y.validJD = 0;
30.848 + y.M = 1;
30.849 + y.D = 1;
30.850 + computeJD(&y);
30.851 + nDay = x.rJD - y.rJD + 0.5;
30.852 + if( zFmt[i]=='W' ){
30.853 + int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
30.854 + wd = ((int)(x.rJD+0.5)) % 7;
30.855 + sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
30.856 + j += 2;
30.857 + }else{
30.858 + sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
30.859 + j += 3;
30.860 + }
30.861 + break;
30.862 + }
30.863 + case 'J': {
30.864 + sqlite3_snprintf(20, &z[j],"%.16g",x.rJD);
30.865 + j+=strlen(&z[j]);
30.866 + break;
30.867 + }
30.868 + case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
30.869 + case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
30.870 + case 's': {
30.871 + sqlite3_snprintf(30,&z[j],"%d",
30.872 + (int)((x.rJD-2440587.5)*86400.0 + 0.5));
30.873 + j += strlen(&z[j]);
30.874 + break;
30.875 + }
30.876 + case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
30.877 + case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
30.878 + case 'Y': sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=strlen(&z[j]);break;
30.879 + case '%': z[j++] = '%'; break;
30.880 + }
30.881 + }
30.882 + }
30.883 + z[j] = 0;
30.884 + sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
30.885 + if( z!=zBuf ){
30.886 + sqliteFree(z);
30.887 + }
30.888 +}
30.889 +
30.890 +/*
30.891 +** current_time()
30.892 +**
30.893 +** This function returns the same value as time('now').
30.894 +*/
30.895 +static void ctimeFunc(
30.896 + sqlite3_context *context,
30.897 + int argc,
30.898 + sqlite3_value **argv
30.899 +){
30.900 + sqlite3_value *pVal = sqlite3ValueNew();
30.901 + if( pVal ){
30.902 + sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
30.903 + timeFunc(context, 1, &pVal);
30.904 + sqlite3ValueFree(pVal);
30.905 + }
30.906 +}
30.907 +
30.908 +/*
30.909 +** current_date()
30.910 +**
30.911 +** This function returns the same value as date('now').
30.912 +*/
30.913 +static void cdateFunc(
30.914 + sqlite3_context *context,
30.915 + int argc,
30.916 + sqlite3_value **argv
30.917 +){
30.918 + sqlite3_value *pVal = sqlite3ValueNew();
30.919 + if( pVal ){
30.920 + sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
30.921 + dateFunc(context, 1, &pVal);
30.922 + sqlite3ValueFree(pVal);
30.923 + }
30.924 +}
30.925 +
30.926 +/*
30.927 +** current_timestamp()
30.928 +**
30.929 +** This function returns the same value as datetime('now').
30.930 +*/
30.931 +static void ctimestampFunc(
30.932 + sqlite3_context *context,
30.933 + int argc,
30.934 + sqlite3_value **argv
30.935 +){
30.936 + sqlite3_value *pVal = sqlite3ValueNew();
30.937 + if( pVal ){
30.938 + sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
30.939 + datetimeFunc(context, 1, &pVal);
30.940 + sqlite3ValueFree(pVal);
30.941 + }
30.942 +}
30.943 +#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
30.944 +
30.945 +#ifdef SQLITE_OMIT_DATETIME_FUNCS
30.946 +/*
30.947 +** If the library is compiled to omit the full-scale date and time
30.948 +** handling (to get a smaller binary), the following minimal version
30.949 +** of the functions current_time(), current_date() and current_timestamp()
30.950 +** are included instead. This is to support column declarations that
30.951 +** include "DEFAULT CURRENT_TIME" etc.
30.952 +**
30.953 +** This function uses the C-library functions time(), gmtime()
30.954 +** and strftime(). The format string to pass to strftime() is supplied
30.955 +** as the user-data for the function.
30.956 +*/
30.957 +static void currentTimeFunc(
30.958 + sqlite3_context *context,
30.959 + int argc,
30.960 + sqlite3_value **argv
30.961 +){
30.962 + time_t t;
30.963 + char *zFormat = (char *)sqlite3_user_data(context);
30.964 + char zBuf[20];
30.965 +
30.966 + time(&t);
30.967 +#ifdef SQLITE_TEST
30.968 + {
30.969 + extern int sqlite3_current_time; /* See os_XXX.c */
30.970 + if( sqlite3_current_time ){
30.971 + t = sqlite3_current_time;
30.972 + }
30.973 + }
30.974 +#endif
30.975 +
30.976 +#ifdef HAVE_GMTIME_R
30.977 + {
30.978 + struct tm sNow;
30.979 + gmtime_r(&t, &sNow);
30.980 + strftime(zBuf, 20, zFormat, &sNow);
30.981 + }
30.982 +#else
30.983 + {
30.984 + struct tm *pTm;
30.985 + sqlite3OsEnterMutex();
30.986 + pTm = gmtime(&t);
30.987 + strftime(zBuf, 20, zFormat, pTm);
30.988 + sqlite3OsLeaveMutex();
30.989 + }
30.990 +#endif
30.991 +
30.992 + sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
30.993 +}
30.994 +#endif
30.995 +
30.996 +/*
30.997 +** This function registered all of the above C functions as SQL
30.998 +** functions. This should be the only routine in this file with
30.999 +** external linkage.
30.1000 +*/
30.1001 +void sqlite3RegisterDateTimeFunctions(sqlite3 *db){
30.1002 +#ifndef SQLITE_OMIT_DATETIME_FUNCS
30.1003 + static const struct {
30.1004 + char *zName;
30.1005 + int nArg;
30.1006 + void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
30.1007 + } aFuncs[] = {
30.1008 + { "julianday", -1, juliandayFunc },
30.1009 + { "date", -1, dateFunc },
30.1010 + { "time", -1, timeFunc },
30.1011 + { "datetime", -1, datetimeFunc },
30.1012 + { "strftime", -1, strftimeFunc },
30.1013 + { "current_time", 0, ctimeFunc },
30.1014 + { "current_timestamp", 0, ctimestampFunc },
30.1015 + { "current_date", 0, cdateFunc },
30.1016 + };
30.1017 + int i;
30.1018 +
30.1019 + for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
30.1020 + sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
30.1021 + SQLITE_UTF8, 0, aFuncs[i].xFunc, 0, 0);
30.1022 + }
30.1023 +#else
30.1024 + static const struct {
30.1025 + char *zName;
30.1026 + char *zFormat;
30.1027 + } aFuncs[] = {
30.1028 + { "current_time", "%H:%M:%S" },
30.1029 + { "current_date", "%Y-%m-%d" },
30.1030 + { "current_timestamp", "%Y-%m-%d %H:%M:%S" }
30.1031 + };
30.1032 + int i;
30.1033 +
30.1034 + for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
30.1035 + sqlite3CreateFunc(db, aFuncs[i].zName, 0, SQLITE_UTF8,
30.1036 + aFuncs[i].zFormat, currentTimeFunc, 0, 0);
30.1037 + }
30.1038 +#endif
30.1039 +}
31.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
31.2 +++ b/extensions/sqlite/sqlite-source/delete.c Sun Jul 29 01:15:31 2007 +0000
31.3 @@ -0,0 +1,467 @@
31.4 +/*
31.5 +** 2001 September 15
31.6 +**
31.7 +** The author disclaims copyright to this source code. In place of
31.8 +** a legal notice, here is a blessing:
31.9 +**
31.10 +** May you do good and not evil.
31.11 +** May you find forgiveness for yourself and forgive others.
31.12 +** May you share freely, never taking more than you give.
31.13 +**
31.14 +*************************************************************************
31.15 +** This file contains C code routines that are called by the parser
31.16 +** in order to generate code for DELETE FROM statements.
31.17 +**
31.18 +** $Id$
31.19 +*/
31.20 +#include "sqliteInt.h"
31.21 +
31.22 +/*
31.23 +** Look up every table that is named in pSrc. If any table is not found,
31.24 +** add an error message to pParse->zErrMsg and return NULL. If all tables
31.25 +** are found, return a pointer to the last table.
31.26 +*/
31.27 +Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
31.28 + Table *pTab = 0;
31.29 + int i;
31.30 + struct SrcList_item *pItem;
31.31 + for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
31.32 + pTab = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
31.33 + sqlite3DeleteTable(pItem->pTab);
31.34 + pItem->pTab = pTab;
31.35 + if( pTab ){
31.36 + pTab->nRef++;
31.37 + }
31.38 + }
31.39 + return pTab;
31.40 +}
31.41 +
31.42 +/*
31.43 +** Check to make sure the given table is writable. If it is not
31.44 +** writable, generate an error message and return 1. If it is
31.45 +** writable return 0;
31.46 +*/
31.47 +int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
31.48 + if( (pTab->readOnly && (pParse->db->flags & SQLITE_WriteSchema)==0
31.49 + && pParse->nested==0)
31.50 +#ifndef SQLITE_OMIT_VIRTUALTABLE
31.51 + || (pTab->pMod && pTab->pMod->pModule->xUpdate==0)
31.52 +#endif
31.53 + ){
31.54 + sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
31.55 + return 1;
31.56 + }
31.57 +#ifndef SQLITE_OMIT_VIEW
31.58 + if( !viewOk && pTab->pSelect ){
31.59 + sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
31.60 + return 1;
31.61 + }
31.62 +#endif
31.63 + return 0;
31.64 +}
31.65 +
31.66 +/*
31.67 +** Generate code that will open a table for reading.
31.68 +*/
31.69 +void sqlite3OpenTable(
31.70 + Parse *p, /* Generate code into this VDBE */
31.71 + int iCur, /* The cursor number of the table */
31.72 + int iDb, /* The database index in sqlite3.aDb[] */
31.73 + Table *pTab, /* The table to be opened */
31.74 + int opcode /* OP_OpenRead or OP_OpenWrite */
31.75 +){
31.76 + Vdbe *v;
31.77 + if( IsVirtual(pTab) ) return;
31.78 + v = sqlite3GetVdbe(p);
31.79 + assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
31.80 + sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite), pTab->zName);
31.81 + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
31.82 + VdbeComment((v, "# %s", pTab->zName));
31.83 + sqlite3VdbeAddOp(v, opcode, iCur, pTab->tnum);
31.84 + sqlite3VdbeAddOp(v, OP_SetNumColumns, iCur, pTab->nCol);
31.85 +}
31.86 +
31.87 +
31.88 +/*
31.89 +** Generate code for a DELETE FROM statement.
31.90 +**
31.91 +** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
31.92 +** \________/ \________________/
31.93 +** pTabList pWhere
31.94 +*/
31.95 +void sqlite3DeleteFrom(
31.96 + Parse *pParse, /* The parser context */
31.97 + SrcList *pTabList, /* The table from which we should delete things */
31.98 + Expr *pWhere /* The WHERE clause. May be null */
31.99 +){
31.100 + Vdbe *v; /* The virtual database engine */
31.101 + Table *pTab; /* The table from which records will be deleted */
31.102 + const char *zDb; /* Name of database holding pTab */
31.103 + int end, addr = 0; /* A couple addresses of generated code */
31.104 + int i; /* Loop counter */
31.105 + WhereInfo *pWInfo; /* Information about the WHERE clause */
31.106 + Index *pIdx; /* For looping over indices of the table */
31.107 + int iCur; /* VDBE Cursor number for pTab */
31.108 + sqlite3 *db; /* Main database structure */
31.109 + AuthContext sContext; /* Authorization context */
31.110 + int oldIdx = -1; /* Cursor for the OLD table of AFTER triggers */
31.111 + NameContext sNC; /* Name context to resolve expressions in */
31.112 + int iDb; /* Database number */
31.113 + int memCnt = 0; /* Memory cell used for change counting */
31.114 +
31.115 +#ifndef SQLITE_OMIT_TRIGGER
31.116 + int isView; /* True if attempting to delete from a view */
31.117 + int triggers_exist = 0; /* True if any triggers exist */
31.118 +#endif
31.119 +
31.120 + sContext.pParse = 0;
31.121 + if( pParse->nErr || sqlite3MallocFailed() ){
31.122 + goto delete_from_cleanup;
31.123 + }
31.124 + db = pParse->db;
31.125 + assert( pTabList->nSrc==1 );
31.126 +
31.127 + /* Locate the table which we want to delete. This table has to be
31.128 + ** put in an SrcList structure because some of the subroutines we
31.129 + ** will be calling are designed to work with multiple tables and expect
31.130 + ** an SrcList* parameter instead of just a Table* parameter.
31.131 + */
31.132 + pTab = sqlite3SrcListLookup(pParse, pTabList);
31.133 + if( pTab==0 ) goto delete_from_cleanup;
31.134 +
31.135 + /* Figure out if we have any triggers and if the table being
31.136 + ** deleted from is a view
31.137 + */
31.138 +#ifndef SQLITE_OMIT_TRIGGER
31.139 + triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0);
31.140 + isView = pTab->pSelect!=0;
31.141 +#else
31.142 +# define triggers_exist 0
31.143 +# define isView 0
31.144 +#endif
31.145 +#ifdef SQLITE_OMIT_VIEW
31.146 +# undef isView
31.147 +# define isView 0
31.148 +#endif
31.149 +
31.150 + if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
31.151 + goto delete_from_cleanup;
31.152 + }
31.153 + iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
31.154 + assert( iDb<db->nDb );
31.155 + zDb = db->aDb[iDb].zName;
31.156 + if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
31.157 + goto delete_from_cleanup;
31.158 + }
31.159 +
31.160 + /* If pTab is really a view, make sure it has been initialized.
31.161 + */
31.162 + if( sqlite3ViewGetColumnNames(pParse, pTab) ){
31.163 + goto delete_from_cleanup;
31.164 + }
31.165 +
31.166 + /* Allocate a cursor used to store the old.* data for a trigger.
31.167 + */
31.168 + if( triggers_exist ){
31.169 + oldIdx = pParse->nTab++;
31.170 + }
31.171 +
31.172 + /* Resolve the column names in the WHERE clause.
31.173 + */
31.174 + assert( pTabList->nSrc==1 );
31.175 + iCur = pTabList->a[0].iCursor = pParse->nTab++;
31.176 + memset(&sNC, 0, sizeof(sNC));
31.177 + sNC.pParse = pParse;
31.178 + sNC.pSrcList = pTabList;
31.179 + if( sqlite3ExprResolveNames(&sNC, pWhere) ){
31.180 + goto delete_from_cleanup;
31.181 + }
31.182 +
31.183 + /* Start the view context
31.184 + */
31.185 + if( isView ){
31.186 + sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
31.187 + }
31.188 +
31.189 + /* Begin generating code.
31.190 + */
31.191 + v = sqlite3GetVdbe(pParse);
31.192 + if( v==0 ){
31.193 + goto delete_from_cleanup;
31.194 + }
31.195 + if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
31.196 + sqlite3BeginWriteOperation(pParse, triggers_exist, iDb);
31.197 +
31.198 + /* If we are trying to delete from a view, realize that view into
31.199 + ** a ephemeral table.
31.200 + */
31.201 + if( isView ){
31.202 + Select *pView = sqlite3SelectDup(pTab->pSelect);
31.203 + sqlite3Select(pParse, pView, SRT_EphemTab, iCur, 0, 0, 0, 0);
31.204 + sqlite3SelectDelete(pView);
31.205 + }
31.206 +
31.207 + /* Initialize the counter of the number of rows deleted, if
31.208 + ** we are counting rows.
31.209 + */
31.210 + if( db->flags & SQLITE_CountRows ){
31.211 + memCnt = pParse->nMem++;
31.212 + sqlite3VdbeAddOp(v, OP_MemInt, 0, memCnt);
31.213 + }
31.214 +
31.215 + /* Special case: A DELETE without a WHERE clause deletes everything.
31.216 + ** It is easier just to erase the whole table. Note, however, that
31.217 + ** this means that the row change count will be incorrect.
31.218 + */
31.219 + if( pWhere==0 && !triggers_exist && !IsVirtual(pTab) ){
31.220 + if( db->flags & SQLITE_CountRows ){
31.221 + /* If counting rows deleted, just count the total number of
31.222 + ** entries in the table. */
31.223 + int endOfLoop = sqlite3VdbeMakeLabel(v);
31.224 + int addr2;
31.225 + if( !isView ){
31.226 + sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
31.227 + }
31.228 + sqlite3VdbeAddOp(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2);
31.229 + addr2 = sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt);
31.230 + sqlite3VdbeAddOp(v, OP_Next, iCur, addr2);
31.231 + sqlite3VdbeResolveLabel(v, endOfLoop);
31.232 + sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
31.233 + }
31.234 + if( !isView ){
31.235 + sqlite3VdbeAddOp(v, OP_Clear, pTab->tnum, iDb);
31.236 + if( !pParse->nested ){
31.237 + sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
31.238 + }
31.239 + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
31.240 + assert( pIdx->pSchema==pTab->pSchema );
31.241 + sqlite3VdbeAddOp(v, OP_Clear, pIdx->tnum, iDb);
31.242 + }
31.243 + }
31.244 + }
31.245 + /* The usual case: There is a WHERE clause so we have to scan through
31.246 + ** the table and pick which records to delete.
31.247 + */
31.248 + else{
31.249 + /* Begin the database scan
31.250 + */
31.251 + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
31.252 + if( pWInfo==0 ) goto delete_from_cleanup;
31.253 +
31.254 + /* Remember the rowid of every item to be deleted.
31.255 + */
31.256 + sqlite3VdbeAddOp(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, 0);
31.257 + sqlite3VdbeAddOp(v, OP_FifoWrite, 0, 0);
31.258 + if( db->flags & SQLITE_CountRows ){
31.259 + sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt);
31.260 + }
31.261 +
31.262 + /* End the database scan loop.
31.263 + */
31.264 + sqlite3WhereEnd(pWInfo);
31.265 +
31.266 + /* Open the pseudo-table used to store OLD if there are triggers.
31.267 + */
31.268 + if( triggers_exist ){
31.269 + sqlite3VdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
31.270 + sqlite3VdbeAddOp(v, OP_SetNumColumns, oldIdx, pTab->nCol);
31.271 + }
31.272 +
31.273 + /* Delete every item whose key was written to the list during the
31.274 + ** database scan. We have to delete items after the scan is complete
31.275 + ** because deleting an item can change the scan order.
31.276 + */
31.277 + end = sqlite3VdbeMakeLabel(v);
31.278 +
31.279 + /* This is the beginning of the delete loop when there are
31.280 + ** row triggers.
31.281 + */
31.282 + if( triggers_exist ){
31.283 + addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, end);
31.284 + if( !isView ){
31.285 + sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
31.286 + sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
31.287 + }
31.288 + sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
31.289 + sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
31.290 + sqlite3VdbeAddOp(v, OP_RowData, iCur, 0);
31.291 + sqlite3VdbeAddOp(v, OP_Insert, oldIdx, 0);
31.292 + if( !isView ){
31.293 + sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
31.294 + }
31.295 +
31.296 + (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab,
31.297 + -1, oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
31.298 + addr);
31.299 + }
31.300 +
31.301 + if( !isView ){
31.302 + /* Open cursors for the table we are deleting from and all its
31.303 + ** indices. If there are row triggers, this happens inside the
31.304 + ** OP_FifoRead loop because the cursor have to all be closed
31.305 + ** before the trigger fires. If there are no row triggers, the
31.306 + ** cursors are opened only once on the outside the loop.
31.307 + */
31.308 + sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
31.309 +
31.310 + /* This is the beginning of the delete loop when there are no
31.311 + ** row triggers */
31.312 + if( !triggers_exist ){
31.313 + addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, end);
31.314 + }
31.315 +
31.316 + /* Delete the row */
31.317 +#ifndef SQLITE_OMIT_VIRTUALTABLE
31.318 + if( IsVirtual(pTab) ){
31.319 + pParse->pVirtualLock = pTab;
31.320 + sqlite3VdbeOp3(v, OP_VUpdate, 0, 1, (const char*)pTab->pVtab, P3_VTAB);
31.321 + }else
31.322 +#endif
31.323 + {
31.324 + sqlite3GenerateRowDelete(db, v, pTab, iCur, pParse->nested==0);
31.325 + }
31.326 + }
31.327 +
31.328 + /* If there are row triggers, close all cursors then invoke
31.329 + ** the AFTER triggers
31.330 + */
31.331 + if( triggers_exist ){
31.332 + if( !isView ){
31.333 + for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
31.334 + sqlite3VdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
31.335 + }
31.336 + sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
31.337 + }
31.338 + (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1,
31.339 + oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
31.340 + addr);
31.341 + }
31.342 +
31.343 + /* End of the delete loop */
31.344 + sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
31.345 + sqlite3VdbeResolveLabel(v, end);
31.346 +
31.347 + /* Close the cursors after the loop if there are no row triggers */
31.348 + if( !triggers_exist && !IsVirtual(pTab) ){
31.349 + for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
31.350 + sqlite3VdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
31.351 + }
31.352 + sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
31.353 + }
31.354 + }
31.355 +
31.356 + /*
31.357 + ** Return the number of rows that were deleted. If this routine is
31.358 + ** generating code because of a call to sqlite3NestedParse(), do not
31.359 + ** invoke the callback function.
31.360 + */
31.361 + if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
31.362 + sqlite3VdbeAddOp(v, OP_MemLoad, memCnt, 0);
31.363 + sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
31.364 + sqlite3VdbeSetNumCols(v, 1);
31.365 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", P3_STATIC);
31.366 + }
31.367 +
31.368 +delete_from_cleanup:
31.369 + sqlite3AuthContextPop(&sContext);
31.370 + sqlite3SrcListDelete(pTabList);
31.371 + sqlite3ExprDelete(pWhere);
31.372 + return;
31.373 +}
31.374 +
31.375 +/*
31.376 +** This routine generates VDBE code that causes a single row of a
31.377 +** single table to be deleted.
31.378 +**
31.379 +** The VDBE must be in a particular state when this routine is called.
31.380 +** These are the requirements:
31.381 +**
31.382 +** 1. A read/write cursor pointing to pTab, the table containing the row
31.383 +** to be deleted, must be opened as cursor number "base".
31.384 +**
31.385 +** 2. Read/write cursors for all indices of pTab must be open as
31.386 +** cursor number base+i for the i-th index.
31.387 +**
31.388 +** 3. The record number of the row to be deleted must be on the top
31.389 +** of the stack.
31.390 +**
31.391 +** This routine pops the top of the stack to remove the record number
31.392 +** and then generates code to remove both the table record and all index
31.393 +** entries that point to that record.
31.394 +*/
31.395 +void sqlite3GenerateRowDelete(
31.396 + sqlite3 *db, /* The database containing the index */
31.397 + Vdbe *v, /* Generate code into this VDBE */
31.398 + Table *pTab, /* Table containing the row to be deleted */
31.399 + int iCur, /* Cursor number for the table */
31.400 + int count /* Increment the row change counter */
31.401 +){
31.402 + int addr;
31.403 + addr = sqlite3VdbeAddOp(v, OP_NotExists, iCur, 0);
31.404 + sqlite3GenerateRowIndexDelete(v, pTab, iCur, 0);
31.405 + sqlite3VdbeAddOp(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
31.406 + if( count ){
31.407 + sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
31.408 + }
31.409 + sqlite3VdbeJumpHere(v, addr);
31.410 +}
31.411 +
31.412 +/*
31.413 +** This routine generates VDBE code that causes the deletion of all
31.414 +** index entries associated with a single row of a single table.
31.415 +**
31.416 +** The VDBE must be in a particular state when this routine is called.
31.417 +** These are the requirements:
31.418 +**
31.419 +** 1. A read/write cursor pointing to pTab, the table containing the row
31.420 +** to be deleted, must be opened as cursor number "iCur".
31.421 +**
31.422 +** 2. Read/write cursors for all indices of pTab must be open as
31.423 +** cursor number iCur+i for the i-th index.
31.424 +**
31.425 +** 3. The "iCur" cursor must be pointing to the row that is to be
31.426 +** deleted.
31.427 +*/
31.428 +void sqlite3GenerateRowIndexDelete(
31.429 + Vdbe *v, /* Generate code into this VDBE */
31.430 + Table *pTab, /* Table containing the row to be deleted */
31.431 + int iCur, /* Cursor number for the table */
31.432 + char *aIdxUsed /* Only delete if aIdxUsed!=0 && aIdxUsed[i]!=0 */
31.433 +){
31.434 + int i;
31.435 + Index *pIdx;
31.436 +
31.437 + for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
31.438 + if( aIdxUsed!=0 && aIdxUsed[i-1]==0 ) continue;
31.439 + sqlite3GenerateIndexKey(v, pIdx, iCur);
31.440 + sqlite3VdbeAddOp(v, OP_IdxDelete, iCur+i, 0);
31.441 + }
31.442 +}
31.443 +
31.444 +/*
31.445 +** Generate code that will assemble an index key and put it on the top
31.446 +** of the tack. The key with be for index pIdx which is an index on pTab.
31.447 +** iCur is the index of a cursor open on the pTab table and pointing to
31.448 +** the entry that needs indexing.
31.449 +*/
31.450 +void sqlite3GenerateIndexKey(
31.451 + Vdbe *v, /* Generate code into this VDBE */
31.452 + Index *pIdx, /* The index for which to generate a key */
31.453 + int iCur /* Cursor number for the pIdx->pTable table */
31.454 +){
31.455 + int j;
31.456 + Table *pTab = pIdx->pTable;
31.457 +
31.458 + sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
31.459 + for(j=0; j<pIdx->nColumn; j++){
31.460 + int idx = pIdx->aiColumn[j];
31.461 + if( idx==pTab->iPKey ){
31.462 + sqlite3VdbeAddOp(v, OP_Dup, j, 0);
31.463 + }else{
31.464 + sqlite3VdbeAddOp(v, OP_Column, iCur, idx);
31.465 + sqlite3ColumnDefault(v, pTab, idx);
31.466 + }
31.467 + }
31.468 + sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
31.469 + sqlite3IndexAffinityStr(v, pIdx);
31.470 +}
32.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
32.2 +++ b/extensions/sqlite/sqlite-source/expr.c Sun Jul 29 01:15:31 2007 +0000
32.3 @@ -0,0 +1,2581 @@
32.4 +/*
32.5 +** 2001 September 15
32.6 +**
32.7 +** The author disclaims copyright to this source code. In place of
32.8 +** a legal notice, here is a blessing:
32.9 +**
32.10 +** May you do good and not evil.
32.11 +** May you find forgiveness for yourself and forgive others.
32.12 +** May you share freely, never taking more than you give.
32.13 +**
32.14 +*************************************************************************
32.15 +** This file contains routines used for analyzing expressions and
32.16 +** for generating VDBE code that evaluates expressions in SQLite.
32.17 +**
32.18 +** $Id$
32.19 +*/
32.20 +#include "sqliteInt.h"
32.21 +#include <ctype.h>
32.22 +
32.23 +/*
32.24 +** Return the 'affinity' of the expression pExpr if any.
32.25 +**
32.26 +** If pExpr is a column, a reference to a column via an 'AS' alias,
32.27 +** or a sub-select with a column as the return value, then the
32.28 +** affinity of that column is returned. Otherwise, 0x00 is returned,
32.29 +** indicating no affinity for the expression.
32.30 +**
32.31 +** i.e. the WHERE clause expresssions in the following statements all
32.32 +** have an affinity:
32.33 +**
32.34 +** CREATE TABLE t1(a);
32.35 +** SELECT * FROM t1 WHERE a;
32.36 +** SELECT a AS b FROM t1 WHERE b;
32.37 +** SELECT * FROM t1 WHERE (select a from t1);
32.38 +*/
32.39 +char sqlite3ExprAffinity(Expr *pExpr){
32.40 + int op = pExpr->op;
32.41 + if( op==TK_SELECT ){
32.42 + return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
32.43 + }
32.44 +#ifndef SQLITE_OMIT_CAST
32.45 + if( op==TK_CAST ){
32.46 + return sqlite3AffinityType(&pExpr->token);
32.47 + }
32.48 +#endif
32.49 + return pExpr->affinity;
32.50 +}
32.51 +
32.52 +/*
32.53 +** Set the collating sequence for expression pExpr to be the collating
32.54 +** sequence named by pToken. Return a pointer to the revised expression.
32.55 +** The collating sequence is marked as "explicit" using the EP_ExpCollate
32.56 +** flag. An explicit collating sequence will override implicit
32.57 +** collating sequences.
32.58 +*/
32.59 +Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
32.60 + CollSeq *pColl;
32.61 + if( pExpr==0 ) return 0;
32.62 + pColl = sqlite3LocateCollSeq(pParse, (char*)pName->z, pName->n);
32.63 + if( pColl ){
32.64 + pExpr->pColl = pColl;
32.65 + pExpr->flags |= EP_ExpCollate;
32.66 + }
32.67 + return pExpr;
32.68 +}
32.69 +
32.70 +/*
32.71 +** Return the default collation sequence for the expression pExpr. If
32.72 +** there is no default collation type, return 0.
32.73 +*/
32.74 +CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
32.75 + CollSeq *pColl = 0;
32.76 + if( pExpr ){
32.77 + int op;
32.78 + pColl = pExpr->pColl;
32.79 + op = pExpr->op;
32.80 + if( (op==TK_CAST || op==TK_UPLUS) && !pColl ){
32.81 + return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
32.82 + }
32.83 + }
32.84 + if( sqlite3CheckCollSeq(pParse, pColl) ){
32.85 + pColl = 0;
32.86 + }
32.87 + return pColl;
32.88 +}
32.89 +
32.90 +/*
32.91 +** pExpr is an operand of a comparison operator. aff2 is the
32.92 +** type affinity of the other operand. This routine returns the
32.93 +** type affinity that should be used for the comparison operator.
32.94 +*/
32.95 +char sqlite3CompareAffinity(Expr *pExpr, char aff2){
32.96 + char aff1 = sqlite3ExprAffinity(pExpr);
32.97 + if( aff1 && aff2 ){
32.98 + /* Both sides of the comparison are columns. If one has numeric
32.99 + ** affinity, use that. Otherwise use no affinity.
32.100 + */
32.101 + if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
32.102 + return SQLITE_AFF_NUMERIC;
32.103 + }else{
32.104 + return SQLITE_AFF_NONE;
32.105 + }
32.106 + }else if( !aff1 && !aff2 ){
32.107 + /* Neither side of the comparison is a column. Compare the
32.108 + ** results directly.
32.109 + */
32.110 + return SQLITE_AFF_NONE;
32.111 + }else{
32.112 + /* One side is a column, the other is not. Use the columns affinity. */
32.113 + assert( aff1==0 || aff2==0 );
32.114 + return (aff1 + aff2);
32.115 + }
32.116 +}
32.117 +
32.118 +/*
32.119 +** pExpr is a comparison operator. Return the type affinity that should
32.120 +** be applied to both operands prior to doing the comparison.
32.121 +*/
32.122 +static char comparisonAffinity(Expr *pExpr){
32.123 + char aff;
32.124 + assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
32.125 + pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
32.126 + pExpr->op==TK_NE );
32.127 + assert( pExpr->pLeft );
32.128 + aff = sqlite3ExprAffinity(pExpr->pLeft);
32.129 + if( pExpr->pRight ){
32.130 + aff = sqlite3CompareAffinity(pExpr->pRight, aff);
32.131 + }
32.132 + else if( pExpr->pSelect ){
32.133 + aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
32.134 + }
32.135 + else if( !aff ){
32.136 + aff = SQLITE_AFF_NONE;
32.137 + }
32.138 + return aff;
32.139 +}
32.140 +
32.141 +/*
32.142 +** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
32.143 +** idx_affinity is the affinity of an indexed column. Return true
32.144 +** if the index with affinity idx_affinity may be used to implement
32.145 +** the comparison in pExpr.
32.146 +*/
32.147 +int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
32.148 + char aff = comparisonAffinity(pExpr);
32.149 + switch( aff ){
32.150 + case SQLITE_AFF_NONE:
32.151 + return 1;
32.152 + case SQLITE_AFF_TEXT:
32.153 + return idx_affinity==SQLITE_AFF_TEXT;
32.154 + default:
32.155 + return sqlite3IsNumericAffinity(idx_affinity);
32.156 + }
32.157 +}
32.158 +
32.159 +/*
32.160 +** Return the P1 value that should be used for a binary comparison
32.161 +** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
32.162 +** If jumpIfNull is true, then set the low byte of the returned
32.163 +** P1 value to tell the opcode to jump if either expression
32.164 +** evaluates to NULL.
32.165 +*/
32.166 +static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
32.167 + char aff = sqlite3ExprAffinity(pExpr2);
32.168 + return ((int)sqlite3CompareAffinity(pExpr1, aff))+(jumpIfNull?0x100:0);
32.169 +}
32.170 +
32.171 +/*
32.172 +** Return a pointer to the collation sequence that should be used by
32.173 +** a binary comparison operator comparing pLeft and pRight.
32.174 +**
32.175 +** If the left hand expression has a collating sequence type, then it is
32.176 +** used. Otherwise the collation sequence for the right hand expression
32.177 +** is used, or the default (BINARY) if neither expression has a collating
32.178 +** type.
32.179 +**
32.180 +** Argument pRight (but not pLeft) may be a null pointer. In this case,
32.181 +** it is not considered.
32.182 +*/
32.183 +CollSeq* sqlite3BinaryCompareCollSeq(
32.184 + Parse *pParse,
32.185 + Expr *pLeft,
32.186 + Expr *pRight
32.187 +){
32.188 + CollSeq *pColl;
32.189 + assert( pLeft );
32.190 + if( pLeft->flags & EP_ExpCollate ){
32.191 + assert( pLeft->pColl );
32.192 + pColl = pLeft->pColl;
32.193 + }else if( pRight && pRight->flags & EP_ExpCollate ){
32.194 + assert( pRight->pColl );
32.195 + pColl = pRight->pColl;
32.196 + }else{
32.197 + pColl = sqlite3ExprCollSeq(pParse, pLeft);
32.198 + if( !pColl ){
32.199 + pColl = sqlite3ExprCollSeq(pParse, pRight);
32.200 + }
32.201 + }
32.202 + return pColl;
32.203 +}
32.204 +
32.205 +/*
32.206 +** Generate code for a comparison operator.
32.207 +*/
32.208 +static int codeCompare(
32.209 + Parse *pParse, /* The parsing (and code generating) context */
32.210 + Expr *pLeft, /* The left operand */
32.211 + Expr *pRight, /* The right operand */
32.212 + int opcode, /* The comparison opcode */
32.213 + int dest, /* Jump here if true. */
32.214 + int jumpIfNull /* If true, jump if either operand is NULL */
32.215 +){
32.216 + int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull);
32.217 + CollSeq *p3 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
32.218 + return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void*)p3, P3_COLLSEQ);
32.219 +}
32.220 +
32.221 +/*
32.222 +** Construct a new expression node and return a pointer to it. Memory
32.223 +** for this node is obtained from sqliteMalloc(). The calling function
32.224 +** is responsible for making sure the node eventually gets freed.
32.225 +*/
32.226 +Expr *sqlite3Expr(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
32.227 + Expr *pNew;
32.228 + pNew = sqliteMalloc( sizeof(Expr) );
32.229 + if( pNew==0 ){
32.230 + /* When malloc fails, delete pLeft and pRight. Expressions passed to
32.231 + ** this function must always be allocated with sqlite3Expr() for this
32.232 + ** reason.
32.233 + */
32.234 + sqlite3ExprDelete(pLeft);
32.235 + sqlite3ExprDelete(pRight);
32.236 + return 0;
32.237 + }
32.238 + pNew->op = op;
32.239 + pNew->pLeft = pLeft;
32.240 + pNew->pRight = pRight;
32.241 + pNew->iAgg = -1;
32.242 + if( pToken ){
32.243 + assert( pToken->dyn==0 );
32.244 + pNew->span = pNew->token = *pToken;
32.245 + }else if( pLeft ){
32.246 + if( pRight ){
32.247 + sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
32.248 + if( pRight->flags & EP_ExpCollate ){
32.249 + pNew->flags |= EP_ExpCollate;
32.250 + pNew->pColl = pRight->pColl;
32.251 + }
32.252 + }
32.253 + if( pLeft->flags & EP_ExpCollate ){
32.254 + pNew->flags |= EP_ExpCollate;
32.255 + pNew->pColl = pLeft->pColl;
32.256 + }
32.257 + }
32.258 +
32.259 + sqlite3ExprSetHeight(pNew);
32.260 + return pNew;
32.261 +}
32.262 +
32.263 +/*
32.264 +** Works like sqlite3Expr() but frees its pLeft and pRight arguments
32.265 +** if it fails due to a malloc problem.
32.266 +*/
32.267 +Expr *sqlite3ExprOrFree(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
32.268 + Expr *pNew = sqlite3Expr(op, pLeft, pRight, pToken);
32.269 + if( pNew==0 ){
32.270 + sqlite3ExprDelete(pLeft);
32.271 + sqlite3ExprDelete(pRight);
32.272 + }
32.273 + return pNew;
32.274 +}
32.275 +
32.276 +/*
32.277 +** When doing a nested parse, you can include terms in an expression
32.278 +** that look like this: #0 #1 #2 ... These terms refer to elements
32.279 +** on the stack. "#0" means the top of the stack.
32.280 +** "#1" means the next down on the stack. And so forth.
32.281 +**
32.282 +** This routine is called by the parser to deal with on of those terms.
32.283 +** It immediately generates code to store the value in a memory location.
32.284 +** The returns an expression that will code to extract the value from
32.285 +** that memory location as needed.
32.286 +*/
32.287 +Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
32.288 + Vdbe *v = pParse->pVdbe;
32.289 + Expr *p;
32.290 + int depth;
32.291 + if( pParse->nested==0 ){
32.292 + sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
32.293 + return sqlite3Expr(TK_NULL, 0, 0, 0);
32.294 + }
32.295 + if( v==0 ) return 0;
32.296 + p = sqlite3Expr(TK_REGISTER, 0, 0, pToken);
32.297 + if( p==0 ){
32.298 + return 0; /* Malloc failed */
32.299 + }
32.300 + depth = atoi((char*)&pToken->z[1]);
32.301 + p->iTable = pParse->nMem++;
32.302 + sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
32.303 + sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
32.304 + return p;
32.305 +}
32.306 +
32.307 +/*
32.308 +** Join two expressions using an AND operator. If either expression is
32.309 +** NULL, then just return the other expression.
32.310 +*/
32.311 +Expr *sqlite3ExprAnd(Expr *pLeft, Expr *pRight){
32.312 + if( pLeft==0 ){
32.313 + return pRight;
32.314 + }else if( pRight==0 ){
32.315 + return pLeft;
32.316 + }else{
32.317 + return sqlite3Expr(TK_AND, pLeft, pRight, 0);
32.318 + }
32.319 +}
32.320 +
32.321 +/*
32.322 +** Set the Expr.span field of the given expression to span all
32.323 +** text between the two given tokens.
32.324 +*/
32.325 +void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
32.326 + assert( pRight!=0 );
32.327 + assert( pLeft!=0 );
32.328 + if( !sqlite3MallocFailed() && pRight->z && pLeft->z ){
32.329 + assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
32.330 + if( pLeft->dyn==0 && pRight->dyn==0 ){
32.331 + pExpr->span.z = pLeft->z;
32.332 + pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
32.333 + }else{
32.334 + pExpr->span.z = 0;
32.335 + }
32.336 + }
32.337 +}
32.338 +
32.339 +/*
32.340 +** Construct a new expression node for a function with multiple
32.341 +** arguments.
32.342 +*/
32.343 +Expr *sqlite3ExprFunction(ExprList *pList, Token *pToken){
32.344 + Expr *pNew;
32.345 + assert( pToken );
32.346 + pNew = sqliteMalloc( sizeof(Expr) );
32.347 + if( pNew==0 ){
32.348 + sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
32.349 + return 0;
32.350 + }
32.351 + pNew->op = TK_FUNCTION;
32.352 + pNew->pList = pList;
32.353 + assert( pToken->dyn==0 );
32.354 + pNew->token = *pToken;
32.355 + pNew->span = pNew->token;
32.356 +
32.357 + sqlite3ExprSetHeight(pNew);
32.358 + return pNew;
32.359 +}
32.360 +
32.361 +/*
32.362 +** Assign a variable number to an expression that encodes a wildcard
32.363 +** in the original SQL statement.
32.364 +**
32.365 +** Wildcards consisting of a single "?" are assigned the next sequential
32.366 +** variable number.
32.367 +**
32.368 +** Wildcards of the form "?nnn" are assigned the number "nnn". We make
32.369 +** sure "nnn" is not too be to avoid a denial of service attack when
32.370 +** the SQL statement comes from an external source.
32.371 +**
32.372 +** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
32.373 +** as the previous instance of the same wildcard. Or if this is the first
32.374 +** instance of the wildcard, the next sequenial variable number is
32.375 +** assigned.
32.376 +*/
32.377 +void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
32.378 + Token *pToken;
32.379 + if( pExpr==0 ) return;
32.380 + pToken = &pExpr->token;
32.381 + assert( pToken->n>=1 );
32.382 + assert( pToken->z!=0 );
32.383 + assert( pToken->z[0]!=0 );
32.384 + if( pToken->n==1 ){
32.385 + /* Wildcard of the form "?". Assign the next variable number */
32.386 + pExpr->iTable = ++pParse->nVar;
32.387 + }else if( pToken->z[0]=='?' ){
32.388 + /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
32.389 + ** use it as the variable number */
32.390 + int i;
32.391 + pExpr->iTable = i = atoi((char*)&pToken->z[1]);
32.392 + if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
32.393 + sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
32.394 + SQLITE_MAX_VARIABLE_NUMBER);
32.395 + }
32.396 + if( i>pParse->nVar ){
32.397 + pParse->nVar = i;
32.398 + }
32.399 + }else{
32.400 + /* Wildcards of the form ":aaa" or "$aaa". Reuse the same variable
32.401 + ** number as the prior appearance of the same name, or if the name
32.402 + ** has never appeared before, reuse the same variable number
32.403 + */
32.404 + int i, n;
32.405 + n = pToken->n;
32.406 + for(i=0; i<pParse->nVarExpr; i++){
32.407 + Expr *pE;
32.408 + if( (pE = pParse->apVarExpr[i])!=0
32.409 + && pE->token.n==n
32.410 + && memcmp(pE->token.z, pToken->z, n)==0 ){
32.411 + pExpr->iTable = pE->iTable;
32.412 + break;
32.413 + }
32.414 + }
32.415 + if( i>=pParse->nVarExpr ){
32.416 + pExpr->iTable = ++pParse->nVar;
32.417 + if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
32.418 + pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
32.419 + pParse->apVarExpr = sqliteReallocOrFree(pParse->apVarExpr,
32.420 + pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) );
32.421 + }
32.422 + if( !sqlite3MallocFailed() ){
32.423 + assert( pParse->apVarExpr!=0 );
32.424 + pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
32.425 + }
32.426 + }
32.427 + }
32.428 + if( !pParse->nErr && pParse->nVar>SQLITE_MAX_VARIABLE_NUMBER ){
32.429 + sqlite3ErrorMsg(pParse, "too many SQL variables");
32.430 + }
32.431 +}
32.432 +
32.433 +/*
32.434 +** Recursively delete an expression tree.
32.435 +*/
32.436 +void sqlite3ExprDelete(Expr *p){
32.437 + if( p==0 ) return;
32.438 + if( p->span.dyn ) sqliteFree((char*)p->span.z);
32.439 + if( p->token.dyn ) sqliteFree((char*)p->token.z);
32.440 + sqlite3ExprDelete(p->pLeft);
32.441 + sqlite3ExprDelete(p->pRight);
32.442 + sqlite3ExprListDelete(p->pList);
32.443 + sqlite3SelectDelete(p->pSelect);
32.444 + sqliteFree(p);
32.445 +}
32.446 +
32.447 +/*
32.448 +** The Expr.token field might be a string literal that is quoted.
32.449 +** If so, remove the quotation marks.
32.450 +*/
32.451 +void sqlite3DequoteExpr(Expr *p){
32.452 + if( ExprHasAnyProperty(p, EP_Dequoted) ){
32.453 + return;
32.454 + }
32.455 + ExprSetProperty(p, EP_Dequoted);
32.456 + if( p->token.dyn==0 ){
32.457 + sqlite3TokenCopy(&p->token, &p->token);
32.458 + }
32.459 + sqlite3Dequote((char*)p->token.z);
32.460 +}
32.461 +
32.462 +
32.463 +/*
32.464 +** The following group of routines make deep copies of expressions,
32.465 +** expression lists, ID lists, and select statements. The copies can
32.466 +** be deleted (by being passed to their respective ...Delete() routines)
32.467 +** without effecting the originals.
32.468 +**
32.469 +** The expression list, ID, and source lists return by sqlite3ExprListDup(),
32.470 +** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
32.471 +** by subsequent calls to sqlite*ListAppend() routines.
32.472 +**
32.473 +** Any tables that the SrcList might point to are not duplicated.
32.474 +*/
32.475 +Expr *sqlite3ExprDup(Expr *p){
32.476 + Expr *pNew;
32.477 + if( p==0 ) return 0;
32.478 + pNew = sqliteMallocRaw( sizeof(*p) );
32.479 + if( pNew==0 ) return 0;
32.480 + memcpy(pNew, p, sizeof(*pNew));
32.481 + if( p->token.z!=0 ){
32.482 + pNew->token.z = (u8*)sqliteStrNDup((char*)p->token.z, p->token.n);
32.483 + pNew->token.dyn = 1;
32.484 + }else{
32.485 + assert( pNew->token.z==0 );
32.486 + }
32.487 + pNew->span.z = 0;
32.488 + pNew->pLeft = sqlite3ExprDup(p->pLeft);
32.489 + pNew->pRight = sqlite3ExprDup(p->pRight);
32.490 + pNew->pList = sqlite3ExprListDup(p->pList);
32.491 + pNew->pSelect = sqlite3SelectDup(p->pSelect);
32.492 + return pNew;
32.493 +}
32.494 +void sqlite3TokenCopy(Token *pTo, Token *pFrom){
32.495 + if( pTo->dyn ) sqliteFree((char*)pTo->z);
32.496 + if( pFrom->z ){
32.497 + pTo->n = pFrom->n;
32.498 + pTo->z = (u8*)sqliteStrNDup((char*)pFrom->z, pFrom->n);
32.499 + pTo->dyn = 1;
32.500 + }else{
32.501 + pTo->z = 0;
32.502 + }
32.503 +}
32.504 +ExprList *sqlite3ExprListDup(ExprList *p){
32.505 + ExprList *pNew;
32.506 + struct ExprList_item *pItem, *pOldItem;
32.507 + int i;
32.508 + if( p==0 ) return 0;
32.509 + pNew = sqliteMalloc( sizeof(*pNew) );
32.510 + if( pNew==0 ) return 0;
32.511 + pNew->nExpr = pNew->nAlloc = p->nExpr;
32.512 + pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
32.513 + if( pItem==0 ){
32.514 + sqliteFree(pNew);
32.515 + return 0;
32.516 + }
32.517 + pOldItem = p->a;
32.518 + for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
32.519 + Expr *pNewExpr, *pOldExpr;
32.520 + pItem->pExpr = pNewExpr = sqlite3ExprDup(pOldExpr = pOldItem->pExpr);
32.521 + if( pOldExpr->span.z!=0 && pNewExpr ){
32.522 + /* Always make a copy of the span for top-level expressions in the
32.523 + ** expression list. The logic in SELECT processing that determines
32.524 + ** the names of columns in the result set needs this information */
32.525 + sqlite3TokenCopy(&pNewExpr->span, &pOldExpr->span);
32.526 + }
32.527 + assert( pNewExpr==0 || pNewExpr->span.z!=0
32.528 + || pOldExpr->span.z==0
32.529 + || sqlite3MallocFailed() );
32.530 + pItem->zName = sqliteStrDup(pOldItem->zName);
32.531 + pItem->sortOrder = pOldItem->sortOrder;
32.532 + pItem->isAgg = pOldItem->isAgg;
32.533 + pItem->done = 0;
32.534 + }
32.535 + return pNew;
32.536 +}
32.537 +
32.538 +/*
32.539 +** If cursors, triggers, views and subqueries are all omitted from
32.540 +** the build, then none of the following routines, except for
32.541 +** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
32.542 +** called with a NULL argument.
32.543 +*/
32.544 +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
32.545 + || !defined(SQLITE_OMIT_SUBQUERY)
32.546 +SrcList *sqlite3SrcListDup(SrcList *p){
32.547 + SrcList *pNew;
32.548 + int i;
32.549 + int nByte;
32.550 + if( p==0 ) return 0;
32.551 + nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
32.552 + pNew = sqliteMallocRaw( nByte );
32.553 + if( pNew==0 ) return 0;
32.554 + pNew->nSrc = pNew->nAlloc = p->nSrc;
32.555 + for(i=0; i<p->nSrc; i++){
32.556 + struct SrcList_item *pNewItem = &pNew->a[i];
32.557 + struct SrcList_item *pOldItem = &p->a[i];
32.558 + Table *pTab;
32.559 + pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
32.560 + pNewItem->zName = sqliteStrDup(pOldItem->zName);
32.561 + pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
32.562 + pNewItem->jointype = pOldItem->jointype;
32.563 + pNewItem->iCursor = pOldItem->iCursor;
32.564 + pNewItem->isPopulated = pOldItem->isPopulated;
32.565 + pTab = pNewItem->pTab = pOldItem->pTab;
32.566 + if( pTab ){
32.567 + pTab->nRef++;
32.568 + }
32.569 + pNewItem->pSelect = sqlite3SelectDup(pOldItem->pSelect);
32.570 + pNewItem->pOn = sqlite3ExprDup(pOldItem->pOn);
32.571 + pNewItem->pUsing = sqlite3IdListDup(pOldItem->pUsing);
32.572 + pNewItem->colUsed = pOldItem->colUsed;
32.573 + }
32.574 + return pNew;
32.575 +}
32.576 +IdList *sqlite3IdListDup(IdList *p){
32.577 + IdList *pNew;
32.578 + int i;
32.579 + if( p==0 ) return 0;
32.580 + pNew = sqliteMallocRaw( sizeof(*pNew) );
32.581 + if( pNew==0 ) return 0;
32.582 + pNew->nId = pNew->nAlloc = p->nId;
32.583 + pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
32.584 + if( pNew->a==0 ){
32.585 + sqliteFree(pNew);
32.586 + return 0;
32.587 + }
32.588 + for(i=0; i<p->nId; i++){
32.589 + struct IdList_item *pNewItem = &pNew->a[i];
32.590 + struct IdList_item *pOldItem = &p->a[i];
32.591 + pNewItem->zName = sqliteStrDup(pOldItem->zName);
32.592 + pNewItem->idx = pOldItem->idx;
32.593 + }
32.594 + return pNew;
32.595 +}
32.596 +Select *sqlite3SelectDup(Select *p){
32.597 + Select *pNew;
32.598 + if( p==0 ) return 0;
32.599 + pNew = sqliteMallocRaw( sizeof(*p) );
32.600 + if( pNew==0 ) return 0;
32.601 + pNew->isDistinct = p->isDistinct;
32.602 + pNew->pEList = sqlite3ExprListDup(p->pEList);
32.603 + pNew->pSrc = sqlite3SrcListDup(p->pSrc);
32.604 + pNew->pWhere = sqlite3ExprDup(p->pWhere);
32.605 + pNew->pGroupBy = sqlite3ExprListDup(p->pGroupBy);
32.606 + pNew->pHaving = sqlite3ExprDup(p->pHaving);
32.607 + pNew->pOrderBy = sqlite3ExprListDup(p->pOrderBy);
32.608 + pNew->op = p->op;
32.609 + pNew->pPrior = sqlite3SelectDup(p->pPrior);
32.610 + pNew->pLimit = sqlite3ExprDup(p->pLimit);
32.611 + pNew->pOffset = sqlite3ExprDup(p->pOffset);
32.612 + pNew->iLimit = -1;
32.613 + pNew->iOffset = -1;
32.614 + pNew->isResolved = p->isResolved;
32.615 + pNew->isAgg = p->isAgg;
32.616 + pNew->usesEphm = 0;
32.617 + pNew->disallowOrderBy = 0;
32.618 + pNew->pRightmost = 0;
32.619 + pNew->addrOpenEphm[0] = -1;
32.620 + pNew->addrOpenEphm[1] = -1;
32.621 + pNew->addrOpenEphm[2] = -1;
32.622 + return pNew;
32.623 +}
32.624 +#else
32.625 +Select *sqlite3SelectDup(Select *p){
32.626 + assert( p==0 );
32.627 + return 0;
32.628 +}
32.629 +#endif
32.630 +
32.631 +
32.632 +/*
32.633 +** Add a new element to the end of an expression list. If pList is
32.634 +** initially NULL, then create a new expression list.
32.635 +*/
32.636 +ExprList *sqlite3ExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
32.637 + if( pList==0 ){
32.638 + pList = sqliteMalloc( sizeof(ExprList) );
32.639 + if( pList==0 ){
32.640 + goto no_mem;
32.641 + }
32.642 + assert( pList->nAlloc==0 );
32.643 + }
32.644 + if( pList->nAlloc<=pList->nExpr ){
32.645 + struct ExprList_item *a;
32.646 + int n = pList->nAlloc*2 + 4;
32.647 + a = sqliteRealloc(pList->a, n*sizeof(pList->a[0]));
32.648 + if( a==0 ){
32.649 + goto no_mem;
32.650 + }
32.651 + pList->a = a;
32.652 + pList->nAlloc = n;
32.653 + }
32.654 + assert( pList->a!=0 );
32.655 + if( pExpr || pName ){
32.656 + struct ExprList_item *pItem = &pList->a[pList->nExpr++];
32.657 + memset(pItem, 0, sizeof(*pItem));
32.658 + pItem->zName = sqlite3NameFromToken(pName);
32.659 + pItem->pExpr = pExpr;
32.660 + }
32.661 + return pList;
32.662 +
32.663 +no_mem:
32.664 + /* Avoid leaking memory if malloc has failed. */
32.665 + sqlite3ExprDelete(pExpr);
32.666 + sqlite3ExprListDelete(pList);
32.667 + return 0;
32.668 +}
32.669 +
32.670 +/*
32.671 +** If the expression list pEList contains more than iLimit elements,
32.672 +** leave an error message in pParse.
32.673 +*/
32.674 +void sqlite3ExprListCheckLength(
32.675 + Parse *pParse,
32.676 + ExprList *pEList,
32.677 + int iLimit,
32.678 + const char *zObject
32.679 +){
32.680 + if( pEList && pEList->nExpr>iLimit ){
32.681 + sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
32.682 + }
32.683 +}
32.684 +
32.685 +
32.686 +#if SQLITE_MAX_EXPR_DEPTH>0
32.687 +/* The following three functions, heightOfExpr(), heightOfExprList()
32.688 +** and heightOfSelect(), are used to determine the maximum height
32.689 +** of any expression tree referenced by the structure passed as the
32.690 +** first argument.
32.691 +**
32.692 +** If this maximum height is greater than the current value pointed
32.693 +** to by pnHeight, the second parameter, then set *pnHeight to that
32.694 +** value.
32.695 +*/
32.696 +static void heightOfExpr(Expr *p, int *pnHeight){
32.697 + if( p ){
32.698 + if( p->nHeight>*pnHeight ){
32.699 + *pnHeight = p->nHeight;
32.700 + }
32.701 + }
32.702 +}
32.703 +static void heightOfExprList(ExprList *p, int *pnHeight){
32.704 + if( p ){
32.705 + int i;
32.706 + for(i=0; i<p->nExpr; i++){
32.707 + heightOfExpr(p->a[i].pExpr, pnHeight);
32.708 + }
32.709 + }
32.710 +}
32.711 +static void heightOfSelect(Select *p, int *pnHeight){
32.712 + if( p ){
32.713 + heightOfExpr(p->pWhere, pnHeight);
32.714 + heightOfExpr(p->pHaving, pnHeight);
32.715 + heightOfExpr(p->pLimit, pnHeight);
32.716 + heightOfExpr(p->pOffset, pnHeight);
32.717 + heightOfExprList(p->pEList, pnHeight);
32.718 + heightOfExprList(p->pGroupBy, pnHeight);
32.719 + heightOfExprList(p->pOrderBy, pnHeight);
32.720 + heightOfSelect(p->pPrior, pnHeight);
32.721 + }
32.722 +}
32.723 +
32.724 +/*
32.725 +** Set the Expr.nHeight variable in the structure passed as an
32.726 +** argument. An expression with no children, Expr.pList or
32.727 +** Expr.pSelect member has a height of 1. Any other expression
32.728 +** has a height equal to the maximum height of any other
32.729 +** referenced Expr plus one.
32.730 +*/
32.731 +void sqlite3ExprSetHeight(Expr *p){
32.732 + int nHeight = 0;
32.733 + heightOfExpr(p->pLeft, &nHeight);
32.734 + heightOfExpr(p->pRight, &nHeight);
32.735 + heightOfExprList(p->pList, &nHeight);
32.736 + heightOfSelect(p->pSelect, &nHeight);
32.737 + p->nHeight = nHeight + 1;
32.738 +}
32.739 +
32.740 +/*
32.741 +** Return the maximum height of any expression tree referenced
32.742 +** by the select statement passed as an argument.
32.743 +*/
32.744 +int sqlite3SelectExprHeight(Select *p){
32.745 + int nHeight = 0;
32.746 + heightOfSelect(p, &nHeight);
32.747 + return nHeight;
32.748 +}
32.749 +#endif
32.750 +
32.751 +/*
32.752 +** Delete an entire expression list.
32.753 +*/
32.754 +void sqlite3ExprListDelete(ExprList *pList){
32.755 + int i;
32.756 + struct ExprList_item *pItem;
32.757 + if( pList==0 ) return;
32.758 + assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
32.759 + assert( pList->nExpr<=pList->nAlloc );
32.760 + for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
32.761 + sqlite3ExprDelete(pItem->pExpr);
32.762 + sqliteFree(pItem->zName);
32.763 + }
32.764 + sqliteFree(pList->a);
32.765 + sqliteFree(pList);
32.766 +}
32.767 +
32.768 +/*
32.769 +** Walk an expression tree. Call xFunc for each node visited.
32.770 +**
32.771 +** The return value from xFunc determines whether the tree walk continues.
32.772 +** 0 means continue walking the tree. 1 means do not walk children
32.773 +** of the current node but continue with siblings. 2 means abandon
32.774 +** the tree walk completely.
32.775 +**
32.776 +** The return value from this routine is 1 to abandon the tree walk
32.777 +** and 0 to continue.
32.778 +**
32.779 +** NOTICE: This routine does *not* descend into subqueries.
32.780 +*/
32.781 +static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
32.782 +static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
32.783 + int rc;
32.784 + if( pExpr==0 ) return 0;
32.785 + rc = (*xFunc)(pArg, pExpr);
32.786 + if( rc==0 ){
32.787 + if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
32.788 + if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
32.789 + if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
32.790 + }
32.791 + return rc>1;
32.792 +}
32.793 +
32.794 +/*
32.795 +** Call walkExprTree() for every expression in list p.
32.796 +*/
32.797 +static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
32.798 + int i;
32.799 + struct ExprList_item *pItem;
32.800 + if( !p ) return 0;
32.801 + for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
32.802 + if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
32.803 + }
32.804 + return 0;
32.805 +}
32.806 +
32.807 +/*
32.808 +** Call walkExprTree() for every expression in Select p, not including
32.809 +** expressions that are part of sub-selects in any FROM clause or the LIMIT
32.810 +** or OFFSET expressions..
32.811 +*/
32.812 +static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
32.813 + walkExprList(p->pEList, xFunc, pArg);
32.814 + walkExprTree(p->pWhere, xFunc, pArg);
32.815 + walkExprList(p->pGroupBy, xFunc, pArg);
32.816 + walkExprTree(p->pHaving, xFunc, pArg);
32.817 + walkExprList(p->pOrderBy, xFunc, pArg);
32.818 + if( p->pPrior ){
32.819 + walkSelectExpr(p->pPrior, xFunc, pArg);
32.820 + }
32.821 + return 0;
32.822 +}
32.823 +
32.824 +
32.825 +/*
32.826 +** This routine is designed as an xFunc for walkExprTree().
32.827 +**
32.828 +** pArg is really a pointer to an integer. If we can tell by looking
32.829 +** at pExpr that the expression that contains pExpr is not a constant
32.830 +** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
32.831 +** If pExpr does does not disqualify the expression from being a constant
32.832 +** then do nothing.
32.833 +**
32.834 +** After walking the whole tree, if no nodes are found that disqualify
32.835 +** the expression as constant, then we assume the whole expression
32.836 +** is constant. See sqlite3ExprIsConstant() for additional information.
32.837 +*/
32.838 +static int exprNodeIsConstant(void *pArg, Expr *pExpr){
32.839 + int *pN = (int*)pArg;
32.840 +
32.841 + /* If *pArg is 3 then any term of the expression that comes from
32.842 + ** the ON or USING clauses of a join disqualifies the expression
32.843 + ** from being considered constant. */
32.844 + if( (*pN)==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
32.845 + *pN = 0;
32.846 + return 2;
32.847 + }
32.848 +
32.849 + switch( pExpr->op ){
32.850 + /* Consider functions to be constant if all their arguments are constant
32.851 + ** and *pArg==2 */
32.852 + case TK_FUNCTION:
32.853 + if( (*pN)==2 ) return 0;
32.854 + /* Fall through */
32.855 + case TK_ID:
32.856 + case TK_COLUMN:
32.857 + case TK_DOT:
32.858 + case TK_AGG_FUNCTION:
32.859 + case TK_AGG_COLUMN:
32.860 +#ifndef SQLITE_OMIT_SUBQUERY
32.861 + case TK_SELECT:
32.862 + case TK_EXISTS:
32.863 +#endif
32.864 + *pN = 0;
32.865 + return 2;
32.866 + case TK_IN:
32.867 + if( pExpr->pSelect ){
32.868 + *pN = 0;
32.869 + return 2;
32.870 + }
32.871 + default:
32.872 + return 0;
32.873 + }
32.874 +}
32.875 +
32.876 +/*
32.877 +** Walk an expression tree. Return 1 if the expression is constant
32.878 +** and 0 if it involves variables or function calls.
32.879 +**
32.880 +** For the purposes of this function, a double-quoted string (ex: "abc")
32.881 +** is considered a variable but a single-quoted string (ex: 'abc') is
32.882 +** a constant.
32.883 +*/
32.884 +int sqlite3ExprIsConstant(Expr *p){
32.885 + int isConst = 1;
32.886 + walkExprTree(p, exprNodeIsConstant, &isConst);
32.887 + return isConst;
32.888 +}
32.889 +
32.890 +/*
32.891 +** Walk an expression tree. Return 1 if the expression is constant
32.892 +** that does no originate from the ON or USING clauses of a join.
32.893 +** Return 0 if it involves variables or function calls or terms from
32.894 +** an ON or USING clause.
32.895 +*/
32.896 +int sqlite3ExprIsConstantNotJoin(Expr *p){
32.897 + int isConst = 3;
32.898 + walkExprTree(p, exprNodeIsConstant, &isConst);
32.899 + return isConst!=0;
32.900 +}
32.901 +
32.902 +/*
32.903 +** Walk an expression tree. Return 1 if the expression is constant
32.904 +** or a function call with constant arguments. Return and 0 if there
32.905 +** are any variables.
32.906 +**
32.907 +** For the purposes of this function, a double-quoted string (ex: "abc")
32.908 +** is considered a variable but a single-quoted string (ex: 'abc') is
32.909 +** a constant.
32.910 +*/
32.911 +int sqlite3ExprIsConstantOrFunction(Expr *p){
32.912 + int isConst = 2;
32.913 + walkExprTree(p, exprNodeIsConstant, &isConst);
32.914 + return isConst!=0;
32.915 +}
32.916 +
32.917 +/*
32.918 +** If the expression p codes a constant integer that is small enough
32.919 +** to fit in a 32-bit integer, return 1 and put the value of the integer
32.920 +** in *pValue. If the expression is not an integer or if it is too big
32.921 +** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
32.922 +*/
32.923 +int sqlite3ExprIsInteger(Expr *p, int *pValue){
32.924 + switch( p->op ){
32.925 + case TK_INTEGER: {
32.926 + if( sqlite3GetInt32((char*)p->token.z, pValue) ){
32.927 + return 1;
32.928 + }
32.929 + break;
32.930 + }
32.931 + case TK_UPLUS: {
32.932 + return sqlite3ExprIsInteger(p->pLeft, pValue);
32.933 + }
32.934 + case TK_UMINUS: {
32.935 + int v;
32.936 + if( sqlite3ExprIsInteger(p->pLeft, &v) ){
32.937 + *pValue = -v;
32.938 + return 1;
32.939 + }
32.940 + break;
32.941 + }
32.942 + default: break;
32.943 + }
32.944 + return 0;
32.945 +}
32.946 +
32.947 +/*
32.948 +** Return TRUE if the given string is a row-id column name.
32.949 +*/
32.950 +int sqlite3IsRowid(const char *z){
32.951 + if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
32.952 + if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
32.953 + if( sqlite3StrICmp(z, "OID")==0 ) return 1;
32.954 + return 0;
32.955 +}
32.956 +
32.957 +/*
32.958 +** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
32.959 +** that name in the set of source tables in pSrcList and make the pExpr
32.960 +** expression node refer back to that source column. The following changes
32.961 +** are made to pExpr:
32.962 +**
32.963 +** pExpr->iDb Set the index in db->aDb[] of the database holding
32.964 +** the table.
32.965 +** pExpr->iTable Set to the cursor number for the table obtained
32.966 +** from pSrcList.
32.967 +** pExpr->iColumn Set to the column number within the table.
32.968 +** pExpr->op Set to TK_COLUMN.
32.969 +** pExpr->pLeft Any expression this points to is deleted
32.970 +** pExpr->pRight Any expression this points to is deleted.
32.971 +**
32.972 +** The pDbToken is the name of the database (the "X"). This value may be
32.973 +** NULL meaning that name is of the form Y.Z or Z. Any available database
32.974 +** can be used. The pTableToken is the name of the table (the "Y"). This
32.975 +** value can be NULL if pDbToken is also NULL. If pTableToken is NULL it
32.976 +** means that the form of the name is Z and that columns from any table
32.977 +** can be used.
32.978 +**
32.979 +** If the name cannot be resolved unambiguously, leave an error message
32.980 +** in pParse and return non-zero. Return zero on success.
32.981 +*/
32.982 +static int lookupName(
32.983 + Parse *pParse, /* The parsing context */
32.984 + Token *pDbToken, /* Name of the database containing table, or NULL */
32.985 + Token *pTableToken, /* Name of table containing column, or NULL */
32.986 + Token *pColumnToken, /* Name of the column. */
32.987 + NameContext *pNC, /* The name context used to resolve the name */
32.988 + Expr *pExpr /* Make this EXPR node point to the selected column */
32.989 +){
32.990 + char *zDb = 0; /* Name of the database. The "X" in X.Y.Z */
32.991 + char *zTab = 0; /* Name of the table. The "Y" in X.Y.Z or Y.Z */
32.992 + char *zCol = 0; /* Name of the column. The "Z" */
32.993 + int i, j; /* Loop counters */
32.994 + int cnt = 0; /* Number of matching column names */
32.995 + int cntTab = 0; /* Number of matching table names */
32.996 + sqlite3 *db = pParse->db; /* The database */
32.997 + struct SrcList_item *pItem; /* Use for looping over pSrcList items */
32.998 + struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
32.999 + NameContext *pTopNC = pNC; /* First namecontext in the list */
32.1000 +
32.1001 + assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
32.1002 + zDb = sqlite3NameFromToken(pDbToken);
32.1003 + zTab = sqlite3NameFromToken(pTableToken);
32.1004 + zCol = sqlite3NameFromToken(pColumnToken);
32.1005 + if( sqlite3MallocFailed() ){
32.1006 + goto lookupname_end;
32.1007 + }
32.1008 +
32.1009 + pExpr->iTable = -1;
32.1010 + while( pNC && cnt==0 ){
32.1011 + ExprList *pEList;
32.1012 + SrcList *pSrcList = pNC->pSrcList;
32.1013 +
32.1014 + if( pSrcList ){
32.1015 + for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
32.1016 + Table *pTab;
32.1017 + int iDb;
32.1018 + Column *pCol;
32.1019 +
32.1020 + pTab = pItem->pTab;
32.1021 + assert( pTab!=0 );
32.1022 + iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
32.1023 + assert( pTab->nCol>0 );
32.1024 + if( zTab ){
32.1025 + if( pItem->zAlias ){
32.1026 + char *zTabName = pItem->zAlias;
32.1027 + if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
32.1028 + }else{
32.1029 + char *zTabName = pTab->zName;
32.1030 + if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
32.1031 + if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
32.1032 + continue;
32.1033 + }
32.1034 + }
32.1035 + }
32.1036 + if( 0==(cntTab++) ){
32.1037 + pExpr->iTable = pItem->iCursor;
32.1038 + pExpr->pSchema = pTab->pSchema;
32.1039 + pMatch = pItem;
32.1040 + }
32.1041 + for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
32.1042 + if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
32.1043 + const char *zColl = pTab->aCol[j].zColl;
32.1044 + IdList *pUsing;
32.1045 + cnt++;
32.1046 + pExpr->iTable = pItem->iCursor;
32.1047 + pMatch = pItem;
32.1048 + pExpr->pSchema = pTab->pSchema;
32.1049 + /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
32.1050 + pExpr->iColumn = j==pTab->iPKey ? -1 : j;
32.1051 + pExpr->affinity = pTab->aCol[j].affinity;
32.1052 + if( (pExpr->flags & EP_ExpCollate)==0 ){
32.1053 + pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
32.1054 + }
32.1055 + if( i<pSrcList->nSrc-1 ){
32.1056 + if( pItem[1].jointype & JT_NATURAL ){
32.1057 + /* If this match occurred in the left table of a natural join,
32.1058 + ** then skip the right table to avoid a duplicate match */
32.1059 + pItem++;
32.1060 + i++;
32.1061 + }else if( (pUsing = pItem[1].pUsing)!=0 ){
32.1062 + /* If this match occurs on a column that is in the USING clause
32.1063 + ** of a join, skip the search of the right table of the join
32.1064 + ** to avoid a duplicate match there. */
32.1065 + int k;
32.1066 + for(k=0; k<pUsing->nId; k++){
32.1067 + if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
32.1068 + pItem++;
32.1069 + i++;
32.1070 + break;
32.1071 + }
32.1072 + }
32.1073 + }
32.1074 + }
32.1075 + break;
32.1076 + }
32.1077 + }
32.1078 + }
32.1079 + }
32.1080 +
32.1081 +#ifndef SQLITE_OMIT_TRIGGER
32.1082 + /* If we have not already resolved the name, then maybe
32.1083 + ** it is a new.* or old.* trigger argument reference
32.1084 + */
32.1085 + if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
32.1086 + TriggerStack *pTriggerStack = pParse->trigStack;
32.1087 + Table *pTab = 0;
32.1088 + if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
32.1089 + pExpr->iTable = pTriggerStack->newIdx;
32.1090 + assert( pTriggerStack->pTab );
32.1091 + pTab = pTriggerStack->pTab;
32.1092 + }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
32.1093 + pExpr->iTable = pTriggerStack->oldIdx;
32.1094 + assert( pTriggerStack->pTab );
32.1095 + pTab = pTriggerStack->pTab;
32.1096 + }
32.1097 +
32.1098 + if( pTab ){
32.1099 + int iCol;
32.1100 + Column *pCol = pTab->aCol;
32.1101 +
32.1102 + pExpr->pSchema = pTab->pSchema;
32.1103 + cntTab++;
32.1104 + for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
32.1105 + if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
32.1106 + const char *zColl = pTab->aCol[iCol].zColl;
32.1107 + cnt++;
32.1108 + pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
32.1109 + pExpr->affinity = pTab->aCol[iCol].affinity;
32.1110 + if( (pExpr->flags & EP_ExpCollate)==0 ){
32.1111 + pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
32.1112 + }
32.1113 + pExpr->pTab = pTab;
32.1114 + break;
32.1115 + }
32.1116 + }
32.1117 + }
32.1118 + }
32.1119 +#endif /* !defined(SQLITE_OMIT_TRIGGER) */
32.1120 +
32.1121 + /*
32.1122 + ** Perhaps the name is a reference to the ROWID
32.1123 + */
32.1124 + if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
32.1125 + cnt = 1;
32.1126 + pExpr->iColumn = -1;
32.1127 + pExpr->affinity = SQLITE_AFF_INTEGER;
32.1128 + }
32.1129 +
32.1130 + /*
32.1131 + ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
32.1132 + ** might refer to an result-set alias. This happens, for example, when
32.1133 + ** we are resolving names in the WHERE clause of the following command:
32.1134 + **
32.1135 + ** SELECT a+b AS x FROM table WHERE x<10;
32.1136 + **
32.1137 + ** In cases like this, replace pExpr with a copy of the expression that
32.1138 + ** forms the result set entry ("a+b" in the example) and return immediately.
32.1139 + ** Note that the expression in the result set should have already been
32.1140 + ** resolved by the time the WHERE clause is resolved.
32.1141 + */
32.1142 + if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
32.1143 + for(j=0; j<pEList->nExpr; j++){
32.1144 + char *zAs = pEList->a[j].zName;
32.1145 + if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
32.1146 + Expr *pDup;
32.1147 + assert( pExpr->pLeft==0 && pExpr->pRight==0 );
32.1148 + assert( pExpr->pList==0 );
32.1149 + assert( pExpr->pSelect==0 );
32.1150 + pDup = sqlite3ExprDup(pEList->a[j].pExpr);
32.1151 + if( pExpr->flags & EP_ExpCollate ){
32.1152 + pDup->pColl = pExpr->pColl;
32.1153 + pDup->flags |= EP_ExpCollate;
32.1154 + }
32.1155 + if( pExpr->span.dyn ) sqliteFree((char*)pExpr->span.z);
32.1156 + if( pExpr->token.dyn ) sqliteFree((char*)pExpr->token.z);
32.1157 + memcpy(pExpr, pDup, sizeof(*pExpr));
32.1158 + sqliteFree(pDup);
32.1159 + cnt = 1;
32.1160 + pMatch = 0;
32.1161 + assert( zTab==0 && zDb==0 );
32.1162 + goto lookupname_end_2;
32.1163 + }
32.1164 + }
32.1165 + }
32.1166 +
32.1167 + /* Advance to the next name context. The loop will exit when either
32.1168 + ** we have a match (cnt>0) or when we run out of name contexts.
32.1169 + */
32.1170 + if( cnt==0 ){
32.1171 + pNC = pNC->pNext;
32.1172 + }
32.1173 + }
32.1174 +
32.1175 + /*
32.1176 + ** If X and Y are NULL (in other words if only the column name Z is
32.1177 + ** supplied) and the value of Z is enclosed in double-quotes, then
32.1178 + ** Z is a string literal if it doesn't match any column names. In that
32.1179 + ** case, we need to return right away and not make any changes to
32.1180 + ** pExpr.
32.1181 + **
32.1182 + ** Because no reference was made to outer contexts, the pNC->nRef
32.1183 + ** fields are not changed in any context.
32.1184 + */
32.1185 + if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
32.1186 + sqliteFree(zCol);
32.1187 + return 0;
32.1188 + }
32.1189 +
32.1190 + /*
32.1191 + ** cnt==0 means there was not match. cnt>1 means there were two or
32.1192 + ** more matches. Either way, we have an error.
32.1193 + */
32.1194 + if( cnt!=1 ){
32.1195 + char *z = 0;
32.1196 + char *zErr;
32.1197 + zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
32.1198 + if( zDb ){
32.1199 + sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
32.1200 + }else if( zTab ){
32.1201 + sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
32.1202 + }else{
32.1203 + z = sqliteStrDup(zCol);
32.1204 + }
32.1205 + sqlite3ErrorMsg(pParse, zErr, z);
32.1206 + sqliteFree(z);
32.1207 + pTopNC->nErr++;
32.1208 + }
32.1209 +
32.1210 + /* If a column from a table in pSrcList is referenced, then record
32.1211 + ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
32.1212 + ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
32.1213 + ** column number is greater than the number of bits in the bitmask
32.1214 + ** then set the high-order bit of the bitmask.
32.1215 + */
32.1216 + if( pExpr->iColumn>=0 && pMatch!=0 ){
32.1217 + int n = pExpr->iColumn;
32.1218 + if( n>=sizeof(Bitmask)*8 ){
32.1219 + n = sizeof(Bitmask)*8-1;
32.1220 + }
32.1221 + assert( pMatch->iCursor==pExpr->iTable );
32.1222 + pMatch->colUsed |= ((Bitmask)1)<<n;
32.1223 + }
32.1224 +
32.1225 +lookupname_end:
32.1226 + /* Clean up and return
32.1227 + */
32.1228 + sqliteFree(zDb);
32.1229 + sqliteFree(zTab);
32.1230 + sqlite3ExprDelete(pExpr->pLeft);
32.1231 + pExpr->pLeft = 0;
32.1232 + sqlite3ExprDelete(pExpr->pRight);
32.1233 + pExpr->pRight = 0;
32.1234 + pExpr->op = TK_COLUMN;
32.1235 +lookupname_end_2:
32.1236 + sqliteFree(zCol);
32.1237 + if( cnt==1 ){
32.1238 + assert( pNC!=0 );
32.1239 + sqlite3AuthRead(pParse, pExpr, pNC->pSrcList);
32.1240 + if( pMatch && !pMatch->pSelect ){
32.1241 + pExpr->pTab = pMatch->pTab;
32.1242 + }
32.1243 + /* Increment the nRef value on all name contexts from TopNC up to
32.1244 + ** the point where the name matched. */
32.1245 + for(;;){
32.1246 + assert( pTopNC!=0 );
32.1247 + pTopNC->nRef++;
32.1248 + if( pTopNC==pNC ) break;
32.1249 + pTopNC = pTopNC->pNext;
32.1250 + }
32.1251 + return 0;
32.1252 + } else {
32.1253 + return 1;
32.1254 + }
32.1255 +}
32.1256 +
32.1257 +/*
32.1258 +** This routine is designed as an xFunc for walkExprTree().
32.1259 +**
32.1260 +** Resolve symbolic names into TK_COLUMN operators for the current
32.1261 +** node in the expression tree. Return 0 to continue the search down
32.1262 +** the tree or 2 to abort the tree walk.
32.1263 +**
32.1264 +** This routine also does error checking and name resolution for
32.1265 +** function names. The operator for aggregate functions is changed
32.1266 +** to TK_AGG_FUNCTION.
32.1267 +*/
32.1268 +static int nameResolverStep(void *pArg, Expr *pExpr){
32.1269 + NameContext *pNC = (NameContext*)pArg;
32.1270 + Parse *pParse;
32.1271 +
32.1272 + if( pExpr==0 ) return 1;
32.1273 + assert( pNC!=0 );
32.1274 + pParse = pNC->pParse;
32.1275 +
32.1276 + if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
32.1277 + ExprSetProperty(pExpr, EP_Resolved);
32.1278 +#ifndef NDEBUG
32.1279 + if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
32.1280 + SrcList *pSrcList = pNC->pSrcList;
32.1281 + int i;
32.1282 + for(i=0; i<pNC->pSrcList->nSrc; i++){
32.1283 + assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
32.1284 + }
32.1285 + }
32.1286 +#endif
32.1287 + switch( pExpr->op ){
32.1288 + /* Double-quoted strings (ex: "abc") are used as identifiers if
32.1289 + ** possible. Otherwise they remain as strings. Single-quoted
32.1290 + ** strings (ex: 'abc') are always string literals.
32.1291 + */
32.1292 + case TK_STRING: {
32.1293 + if( pExpr->token.z[0]=='\'' ) break;
32.1294 + /* Fall thru into the TK_ID case if this is a double-quoted string */
32.1295 + }
32.1296 + /* A lone identifier is the name of a column.
32.1297 + */
32.1298 + case TK_ID: {
32.1299 + lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
32.1300 + return 1;
32.1301 + }
32.1302 +
32.1303 + /* A table name and column name: ID.ID
32.1304 + ** Or a database, table and column: ID.ID.ID
32.1305 + */
32.1306 + case TK_DOT: {
32.1307 + Token *pColumn;
32.1308 + Token *pTable;
32.1309 + Token *pDb;
32.1310 + Expr *pRight;
32.1311 +
32.1312 + /* if( pSrcList==0 ) break; */
32.1313 + pRight = pExpr->pRight;
32.1314 + if( pRight->op==TK_ID ){
32.1315 + pDb = 0;
32.1316 + pTable = &pExpr->pLeft->token;
32.1317 + pColumn = &pRight->token;
32.1318 + }else{
32.1319 + assert( pRight->op==TK_DOT );
32.1320 + pDb = &pExpr->pLeft->token;
32.1321 + pTable = &pRight->pLeft->token;
32.1322 + pColumn = &pRight->pRight->token;
32.1323 + }
32.1324 + lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
32.1325 + return 1;
32.1326 + }
32.1327 +
32.1328 + /* Resolve function names
32.1329 + */
32.1330 + case TK_CONST_FUNC:
32.1331 + case TK_FUNCTION: {
32.1332 + ExprList *pList = pExpr->pList; /* The argument list */
32.1333 + int n = pList ? pList->nExpr : 0; /* Number of arguments */
32.1334 + int no_such_func = 0; /* True if no such function exists */
32.1335 + int wrong_num_args = 0; /* True if wrong number of arguments */
32.1336 + int is_agg = 0; /* True if is an aggregate function */
32.1337 + int i;
32.1338 + int auth; /* Authorization to use the function */
32.1339 + int nId; /* Number of characters in function name */
32.1340 + const char *zId; /* The function name. */
32.1341 + FuncDef *pDef; /* Information about the function */
32.1342 + int enc = ENC(pParse->db); /* The database encoding */
32.1343 +
32.1344 + zId = (char*)pExpr->token.z;
32.1345 + nId = pExpr->token.n;
32.1346 + pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
32.1347 + if( pDef==0 ){
32.1348 + pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
32.1349 + if( pDef==0 ){
32.1350 + no_such_func = 1;
32.1351 + }else{
32.1352 + wrong_num_args = 1;
32.1353 + }
32.1354 + }else{
32.1355 + is_agg = pDef->xFunc==0;
32.1356 + }
32.1357 +#ifndef SQLITE_OMIT_AUTHORIZATION
32.1358 + if( pDef ){
32.1359 + auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
32.1360 + if( auth!=SQLITE_OK ){
32.1361 + if( auth==SQLITE_DENY ){
32.1362 + sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
32.1363 + pDef->zName);
32.1364 + pNC->nErr++;
32.1365 + }
32.1366 + pExpr->op = TK_NULL;
32.1367 + return 1;
32.1368 + }
32.1369 + }
32.1370 +#endif
32.1371 + if( is_agg && !pNC->allowAgg ){
32.1372 + sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
32.1373 + pNC->nErr++;
32.1374 + is_agg = 0;
32.1375 + }else if( no_such_func ){
32.1376 + sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
32.1377 + pNC->nErr++;
32.1378 + }else if( wrong_num_args ){
32.1379 + sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
32.1380 + nId, zId);
32.1381 + pNC->nErr++;
32.1382 + }
32.1383 + if( is_agg ){
32.1384 + pExpr->op = TK_AGG_FUNCTION;
32.1385 + pNC->hasAgg = 1;
32.1386 + }
32.1387 + if( is_agg ) pNC->allowAgg = 0;
32.1388 + for(i=0; pNC->nErr==0 && i<n; i++){
32.1389 + walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
32.1390 + }
32.1391 + if( is_agg ) pNC->allowAgg = 1;
32.1392 + /* FIX ME: Compute pExpr->affinity based on the expected return
32.1393 + ** type of the function
32.1394 + */
32.1395 + return is_agg;
32.1396 + }
32.1397 +#ifndef SQLITE_OMIT_SUBQUERY
32.1398 + case TK_SELECT:
32.1399 + case TK_EXISTS:
32.1400 +#endif
32.1401 + case TK_IN: {
32.1402 + if( pExpr->pSelect ){
32.1403 + int nRef = pNC->nRef;
32.1404 +#ifndef SQLITE_OMIT_CHECK
32.1405 + if( pNC->isCheck ){
32.1406 + sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
32.1407 + }
32.1408 +#endif
32.1409 + sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
32.1410 + assert( pNC->nRef>=nRef );
32.1411 + if( nRef!=pNC->nRef ){
32.1412 + ExprSetProperty(pExpr, EP_VarSelect);
32.1413 + }
32.1414 + }
32.1415 + break;
32.1416 + }
32.1417 +#ifndef SQLITE_OMIT_CHECK
32.1418 + case TK_VARIABLE: {
32.1419 + if( pNC->isCheck ){
32.1420 + sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
32.1421 + }
32.1422 + break;
32.1423 + }
32.1424 +#endif
32.1425 + }
32.1426 + return 0;
32.1427 +}
32.1428 +
32.1429 +/*
32.1430 +** This routine walks an expression tree and resolves references to
32.1431 +** table columns. Nodes of the form ID.ID or ID resolve into an
32.1432 +** index to the table in the table list and a column offset. The
32.1433 +** Expr.opcode for such nodes is changed to TK_COLUMN. The Expr.iTable
32.1434 +** value is changed to the index of the referenced table in pTabList
32.1435 +** plus the "base" value. The base value will ultimately become the
32.1436 +** VDBE cursor number for a cursor that is pointing into the referenced
32.1437 +** table. The Expr.iColumn value is changed to the index of the column
32.1438 +** of the referenced table. The Expr.iColumn value for the special
32.1439 +** ROWID column is -1. Any INTEGER PRIMARY KEY column is tried as an
32.1440 +** alias for ROWID.
32.1441 +**
32.1442 +** Also resolve function names and check the functions for proper
32.1443 +** usage. Make sure all function names are recognized and all functions
32.1444 +** have the correct number of arguments. Leave an error message
32.1445 +** in pParse->zErrMsg if anything is amiss. Return the number of errors.
32.1446 +**
32.1447 +** If the expression contains aggregate functions then set the EP_Agg
32.1448 +** property on the expression.
32.1449 +*/
32.1450 +int sqlite3ExprResolveNames(
32.1451 + NameContext *pNC, /* Namespace to resolve expressions in. */
32.1452 + Expr *pExpr /* The expression to be analyzed. */
32.1453 +){
32.1454 + int savedHasAgg;
32.1455 + if( pExpr==0 ) return 0;
32.1456 +#if SQLITE_MAX_EXPR_DEPTH>0
32.1457 + if( (pExpr->nHeight+pNC->pParse->nHeight)>SQLITE_MAX_EXPR_DEPTH ){
32.1458 + sqlite3ErrorMsg(pNC->pParse,
32.1459 + "Expression tree is too large (maximum depth %d)",
32.1460 + SQLITE_MAX_EXPR_DEPTH
32.1461 + );
32.1462 + return 1;
32.1463 + }
32.1464 + pNC->pParse->nHeight += pExpr->nHeight;
32.1465 +#endif
32.1466 + savedHasAgg = pNC->hasAgg;
32.1467 + pNC->hasAgg = 0;
32.1468 + walkExprTree(pExpr, nameResolverStep, pNC);
32.1469 +#if SQLITE_MAX_EXPR_DEPTH>0
32.1470 + pNC->pParse->nHeight -= pExpr->nHeight;
32.1471 +#endif
32.1472 + if( pNC->nErr>0 ){
32.1473 + ExprSetProperty(pExpr, EP_Error);
32.1474 + }
32.1475 + if( pNC->hasAgg ){
32.1476 + ExprSetProperty(pExpr, EP_Agg);
32.1477 + }else if( savedHasAgg ){
32.1478 + pNC->hasAgg = 1;
32.1479 + }
32.1480 + return ExprHasProperty(pExpr, EP_Error);
32.1481 +}
32.1482 +
32.1483 +/*
32.1484 +** A pointer instance of this structure is used to pass information
32.1485 +** through walkExprTree into codeSubqueryStep().
32.1486 +*/
32.1487 +typedef struct QueryCoder QueryCoder;
32.1488 +struct QueryCoder {
32.1489 + Parse *pParse; /* The parsing context */
32.1490 + NameContext *pNC; /* Namespace of first enclosing query */
32.1491 +};
32.1492 +
32.1493 +
32.1494 +/*
32.1495 +** Generate code for scalar subqueries used as an expression
32.1496 +** and IN operators. Examples:
32.1497 +**
32.1498 +** (SELECT a FROM b) -- subquery
32.1499 +** EXISTS (SELECT a FROM b) -- EXISTS subquery
32.1500 +** x IN (4,5,11) -- IN operator with list on right-hand side
32.1501 +** x IN (SELECT a FROM b) -- IN operator with subquery on the right
32.1502 +**
32.1503 +** The pExpr parameter describes the expression that contains the IN
32.1504 +** operator or subquery.
32.1505 +*/
32.1506 +#ifndef SQLITE_OMIT_SUBQUERY
32.1507 +void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
32.1508 + int testAddr = 0; /* One-time test address */
32.1509 + Vdbe *v = sqlite3GetVdbe(pParse);
32.1510 + if( v==0 ) return;
32.1511 +
32.1512 +
32.1513 + /* This code must be run in its entirety every time it is encountered
32.1514 + ** if any of the following is true:
32.1515 + **
32.1516 + ** * The right-hand side is a correlated subquery
32.1517 + ** * The right-hand side is an expression list containing variables
32.1518 + ** * We are inside a trigger
32.1519 + **
32.1520 + ** If all of the above are false, then we can run this code just once
32.1521 + ** save the results, and reuse the same result on subsequent invocations.
32.1522 + */
32.1523 + if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
32.1524 + int mem = pParse->nMem++;
32.1525 + sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
32.1526 + testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
32.1527 + assert( testAddr>0 || sqlite3MallocFailed() );
32.1528 + sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
32.1529 + }
32.1530 +
32.1531 + switch( pExpr->op ){
32.1532 + case TK_IN: {
32.1533 + char affinity;
32.1534 + KeyInfo keyInfo;
32.1535 + int addr; /* Address of OP_OpenEphemeral instruction */
32.1536 +
32.1537 + affinity = sqlite3ExprAffinity(pExpr->pLeft);
32.1538 +
32.1539 + /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
32.1540 + ** expression it is handled the same way. A virtual table is
32.1541 + ** filled with single-field index keys representing the results
32.1542 + ** from the SELECT or the <exprlist>.
32.1543 + **
32.1544 + ** If the 'x' expression is a column value, or the SELECT...
32.1545 + ** statement returns a column value, then the affinity of that
32.1546 + ** column is used to build the index keys. If both 'x' and the
32.1547 + ** SELECT... statement are columns, then numeric affinity is used
32.1548 + ** if either column has NUMERIC or INTEGER affinity. If neither
32.1549 + ** 'x' nor the SELECT... statement are columns, then numeric affinity
32.1550 + ** is used.
32.1551 + */
32.1552 + pExpr->iTable = pParse->nTab++;
32.1553 + addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, pExpr->iTable, 0);
32.1554 + memset(&keyInfo, 0, sizeof(keyInfo));
32.1555 + keyInfo.nField = 1;
32.1556 + sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
32.1557 +
32.1558 + if( pExpr->pSelect ){
32.1559 + /* Case 1: expr IN (SELECT ...)
32.1560 + **
32.1561 + ** Generate code to write the results of the select into the temporary
32.1562 + ** table allocated and opened above.
32.1563 + */
32.1564 + int iParm = pExpr->iTable + (((int)affinity)<<16);
32.1565 + ExprList *pEList;
32.1566 + assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
32.1567 + if( sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0) ){
32.1568 + return;
32.1569 + }
32.1570 + pEList = pExpr->pSelect->pEList;
32.1571 + if( pEList && pEList->nExpr>0 ){
32.1572 + keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
32.1573 + pEList->a[0].pExpr);
32.1574 + }
32.1575 + }else if( pExpr->pList ){
32.1576 + /* Case 2: expr IN (exprlist)
32.1577 + **
32.1578 + ** For each expression, build an index key from the evaluation and
32.1579 + ** store it in the temporary table. If <expr> is a column, then use
32.1580 + ** that columns affinity when building index keys. If <expr> is not
32.1581 + ** a column, use numeric affinity.
32.1582 + */
32.1583 + int i;
32.1584 + ExprList *pList = pExpr->pList;
32.1585 + struct ExprList_item *pItem;
32.1586 +
32.1587 + if( !affinity ){
32.1588 + affinity = SQLITE_AFF_NONE;
32.1589 + }
32.1590 + keyInfo.aColl[0] = pExpr->pLeft->pColl;
32.1591 +
32.1592 + /* Loop through each expression in <exprlist>. */
32.1593 + for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
32.1594 + Expr *pE2 = pItem->pExpr;
32.1595 +
32.1596 + /* If the expression is not constant then we will need to
32.1597 + ** disable the test that was generated above that makes sure
32.1598 + ** this code only executes once. Because for a non-constant
32.1599 + ** expression we need to rerun this code each time.
32.1600 + */
32.1601 + if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){
32.1602 + sqlite3VdbeChangeToNoop(v, testAddr-1, 3);
32.1603 + testAddr = 0;
32.1604 + }
32.1605 +
32.1606 + /* Evaluate the expression and insert it into the temp table */
32.1607 + sqlite3ExprCode(pParse, pE2);
32.1608 + sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
32.1609 + sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0);
32.1610 + }
32.1611 + }
32.1612 + sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
32.1613 + break;
32.1614 + }
32.1615 +
32.1616 + case TK_EXISTS:
32.1617 + case TK_SELECT: {
32.1618 + /* This has to be a scalar SELECT. Generate code to put the
32.1619 + ** value of this select in a memory cell and record the number
32.1620 + ** of the memory cell in iColumn.
32.1621 + */
32.1622 + static const Token one = { (u8*)"1", 0, 1 };
32.1623 + Select *pSel;
32.1624 + int iMem;
32.1625 + int sop;
32.1626 +
32.1627 + pExpr->iColumn = iMem = pParse->nMem++;
32.1628 + pSel = pExpr->pSelect;
32.1629 + if( pExpr->op==TK_SELECT ){
32.1630 + sop = SRT_Mem;
32.1631 + sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0);
32.1632 + VdbeComment((v, "# Init subquery result"));
32.1633 + }else{
32.1634 + sop = SRT_Exists;
32.1635 + sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
32.1636 + VdbeComment((v, "# Init EXISTS result"));
32.1637 + }
32.1638 + sqlite3ExprDelete(pSel->pLimit);
32.1639 + pSel->pLimit = sqlite3Expr(TK_INTEGER, 0, 0, &one);
32.1640 + if( sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0) ){
32.1641 + return;
32.1642 + }
32.1643 + break;
32.1644 + }
32.1645 + }
32.1646 +
32.1647 + if( testAddr ){
32.1648 + sqlite3VdbeJumpHere(v, testAddr);
32.1649 + }
32.1650 +
32.1651 + return;
32.1652 +}
32.1653 +#endif /* SQLITE_OMIT_SUBQUERY */
32.1654 +
32.1655 +/*
32.1656 +** Generate an instruction that will put the integer describe by
32.1657 +** text z[0..n-1] on the stack.
32.1658 +*/
32.1659 +static void codeInteger(Vdbe *v, const char *z, int n){
32.1660 + assert( z || sqlite3MallocFailed() );
32.1661 + if( z ){
32.1662 + int i;
32.1663 + if( sqlite3GetInt32(z, &i) ){
32.1664 + sqlite3VdbeAddOp(v, OP_Integer, i, 0);
32.1665 + }else if( sqlite3FitsIn64Bits(z) ){
32.1666 + sqlite3VdbeOp3(v, OP_Int64, 0, 0, z, n);
32.1667 + }else{
32.1668 + sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
32.1669 + }
32.1670 + }
32.1671 +}
32.1672 +
32.1673 +
32.1674 +/*
32.1675 +** Generate code that will extract the iColumn-th column from
32.1676 +** table pTab and push that column value on the stack. There
32.1677 +** is an open cursor to pTab in iTable. If iColumn<0 then
32.1678 +** code is generated that extracts the rowid.
32.1679 +*/
32.1680 +void sqlite3ExprCodeGetColumn(Vdbe *v, Table *pTab, int iColumn, int iTable){
32.1681 + if( iColumn<0 ){
32.1682 + int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
32.1683 + sqlite3VdbeAddOp(v, op, iTable, 0);
32.1684 + }else if( pTab==0 ){
32.1685 + sqlite3VdbeAddOp(v, OP_Column, iTable, iColumn);
32.1686 + }else{
32.1687 + int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
32.1688 + sqlite3VdbeAddOp(v, op, iTable, iColumn);
32.1689 + sqlite3ColumnDefault(v, pTab, iColumn);
32.1690 +#ifndef SQLITE_OMIT_FLOATING_POINT
32.1691 + if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
32.1692 + sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0);
32.1693 + }
32.1694 +#endif
32.1695 + }
32.1696 +}
32.1697 +
32.1698 +/*
32.1699 +** Generate code into the current Vdbe to evaluate the given
32.1700 +** expression and leave the result on the top of stack.
32.1701 +**
32.1702 +** This code depends on the fact that certain token values (ex: TK_EQ)
32.1703 +** are the same as opcode values (ex: OP_Eq) that implement the corresponding
32.1704 +** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
32.1705 +** the make process cause these values to align. Assert()s in the code
32.1706 +** below verify that the numbers are aligned correctly.
32.1707 +*/
32.1708 +void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
32.1709 + Vdbe *v = pParse->pVdbe;
32.1710 + int op;
32.1711 + int stackChng = 1; /* Amount of change to stack depth */
32.1712 +
32.1713 + if( v==0 ) return;
32.1714 + if( pExpr==0 ){
32.1715 + sqlite3VdbeAddOp(v, OP_Null, 0, 0);
32.1716 + return;
32.1717 + }
32.1718 + op = pExpr->op;
32.1719 + switch( op ){
32.1720 + case TK_AGG_COLUMN: {
32.1721 + AggInfo *pAggInfo = pExpr->pAggInfo;
32.1722 + struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
32.1723 + if( !pAggInfo->directMode ){
32.1724 + sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0);
32.1725 + break;
32.1726 + }else if( pAggInfo->useSortingIdx ){
32.1727 + sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx,
32.1728 + pCol->iSorterColumn);
32.1729 + break;
32.1730 + }
32.1731 + /* Otherwise, fall thru into the TK_COLUMN case */
32.1732 + }
32.1733 + case TK_COLUMN: {
32.1734 + if( pExpr->iTable<0 ){
32.1735 + /* This only happens when coding check constraints */
32.1736 + assert( pParse->ckOffset>0 );
32.1737 + sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1);
32.1738 + }else{
32.1739 + sqlite3ExprCodeGetColumn(v, pExpr->pTab, pExpr->iColumn, pExpr->iTable);
32.1740 + }
32.1741 + break;
32.1742 + }
32.1743 + case TK_INTEGER: {
32.1744 + codeInteger(v, (char*)pExpr->token.z, pExpr->token.n);
32.1745 + break;
32.1746 + }
32.1747 + case TK_FLOAT:
32.1748 + case TK_STRING: {
32.1749 + assert( TK_FLOAT==OP_Real );
32.1750 + assert( TK_STRING==OP_String8 );
32.1751 + sqlite3DequoteExpr(pExpr);
32.1752 + sqlite3VdbeOp3(v, op, 0, 0, (char*)pExpr->token.z, pExpr->token.n);
32.1753 + break;
32.1754 + }
32.1755 + case TK_NULL: {
32.1756 + sqlite3VdbeAddOp(v, OP_Null, 0, 0);
32.1757 + break;
32.1758 + }
32.1759 +#ifndef SQLITE_OMIT_BLOB_LITERAL
32.1760 + case TK_BLOB: {
32.1761 + int n;
32.1762 + const char *z;
32.1763 + assert( TK_BLOB==OP_HexBlob );
32.1764 + n = pExpr->token.n - 3;
32.1765 + z = (char*)pExpr->token.z + 2;
32.1766 + assert( n>=0 );
32.1767 + if( n==0 ){
32.1768 + z = "";
32.1769 + }
32.1770 + sqlite3VdbeOp3(v, op, 0, 0, z, n);
32.1771 + break;
32.1772 + }
32.1773 +#endif
32.1774 + case TK_VARIABLE: {
32.1775 + sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
32.1776 + if( pExpr->token.n>1 ){
32.1777 + sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n);
32.1778 + }
32.1779 + break;
32.1780 + }
32.1781 + case TK_REGISTER: {
32.1782 + sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
32.1783 + break;
32.1784 + }
32.1785 +#ifndef SQLITE_OMIT_CAST
32.1786 + case TK_CAST: {
32.1787 + /* Expressions of the form: CAST(pLeft AS token) */
32.1788 + int aff, to_op;
32.1789 + sqlite3ExprCode(pParse, pExpr->pLeft);
32.1790 + aff = sqlite3AffinityType(&pExpr->token);
32.1791 + to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
32.1792 + assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
32.1793 + assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
32.1794 + assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
32.1795 + assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
32.1796 + assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
32.1797 + sqlite3VdbeAddOp(v, to_op, 0, 0);
32.1798 + stackChng = 0;
32.1799 + break;
32.1800 + }
32.1801 +#endif /* SQLITE_OMIT_CAST */
32.1802 + case TK_LT:
32.1803 + case TK_LE:
32.1804 + case TK_GT:
32.1805 + case TK_GE:
32.1806 + case TK_NE:
32.1807 + case TK_EQ: {
32.1808 + assert( TK_LT==OP_Lt );
32.1809 + assert( TK_LE==OP_Le );
32.1810 + assert( TK_GT==OP_Gt );
32.1811 + assert( TK_GE==OP_Ge );
32.1812 + assert( TK_EQ==OP_Eq );
32.1813 + assert( TK_NE==OP_Ne );
32.1814 + sqlite3ExprCode(pParse, pExpr->pLeft);
32.1815 + sqlite3ExprCode(pParse, pExpr->pRight);
32.1816 + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
32.1817 + stackChng = -1;
32.1818 + break;
32.1819 + }
32.1820 + case TK_AND:
32.1821 + case TK_OR:
32.1822 + case TK_PLUS:
32.1823 + case TK_STAR:
32.1824 + case TK_MINUS:
32.1825 + case TK_REM:
32.1826 + case TK_BITAND:
32.1827 + case TK_BITOR:
32.1828 + case TK_SLASH:
32.1829 + case TK_LSHIFT:
32.1830 + case TK_RSHIFT:
32.1831 + case TK_CONCAT: {
32.1832 + assert( TK_AND==OP_And );
32.1833 + assert( TK_OR==OP_Or );
32.1834 + assert( TK_PLUS==OP_Add );
32.1835 + assert( TK_MINUS==OP_Subtract );
32.1836 + assert( TK_REM==OP_Remainder );
32.1837 + assert( TK_BITAND==OP_BitAnd );
32.1838 + assert( TK_BITOR==OP_BitOr );
32.1839 + assert( TK_SLASH==OP_Divide );
32.1840 + assert( TK_LSHIFT==OP_ShiftLeft );
32.1841 + assert( TK_RSHIFT==OP_ShiftRight );
32.1842 + assert( TK_CONCAT==OP_Concat );
32.1843 + sqlite3ExprCode(pParse, pExpr->pLeft);
32.1844 + sqlite3ExprCode(pParse, pExpr->pRight);
32.1845 + sqlite3VdbeAddOp(v, op, 0, 0);
32.1846 + stackChng = -1;
32.1847 + break;
32.1848 + }
32.1849 + case TK_UMINUS: {
32.1850 + Expr *pLeft = pExpr->pLeft;
32.1851 + assert( pLeft );
32.1852 + if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
32.1853 + Token *p = &pLeft->token;
32.1854 + char *z = sqlite3MPrintf("-%.*s", p->n, p->z);
32.1855 + if( pLeft->op==TK_FLOAT ){
32.1856 + sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
32.1857 + }else{
32.1858 + codeInteger(v, z, p->n+1);
32.1859 + }
32.1860 + sqliteFree(z);
32.1861 + break;
32.1862 + }
32.1863 + /* Fall through into TK_NOT */
32.1864 + }
32.1865 + case TK_BITNOT:
32.1866 + case TK_NOT: {
32.1867 + assert( TK_BITNOT==OP_BitNot );
32.1868 + assert( TK_NOT==OP_Not );
32.1869 + sqlite3ExprCode(pParse, pExpr->pLeft);
32.1870 + sqlite3VdbeAddOp(v, op, 0, 0);
32.1871 + stackChng = 0;
32.1872 + break;
32.1873 + }
32.1874 + case TK_ISNULL:
32.1875 + case TK_NOTNULL: {
32.1876 + int dest;
32.1877 + assert( TK_ISNULL==OP_IsNull );
32.1878 + assert( TK_NOTNULL==OP_NotNull );
32.1879 + sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
32.1880 + sqlite3ExprCode(pParse, pExpr->pLeft);
32.1881 + dest = sqlite3VdbeCurrentAddr(v) + 2;
32.1882 + sqlite3VdbeAddOp(v, op, 1, dest);
32.1883 + sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
32.1884 + stackChng = 0;
32.1885 + break;
32.1886 + }
32.1887 + case TK_AGG_FUNCTION: {
32.1888 + AggInfo *pInfo = pExpr->pAggInfo;
32.1889 + if( pInfo==0 ){
32.1890 + sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
32.1891 + &pExpr->span);
32.1892 + }else{
32.1893 + sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
32.1894 + }
32.1895 + break;
32.1896 + }
32.1897 + case TK_CONST_FUNC:
32.1898 + case TK_FUNCTION: {
32.1899 + ExprList *pList = pExpr->pList;
32.1900 + int nExpr = pList ? pList->nExpr : 0;
32.1901 + FuncDef *pDef;
32.1902 + int nId;
32.1903 + const char *zId;
32.1904 + int constMask = 0;
32.1905 + int i;
32.1906 + u8 enc = ENC(pParse->db);
32.1907 + CollSeq *pColl = 0;
32.1908 + zId = (char*)pExpr->token.z;
32.1909 + nId = pExpr->token.n;
32.1910 + pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
32.1911 + assert( pDef!=0 );
32.1912 + nExpr = sqlite3ExprCodeExprList(pParse, pList);
32.1913 +#ifndef SQLITE_OMIT_VIRTUALTABLE
32.1914 + /* Possibly overload the function if the first argument is
32.1915 + ** a virtual table column.
32.1916 + **
32.1917 + ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
32.1918 + ** second argument, not the first, as the argument to test to
32.1919 + ** see if it is a column in a virtual table. This is done because
32.1920 + ** the left operand of infix functions (the operand we want to
32.1921 + ** control overloading) ends up as the second argument to the
32.1922 + ** function. The expression "A glob B" is equivalent to
32.1923 + ** "glob(B,A). We want to use the A in "A glob B" to test
32.1924 + ** for function overloading. But we use the B term in "glob(B,A)".
32.1925 + */
32.1926 + if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
32.1927 + pDef = sqlite3VtabOverloadFunction(pDef, nExpr, pList->a[1].pExpr);
32.1928 + }else if( nExpr>0 ){
32.1929 + pDef = sqlite3VtabOverloadFunction(pDef, nExpr, pList->a[0].pExpr);
32.1930 + }
32.1931 +#endif
32.1932 + for(i=0; i<nExpr && i<32; i++){
32.1933 + if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
32.1934 + constMask |= (1<<i);
32.1935 + }
32.1936 + if( pDef->needCollSeq && !pColl ){
32.1937 + pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
32.1938 + }
32.1939 + }
32.1940 + if( pDef->needCollSeq ){
32.1941 + if( !pColl ) pColl = pParse->db->pDfltColl;
32.1942 + sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
32.1943 + }
32.1944 + sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF);
32.1945 + stackChng = 1-nExpr;
32.1946 + break;
32.1947 + }
32.1948 +#ifndef SQLITE_OMIT_SUBQUERY
32.1949 + case TK_EXISTS:
32.1950 + case TK_SELECT: {
32.1951 + if( pExpr->iColumn==0 ){
32.1952 + sqlite3CodeSubselect(pParse, pExpr);
32.1953 + }
32.1954 + sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
32.1955 + VdbeComment((v, "# load subquery result"));
32.1956 + break;
32.1957 + }
32.1958 + case TK_IN: {
32.1959 + int addr;
32.1960 + char affinity;
32.1961 + int ckOffset = pParse->ckOffset;
32.1962 + sqlite3CodeSubselect(pParse, pExpr);
32.1963 +
32.1964 + /* Figure out the affinity to use to create a key from the results
32.1965 + ** of the expression. affinityStr stores a static string suitable for
32.1966 + ** P3 of OP_MakeRecord.
32.1967 + */
32.1968 + affinity = comparisonAffinity(pExpr);
32.1969 +
32.1970 + sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
32.1971 + pParse->ckOffset = (ckOffset ? (ckOffset+1) : 0);
32.1972 +
32.1973 + /* Code the <expr> from "<expr> IN (...)". The temporary table
32.1974 + ** pExpr->iTable contains the values that make up the (...) set.
32.1975 + */
32.1976 + sqlite3ExprCode(pParse, pExpr->pLeft);
32.1977 + addr = sqlite3VdbeCurrentAddr(v);
32.1978 + sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4); /* addr + 0 */
32.1979 + sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
32.1980 + sqlite3VdbeAddOp(v, OP_Null, 0, 0);
32.1981 + sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
32.1982 + sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1); /* addr + 4 */
32.1983 + sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
32.1984 + sqlite3VdbeAddOp(v, OP_AddImm, -1, 0); /* addr + 6 */
32.1985 +
32.1986 + break;
32.1987 + }
32.1988 +#endif
32.1989 + case TK_BETWEEN: {
32.1990 + Expr *pLeft = pExpr->pLeft;
32.1991 + struct ExprList_item *pLItem = pExpr->pList->a;
32.1992 + Expr *pRight = pLItem->pExpr;
32.1993 + sqlite3ExprCode(pParse, pLeft);
32.1994 + sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
32.1995 + sqlite3ExprCode(pParse, pRight);
32.1996 + codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
32.1997 + sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
32.1998 + pLItem++;
32.1999 + pRight = pLItem->pExpr;
32.2000 + sqlite3ExprCode(pParse, pRight);
32.2001 + codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
32.2002 + sqlite3VdbeAddOp(v, OP_And, 0, 0);
32.2003 + break;
32.2004 + }
32.2005 + case TK_UPLUS: {
32.2006 + sqlite3ExprCode(pParse, pExpr->pLeft);
32.2007 + stackChng = 0;
32.2008 + break;
32.2009 + }
32.2010 + case TK_CASE: {
32.2011 + int expr_end_label;
32.2012 + int jumpInst;
32.2013 + int nExpr;
32.2014 + int i;
32.2015 + ExprList *pEList;
32.2016 + struct ExprList_item *aListelem;
32.2017 +
32.2018 + assert(pExpr->pList);
32.2019 + assert((pExpr->pList->nExpr % 2) == 0);
32.2020 + assert(pExpr->pList->nExpr > 0);
32.2021 + pEList = pExpr->pList;
32.2022 + aListelem = pEList->a;
32.2023 + nExpr = pEList->nExpr;
32.2024 + expr_end_label = sqlite3VdbeMakeLabel(v);
32.2025 + if( pExpr->pLeft ){
32.2026 + sqlite3ExprCode(pParse, pExpr->pLeft);
32.2027 + }
32.2028 + for(i=0; i<nExpr; i=i+2){
32.2029 + sqlite3ExprCode(pParse, aListelem[i].pExpr);
32.2030 + if( pExpr->pLeft ){
32.2031 + sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
32.2032 + jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
32.2033 + OP_Ne, 0, 1);
32.2034 + sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
32.2035 + }else{
32.2036 + jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
32.2037 + }
32.2038 + sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
32.2039 + sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
32.2040 + sqlite3VdbeJumpHere(v, jumpInst);
32.2041 + }
32.2042 + if( pExpr->pLeft ){
32.2043 + sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
32.2044 + }
32.2045 + if( pExpr->pRight ){
32.2046 + sqlite3ExprCode(pParse, pExpr->pRight);
32.2047 + }else{
32.2048 + sqlite3VdbeAddOp(v, OP_Null, 0, 0);
32.2049 + }
32.2050 + sqlite3VdbeResolveLabel(v, expr_end_label);
32.2051 + break;
32.2052 + }
32.2053 +#ifndef SQLITE_OMIT_TRIGGER
32.2054 + case TK_RAISE: {
32.2055 + if( !pParse->trigStack ){
32.2056 + sqlite3ErrorMsg(pParse,
32.2057 + "RAISE() may only be used within a trigger-program");
32.2058 + return;
32.2059 + }
32.2060 + if( pExpr->iColumn!=OE_Ignore ){
32.2061 + assert( pExpr->iColumn==OE_Rollback ||
32.2062 + pExpr->iColumn == OE_Abort ||
32.2063 + pExpr->iColumn == OE_Fail );
32.2064 + sqlite3DequoteExpr(pExpr);
32.2065 + sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
32.2066 + (char*)pExpr->token.z, pExpr->token.n);
32.2067 + } else {
32.2068 + assert( pExpr->iColumn == OE_Ignore );
32.2069 + sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
32.2070 + sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
32.2071 + VdbeComment((v, "# raise(IGNORE)"));
32.2072 + }
32.2073 + stackChng = 0;
32.2074 + break;
32.2075 + }
32.2076 +#endif
32.2077 + }
32.2078 +
32.2079 + if( pParse->ckOffset ){
32.2080 + pParse->ckOffset += stackChng;
32.2081 + assert( pParse->ckOffset );
32.2082 + }
32.2083 +}
32.2084 +
32.2085 +#ifndef SQLITE_OMIT_TRIGGER
32.2086 +/*
32.2087 +** Generate code that evalutes the given expression and leaves the result
32.2088 +** on the stack. See also sqlite3ExprCode().
32.2089 +**
32.2090 +** This routine might also cache the result and modify the pExpr tree
32.2091 +** so that it will make use of the cached result on subsequent evaluations
32.2092 +** rather than evaluate the whole expression again. Trivial expressions are
32.2093 +** not cached. If the expression is cached, its result is stored in a
32.2094 +** memory location.
32.2095 +*/
32.2096 +void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
32.2097 + Vdbe *v = pParse->pVdbe;
32.2098 + int iMem;
32.2099 + int addr1, addr2;
32.2100 + if( v==0 ) return;
32.2101 + addr1 = sqlite3VdbeCurrentAddr(v);
32.2102 + sqlite3ExprCode(pParse, pExpr);
32.2103 + addr2 = sqlite3VdbeCurrentAddr(v);
32.2104 + if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){
32.2105 + iMem = pExpr->iTable = pParse->nMem++;
32.2106 + sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
32.2107 + pExpr->op = TK_REGISTER;
32.2108 + }
32.2109 +}
32.2110 +#endif
32.2111 +
32.2112 +/*
32.2113 +** Generate code that pushes the value of every element of the given
32.2114 +** expression list onto the stack.
32.2115 +**
32.2116 +** Return the number of elements pushed onto the stack.
32.2117 +*/
32.2118 +int sqlite3ExprCodeExprList(
32.2119 + Parse *pParse, /* Parsing context */
32.2120 + ExprList *pList /* The expression list to be coded */
32.2121 +){
32.2122 + struct ExprList_item *pItem;
32.2123 + int i, n;
32.2124 + if( pList==0 ) return 0;
32.2125 + n = pList->nExpr;
32.2126 + for(pItem=pList->a, i=n; i>0; i--, pItem++){
32.2127 + sqlite3ExprCode(pParse, pItem->pExpr);
32.2128 + }
32.2129 + return n;
32.2130 +}
32.2131 +
32.2132 +/*
32.2133 +** Generate code for a boolean expression such that a jump is made
32.2134 +** to the label "dest" if the expression is true but execution
32.2135 +** continues straight thru if the expression is false.
32.2136 +**
32.2137 +** If the expression evaluates to NULL (neither true nor false), then
32.2138 +** take the jump if the jumpIfNull flag is true.
32.2139 +**
32.2140 +** This code depends on the fact that certain token values (ex: TK_EQ)
32.2141 +** are the same as opcode values (ex: OP_Eq) that implement the corresponding
32.2142 +** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
32.2143 +** the make process cause these values to align. Assert()s in the code
32.2144 +** below verify that the numbers are aligned correctly.
32.2145 +*/
32.2146 +void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
32.2147 + Vdbe *v = pParse->pVdbe;
32.2148 + int op = 0;
32.2149 + int ckOffset = pParse->ckOffset;
32.2150 + if( v==0 || pExpr==0 ) return;
32.2151 + op = pExpr->op;
32.2152 + switch( op ){
32.2153 + case TK_AND: {
32.2154 + int d2 = sqlite3VdbeMakeLabel(v);
32.2155 + sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
32.2156 + sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
32.2157 + sqlite3VdbeResolveLabel(v, d2);
32.2158 + break;
32.2159 + }
32.2160 + case TK_OR: {
32.2161 + sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
32.2162 + sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
32.2163 + break;
32.2164 + }
32.2165 + case TK_NOT: {
32.2166 + sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
32.2167 + break;
32.2168 + }
32.2169 + case TK_LT:
32.2170 + case TK_LE:
32.2171 + case TK_GT:
32.2172 + case TK_GE:
32.2173 + case TK_NE:
32.2174 + case TK_EQ: {
32.2175 + assert( TK_LT==OP_Lt );
32.2176 + assert( TK_LE==OP_Le );
32.2177 + assert( TK_GT==OP_Gt );
32.2178 + assert( TK_GE==OP_Ge );
32.2179 + assert( TK_EQ==OP_Eq );
32.2180 + assert( TK_NE==OP_Ne );
32.2181 + sqlite3ExprCode(pParse, pExpr->pLeft);
32.2182 + sqlite3ExprCode(pParse, pExpr->pRight);
32.2183 + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
32.2184 + break;
32.2185 + }
32.2186 + case TK_ISNULL:
32.2187 + case TK_NOTNULL: {
32.2188 + assert( TK_ISNULL==OP_IsNull );
32.2189 + assert( TK_NOTNULL==OP_NotNull );
32.2190 + sqlite3ExprCode(pParse, pExpr->pLeft);
32.2191 + sqlite3VdbeAddOp(v, op, 1, dest);
32.2192 + break;
32.2193 + }
32.2194 + case TK_BETWEEN: {
32.2195 + /* The expression "x BETWEEN y AND z" is implemented as:
32.2196 + **
32.2197 + ** 1 IF (x < y) GOTO 3
32.2198 + ** 2 IF (x <= z) GOTO <dest>
32.2199 + ** 3 ...
32.2200 + */
32.2201 + int addr;
32.2202 + Expr *pLeft = pExpr->pLeft;
32.2203 + Expr *pRight = pExpr->pList->a[0].pExpr;
32.2204 + sqlite3ExprCode(pParse, pLeft);
32.2205 + sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
32.2206 + sqlite3ExprCode(pParse, pRight);
32.2207 + addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
32.2208 +
32.2209 + pRight = pExpr->pList->a[1].pExpr;
32.2210 + sqlite3ExprCode(pParse, pRight);
32.2211 + codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
32.2212 +
32.2213 + sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
32.2214 + sqlite3VdbeJumpHere(v, addr);
32.2215 + sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
32.2216 + break;
32.2217 + }
32.2218 + default: {
32.2219 + sqlite3ExprCode(pParse, pExpr);
32.2220 + sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
32.2221 + break;
32.2222 + }
32.2223 + }
32.2224 + pParse->ckOffset = ckOffset;
32.2225 +}
32.2226 +
32.2227 +/*
32.2228 +** Generate code for a boolean expression such that a jump is made
32.2229 +** to the label "dest" if the expression is false but execution
32.2230 +** continues straight thru if the expression is true.
32.2231 +**
32.2232 +** If the expression evaluates to NULL (neither true nor false) then
32.2233 +** jump if jumpIfNull is true or fall through if jumpIfNull is false.
32.2234 +*/
32.2235 +void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
32.2236 + Vdbe *v = pParse->pVdbe;
32.2237 + int op = 0;
32.2238 + int ckOffset = pParse->ckOffset;
32.2239 + if( v==0 || pExpr==0 ) return;
32.2240 +
32.2241 + /* The value of pExpr->op and op are related as follows:
32.2242 + **
32.2243 + ** pExpr->op op
32.2244 + ** --------- ----------
32.2245 + ** TK_ISNULL OP_NotNull
32.2246 + ** TK_NOTNULL OP_IsNull
32.2247 + ** TK_NE OP_Eq
32.2248 + ** TK_EQ OP_Ne
32.2249 + ** TK_GT OP_Le
32.2250 + ** TK_LE OP_Gt
32.2251 + ** TK_GE OP_Lt
32.2252 + ** TK_LT OP_Ge
32.2253 + **
32.2254 + ** For other values of pExpr->op, op is undefined and unused.
32.2255 + ** The value of TK_ and OP_ constants are arranged such that we
32.2256 + ** can compute the mapping above using the following expression.
32.2257 + ** Assert()s verify that the computation is correct.
32.2258 + */
32.2259 + op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
32.2260 +
32.2261 + /* Verify correct alignment of TK_ and OP_ constants
32.2262 + */
32.2263 + assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
32.2264 + assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
32.2265 + assert( pExpr->op!=TK_NE || op==OP_Eq );
32.2266 + assert( pExpr->op!=TK_EQ || op==OP_Ne );
32.2267 + assert( pExpr->op!=TK_LT || op==OP_Ge );
32.2268 + assert( pExpr->op!=TK_LE || op==OP_Gt );
32.2269 + assert( pExpr->op!=TK_GT || op==OP_Le );
32.2270 + assert( pExpr->op!=TK_GE || op==OP_Lt );
32.2271 +
32.2272 + switch( pExpr->op ){
32.2273 + case TK_AND: {
32.2274 + sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
32.2275 + sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
32.2276 + break;
32.2277 + }
32.2278 + case TK_OR: {
32.2279 + int d2 = sqlite3VdbeMakeLabel(v);
32.2280 + sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
32.2281 + sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
32.2282 + sqlite3VdbeResolveLabel(v, d2);
32.2283 + break;
32.2284 + }
32.2285 + case TK_NOT: {
32.2286 + sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
32.2287 + break;
32.2288 + }
32.2289 + case TK_LT:
32.2290 + case TK_LE:
32.2291 + case TK_GT:
32.2292 + case TK_GE:
32.2293 + case TK_NE:
32.2294 + case TK_EQ: {
32.2295 + sqlite3ExprCode(pParse, pExpr->pLeft);
32.2296 + sqlite3ExprCode(pParse, pExpr->pRight);
32.2297 + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
32.2298 + break;
32.2299 + }
32.2300 + case TK_ISNULL:
32.2301 + case TK_NOTNULL: {
32.2302 + sqlite3ExprCode(pParse, pExpr->pLeft);
32.2303 + sqlite3VdbeAddOp(v, op, 1, dest);
32.2304 + break;
32.2305 + }
32.2306 + case TK_BETWEEN: {
32.2307 + /* The expression is "x BETWEEN y AND z". It is implemented as:
32.2308 + **
32.2309 + ** 1 IF (x >= y) GOTO 3
32.2310 + ** 2 GOTO <dest>
32.2311 + ** 3 IF (x > z) GOTO <dest>
32.2312 + */
32.2313 + int addr;
32.2314 + Expr *pLeft = pExpr->pLeft;
32.2315 + Expr *pRight = pExpr->pList->a[0].pExpr;
32.2316 + sqlite3ExprCode(pParse, pLeft);
32.2317 + sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
32.2318 + sqlite3ExprCode(pParse, pRight);
32.2319 + addr = sqlite3VdbeCurrentAddr(v);
32.2320 + codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
32.2321 +
32.2322 + sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
32.2323 + sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
32.2324 + pRight = pExpr->pList->a[1].pExpr;
32.2325 + sqlite3ExprCode(pParse, pRight);
32.2326 + codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
32.2327 + break;
32.2328 + }
32.2329 + default: {
32.2330 + sqlite3ExprCode(pParse, pExpr);
32.2331 + sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
32.2332 + break;
32.2333 + }
32.2334 + }
32.2335 + pParse->ckOffset = ckOffset;
32.2336 +}
32.2337 +
32.2338 +/*
32.2339 +** Do a deep comparison of two expression trees. Return TRUE (non-zero)
32.2340 +** if they are identical and return FALSE if they differ in any way.
32.2341 +**
32.2342 +** Sometimes this routine will return FALSE even if the two expressions
32.2343 +** really are equivalent. If we cannot prove that the expressions are
32.2344 +** identical, we return FALSE just to be safe. So if this routine
32.2345 +** returns false, then you do not really know for certain if the two
32.2346 +** expressions are the same. But if you get a TRUE return, then you
32.2347 +** can be sure the expressions are the same. In the places where
32.2348 +** this routine is used, it does not hurt to get an extra FALSE - that
32.2349 +** just might result in some slightly slower code. But returning
32.2350 +** an incorrect TRUE could lead to a malfunction.
32.2351 +*/
32.2352 +int sqlite3ExprCompare(Expr *pA, Expr *pB){
32.2353 + int i;
32.2354 + if( pA==0||pB==0 ){
32.2355 + return pB==pA;
32.2356 + }
32.2357 + if( pA->op!=pB->op ) return 0;
32.2358 + if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
32.2359 + if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
32.2360 + if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
32.2361 + if( pA->pList ){
32.2362 + if( pB->pList==0 ) return 0;
32.2363 + if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
32.2364 + for(i=0; i<pA->pList->nExpr; i++){
32.2365 + if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
32.2366 + return 0;
32.2367 + }
32.2368 + }
32.2369 + }else if( pB->pList ){
32.2370 + return 0;
32.2371 + }
32.2372 + if( pA->pSelect || pB->pSelect ) return 0;
32.2373 + if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
32.2374 + if( pA->op!=TK_COLUMN && pA->token.z ){
32.2375 + if( pB->token.z==0 ) return 0;
32.2376 + if( pB->token.n!=pA->token.n ) return 0;
32.2377 + if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
32.2378 + return 0;
32.2379 + }
32.2380 + }
32.2381 + return 1;
32.2382 +}
32.2383 +
32.2384 +
32.2385 +/*
32.2386 +** Add a new element to the pAggInfo->aCol[] array. Return the index of
32.2387 +** the new element. Return a negative number if malloc fails.
32.2388 +*/
32.2389 +static int addAggInfoColumn(AggInfo *pInfo){
32.2390 + int i;
32.2391 + pInfo->aCol = sqlite3ArrayAllocate(
32.2392 + pInfo->aCol,
32.2393 + sizeof(pInfo->aCol[0]),
32.2394 + 3,
32.2395 + &pInfo->nColumn,
32.2396 + &pInfo->nColumnAlloc,
32.2397 + &i
32.2398 + );
32.2399 + return i;
32.2400 +}
32.2401 +
32.2402 +/*
32.2403 +** Add a new element to the pAggInfo->aFunc[] array. Return the index of
32.2404 +** the new element. Return a negative number if malloc fails.
32.2405 +*/
32.2406 +static int addAggInfoFunc(AggInfo *pInfo){
32.2407 + int i;
32.2408 + pInfo->aFunc = sqlite3ArrayAllocate(
32.2409 + pInfo->aFunc,
32.2410 + sizeof(pInfo->aFunc[0]),
32.2411 + 3,
32.2412 + &pInfo->nFunc,
32.2413 + &pInfo->nFuncAlloc,
32.2414 + &i
32.2415 + );
32.2416 + return i;
32.2417 +}
32.2418 +
32.2419 +/*
32.2420 +** This is an xFunc for walkExprTree() used to implement
32.2421 +** sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
32.2422 +** for additional information.
32.2423 +**
32.2424 +** This routine analyzes the aggregate function at pExpr.
32.2425 +*/
32.2426 +static int analyzeAggregate(void *pArg, Expr *pExpr){
32.2427 + int i;
32.2428 + NameContext *pNC = (NameContext *)pArg;
32.2429 + Parse *pParse = pNC->pParse;
32.2430 + SrcList *pSrcList = pNC->pSrcList;
32.2431 + AggInfo *pAggInfo = pNC->pAggInfo;
32.2432 +
32.2433 +
32.2434 + switch( pExpr->op ){
32.2435 + case TK_AGG_COLUMN:
32.2436 + case TK_COLUMN: {
32.2437 + /* Check to see if the column is in one of the tables in the FROM
32.2438 + ** clause of the aggregate query */
32.2439 + if( pSrcList ){
32.2440 + struct SrcList_item *pItem = pSrcList->a;
32.2441 + for(i=0; i<pSrcList->nSrc; i++, pItem++){
32.2442 + struct AggInfo_col *pCol;
32.2443 + if( pExpr->iTable==pItem->iCursor ){
32.2444 + /* If we reach this point, it means that pExpr refers to a table
32.2445 + ** that is in the FROM clause of the aggregate query.
32.2446 + **
32.2447 + ** Make an entry for the column in pAggInfo->aCol[] if there
32.2448 + ** is not an entry there already.
32.2449 + */
32.2450 + int k;
32.2451 + pCol = pAggInfo->aCol;
32.2452 + for(k=0; k<pAggInfo->nColumn; k++, pCol++){
32.2453 + if( pCol->iTable==pExpr->iTable &&
32.2454 + pCol->iColumn==pExpr->iColumn ){
32.2455 + break;
32.2456 + }
32.2457 + }
32.2458 + if( k>=pAggInfo->nColumn && (k = addAggInfoColumn(pAggInfo))>=0 ){
32.2459 + pCol = &pAggInfo->aCol[k];
32.2460 + pCol->pTab = pExpr->pTab;
32.2461 + pCol->iTable = pExpr->iTable;
32.2462 + pCol->iColumn = pExpr->iColumn;
32.2463 + pCol->iMem = pParse->nMem++;
32.2464 + pCol->iSorterColumn = -1;
32.2465 + pCol->pExpr = pExpr;
32.2466 + if( pAggInfo->pGroupBy ){
32.2467 + int j, n;
32.2468 + ExprList *pGB = pAggInfo->pGroupBy;
32.2469 + struct ExprList_item *pTerm = pGB->a;
32.2470 + n = pGB->nExpr;
32.2471 + for(j=0; j<n; j++, pTerm++){
32.2472 + Expr *pE = pTerm->pExpr;
32.2473 + if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
32.2474 + pE->iColumn==pExpr->iColumn ){
32.2475 + pCol->iSorterColumn = j;
32.2476 + break;
32.2477 + }
32.2478 + }
32.2479 + }
32.2480 + if( pCol->iSorterColumn<0 ){
32.2481 + pCol->iSorterColumn = pAggInfo->nSortingColumn++;
32.2482 + }
32.2483 + }
32.2484 + /* There is now an entry for pExpr in pAggInfo->aCol[] (either
32.2485 + ** because it was there before or because we just created it).
32.2486 + ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
32.2487 + ** pAggInfo->aCol[] entry.
32.2488 + */
32.2489 + pExpr->pAggInfo = pAggInfo;
32.2490 + pExpr->op = TK_AGG_COLUMN;
32.2491 + pExpr->iAgg = k;
32.2492 + break;
32.2493 + } /* endif pExpr->iTable==pItem->iCursor */
32.2494 + } /* end loop over pSrcList */
32.2495 + }
32.2496 + return 1;
32.2497 + }
32.2498 + case TK_AGG_FUNCTION: {
32.2499 + /* The pNC->nDepth==0 test causes aggregate functions in subqueries
32.2500 + ** to be ignored */
32.2501 + if( pNC->nDepth==0 ){
32.2502 + /* Check to see if pExpr is a duplicate of another aggregate
32.2503 + ** function that is already in the pAggInfo structure
32.2504 + */
32.2505 + struct AggInfo_func *pItem = pAggInfo->aFunc;
32.2506 + for(i=0; i<pAggInfo->nFunc; i++, pItem++){
32.2507 + if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
32.2508 + break;
32.2509 + }
32.2510 + }
32.2511 + if( i>=pAggInfo->nFunc ){
32.2512 + /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
32.2513 + */
32.2514 + u8 enc = ENC(pParse->db);
32.2515 + i = addAggInfoFunc(pAggInfo);
32.2516 + if( i>=0 ){
32.2517 + pItem = &pAggInfo->aFunc[i];
32.2518 + pItem->pExpr = pExpr;
32.2519 + pItem->iMem = pParse->nMem++;
32.2520 + pItem->pFunc = sqlite3FindFunction(pParse->db,
32.2521 + (char*)pExpr->token.z, pExpr->token.n,
32.2522 + pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
32.2523 + if( pExpr->flags & EP_Distinct ){
32.2524 + pItem->iDistinct = pParse->nTab++;
32.2525 + }else{
32.2526 + pItem->iDistinct = -1;
32.2527 + }
32.2528 + }
32.2529 + }
32.2530 + /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
32.2531 + */
32.2532 + pExpr->iAgg = i;
32.2533 + pExpr->pAggInfo = pAggInfo;
32.2534 + return 1;
32.2535 + }
32.2536 + }
32.2537 + }
32.2538 +
32.2539 + /* Recursively walk subqueries looking for TK_COLUMN nodes that need
32.2540 + ** to be changed to TK_AGG_COLUMN. But increment nDepth so that
32.2541 + ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
32.2542 + */
32.2543 + if( pExpr->pSelect ){
32.2544 + pNC->nDepth++;
32.2545 + walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
32.2546 + pNC->nDepth--;
32.2547 + }
32.2548 + return 0;
32.2549 +}
32.2550 +
32.2551 +/*
32.2552 +** Analyze the given expression looking for aggregate functions and
32.2553 +** for variables that need to be added to the pParse->aAgg[] array.
32.2554 +** Make additional entries to the pParse->aAgg[] array as necessary.
32.2555 +**
32.2556 +** This routine should only be called after the expression has been
32.2557 +** analyzed by sqlite3ExprResolveNames().
32.2558 +**
32.2559 +** If errors are seen, leave an error message in zErrMsg and return
32.2560 +** the number of errors.
32.2561 +*/
32.2562 +int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
32.2563 + int nErr = pNC->pParse->nErr;
32.2564 + walkExprTree(pExpr, analyzeAggregate, pNC);
32.2565 + return pNC->pParse->nErr - nErr;
32.2566 +}
32.2567 +
32.2568 +/*
32.2569 +** Call sqlite3ExprAnalyzeAggregates() for every expression in an
32.2570 +** expression list. Return the number of errors.
32.2571 +**
32.2572 +** If an error is found, the analysis is cut short.
32.2573 +*/
32.2574 +int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
32.2575 + struct ExprList_item *pItem;
32.2576 + int i;
32.2577 + int nErr = 0;
32.2578 + if( pList ){
32.2579 + for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){
32.2580 + nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
32.2581 + }
32.2582 + }
32.2583 + return nErr;
32.2584 +}
33.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
33.2 +++ b/extensions/sqlite/sqlite-source/func.c Sun Jul 29 01:15:31 2007 +0000
33.3 @@ -0,0 +1,1493 @@
33.4 +/*
33.5 +** 2002 February 23
33.6 +**
33.7 +** The author disclaims copyright to this source code. In place of
33.8 +** a legal notice, here is a blessing:
33.9 +**
33.10 +** May you do good and not evil.
33.11 +** May you find forgiveness for yourself and forgive others.
33.12 +** May you share freely, never taking more than you give.
33.13 +**
33.14 +*************************************************************************
33.15 +** This file contains the C functions that implement various SQL
33.16 +** functions of SQLite.
33.17 +**
33.18 +** There is only one exported symbol in this file - the function
33.19 +** sqliteRegisterBuildinFunctions() found at the bottom of the file.
33.20 +** All other code has file scope.
33.21 +**
33.22 +** $Id$
33.23 +*/
33.24 +#include "sqliteInt.h"
33.25 +#include <ctype.h>
33.26 +/* #include <math.h> */
33.27 +#include <stdlib.h>
33.28 +#include <assert.h>
33.29 +#include "vdbeInt.h"
33.30 +#include "os.h"
33.31 +
33.32 +/*
33.33 +** Return the collating function associated with a function.
33.34 +*/
33.35 +static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
33.36 + return context->pColl;
33.37 +}
33.38 +
33.39 +/*
33.40 +** Implementation of the non-aggregate min() and max() functions
33.41 +*/
33.42 +static void minmaxFunc(
33.43 + sqlite3_context *context,
33.44 + int argc,
33.45 + sqlite3_value **argv
33.46 +){
33.47 + int i;
33.48 + int mask; /* 0 for min() or 0xffffffff for max() */
33.49 + int iBest;
33.50 + CollSeq *pColl;
33.51 +
33.52 + if( argc==0 ) return;
33.53 + mask = sqlite3_user_data(context)==0 ? 0 : -1;
33.54 + pColl = sqlite3GetFuncCollSeq(context);
33.55 + assert( pColl );
33.56 + assert( mask==-1 || mask==0 );
33.57 + iBest = 0;
33.58 + if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
33.59 + for(i=1; i<argc; i++){
33.60 + if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
33.61 + if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
33.62 + iBest = i;
33.63 + }
33.64 + }
33.65 + sqlite3_result_value(context, argv[iBest]);
33.66 +}
33.67 +
33.68 +/*
33.69 +** Return the type of the argument.
33.70 +*/
33.71 +static void typeofFunc(
33.72 + sqlite3_context *context,
33.73 + int argc,
33.74 + sqlite3_value **argv
33.75 +){
33.76 + const char *z = 0;
33.77 + switch( sqlite3_value_type(argv[0]) ){
33.78 + case SQLITE_NULL: z = "null"; break;
33.79 + case SQLITE_INTEGER: z = "integer"; break;
33.80 + case SQLITE_TEXT: z = "text"; break;
33.81 + case SQLITE_FLOAT: z = "real"; break;
33.82 + case SQLITE_BLOB: z = "blob"; break;
33.83 + }
33.84 + sqlite3_result_text(context, z, -1, SQLITE_STATIC);
33.85 +}
33.86 +
33.87 +
33.88 +/*
33.89 +** Implementation of the length() function
33.90 +*/
33.91 +static void lengthFunc(
33.92 + sqlite3_context *context,
33.93 + int argc,
33.94 + sqlite3_value **argv
33.95 +){
33.96 + int len;
33.97 +
33.98 + assert( argc==1 );
33.99 + switch( sqlite3_value_type(argv[0]) ){
33.100 + case SQLITE_BLOB:
33.101 + case SQLITE_INTEGER:
33.102 + case SQLITE_FLOAT: {
33.103 + sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
33.104 + break;
33.105 + }
33.106 + case SQLITE_TEXT: {
33.107 + const unsigned char *z = sqlite3_value_text(argv[0]);
33.108 + if( z==0 ) return;
33.109 + len = 0;
33.110 + while( *z ){
33.111 + len++;
33.112 + SQLITE_SKIP_UTF8(z);
33.113 + }
33.114 + sqlite3_result_int(context, len);
33.115 + break;
33.116 + }
33.117 + default: {
33.118 + sqlite3_result_null(context);
33.119 + break;
33.120 + }
33.121 + }
33.122 +}
33.123 +
33.124 +/*
33.125 +** Implementation of the abs() function
33.126 +*/
33.127 +static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
33.128 + assert( argc==1 );
33.129 + switch( sqlite3_value_type(argv[0]) ){
33.130 + case SQLITE_INTEGER: {
33.131 + i64 iVal = sqlite3_value_int64(argv[0]);
33.132 + if( iVal<0 ){
33.133 + if( (iVal<<1)==0 ){
33.134 + sqlite3_result_error(context, "integer overflow", -1);
33.135 + return;
33.136 + }
33.137 + iVal = -iVal;
33.138 + }
33.139 + sqlite3_result_int64(context, iVal);
33.140 + break;
33.141 + }
33.142 + case SQLITE_NULL: {
33.143 + sqlite3_result_null(context);
33.144 + break;
33.145 + }
33.146 + default: {
33.147 + double rVal = sqlite3_value_double(argv[0]);
33.148 + if( rVal<0 ) rVal = -rVal;
33.149 + sqlite3_result_double(context, rVal);
33.150 + break;
33.151 + }
33.152 + }
33.153 +}
33.154 +
33.155 +/*
33.156 +** Implementation of the substr() function.
33.157 +**
33.158 +** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
33.159 +** p1 is 1-indexed. So substr(x,1,1) returns the first character
33.160 +** of x. If x is text, then we actually count UTF-8 characters.
33.161 +** If x is a blob, then we count bytes.
33.162 +**
33.163 +** If p1 is negative, then we begin abs(p1) from the end of x[].
33.164 +*/
33.165 +static void substrFunc(
33.166 + sqlite3_context *context,
33.167 + int argc,
33.168 + sqlite3_value **argv
33.169 +){
33.170 + const unsigned char *z;
33.171 + const unsigned char *z2;
33.172 + int len;
33.173 + int p0type;
33.174 + i64 p1, p2;
33.175 +
33.176 + assert( argc==3 );
33.177 + p0type = sqlite3_value_type(argv[0]);
33.178 + if( p0type==SQLITE_BLOB ){
33.179 + len = sqlite3_value_bytes(argv[0]);
33.180 + z = sqlite3_value_blob(argv[0]);
33.181 + if( z==0 ) return;
33.182 + assert( len==sqlite3_value_bytes(argv[0]) );
33.183 + }else{
33.184 + z = sqlite3_value_text(argv[0]);
33.185 + if( z==0 ) return;
33.186 + len = 0;
33.187 + for(z2=z; *z2; len++){
33.188 + SQLITE_SKIP_UTF8(z2);
33.189 + }
33.190 + }
33.191 + p1 = sqlite3_value_int(argv[1]);
33.192 + p2 = sqlite3_value_int(argv[2]);
33.193 + if( p1<0 ){
33.194 + p1 += len;
33.195 + if( p1<0 ){
33.196 + p2 += p1;
33.197 + p1 = 0;
33.198 + }
33.199 + }else if( p1>0 ){
33.200 + p1--;
33.201 + }
33.202 + if( p1+p2>len ){
33.203 + p2 = len-p1;
33.204 + }
33.205 + if( p0type!=SQLITE_BLOB ){
33.206 + while( *z && p1 ){
33.207 + SQLITE_SKIP_UTF8(z);
33.208 + p1--;
33.209 + }
33.210 + for(z2=z; *z2 && p2; p2--){
33.211 + SQLITE_SKIP_UTF8(z2);
33.212 + }
33.213 + sqlite3_result_text(context, (char*)z, z2-z, SQLITE_TRANSIENT);
33.214 + }else{
33.215 + if( p2<0 ) p2 = 0;
33.216 + sqlite3_result_blob(context, (char*)&z[p1], p2, SQLITE_TRANSIENT);
33.217 + }
33.218 +}
33.219 +
33.220 +/*
33.221 +** Implementation of the round() function
33.222 +*/
33.223 +static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
33.224 + int n = 0;
33.225 + double r;
33.226 + char zBuf[500]; /* larger than the %f representation of the largest double */
33.227 + assert( argc==1 || argc==2 );
33.228 + if( argc==2 ){
33.229 + if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
33.230 + n = sqlite3_value_int(argv[1]);
33.231 + if( n>30 ) n = 30;
33.232 + if( n<0 ) n = 0;
33.233 + }
33.234 + if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
33.235 + r = sqlite3_value_double(argv[0]);
33.236 + sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
33.237 + sqlite3AtoF(zBuf, &r);
33.238 + sqlite3_result_double(context, r);
33.239 +}
33.240 +
33.241 +/*
33.242 +** Implementation of the upper() and lower() SQL functions.
33.243 +*/
33.244 +static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
33.245 + char *z1;
33.246 + const char *z2;
33.247 + int i, n;
33.248 + if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
33.249 + z2 = (char*)sqlite3_value_text(argv[0]);
33.250 + n = sqlite3_value_bytes(argv[0]);
33.251 + /* Verify that the call to _bytes() does not invalidate the _text() pointer */
33.252 + assert( z2==(char*)sqlite3_value_text(argv[0]) );
33.253 + if( z2 ){
33.254 + z1 = sqlite3_malloc(n+1);
33.255 + if( z1 ){
33.256 + memcpy(z1, z2, n+1);
33.257 + for(i=0; z1[i]; i++){
33.258 + z1[i] = toupper(z1[i]);
33.259 + }
33.260 + sqlite3_result_text(context, z1, -1, sqlite3_free);
33.261 + }
33.262 + }
33.263 +}
33.264 +static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
33.265 + char *z1;
33.266 + const char *z2;
33.267 + int i, n;
33.268 + if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
33.269 + z2 = (char*)sqlite3_value_text(argv[0]);
33.270 + n = sqlite3_value_bytes(argv[0]);
33.271 + /* Verify that the call to _bytes() does not invalidate the _text() pointer */
33.272 + assert( z2==(char*)sqlite3_value_text(argv[0]) );
33.273 + if( z2 ){
33.274 + z1 = sqlite3_malloc(n+1);
33.275 + if( z1 ){
33.276 + memcpy(z1, z2, n+1);
33.277 + for(i=0; z1[i]; i++){
33.278 + z1[i] = tolower(z1[i]);
33.279 + }
33.280 + sqlite3_result_text(context, z1, -1, sqlite3_free);
33.281 + }
33.282 + }
33.283 +}
33.284 +
33.285 +/*
33.286 +** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
33.287 +** All three do the same thing. They return the first non-NULL
33.288 +** argument.
33.289 +*/
33.290 +static void ifnullFunc(
33.291 + sqlite3_context *context,
33.292 + int argc,
33.293 + sqlite3_value **argv
33.294 +){
33.295 + int i;
33.296 + for(i=0; i<argc; i++){
33.297 + if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
33.298 + sqlite3_result_value(context, argv[i]);
33.299 + break;
33.300 + }
33.301 + }
33.302 +}
33.303 +
33.304 +/*
33.305 +** Implementation of random(). Return a random integer.
33.306 +*/
33.307 +static void randomFunc(
33.308 + sqlite3_context *context,
33.309 + int argc,
33.310 + sqlite3_value **argv
33.311 +){
33.312 + sqlite_int64 r;
33.313 + sqlite3Randomness(sizeof(r), &r);
33.314 + if( (r<<1)==0 ) r = 0; /* Prevent 0x8000.... as the result so that we */
33.315 + /* can always do abs() of the result */
33.316 + sqlite3_result_int64(context, r);
33.317 +}
33.318 +
33.319 +/*
33.320 +** Implementation of randomblob(N). Return a random blob
33.321 +** that is N bytes long.
33.322 +*/
33.323 +static void randomBlob(
33.324 + sqlite3_context *context,
33.325 + int argc,
33.326 + sqlite3_value **argv
33.327 +){
33.328 + int n;
33.329 + unsigned char *p;
33.330 + assert( argc==1 );
33.331 + n = sqlite3_value_int(argv[0]);
33.332 + if( n<1 ){
33.333 + n = 1;
33.334 + }
33.335 + if( n>SQLITE_MAX_LENGTH ){
33.336 + sqlite3_result_error_toobig(context);
33.337 + return;
33.338 + }
33.339 + p = sqliteMalloc(n);
33.340 + if( p ){
33.341 + sqlite3Randomness(n, p);
33.342 + sqlite3_result_blob(context, (char*)p, n, sqlite3FreeX);
33.343 + }
33.344 +}
33.345 +
33.346 +/*
33.347 +** Implementation of the last_insert_rowid() SQL function. The return
33.348 +** value is the same as the sqlite3_last_insert_rowid() API function.
33.349 +*/
33.350 +static void last_insert_rowid(
33.351 + sqlite3_context *context,
33.352 + int arg,
33.353 + sqlite3_value **argv
33.354 +){
33.355 + sqlite3 *db = sqlite3_user_data(context);
33.356 + sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
33.357 +}
33.358 +
33.359 +/*
33.360 +** Implementation of the changes() SQL function. The return value is the
33.361 +** same as the sqlite3_changes() API function.
33.362 +*/
33.363 +static void changes(
33.364 + sqlite3_context *context,
33.365 + int arg,
33.366 + sqlite3_value **argv
33.367 +){
33.368 + sqlite3 *db = sqlite3_user_data(context);
33.369 + sqlite3_result_int(context, sqlite3_changes(db));
33.370 +}
33.371 +
33.372 +/*
33.373 +** Implementation of the total_changes() SQL function. The return value is
33.374 +** the same as the sqlite3_total_changes() API function.
33.375 +*/
33.376 +static void total_changes(
33.377 + sqlite3_context *context,
33.378 + int arg,
33.379 + sqlite3_value **argv
33.380 +){
33.381 + sqlite3 *db = sqlite3_user_data(context);
33.382 + sqlite3_result_int(context, sqlite3_total_changes(db));
33.383 +}
33.384 +
33.385 +/*
33.386 +** A structure defining how to do GLOB-style comparisons.
33.387 +*/
33.388 +struct compareInfo {
33.389 + u8 matchAll;
33.390 + u8 matchOne;
33.391 + u8 matchSet;
33.392 + u8 noCase;
33.393 +};
33.394 +
33.395 +static const struct compareInfo globInfo = { '*', '?', '[', 0 };
33.396 +/* The correct SQL-92 behavior is for the LIKE operator to ignore
33.397 +** case. Thus 'a' LIKE 'A' would be true. */
33.398 +static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
33.399 +/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
33.400 +** is case sensitive causing 'a' LIKE 'A' to be false */
33.401 +static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
33.402 +
33.403 +/*
33.404 +** Read a single UTF-8 character and return its value.
33.405 +*/
33.406 +u32 sqlite3ReadUtf8(const unsigned char *z){
33.407 + u32 c;
33.408 + SQLITE_READ_UTF8(z, c);
33.409 + return c;
33.410 +}
33.411 +
33.412 +/*
33.413 +** Compare two UTF-8 strings for equality where the first string can
33.414 +** potentially be a "glob" expression. Return true (1) if they
33.415 +** are the same and false (0) if they are different.
33.416 +**
33.417 +** Globbing rules:
33.418 +**
33.419 +** '*' Matches any sequence of zero or more characters.
33.420 +**
33.421 +** '?' Matches exactly one character.
33.422 +**
33.423 +** [...] Matches one character from the enclosed list of
33.424 +** characters.
33.425 +**
33.426 +** [^...] Matches one character not in the enclosed list.
33.427 +**
33.428 +** With the [...] and [^...] matching, a ']' character can be included
33.429 +** in the list by making it the first character after '[' or '^'. A
33.430 +** range of characters can be specified using '-'. Example:
33.431 +** "[a-z]" matches any single lower-case letter. To match a '-', make
33.432 +** it the last character in the list.
33.433 +**
33.434 +** This routine is usually quick, but can be N**2 in the worst case.
33.435 +**
33.436 +** Hints: to match '*' or '?', put them in "[]". Like this:
33.437 +**
33.438 +** abc[*]xyz Matches "abc*xyz" only
33.439 +*/
33.440 +static int patternCompare(
33.441 + const u8 *zPattern, /* The glob pattern */
33.442 + const u8 *zString, /* The string to compare against the glob */
33.443 + const struct compareInfo *pInfo, /* Information about how to do the compare */
33.444 + const int esc /* The escape character */
33.445 +){
33.446 + register int c;
33.447 + int invert;
33.448 + int seen;
33.449 + int c2;
33.450 + u8 matchOne = pInfo->matchOne;
33.451 + u8 matchAll = pInfo->matchAll;
33.452 + u8 matchSet = pInfo->matchSet;
33.453 + u8 noCase = pInfo->noCase;
33.454 + int prevEscape = 0; /* True if the previous character was 'escape' */
33.455 +
33.456 + while( (c = *zPattern)!=0 ){
33.457 + if( !prevEscape && c==matchAll ){
33.458 + while( (c=zPattern[1]) == matchAll || c == matchOne ){
33.459 + if( c==matchOne ){
33.460 + if( *zString==0 ) return 0;
33.461 + SQLITE_SKIP_UTF8(zString);
33.462 + }
33.463 + zPattern++;
33.464 + }
33.465 + if( c && esc && sqlite3ReadUtf8(&zPattern[1])==esc ){
33.466 + u8 const *zTemp = &zPattern[1];
33.467 + SQLITE_SKIP_UTF8(zTemp);
33.468 + c = *zTemp;
33.469 + }
33.470 + if( c==0 ) return 1;
33.471 + if( c==matchSet ){
33.472 + assert( esc==0 ); /* This is GLOB, not LIKE */
33.473 + while( *zString && patternCompare(&zPattern[1],zString,pInfo,esc)==0 ){
33.474 + SQLITE_SKIP_UTF8(zString);
33.475 + }
33.476 + return *zString!=0;
33.477 + }else{
33.478 + while( (c2 = *zString)!=0 ){
33.479 + if( noCase ){
33.480 + c2 = sqlite3UpperToLower[c2];
33.481 + c = sqlite3UpperToLower[c];
33.482 + while( c2 != 0 && c2 != c ){ c2 = sqlite3UpperToLower[*++zString]; }
33.483 + }else{
33.484 + while( c2 != 0 && c2 != c ){ c2 = *++zString; }
33.485 + }
33.486 + if( c2==0 ) return 0;
33.487 + if( patternCompare(&zPattern[1],zString,pInfo,esc) ) return 1;
33.488 + SQLITE_SKIP_UTF8(zString);
33.489 + }
33.490 + return 0;
33.491 + }
33.492 + }else if( !prevEscape && c==matchOne ){
33.493 + if( *zString==0 ) return 0;
33.494 + SQLITE_SKIP_UTF8(zString);
33.495 + zPattern++;
33.496 + }else if( c==matchSet ){
33.497 + int prior_c = 0;
33.498 + assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
33.499 + seen = 0;
33.500 + invert = 0;
33.501 + c = sqlite3ReadUtf8(zString);
33.502 + if( c==0 ) return 0;
33.503 + c2 = *++zPattern;
33.504 + if( c2=='^' ){ invert = 1; c2 = *++zPattern; }
33.505 + if( c2==']' ){
33.506 + if( c==']' ) seen = 1;
33.507 + c2 = *++zPattern;
33.508 + }
33.509 + while( (c2 = sqlite3ReadUtf8(zPattern))!=0 && c2!=']' ){
33.510 + if( c2=='-' && zPattern[1]!=']' && zPattern[1]!=0 && prior_c>0 ){
33.511 + zPattern++;
33.512 + c2 = sqlite3ReadUtf8(zPattern);
33.513 + if( c>=prior_c && c<=c2 ) seen = 1;
33.514 + prior_c = 0;
33.515 + }else if( c==c2 ){
33.516 + seen = 1;
33.517 + prior_c = c2;
33.518 + }else{
33.519 + prior_c = c2;
33.520 + }
33.521 + SQLITE_SKIP_UTF8(zPattern);
33.522 + }
33.523 + if( c2==0 || (seen ^ invert)==0 ) return 0;
33.524 + SQLITE_SKIP_UTF8(zString);
33.525 + zPattern++;
33.526 + }else if( esc && !prevEscape && sqlite3ReadUtf8(zPattern)==esc){
33.527 + prevEscape = 1;
33.528 + SQLITE_SKIP_UTF8(zPattern);
33.529 + }else{
33.530 + if( noCase ){
33.531 + if( sqlite3UpperToLower[c] != sqlite3UpperToLower[*zString] ) return 0;
33.532 + }else{
33.533 + if( c != *zString ) return 0;
33.534 + }
33.535 + zPattern++;
33.536 + zString++;
33.537 + prevEscape = 0;
33.538 + }
33.539 + }
33.540 + return *zString==0;
33.541 +}
33.542 +
33.543 +/*
33.544 +** Count the number of times that the LIKE operator (or GLOB which is
33.545 +** just a variation of LIKE) gets called. This is used for testing
33.546 +** only.
33.547 +*/
33.548 +#ifdef SQLITE_TEST
33.549 +int sqlite3_like_count = 0;
33.550 +#endif
33.551 +
33.552 +
33.553 +/*
33.554 +** Implementation of the like() SQL function. This function implements
33.555 +** the build-in LIKE operator. The first argument to the function is the
33.556 +** pattern and the second argument is the string. So, the SQL statements:
33.557 +**
33.558 +** A LIKE B
33.559 +**
33.560 +** is implemented as like(B,A).
33.561 +**
33.562 +** This same function (with a different compareInfo structure) computes
33.563 +** the GLOB operator.
33.564 +*/
33.565 +static void likeFunc(
33.566 + sqlite3_context *context,
33.567 + int argc,
33.568 + sqlite3_value **argv
33.569 +){
33.570 + const unsigned char *zA, *zB;
33.571 + int escape = 0;
33.572 +
33.573 + zB = sqlite3_value_text(argv[0]);
33.574 + zA = sqlite3_value_text(argv[1]);
33.575 +
33.576 + /* Limit the length of the LIKE or GLOB pattern to avoid problems
33.577 + ** of deep recursion and N*N behavior in patternCompare().
33.578 + */
33.579 + if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
33.580 + sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
33.581 + return;
33.582 + }
33.583 + assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
33.584 +
33.585 + if( argc==3 ){
33.586 + /* The escape character string must consist of a single UTF-8 character.
33.587 + ** Otherwise, return an error.
33.588 + */
33.589 + const unsigned char *zEsc = sqlite3_value_text(argv[2]);
33.590 + if( zEsc==0 ) return;
33.591 + if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
33.592 + sqlite3_result_error(context,
33.593 + "ESCAPE expression must be a single character", -1);
33.594 + return;
33.595 + }
33.596 + escape = sqlite3ReadUtf8(zEsc);
33.597 + }
33.598 + if( zA && zB ){
33.599 + struct compareInfo *pInfo = sqlite3_user_data(context);
33.600 +#ifdef SQLITE_TEST
33.601 + sqlite3_like_count++;
33.602 +#endif
33.603 +
33.604 + sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
33.605 + }
33.606 +}
33.607 +
33.608 +/*
33.609 +** Implementation of the NULLIF(x,y) function. The result is the first
33.610 +** argument if the arguments are different. The result is NULL if the
33.611 +** arguments are equal to each other.
33.612 +*/
33.613 +static void nullifFunc(
33.614 + sqlite3_context *context,
33.615 + int argc,
33.616 + sqlite3_value **argv
33.617 +){
33.618 + CollSeq *pColl = sqlite3GetFuncCollSeq(context);
33.619 + if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
33.620 + sqlite3_result_value(context, argv[0]);
33.621 + }
33.622 +}
33.623 +
33.624 +/*
33.625 +** Implementation of the VERSION(*) function. The result is the version
33.626 +** of the SQLite library that is running.
33.627 +*/
33.628 +static void versionFunc(
33.629 + sqlite3_context *context,
33.630 + int argc,
33.631 + sqlite3_value **argv
33.632 +){
33.633 + sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
33.634 +}
33.635 +
33.636 +/* Array for converting from half-bytes (nybbles) into ASCII hex
33.637 +** digits. */
33.638 +static const char hexdigits[] = {
33.639 + '0', '1', '2', '3', '4', '5', '6', '7',
33.640 + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
33.641 +};
33.642 +
33.643 +/*
33.644 +** EXPERIMENTAL - This is not an official function. The interface may
33.645 +** change. This function may disappear. Do not write code that depends
33.646 +** on this function.
33.647 +**
33.648 +** Implementation of the QUOTE() function. This function takes a single
33.649 +** argument. If the argument is numeric, the return value is the same as
33.650 +** the argument. If the argument is NULL, the return value is the string
33.651 +** "NULL". Otherwise, the argument is enclosed in single quotes with
33.652 +** single-quote escapes.
33.653 +*/
33.654 +static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
33.655 + if( argc<1 ) return;
33.656 + switch( sqlite3_value_type(argv[0]) ){
33.657 + case SQLITE_NULL: {
33.658 + sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
33.659 + break;
33.660 + }
33.661 + case SQLITE_INTEGER:
33.662 + case SQLITE_FLOAT: {
33.663 + sqlite3_result_value(context, argv[0]);
33.664 + break;
33.665 + }
33.666 + case SQLITE_BLOB: {
33.667 + char *zText = 0;
33.668 + char const *zBlob = sqlite3_value_blob(argv[0]);
33.669 + int nBlob = sqlite3_value_bytes(argv[0]);
33.670 + assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
33.671 +
33.672 + if( 2*nBlob+4>SQLITE_MAX_LENGTH ){
33.673 + sqlite3_result_error_toobig(context);
33.674 + return;
33.675 + }
33.676 + zText = (char *)sqliteMalloc((2*nBlob)+4);
33.677 + if( !zText ){
33.678 + sqlite3_result_error(context, "out of memory", -1);
33.679 + }else{
33.680 + int i;
33.681 + for(i=0; i<nBlob; i++){
33.682 + zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
33.683 + zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
33.684 + }
33.685 + zText[(nBlob*2)+2] = '\'';
33.686 + zText[(nBlob*2)+3] = '\0';
33.687 + zText[0] = 'X';
33.688 + zText[1] = '\'';
33.689 + sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
33.690 + sqliteFree(zText);
33.691 + }
33.692 + break;
33.693 + }
33.694 + case SQLITE_TEXT: {
33.695 + int i,j;
33.696 + u64 n;
33.697 + const unsigned char *zArg = sqlite3_value_text(argv[0]);
33.698 + char *z;
33.699 +
33.700 + if( zArg==0 ) return;
33.701 + for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
33.702 + if( i+n+3>SQLITE_MAX_LENGTH ){
33.703 + sqlite3_result_error_toobig(context);
33.704 + return;
33.705 + }
33.706 + z = sqliteMalloc( i+n+3 );
33.707 + if( z==0 ) return;
33.708 + z[0] = '\'';
33.709 + for(i=0, j=1; zArg[i]; i++){
33.710 + z[j++] = zArg[i];
33.711 + if( zArg[i]=='\'' ){
33.712 + z[j++] = '\'';
33.713 + }
33.714 + }
33.715 + z[j++] = '\'';
33.716 + z[j] = 0;
33.717 + sqlite3_result_text(context, z, j, SQLITE_TRANSIENT);
33.718 + sqliteFree(z);
33.719 + }
33.720 + }
33.721 +}
33.722 +
33.723 +/*
33.724 +** The hex() function. Interpret the argument as a blob. Return
33.725 +** a hexadecimal rendering as text.
33.726 +*/
33.727 +static void hexFunc(
33.728 + sqlite3_context *context,
33.729 + int argc,
33.730 + sqlite3_value **argv
33.731 +){
33.732 + int i, n;
33.733 + const unsigned char *pBlob;
33.734 + char *zHex, *z;
33.735 + assert( argc==1 );
33.736 + pBlob = sqlite3_value_blob(argv[0]);
33.737 + n = sqlite3_value_bytes(argv[0]);
33.738 + if( n*2+1>SQLITE_MAX_LENGTH ){
33.739 + sqlite3_result_error_toobig(context);
33.740 + return;
33.741 + }
33.742 + assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
33.743 + z = zHex = sqlite3_malloc(n*2 + 1);
33.744 + if( zHex==0 ) return;
33.745 + for(i=0; i<n; i++, pBlob++){
33.746 + unsigned char c = *pBlob;
33.747 + *(z++) = hexdigits[(c>>4)&0xf];
33.748 + *(z++) = hexdigits[c&0xf];
33.749 + }
33.750 + *z = 0;
33.751 + sqlite3_result_text(context, zHex, n*2, sqlite3_free);
33.752 +}
33.753 +
33.754 +/*
33.755 +** The zeroblob(N) function returns a zero-filled blob of size N bytes.
33.756 +*/
33.757 +static void zeroblobFunc(
33.758 + sqlite3_context *context,
33.759 + int argc,
33.760 + sqlite3_value **argv
33.761 +){
33.762 + i64 n;
33.763 + assert( argc==1 );
33.764 + n = sqlite3_value_int64(argv[0]);
33.765 + if( n>SQLITE_MAX_LENGTH ){
33.766 + sqlite3_result_error_toobig(context);
33.767 + }else{
33.768 + sqlite3_result_zeroblob(context, n);
33.769 + }
33.770 +}
33.771 +
33.772 +/*
33.773 +** The replace() function. Three arguments are all strings: call
33.774 +** them A, B, and C. The result is also a string which is derived
33.775 +** from A by replacing every occurance of B with C. The match
33.776 +** must be exact. Collating sequences are not used.
33.777 +*/
33.778 +static void replaceFunc(
33.779 + sqlite3_context *context,
33.780 + int argc,
33.781 + sqlite3_value **argv
33.782 +){
33.783 + const unsigned char *zStr; /* The input string A */
33.784 + const unsigned char *zPattern; /* The pattern string B */
33.785 + const unsigned char *zRep; /* The replacement string C */
33.786 + unsigned char *zOut; /* The output */
33.787 + int nStr; /* Size of zStr */
33.788 + int nPattern; /* Size of zPattern */
33.789 + int nRep; /* Size of zRep */
33.790 + i64 nOut; /* Maximum size of zOut */
33.791 + int loopLimit; /* Last zStr[] that might match zPattern[] */
33.792 + int i, j; /* Loop counters */
33.793 +
33.794 + assert( argc==3 );
33.795 + zStr = sqlite3_value_text(argv[0]);
33.796 + if( zStr==0 ) return;
33.797 + nStr = sqlite3_value_bytes(argv[0]);
33.798 + assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
33.799 + zPattern = sqlite3_value_text(argv[1]);
33.800 + if( zPattern==0 || zPattern[0]==0 ) return;
33.801 + nPattern = sqlite3_value_bytes(argv[1]);
33.802 + assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
33.803 + zRep = sqlite3_value_text(argv[2]);
33.804 + if( zRep==0 ) return;
33.805 + nRep = sqlite3_value_bytes(argv[2]);
33.806 + assert( zRep==sqlite3_value_text(argv[2]) );
33.807 + nOut = nStr + 1;
33.808 + assert( nOut<SQLITE_MAX_LENGTH );
33.809 + zOut = sqlite3_malloc((int)nOut);
33.810 + if( zOut==0 ){
33.811 + return;
33.812 + }
33.813 + loopLimit = nStr - nPattern;
33.814 + for(i=j=0; i<=loopLimit; i++){
33.815 + if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
33.816 + zOut[j++] = zStr[i];
33.817 + }else{
33.818 + nOut += nRep - nPattern;
33.819 + if( nOut>=SQLITE_MAX_LENGTH ){
33.820 + sqlite3_result_error_toobig(context);
33.821 + sqlite3_free(zOut);
33.822 + return;
33.823 + }
33.824 + zOut = sqlite3_realloc(zOut, (int)nOut);
33.825 + if( zOut==0 ){
33.826 + return;
33.827 + }
33.828 + memcpy(&zOut[j], zRep, nRep);
33.829 + j += nRep;
33.830 + i += nPattern-1;
33.831 + }
33.832 + }
33.833 + assert( j+nStr-i+1==nOut );
33.834 + memcpy(&zOut[j], &zStr[i], nStr-i);
33.835 + j += nStr - i;
33.836 + assert( j<=nOut );
33.837 + zOut[j] = 0;
33.838 + sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
33.839 +}
33.840 +
33.841 +/*
33.842 +** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
33.843 +** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
33.844 +*/
33.845 +static void trimFunc(
33.846 + sqlite3_context *context,
33.847 + int argc,
33.848 + sqlite3_value **argv
33.849 +){
33.850 + const unsigned char *zIn; /* Input string */
33.851 + const unsigned char *zCharSet; /* Set of characters to trim */
33.852 + int nIn; /* Number of bytes in input */
33.853 + int flags; /* 1: trimleft 2: trimright 3: trim */
33.854 + int i; /* Loop counter */
33.855 + unsigned char *aLen; /* Length of each character in zCharSet */
33.856 + const unsigned char **azChar; /* Individual characters in zCharSet */
33.857 + int nChar; /* Number of characters in zCharSet */
33.858 +
33.859 + if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
33.860 + return;
33.861 + }
33.862 + zIn = sqlite3_value_text(argv[0]);
33.863 + if( zIn==0 ) return;
33.864 + nIn = sqlite3_value_bytes(argv[0]);
33.865 + assert( zIn==sqlite3_value_text(argv[0]) );
33.866 + if( argc==1 ){
33.867 + static const unsigned char lenOne[] = { 1 };
33.868 + static const unsigned char *azOne[] = { (u8*)" " };
33.869 + nChar = 1;
33.870 + aLen = (u8*)lenOne;
33.871 + azChar = azOne;
33.872 + zCharSet = 0;
33.873 + }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
33.874 + return;
33.875 + }else{
33.876 + const unsigned char *z;
33.877 + for(z=zCharSet, nChar=0; *z; nChar++){
33.878 + SQLITE_SKIP_UTF8(z);
33.879 + }
33.880 + if( nChar>0 ){
33.881 + azChar = sqlite3_malloc( nChar*(sizeof(char*)+1) );
33.882 + if( azChar==0 ){
33.883 + return;
33.884 + }
33.885 + aLen = (unsigned char*)&azChar[nChar];
33.886 + for(z=zCharSet, nChar=0; *z; nChar++){
33.887 + azChar[nChar] = z;
33.888 + SQLITE_SKIP_UTF8(z);
33.889 + aLen[nChar] = z - azChar[nChar];
33.890 + }
33.891 + }
33.892 + }
33.893 + if( nChar>0 ){
33.894 + flags = (int)sqlite3_user_data(context);
33.895 + if( flags & 1 ){
33.896 + while( nIn>0 ){
33.897 + int len;
33.898 + for(i=0; i<nChar; i++){
33.899 + len = aLen[i];
33.900 + if( memcmp(zIn, azChar[i], len)==0 ) break;
33.901 + }
33.902 + if( i>=nChar ) break;
33.903 + zIn += len;
33.904 + nIn -= len;
33.905 + }
33.906 + }
33.907 + if( flags & 2 ){
33.908 + while( nIn>0 ){
33.909 + int len;
33.910 + for(i=0; i<nChar; i++){
33.911 + len = aLen[i];
33.912 + if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
33.913 + }
33.914 + if( i>=nChar ) break;
33.915 + nIn -= len;
33.916 + }
33.917 + }
33.918 + if( zCharSet ){
33.919 + sqlite3_free(azChar);
33.920 + }
33.921 + }
33.922 + sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
33.923 +}
33.924 +
33.925 +#ifdef SQLITE_SOUNDEX
33.926 +/*
33.927 +** Compute the soundex encoding of a word.
33.928 +*/
33.929 +static void soundexFunc(
33.930 + sqlite3_context *context,
33.931 + int argc,
33.932 + sqlite3_value **argv
33.933 +){
33.934 + char zResult[8];
33.935 + const u8 *zIn;
33.936 + int i, j;
33.937 + static const unsigned char iCode[] = {
33.938 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
33.939 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
33.940 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
33.941 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
33.942 + 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
33.943 + 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
33.944 + 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
33.945 + 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
33.946 + };
33.947 + assert( argc==1 );
33.948 + zIn = (u8*)sqlite3_value_text(argv[0]);
33.949 + if( zIn==0 ) zIn = (u8*)"";
33.950 + for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
33.951 + if( zIn[i] ){
33.952 + u8 prevcode = iCode[zIn[i]&0x7f];
33.953 + zResult[0] = toupper(zIn[i]);
33.954 + for(j=1; j<4 && zIn[i]; i++){
33.955 + int code = iCode[zIn[i]&0x7f];
33.956 + if( code>0 ){
33.957 + if( code!=prevcode ){
33.958 + prevcode = code;
33.959 + zResult[j++] = code + '0';
33.960 + }
33.961 + }else{
33.962 + prevcode = 0;
33.963 + }
33.964 + }
33.965 + while( j<4 ){
33.966 + zResult[j++] = '0';
33.967 + }
33.968 + zResult[j] = 0;
33.969 + sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
33.970 + }else{
33.971 + sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
33.972 + }
33.973 +}
33.974 +#endif
33.975 +
33.976 +#ifndef SQLITE_OMIT_LOAD_EXTENSION
33.977 +/*
33.978 +** A function that loads a shared-library extension then returns NULL.
33.979 +*/
33.980 +static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
33.981 + const char *zFile = (const char *)sqlite3_value_text(argv[0]);
33.982 + const char *zProc;
33.983 + sqlite3 *db = sqlite3_user_data(context);
33.984 + char *zErrMsg = 0;
33.985 +
33.986 + if( argc==2 ){
33.987 + zProc = (const char *)sqlite3_value_text(argv[1]);
33.988 + }else{
33.989 + zProc = 0;
33.990 + }
33.991 + if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
33.992 + sqlite3_result_error(context, zErrMsg, -1);
33.993 + sqlite3_free(zErrMsg);
33.994 + }
33.995 +}
33.996 +#endif
33.997 +
33.998 +#ifdef SQLITE_TEST
33.999 +/*
33.1000 +** This function generates a string of random characters. Used for
33.1001 +** generating test data.
33.1002 +*/
33.1003 +static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){
33.1004 + static const unsigned char zSrc[] =
33.1005 + "abcdefghijklmnopqrstuvwxyz"
33.1006 + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
33.1007 + "0123456789"
33.1008 + ".-!,:*^+=_|?/<> ";
33.1009 + int iMin, iMax, n, r, i;
33.1010 + unsigned char zBuf[1000];
33.1011 + if( argc>=1 ){
33.1012 + iMin = sqlite3_value_int(argv[0]);
33.1013 + if( iMin<0 ) iMin = 0;
33.1014 + if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
33.1015 + }else{
33.1016 + iMin = 1;
33.1017 + }
33.1018 + if( argc>=2 ){
33.1019 + iMax = sqlite3_value_int(argv[1]);
33.1020 + if( iMax<iMin ) iMax = iMin;
33.1021 + if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
33.1022 + }else{
33.1023 + iMax = 50;
33.1024 + }
33.1025 + n = iMin;
33.1026 + if( iMax>iMin ){
33.1027 + sqlite3Randomness(sizeof(r), &r);
33.1028 + r &= 0x7fffffff;
33.1029 + n += r%(iMax + 1 - iMin);
33.1030 + }
33.1031 + assert( n<sizeof(zBuf) );
33.1032 + sqlite3Randomness(n, zBuf);
33.1033 + for(i=0; i<n; i++){
33.1034 + zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
33.1035 + }
33.1036 + zBuf[n] = 0;
33.1037 + sqlite3_result_text(context, (char*)zBuf, n, SQLITE_TRANSIENT);
33.1038 +}
33.1039 +#endif /* SQLITE_TEST */
33.1040 +
33.1041 +#ifdef SQLITE_TEST
33.1042 +/*
33.1043 +** The following two SQL functions are used to test returning a text
33.1044 +** result with a destructor. Function 'test_destructor' takes one argument
33.1045 +** and returns the same argument interpreted as TEXT. A destructor is
33.1046 +** passed with the sqlite3_result_text() call.
33.1047 +**
33.1048 +** SQL function 'test_destructor_count' returns the number of outstanding
33.1049 +** allocations made by 'test_destructor';
33.1050 +**
33.1051 +** WARNING: Not threadsafe.
33.1052 +*/
33.1053 +static int test_destructor_count_var = 0;
33.1054 +static void destructor(void *p){
33.1055 + char *zVal = (char *)p;
33.1056 + assert(zVal);
33.1057 + zVal--;
33.1058 + sqliteFree(zVal);
33.1059 + test_destructor_count_var--;
33.1060 +}
33.1061 +static void test_destructor(
33.1062 + sqlite3_context *pCtx,
33.1063 + int nArg,
33.1064 + sqlite3_value **argv
33.1065 +){
33.1066 + char *zVal;
33.1067 + int len;
33.1068 + sqlite3 *db = sqlite3_user_data(pCtx);
33.1069 +
33.1070 + test_destructor_count_var++;
33.1071 + assert( nArg==1 );
33.1072 + if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
33.1073 + len = sqlite3ValueBytes(argv[0], ENC(db));
33.1074 + zVal = sqliteMalloc(len+3);
33.1075 + zVal[len] = 0;
33.1076 + zVal[len-1] = 0;
33.1077 + assert( zVal );
33.1078 + zVal++;
33.1079 + memcpy(zVal, sqlite3ValueText(argv[0], ENC(db)), len);
33.1080 + if( ENC(db)==SQLITE_UTF8 ){
33.1081 + sqlite3_result_text(pCtx, zVal, -1, destructor);
33.1082 +#ifndef SQLITE_OMIT_UTF16
33.1083 + }else if( ENC(db)==SQLITE_UTF16LE ){
33.1084 + sqlite3_result_text16le(pCtx, zVal, -1, destructor);
33.1085 + }else{
33.1086 + sqlite3_result_text16be(pCtx, zVal, -1, destructor);
33.1087 +#endif /* SQLITE_OMIT_UTF16 */
33.1088 + }
33.1089 +}
33.1090 +static void test_destructor_count(
33.1091 + sqlite3_context *pCtx,
33.1092 + int nArg,
33.1093 + sqlite3_value **argv
33.1094 +){
33.1095 + sqlite3_result_int(pCtx, test_destructor_count_var);
33.1096 +}
33.1097 +#endif /* SQLITE_TEST */
33.1098 +
33.1099 +#ifdef SQLITE_TEST
33.1100 +/*
33.1101 +** Routines for testing the sqlite3_get_auxdata() and sqlite3_set_auxdata()
33.1102 +** interface.
33.1103 +**
33.1104 +** The test_auxdata() SQL function attempts to register each of its arguments
33.1105 +** as auxiliary data. If there are no prior registrations of aux data for
33.1106 +** that argument (meaning the argument is not a constant or this is its first
33.1107 +** call) then the result for that argument is 0. If there is a prior
33.1108 +** registration, the result for that argument is 1. The overall result
33.1109 +** is the individual argument results separated by spaces.
33.1110 +*/
33.1111 +static void free_test_auxdata(void *p) {sqliteFree(p);}
33.1112 +static void test_auxdata(
33.1113 + sqlite3_context *pCtx,
33.1114 + int nArg,
33.1115 + sqlite3_value **argv
33.1116 +){
33.1117 + int i;
33.1118 + char *zRet = sqliteMalloc(nArg*2);
33.1119 + if( !zRet ) return;
33.1120 + for(i=0; i<nArg; i++){
33.1121 + char const *z = (char*)sqlite3_value_text(argv[i]);
33.1122 + if( z ){
33.1123 + char *zAux = sqlite3_get_auxdata(pCtx, i);
33.1124 + if( zAux ){
33.1125 + zRet[i*2] = '1';
33.1126 + if( strcmp(zAux, z) ){
33.1127 + sqlite3_result_error(pCtx, "Auxilary data corruption", -1);
33.1128 + return;
33.1129 + }
33.1130 + }else{
33.1131 + zRet[i*2] = '0';
33.1132 + zAux = sqliteStrDup(z);
33.1133 + sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
33.1134 + }
33.1135 + zRet[i*2+1] = ' ';
33.1136 + }
33.1137 + }
33.1138 + sqlite3_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);
33.1139 +}
33.1140 +#endif /* SQLITE_TEST */
33.1141 +
33.1142 +#ifdef SQLITE_TEST
33.1143 +/*
33.1144 +** A function to test error reporting from user functions. This function
33.1145 +** returns a copy of it's first argument as an error.
33.1146 +*/
33.1147 +static void test_error(
33.1148 + sqlite3_context *pCtx,
33.1149 + int nArg,
33.1150 + sqlite3_value **argv
33.1151 +){
33.1152 + sqlite3_result_error(pCtx, (char*)sqlite3_value_text(argv[0]), 0);
33.1153 +}
33.1154 +#endif /* SQLITE_TEST */
33.1155 +
33.1156 +/*
33.1157 +** An instance of the following structure holds the context of a
33.1158 +** sum() or avg() aggregate computation.
33.1159 +*/
33.1160 +typedef struct SumCtx SumCtx;
33.1161 +struct SumCtx {
33.1162 + double rSum; /* Floating point sum */
33.1163 + i64 iSum; /* Integer sum */
33.1164 + i64 cnt; /* Number of elements summed */
33.1165 + u8 overflow; /* True if integer overflow seen */
33.1166 + u8 approx; /* True if non-integer value was input to the sum */
33.1167 +};
33.1168 +
33.1169 +/*
33.1170 +** Routines used to compute the sum, average, and total.
33.1171 +**
33.1172 +** The SUM() function follows the (broken) SQL standard which means
33.1173 +** that it returns NULL if it sums over no inputs. TOTAL returns
33.1174 +** 0.0 in that case. In addition, TOTAL always returns a float where
33.1175 +** SUM might return an integer if it never encounters a floating point
33.1176 +** value. TOTAL never fails, but SUM might through an exception if
33.1177 +** it overflows an integer.
33.1178 +*/
33.1179 +static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
33.1180 + SumCtx *p;
33.1181 + int type;
33.1182 + assert( argc==1 );
33.1183 + p = sqlite3_aggregate_context(context, sizeof(*p));
33.1184 + type = sqlite3_value_numeric_type(argv[0]);
33.1185 + if( p && type!=SQLITE_NULL ){
33.1186 + p->cnt++;
33.1187 + if( type==SQLITE_INTEGER ){
33.1188 + i64 v = sqlite3_value_int64(argv[0]);
33.1189 + p->rSum += v;
33.1190 + if( (p->approx|p->overflow)==0 ){
33.1191 + i64 iNewSum = p->iSum + v;
33.1192 + int s1 = p->iSum >> (sizeof(i64)*8-1);
33.1193 + int s2 = v >> (sizeof(i64)*8-1);
33.1194 + int s3 = iNewSum >> (sizeof(i64)*8-1);
33.1195 + p->overflow = (s1&s2&~s3) | (~s1&~s2&s3);
33.1196 + p->iSum = iNewSum;
33.1197 + }
33.1198 + }else{
33.1199 + p->rSum += sqlite3_value_double(argv[0]);
33.1200 + p->approx = 1;
33.1201 + }
33.1202 + }
33.1203 +}
33.1204 +static void sumFinalize(sqlite3_context *context){
33.1205 + SumCtx *p;
33.1206 + p = sqlite3_aggregate_context(context, 0);
33.1207 + if( p && p->cnt>0 ){
33.1208 + if( p->overflow ){
33.1209 + sqlite3_result_error(context,"integer overflow",-1);
33.1210 + }else if( p->approx ){
33.1211 + sqlite3_result_double(context, p->rSum);
33.1212 + }else{
33.1213 + sqlite3_result_int64(context, p->iSum);
33.1214 + }
33.1215 + }
33.1216 +}
33.1217 +static void avgFinalize(sqlite3_context *context){
33.1218 + SumCtx *p;
33.1219 + p = sqlite3_aggregate_context(context, 0);
33.1220 + if( p && p->cnt>0 ){
33.1221 + sqlite3_result_double(context, p->rSum/(double)p->cnt);
33.1222 + }
33.1223 +}
33.1224 +static void totalFinalize(sqlite3_context *context){
33.1225 + SumCtx *p;
33.1226 + p = sqlite3_aggregate_context(context, 0);
33.1227 + sqlite3_result_double(context, p ? p->rSum : 0.0);
33.1228 +}
33.1229 +
33.1230 +/*
33.1231 +** The following structure keeps track of state information for the
33.1232 +** count() aggregate function.
33.1233 +*/
33.1234 +typedef struct CountCtx CountCtx;
33.1235 +struct CountCtx {
33.1236 + i64 n;
33.1237 +};
33.1238 +
33.1239 +/*
33.1240 +** Routines to implement the count() aggregate function.
33.1241 +*/
33.1242 +static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
33.1243 + CountCtx *p;
33.1244 + p = sqlite3_aggregate_context(context, sizeof(*p));
33.1245 + if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
33.1246 + p->n++;
33.1247 + }
33.1248 +}
33.1249 +static void countFinalize(sqlite3_context *context){
33.1250 + CountCtx *p;
33.1251 + p = sqlite3_aggregate_context(context, 0);
33.1252 + sqlite3_result_int64(context, p ? p->n : 0);
33.1253 +}
33.1254 +
33.1255 +/*
33.1256 +** Routines to implement min() and max() aggregate functions.
33.1257 +*/
33.1258 +static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
33.1259 + Mem *pArg = (Mem *)argv[0];
33.1260 + Mem *pBest;
33.1261 +
33.1262 + if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
33.1263 + pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
33.1264 + if( !pBest ) return;
33.1265 +
33.1266 + if( pBest->flags ){
33.1267 + int max;
33.1268 + int cmp;
33.1269 + CollSeq *pColl = sqlite3GetFuncCollSeq(context);
33.1270 + /* This step function is used for both the min() and max() aggregates,
33.1271 + ** the only difference between the two being that the sense of the
33.1272 + ** comparison is inverted. For the max() aggregate, the
33.1273 + ** sqlite3_user_data() function returns (void *)-1. For min() it
33.1274 + ** returns (void *)db, where db is the sqlite3* database pointer.
33.1275 + ** Therefore the next statement sets variable 'max' to 1 for the max()
33.1276 + ** aggregate, or 0 for min().
33.1277 + */
33.1278 + max = sqlite3_user_data(context)!=0;
33.1279 + cmp = sqlite3MemCompare(pBest, pArg, pColl);
33.1280 + if( (max && cmp<0) || (!max && cmp>0) ){
33.1281 + sqlite3VdbeMemCopy(pBest, pArg);
33.1282 + }
33.1283 + }else{
33.1284 + sqlite3VdbeMemCopy(pBest, pArg);
33.1285 + }
33.1286 +}
33.1287 +static void minMaxFinalize(sqlite3_context *context){
33.1288 + sqlite3_value *pRes;
33.1289 + pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
33.1290 + if( pRes ){
33.1291 + if( pRes->flags ){
33.1292 + sqlite3_result_value(context, pRes);
33.1293 + }
33.1294 + sqlite3VdbeMemRelease(pRes);
33.1295 + }
33.1296 +}
33.1297 +
33.1298 +
33.1299 +/*
33.1300 +** This function registered all of the above C functions as SQL
33.1301 +** functions. This should be the only routine in this file with
33.1302 +** external linkage.
33.1303 +*/
33.1304 +void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
33.1305 + static const struct {
33.1306 + char *zName;
33.1307 + signed char nArg;
33.1308 + u8 argType; /* ff: db 1: 0, 2: 1, 3: 2,... N: N-1. */
33.1309 + u8 eTextRep; /* 1: UTF-16. 0: UTF-8 */
33.1310 + u8 needCollSeq;
33.1311 + void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
33.1312 + } aFuncs[] = {
33.1313 + { "min", -1, 0, SQLITE_UTF8, 1, minmaxFunc },
33.1314 + { "min", 0, 0, SQLITE_UTF8, 1, 0 },
33.1315 + { "max", -1, 1, SQLITE_UTF8, 1, minmaxFunc },
33.1316 + { "max", 0, 1, SQLITE_UTF8, 1, 0 },
33.1317 + { "typeof", 1, 0, SQLITE_UTF8, 0, typeofFunc },
33.1318 + { "length", 1, 0, SQLITE_UTF8, 0, lengthFunc },
33.1319 + { "substr", 3, 0, SQLITE_UTF8, 0, substrFunc },
33.1320 + { "abs", 1, 0, SQLITE_UTF8, 0, absFunc },
33.1321 + { "round", 1, 0, SQLITE_UTF8, 0, roundFunc },
33.1322 + { "round", 2, 0, SQLITE_UTF8, 0, roundFunc },
33.1323 + { "upper", 1, 0, SQLITE_UTF8, 0, upperFunc },
33.1324 + { "lower", 1, 0, SQLITE_UTF8, 0, lowerFunc },
33.1325 + { "coalesce", -1, 0, SQLITE_UTF8, 0, ifnullFunc },
33.1326 + { "coalesce", 0, 0, SQLITE_UTF8, 0, 0 },
33.1327 + { "coalesce", 1, 0, SQLITE_UTF8, 0, 0 },
33.1328 + { "hex", 1, 0, SQLITE_UTF8, 0, hexFunc },
33.1329 + { "ifnull", 2, 0, SQLITE_UTF8, 1, ifnullFunc },
33.1330 + { "random", -1, 0, SQLITE_UTF8, 0, randomFunc },
33.1331 + { "randomblob", 1, 0, SQLITE_UTF8, 0, randomBlob },
33.1332 + { "nullif", 2, 0, SQLITE_UTF8, 1, nullifFunc },
33.1333 + { "sqlite_version", 0, 0, SQLITE_UTF8, 0, versionFunc},
33.1334 + { "quote", 1, 0, SQLITE_UTF8, 0, quoteFunc },
33.1335 + { "last_insert_rowid", 0, 0xff, SQLITE_UTF8, 0, last_insert_rowid },
33.1336 + { "changes", 0, 0xff, SQLITE_UTF8, 0, changes },
33.1337 + { "total_changes", 0, 0xff, SQLITE_UTF8, 0, total_changes },
33.1338 + { "replace", 3, 0, SQLITE_UTF8, 0, replaceFunc },
33.1339 + { "ltrim", 1, 1, SQLITE_UTF8, 0, trimFunc },
33.1340 + { "ltrim", 2, 1, SQLITE_UTF8, 0, trimFunc },
33.1341 + { "rtrim", 1, 2, SQLITE_UTF8, 0, trimFunc },
33.1342 + { "rtrim", 2, 2, SQLITE_UTF8, 0, trimFunc },
33.1343 + { "trim", 1, 3, SQLITE_UTF8, 0, trimFunc },
33.1344 + { "trim", 2, 3, SQLITE_UTF8, 0, trimFunc },
33.1345 + { "zeroblob", 1, 0, SQLITE_UTF8, 0, zeroblobFunc },
33.1346 +#ifdef SQLITE_SOUNDEX
33.1347 + { "soundex", 1, 0, SQLITE_UTF8, 0, soundexFunc},
33.1348 +#endif
33.1349 +#ifndef SQLITE_OMIT_LOAD_EXTENSION
33.1350 + { "load_extension", 1, 0xff, SQLITE_UTF8, 0, loadExt },
33.1351 + { "load_extension", 2, 0xff, SQLITE_UTF8, 0, loadExt },
33.1352 +#endif
33.1353 +#ifdef SQLITE_TEST
33.1354 + { "randstr", 2, 0, SQLITE_UTF8, 0, randStr },
33.1355 + { "test_destructor", 1, 0xff, SQLITE_UTF8, 0, test_destructor},
33.1356 + { "test_destructor_count", 0, 0, SQLITE_UTF8, 0, test_destructor_count},
33.1357 + { "test_auxdata", -1, 0, SQLITE_UTF8, 0, test_auxdata},
33.1358 + { "test_error", 1, 0, SQLITE_UTF8, 0, test_error},
33.1359 +#endif
33.1360 + };
33.1361 + static const struct {
33.1362 + char *zName;
33.1363 + signed char nArg;
33.1364 + u8 argType;
33.1365 + u8 needCollSeq;
33.1366 + void (*xStep)(sqlite3_context*,int,sqlite3_value**);
33.1367 + void (*xFinalize)(sqlite3_context*);
33.1368 + } aAggs[] = {
33.1369 + { "min", 1, 0, 1, minmaxStep, minMaxFinalize },
33.1370 + { "max", 1, 1, 1, minmaxStep, minMaxFinalize },
33.1371 + { "sum", 1, 0, 0, sumStep, sumFinalize },
33.1372 + { "total", 1, 0, 0, sumStep, totalFinalize },
33.1373 + { "avg", 1, 0, 0, sumStep, avgFinalize },
33.1374 + { "count", 0, 0, 0, countStep, countFinalize },
33.1375 + { "count", 1, 0, 0, countStep, countFinalize },
33.1376 + };
33.1377 + int i;
33.1378 +
33.1379 + for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
33.1380 + void *pArg;
33.1381 + u8 argType = aFuncs[i].argType;
33.1382 + if( argType==0xff ){
33.1383 + pArg = db;
33.1384 + }else{
33.1385 + pArg = (void*)(int)argType;
33.1386 + }
33.1387 + sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
33.1388 + aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, 0, 0);
33.1389 + if( aFuncs[i].needCollSeq ){
33.1390 + FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName,
33.1391 + strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
33.1392 + if( pFunc && aFuncs[i].needCollSeq ){
33.1393 + pFunc->needCollSeq = 1;
33.1394 + }
33.1395 + }
33.1396 + }
33.1397 +#ifndef SQLITE_OMIT_ALTERTABLE
33.1398 + sqlite3AlterFunctions(db);
33.1399 +#endif
33.1400 +#ifndef SQLITE_OMIT_PARSER
33.1401 + sqlite3AttachFunctions(db);
33.1402 +#endif
33.1403 + for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
33.1404 + void *pArg = (void*)(int)aAggs[i].argType;
33.1405 + sqlite3CreateFunc(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8,
33.1406 + pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
33.1407 + if( aAggs[i].needCollSeq ){
33.1408 + FuncDef *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
33.1409 + strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
33.1410 + if( pFunc && aAggs[i].needCollSeq ){
33.1411 + pFunc->needCollSeq = 1;
33.1412 + }
33.1413 + }
33.1414 + }
33.1415 + sqlite3RegisterDateTimeFunctions(db);
33.1416 + if( !sqlite3MallocFailed() ){
33.1417 + int rc = sqlite3_overload_function(db, "MATCH", 2);
33.1418 + assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
33.1419 + if( rc==SQLITE_NOMEM ){
33.1420 + sqlite3FailedMalloc();
33.1421 + }
33.1422 + }
33.1423 +#ifdef SQLITE_SSE
33.1424 + (void)sqlite3SseFunctions(db);
33.1425 +#endif
33.1426 +#ifdef SQLITE_CASE_SENSITIVE_LIKE
33.1427 + sqlite3RegisterLikeFunctions(db, 1);
33.1428 +#else
33.1429 + sqlite3RegisterLikeFunctions(db, 0);
33.1430 +#endif
33.1431 +}
33.1432 +
33.1433 +/*
33.1434 +** Set the LIKEOPT flag on the 2-argument function with the given name.
33.1435 +*/
33.1436 +static void setLikeOptFlag(sqlite3 *db, const char *zName, int flagVal){
33.1437 + FuncDef *pDef;
33.1438 + pDef = sqlite3FindFunction(db, zName, strlen(zName), 2, SQLITE_UTF8, 0);
33.1439 + if( pDef ){
33.1440 + pDef->flags = flagVal;
33.1441 + }
33.1442 +}
33.1443 +
33.1444 +/*
33.1445 +** Register the built-in LIKE and GLOB functions. The caseSensitive
33.1446 +** parameter determines whether or not the LIKE operator is case
33.1447 +** sensitive. GLOB is always case sensitive.
33.1448 +*/
33.1449 +void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
33.1450 + struct compareInfo *pInfo;
33.1451 + if( caseSensitive ){
33.1452 + pInfo = (struct compareInfo*)&likeInfoAlt;
33.1453 + }else{
33.1454 + pInfo = (struct compareInfo*)&likeInfoNorm;
33.1455 + }
33.1456 + sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
33.1457 + sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
33.1458 + sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
33.1459 + (struct compareInfo*)&globInfo, likeFunc, 0,0);
33.1460 + setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
33.1461 + setLikeOptFlag(db, "like",
33.1462 + caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
33.1463 +}
33.1464 +
33.1465 +/*
33.1466 +** pExpr points to an expression which implements a function. If
33.1467 +** it is appropriate to apply the LIKE optimization to that function
33.1468 +** then set aWc[0] through aWc[2] to the wildcard characters and
33.1469 +** return TRUE. If the function is not a LIKE-style function then
33.1470 +** return FALSE.
33.1471 +*/
33.1472 +int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
33.1473 + FuncDef *pDef;
33.1474 + if( pExpr->op!=TK_FUNCTION || !pExpr->pList ){
33.1475 + return 0;
33.1476 + }
33.1477 + if( pExpr->pList->nExpr!=2 ){
33.1478 + return 0;
33.1479 + }
33.1480 + pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
33.1481 + SQLITE_UTF8, 0);
33.1482 + if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
33.1483 + return 0;
33.1484 + }
33.1485 +
33.1486 + /* The memcpy() statement assumes that the wildcard characters are
33.1487 + ** the first three statements in the compareInfo structure. The
33.1488 + ** asserts() that follow verify that assumption
33.1489 + */
33.1490 + memcpy(aWc, pDef->pUserData, 3);
33.1491 + assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
33.1492 + assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
33.1493 + assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
33.1494 + *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
33.1495 + return 1;
33.1496 +}
34.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
34.2 +++ b/extensions/sqlite/sqlite-source/hash.c Sun Jul 29 01:15:31 2007 +0000
34.3 @@ -0,0 +1,397 @@
34.4 +/*
34.5 +** 2001 September 22
34.6 +**
34.7 +** The author disclaims copyright to this source code. In place of
34.8 +** a legal notice, here is a blessing:
34.9 +**
34.10 +** May you do good and not evil.
34.11 +** May you find forgiveness for yourself and forgive others.
34.12 +** May you share freely, never taking more than you give.
34.13 +**
34.14 +*************************************************************************
34.15 +** This is the implementation of generic hash-tables
34.16 +** used in SQLite.
34.17 +**
34.18 +** $Id$
34.19 +*/
34.20 +#include "sqliteInt.h"
34.21 +#include <assert.h>
34.22 +
34.23 +/* Turn bulk memory into a hash table object by initializing the
34.24 +** fields of the Hash structure.
34.25 +**
34.26 +** "pNew" is a pointer to the hash table that is to be initialized.
34.27 +** keyClass is one of the constants SQLITE_HASH_INT, SQLITE_HASH_POINTER,
34.28 +** SQLITE_HASH_BINARY, or SQLITE_HASH_STRING. The value of keyClass
34.29 +** determines what kind of key the hash table will use. "copyKey" is
34.30 +** true if the hash table should make its own private copy of keys and
34.31 +** false if it should just use the supplied pointer. CopyKey only makes
34.32 +** sense for SQLITE_HASH_STRING and SQLITE_HASH_BINARY and is ignored
34.33 +** for other key classes.
34.34 +*/
34.35 +void sqlite3HashInit(Hash *pNew, int keyClass, int copyKey){
34.36 + assert( pNew!=0 );
34.37 + assert( keyClass>=SQLITE_HASH_STRING && keyClass<=SQLITE_HASH_BINARY );
34.38 + pNew->keyClass = keyClass;
34.39 +#if 0
34.40 + if( keyClass==SQLITE_HASH_POINTER || keyClass==SQLITE_HASH_INT ) copyKey = 0;
34.41 +#endif
34.42 + pNew->copyKey = copyKey;
34.43 + pNew->first = 0;
34.44 + pNew->count = 0;
34.45 + pNew->htsize = 0;
34.46 + pNew->ht = 0;
34.47 + pNew->xMalloc = sqlite3MallocX;
34.48 + pNew->xFree = sqlite3FreeX;
34.49 +}
34.50 +
34.51 +/* Remove all entries from a hash table. Reclaim all memory.
34.52 +** Call this routine to delete a hash table or to reset a hash table
34.53 +** to the empty state.
34.54 +*/
34.55 +void sqlite3HashClear(Hash *pH){
34.56 + HashElem *elem; /* For looping over all elements of the table */
34.57 +
34.58 + assert( pH!=0 );
34.59 + elem = pH->first;
34.60 + pH->first = 0;
34.61 + if( pH->ht ) pH->xFree(pH->ht);
34.62 + pH->ht = 0;
34.63 + pH->htsize = 0;
34.64 + while( elem ){
34.65 + HashElem *next_elem = elem->next;
34.66 + if( pH->copyKey && elem->pKey ){
34.67 + pH->xFree(elem->pKey);
34.68 + }
34.69 + pH->xFree(elem);
34.70 + elem = next_elem;
34.71 + }
34.72 + pH->count = 0;
34.73 +}
34.74 +
34.75 +#if 0 /* NOT USED */
34.76 +/*
34.77 +** Hash and comparison functions when the mode is SQLITE_HASH_INT
34.78 +*/
34.79 +static int intHash(const void *pKey, int nKey){
34.80 + return nKey ^ (nKey<<8) ^ (nKey>>8);
34.81 +}
34.82 +static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2){
34.83 + return n2 - n1;
34.84 +}
34.85 +#endif
34.86 +
34.87 +#if 0 /* NOT USED */
34.88 +/*
34.89 +** Hash and comparison functions when the mode is SQLITE_HASH_POINTER
34.90 +*/
34.91 +static int ptrHash(const void *pKey, int nKey){
34.92 + uptr x = Addr(pKey);
34.93 + return x ^ (x<<8) ^ (x>>8);
34.94 +}
34.95 +static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
34.96 + if( pKey1==pKey2 ) return 0;
34.97 + if( pKey1<pKey2 ) return -1;
34.98 + return 1;
34.99 +}
34.100 +#endif
34.101 +
34.102 +/*
34.103 +** Hash and comparison functions when the mode is SQLITE_HASH_STRING
34.104 +*/
34.105 +static int strHash(const void *pKey, int nKey){
34.106 + const char *z = (const char *)pKey;
34.107 + int h = 0;
34.108 + if( nKey<=0 ) nKey = strlen(z);
34.109 + while( nKey > 0 ){
34.110 + h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
34.111 + nKey--;
34.112 + }
34.113 + return h & 0x7fffffff;
34.114 +}
34.115 +static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
34.116 + if( n1!=n2 ) return 1;
34.117 + return sqlite3StrNICmp((const char*)pKey1,(const char*)pKey2,n1);
34.118 +}
34.119 +
34.120 +/*
34.121 +** Hash and comparison functions when the mode is SQLITE_HASH_BINARY
34.122 +*/
34.123 +static int binHash(const void *pKey, int nKey){
34.124 + int h = 0;
34.125 + const char *z = (const char *)pKey;
34.126 + while( nKey-- > 0 ){
34.127 + h = (h<<3) ^ h ^ *(z++);
34.128 + }
34.129 + return h & 0x7fffffff;
34.130 +}
34.131 +static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
34.132 + if( n1!=n2 ) return 1;
34.133 + return memcmp(pKey1,pKey2,n1);
34.134 +}
34.135 +
34.136 +/*
34.137 +** Return a pointer to the appropriate hash function given the key class.
34.138 +**
34.139 +** The C syntax in this function definition may be unfamilar to some
34.140 +** programmers, so we provide the following additional explanation:
34.141 +**
34.142 +** The name of the function is "hashFunction". The function takes a
34.143 +** single parameter "keyClass". The return value of hashFunction()
34.144 +** is a pointer to another function. Specifically, the return value
34.145 +** of hashFunction() is a pointer to a function that takes two parameters
34.146 +** with types "const void*" and "int" and returns an "int".
34.147 +*/
34.148 +static int (*hashFunction(int keyClass))(const void*,int){
34.149 +#if 0 /* HASH_INT and HASH_POINTER are never used */
34.150 + switch( keyClass ){
34.151 + case SQLITE_HASH_INT: return &intHash;
34.152 + case SQLITE_HASH_POINTER: return &ptrHash;
34.153 + case SQLITE_HASH_STRING: return &strHash;
34.154 + case SQLITE_HASH_BINARY: return &binHash;;
34.155 + default: break;
34.156 + }
34.157 + return 0;
34.158 +#else
34.159 + if( keyClass==SQLITE_HASH_STRING ){
34.160 + return &strHash;
34.161 + }else{
34.162 + assert( keyClass==SQLITE_HASH_BINARY );
34.163 + return &binHash;
34.164 + }
34.165 +#endif
34.166 +}
34.167 +
34.168 +/*
34.169 +** Return a pointer to the appropriate hash function given the key class.
34.170 +**
34.171 +** For help in interpreted the obscure C code in the function definition,
34.172 +** see the header comment on the previous function.
34.173 +*/
34.174 +static int (*compareFunction(int keyClass))(const void*,int,const void*,int){
34.175 +#if 0 /* HASH_INT and HASH_POINTER are never used */
34.176 + switch( keyClass ){
34.177 + case SQLITE_HASH_INT: return &intCompare;
34.178 + case SQLITE_HASH_POINTER: return &ptrCompare;
34.179 + case SQLITE_HASH_STRING: return &strCompare;
34.180 + case SQLITE_HASH_BINARY: return &binCompare;
34.181 + default: break;
34.182 + }
34.183 + return 0;
34.184 +#else
34.185 + if( keyClass==SQLITE_HASH_STRING ){
34.186 + return &strCompare;
34.187 + }else{
34.188 + assert( keyClass==SQLITE_HASH_BINARY );
34.189 + return &binCompare;
34.190 + }
34.191 +#endif
34.192 +}
34.193 +
34.194 +/* Link an element into the hash table
34.195 +*/
34.196 +static void insertElement(
34.197 + Hash *pH, /* The complete hash table */
34.198 + struct _ht *pEntry, /* The entry into which pNew is inserted */
34.199 + HashElem *pNew /* The element to be inserted */
34.200 +){
34.201 + HashElem *pHead; /* First element already in pEntry */
34.202 + pHead = pEntry->chain;
34.203 + if( pHead ){
34.204 + pNew->next = pHead;
34.205 + pNew->prev = pHead->prev;
34.206 + if( pHead->prev ){ pHead->prev->next = pNew; }
34.207 + else { pH->first = pNew; }
34.208 + pHead->prev = pNew;
34.209 + }else{
34.210 + pNew->next = pH->first;
34.211 + if( pH->first ){ pH->first->prev = pNew; }
34.212 + pNew->prev = 0;
34.213 + pH->first = pNew;
34.214 + }
34.215 + pEntry->count++;
34.216 + pEntry->chain = pNew;
34.217 +}
34.218 +
34.219 +
34.220 +/* Resize the hash table so that it cantains "new_size" buckets.
34.221 +** "new_size" must be a power of 2. The hash table might fail
34.222 +** to resize if sqliteMalloc() fails.
34.223 +*/
34.224 +static void rehash(Hash *pH, int new_size){
34.225 + struct _ht *new_ht; /* The new hash table */
34.226 + HashElem *elem, *next_elem; /* For looping over existing elements */
34.227 + int (*xHash)(const void*,int); /* The hash function */
34.228 +
34.229 + assert( (new_size & (new_size-1))==0 );
34.230 + new_ht = (struct _ht *)pH->xMalloc( new_size*sizeof(struct _ht) );
34.231 + if( new_ht==0 ) return;
34.232 + if( pH->ht ) pH->xFree(pH->ht);
34.233 + pH->ht = new_ht;
34.234 + pH->htsize = new_size;
34.235 + xHash = hashFunction(pH->keyClass);
34.236 + for(elem=pH->first, pH->first=0; elem; elem = next_elem){
34.237 + int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
34.238 + next_elem = elem->next;
34.239 + insertElement(pH, &new_ht[h], elem);
34.240 + }
34.241 +}
34.242 +
34.243 +/* This function (for internal use only) locates an element in an
34.244 +** hash table that matches the given key. The hash for this key has
34.245 +** already been computed and is passed as the 4th parameter.
34.246 +*/
34.247 +static HashElem *findElementGivenHash(
34.248 + const Hash *pH, /* The pH to be searched */
34.249 + const void *pKey, /* The key we are searching for */
34.250 + int nKey,
34.251 + int h /* The hash for this key. */
34.252 +){
34.253 + HashElem *elem; /* Used to loop thru the element list */
34.254 + int count; /* Number of elements left to test */
34.255 + int (*xCompare)(const void*,int,const void*,int); /* comparison function */
34.256 +
34.257 + if( pH->ht ){
34.258 + struct _ht *pEntry = &pH->ht[h];
34.259 + elem = pEntry->chain;
34.260 + count = pEntry->count;
34.261 + xCompare = compareFunction(pH->keyClass);
34.262 + while( count-- && elem ){
34.263 + if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
34.264 + return elem;
34.265 + }
34.266 + elem = elem->next;
34.267 + }
34.268 + }
34.269 + return 0;
34.270 +}
34.271 +
34.272 +/* Remove a single entry from the hash table given a pointer to that
34.273 +** element and a hash on the element's key.
34.274 +*/
34.275 +static void removeElementGivenHash(
34.276 + Hash *pH, /* The pH containing "elem" */
34.277 + HashElem* elem, /* The element to be removed from the pH */
34.278 + int h /* Hash value for the element */
34.279 +){
34.280 + struct _ht *pEntry;
34.281 + if( elem->prev ){
34.282 + elem->prev->next = elem->next;
34.283 + }else{
34.284 + pH->first = elem->next;
34.285 + }
34.286 + if( elem->next ){
34.287 + elem->next->prev = elem->prev;
34.288 + }
34.289 + pEntry = &pH->ht[h];
34.290 + if( pEntry->chain==elem ){
34.291 + pEntry->chain = elem->next;
34.292 + }
34.293 + pEntry->count--;
34.294 + if( pEntry->count<=0 ){
34.295 + pEntry->chain = 0;
34.296 + }
34.297 + if( pH->copyKey ){
34.298 + pH->xFree(elem->pKey);
34.299 + }
34.300 + pH->xFree( elem );
34.301 + pH->count--;
34.302 + if( pH->count<=0 ){
34.303 + assert( pH->first==0 );
34.304 + assert( pH->count==0 );
34.305 + sqlite3HashClear(pH);
34.306 + }
34.307 +}
34.308 +
34.309 +/* Attempt to locate an element of the hash table pH with a key
34.310 +** that matches pKey,nKey. Return the data for this element if it is
34.311 +** found, or NULL if there is no match.
34.312 +*/
34.313 +void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
34.314 + int h; /* A hash on key */
34.315 + HashElem *elem; /* The element that matches key */
34.316 + int (*xHash)(const void*,int); /* The hash function */
34.317 +
34.318 + if( pH==0 || pH->ht==0 ) return 0;
34.319 + xHash = hashFunction(pH->keyClass);
34.320 + assert( xHash!=0 );
34.321 + h = (*xHash)(pKey,nKey);
34.322 + assert( (pH->htsize & (pH->htsize-1))==0 );
34.323 + elem = findElementGivenHash(pH,pKey,nKey, h & (pH->htsize-1));
34.324 + return elem ? elem->data : 0;
34.325 +}
34.326 +
34.327 +/* Insert an element into the hash table pH. The key is pKey,nKey
34.328 +** and the data is "data".
34.329 +**
34.330 +** If no element exists with a matching key, then a new
34.331 +** element is created. A copy of the key is made if the copyKey
34.332 +** flag is set. NULL is returned.
34.333 +**
34.334 +** If another element already exists with the same key, then the
34.335 +** new data replaces the old data and the old data is returned.
34.336 +** The key is not copied in this instance. If a malloc fails, then
34.337 +** the new data is returned and the hash table is unchanged.
34.338 +**
34.339 +** If the "data" parameter to this function is NULL, then the
34.340 +** element corresponding to "key" is removed from the hash table.
34.341 +*/
34.342 +void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
34.343 + int hraw; /* Raw hash value of the key */
34.344 + int h; /* the hash of the key modulo hash table size */
34.345 + HashElem *elem; /* Used to loop thru the element list */
34.346 + HashElem *new_elem; /* New element added to the pH */
34.347 + int (*xHash)(const void*,int); /* The hash function */
34.348 +
34.349 + assert( pH!=0 );
34.350 + xHash = hashFunction(pH->keyClass);
34.351 + assert( xHash!=0 );
34.352 + hraw = (*xHash)(pKey, nKey);
34.353 + assert( (pH->htsize & (pH->htsize-1))==0 );
34.354 + h = hraw & (pH->htsize-1);
34.355 + elem = findElementGivenHash(pH,pKey,nKey,h);
34.356 + if( elem ){
34.357 + void *old_data = elem->data;
34.358 + if( data==0 ){
34.359 + removeElementGivenHash(pH,elem,h);
34.360 + }else{
34.361 + elem->data = data;
34.362 + }
34.363 + return old_data;
34.364 + }
34.365 + if( data==0 ) return 0;
34.366 + new_elem = (HashElem*)pH->xMalloc( sizeof(HashElem) );
34.367 + if( new_elem==0 ) return data;
34.368 + if( pH->copyKey && pKey!=0 ){
34.369 + new_elem->pKey = pH->xMalloc( nKey );
34.370 + if( new_elem->pKey==0 ){
34.371 + pH->xFree(new_elem);
34.372 + return data;
34.373 + }
34.374 + memcpy((void*)new_elem->pKey, pKey, nKey);
34.375 + }else{
34.376 + new_elem->pKey = (void*)pKey;
34.377 + }
34.378 + new_elem->nKey = nKey;
34.379 + pH->count++;
34.380 + if( pH->htsize==0 ){
34.381 + rehash(pH,8);
34.382 + if( pH->htsize==0 ){
34.383 + pH->count = 0;
34.384 + if( pH->copyKey ){
34.385 + pH->xFree(new_elem->pKey);
34.386 + }
34.387 + pH->xFree(new_elem);
34.388 + return data;
34.389 + }
34.390 + }
34.391 + if( pH->count > pH->htsize ){
34.392 + rehash(pH,pH->htsize*2);
34.393 + }
34.394 + assert( pH->htsize>0 );
34.395 + assert( (pH->htsize & (pH->htsize-1))==0 );
34.396 + h = hraw & (pH->htsize-1);
34.397 + insertElement(pH, &pH->ht[h], new_elem);
34.398 + new_elem->data = data;
34.399 + return 0;
34.400 +}
35.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
35.2 +++ b/extensions/sqlite/sqlite-source/hash.h Sun Jul 29 01:15:31 2007 +0000
35.3 @@ -0,0 +1,111 @@
35.4 +/*
35.5 +** 2001 September 22
35.6 +**
35.7 +** The author disclaims copyright to this source code. In place of
35.8 +** a legal notice, here is a blessing:
35.9 +**
35.10 +** May you do good and not evil.
35.11 +** May you find forgiveness for yourself and forgive others.
35.12 +** May you share freely, never taking more than you give.
35.13 +**
35.14 +*************************************************************************
35.15 +** This is the header file for the generic hash-table implemenation
35.16 +** used in SQLite.
35.17 +**
35.18 +** $Id$
35.19 +*/
35.20 +#ifndef _SQLITE_HASH_H_
35.21 +#define _SQLITE_HASH_H_
35.22 +
35.23 +/* Forward declarations of structures. */
35.24 +typedef struct Hash Hash;
35.25 +typedef struct HashElem HashElem;
35.26 +
35.27 +/* A complete hash table is an instance of the following structure.
35.28 +** The internals of this structure are intended to be opaque -- client
35.29 +** code should not attempt to access or modify the fields of this structure
35.30 +** directly. Change this structure only by using the routines below.
35.31 +** However, many of the "procedures" and "functions" for modifying and
35.32 +** accessing this structure are really macros, so we can't really make
35.33 +** this structure opaque.
35.34 +*/
35.35 +struct Hash {
35.36 + char keyClass; /* SQLITE_HASH_INT, _POINTER, _STRING, _BINARY */
35.37 + char copyKey; /* True if copy of key made on insert */
35.38 + int count; /* Number of entries in this table */
35.39 + HashElem *first; /* The first element of the array */
35.40 + void *(*xMalloc)(int); /* malloc() function to use */
35.41 + void (*xFree)(void *); /* free() function to use */
35.42 + int htsize; /* Number of buckets in the hash table */
35.43 + struct _ht { /* the hash table */
35.44 + int count; /* Number of entries with this hash */
35.45 + HashElem *chain; /* Pointer to first entry with this hash */
35.46 + } *ht;
35.47 +};
35.48 +
35.49 +/* Each element in the hash table is an instance of the following
35.50 +** structure. All elements are stored on a single doubly-linked list.
35.51 +**
35.52 +** Again, this structure is intended to be opaque, but it can't really
35.53 +** be opaque because it is used by macros.
35.54 +*/
35.55 +struct HashElem {
35.56 + HashElem *next, *prev; /* Next and previous elements in the table */
35.57 + void *data; /* Data associated with this element */
35.58 + void *pKey; int nKey; /* Key associated with this element */
35.59 +};
35.60 +
35.61 +/*
35.62 +** There are 4 different modes of operation for a hash table:
35.63 +**
35.64 +** SQLITE_HASH_INT nKey is used as the key and pKey is ignored.
35.65 +**
35.66 +** SQLITE_HASH_POINTER pKey is used as the key and nKey is ignored.
35.67 +**
35.68 +** SQLITE_HASH_STRING pKey points to a string that is nKey bytes long
35.69 +** (including the null-terminator, if any). Case
35.70 +** is ignored in comparisons.
35.71 +**
35.72 +** SQLITE_HASH_BINARY pKey points to binary data nKey bytes long.
35.73 +** memcmp() is used to compare keys.
35.74 +**
35.75 +** A copy of the key is made for SQLITE_HASH_STRING and SQLITE_HASH_BINARY
35.76 +** if the copyKey parameter to HashInit is 1.
35.77 +*/
35.78 +/* #define SQLITE_HASH_INT 1 // NOT USED */
35.79 +/* #define SQLITE_HASH_POINTER 2 // NOT USED */
35.80 +#define SQLITE_HASH_STRING 3
35.81 +#define SQLITE_HASH_BINARY 4
35.82 +
35.83 +/*
35.84 +** Access routines. To delete, insert a NULL pointer.
35.85 +*/
35.86 +void sqlite3HashInit(Hash*, int keytype, int copyKey);
35.87 +void *sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
35.88 +void *sqlite3HashFind(const Hash*, const void *pKey, int nKey);
35.89 +void sqlite3HashClear(Hash*);
35.90 +
35.91 +/*
35.92 +** Macros for looping over all elements of a hash table. The idiom is
35.93 +** like this:
35.94 +**
35.95 +** Hash h;
35.96 +** HashElem *p;
35.97 +** ...
35.98 +** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
35.99 +** SomeStructure *pData = sqliteHashData(p);
35.100 +** // do something with pData
35.101 +** }
35.102 +*/
35.103 +#define sqliteHashFirst(H) ((H)->first)
35.104 +#define sqliteHashNext(E) ((E)->next)
35.105 +#define sqliteHashData(E) ((E)->data)
35.106 +#define sqliteHashKey(E) ((E)->pKey)
35.107 +#define sqliteHashKeysize(E) ((E)->nKey)
35.108 +
35.109 +/*
35.110 +** Number of entries in a hash table
35.111 +*/
35.112 +#define sqliteHashCount(H) ((H)->count)
35.113 +
35.114 +#endif /* _SQLITE_HASH_H_ */
36.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
36.2 +++ b/extensions/sqlite/sqlite-source/insert.c Sun Jul 29 01:15:31 2007 +0000
36.3 @@ -0,0 +1,1604 @@
36.4 +/*
36.5 +** 2001 September 15
36.6 +**
36.7 +** The author disclaims copyright to this source code. In place of
36.8 +** a legal notice, here is a blessing:
36.9 +**
36.10 +** May you do good and not evil.
36.11 +** May you find forgiveness for yourself and forgive others.
36.12 +** May you share freely, never taking more than you give.
36.13 +**
36.14 +*************************************************************************
36.15 +** This file contains C code routines that are called by the parser
36.16 +** to handle INSERT statements in SQLite.
36.17 +**
36.18 +** $Id$
36.19 +*/
36.20 +#include "sqliteInt.h"
36.21 +
36.22 +/*
36.23 +** Set P3 of the most recently inserted opcode to a column affinity
36.24 +** string for index pIdx. A column affinity string has one character
36.25 +** for each column in the table, according to the affinity of the column:
36.26 +**
36.27 +** Character Column affinity
36.28 +** ------------------------------
36.29 +** 'a' TEXT
36.30 +** 'b' NONE
36.31 +** 'c' NUMERIC
36.32 +** 'd' INTEGER
36.33 +** 'e' REAL
36.34 +*/
36.35 +void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
36.36 + if( !pIdx->zColAff ){
36.37 + /* The first time a column affinity string for a particular index is
36.38 + ** required, it is allocated and populated here. It is then stored as
36.39 + ** a member of the Index structure for subsequent use.
36.40 + **
36.41 + ** The column affinity string will eventually be deleted by
36.42 + ** sqliteDeleteIndex() when the Index structure itself is cleaned
36.43 + ** up.
36.44 + */
36.45 + int n;
36.46 + Table *pTab = pIdx->pTable;
36.47 + pIdx->zColAff = (char *)sqliteMalloc(pIdx->nColumn+1);
36.48 + if( !pIdx->zColAff ){
36.49 + return;
36.50 + }
36.51 + for(n=0; n<pIdx->nColumn; n++){
36.52 + pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
36.53 + }
36.54 + pIdx->zColAff[pIdx->nColumn] = '\0';
36.55 + }
36.56 +
36.57 + sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0);
36.58 +}
36.59 +
36.60 +/*
36.61 +** Set P3 of the most recently inserted opcode to a column affinity
36.62 +** string for table pTab. A column affinity string has one character
36.63 +** for each column indexed by the index, according to the affinity of the
36.64 +** column:
36.65 +**
36.66 +** Character Column affinity
36.67 +** ------------------------------
36.68 +** 'a' TEXT
36.69 +** 'b' NONE
36.70 +** 'c' NUMERIC
36.71 +** 'd' INTEGER
36.72 +** 'e' REAL
36.73 +*/
36.74 +void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
36.75 + /* The first time a column affinity string for a particular table
36.76 + ** is required, it is allocated and populated here. It is then
36.77 + ** stored as a member of the Table structure for subsequent use.
36.78 + **
36.79 + ** The column affinity string will eventually be deleted by
36.80 + ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
36.81 + */
36.82 + if( !pTab->zColAff ){
36.83 + char *zColAff;
36.84 + int i;
36.85 +
36.86 + zColAff = (char *)sqliteMalloc(pTab->nCol+1);
36.87 + if( !zColAff ){
36.88 + return;
36.89 + }
36.90 +
36.91 + for(i=0; i<pTab->nCol; i++){
36.92 + zColAff[i] = pTab->aCol[i].affinity;
36.93 + }
36.94 + zColAff[pTab->nCol] = '\0';
36.95 +
36.96 + pTab->zColAff = zColAff;
36.97 + }
36.98 +
36.99 + sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0);
36.100 +}
36.101 +
36.102 +/*
36.103 +** Return non-zero if SELECT statement p opens the table with rootpage
36.104 +** iTab in database iDb. This is used to see if a statement of the form
36.105 +** "INSERT INTO <iDb, iTab> SELECT ..." can run without using temporary
36.106 +** table for the results of the SELECT.
36.107 +**
36.108 +** No checking is done for sub-selects that are part of expressions.
36.109 +*/
36.110 +static int selectReadsTable(Select *p, Schema *pSchema, int iTab){
36.111 + int i;
36.112 + struct SrcList_item *pItem;
36.113 + if( p->pSrc==0 ) return 0;
36.114 + for(i=0, pItem=p->pSrc->a; i<p->pSrc->nSrc; i++, pItem++){
36.115 + if( pItem->pSelect ){
36.116 + if( selectReadsTable(pItem->pSelect, pSchema, iTab) ) return 1;
36.117 + }else{
36.118 + if( pItem->pTab->pSchema==pSchema && pItem->pTab->tnum==iTab ) return 1;
36.119 + }
36.120 + }
36.121 + return 0;
36.122 +}
36.123 +
36.124 +#ifndef SQLITE_OMIT_AUTOINCREMENT
36.125 +/*
36.126 +** Write out code to initialize the autoincrement logic. This code
36.127 +** looks up the current autoincrement value in the sqlite_sequence
36.128 +** table and stores that value in a memory cell. Code generated by
36.129 +** autoIncStep() will keep that memory cell holding the largest
36.130 +** rowid value. Code generated by autoIncEnd() will write the new
36.131 +** largest value of the counter back into the sqlite_sequence table.
36.132 +**
36.133 +** This routine returns the index of the mem[] cell that contains
36.134 +** the maximum rowid counter.
36.135 +**
36.136 +** Two memory cells are allocated. The next memory cell after the
36.137 +** one returned holds the rowid in sqlite_sequence where we will
36.138 +** write back the revised maximum rowid.
36.139 +*/
36.140 +static int autoIncBegin(
36.141 + Parse *pParse, /* Parsing context */
36.142 + int iDb, /* Index of the database holding pTab */
36.143 + Table *pTab /* The table we are writing to */
36.144 +){
36.145 + int memId = 0;
36.146 + if( pTab->autoInc ){
36.147 + Vdbe *v = pParse->pVdbe;
36.148 + Db *pDb = &pParse->db->aDb[iDb];
36.149 + int iCur = pParse->nTab;
36.150 + int addr;
36.151 + assert( v );
36.152 + addr = sqlite3VdbeCurrentAddr(v);
36.153 + memId = pParse->nMem+1;
36.154 + pParse->nMem += 2;
36.155 + sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
36.156 + sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
36.157 + sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
36.158 + sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
36.159 + sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
36.160 + sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
36.161 + sqlite3VdbeAddOp(v, OP_MemStore, memId-1, 1);
36.162 + sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
36.163 + sqlite3VdbeAddOp(v, OP_MemStore, memId, 1);
36.164 + sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
36.165 + sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
36.166 + sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
36.167 + }
36.168 + return memId;
36.169 +}
36.170 +
36.171 +/*
36.172 +** Update the maximum rowid for an autoincrement calculation.
36.173 +**
36.174 +** This routine should be called when the top of the stack holds a
36.175 +** new rowid that is about to be inserted. If that new rowid is
36.176 +** larger than the maximum rowid in the memId memory cell, then the
36.177 +** memory cell is updated. The stack is unchanged.
36.178 +*/
36.179 +static void autoIncStep(Parse *pParse, int memId){
36.180 + if( memId>0 ){
36.181 + sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0);
36.182 + }
36.183 +}
36.184 +
36.185 +/*
36.186 +** After doing one or more inserts, the maximum rowid is stored
36.187 +** in mem[memId]. Generate code to write this value back into the
36.188 +** the sqlite_sequence table.
36.189 +*/
36.190 +static void autoIncEnd(
36.191 + Parse *pParse, /* The parsing context */
36.192 + int iDb, /* Index of the database holding pTab */
36.193 + Table *pTab, /* Table we are inserting into */
36.194 + int memId /* Memory cell holding the maximum rowid */
36.195 +){
36.196 + if( pTab->autoInc ){
36.197 + int iCur = pParse->nTab;
36.198 + Vdbe *v = pParse->pVdbe;
36.199 + Db *pDb = &pParse->db->aDb[iDb];
36.200 + int addr;
36.201 + assert( v );
36.202 + addr = sqlite3VdbeCurrentAddr(v);
36.203 + sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
36.204 + sqlite3VdbeAddOp(v, OP_MemLoad, memId-1, 0);
36.205 + sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
36.206 + sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
36.207 + sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
36.208 + sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
36.209 + sqlite3VdbeAddOp(v, OP_MemLoad, memId, 0);
36.210 + sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
36.211 + sqlite3VdbeAddOp(v, OP_Insert, iCur, OPFLAG_APPEND);
36.212 + sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
36.213 + }
36.214 +}
36.215 +#else
36.216 +/*
36.217 +** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
36.218 +** above are all no-ops
36.219 +*/
36.220 +# define autoIncBegin(A,B,C) (0)
36.221 +# define autoIncStep(A,B)
36.222 +# define autoIncEnd(A,B,C,D)
36.223 +#endif /* SQLITE_OMIT_AUTOINCREMENT */
36.224 +
36.225 +
36.226 +/* Forward declaration */
36.227 +static int xferOptimization(
36.228 + Parse *pParse, /* Parser context */
36.229 + Table *pDest, /* The table we are inserting into */
36.230 + Select *pSelect, /* A SELECT statement to use as the data source */
36.231 + int onError, /* How to handle constraint errors */
36.232 + int iDbDest /* The database of pDest */
36.233 +);
36.234 +
36.235 +/*
36.236 +** This routine is call to handle SQL of the following forms:
36.237 +**
36.238 +** insert into TABLE (IDLIST) values(EXPRLIST)
36.239 +** insert into TABLE (IDLIST) select
36.240 +**
36.241 +** The IDLIST following the table name is always optional. If omitted,
36.242 +** then a list of all columns for the table is substituted. The IDLIST
36.243 +** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
36.244 +**
36.245 +** The pList parameter holds EXPRLIST in the first form of the INSERT
36.246 +** statement above, and pSelect is NULL. For the second form, pList is
36.247 +** NULL and pSelect is a pointer to the select statement used to generate
36.248 +** data for the insert.
36.249 +**
36.250 +** The code generated follows one of four templates. For a simple
36.251 +** select with data coming from a VALUES clause, the code executes
36.252 +** once straight down through. The template looks like this:
36.253 +**
36.254 +** open write cursor to <table> and its indices
36.255 +** puts VALUES clause expressions onto the stack
36.256 +** write the resulting record into <table>
36.257 +** cleanup
36.258 +**
36.259 +** The three remaining templates assume the statement is of the form
36.260 +**
36.261 +** INSERT INTO <table> SELECT ...
36.262 +**
36.263 +** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
36.264 +** in other words if the SELECT pulls all columns from a single table
36.265 +** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
36.266 +** if <table2> and <table1> are distinct tables but have identical
36.267 +** schemas, including all the same indices, then a special optimization
36.268 +** is invoked that copies raw records from <table2> over to <table1>.
36.269 +** See the xferOptimization() function for the implementation of this
36.270 +** template. This is the second template.
36.271 +**
36.272 +** open a write cursor to <table>
36.273 +** open read cursor on <table2>
36.274 +** transfer all records in <table2> over to <table>
36.275 +** close cursors
36.276 +** foreach index on <table>
36.277 +** open a write cursor on the <table> index
36.278 +** open a read cursor on the corresponding <table2> index
36.279 +** transfer all records from the read to the write cursors
36.280 +** close cursors
36.281 +** end foreach
36.282 +**
36.283 +** The third template is for when the second template does not apply
36.284 +** and the SELECT clause does not read from <table> at any time.
36.285 +** The generated code follows this template:
36.286 +**
36.287 +** goto B
36.288 +** A: setup for the SELECT
36.289 +** loop over the rows in the SELECT
36.290 +** gosub C
36.291 +** end loop
36.292 +** cleanup after the SELECT
36.293 +** goto D
36.294 +** B: open write cursor to <table> and its indices
36.295 +** goto A
36.296 +** C: insert the select result into <table>
36.297 +** return
36.298 +** D: cleanup
36.299 +**
36.300 +** The fourth template is used if the insert statement takes its
36.301 +** values from a SELECT but the data is being inserted into a table
36.302 +** that is also read as part of the SELECT. In the third form,
36.303 +** we have to use a intermediate table to store the results of
36.304 +** the select. The template is like this:
36.305 +**
36.306 +** goto B
36.307 +** A: setup for the SELECT
36.308 +** loop over the tables in the SELECT
36.309 +** gosub C
36.310 +** end loop
36.311 +** cleanup after the SELECT
36.312 +** goto D
36.313 +** C: insert the select result into the intermediate table
36.314 +** return
36.315 +** B: open a cursor to an intermediate table
36.316 +** goto A
36.317 +** D: open write cursor to <table> and its indices
36.318 +** loop over the intermediate table
36.319 +** transfer values form intermediate table into <table>
36.320 +** end the loop
36.321 +** cleanup
36.322 +*/
36.323 +void sqlite3Insert(
36.324 + Parse *pParse, /* Parser context */
36.325 + SrcList *pTabList, /* Name of table into which we are inserting */
36.326 + ExprList *pList, /* List of values to be inserted */
36.327 + Select *pSelect, /* A SELECT statement to use as the data source */
36.328 + IdList *pColumn, /* Column names corresponding to IDLIST. */
36.329 + int onError /* How to handle constraint errors */
36.330 +){
36.331 + Table *pTab; /* The table to insert into */
36.332 + char *zTab; /* Name of the table into which we are inserting */
36.333 + const char *zDb; /* Name of the database holding this table */
36.334 + int i, j, idx; /* Loop counters */
36.335 + Vdbe *v; /* Generate code into this virtual machine */
36.336 + Index *pIdx; /* For looping over indices of the table */
36.337 + int nColumn; /* Number of columns in the data */
36.338 + int base = 0; /* VDBE Cursor number for pTab */
36.339 + int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
36.340 + sqlite3 *db; /* The main database structure */
36.341 + int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
36.342 + int endOfLoop; /* Label for the end of the insertion loop */
36.343 + int useTempTable = 0; /* Store SELECT results in intermediate table */
36.344 + int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
36.345 + int iSelectLoop = 0; /* Address of code that implements the SELECT */
36.346 + int iCleanup = 0; /* Address of the cleanup code */
36.347 + int iInsertBlock = 0; /* Address of the subroutine used to insert data */
36.348 + int iCntMem = 0; /* Memory cell used for the row counter */
36.349 + int newIdx = -1; /* Cursor for the NEW table */
36.350 + Db *pDb; /* The database containing table being inserted into */
36.351 + int counterMem = 0; /* Memory cell holding AUTOINCREMENT counter */
36.352 + int appendFlag = 0; /* True if the insert is likely to be an append */
36.353 + int iDb;
36.354 +
36.355 + int nHidden = 0;
36.356 +
36.357 +#ifndef SQLITE_OMIT_TRIGGER
36.358 + int isView; /* True if attempting to insert into a view */
36.359 + int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
36.360 +#endif
36.361 +
36.362 + if( pParse->nErr || sqlite3MallocFailed() ){
36.363 + goto insert_cleanup;
36.364 + }
36.365 + db = pParse->db;
36.366 +
36.367 + /* Locate the table into which we will be inserting new information.
36.368 + */
36.369 + assert( pTabList->nSrc==1 );
36.370 + zTab = pTabList->a[0].zName;
36.371 + if( zTab==0 ) goto insert_cleanup;
36.372 + pTab = sqlite3SrcListLookup(pParse, pTabList);
36.373 + if( pTab==0 ){
36.374 + goto insert_cleanup;
36.375 + }
36.376 + iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
36.377 + assert( iDb<db->nDb );
36.378 + pDb = &db->aDb[iDb];
36.379 + zDb = pDb->zName;
36.380 + if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
36.381 + goto insert_cleanup;
36.382 + }
36.383 +
36.384 + /* Figure out if we have any triggers and if the table being
36.385 + ** inserted into is a view
36.386 + */
36.387 +#ifndef SQLITE_OMIT_TRIGGER
36.388 + triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
36.389 + isView = pTab->pSelect!=0;
36.390 +#else
36.391 +# define triggers_exist 0
36.392 +# define isView 0
36.393 +#endif
36.394 +#ifdef SQLITE_OMIT_VIEW
36.395 +# undef isView
36.396 +# define isView 0
36.397 +#endif
36.398 +
36.399 + /* Ensure that:
36.400 + * (a) the table is not read-only,
36.401 + * (b) that if it is a view then ON INSERT triggers exist
36.402 + */
36.403 + if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
36.404 + goto insert_cleanup;
36.405 + }
36.406 + assert( pTab!=0 );
36.407 +
36.408 + /* If pTab is really a view, make sure it has been initialized.
36.409 + ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
36.410 + ** module table).
36.411 + */
36.412 + if( sqlite3ViewGetColumnNames(pParse, pTab) ){
36.413 + goto insert_cleanup;
36.414 + }
36.415 +
36.416 + /* Allocate a VDBE
36.417 + */
36.418 + v = sqlite3GetVdbe(pParse);
36.419 + if( v==0 ) goto insert_cleanup;
36.420 + if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
36.421 + sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
36.422 +
36.423 + /* if there are row triggers, allocate a temp table for new.* references. */
36.424 + if( triggers_exist ){
36.425 + newIdx = pParse->nTab++;
36.426 + }
36.427 +
36.428 +#ifndef SQLITE_OMIT_XFER_OPT
36.429 + /* If the statement is of the form
36.430 + **
36.431 + ** INSERT INTO <table1> SELECT * FROM <table2>;
36.432 + **
36.433 + ** Then special optimizations can be applied that make the transfer
36.434 + ** very fast and which reduce fragmentation of indices.
36.435 + */
36.436 + if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
36.437 + assert( !triggers_exist );
36.438 + assert( pList==0 );
36.439 + goto insert_cleanup;
36.440 + }
36.441 +#endif /* SQLITE_OMIT_XFER_OPT */
36.442 +
36.443 + /* If this is an AUTOINCREMENT table, look up the sequence number in the
36.444 + ** sqlite_sequence table and store it in memory cell counterMem. Also
36.445 + ** remember the rowid of the sqlite_sequence table entry in memory cell
36.446 + ** counterRowid.
36.447 + */
36.448 + counterMem = autoIncBegin(pParse, iDb, pTab);
36.449 +
36.450 + /* Figure out how many columns of data are supplied. If the data
36.451 + ** is coming from a SELECT statement, then this step also generates
36.452 + ** all the code to implement the SELECT statement and invoke a subroutine
36.453 + ** to process each row of the result. (Template 2.) If the SELECT
36.454 + ** statement uses the the table that is being inserted into, then the
36.455 + ** subroutine is also coded here. That subroutine stores the SELECT
36.456 + ** results in a temporary table. (Template 3.)
36.457 + */
36.458 + if( pSelect ){
36.459 + /* Data is coming from a SELECT. Generate code to implement that SELECT
36.460 + */
36.461 + int rc, iInitCode;
36.462 + iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
36.463 + iSelectLoop = sqlite3VdbeCurrentAddr(v);
36.464 + iInsertBlock = sqlite3VdbeMakeLabel(v);
36.465 +
36.466 + /* Resolve the expressions in the SELECT statement and execute it. */
36.467 + rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
36.468 + if( rc || pParse->nErr || sqlite3MallocFailed() ){
36.469 + goto insert_cleanup;
36.470 + }
36.471 +
36.472 + iCleanup = sqlite3VdbeMakeLabel(v);
36.473 + sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
36.474 + assert( pSelect->pEList );
36.475 + nColumn = pSelect->pEList->nExpr;
36.476 +
36.477 + /* Set useTempTable to TRUE if the result of the SELECT statement
36.478 + ** should be written into a temporary table. Set to FALSE if each
36.479 + ** row of the SELECT can be written directly into the result table.
36.480 + **
36.481 + ** A temp table must be used if the table being updated is also one
36.482 + ** of the tables being read by the SELECT statement. Also use a
36.483 + ** temp table in the case of row triggers.
36.484 + */
36.485 + if( triggers_exist || selectReadsTable(pSelect,pTab->pSchema,pTab->tnum) ){
36.486 + useTempTable = 1;
36.487 + }
36.488 +
36.489 + if( useTempTable ){
36.490 + /* Generate the subroutine that SELECT calls to process each row of
36.491 + ** the result. Store the result in a temporary table
36.492 + */
36.493 + srcTab = pParse->nTab++;
36.494 + sqlite3VdbeResolveLabel(v, iInsertBlock);
36.495 + sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
36.496 + sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
36.497 + sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
36.498 + sqlite3VdbeAddOp(v, OP_Insert, srcTab, OPFLAG_APPEND);
36.499 + sqlite3VdbeAddOp(v, OP_Return, 0, 0);
36.500 +
36.501 + /* The following code runs first because the GOTO at the very top
36.502 + ** of the program jumps to it. Create the temporary table, then jump
36.503 + ** back up and execute the SELECT code above.
36.504 + */
36.505 + sqlite3VdbeJumpHere(v, iInitCode);
36.506 + sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0);
36.507 + sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
36.508 + sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
36.509 + sqlite3VdbeResolveLabel(v, iCleanup);
36.510 + }else{
36.511 + sqlite3VdbeJumpHere(v, iInitCode);
36.512 + }
36.513 + }else{
36.514 + /* This is the case if the data for the INSERT is coming from a VALUES
36.515 + ** clause
36.516 + */
36.517 + NameContext sNC;
36.518 + memset(&sNC, 0, sizeof(sNC));
36.519 + sNC.pParse = pParse;
36.520 + srcTab = -1;
36.521 + useTempTable = 0;
36.522 + nColumn = pList ? pList->nExpr : 0;
36.523 + for(i=0; i<nColumn; i++){
36.524 + if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
36.525 + goto insert_cleanup;
36.526 + }
36.527 + }
36.528 + }
36.529 +
36.530 + /* Make sure the number of columns in the source data matches the number
36.531 + ** of columns to be inserted into the table.
36.532 + */
36.533 + if( IsVirtual(pTab) ){
36.534 + for(i=0; i<pTab->nCol; i++){
36.535 + nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
36.536 + }
36.537 + }
36.538 + if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
36.539 + sqlite3ErrorMsg(pParse,
36.540 + "table %S has %d columns but %d values were supplied",
36.541 + pTabList, 0, pTab->nCol, nColumn);
36.542 + goto insert_cleanup;
36.543 + }
36.544 + if( pColumn!=0 && nColumn!=pColumn->nId ){
36.545 + sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
36.546 + goto insert_cleanup;
36.547 + }
36.548 +
36.549 + /* If the INSERT statement included an IDLIST term, then make sure
36.550 + ** all elements of the IDLIST really are columns of the table and
36.551 + ** remember the column indices.
36.552 + **
36.553 + ** If the table has an INTEGER PRIMARY KEY column and that column
36.554 + ** is named in the IDLIST, then record in the keyColumn variable
36.555 + ** the index into IDLIST of the primary key column. keyColumn is
36.556 + ** the index of the primary key as it appears in IDLIST, not as
36.557 + ** is appears in the original table. (The index of the primary
36.558 + ** key in the original table is pTab->iPKey.)
36.559 + */
36.560 + if( pColumn ){
36.561 + for(i=0; i<pColumn->nId; i++){
36.562 + pColumn->a[i].idx = -1;
36.563 + }
36.564 + for(i=0; i<pColumn->nId; i++){
36.565 + for(j=0; j<pTab->nCol; j++){
36.566 + if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
36.567 + pColumn->a[i].idx = j;
36.568 + if( j==pTab->iPKey ){
36.569 + keyColumn = i;
36.570 + }
36.571 + break;
36.572 + }
36.573 + }
36.574 + if( j>=pTab->nCol ){
36.575 + if( sqlite3IsRowid(pColumn->a[i].zName) ){
36.576 + keyColumn = i;
36.577 + }else{
36.578 + sqlite3ErrorMsg(pParse, "table %S has no column named %s",
36.579 + pTabList, 0, pColumn->a[i].zName);
36.580 + pParse->nErr++;
36.581 + goto insert_cleanup;
36.582 + }
36.583 + }
36.584 + }
36.585 + }
36.586 +
36.587 + /* If there is no IDLIST term but the table has an integer primary
36.588 + ** key, the set the keyColumn variable to the primary key column index
36.589 + ** in the original table definition.
36.590 + */
36.591 + if( pColumn==0 && nColumn>0 ){
36.592 + keyColumn = pTab->iPKey;
36.593 + }
36.594 +
36.595 + /* Open the temp table for FOR EACH ROW triggers
36.596 + */
36.597 + if( triggers_exist ){
36.598 + sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
36.599 + sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
36.600 + }
36.601 +
36.602 + /* Initialize the count of rows to be inserted
36.603 + */
36.604 + if( db->flags & SQLITE_CountRows ){
36.605 + iCntMem = pParse->nMem++;
36.606 + sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
36.607 + }
36.608 +
36.609 + /* Open tables and indices if there are no row triggers */
36.610 + if( !triggers_exist ){
36.611 + base = pParse->nTab;
36.612 + sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
36.613 + }
36.614 +
36.615 + /* If the data source is a temporary table, then we have to create
36.616 + ** a loop because there might be multiple rows of data. If the data
36.617 + ** source is a subroutine call from the SELECT statement, then we need
36.618 + ** to launch the SELECT statement processing.
36.619 + */
36.620 + if( useTempTable ){
36.621 + iBreak = sqlite3VdbeMakeLabel(v);
36.622 + sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
36.623 + iCont = sqlite3VdbeCurrentAddr(v);
36.624 + }else if( pSelect ){
36.625 + sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
36.626 + sqlite3VdbeResolveLabel(v, iInsertBlock);
36.627 + }
36.628 +
36.629 + /* Run the BEFORE and INSTEAD OF triggers, if there are any
36.630 + */
36.631 + endOfLoop = sqlite3VdbeMakeLabel(v);
36.632 + if( triggers_exist & TRIGGER_BEFORE ){
36.633 +
36.634 + /* build the NEW.* reference row. Note that if there is an INTEGER
36.635 + ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
36.636 + ** translated into a unique ID for the row. But on a BEFORE trigger,
36.637 + ** we do not know what the unique ID will be (because the insert has
36.638 + ** not happened yet) so we substitute a rowid of -1
36.639 + */
36.640 + if( keyColumn<0 ){
36.641 + sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
36.642 + }else if( useTempTable ){
36.643 + sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
36.644 + }else{
36.645 + assert( pSelect==0 ); /* Otherwise useTempTable is true */
36.646 + sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
36.647 + sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
36.648 + sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
36.649 + sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
36.650 + sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
36.651 + }
36.652 +
36.653 + /* Cannot have triggers on a virtual table. If it were possible,
36.654 + ** this block would have to account for hidden column.
36.655 + */
36.656 + assert(!IsVirtual(pTab));
36.657 +
36.658 + /* Create the new column data
36.659 + */
36.660 + for(i=0; i<pTab->nCol; i++){
36.661 + if( pColumn==0 ){
36.662 + j = i;
36.663 + }else{
36.664 + for(j=0; j<pColumn->nId; j++){
36.665 + if( pColumn->a[j].idx==i ) break;
36.666 + }
36.667 + }
36.668 + if( pColumn && j>=pColumn->nId ){
36.669 + sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
36.670 + }else if( useTempTable ){
36.671 + sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
36.672 + }else{
36.673 + assert( pSelect==0 ); /* Otherwise useTempTable is true */
36.674 + sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
36.675 + }
36.676 + }
36.677 + sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
36.678 +
36.679 + /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
36.680 + ** do not attempt any conversions before assembling the record.
36.681 + ** If this is a real table, attempt conversions as required by the
36.682 + ** table column affinities.
36.683 + */
36.684 + if( !isView ){
36.685 + sqlite3TableAffinityStr(v, pTab);
36.686 + }
36.687 + sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
36.688 +
36.689 + /* Fire BEFORE or INSTEAD OF triggers */
36.690 + if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
36.691 + newIdx, -1, onError, endOfLoop) ){
36.692 + goto insert_cleanup;
36.693 + }
36.694 + }
36.695 +
36.696 + /* If any triggers exists, the opening of tables and indices is deferred
36.697 + ** until now.
36.698 + */
36.699 + if( triggers_exist && !isView ){
36.700 + base = pParse->nTab;
36.701 + sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
36.702 + }
36.703 +
36.704 + /* Push the record number for the new entry onto the stack. The
36.705 + ** record number is a randomly generate integer created by NewRowid
36.706 + ** except when the table has an INTEGER PRIMARY KEY column, in which
36.707 + ** case the record number is the same as that column.
36.708 + */
36.709 + if( !isView ){
36.710 + if( IsVirtual(pTab) ){
36.711 + /* The row that the VUpdate opcode will delete: none */
36.712 + sqlite3VdbeAddOp(v, OP_Null, 0, 0);
36.713 + }
36.714 + if( keyColumn>=0 ){
36.715 + if( useTempTable ){
36.716 + sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
36.717 + }else if( pSelect ){
36.718 + sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
36.719 + }else{
36.720 + VdbeOp *pOp;
36.721 + sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
36.722 + pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
36.723 + if( pOp && pOp->opcode==OP_Null ){
36.724 + appendFlag = 1;
36.725 + pOp->opcode = OP_NewRowid;
36.726 + pOp->p1 = base;
36.727 + pOp->p2 = counterMem;
36.728 + }
36.729 + }
36.730 + /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
36.731 + ** to generate a unique primary key value.
36.732 + */
36.733 + if( !appendFlag ){
36.734 + sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
36.735 + sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
36.736 + sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
36.737 + sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
36.738 + }
36.739 + }else if( IsVirtual(pTab) ){
36.740 + sqlite3VdbeAddOp(v, OP_Null, 0, 0);
36.741 + }else{
36.742 + sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
36.743 + appendFlag = 1;
36.744 + }
36.745 + autoIncStep(pParse, counterMem);
36.746 +
36.747 + /* Push onto the stack, data for all columns of the new entry, beginning
36.748 + ** with the first column.
36.749 + */
36.750 + nHidden = 0;
36.751 + for(i=0; i<pTab->nCol; i++){
36.752 + if( i==pTab->iPKey ){
36.753 + /* The value of the INTEGER PRIMARY KEY column is always a NULL.
36.754 + ** Whenever this column is read, the record number will be substituted
36.755 + ** in its place. So will fill this column with a NULL to avoid
36.756 + ** taking up data space with information that will never be used. */
36.757 + sqlite3VdbeAddOp(v, OP_Null, 0, 0);
36.758 + continue;
36.759 + }
36.760 + if( pColumn==0 ){
36.761 + if( IsHiddenColumn(&pTab->aCol[i]) ){
36.762 + assert( IsVirtual(pTab) );
36.763 + j = -1;
36.764 + nHidden++;
36.765 + }else{
36.766 + j = i - nHidden;
36.767 + }
36.768 + }else{
36.769 + for(j=0; j<pColumn->nId; j++){
36.770 + if( pColumn->a[j].idx==i ) break;
36.771 + }
36.772 + }
36.773 + if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
36.774 + sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
36.775 + }else if( useTempTable ){
36.776 + sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
36.777 + }else if( pSelect ){
36.778 + sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
36.779 + }else{
36.780 + sqlite3ExprCode(pParse, pList->a[j].pExpr);
36.781 + }
36.782 + }
36.783 +
36.784 + /* Generate code to check constraints and generate index keys and
36.785 + ** do the insertion.
36.786 + */
36.787 +#ifndef SQLITE_OMIT_VIRTUALTABLE
36.788 + if( IsVirtual(pTab) ){
36.789 + pParse->pVirtualLock = pTab;
36.790 + sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2,
36.791 + (const char*)pTab->pVtab, P3_VTAB);
36.792 + }else
36.793 +#endif
36.794 + {
36.795 + sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
36.796 + 0, onError, endOfLoop);
36.797 + sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
36.798 + (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
36.799 + appendFlag);
36.800 + }
36.801 + }
36.802 +
36.803 + /* Update the count of rows that are inserted
36.804 + */
36.805 + if( (db->flags & SQLITE_CountRows)!=0 ){
36.806 + sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
36.807 + }
36.808 +
36.809 + if( triggers_exist ){
36.810 + /* Close all tables opened */
36.811 + if( !isView ){
36.812 + sqlite3VdbeAddOp(v, OP_Close, base, 0);
36.813 + for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
36.814 + sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
36.815 + }
36.816 + }
36.817 +
36.818 + /* Code AFTER triggers */
36.819 + if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
36.820 + newIdx, -1, onError, endOfLoop) ){
36.821 + goto insert_cleanup;
36.822 + }
36.823 + }
36.824 +
36.825 + /* The bottom of the loop, if the data source is a SELECT statement
36.826 + */
36.827 + sqlite3VdbeResolveLabel(v, endOfLoop);
36.828 + if( useTempTable ){
36.829 + sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
36.830 + sqlite3VdbeResolveLabel(v, iBreak);
36.831 + sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
36.832 + }else if( pSelect ){
36.833 + sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
36.834 + sqlite3VdbeAddOp(v, OP_Return, 0, 0);
36.835 + sqlite3VdbeResolveLabel(v, iCleanup);
36.836 + }
36.837 +
36.838 + if( !triggers_exist && !IsVirtual(pTab) ){
36.839 + /* Close all tables opened */
36.840 + sqlite3VdbeAddOp(v, OP_Close, base, 0);
36.841 + for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
36.842 + sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
36.843 + }
36.844 + }
36.845 +
36.846 + /* Update the sqlite_sequence table by storing the content of the
36.847 + ** counter value in memory counterMem back into the sqlite_sequence
36.848 + ** table.
36.849 + */
36.850 + autoIncEnd(pParse, iDb, pTab, counterMem);
36.851 +
36.852 + /*
36.853 + ** Return the number of rows inserted. If this routine is
36.854 + ** generating code because of a call to sqlite3NestedParse(), do not
36.855 + ** invoke the callback function.
36.856 + */
36.857 + if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
36.858 + sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
36.859 + sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
36.860 + sqlite3VdbeSetNumCols(v, 1);
36.861 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
36.862 + }
36.863 +
36.864 +insert_cleanup:
36.865 + sqlite3SrcListDelete(pTabList);
36.866 + sqlite3ExprListDelete(pList);
36.867 + sqlite3SelectDelete(pSelect);
36.868 + sqlite3IdListDelete(pColumn);
36.869 +}
36.870 +
36.871 +/*
36.872 +** Generate code to do a constraint check prior to an INSERT or an UPDATE.
36.873 +**
36.874 +** When this routine is called, the stack contains (from bottom to top)
36.875 +** the following values:
36.876 +**
36.877 +** 1. The rowid of the row to be updated before the update. This
36.878 +** value is omitted unless we are doing an UPDATE that involves a
36.879 +** change to the record number.
36.880 +**
36.881 +** 2. The rowid of the row after the update.
36.882 +**
36.883 +** 3. The data in the first column of the entry after the update.
36.884 +**
36.885 +** i. Data from middle columns...
36.886 +**
36.887 +** N. The data in the last column of the entry after the update.
36.888 +**
36.889 +** The old rowid shown as entry (1) above is omitted unless both isUpdate
36.890 +** and rowidChng are 1. isUpdate is true for UPDATEs and false for
36.891 +** INSERTs and rowidChng is true if the record number is being changed.
36.892 +**
36.893 +** The code generated by this routine pushes additional entries onto
36.894 +** the stack which are the keys for new index entries for the new record.
36.895 +** The order of index keys is the same as the order of the indices on
36.896 +** the pTable->pIndex list. A key is only created for index i if
36.897 +** aIdxUsed!=0 and aIdxUsed[i]!=0.
36.898 +**
36.899 +** This routine also generates code to check constraints. NOT NULL,
36.900 +** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
36.901 +** then the appropriate action is performed. There are five possible
36.902 +** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
36.903 +**
36.904 +** Constraint type Action What Happens
36.905 +** --------------- ---------- ----------------------------------------
36.906 +** any ROLLBACK The current transaction is rolled back and
36.907 +** sqlite3_exec() returns immediately with a
36.908 +** return code of SQLITE_CONSTRAINT.
36.909 +**
36.910 +** any ABORT Back out changes from the current command
36.911 +** only (do not do a complete rollback) then
36.912 +** cause sqlite3_exec() to return immediately
36.913 +** with SQLITE_CONSTRAINT.
36.914 +**
36.915 +** any FAIL Sqlite_exec() returns immediately with a
36.916 +** return code of SQLITE_CONSTRAINT. The
36.917 +** transaction is not rolled back and any
36.918 +** prior changes are retained.
36.919 +**
36.920 +** any IGNORE The record number and data is popped from
36.921 +** the stack and there is an immediate jump
36.922 +** to label ignoreDest.
36.923 +**
36.924 +** NOT NULL REPLACE The NULL value is replace by the default
36.925 +** value for that column. If the default value
36.926 +** is NULL, the action is the same as ABORT.
36.927 +**
36.928 +** UNIQUE REPLACE The other row that conflicts with the row
36.929 +** being inserted is removed.
36.930 +**
36.931 +** CHECK REPLACE Illegal. The results in an exception.
36.932 +**
36.933 +** Which action to take is determined by the overrideError parameter.
36.934 +** Or if overrideError==OE_Default, then the pParse->onError parameter
36.935 +** is used. Or if pParse->onError==OE_Default then the onError value
36.936 +** for the constraint is used.
36.937 +**
36.938 +** The calling routine must open a read/write cursor for pTab with
36.939 +** cursor number "base". All indices of pTab must also have open
36.940 +** read/write cursors with cursor number base+i for the i-th cursor.
36.941 +** Except, if there is no possibility of a REPLACE action then
36.942 +** cursors do not need to be open for indices where aIdxUsed[i]==0.
36.943 +**
36.944 +** If the isUpdate flag is true, it means that the "base" cursor is
36.945 +** initially pointing to an entry that is being updated. The isUpdate
36.946 +** flag causes extra code to be generated so that the "base" cursor
36.947 +** is still pointing at the same entry after the routine returns.
36.948 +** Without the isUpdate flag, the "base" cursor might be moved.
36.949 +*/
36.950 +void sqlite3GenerateConstraintChecks(
36.951 + Parse *pParse, /* The parser context */
36.952 + Table *pTab, /* the table into which we are inserting */
36.953 + int base, /* Index of a read/write cursor pointing at pTab */
36.954 + char *aIdxUsed, /* Which indices are used. NULL means all are used */
36.955 + int rowidChng, /* True if the record number will change */
36.956 + int isUpdate, /* True for UPDATE, False for INSERT */
36.957 + int overrideError, /* Override onError to this if not OE_Default */
36.958 + int ignoreDest /* Jump to this label on an OE_Ignore resolution */
36.959 +){
36.960 + int i;
36.961 + Vdbe *v;
36.962 + int nCol;
36.963 + int onError;
36.964 + int addr;
36.965 + int extra;
36.966 + int iCur;
36.967 + Index *pIdx;
36.968 + int seenReplace = 0;
36.969 + int jumpInst1=0, jumpInst2;
36.970 + int hasTwoRowids = (isUpdate && rowidChng);
36.971 +
36.972 + v = sqlite3GetVdbe(pParse);
36.973 + assert( v!=0 );
36.974 + assert( pTab->pSelect==0 ); /* This table is not a VIEW */
36.975 + nCol = pTab->nCol;
36.976 +
36.977 + /* Test all NOT NULL constraints.
36.978 + */
36.979 + for(i=0; i<nCol; i++){
36.980 + if( i==pTab->iPKey ){
36.981 + continue;
36.982 + }
36.983 + onError = pTab->aCol[i].notNull;
36.984 + if( onError==OE_None ) continue;
36.985 + if( overrideError!=OE_Default ){
36.986 + onError = overrideError;
36.987 + }else if( onError==OE_Default ){
36.988 + onError = OE_Abort;
36.989 + }
36.990 + if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
36.991 + onError = OE_Abort;
36.992 + }
36.993 + sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
36.994 + addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
36.995 + assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
36.996 + || onError==OE_Ignore || onError==OE_Replace );
36.997 + switch( onError ){
36.998 + case OE_Rollback:
36.999 + case OE_Abort:
36.1000 + case OE_Fail: {
36.1001 + char *zMsg = 0;
36.1002 + sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
36.1003 + sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
36.1004 + " may not be NULL", (char*)0);
36.1005 + sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
36.1006 + break;
36.1007 + }
36.1008 + case OE_Ignore: {
36.1009 + sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
36.1010 + sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
36.1011 + break;
36.1012 + }
36.1013 + case OE_Replace: {
36.1014 + sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
36.1015 + sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
36.1016 + break;
36.1017 + }
36.1018 + }
36.1019 + sqlite3VdbeJumpHere(v, addr);
36.1020 + }
36.1021 +
36.1022 + /* Test all CHECK constraints
36.1023 + */
36.1024 +#ifndef SQLITE_OMIT_CHECK
36.1025 + if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
36.1026 + int allOk = sqlite3VdbeMakeLabel(v);
36.1027 + assert( pParse->ckOffset==0 );
36.1028 + pParse->ckOffset = nCol;
36.1029 + sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
36.1030 + assert( pParse->ckOffset==nCol );
36.1031 + pParse->ckOffset = 0;
36.1032 + onError = overrideError!=OE_Default ? overrideError : OE_Abort;
36.1033 + if( onError==OE_Ignore || onError==OE_Replace ){
36.1034 + sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
36.1035 + sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
36.1036 + }else{
36.1037 + sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
36.1038 + }
36.1039 + sqlite3VdbeResolveLabel(v, allOk);
36.1040 + }
36.1041 +#endif /* !defined(SQLITE_OMIT_CHECK) */
36.1042 +
36.1043 + /* If we have an INTEGER PRIMARY KEY, make sure the primary key
36.1044 + ** of the new record does not previously exist. Except, if this
36.1045 + ** is an UPDATE and the primary key is not changing, that is OK.
36.1046 + */
36.1047 + if( rowidChng ){
36.1048 + onError = pTab->keyConf;
36.1049 + if( overrideError!=OE_Default ){
36.1050 + onError = overrideError;
36.1051 + }else if( onError==OE_Default ){
36.1052 + onError = OE_Abort;
36.1053 + }
36.1054 +
36.1055 + if( isUpdate ){
36.1056 + sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
36.1057 + sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
36.1058 + jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
36.1059 + }
36.1060 + sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
36.1061 + jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
36.1062 + switch( onError ){
36.1063 + default: {
36.1064 + onError = OE_Abort;
36.1065 + /* Fall thru into the next case */
36.1066 + }
36.1067 + case OE_Rollback:
36.1068 + case OE_Abort:
36.1069 + case OE_Fail: {
36.1070 + sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
36.1071 + "PRIMARY KEY must be unique", P3_STATIC);
36.1072 + break;
36.1073 + }
36.1074 + case OE_Replace: {
36.1075 + sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
36.1076 + if( isUpdate ){
36.1077 + sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
36.1078 + sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
36.1079 + }
36.1080 + seenReplace = 1;
36.1081 + break;
36.1082 + }
36.1083 + case OE_Ignore: {
36.1084 + assert( seenReplace==0 );
36.1085 + sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
36.1086 + sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
36.1087 + break;
36.1088 + }
36.1089 + }
36.1090 + sqlite3VdbeJumpHere(v, jumpInst2);
36.1091 + if( isUpdate ){
36.1092 + sqlite3VdbeJumpHere(v, jumpInst1);
36.1093 + sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
36.1094 + sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
36.1095 + }
36.1096 + }
36.1097 +
36.1098 + /* Test all UNIQUE constraints by creating entries for each UNIQUE
36.1099 + ** index and making sure that duplicate entries do not already exist.
36.1100 + ** Add the new records to the indices as we go.
36.1101 + */
36.1102 + extra = -1;
36.1103 + for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
36.1104 + if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */
36.1105 + extra++;
36.1106 +
36.1107 + /* Create a key for accessing the index entry */
36.1108 + sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
36.1109 + for(i=0; i<pIdx->nColumn; i++){
36.1110 + int idx = pIdx->aiColumn[i];
36.1111 + if( idx==pTab->iPKey ){
36.1112 + sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
36.1113 + }else{
36.1114 + sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
36.1115 + }
36.1116 + }
36.1117 + jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
36.1118 + sqlite3IndexAffinityStr(v, pIdx);
36.1119 +
36.1120 + /* Find out what action to take in case there is an indexing conflict */
36.1121 + onError = pIdx->onError;
36.1122 + if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
36.1123 + if( overrideError!=OE_Default ){
36.1124 + onError = overrideError;
36.1125 + }else if( onError==OE_Default ){
36.1126 + onError = OE_Abort;
36.1127 + }
36.1128 + if( seenReplace ){
36.1129 + if( onError==OE_Ignore ) onError = OE_Replace;
36.1130 + else if( onError==OE_Fail ) onError = OE_Abort;
36.1131 + }
36.1132 +
36.1133 +
36.1134 + /* Check to see if the new index entry will be unique */
36.1135 + sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
36.1136 + jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
36.1137 +
36.1138 + /* Generate code that executes if the new index entry is not unique */
36.1139 + assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
36.1140 + || onError==OE_Ignore || onError==OE_Replace );
36.1141 + switch( onError ){
36.1142 + case OE_Rollback:
36.1143 + case OE_Abort:
36.1144 + case OE_Fail: {
36.1145 + int j, n1, n2;
36.1146 + char zErrMsg[200];
36.1147 + sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
36.1148 + pIdx->nColumn>1 ? "columns " : "column ");
36.1149 + n1 = strlen(zErrMsg);
36.1150 + for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
36.1151 + char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
36.1152 + n2 = strlen(zCol);
36.1153 + if( j>0 ){
36.1154 + sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
36.1155 + n1 += 2;
36.1156 + }
36.1157 + if( n1+n2>sizeof(zErrMsg)-30 ){
36.1158 + sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
36.1159 + n1 += 3;
36.1160 + break;
36.1161 + }else{
36.1162 + sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
36.1163 + n1 += n2;
36.1164 + }
36.1165 + }
36.1166 + sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
36.1167 + pIdx->nColumn>1 ? " are not unique" : " is not unique");
36.1168 + sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
36.1169 + break;
36.1170 + }
36.1171 + case OE_Ignore: {
36.1172 + assert( seenReplace==0 );
36.1173 + sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
36.1174 + sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
36.1175 + break;
36.1176 + }
36.1177 + case OE_Replace: {
36.1178 + sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
36.1179 + if( isUpdate ){
36.1180 + sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
36.1181 + sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
36.1182 + }
36.1183 + seenReplace = 1;
36.1184 + break;
36.1185 + }
36.1186 + }
36.1187 +#if NULL_DISTINCT_FOR_UNIQUE
36.1188 + sqlite3VdbeJumpHere(v, jumpInst1);
36.1189 +#endif
36.1190 + sqlite3VdbeJumpHere(v, jumpInst2);
36.1191 + }
36.1192 +}
36.1193 +
36.1194 +/*
36.1195 +** This routine generates code to finish the INSERT or UPDATE operation
36.1196 +** that was started by a prior call to sqlite3GenerateConstraintChecks.
36.1197 +** The stack must contain keys for all active indices followed by data
36.1198 +** and the rowid for the new entry. This routine creates the new
36.1199 +** entries in all indices and in the main table.
36.1200 +**
36.1201 +** The arguments to this routine should be the same as the first six
36.1202 +** arguments to sqlite3GenerateConstraintChecks.
36.1203 +*/
36.1204 +void sqlite3CompleteInsertion(
36.1205 + Parse *pParse, /* The parser context */
36.1206 + Table *pTab, /* the table into which we are inserting */
36.1207 + int base, /* Index of a read/write cursor pointing at pTab */
36.1208 + char *aIdxUsed, /* Which indices are used. NULL means all are used */
36.1209 + int rowidChng, /* True if the record number will change */
36.1210 + int isUpdate, /* True for UPDATE, False for INSERT */
36.1211 + int newIdx, /* Index of NEW table for triggers. -1 if none */
36.1212 + int appendBias /* True if this is likely to be an append */
36.1213 +){
36.1214 + int i;
36.1215 + Vdbe *v;
36.1216 + int nIdx;
36.1217 + Index *pIdx;
36.1218 + int pik_flags;
36.1219 +
36.1220 + v = sqlite3GetVdbe(pParse);
36.1221 + assert( v!=0 );
36.1222 + assert( pTab->pSelect==0 ); /* This table is not a VIEW */
36.1223 + for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
36.1224 + for(i=nIdx-1; i>=0; i--){
36.1225 + if( aIdxUsed && aIdxUsed[i]==0 ) continue;
36.1226 + sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
36.1227 + }
36.1228 + sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
36.1229 + sqlite3TableAffinityStr(v, pTab);
36.1230 +#ifndef SQLITE_OMIT_TRIGGER
36.1231 + if( newIdx>=0 ){
36.1232 + sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
36.1233 + sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
36.1234 + sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
36.1235 + }
36.1236 +#endif
36.1237 + if( pParse->nested ){
36.1238 + pik_flags = 0;
36.1239 + }else{
36.1240 + pik_flags = OPFLAG_NCHANGE;
36.1241 + pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
36.1242 + }
36.1243 + if( appendBias ){
36.1244 + pik_flags |= OPFLAG_APPEND;
36.1245 + }
36.1246 + sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
36.1247 + if( !pParse->nested ){
36.1248 + sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
36.1249 + }
36.1250 +
36.1251 + if( isUpdate && rowidChng ){
36.1252 + sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
36.1253 + }
36.1254 +}
36.1255 +
36.1256 +/*
36.1257 +** Generate code that will open cursors for a table and for all
36.1258 +** indices of that table. The "base" parameter is the cursor number used
36.1259 +** for the table. Indices are opened on subsequent cursors.
36.1260 +*/
36.1261 +void sqlite3OpenTableAndIndices(
36.1262 + Parse *pParse, /* Parsing context */
36.1263 + Table *pTab, /* Table to be opened */
36.1264 + int base, /* Cursor number assigned to the table */
36.1265 + int op /* OP_OpenRead or OP_OpenWrite */
36.1266 +){
36.1267 + int i;
36.1268 + int iDb;
36.1269 + Index *pIdx;
36.1270 + Vdbe *v;
36.1271 +
36.1272 + if( IsVirtual(pTab) ) return;
36.1273 + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
36.1274 + v = sqlite3GetVdbe(pParse);
36.1275 + assert( v!=0 );
36.1276 + sqlite3OpenTable(pParse, base, iDb, pTab, op);
36.1277 + for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
36.1278 + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
36.1279 + assert( pIdx->pSchema==pTab->pSchema );
36.1280 + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
36.1281 + VdbeComment((v, "# %s", pIdx->zName));
36.1282 + sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
36.1283 + }
36.1284 + if( pParse->nTab<=base+i ){
36.1285 + pParse->nTab = base+i;
36.1286 + }
36.1287 +}
36.1288 +
36.1289 +
36.1290 +#ifdef SQLITE_TEST
36.1291 +/*
36.1292 +** The following global variable is incremented whenever the
36.1293 +** transfer optimization is used. This is used for testing
36.1294 +** purposes only - to make sure the transfer optimization really
36.1295 +** is happening when it is suppose to.
36.1296 +*/
36.1297 +int sqlite3_xferopt_count;
36.1298 +#endif /* SQLITE_TEST */
36.1299 +
36.1300 +
36.1301 +#ifndef SQLITE_OMIT_XFER_OPT
36.1302 +/*
36.1303 +** Check to collation names to see if they are compatible.
36.1304 +*/
36.1305 +static int xferCompatibleCollation(const char *z1, const char *z2){
36.1306 + if( z1==0 ){
36.1307 + return z2==0;
36.1308 + }
36.1309 + if( z2==0 ){
36.1310 + return 0;
36.1311 + }
36.1312 + return sqlite3StrICmp(z1, z2)==0;
36.1313 +}
36.1314 +
36.1315 +
36.1316 +/*
36.1317 +** Check to see if index pSrc is compatible as a source of data
36.1318 +** for index pDest in an insert transfer optimization. The rules
36.1319 +** for a compatible index:
36.1320 +**
36.1321 +** * The index is over the same set of columns
36.1322 +** * The same DESC and ASC markings occurs on all columns
36.1323 +** * The same onError processing (OE_Abort, OE_Ignore, etc)
36.1324 +** * The same collating sequence on each column
36.1325 +*/
36.1326 +static int xferCompatibleIndex(Index *pDest, Index *pSrc){
36.1327 + int i;
36.1328 + assert( pDest && pSrc );
36.1329 + assert( pDest->pTable!=pSrc->pTable );
36.1330 + if( pDest->nColumn!=pSrc->nColumn ){
36.1331 + return 0; /* Different number of columns */
36.1332 + }
36.1333 + if( pDest->onError!=pSrc->onError ){
36.1334 + return 0; /* Different conflict resolution strategies */
36.1335 + }
36.1336 + for(i=0; i<pSrc->nColumn; i++){
36.1337 + if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
36.1338 + return 0; /* Different columns indexed */
36.1339 + }
36.1340 + if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
36.1341 + return 0; /* Different sort orders */
36.1342 + }
36.1343 + if( pSrc->azColl[i]!=pDest->azColl[i] ){
36.1344 + return 0; /* Different sort orders */
36.1345 + }
36.1346 + }
36.1347 +
36.1348 + /* If no test above fails then the indices must be compatible */
36.1349 + return 1;
36.1350 +}
36.1351 +
36.1352 +/*
36.1353 +** Attempt the transfer optimization on INSERTs of the form
36.1354 +**
36.1355 +** INSERT INTO tab1 SELECT * FROM tab2;
36.1356 +**
36.1357 +** This optimization is only attempted if
36.1358 +**
36.1359 +** (1) tab1 and tab2 have identical schemas including all the
36.1360 +** same indices and constraints
36.1361 +**
36.1362 +** (2) tab1 and tab2 are different tables
36.1363 +**
36.1364 +** (3) There must be no triggers on tab1
36.1365 +**
36.1366 +** (4) The result set of the SELECT statement is "*"
36.1367 +**
36.1368 +** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
36.1369 +** or LIMIT clause.
36.1370 +**
36.1371 +** (6) The SELECT statement is a simple (not a compound) select that
36.1372 +** contains only tab2 in its FROM clause
36.1373 +**
36.1374 +** This method for implementing the INSERT transfers raw records from
36.1375 +** tab2 over to tab1. The columns are not decoded. Raw records from
36.1376 +** the indices of tab2 are transfered to tab1 as well. In so doing,
36.1377 +** the resulting tab1 has much less fragmentation.
36.1378 +**
36.1379 +** This routine returns TRUE if the optimization is attempted. If any
36.1380 +** of the conditions above fail so that the optimization should not
36.1381 +** be attempted, then this routine returns FALSE.
36.1382 +*/
36.1383 +static int xferOptimization(
36.1384 + Parse *pParse, /* Parser context */
36.1385 + Table *pDest, /* The table we are inserting into */
36.1386 + Select *pSelect, /* A SELECT statement to use as the data source */
36.1387 + int onError, /* How to handle constraint errors */
36.1388 + int iDbDest /* The database of pDest */
36.1389 +){
36.1390 + ExprList *pEList; /* The result set of the SELECT */
36.1391 + Table *pSrc; /* The table in the FROM clause of SELECT */
36.1392 + Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
36.1393 + struct SrcList_item *pItem; /* An element of pSelect->pSrc */
36.1394 + int i; /* Loop counter */
36.1395 + int iDbSrc; /* The database of pSrc */
36.1396 + int iSrc, iDest; /* Cursors from source and destination */
36.1397 + int addr1, addr2; /* Loop addresses */
36.1398 + int emptyDestTest; /* Address of test for empty pDest */
36.1399 + int emptySrcTest; /* Address of test for empty pSrc */
36.1400 + Vdbe *v; /* The VDBE we are building */
36.1401 + KeyInfo *pKey; /* Key information for an index */
36.1402 + int counterMem; /* Memory register used by AUTOINC */
36.1403 + int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
36.1404 +
36.1405 + if( pSelect==0 ){
36.1406 + return 0; /* Must be of the form INSERT INTO ... SELECT ... */
36.1407 + }
36.1408 + if( pDest->pTrigger ){
36.1409 + return 0; /* tab1 must not have triggers */
36.1410 + }
36.1411 +#ifndef SQLITE_OMIT_VIRTUALTABLE
36.1412 + if( pDest->isVirtual ){
36.1413 + return 0; /* tab1 must not be a virtual table */
36.1414 + }
36.1415 +#endif
36.1416 + if( onError==OE_Default ){
36.1417 + onError = OE_Abort;
36.1418 + }
36.1419 + if( onError!=OE_Abort && onError!=OE_Rollback ){
36.1420 + return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
36.1421 + }
36.1422 + if( pSelect->pSrc==0 ){
36.1423 + return 0; /* SELECT must have a FROM clause */
36.1424 + }
36.1425 + if( pSelect->pSrc->nSrc!=1 ){
36.1426 + return 0; /* FROM clause must have exactly one term */
36.1427 + }
36.1428 + if( pSelect->pSrc->a[0].pSelect ){
36.1429 + return 0; /* FROM clause cannot contain a subquery */
36.1430 + }
36.1431 + if( pSelect->pWhere ){
36.1432 + return 0; /* SELECT may not have a WHERE clause */
36.1433 + }
36.1434 + if( pSelect->pOrderBy ){
36.1435 + return 0; /* SELECT may not have an ORDER BY clause */
36.1436 + }
36.1437 + /* Do not need to test for a HAVING clause. If HAVING is present but
36.1438 + ** there is no ORDER BY, we will get an error. */
36.1439 + if( pSelect->pGroupBy ){
36.1440 + return 0; /* SELECT may not have a GROUP BY clause */
36.1441 + }
36.1442 + if( pSelect->pLimit ){
36.1443 + return 0; /* SELECT may not have a LIMIT clause */
36.1444 + }
36.1445 + assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
36.1446 + if( pSelect->pPrior ){
36.1447 + return 0; /* SELECT may not be a compound query */
36.1448 + }
36.1449 + if( pSelect->isDistinct ){
36.1450 + return 0; /* SELECT may not be DISTINCT */
36.1451 + }
36.1452 + pEList = pSelect->pEList;
36.1453 + assert( pEList!=0 );
36.1454 + if( pEList->nExpr!=1 ){
36.1455 + return 0; /* The result set must have exactly one column */
36.1456 + }
36.1457 + assert( pEList->a[0].pExpr );
36.1458 + if( pEList->a[0].pExpr->op!=TK_ALL ){
36.1459 + return 0; /* The result set must be the special operator "*" */
36.1460 + }
36.1461 +
36.1462 + /* At this point we have established that the statement is of the
36.1463 + ** correct syntactic form to participate in this optimization. Now
36.1464 + ** we have to check the semantics.
36.1465 + */
36.1466 + pItem = pSelect->pSrc->a;
36.1467 + pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
36.1468 + if( pSrc==0 ){
36.1469 + return 0; /* FROM clause does not contain a real table */
36.1470 + }
36.1471 + if( pSrc==pDest ){
36.1472 + return 0; /* tab1 and tab2 may not be the same table */
36.1473 + }
36.1474 +#ifndef SQLITE_OMIT_VIRTUALTABLE
36.1475 + if( pSrc->isVirtual ){
36.1476 + return 0; /* tab2 must not be a virtual table */
36.1477 + }
36.1478 +#endif
36.1479 + if( pSrc->pSelect ){
36.1480 + return 0; /* tab2 may not be a view */
36.1481 + }
36.1482 + if( pDest->nCol!=pSrc->nCol ){
36.1483 + return 0; /* Number of columns must be the same in tab1 and tab2 */
36.1484 + }
36.1485 + if( pDest->iPKey!=pSrc->iPKey ){
36.1486 + return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
36.1487 + }
36.1488 + for(i=0; i<pDest->nCol; i++){
36.1489 + if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
36.1490 + return 0; /* Affinity must be the same on all columns */
36.1491 + }
36.1492 + if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
36.1493 + return 0; /* Collating sequence must be the same on all columns */
36.1494 + }
36.1495 + if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
36.1496 + return 0; /* tab2 must be NOT NULL if tab1 is */
36.1497 + }
36.1498 + }
36.1499 + for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
36.1500 + if( pDestIdx->onError!=OE_None ){
36.1501 + destHasUniqueIdx = 1;
36.1502 + }
36.1503 + for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
36.1504 + if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
36.1505 + }
36.1506 + if( pSrcIdx==0 ){
36.1507 + return 0; /* pDestIdx has no corresponding index in pSrc */
36.1508 + }
36.1509 + }
36.1510 +#ifndef SQLITE_OMIT_CHECK
36.1511 + if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
36.1512 + return 0; /* Tables have different CHECK constraints. Ticket #2252 */
36.1513 + }
36.1514 +#endif
36.1515 +
36.1516 + /* If we get this far, it means either:
36.1517 + **
36.1518 + ** * We can always do the transfer if the table contains an
36.1519 + ** an integer primary key
36.1520 + **
36.1521 + ** * We can conditionally do the transfer if the destination
36.1522 + ** table is empty.
36.1523 + */
36.1524 +#ifdef SQLITE_TEST
36.1525 + sqlite3_xferopt_count++;
36.1526 +#endif
36.1527 + iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
36.1528 + v = sqlite3GetVdbe(pParse);
36.1529 + iSrc = pParse->nTab++;
36.1530 + iDest = pParse->nTab++;
36.1531 + counterMem = autoIncBegin(pParse, iDbDest, pDest);
36.1532 + sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
36.1533 + if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
36.1534 + /* If tables do not have an INTEGER PRIMARY KEY and there
36.1535 + ** are indices to be copied and the destination is not empty,
36.1536 + ** we have to disallow the transfer optimization because the
36.1537 + ** the rowids might change which will mess up indexing.
36.1538 + **
36.1539 + ** Or if the destination has a UNIQUE index and is not empty,
36.1540 + ** we also disallow the transfer optimization because we cannot
36.1541 + ** insure that all entries in the union of DEST and SRC will be
36.1542 + ** unique.
36.1543 + */
36.1544 + addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0);
36.1545 + emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
36.1546 + sqlite3VdbeJumpHere(v, addr1);
36.1547 + }else{
36.1548 + emptyDestTest = 0;
36.1549 + }
36.1550 + sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
36.1551 + emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
36.1552 + if( pDest->iPKey>=0 ){
36.1553 + addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
36.1554 + sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
36.1555 + addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0);
36.1556 + sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
36.1557 + "PRIMARY KEY must be unique", P3_STATIC);
36.1558 + sqlite3VdbeJumpHere(v, addr2);
36.1559 + autoIncStep(pParse, counterMem);
36.1560 + }else if( pDest->pIndex==0 ){
36.1561 + addr1 = sqlite3VdbeAddOp(v, OP_NewRowid, iDest, 0);
36.1562 + }else{
36.1563 + addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
36.1564 + assert( pDest->autoInc==0 );
36.1565 + }
36.1566 + sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0);
36.1567 + sqlite3VdbeOp3(v, OP_Insert, iDest,
36.1568 + OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND,
36.1569 + pDest->zName, 0);
36.1570 + sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1);
36.1571 + autoIncEnd(pParse, iDbDest, pDest, counterMem);
36.1572 + for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
36.1573 + for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
36.1574 + if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
36.1575 + }
36.1576 + assert( pSrcIdx );
36.1577 + sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
36.1578 + sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
36.1579 + sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0);
36.1580 + pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
36.1581 + VdbeComment((v, "# %s", pSrcIdx->zName));
36.1582 + sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum,
36.1583 + (char*)pKey, P3_KEYINFO_HANDOFF);
36.1584 + sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0);
36.1585 + pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
36.1586 + VdbeComment((v, "# %s", pDestIdx->zName));
36.1587 + sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum,
36.1588 + (char*)pKey, P3_KEYINFO_HANDOFF);
36.1589 + addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
36.1590 + sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0);
36.1591 + sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 1);
36.1592 + sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1);
36.1593 + sqlite3VdbeJumpHere(v, addr1);
36.1594 + }
36.1595 + sqlite3VdbeJumpHere(v, emptySrcTest);
36.1596 + sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
36.1597 + sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
36.1598 + if( emptyDestTest ){
36.1599 + sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0);
36.1600 + sqlite3VdbeJumpHere(v, emptyDestTest);
36.1601 + sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
36.1602 + return 0;
36.1603 + }else{
36.1604 + return 1;
36.1605 + }
36.1606 +}
36.1607 +#endif /* SQLITE_OMIT_XFER_OPT */
37.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
37.2 +++ b/extensions/sqlite/sqlite-source/keywordhash.h Sun Jul 29 01:15:31 2007 +0000
37.3 @@ -0,0 +1,112 @@
37.4 +/***** This file contains automatically generated code ******
37.5 +**
37.6 +** The code in this file has been automatically generated by
37.7 +**
37.8 +** $Header: /sqlite/sqlite/tool/mkkeywordhash.c,v 1.30 2007/05/04 18:30:41 drh Exp $
37.9 +**
37.10 +** The code in this file implements a function that determines whether
37.11 +** or not a given identifier is really an SQL keyword. The same thing
37.12 +** might be implemented more directly using a hand-written hash table.
37.13 +** But by using this automatically generated code, the size of the code
37.14 +** is substantially reduced. This is important for embedded applications
37.15 +** on platforms with limited memory.
37.16 +*/
37.17 +/* Hash score: 165 */
37.18 +static int keywordCode(const char *z, int n){
37.19 + /* zText[] encodes 775 bytes of keywords in 526 bytes */
37.20 + static const char zText[526] =
37.21 + "BEFOREIGNOREGEXPLAINSTEADDESCAPEACHECKEYCONSTRAINTERSECTABLEFT"
37.22 + "HENDATABASELECTRANSACTIONATURALTERAISELSEXCEPTRIGGEREFERENCES"
37.23 + "UNIQUERYATTACHAVINGROUPDATEMPORARYBEGINNEREINDEXCLUSIVEXISTSBETWEEN"
37.24 + "OTNULLIKECASCADEFERRABLECASECOLLATECREATECURRENT_DATEDELETEDETACH"
37.25 + "IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN"
37.26 + "WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICT"
37.27 + "CROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOB"
37.28 + "YIFINTOFFSETISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUM"
37.29 + "VIEWINITIALLY";
37.30 + static const unsigned char aHash[127] = {
37.31 + 63, 92, 109, 61, 0, 38, 0, 0, 69, 0, 64, 0, 0,
37.32 + 102, 4, 65, 7, 0, 108, 72, 103, 99, 0, 22, 0, 0,
37.33 + 113, 0, 111, 106, 0, 18, 80, 0, 1, 0, 0, 56, 57,
37.34 + 0, 55, 11, 0, 33, 77, 89, 0, 110, 88, 0, 0, 45,
37.35 + 0, 90, 54, 0, 20, 0, 114, 34, 19, 0, 10, 97, 28,
37.36 + 83, 0, 0, 116, 93, 47, 115, 41, 12, 44, 0, 78, 0,
37.37 + 87, 29, 0, 86, 0, 0, 0, 82, 79, 84, 75, 96, 6,
37.38 + 14, 95, 0, 68, 0, 21, 76, 98, 27, 0, 112, 67, 104,
37.39 + 49, 40, 71, 0, 0, 81, 100, 0, 107, 0, 15, 0, 0,
37.40 + 24, 0, 73, 42, 50, 0, 16, 48, 0, 37,
37.41 + };
37.42 + static const unsigned char aNext[116] = {
37.43 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0,
37.44 + 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0,
37.45 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0,
37.46 + 17, 0, 0, 0, 36, 39, 0, 0, 25, 0, 0, 31, 0,
37.47 + 0, 0, 43, 52, 0, 0, 0, 53, 0, 0, 0, 0, 0,
37.48 + 0, 0, 0, 0, 51, 0, 0, 0, 0, 26, 0, 8, 46,
37.49 + 2, 0, 0, 0, 0, 0, 0, 0, 3, 58, 66, 0, 13,
37.50 + 0, 91, 85, 0, 94, 0, 74, 0, 0, 62, 0, 35, 101,
37.51 + 0, 0, 105, 23, 30, 60, 70, 0, 0, 59, 0, 0,
37.52 + };
37.53 + static const unsigned char aLen[116] = {
37.54 + 6, 7, 3, 6, 6, 7, 7, 3, 4, 6, 4, 5, 3,
37.55 + 10, 9, 5, 4, 4, 3, 8, 2, 6, 11, 2, 7, 5,
37.56 + 5, 4, 6, 7, 10, 6, 5, 6, 6, 5, 6, 4, 9,
37.57 + 2, 5, 5, 7, 5, 9, 6, 7, 7, 3, 4, 4, 7,
37.58 + 3, 10, 4, 7, 6, 12, 6, 6, 9, 4, 6, 5, 4,
37.59 + 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
37.60 + 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
37.61 + 2, 4, 4, 4, 4, 4, 2, 2, 4, 6, 2, 3, 6,
37.62 + 5, 8, 5, 5, 8, 3, 5, 5, 6, 4, 9, 3,
37.63 + };
37.64 + static const unsigned short int aOffset[116] = {
37.65 + 0, 2, 2, 6, 10, 13, 18, 23, 25, 26, 31, 33, 37,
37.66 + 40, 47, 55, 58, 61, 63, 65, 70, 71, 76, 85, 86, 91,
37.67 + 95, 99, 102, 107, 113, 123, 126, 131, 136, 141, 144, 148, 148,
37.68 + 152, 157, 160, 164, 166, 169, 177, 183, 189, 189, 192, 195, 199,
37.69 + 200, 204, 214, 218, 225, 231, 243, 249, 255, 264, 266, 272, 277,
37.70 + 279, 286, 291, 296, 302, 308, 313, 317, 320, 326, 330, 337, 339,
37.71 + 346, 348, 350, 359, 363, 369, 375, 383, 388, 388, 404, 411, 418,
37.72 + 419, 426, 430, 434, 438, 442, 445, 447, 449, 452, 452, 455, 458,
37.73 + 464, 468, 476, 480, 485, 493, 496, 501, 506, 512, 516, 521,
37.74 + };
37.75 + static const unsigned char aCode[116] = {
37.76 + TK_BEFORE, TK_FOREIGN, TK_FOR, TK_IGNORE, TK_LIKE_KW,
37.77 + TK_EXPLAIN, TK_INSTEAD, TK_ADD, TK_DESC, TK_ESCAPE,
37.78 + TK_EACH, TK_CHECK, TK_KEY, TK_CONSTRAINT, TK_INTERSECT,
37.79 + TK_TABLE, TK_JOIN_KW, TK_THEN, TK_END, TK_DATABASE,
37.80 + TK_AS, TK_SELECT, TK_TRANSACTION,TK_ON, TK_JOIN_KW,
37.81 + TK_ALTER, TK_RAISE, TK_ELSE, TK_EXCEPT, TK_TRIGGER,
37.82 + TK_REFERENCES, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
37.83 + TK_GROUP, TK_UPDATE, TK_TEMP, TK_TEMP, TK_OR,
37.84 + TK_BEGIN, TK_JOIN_KW, TK_REINDEX, TK_INDEX, TK_EXCLUSIVE,
37.85 + TK_EXISTS, TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NULL,
37.86 + TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DEFERRABLE, TK_CASE,
37.87 + TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DELETE, TK_DETACH,
37.88 + TK_IMMEDIATE, TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN,
37.89 + TK_ANALYZE, TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL,
37.90 + TK_LIMIT, TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER,
37.91 + TK_REPLACE, TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO,
37.92 + TK_IN, TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT,
37.93 + TK_JOIN_KW, TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED,
37.94 + TK_DISTINCT, TK_IS, TK_DROP, TK_FAIL, TK_FROM,
37.95 + TK_JOIN_KW, TK_LIKE_KW, TK_BY, TK_IF, TK_INTO,
37.96 + TK_OFFSET, TK_OF, TK_SET, TK_ISNULL, TK_ORDER,
37.97 + TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
37.98 + TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
37.99 + TK_ALL,
37.100 + };
37.101 + int h, i;
37.102 + if( n<2 ) return TK_ID;
37.103 + h = ((charMap(z[0])*4) ^
37.104 + (charMap(z[n-1])*3) ^
37.105 + n) % 127;
37.106 + for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
37.107 + if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
37.108 + return aCode[i];
37.109 + }
37.110 + }
37.111 + return TK_ID;
37.112 +}
37.113 +int sqlite3KeywordCode(const unsigned char *z, int n){
37.114 + return keywordCode((char*)z, n);
37.115 +}
38.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
38.2 +++ b/extensions/sqlite/sqlite-source/legacy.c Sun Jul 29 01:15:31 2007 +0000
38.3 @@ -0,0 +1,132 @@
38.4 +/*
38.5 +** 2001 September 15
38.6 +**
38.7 +** The author disclaims copyright to this source code. In place of
38.8 +** a legal notice, here is a blessing:
38.9 +**
38.10 +** May you do good and not evil.
38.11 +** May you find forgiveness for yourself and forgive others.
38.12 +** May you share freely, never taking more than you give.
38.13 +**
38.14 +*************************************************************************
38.15 +** Main file for the SQLite library. The routines in this file
38.16 +** implement the programmer interface to the library. Routines in
38.17 +** other files are for internal use by SQLite and should not be
38.18 +** accessed by users of the library.
38.19 +**
38.20 +** $Id$
38.21 +*/
38.22 +
38.23 +#include "sqliteInt.h"
38.24 +#include "os.h"
38.25 +#include <ctype.h>
38.26 +
38.27 +/*
38.28 +** Execute SQL code. Return one of the SQLITE_ success/failure
38.29 +** codes. Also write an error message into memory obtained from
38.30 +** malloc() and make *pzErrMsg point to that message.
38.31 +**
38.32 +** If the SQL is a query, then for each row in the query result
38.33 +** the xCallback() function is called. pArg becomes the first
38.34 +** argument to xCallback(). If xCallback=NULL then no callback
38.35 +** is invoked, even for queries.
38.36 +*/
38.37 +int sqlite3_exec(
38.38 + sqlite3 *db, /* The database on which the SQL executes */
38.39 + const char *zSql, /* The SQL to be executed */
38.40 + sqlite3_callback xCallback, /* Invoke this callback routine */
38.41 + void *pArg, /* First argument to xCallback() */
38.42 + char **pzErrMsg /* Write error messages here */
38.43 +){
38.44 + int rc = SQLITE_OK;
38.45 + const char *zLeftover;
38.46 + sqlite3_stmt *pStmt = 0;
38.47 + char **azCols = 0;
38.48 +
38.49 + int nRetry = 0;
38.50 + int nCallback;
38.51 +
38.52 + if( zSql==0 ) return SQLITE_OK;
38.53 + while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
38.54 + int nCol;
38.55 + char **azVals = 0;
38.56 +
38.57 + pStmt = 0;
38.58 + rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
38.59 + assert( rc==SQLITE_OK || pStmt==0 );
38.60 + if( rc!=SQLITE_OK ){
38.61 + continue;
38.62 + }
38.63 + if( !pStmt ){
38.64 + /* this happens for a comment or white-space */
38.65 + zSql = zLeftover;
38.66 + continue;
38.67 + }
38.68 +
38.69 + nCallback = 0;
38.70 +
38.71 + nCol = sqlite3_column_count(pStmt);
38.72 + azCols = sqliteMalloc(2*nCol*sizeof(const char *) + 1);
38.73 + if( azCols==0 ){
38.74 + goto exec_out;
38.75 + }
38.76 +
38.77 + while( 1 ){
38.78 + int i;
38.79 + rc = sqlite3_step(pStmt);
38.80 +
38.81 + /* Invoke the callback function if required */
38.82 + if( xCallback && (SQLITE_ROW==rc ||
38.83 + (SQLITE_DONE==rc && !nCallback && db->flags&SQLITE_NullCallback)) ){
38.84 + if( 0==nCallback ){
38.85 + for(i=0; i<nCol; i++){
38.86 + azCols[i] = (char *)sqlite3_column_name(pStmt, i);
38.87 + }
38.88 + nCallback++;
38.89 + }
38.90 + if( rc==SQLITE_ROW ){
38.91 + azVals = &azCols[nCol];
38.92 + for(i=0; i<nCol; i++){
38.93 + azVals[i] = (char *)sqlite3_column_text(pStmt, i);
38.94 + }
38.95 + }
38.96 + if( xCallback(pArg, nCol, azVals, azCols) ){
38.97 + rc = SQLITE_ABORT;
38.98 + goto exec_out;
38.99 + }
38.100 + }
38.101 +
38.102 + if( rc!=SQLITE_ROW ){
38.103 + rc = sqlite3_finalize(pStmt);
38.104 + pStmt = 0;
38.105 + if( rc!=SQLITE_SCHEMA ){
38.106 + nRetry = 0;
38.107 + zSql = zLeftover;
38.108 + while( isspace((unsigned char)zSql[0]) ) zSql++;
38.109 + }
38.110 + break;
38.111 + }
38.112 + }
38.113 +
38.114 + sqliteFree(azCols);
38.115 + azCols = 0;
38.116 + }
38.117 +
38.118 +exec_out:
38.119 + if( pStmt ) sqlite3_finalize(pStmt);
38.120 + if( azCols ) sqliteFree(azCols);
38.121 +
38.122 + rc = sqlite3ApiExit(0, rc);
38.123 + if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
38.124 + int nErrMsg = 1 + strlen(sqlite3_errmsg(db));
38.125 + *pzErrMsg = sqlite3_malloc(nErrMsg);
38.126 + if( *pzErrMsg ){
38.127 + memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
38.128 + }
38.129 + }else if( pzErrMsg ){
38.130 + *pzErrMsg = 0;
38.131 + }
38.132 +
38.133 + assert( (rc&db->errMask)==rc );
38.134 + return rc;
38.135 +}
39.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
39.2 +++ b/extensions/sqlite/sqlite-source/loadext.c Sun Jul 29 01:15:31 2007 +0000
39.3 @@ -0,0 +1,440 @@
39.4 +/*
39.5 +** 2006 June 7
39.6 +**
39.7 +** The author disclaims copyright to this source code. In place of
39.8 +** a legal notice, here is a blessing:
39.9 +**
39.10 +** May you do good and not evil.
39.11 +** May you find forgiveness for yourself and forgive others.
39.12 +** May you share freely, never taking more than you give.
39.13 +**
39.14 +*************************************************************************
39.15 +** This file contains code used to dynamically load extensions into
39.16 +** the SQLite library.
39.17 +*/
39.18 +#ifndef SQLITE_OMIT_LOAD_EXTENSION
39.19 +
39.20 +#define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
39.21 +#include "sqlite3ext.h"
39.22 +#include "sqliteInt.h"
39.23 +#include "os.h"
39.24 +#include <string.h>
39.25 +#include <ctype.h>
39.26 +
39.27 +/*
39.28 +** Some API routines are omitted when various features are
39.29 +** excluded from a build of SQLite. Substitute a NULL pointer
39.30 +** for any missing APIs.
39.31 +*/
39.32 +#ifndef SQLITE_ENABLE_COLUMN_METADATA
39.33 +# define sqlite3_column_database_name 0
39.34 +# define sqlite3_column_database_name16 0
39.35 +# define sqlite3_column_table_name 0
39.36 +# define sqlite3_column_table_name16 0
39.37 +# define sqlite3_column_origin_name 0
39.38 +# define sqlite3_column_origin_name16 0
39.39 +# define sqlite3_table_column_metadata 0
39.40 +#endif
39.41 +
39.42 +#ifdef SQLITE_OMIT_AUTHORIZATION
39.43 +# define sqlite3_set_authorizer 0
39.44 +#endif
39.45 +
39.46 +#ifdef SQLITE_OMIT_UTF16
39.47 +# define sqlite3_bind_text16 0
39.48 +# define sqlite3_collation_needed16 0
39.49 +# define sqlite3_column_decltype16 0
39.50 +# define sqlite3_column_name16 0
39.51 +# define sqlite3_column_text16 0
39.52 +# define sqlite3_complete16 0
39.53 +# define sqlite3_create_collation16 0
39.54 +# define sqlite3_create_function16 0
39.55 +# define sqlite3_errmsg16 0
39.56 +# define sqlite3_open16 0
39.57 +# define sqlite3_prepare16 0
39.58 +# define sqlite3_prepare16_v2 0
39.59 +# define sqlite3_result_error16 0
39.60 +# define sqlite3_result_text16 0
39.61 +# define sqlite3_result_text16be 0
39.62 +# define sqlite3_result_text16le 0
39.63 +# define sqlite3_value_text16 0
39.64 +# define sqlite3_value_text16be 0
39.65 +# define sqlite3_value_text16le 0
39.66 +# define sqlite3_column_database_name16 0
39.67 +# define sqlite3_column_table_name16 0
39.68 +# define sqlite3_column_origin_name16 0
39.69 +#endif
39.70 +
39.71 +#ifdef SQLITE_OMIT_COMPLETE
39.72 +# define sqlite3_complete 0
39.73 +# define sqlite3_complete16 0
39.74 +#endif
39.75 +
39.76 +#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
39.77 +# define sqlite3_progress_handler 0
39.78 +#endif
39.79 +
39.80 +#ifdef SQLITE_OMIT_VIRTUALTABLE
39.81 +# define sqlite3_create_module 0
39.82 +# define sqlite3_create_module_v2 0
39.83 +# define sqlite3_declare_vtab 0
39.84 +#endif
39.85 +
39.86 +#ifdef SQLITE_OMIT_SHARED_CACHE
39.87 +# define sqlite3_enable_shared_cache 0
39.88 +#endif
39.89 +
39.90 +#ifdef SQLITE_OMIT_TRACE
39.91 +# define sqlite3_profile 0
39.92 +# define sqlite3_trace 0
39.93 +#endif
39.94 +
39.95 +#ifdef SQLITE_OMIT_GET_TABLE
39.96 +# define sqlite3_free_table 0
39.97 +# define sqlite3_get_table 0
39.98 +#endif
39.99 +
39.100 +/*
39.101 +** The following structure contains pointers to all SQLite API routines.
39.102 +** A pointer to this structure is passed into extensions when they are
39.103 +** loaded so that the extension can make calls back into the SQLite
39.104 +** library.
39.105 +**
39.106 +** When adding new APIs, add them to the bottom of this structure
39.107 +** in order to preserve backwards compatibility.
39.108 +**
39.109 +** Extensions that use newer APIs should first call the
39.110 +** sqlite3_libversion_number() to make sure that the API they
39.111 +** intend to use is supported by the library. Extensions should
39.112 +** also check to make sure that the pointer to the function is
39.113 +** not NULL before calling it.
39.114 +*/
39.115 +const sqlite3_api_routines sqlite3_apis = {
39.116 + sqlite3_aggregate_context,
39.117 + sqlite3_aggregate_count,
39.118 + sqlite3_bind_blob,
39.119 + sqlite3_bind_double,
39.120 + sqlite3_bind_int,
39.121 + sqlite3_bind_int64,
39.122 + sqlite3_bind_null,
39.123 + sqlite3_bind_parameter_count,
39.124 + sqlite3_bind_parameter_index,
39.125 + sqlite3_bind_parameter_name,
39.126 + sqlite3_bind_text,
39.127 + sqlite3_bind_text16,
39.128 + sqlite3_bind_value,
39.129 + sqlite3_busy_handler,
39.130 + sqlite3_busy_timeout,
39.131 + sqlite3_changes,
39.132 + sqlite3_close,
39.133 + sqlite3_collation_needed,
39.134 + sqlite3_collation_needed16,
39.135 + sqlite3_column_blob,
39.136 + sqlite3_column_bytes,
39.137 + sqlite3_column_bytes16,
39.138 + sqlite3_column_count,
39.139 + sqlite3_column_database_name,
39.140 + sqlite3_column_database_name16,
39.141 + sqlite3_column_decltype,
39.142 + sqlite3_column_decltype16,
39.143 + sqlite3_column_double,
39.144 + sqlite3_column_int,
39.145 + sqlite3_column_int64,
39.146 + sqlite3_column_name,
39.147 + sqlite3_column_name16,
39.148 + sqlite3_column_origin_name,
39.149 + sqlite3_column_origin_name16,
39.150 + sqlite3_column_table_name,
39.151 + sqlite3_column_table_name16,
39.152 + sqlite3_column_text,
39.153 + sqlite3_column_text16,
39.154 + sqlite3_column_type,
39.155 + sqlite3_column_value,
39.156 + sqlite3_commit_hook,
39.157 + sqlite3_complete,
39.158 + sqlite3_complete16,
39.159 + sqlite3_create_collation,
39.160 + sqlite3_create_collation16,
39.161 + sqlite3_create_function,
39.162 + sqlite3_create_function16,
39.163 + sqlite3_create_module,
39.164 + sqlite3_data_count,
39.165 + sqlite3_db_handle,
39.166 + sqlite3_declare_vtab,
39.167 + sqlite3_enable_shared_cache,
39.168 + sqlite3_errcode,
39.169 + sqlite3_errmsg,
39.170 + sqlite3_errmsg16,
39.171 + sqlite3_exec,
39.172 + sqlite3_expired,
39.173 + sqlite3_finalize,
39.174 + sqlite3_free,
39.175 + sqlite3_free_table,
39.176 + sqlite3_get_autocommit,
39.177 + sqlite3_get_auxdata,
39.178 + sqlite3_get_table,
39.179 + 0, /* Was sqlite3_global_recover(), but that function is deprecated */
39.180 + sqlite3_interrupt,
39.181 + sqlite3_last_insert_rowid,
39.182 + sqlite3_libversion,
39.183 + sqlite3_libversion_number,
39.184 + sqlite3_malloc,
39.185 + sqlite3_mprintf,
39.186 + sqlite3_open,
39.187 + sqlite3_open16,
39.188 + sqlite3_prepare,
39.189 + sqlite3_prepare16,
39.190 + sqlite3_profile,
39.191 + sqlite3_progress_handler,
39.192 + sqlite3_realloc,
39.193 + sqlite3_reset,
39.194 + sqlite3_result_blob,
39.195 + sqlite3_result_double,
39.196 + sqlite3_result_error,
39.197 + sqlite3_result_error16,
39.198 + sqlite3_result_int,
39.199 + sqlite3_result_int64,
39.200 + sqlite3_result_null,
39.201 + sqlite3_result_text,
39.202 + sqlite3_result_text16,
39.203 + sqlite3_result_text16be,
39.204 + sqlite3_result_text16le,
39.205 + sqlite3_result_value,
39.206 + sqlite3_rollback_hook,
39.207 + sqlite3_set_authorizer,
39.208 + sqlite3_set_auxdata,
39.209 + sqlite3_snprintf,
39.210 + sqlite3_step,
39.211 + sqlite3_table_column_metadata,
39.212 + sqlite3_thread_cleanup,
39.213 + sqlite3_total_changes,
39.214 + sqlite3_trace,
39.215 + sqlite3_transfer_bindings,
39.216 + sqlite3_update_hook,
39.217 + sqlite3_user_data,
39.218 + sqlite3_value_blob,
39.219 + sqlite3_value_bytes,
39.220 + sqlite3_value_bytes16,
39.221 + sqlite3_value_double,
39.222 + sqlite3_value_int,
39.223 + sqlite3_value_int64,
39.224 + sqlite3_value_numeric_type,
39.225 + sqlite3_value_text,
39.226 + sqlite3_value_text16,
39.227 + sqlite3_value_text16be,
39.228 + sqlite3_value_text16le,
39.229 + sqlite3_value_type,
39.230 + sqlite3_vmprintf,
39.231 + /*
39.232 + ** The original API set ends here. All extensions can call any
39.233 + ** of the APIs above provided that the pointer is not NULL. But
39.234 + ** before calling APIs that follow, extension should check the
39.235 + ** sqlite3_libversion_number() to make sure they are dealing with
39.236 + ** a library that is new enough to support that API.
39.237 + *************************************************************************
39.238 + */
39.239 + sqlite3_overload_function,
39.240 +
39.241 + /*
39.242 + ** Added after 3.3.13
39.243 + */
39.244 + sqlite3_prepare_v2,
39.245 + sqlite3_prepare16_v2,
39.246 + sqlite3_clear_bindings,
39.247 +
39.248 + /*
39.249 + ** Added for 3.4.1
39.250 + */
39.251 + sqlite3_create_module_v2,
39.252 +
39.253 +};
39.254 +
39.255 +/*
39.256 +** Attempt to load an SQLite extension library contained in the file
39.257 +** zFile. The entry point is zProc. zProc may be 0 in which case a
39.258 +** default entry point name (sqlite3_extension_init) is used. Use
39.259 +** of the default name is recommended.
39.260 +**
39.261 +** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
39.262 +**
39.263 +** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
39.264 +** error message text. The calling function should free this memory
39.265 +** by calling sqlite3_free().
39.266 +*/
39.267 +int sqlite3_load_extension(
39.268 + sqlite3 *db, /* Load the extension into this database connection */
39.269 + const char *zFile, /* Name of the shared library containing extension */
39.270 + const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
39.271 + char **pzErrMsg /* Put error message here if not 0 */
39.272 +){
39.273 + void *handle;
39.274 + int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
39.275 + char *zErrmsg = 0;
39.276 + void **aHandle;
39.277 +
39.278 + /* Ticket #1863. To avoid a creating security problems for older
39.279 + ** applications that relink against newer versions of SQLite, the
39.280 + ** ability to run load_extension is turned off by default. One
39.281 + ** must call sqlite3_enable_load_extension() to turn on extension
39.282 + ** loading. Otherwise you get the following error.
39.283 + */
39.284 + if( (db->flags & SQLITE_LoadExtension)==0 ){
39.285 + if( pzErrMsg ){
39.286 + *pzErrMsg = sqlite3_mprintf("not authorized");
39.287 + }
39.288 + return SQLITE_ERROR;
39.289 + }
39.290 +
39.291 + if( zProc==0 ){
39.292 + zProc = "sqlite3_extension_init";
39.293 + }
39.294 +
39.295 + handle = sqlite3OsDlopen(zFile);
39.296 + if( handle==0 ){
39.297 + if( pzErrMsg ){
39.298 + *pzErrMsg = sqlite3_mprintf("unable to open shared library [%s]", zFile);
39.299 + }
39.300 + return SQLITE_ERROR;
39.301 + }
39.302 + xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
39.303 + sqlite3OsDlsym(handle, zProc);
39.304 + if( xInit==0 ){
39.305 + if( pzErrMsg ){
39.306 + *pzErrMsg = sqlite3_mprintf("no entry point [%s] in shared library [%s]",
39.307 + zProc, zFile);
39.308 + }
39.309 + sqlite3OsDlclose(handle);
39.310 + return SQLITE_ERROR;
39.311 + }else if( xInit(db, &zErrmsg, &sqlite3_apis) ){
39.312 + if( pzErrMsg ){
39.313 + *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
39.314 + }
39.315 + sqlite3_free(zErrmsg);
39.316 + sqlite3OsDlclose(handle);
39.317 + return SQLITE_ERROR;
39.318 + }
39.319 +
39.320 + /* Append the new shared library handle to the db->aExtension array. */
39.321 + db->nExtension++;
39.322 + aHandle = sqliteMalloc(sizeof(handle)*db->nExtension);
39.323 + if( aHandle==0 ){
39.324 + return SQLITE_NOMEM;
39.325 + }
39.326 + if( db->nExtension>0 ){
39.327 + memcpy(aHandle, db->aExtension, sizeof(handle)*(db->nExtension-1));
39.328 + }
39.329 + sqliteFree(db->aExtension);
39.330 + db->aExtension = aHandle;
39.331 +
39.332 + db->aExtension[db->nExtension-1] = handle;
39.333 + return SQLITE_OK;
39.334 +}
39.335 +
39.336 +/*
39.337 +** Call this routine when the database connection is closing in order
39.338 +** to clean up loaded extensions
39.339 +*/
39.340 +void sqlite3CloseExtensions(sqlite3 *db){
39.341 + int i;
39.342 + for(i=0; i<db->nExtension; i++){
39.343 + sqlite3OsDlclose(db->aExtension[i]);
39.344 + }
39.345 + sqliteFree(db->aExtension);
39.346 +}
39.347 +
39.348 +/*
39.349 +** Enable or disable extension loading. Extension loading is disabled by
39.350 +** default so as not to open security holes in older applications.
39.351 +*/
39.352 +int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
39.353 + if( onoff ){
39.354 + db->flags |= SQLITE_LoadExtension;
39.355 + }else{
39.356 + db->flags &= ~SQLITE_LoadExtension;
39.357 + }
39.358 + return SQLITE_OK;
39.359 +}
39.360 +
39.361 +/*
39.362 +** A list of automatically loaded extensions.
39.363 +**
39.364 +** This list is shared across threads, so be sure to hold the
39.365 +** mutex while accessing or changing it.
39.366 +*/
39.367 +static int nAutoExtension = 0;
39.368 +static void **aAutoExtension = 0;
39.369 +
39.370 +
39.371 +/*
39.372 +** Register a statically linked extension that is automatically
39.373 +** loaded by every new database connection.
39.374 +*/
39.375 +int sqlite3_auto_extension(void *xInit){
39.376 + int i;
39.377 + int rc = SQLITE_OK;
39.378 + sqlite3OsEnterMutex();
39.379 + for(i=0; i<nAutoExtension; i++){
39.380 + if( aAutoExtension[i]==xInit ) break;
39.381 + }
39.382 + if( i==nAutoExtension ){
39.383 + nAutoExtension++;
39.384 + aAutoExtension = sqlite3Realloc( aAutoExtension,
39.385 + nAutoExtension*sizeof(aAutoExtension[0]) );
39.386 + if( aAutoExtension==0 ){
39.387 + nAutoExtension = 0;
39.388 + rc = SQLITE_NOMEM;
39.389 + }else{
39.390 + aAutoExtension[nAutoExtension-1] = xInit;
39.391 + }
39.392 + }
39.393 + sqlite3OsLeaveMutex();
39.394 + assert( (rc&0xff)==rc );
39.395 + return rc;
39.396 +}
39.397 +
39.398 +/*
39.399 +** Reset the automatic extension loading mechanism.
39.400 +*/
39.401 +void sqlite3_reset_auto_extension(void){
39.402 + sqlite3OsEnterMutex();
39.403 + sqliteFree(aAutoExtension);
39.404 + aAutoExtension = 0;
39.405 + nAutoExtension = 0;
39.406 + sqlite3OsLeaveMutex();
39.407 +}
39.408 +
39.409 +/*
39.410 +** Load all automatic extensions.
39.411 +*/
39.412 +int sqlite3AutoLoadExtensions(sqlite3 *db){
39.413 + int i;
39.414 + int go = 1;
39.415 + int rc = SQLITE_OK;
39.416 + int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
39.417 +
39.418 + if( nAutoExtension==0 ){
39.419 + /* Common case: early out without every having to acquire a mutex */
39.420 + return SQLITE_OK;
39.421 + }
39.422 + for(i=0; go; i++){
39.423 + char *zErrmsg = 0;
39.424 + sqlite3OsEnterMutex();
39.425 + if( i>=nAutoExtension ){
39.426 + xInit = 0;
39.427 + go = 0;
39.428 + }else{
39.429 + xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
39.430 + aAutoExtension[i];
39.431 + }
39.432 + sqlite3OsLeaveMutex();
39.433 + if( xInit && xInit(db, &zErrmsg, &sqlite3_apis) ){
39.434 + sqlite3Error(db, SQLITE_ERROR,
39.435 + "automatic extension loading failed: %s", zErrmsg);
39.436 + go = 0;
39.437 + rc = SQLITE_ERROR;
39.438 + }
39.439 + }
39.440 + return rc;
39.441 +}
39.442 +
39.443 +#endif /* SQLITE_OMIT_LOAD_EXTENSION */
40.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
40.2 +++ b/extensions/sqlite/sqlite-source/main.c Sun Jul 29 01:15:31 2007 +0000
40.3 @@ -0,0 +1,1442 @@
40.4 +/*
40.5 +** 2001 September 15
40.6 +**
40.7 +** The author disclaims copyright to this source code. In place of
40.8 +** a legal notice, here is a blessing:
40.9 +**
40.10 +** May you do good and not evil.
40.11 +** May you find forgiveness for yourself and forgive others.
40.12 +** May you share freely, never taking more than you give.
40.13 +**
40.14 +*************************************************************************
40.15 +** Main file for the SQLite library. The routines in this file
40.16 +** implement the programmer interface to the library. Routines in
40.17 +** other files are for internal use by SQLite and should not be
40.18 +** accessed by users of the library.
40.19 +**
40.20 +** $Id$
40.21 +*/
40.22 +#include "sqliteInt.h"
40.23 +#include "os.h"
40.24 +#include <ctype.h>
40.25 +
40.26 +/*
40.27 +** The version of the library
40.28 +*/
40.29 +const char sqlite3_version[] = SQLITE_VERSION;
40.30 +const char *sqlite3_libversion(void){ return sqlite3_version; }
40.31 +int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
40.32 +
40.33 +/*
40.34 +** If the following function pointer is not NULL and if
40.35 +** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
40.36 +** I/O active are written using this function. These messages
40.37 +** are intended for debugging activity only.
40.38 +*/
40.39 +void (*sqlite3_io_trace)(const char*, ...) = 0;
40.40 +
40.41 +/*
40.42 +** If the following global variable points to a string which is the
40.43 +** name of a directory, then that directory will be used to store
40.44 +** temporary files.
40.45 +**
40.46 +** See also the "PRAGMA temp_store_directory" SQL command.
40.47 +*/
40.48 +char *sqlite3_temp_directory = 0;
40.49 +
40.50 +
40.51 +/*
40.52 +** This is the default collating function named "BINARY" which is always
40.53 +** available.
40.54 +*/
40.55 +static int binCollFunc(
40.56 + void *NotUsed,
40.57 + int nKey1, const void *pKey1,
40.58 + int nKey2, const void *pKey2
40.59 +){
40.60 + int rc, n;
40.61 + n = nKey1<nKey2 ? nKey1 : nKey2;
40.62 + rc = memcmp(pKey1, pKey2, n);
40.63 + if( rc==0 ){
40.64 + rc = nKey1 - nKey2;
40.65 + }
40.66 + return rc;
40.67 +}
40.68 +
40.69 +/*
40.70 +** Another built-in collating sequence: NOCASE.
40.71 +**
40.72 +** This collating sequence is intended to be used for "case independant
40.73 +** comparison". SQLite's knowledge of upper and lower case equivalents
40.74 +** extends only to the 26 characters used in the English language.
40.75 +**
40.76 +** At the moment there is only a UTF-8 implementation.
40.77 +*/
40.78 +static int nocaseCollatingFunc(
40.79 + void *NotUsed,
40.80 + int nKey1, const void *pKey1,
40.81 + int nKey2, const void *pKey2
40.82 +){
40.83 + int r = sqlite3StrNICmp(
40.84 + (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
40.85 + if( 0==r ){
40.86 + r = nKey1-nKey2;
40.87 + }
40.88 + return r;
40.89 +}
40.90 +
40.91 +/*
40.92 +** Return the ROWID of the most recent insert
40.93 +*/
40.94 +sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
40.95 + return db->lastRowid;
40.96 +}
40.97 +
40.98 +/*
40.99 +** Return the number of changes in the most recent call to sqlite3_exec().
40.100 +*/
40.101 +int sqlite3_changes(sqlite3 *db){
40.102 + return db->nChange;
40.103 +}
40.104 +
40.105 +/*
40.106 +** Return the number of changes since the database handle was opened.
40.107 +*/
40.108 +int sqlite3_total_changes(sqlite3 *db){
40.109 + return db->nTotalChange;
40.110 +}
40.111 +
40.112 +/*
40.113 +** Close an existing SQLite database
40.114 +*/
40.115 +int sqlite3_close(sqlite3 *db){
40.116 + HashElem *i;
40.117 + int j;
40.118 +
40.119 + if( !db ){
40.120 + return SQLITE_OK;
40.121 + }
40.122 + if( sqlite3SafetyCheck(db) ){
40.123 + return SQLITE_MISUSE;
40.124 + }
40.125 +
40.126 +#ifdef SQLITE_SSE
40.127 + {
40.128 + extern void sqlite3SseCleanup(sqlite3*);
40.129 + sqlite3SseCleanup(db);
40.130 + }
40.131 +#endif
40.132 +
40.133 + sqlite3ResetInternalSchema(db, 0);
40.134 +
40.135 + /* If a transaction is open, the ResetInternalSchema() call above
40.136 + ** will not have called the xDisconnect() method on any virtual
40.137 + ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
40.138 + ** call will do so. We need to do this before the check for active
40.139 + ** SQL statements below, as the v-table implementation may be storing
40.140 + ** some prepared statements internally.
40.141 + */
40.142 + sqlite3VtabRollback(db);
40.143 +
40.144 + /* If there are any outstanding VMs, return SQLITE_BUSY. */
40.145 + if( db->pVdbe ){
40.146 + sqlite3Error(db, SQLITE_BUSY,
40.147 + "Unable to close due to unfinalised statements");
40.148 + return SQLITE_BUSY;
40.149 + }
40.150 + assert( !sqlite3SafetyCheck(db) );
40.151 +
40.152 + /* FIX ME: db->magic may be set to SQLITE_MAGIC_CLOSED if the database
40.153 + ** cannot be opened for some reason. So this routine needs to run in
40.154 + ** that case. But maybe there should be an extra magic value for the
40.155 + ** "failed to open" state.
40.156 + **
40.157 + ** TODO: Coverage tests do not test the case where this condition is
40.158 + ** true. It's hard to see how to cause it without messing with threads.
40.159 + */
40.160 + if( db->magic!=SQLITE_MAGIC_CLOSED && sqlite3SafetyOn(db) ){
40.161 + /* printf("DID NOT CLOSE\n"); fflush(stdout); */
40.162 + return SQLITE_ERROR;
40.163 + }
40.164 +
40.165 + for(j=0; j<db->nDb; j++){
40.166 + struct Db *pDb = &db->aDb[j];
40.167 + if( pDb->pBt ){
40.168 + sqlite3BtreeClose(pDb->pBt);
40.169 + pDb->pBt = 0;
40.170 + if( j!=1 ){
40.171 + pDb->pSchema = 0;
40.172 + }
40.173 + }
40.174 + }
40.175 + sqlite3ResetInternalSchema(db, 0);
40.176 + assert( db->nDb<=2 );
40.177 + assert( db->aDb==db->aDbStatic );
40.178 + for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
40.179 + FuncDef *pFunc, *pNext;
40.180 + for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
40.181 + pNext = pFunc->pNext;
40.182 + sqliteFree(pFunc);
40.183 + }
40.184 + }
40.185 +
40.186 + for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
40.187 + CollSeq *pColl = (CollSeq *)sqliteHashData(i);
40.188 + /* Invoke any destructors registered for collation sequence user data. */
40.189 + for(j=0; j<3; j++){
40.190 + if( pColl[j].xDel ){
40.191 + pColl[j].xDel(pColl[j].pUser);
40.192 + }
40.193 + }
40.194 + sqliteFree(pColl);
40.195 + }
40.196 + sqlite3HashClear(&db->aCollSeq);
40.197 +#ifndef SQLITE_OMIT_VIRTUALTABLE
40.198 + for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
40.199 + Module *pMod = (Module *)sqliteHashData(i);
40.200 + if( pMod->xDestroy ){
40.201 + pMod->xDestroy(pMod->pAux);
40.202 + }
40.203 + sqliteFree(pMod);
40.204 + }
40.205 + sqlite3HashClear(&db->aModule);
40.206 +#endif
40.207 +
40.208 + sqlite3HashClear(&db->aFunc);
40.209 + sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
40.210 + if( db->pErr ){
40.211 + sqlite3ValueFree(db->pErr);
40.212 + }
40.213 + sqlite3CloseExtensions(db);
40.214 +
40.215 + db->magic = SQLITE_MAGIC_ERROR;
40.216 +
40.217 + /* The temp-database schema is allocated differently from the other schema
40.218 + ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
40.219 + ** So it needs to be freed here. Todo: Why not roll the temp schema into
40.220 + ** the same sqliteMalloc() as the one that allocates the database
40.221 + ** structure?
40.222 + */
40.223 + sqliteFree(db->aDb[1].pSchema);
40.224 + sqliteFree(db);
40.225 + sqlite3ReleaseThreadData();
40.226 + return SQLITE_OK;
40.227 +}
40.228 +
40.229 +/*
40.230 +** Rollback all database files.
40.231 +*/
40.232 +void sqlite3RollbackAll(sqlite3 *db){
40.233 + int i;
40.234 + int inTrans = 0;
40.235 + for(i=0; i<db->nDb; i++){
40.236 + if( db->aDb[i].pBt ){
40.237 + if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
40.238 + inTrans = 1;
40.239 + }
40.240 + sqlite3BtreeRollback(db->aDb[i].pBt);
40.241 + db->aDb[i].inTrans = 0;
40.242 + }
40.243 + }
40.244 + sqlite3VtabRollback(db);
40.245 + if( db->flags&SQLITE_InternChanges ){
40.246 + sqlite3ResetInternalSchema(db, 0);
40.247 + }
40.248 +
40.249 + /* If one has been configured, invoke the rollback-hook callback */
40.250 + if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
40.251 + db->xRollbackCallback(db->pRollbackArg);
40.252 + }
40.253 +}
40.254 +
40.255 +/*
40.256 +** Return a static string that describes the kind of error specified in the
40.257 +** argument.
40.258 +*/
40.259 +const char *sqlite3ErrStr(int rc){
40.260 + const char *z;
40.261 + switch( rc & 0xff ){
40.262 + case SQLITE_ROW:
40.263 + case SQLITE_DONE:
40.264 + case SQLITE_OK: z = "not an error"; break;
40.265 + case SQLITE_ERROR: z = "SQL logic error or missing database"; break;
40.266 + case SQLITE_PERM: z = "access permission denied"; break;
40.267 + case SQLITE_ABORT: z = "callback requested query abort"; break;
40.268 + case SQLITE_BUSY: z = "database is locked"; break;
40.269 + case SQLITE_LOCKED: z = "database table is locked"; break;
40.270 + case SQLITE_NOMEM: z = "out of memory"; break;
40.271 + case SQLITE_READONLY: z = "attempt to write a readonly database"; break;
40.272 + case SQLITE_INTERRUPT: z = "interrupted"; break;
40.273 + case SQLITE_IOERR: z = "disk I/O error"; break;
40.274 + case SQLITE_CORRUPT: z = "database disk image is malformed"; break;
40.275 + case SQLITE_FULL: z = "database or disk is full"; break;
40.276 + case SQLITE_CANTOPEN: z = "unable to open database file"; break;
40.277 + case SQLITE_EMPTY: z = "table contains no data"; break;
40.278 + case SQLITE_SCHEMA: z = "database schema has changed"; break;
40.279 + case SQLITE_TOOBIG: z = "String or BLOB exceeded size limit"; break;
40.280 + case SQLITE_CONSTRAINT: z = "constraint failed"; break;
40.281 + case SQLITE_MISMATCH: z = "datatype mismatch"; break;
40.282 + case SQLITE_MISUSE: z = "library routine called out of sequence";break;
40.283 + case SQLITE_NOLFS: z = "kernel lacks large file support"; break;
40.284 + case SQLITE_AUTH: z = "authorization denied"; break;
40.285 + case SQLITE_FORMAT: z = "auxiliary database format error"; break;
40.286 + case SQLITE_RANGE: z = "bind or column index out of range"; break;
40.287 + case SQLITE_NOTADB: z = "file is encrypted or is not a database";break;
40.288 + default: z = "unknown error"; break;
40.289 + }
40.290 + return z;
40.291 +}
40.292 +
40.293 +/*
40.294 +** This routine implements a busy callback that sleeps and tries
40.295 +** again until a timeout value is reached. The timeout value is
40.296 +** an integer number of milliseconds passed in as the first
40.297 +** argument.
40.298 +*/
40.299 +static int sqliteDefaultBusyCallback(
40.300 + void *ptr, /* Database connection */
40.301 + int count /* Number of times table has been busy */
40.302 +){
40.303 +#if OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
40.304 + static const u8 delays[] =
40.305 + { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
40.306 + static const u8 totals[] =
40.307 + { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
40.308 +# define NDELAY (sizeof(delays)/sizeof(delays[0]))
40.309 + int timeout = ((sqlite3 *)ptr)->busyTimeout;
40.310 + int delay, prior;
40.311 +
40.312 + assert( count>=0 );
40.313 + if( count < NDELAY ){
40.314 + delay = delays[count];
40.315 + prior = totals[count];
40.316 + }else{
40.317 + delay = delays[NDELAY-1];
40.318 + prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
40.319 + }
40.320 + if( prior + delay > timeout ){
40.321 + delay = timeout - prior;
40.322 + if( delay<=0 ) return 0;
40.323 + }
40.324 + sqlite3OsSleep(delay);
40.325 + return 1;
40.326 +#else
40.327 + int timeout = ((sqlite3 *)ptr)->busyTimeout;
40.328 + if( (count+1)*1000 > timeout ){
40.329 + return 0;
40.330 + }
40.331 + sqlite3OsSleep(1000);
40.332 + return 1;
40.333 +#endif
40.334 +}
40.335 +
40.336 +/*
40.337 +** Invoke the given busy handler.
40.338 +**
40.339 +** This routine is called when an operation failed with a lock.
40.340 +** If this routine returns non-zero, the lock is retried. If it
40.341 +** returns 0, the operation aborts with an SQLITE_BUSY error.
40.342 +*/
40.343 +int sqlite3InvokeBusyHandler(BusyHandler *p){
40.344 + int rc;
40.345 + if( p==0 || p->xFunc==0 || p->nBusy<0 ) return 0;
40.346 + rc = p->xFunc(p->pArg, p->nBusy);
40.347 + if( rc==0 ){
40.348 + p->nBusy = -1;
40.349 + }else{
40.350 + p->nBusy++;
40.351 + }
40.352 + return rc;
40.353 +}
40.354 +
40.355 +/*
40.356 +** This routine sets the busy callback for an Sqlite database to the
40.357 +** given callback function with the given argument.
40.358 +*/
40.359 +int sqlite3_busy_handler(
40.360 + sqlite3 *db,
40.361 + int (*xBusy)(void*,int),
40.362 + void *pArg
40.363 +){
40.364 + if( sqlite3SafetyCheck(db) ){
40.365 + return SQLITE_MISUSE;
40.366 + }
40.367 + db->busyHandler.xFunc = xBusy;
40.368 + db->busyHandler.pArg = pArg;
40.369 + db->busyHandler.nBusy = 0;
40.370 + return SQLITE_OK;
40.371 +}
40.372 +
40.373 +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
40.374 +/*
40.375 +** This routine sets the progress callback for an Sqlite database to the
40.376 +** given callback function with the given argument. The progress callback will
40.377 +** be invoked every nOps opcodes.
40.378 +*/
40.379 +void sqlite3_progress_handler(
40.380 + sqlite3 *db,
40.381 + int nOps,
40.382 + int (*xProgress)(void*),
40.383 + void *pArg
40.384 +){
40.385 + if( !sqlite3SafetyCheck(db) ){
40.386 + if( nOps>0 ){
40.387 + db->xProgress = xProgress;
40.388 + db->nProgressOps = nOps;
40.389 + db->pProgressArg = pArg;
40.390 + }else{
40.391 + db->xProgress = 0;
40.392 + db->nProgressOps = 0;
40.393 + db->pProgressArg = 0;
40.394 + }
40.395 + }
40.396 +}
40.397 +#endif
40.398 +
40.399 +
40.400 +/*
40.401 +** This routine installs a default busy handler that waits for the
40.402 +** specified number of milliseconds before returning 0.
40.403 +*/
40.404 +int sqlite3_busy_timeout(sqlite3 *db, int ms){
40.405 + if( sqlite3SafetyCheck(db) ){
40.406 + return SQLITE_MISUSE;
40.407 + }
40.408 + if( ms>0 ){
40.409 + db->busyTimeout = ms;
40.410 + sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
40.411 + }else{
40.412 + sqlite3_busy_handler(db, 0, 0);
40.413 + }
40.414 + return SQLITE_OK;
40.415 +}
40.416 +
40.417 +/*
40.418 +** Cause any pending operation to stop at its earliest opportunity.
40.419 +*/
40.420 +void sqlite3_interrupt(sqlite3 *db){
40.421 + if( db && (db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_BUSY) ){
40.422 + db->u1.isInterrupted = 1;
40.423 + }
40.424 +}
40.425 +
40.426 +/*
40.427 +** Memory allocation routines that use SQLites internal memory
40.428 +** memory allocator. Depending on how SQLite is compiled, the
40.429 +** internal memory allocator might be just an alias for the
40.430 +** system default malloc/realloc/free. Or the built-in allocator
40.431 +** might do extra stuff like put sentinals around buffers to
40.432 +** check for overruns or look for memory leaks.
40.433 +**
40.434 +** Use sqlite3_free() to free memory returned by sqlite3_mprintf().
40.435 +*/
40.436 +void sqlite3_free(void *p){ if( p ) sqlite3OsFree(p); }
40.437 +void *sqlite3_malloc(int nByte){ return nByte>0 ? sqlite3OsMalloc(nByte) : 0; }
40.438 +void *sqlite3_realloc(void *pOld, int nByte){
40.439 + if( pOld ){
40.440 + if( nByte>0 ){
40.441 + return sqlite3OsRealloc(pOld, nByte);
40.442 + }else{
40.443 + sqlite3OsFree(pOld);
40.444 + return 0;
40.445 + }
40.446 + }else{
40.447 + return sqlite3_malloc(nByte);
40.448 + }
40.449 +}
40.450 +
40.451 +/*
40.452 +** This function is exactly the same as sqlite3_create_function(), except
40.453 +** that it is designed to be called by internal code. The difference is
40.454 +** that if a malloc() fails in sqlite3_create_function(), an error code
40.455 +** is returned and the mallocFailed flag cleared.
40.456 +*/
40.457 +int sqlite3CreateFunc(
40.458 + sqlite3 *db,
40.459 + const char *zFunctionName,
40.460 + int nArg,
40.461 + int enc,
40.462 + void *pUserData,
40.463 + void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
40.464 + void (*xStep)(sqlite3_context*,int,sqlite3_value **),
40.465 + void (*xFinal)(sqlite3_context*)
40.466 +){
40.467 + FuncDef *p;
40.468 + int nName;
40.469 +
40.470 + if( sqlite3SafetyCheck(db) ){
40.471 + return SQLITE_MISUSE;
40.472 + }
40.473 + if( zFunctionName==0 ||
40.474 + (xFunc && (xFinal || xStep)) ||
40.475 + (!xFunc && (xFinal && !xStep)) ||
40.476 + (!xFunc && (!xFinal && xStep)) ||
40.477 + (nArg<-1 || nArg>127) ||
40.478 + (255<(nName = strlen(zFunctionName))) ){
40.479 + sqlite3Error(db, SQLITE_ERROR, "bad parameters");
40.480 + return SQLITE_ERROR;
40.481 + }
40.482 +
40.483 +#ifndef SQLITE_OMIT_UTF16
40.484 + /* If SQLITE_UTF16 is specified as the encoding type, transform this
40.485 + ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
40.486 + ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
40.487 + **
40.488 + ** If SQLITE_ANY is specified, add three versions of the function
40.489 + ** to the hash table.
40.490 + */
40.491 + if( enc==SQLITE_UTF16 ){
40.492 + enc = SQLITE_UTF16NATIVE;
40.493 + }else if( enc==SQLITE_ANY ){
40.494 + int rc;
40.495 + rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
40.496 + pUserData, xFunc, xStep, xFinal);
40.497 + if( rc!=SQLITE_OK ) return rc;
40.498 + rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
40.499 + pUserData, xFunc, xStep, xFinal);
40.500 + if( rc!=SQLITE_OK ) return rc;
40.501 + enc = SQLITE_UTF16BE;
40.502 + }
40.503 +#else
40.504 + enc = SQLITE_UTF8;
40.505 +#endif
40.506 +
40.507 + /* Check if an existing function is being overridden or deleted. If so,
40.508 + ** and there are active VMs, then return SQLITE_BUSY. If a function
40.509 + ** is being overridden/deleted but there are no active VMs, allow the
40.510 + ** operation to continue but invalidate all precompiled statements.
40.511 + */
40.512 + p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);
40.513 + if( p && p->iPrefEnc==enc && p->nArg==nArg ){
40.514 + if( db->activeVdbeCnt ){
40.515 + sqlite3Error(db, SQLITE_BUSY,
40.516 + "Unable to delete/modify user-function due to active statements");
40.517 + assert( !sqlite3MallocFailed() );
40.518 + return SQLITE_BUSY;
40.519 + }else{
40.520 + sqlite3ExpirePreparedStatements(db);
40.521 + }
40.522 + }
40.523 +
40.524 + p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);
40.525 + if( p ){
40.526 + p->flags = 0;
40.527 + p->xFunc = xFunc;
40.528 + p->xStep = xStep;
40.529 + p->xFinalize = xFinal;
40.530 + p->pUserData = pUserData;
40.531 + p->nArg = nArg;
40.532 + }
40.533 + return SQLITE_OK;
40.534 +}
40.535 +
40.536 +/*
40.537 +** Create new user functions.
40.538 +*/
40.539 +int sqlite3_create_function(
40.540 + sqlite3 *db,
40.541 + const char *zFunctionName,
40.542 + int nArg,
40.543 + int enc,
40.544 + void *p,
40.545 + void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
40.546 + void (*xStep)(sqlite3_context*,int,sqlite3_value **),
40.547 + void (*xFinal)(sqlite3_context*)
40.548 +){
40.549 + int rc;
40.550 + assert( !sqlite3MallocFailed() );
40.551 + rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
40.552 +
40.553 + return sqlite3ApiExit(db, rc);
40.554 +}
40.555 +
40.556 +#ifndef SQLITE_OMIT_UTF16
40.557 +int sqlite3_create_function16(
40.558 + sqlite3 *db,
40.559 + const void *zFunctionName,
40.560 + int nArg,
40.561 + int eTextRep,
40.562 + void *p,
40.563 + void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
40.564 + void (*xStep)(sqlite3_context*,int,sqlite3_value**),
40.565 + void (*xFinal)(sqlite3_context*)
40.566 +){
40.567 + int rc;
40.568 + char *zFunc8;
40.569 + assert( !sqlite3MallocFailed() );
40.570 +
40.571 + zFunc8 = sqlite3Utf16to8(zFunctionName, -1);
40.572 + rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
40.573 + sqliteFree(zFunc8);
40.574 +
40.575 + return sqlite3ApiExit(db, rc);
40.576 +}
40.577 +#endif
40.578 +
40.579 +
40.580 +/*
40.581 +** Declare that a function has been overloaded by a virtual table.
40.582 +**
40.583 +** If the function already exists as a regular global function, then
40.584 +** this routine is a no-op. If the function does not exist, then create
40.585 +** a new one that always throws a run-time error.
40.586 +**
40.587 +** When virtual tables intend to provide an overloaded function, they
40.588 +** should call this routine to make sure the global function exists.
40.589 +** A global function must exist in order for name resolution to work
40.590 +** properly.
40.591 +*/
40.592 +int sqlite3_overload_function(
40.593 + sqlite3 *db,
40.594 + const char *zName,
40.595 + int nArg
40.596 +){
40.597 + int nName = strlen(zName);
40.598 + if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
40.599 + sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
40.600 + 0, sqlite3InvalidFunction, 0, 0);
40.601 + }
40.602 + return sqlite3ApiExit(db, SQLITE_OK);
40.603 +}
40.604 +
40.605 +#ifndef SQLITE_OMIT_TRACE
40.606 +/*
40.607 +** Register a trace function. The pArg from the previously registered trace
40.608 +** is returned.
40.609 +**
40.610 +** A NULL trace function means that no tracing is executes. A non-NULL
40.611 +** trace is a pointer to a function that is invoked at the start of each
40.612 +** SQL statement.
40.613 +*/
40.614 +void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
40.615 + void *pOld = db->pTraceArg;
40.616 + db->xTrace = xTrace;
40.617 + db->pTraceArg = pArg;
40.618 + return pOld;
40.619 +}
40.620 +/*
40.621 +** Register a profile function. The pArg from the previously registered
40.622 +** profile function is returned.
40.623 +**
40.624 +** A NULL profile function means that no profiling is executes. A non-NULL
40.625 +** profile is a pointer to a function that is invoked at the conclusion of
40.626 +** each SQL statement that is run.
40.627 +*/
40.628 +void *sqlite3_profile(
40.629 + sqlite3 *db,
40.630 + void (*xProfile)(void*,const char*,sqlite_uint64),
40.631 + void *pArg
40.632 +){
40.633 + void *pOld = db->pProfileArg;
40.634 + db->xProfile = xProfile;
40.635 + db->pProfileArg = pArg;
40.636 + return pOld;
40.637 +}
40.638 +#endif /* SQLITE_OMIT_TRACE */
40.639 +
40.640 +/*** EXPERIMENTAL ***
40.641 +**
40.642 +** Register a function to be invoked when a transaction comments.
40.643 +** If the invoked function returns non-zero, then the commit becomes a
40.644 +** rollback.
40.645 +*/
40.646 +void *sqlite3_commit_hook(
40.647 + sqlite3 *db, /* Attach the hook to this database */
40.648 + int (*xCallback)(void*), /* Function to invoke on each commit */
40.649 + void *pArg /* Argument to the function */
40.650 +){
40.651 + void *pOld = db->pCommitArg;
40.652 + db->xCommitCallback = xCallback;
40.653 + db->pCommitArg = pArg;
40.654 + return pOld;
40.655 +}
40.656 +
40.657 +/*
40.658 +** Register a callback to be invoked each time a row is updated,
40.659 +** inserted or deleted using this database connection.
40.660 +*/
40.661 +void *sqlite3_update_hook(
40.662 + sqlite3 *db, /* Attach the hook to this database */
40.663 + void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
40.664 + void *pArg /* Argument to the function */
40.665 +){
40.666 + void *pRet = db->pUpdateArg;
40.667 + db->xUpdateCallback = xCallback;
40.668 + db->pUpdateArg = pArg;
40.669 + return pRet;
40.670 +}
40.671 +
40.672 +/*
40.673 +** Register a callback to be invoked each time a transaction is rolled
40.674 +** back by this database connection.
40.675 +*/
40.676 +void *sqlite3_rollback_hook(
40.677 + sqlite3 *db, /* Attach the hook to this database */
40.678 + void (*xCallback)(void*), /* Callback function */
40.679 + void *pArg /* Argument to the function */
40.680 +){
40.681 + void *pRet = db->pRollbackArg;
40.682 + db->xRollbackCallback = xCallback;
40.683 + db->pRollbackArg = pArg;
40.684 + return pRet;
40.685 +}
40.686 +
40.687 +/*
40.688 +** This routine is called to create a connection to a database BTree
40.689 +** driver. If zFilename is the name of a file, then that file is
40.690 +** opened and used. If zFilename is the magic name ":memory:" then
40.691 +** the database is stored in memory (and is thus forgotten as soon as
40.692 +** the connection is closed.) If zFilename is NULL then the database
40.693 +** is a "virtual" database for transient use only and is deleted as
40.694 +** soon as the connection is closed.
40.695 +**
40.696 +** A virtual database can be either a disk file (that is automatically
40.697 +** deleted when the file is closed) or it an be held entirely in memory,
40.698 +** depending on the values of the TEMP_STORE compile-time macro and the
40.699 +** db->temp_store variable, according to the following chart:
40.700 +**
40.701 +** TEMP_STORE db->temp_store Location of temporary database
40.702 +** ---------- -------------- ------------------------------
40.703 +** 0 any file
40.704 +** 1 1 file
40.705 +** 1 2 memory
40.706 +** 1 0 file
40.707 +** 2 1 file
40.708 +** 2 2 memory
40.709 +** 2 0 memory
40.710 +** 3 any memory
40.711 +*/
40.712 +int sqlite3BtreeFactory(
40.713 + const sqlite3 *db, /* Main database when opening aux otherwise 0 */
40.714 + const char *zFilename, /* Name of the file containing the BTree database */
40.715 + int omitJournal, /* if TRUE then do not journal this file */
40.716 + int nCache, /* How many pages in the page cache */
40.717 + Btree **ppBtree /* Pointer to new Btree object written here */
40.718 +){
40.719 + int btree_flags = 0;
40.720 + int rc;
40.721 +
40.722 + assert( ppBtree != 0);
40.723 + if( omitJournal ){
40.724 + btree_flags |= BTREE_OMIT_JOURNAL;
40.725 + }
40.726 + if( db->flags & SQLITE_NoReadlock ){
40.727 + btree_flags |= BTREE_NO_READLOCK;
40.728 + }
40.729 + if( zFilename==0 ){
40.730 +#if TEMP_STORE==0
40.731 + /* Do nothing */
40.732 +#endif
40.733 +#ifndef SQLITE_OMIT_MEMORYDB
40.734 +#if TEMP_STORE==1
40.735 + if( db->temp_store==2 ) zFilename = ":memory:";
40.736 +#endif
40.737 +#if TEMP_STORE==2
40.738 + if( db->temp_store!=1 ) zFilename = ":memory:";
40.739 +#endif
40.740 +#if TEMP_STORE==3
40.741 + zFilename = ":memory:";
40.742 +#endif
40.743 +#endif /* SQLITE_OMIT_MEMORYDB */
40.744 + }
40.745 +
40.746 + rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btree_flags);
40.747 + if( rc==SQLITE_OK ){
40.748 + sqlite3BtreeSetBusyHandler(*ppBtree, (void*)&db->busyHandler);
40.749 + sqlite3BtreeSetCacheSize(*ppBtree, nCache);
40.750 + }
40.751 + return rc;
40.752 +}
40.753 +
40.754 +/*
40.755 +** Return UTF-8 encoded English language explanation of the most recent
40.756 +** error.
40.757 +*/
40.758 +const char *sqlite3_errmsg(sqlite3 *db){
40.759 + const char *z;
40.760 + assert( !sqlite3MallocFailed() );
40.761 + if( !db ){
40.762 + return sqlite3ErrStr(SQLITE_NOMEM);
40.763 + }
40.764 + if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
40.765 + return sqlite3ErrStr(SQLITE_MISUSE);
40.766 + }
40.767 + z = (char*)sqlite3_value_text(db->pErr);
40.768 + if( z==0 ){
40.769 + z = sqlite3ErrStr(db->errCode);
40.770 + }
40.771 + return z;
40.772 +}
40.773 +
40.774 +#ifndef SQLITE_OMIT_UTF16
40.775 +/*
40.776 +** Return UTF-16 encoded English language explanation of the most recent
40.777 +** error.
40.778 +*/
40.779 +const void *sqlite3_errmsg16(sqlite3 *db){
40.780 + /* Because all the characters in the string are in the unicode
40.781 + ** range 0x00-0xFF, if we pad the big-endian string with a
40.782 + ** zero byte, we can obtain the little-endian string with
40.783 + ** &big_endian[1].
40.784 + */
40.785 + static const char outOfMemBe[] = {
40.786 + 0, 'o', 0, 'u', 0, 't', 0, ' ',
40.787 + 0, 'o', 0, 'f', 0, ' ',
40.788 + 0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
40.789 + };
40.790 + static const char misuseBe [] = {
40.791 + 0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ',
40.792 + 0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ',
40.793 + 0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ',
40.794 + 0, 'o', 0, 'u', 0, 't', 0, ' ',
40.795 + 0, 'o', 0, 'f', 0, ' ',
40.796 + 0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
40.797 + };
40.798 +
40.799 + const void *z;
40.800 + assert( !sqlite3MallocFailed() );
40.801 + if( !db ){
40.802 + return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
40.803 + }
40.804 + if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
40.805 + return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
40.806 + }
40.807 + z = sqlite3_value_text16(db->pErr);
40.808 + if( z==0 ){
40.809 + sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
40.810 + SQLITE_UTF8, SQLITE_STATIC);
40.811 + z = sqlite3_value_text16(db->pErr);
40.812 + }
40.813 + sqlite3ApiExit(0, 0);
40.814 + return z;
40.815 +}
40.816 +#endif /* SQLITE_OMIT_UTF16 */
40.817 +
40.818 +/*
40.819 +** Return the most recent error code generated by an SQLite routine. If NULL is
40.820 +** passed to this function, we assume a malloc() failed during sqlite3_open().
40.821 +*/
40.822 +int sqlite3_errcode(sqlite3 *db){
40.823 + if( !db || sqlite3MallocFailed() ){
40.824 + return SQLITE_NOMEM;
40.825 + }
40.826 + if( sqlite3SafetyCheck(db) ){
40.827 + return SQLITE_MISUSE;
40.828 + }
40.829 + return db->errCode & db->errMask;
40.830 +}
40.831 +
40.832 +/*
40.833 +** Create a new collating function for database "db". The name is zName
40.834 +** and the encoding is enc.
40.835 +*/
40.836 +static int createCollation(
40.837 + sqlite3* db,
40.838 + const char *zName,
40.839 + int enc,
40.840 + void* pCtx,
40.841 + int(*xCompare)(void*,int,const void*,int,const void*),
40.842 + void(*xDel)(void*)
40.843 +){
40.844 + CollSeq *pColl;
40.845 + int enc2;
40.846 +
40.847 + if( sqlite3SafetyCheck(db) ){
40.848 + return SQLITE_MISUSE;
40.849 + }
40.850 +
40.851 + /* If SQLITE_UTF16 is specified as the encoding type, transform this
40.852 + ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
40.853 + ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
40.854 + */
40.855 + enc2 = enc & ~SQLITE_UTF16_ALIGNED;
40.856 + if( enc2==SQLITE_UTF16 ){
40.857 + enc2 = SQLITE_UTF16NATIVE;
40.858 + }
40.859 +
40.860 + if( (enc2&~3)!=0 ){
40.861 + sqlite3Error(db, SQLITE_ERROR, "unknown encoding");
40.862 + return SQLITE_ERROR;
40.863 + }
40.864 +
40.865 + /* Check if this call is removing or replacing an existing collation
40.866 + ** sequence. If so, and there are active VMs, return busy. If there
40.867 + ** are no active VMs, invalidate any pre-compiled statements.
40.868 + */
40.869 + pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 0);
40.870 + if( pColl && pColl->xCmp ){
40.871 + if( db->activeVdbeCnt ){
40.872 + sqlite3Error(db, SQLITE_BUSY,
40.873 + "Unable to delete/modify collation sequence due to active statements");
40.874 + return SQLITE_BUSY;
40.875 + }
40.876 + sqlite3ExpirePreparedStatements(db);
40.877 +
40.878 + /* If collation sequence pColl was created directly by a call to
40.879 + ** sqlite3_create_collation, and not generated by synthCollSeq(),
40.880 + ** then any copies made by synthCollSeq() need to be invalidated.
40.881 + ** Also, collation destructor - CollSeq.xDel() - function may need
40.882 + ** to be called.
40.883 + */
40.884 + if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
40.885 + CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, strlen(zName));
40.886 + int j;
40.887 + for(j=0; j<3; j++){
40.888 + CollSeq *p = &aColl[j];
40.889 + if( p->enc==pColl->enc ){
40.890 + if( p->xDel ){
40.891 + p->xDel(p->pUser);
40.892 + }
40.893 + p->xCmp = 0;
40.894 + }
40.895 + }
40.896 + }
40.897 + }
40.898 +
40.899 + pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 1);
40.900 + if( pColl ){
40.901 + pColl->xCmp = xCompare;
40.902 + pColl->pUser = pCtx;
40.903 + pColl->xDel = xDel;
40.904 + pColl->enc = enc2 | (enc & SQLITE_UTF16_ALIGNED);
40.905 + }
40.906 + sqlite3Error(db, SQLITE_OK, 0);
40.907 + return SQLITE_OK;
40.908 +}
40.909 +
40.910 +
40.911 +/*
40.912 +** This routine does the work of opening a database on behalf of
40.913 +** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
40.914 +** is UTF-8 encoded.
40.915 +*/
40.916 +static int openDatabase(
40.917 + const char *zFilename, /* Database filename UTF-8 encoded */
40.918 + sqlite3 **ppDb /* OUT: Returned database handle */
40.919 +){
40.920 + sqlite3 *db;
40.921 + int rc;
40.922 + CollSeq *pColl;
40.923 +
40.924 + assert( !sqlite3MallocFailed() );
40.925 +
40.926 + /* Allocate the sqlite data structure */
40.927 + db = sqliteMalloc( sizeof(sqlite3) );
40.928 + if( db==0 ) goto opendb_out;
40.929 + db->errMask = 0xff;
40.930 + db->priorNewRowid = 0;
40.931 + db->magic = SQLITE_MAGIC_BUSY;
40.932 + db->nDb = 2;
40.933 + db->aDb = db->aDbStatic;
40.934 + db->autoCommit = 1;
40.935 + db->flags |= SQLITE_ShortColNames
40.936 +#if SQLITE_DEFAULT_FILE_FORMAT<4
40.937 + | SQLITE_LegacyFileFmt
40.938 +#endif
40.939 +#ifdef SQLITE_ENABLE_LOAD_EXTENSION
40.940 + | SQLITE_LoadExtension
40.941 +#endif
40.942 + ;
40.943 + sqlite3HashInit(&db->aFunc, SQLITE_HASH_STRING, 0);
40.944 + sqlite3HashInit(&db->aCollSeq, SQLITE_HASH_STRING, 0);
40.945 +#ifndef SQLITE_OMIT_VIRTUALTABLE
40.946 + sqlite3HashInit(&db->aModule, SQLITE_HASH_STRING, 0);
40.947 +#endif
40.948 +
40.949 + /* Add the default collation sequence BINARY. BINARY works for both UTF-8
40.950 + ** and UTF-16, so add a version for each to avoid any unnecessary
40.951 + ** conversions. The only error that can occur here is a malloc() failure.
40.952 + */
40.953 + if( createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0) ||
40.954 + createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0) ||
40.955 + createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0) ||
40.956 + (db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0))==0
40.957 + ){
40.958 + assert( sqlite3MallocFailed() );
40.959 + db->magic = SQLITE_MAGIC_CLOSED;
40.960 + goto opendb_out;
40.961 + }
40.962 +
40.963 + /* Also add a UTF-8 case-insensitive collation sequence. */
40.964 + createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
40.965 +
40.966 + /* Set flags on the built-in collating sequences */
40.967 + db->pDfltColl->type = SQLITE_COLL_BINARY;
40.968 + pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
40.969 + if( pColl ){
40.970 + pColl->type = SQLITE_COLL_NOCASE;
40.971 + }
40.972 +
40.973 + /* Open the backend database driver */
40.974 + rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
40.975 + &db->aDb[0].pBt);
40.976 + if( rc!=SQLITE_OK ){
40.977 + sqlite3Error(db, rc, 0);
40.978 + db->magic = SQLITE_MAGIC_CLOSED;
40.979 + goto opendb_out;
40.980 + }
40.981 + db->aDb[0].pSchema = sqlite3SchemaGet(db->aDb[0].pBt);
40.982 + db->aDb[1].pSchema = sqlite3SchemaGet(0);
40.983 +
40.984 +
40.985 + /* The default safety_level for the main database is 'full'; for the temp
40.986 + ** database it is 'NONE'. This matches the pager layer defaults.
40.987 + */
40.988 + db->aDb[0].zName = "main";
40.989 + db->aDb[0].safety_level = 3;
40.990 +#ifndef SQLITE_OMIT_TEMPDB
40.991 + db->aDb[1].zName = "temp";
40.992 + db->aDb[1].safety_level = 1;
40.993 +#endif
40.994 +
40.995 + db->magic = SQLITE_MAGIC_OPEN;
40.996 + if( sqlite3MallocFailed() ){
40.997 + goto opendb_out;
40.998 + }
40.999 +
40.1000 + /* Register all built-in functions, but do not attempt to read the
40.1001 + ** database schema yet. This is delayed until the first time the database
40.1002 + ** is accessed.
40.1003 + */
40.1004 + sqlite3Error(db, SQLITE_OK, 0);
40.1005 + sqlite3RegisterBuiltinFunctions(db);
40.1006 +
40.1007 + /* Load automatic extensions - extensions that have been registered
40.1008 + ** using the sqlite3_automatic_extension() API.
40.1009 + */
40.1010 + (void)sqlite3AutoLoadExtensions(db);
40.1011 + if( sqlite3_errcode(db)!=SQLITE_OK ){
40.1012 + goto opendb_out;
40.1013 + }
40.1014 +
40.1015 +#ifdef SQLITE_ENABLE_FTS1
40.1016 + if( !sqlite3MallocFailed() ){
40.1017 + extern int sqlite3Fts1Init(sqlite3*);
40.1018 + rc = sqlite3Fts1Init(db);
40.1019 + }
40.1020 +#endif
40.1021 +
40.1022 +#ifdef SQLITE_ENABLE_FTS2
40.1023 + if( !sqlite3MallocFailed() && rc==SQLITE_OK ){
40.1024 + extern int sqlite3Fts2Init(sqlite3*);
40.1025 + rc = sqlite3Fts2Init(db);
40.1026 + }
40.1027 +#endif
40.1028 +
40.1029 +#ifdef SQLITE_ENABLE_ICU
40.1030 + if( !sqlite3MallocFailed() && rc==SQLITE_OK ){
40.1031 + extern int sqlite3IcuInit(sqlite3*);
40.1032 + rc = sqlite3IcuInit(db);
40.1033 + }
40.1034 +#endif
40.1035 + sqlite3Error(db, rc, 0);
40.1036 +
40.1037 + /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
40.1038 + ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
40.1039 + ** mode. Doing nothing at all also makes NORMAL the default.
40.1040 + */
40.1041 +#ifdef SQLITE_DEFAULT_LOCKING_MODE
40.1042 + db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
40.1043 + sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
40.1044 + SQLITE_DEFAULT_LOCKING_MODE);
40.1045 +#endif
40.1046 +
40.1047 +opendb_out:
40.1048 + if( SQLITE_NOMEM==(rc = sqlite3_errcode(db)) ){
40.1049 + sqlite3_close(db);
40.1050 + db = 0;
40.1051 + }
40.1052 + *ppDb = db;
40.1053 + return sqlite3ApiExit(0, rc);
40.1054 +}
40.1055 +
40.1056 +/*
40.1057 +** Open a new database handle.
40.1058 +*/
40.1059 +int sqlite3_open(
40.1060 + const char *zFilename,
40.1061 + sqlite3 **ppDb
40.1062 +){
40.1063 + return openDatabase(zFilename, ppDb);
40.1064 +}
40.1065 +
40.1066 +#ifndef SQLITE_OMIT_UTF16
40.1067 +/*
40.1068 +** Open a new database handle.
40.1069 +*/
40.1070 +int sqlite3_open16(
40.1071 + const void *zFilename,
40.1072 + sqlite3 **ppDb
40.1073 +){
40.1074 + char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
40.1075 + int rc = SQLITE_OK;
40.1076 + sqlite3_value *pVal;
40.1077 +
40.1078 + assert( zFilename );
40.1079 + assert( ppDb );
40.1080 + *ppDb = 0;
40.1081 + pVal = sqlite3ValueNew();
40.1082 + sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
40.1083 + zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
40.1084 + if( zFilename8 ){
40.1085 + rc = openDatabase(zFilename8, ppDb);
40.1086 + if( rc==SQLITE_OK && *ppDb ){
40.1087 + rc = sqlite3_exec(*ppDb, "PRAGMA encoding = 'UTF-16'", 0, 0, 0);
40.1088 + if( rc!=SQLITE_OK ){
40.1089 + sqlite3_close(*ppDb);
40.1090 + *ppDb = 0;
40.1091 + }
40.1092 + }
40.1093 + }
40.1094 + sqlite3ValueFree(pVal);
40.1095 +
40.1096 + return sqlite3ApiExit(0, rc);
40.1097 +}
40.1098 +#endif /* SQLITE_OMIT_UTF16 */
40.1099 +
40.1100 +/*
40.1101 +** The following routine destroys a virtual machine that is created by
40.1102 +** the sqlite3_compile() routine. The integer returned is an SQLITE_
40.1103 +** success/failure code that describes the result of executing the virtual
40.1104 +** machine.
40.1105 +**
40.1106 +** This routine sets the error code and string returned by
40.1107 +** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
40.1108 +*/
40.1109 +int sqlite3_finalize(sqlite3_stmt *pStmt){
40.1110 + int rc;
40.1111 + if( pStmt==0 ){
40.1112 + rc = SQLITE_OK;
40.1113 + }else{
40.1114 + rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
40.1115 + }
40.1116 + return rc;
40.1117 +}
40.1118 +
40.1119 +/*
40.1120 +** Terminate the current execution of an SQL statement and reset it
40.1121 +** back to its starting state so that it can be reused. A success code from
40.1122 +** the prior execution is returned.
40.1123 +**
40.1124 +** This routine sets the error code and string returned by
40.1125 +** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
40.1126 +*/
40.1127 +int sqlite3_reset(sqlite3_stmt *pStmt){
40.1128 + int rc;
40.1129 + if( pStmt==0 ){
40.1130 + rc = SQLITE_OK;
40.1131 + }else{
40.1132 + rc = sqlite3VdbeReset((Vdbe*)pStmt);
40.1133 + sqlite3VdbeMakeReady((Vdbe*)pStmt, -1, 0, 0, 0);
40.1134 + assert( (rc & (sqlite3_db_handle(pStmt)->errMask))==rc );
40.1135 + }
40.1136 + return rc;
40.1137 +}
40.1138 +
40.1139 +/*
40.1140 +** Register a new collation sequence with the database handle db.
40.1141 +*/
40.1142 +int sqlite3_create_collation(
40.1143 + sqlite3* db,
40.1144 + const char *zName,
40.1145 + int enc,
40.1146 + void* pCtx,
40.1147 + int(*xCompare)(void*,int,const void*,int,const void*)
40.1148 +){
40.1149 + int rc;
40.1150 + assert( !sqlite3MallocFailed() );
40.1151 + rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
40.1152 + return sqlite3ApiExit(db, rc);
40.1153 +}
40.1154 +
40.1155 +/*
40.1156 +** Register a new collation sequence with the database handle db.
40.1157 +*/
40.1158 +int sqlite3_create_collation_v2(
40.1159 + sqlite3* db,
40.1160 + const char *zName,
40.1161 + int enc,
40.1162 + void* pCtx,
40.1163 + int(*xCompare)(void*,int,const void*,int,const void*),
40.1164 + void(*xDel)(void*)
40.1165 +){
40.1166 + int rc;
40.1167 + assert( !sqlite3MallocFailed() );
40.1168 + rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
40.1169 + return sqlite3ApiExit(db, rc);
40.1170 +}
40.1171 +
40.1172 +#ifndef SQLITE_OMIT_UTF16
40.1173 +/*
40.1174 +** Register a new collation sequence with the database handle db.
40.1175 +*/
40.1176 +int sqlite3_create_collation16(
40.1177 + sqlite3* db,
40.1178 + const char *zName,
40.1179 + int enc,
40.1180 + void* pCtx,
40.1181 + int(*xCompare)(void*,int,const void*,int,const void*)
40.1182 +){
40.1183 + int rc = SQLITE_OK;
40.1184 + char *zName8;
40.1185 + assert( !sqlite3MallocFailed() );
40.1186 + zName8 = sqlite3Utf16to8(zName, -1);
40.1187 + if( zName8 ){
40.1188 + rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
40.1189 + sqliteFree(zName8);
40.1190 + }
40.1191 + return sqlite3ApiExit(db, rc);
40.1192 +}
40.1193 +#endif /* SQLITE_OMIT_UTF16 */
40.1194 +
40.1195 +/*
40.1196 +** Register a collation sequence factory callback with the database handle
40.1197 +** db. Replace any previously installed collation sequence factory.
40.1198 +*/
40.1199 +int sqlite3_collation_needed(
40.1200 + sqlite3 *db,
40.1201 + void *pCollNeededArg,
40.1202 + void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
40.1203 +){
40.1204 + if( sqlite3SafetyCheck(db) ){
40.1205 + return SQLITE_MISUSE;
40.1206 + }
40.1207 + db->xCollNeeded = xCollNeeded;
40.1208 + db->xCollNeeded16 = 0;
40.1209 + db->pCollNeededArg = pCollNeededArg;
40.1210 + return SQLITE_OK;
40.1211 +}
40.1212 +
40.1213 +#ifndef SQLITE_OMIT_UTF16
40.1214 +/*
40.1215 +** Register a collation sequence factory callback with the database handle
40.1216 +** db. Replace any previously installed collation sequence factory.
40.1217 +*/
40.1218 +int sqlite3_collation_needed16(
40.1219 + sqlite3 *db,
40.1220 + void *pCollNeededArg,
40.1221 + void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
40.1222 +){
40.1223 + if( sqlite3SafetyCheck(db) ){
40.1224 + return SQLITE_MISUSE;
40.1225 + }
40.1226 + db->xCollNeeded = 0;
40.1227 + db->xCollNeeded16 = xCollNeeded16;
40.1228 + db->pCollNeededArg = pCollNeededArg;
40.1229 + return SQLITE_OK;
40.1230 +}
40.1231 +#endif /* SQLITE_OMIT_UTF16 */
40.1232 +
40.1233 +#ifndef SQLITE_OMIT_GLOBALRECOVER
40.1234 +/*
40.1235 +** This function is now an anachronism. It used to be used to recover from a
40.1236 +** malloc() failure, but SQLite now does this automatically.
40.1237 +*/
40.1238 +int sqlite3_global_recover(){
40.1239 + return SQLITE_OK;
40.1240 +}
40.1241 +#endif
40.1242 +
40.1243 +/*
40.1244 +** Test to see whether or not the database connection is in autocommit
40.1245 +** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
40.1246 +** by default. Autocommit is disabled by a BEGIN statement and reenabled
40.1247 +** by the next COMMIT or ROLLBACK.
40.1248 +**
40.1249 +******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
40.1250 +*/
40.1251 +int sqlite3_get_autocommit(sqlite3 *db){
40.1252 + return db->autoCommit;
40.1253 +}
40.1254 +
40.1255 +#ifdef SQLITE_DEBUG
40.1256 +/*
40.1257 +** The following routine is subtituted for constant SQLITE_CORRUPT in
40.1258 +** debugging builds. This provides a way to set a breakpoint for when
40.1259 +** corruption is first detected.
40.1260 +*/
40.1261 +int sqlite3Corrupt(void){
40.1262 + return SQLITE_CORRUPT;
40.1263 +}
40.1264 +#endif
40.1265 +
40.1266 +
40.1267 +#ifndef SQLITE_OMIT_SHARED_CACHE
40.1268 +/*
40.1269 +** Enable or disable the shared pager and schema features for the
40.1270 +** current thread.
40.1271 +**
40.1272 +** This routine should only be called when there are no open
40.1273 +** database connections.
40.1274 +*/
40.1275 +int sqlite3_enable_shared_cache(int enable){
40.1276 + ThreadData *pTd = sqlite3ThreadData();
40.1277 + if( pTd ){
40.1278 + /* It is only legal to call sqlite3_enable_shared_cache() when there
40.1279 + ** are no currently open b-trees that were opened by the calling thread.
40.1280 + ** This condition is only easy to detect if the shared-cache were
40.1281 + ** previously enabled (and is being disabled).
40.1282 + */
40.1283 + if( pTd->pBtree && !enable ){
40.1284 + assert( pTd->useSharedData );
40.1285 + return SQLITE_MISUSE;
40.1286 + }
40.1287 +
40.1288 + pTd->useSharedData = enable;
40.1289 + sqlite3ReleaseThreadData();
40.1290 + }
40.1291 + return sqlite3ApiExit(0, SQLITE_OK);
40.1292 +}
40.1293 +#endif
40.1294 +
40.1295 +/*
40.1296 +** This is a convenience routine that makes sure that all thread-specific
40.1297 +** data for this thread has been deallocated.
40.1298 +*/
40.1299 +void sqlite3_thread_cleanup(void){
40.1300 + ThreadData *pTd = sqlite3OsThreadSpecificData(0);
40.1301 + if( pTd ){
40.1302 + memset(pTd, 0, sizeof(*pTd));
40.1303 + sqlite3OsThreadSpecificData(-1);
40.1304 + }
40.1305 +}
40.1306 +
40.1307 +/*
40.1308 +** Return meta information about a specific column of a database table.
40.1309 +** See comment in sqlite3.h (sqlite.h.in) for details.
40.1310 +*/
40.1311 +#ifdef SQLITE_ENABLE_COLUMN_METADATA
40.1312 +int sqlite3_table_column_metadata(
40.1313 + sqlite3 *db, /* Connection handle */
40.1314 + const char *zDbName, /* Database name or NULL */
40.1315 + const char *zTableName, /* Table name */
40.1316 + const char *zColumnName, /* Column name */
40.1317 + char const **pzDataType, /* OUTPUT: Declared data type */
40.1318 + char const **pzCollSeq, /* OUTPUT: Collation sequence name */
40.1319 + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
40.1320 + int *pPrimaryKey, /* OUTPUT: True if column part of PK */
40.1321 + int *pAutoinc /* OUTPUT: True if colums is auto-increment */
40.1322 +){
40.1323 + int rc;
40.1324 + char *zErrMsg = 0;
40.1325 + Table *pTab = 0;
40.1326 + Column *pCol = 0;
40.1327 + int iCol;
40.1328 +
40.1329 + char const *zDataType = 0;
40.1330 + char const *zCollSeq = 0;
40.1331 + int notnull = 0;
40.1332 + int primarykey = 0;
40.1333 + int autoinc = 0;
40.1334 +
40.1335 + /* Ensure the database schema has been loaded */
40.1336 + if( sqlite3SafetyOn(db) ){
40.1337 + return SQLITE_MISUSE;
40.1338 + }
40.1339 + rc = sqlite3Init(db, &zErrMsg);
40.1340 + if( SQLITE_OK!=rc ){
40.1341 + goto error_out;
40.1342 + }
40.1343 +
40.1344 + /* Locate the table in question */
40.1345 + pTab = sqlite3FindTable(db, zTableName, zDbName);
40.1346 + if( !pTab || pTab->pSelect ){
40.1347 + pTab = 0;
40.1348 + goto error_out;
40.1349 + }
40.1350 +
40.1351 + /* Find the column for which info is requested */
40.1352 + if( sqlite3IsRowid(zColumnName) ){
40.1353 + iCol = pTab->iPKey;
40.1354 + if( iCol>=0 ){
40.1355 + pCol = &pTab->aCol[iCol];
40.1356 + }
40.1357 + }else{
40.1358 + for(iCol=0; iCol<pTab->nCol; iCol++){
40.1359 + pCol = &pTab->aCol[iCol];
40.1360 + if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
40.1361 + break;
40.1362 + }
40.1363 + }
40.1364 + if( iCol==pTab->nCol ){
40.1365 + pTab = 0;
40.1366 + goto error_out;
40.1367 + }
40.1368 + }
40.1369 +
40.1370 + /* The following block stores the meta information that will be returned
40.1371 + ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
40.1372 + ** and autoinc. At this point there are two possibilities:
40.1373 + **
40.1374 + ** 1. The specified column name was rowid", "oid" or "_rowid_"
40.1375 + ** and there is no explicitly declared IPK column.
40.1376 + **
40.1377 + ** 2. The table is not a view and the column name identified an
40.1378 + ** explicitly declared column. Copy meta information from *pCol.
40.1379 + */
40.1380 + if( pCol ){
40.1381 + zDataType = pCol->zType;
40.1382 + zCollSeq = pCol->zColl;
40.1383 + notnull = (pCol->notNull?1:0);
40.1384 + primarykey = (pCol->isPrimKey?1:0);
40.1385 + autoinc = ((pTab->iPKey==iCol && pTab->autoInc)?1:0);
40.1386 + }else{
40.1387 + zDataType = "INTEGER";
40.1388 + primarykey = 1;
40.1389 + }
40.1390 + if( !zCollSeq ){
40.1391 + zCollSeq = "BINARY";
40.1392 + }
40.1393 +
40.1394 +error_out:
40.1395 + if( sqlite3SafetyOff(db) ){
40.1396 + rc = SQLITE_MISUSE;
40.1397 + }
40.1398 +
40.1399 + /* Whether the function call succeeded or failed, set the output parameters
40.1400 + ** to whatever their local counterparts contain. If an error did occur,
40.1401 + ** this has the effect of zeroing all output parameters.
40.1402 + */
40.1403 + if( pzDataType ) *pzDataType = zDataType;
40.1404 + if( pzCollSeq ) *pzCollSeq = zCollSeq;
40.1405 + if( pNotNull ) *pNotNull = notnull;
40.1406 + if( pPrimaryKey ) *pPrimaryKey = primarykey;
40.1407 + if( pAutoinc ) *pAutoinc = autoinc;
40.1408 +
40.1409 + if( SQLITE_OK==rc && !pTab ){
40.1410 + sqlite3SetString(&zErrMsg, "no such table column: ", zTableName, ".",
40.1411 + zColumnName, 0);
40.1412 + rc = SQLITE_ERROR;
40.1413 + }
40.1414 + sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
40.1415 + sqliteFree(zErrMsg);
40.1416 + return sqlite3ApiExit(db, rc);
40.1417 +}
40.1418 +#endif
40.1419 +
40.1420 +/*
40.1421 +** Set all the parameters in the compiled SQL statement to NULL.
40.1422 +*/
40.1423 +int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
40.1424 + int i;
40.1425 + int rc = SQLITE_OK;
40.1426 + for(i=1; rc==SQLITE_OK && i<=sqlite3_bind_parameter_count(pStmt); i++){
40.1427 + rc = sqlite3_bind_null(pStmt, i);
40.1428 + }
40.1429 + return rc;
40.1430 +}
40.1431 +
40.1432 +/*
40.1433 +** Sleep for a little while. Return the amount of time slept.
40.1434 +*/
40.1435 +int sqlite3_sleep(int ms){
40.1436 + return sqlite3OsSleep(ms);
40.1437 +}
40.1438 +
40.1439 +/*
40.1440 +** Enable or disable the extended result codes.
40.1441 +*/
40.1442 +int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
40.1443 + db->errMask = onoff ? 0xffffffff : 0xff;
40.1444 + return SQLITE_OK;
40.1445 +}
41.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
41.2 +++ b/extensions/sqlite/sqlite-source/malloc.c Sun Jul 29 01:15:31 2007 +0000
41.3 @@ -0,0 +1,835 @@
41.4 +/*
41.5 +** 2001 September 15
41.6 +**
41.7 +** The author disclaims copyright to this source code. In place of
41.8 +** a legal notice, here is a blessing:
41.9 +**
41.10 +** May you do good and not evil.
41.11 +** May you find forgiveness for yourself and forgive others.
41.12 +** May you share freely, never taking more than you give.
41.13 +**
41.14 +*************************************************************************
41.15 +** Memory allocation functions used throughout sqlite.
41.16 +**
41.17 +**
41.18 +** $Id$
41.19 +*/
41.20 +#include "sqliteInt.h"
41.21 +#include "os.h"
41.22 +#include <stdarg.h>
41.23 +#include <ctype.h>
41.24 +
41.25 +/*
41.26 +** MALLOC WRAPPER ARCHITECTURE
41.27 +**
41.28 +** The sqlite code accesses dynamic memory allocation/deallocation by invoking
41.29 +** the following six APIs (which may be implemented as macros).
41.30 +**
41.31 +** sqlite3Malloc()
41.32 +** sqlite3MallocRaw()
41.33 +** sqlite3Realloc()
41.34 +** sqlite3ReallocOrFree()
41.35 +** sqlite3Free()
41.36 +** sqlite3AllocSize()
41.37 +**
41.38 +** The function sqlite3FreeX performs the same task as sqlite3Free and is
41.39 +** guaranteed to be a real function. The same holds for sqlite3MallocX
41.40 +**
41.41 +** The above APIs are implemented in terms of the functions provided in the
41.42 +** operating-system interface. The OS interface is never accessed directly
41.43 +** by code outside of this file.
41.44 +**
41.45 +** sqlite3OsMalloc()
41.46 +** sqlite3OsRealloc()
41.47 +** sqlite3OsFree()
41.48 +** sqlite3OsAllocationSize()
41.49 +**
41.50 +** Functions sqlite3MallocRaw() and sqlite3Realloc() may invoke
41.51 +** sqlite3_release_memory() if a call to sqlite3OsMalloc() or
41.52 +** sqlite3OsRealloc() fails (or if the soft-heap-limit for the thread is
41.53 +** exceeded). Function sqlite3Malloc() usually invokes
41.54 +** sqlite3MallocRaw().
41.55 +**
41.56 +** MALLOC TEST WRAPPER ARCHITECTURE
41.57 +**
41.58 +** The test wrapper provides extra test facilities to ensure the library
41.59 +** does not leak memory and handles the failure of the underlying OS level
41.60 +** allocation system correctly. It is only present if the library is
41.61 +** compiled with the SQLITE_MEMDEBUG macro set.
41.62 +**
41.63 +** * Guardposts to detect overwrites.
41.64 +** * Ability to cause a specific Malloc() or Realloc() to fail.
41.65 +** * Audit outstanding memory allocations (i.e check for leaks).
41.66 +*/
41.67 +
41.68 +#define MAX(x,y) ((x)>(y)?(x):(y))
41.69 +
41.70 +#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO)
41.71 +/*
41.72 +** Set the soft heap-size limit for the current thread. Passing a negative
41.73 +** value indicates no limit.
41.74 +*/
41.75 +void sqlite3_soft_heap_limit(int n){
41.76 + ThreadData *pTd = sqlite3ThreadData();
41.77 + if( pTd ){
41.78 + pTd->nSoftHeapLimit = n;
41.79 + }
41.80 + sqlite3ReleaseThreadData();
41.81 +}
41.82 +
41.83 +/*
41.84 +** Release memory held by SQLite instances created by the current thread.
41.85 +*/
41.86 +int sqlite3_release_memory(int n){
41.87 + return sqlite3PagerReleaseMemory(n);
41.88 +}
41.89 +#else
41.90 +/* If SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, then define a version
41.91 +** of sqlite3_release_memory() to be used by other code in this file.
41.92 +** This is done for no better reason than to reduce the number of
41.93 +** pre-processor #ifndef statements.
41.94 +*/
41.95 +#define sqlite3_release_memory(x) 0 /* 0 == no memory freed */
41.96 +#endif
41.97 +
41.98 +#ifdef SQLITE_MEMDEBUG
41.99 +/*--------------------------------------------------------------------------
41.100 +** Begin code for memory allocation system test layer.
41.101 +**
41.102 +** Memory debugging is turned on by defining the SQLITE_MEMDEBUG macro.
41.103 +**
41.104 +** SQLITE_MEMDEBUG==1 -> Fence-posting only (thread safe)
41.105 +** SQLITE_MEMDEBUG==2 -> Fence-posting + linked list of allocations (not ts)
41.106 +** SQLITE_MEMDEBUG==3 -> Above + backtraces (not thread safe, req. glibc)
41.107 +*/
41.108 +
41.109 +/* Figure out whether or not to store backtrace() information for each malloc.
41.110 +** The backtrace() function is only used if SQLITE_MEMDEBUG is set to 2 or
41.111 +** greater and glibc is in use. If we don't want to use backtrace(), then just
41.112 +** define it as an empty macro and set the amount of space reserved to 0.
41.113 +*/
41.114 +#if defined(__GLIBC__) && SQLITE_MEMDEBUG>2
41.115 + extern int backtrace(void **, int);
41.116 + #define TESTALLOC_STACKSIZE 128
41.117 + #define TESTALLOC_STACKFRAMES ((TESTALLOC_STACKSIZE-8)/sizeof(void*))
41.118 +#else
41.119 + #define backtrace(x, y)
41.120 + #define TESTALLOC_STACKSIZE 0
41.121 + #define TESTALLOC_STACKFRAMES 0
41.122 +#endif
41.123 +
41.124 +/*
41.125 +** Number of 32-bit guard words. This should probably be a multiple of
41.126 +** 2 since on 64-bit machines we want the value returned by sqliteMalloc()
41.127 +** to be 8-byte aligned.
41.128 +*/
41.129 +#ifndef TESTALLOC_NGUARD
41.130 +# define TESTALLOC_NGUARD 2
41.131 +#endif
41.132 +
41.133 +/*
41.134 +** Size reserved for storing file-name along with each malloc()ed blob.
41.135 +*/
41.136 +#define TESTALLOC_FILESIZE 64
41.137 +
41.138 +/*
41.139 +** Size reserved for storing the user string. Each time a Malloc() or Realloc()
41.140 +** call succeeds, up to TESTALLOC_USERSIZE bytes of the string pointed to by
41.141 +** sqlite3_malloc_id are stored along with the other test system metadata.
41.142 +*/
41.143 +#define TESTALLOC_USERSIZE 64
41.144 +const char *sqlite3_malloc_id = 0;
41.145 +
41.146 +/*
41.147 +** Blocks used by the test layer have the following format:
41.148 +**
41.149 +** <sizeof(void *) pNext pointer>
41.150 +** <sizeof(void *) pPrev pointer>
41.151 +** <TESTALLOC_NGUARD 32-bit guard words>
41.152 +** <The application level allocation>
41.153 +** <TESTALLOC_NGUARD 32-bit guard words>
41.154 +** <32-bit line number>
41.155 +** <TESTALLOC_FILESIZE bytes containing null-terminated file name>
41.156 +** <TESTALLOC_STACKSIZE bytes of backtrace() output>
41.157 +*/
41.158 +
41.159 +#define TESTALLOC_OFFSET_GUARD1(p) (sizeof(void *) * 2)
41.160 +#define TESTALLOC_OFFSET_DATA(p) ( \
41.161 + TESTALLOC_OFFSET_GUARD1(p) + sizeof(u32) * TESTALLOC_NGUARD \
41.162 +)
41.163 +#define TESTALLOC_OFFSET_GUARD2(p) ( \
41.164 + TESTALLOC_OFFSET_DATA(p) + sqlite3OsAllocationSize(p) - TESTALLOC_OVERHEAD \
41.165 +)
41.166 +#define TESTALLOC_OFFSET_LINENUMBER(p) ( \
41.167 + TESTALLOC_OFFSET_GUARD2(p) + sizeof(u32) * TESTALLOC_NGUARD \
41.168 +)
41.169 +#define TESTALLOC_OFFSET_FILENAME(p) ( \
41.170 + TESTALLOC_OFFSET_LINENUMBER(p) + sizeof(u32) \
41.171 +)
41.172 +#define TESTALLOC_OFFSET_USER(p) ( \
41.173 + TESTALLOC_OFFSET_FILENAME(p) + TESTALLOC_FILESIZE \
41.174 +)
41.175 +#define TESTALLOC_OFFSET_STACK(p) ( \
41.176 + TESTALLOC_OFFSET_USER(p) + TESTALLOC_USERSIZE + 8 - \
41.177 + (TESTALLOC_OFFSET_USER(p) % 8) \
41.178 +)
41.179 +
41.180 +#define TESTALLOC_OVERHEAD ( \
41.181 + sizeof(void *)*2 + /* pPrev and pNext pointers */ \
41.182 + TESTALLOC_NGUARD*sizeof(u32)*2 + /* Guard words */ \
41.183 + sizeof(u32) + TESTALLOC_FILESIZE + /* File and line number */ \
41.184 + TESTALLOC_USERSIZE + /* User string */ \
41.185 + TESTALLOC_STACKSIZE /* backtrace() stack */ \
41.186 +)
41.187 +
41.188 +
41.189 +/*
41.190 +** For keeping track of the number of mallocs and frees. This
41.191 +** is used to check for memory leaks. The iMallocFail and iMallocReset
41.192 +** values are used to simulate malloc() failures during testing in
41.193 +** order to verify that the library correctly handles an out-of-memory
41.194 +** condition.
41.195 +*/
41.196 +int sqlite3_nMalloc; /* Number of sqliteMalloc() calls */
41.197 +int sqlite3_nFree; /* Number of sqliteFree() calls */
41.198 +int sqlite3_memUsed; /* TODO Total memory obtained from malloc */
41.199 +int sqlite3_memMax; /* TODO Mem usage high-water mark */
41.200 +int sqlite3_iMallocFail; /* Fail sqliteMalloc() after this many calls */
41.201 +int sqlite3_iMallocReset = -1; /* When iMallocFail reaches 0, set to this */
41.202 +
41.203 +void *sqlite3_pFirst = 0; /* Pointer to linked list of allocations */
41.204 +int sqlite3_nMaxAlloc = 0; /* High water mark of ThreadData.nAlloc */
41.205 +int sqlite3_mallocDisallowed = 0; /* assert() in sqlite3Malloc() if set */
41.206 +int sqlite3_isFail = 0; /* True if all malloc calls should fail */
41.207 +const char *sqlite3_zFile = 0; /* Filename to associate debug info with */
41.208 +int sqlite3_iLine = 0; /* Line number for debug info */
41.209 +int sqlite3_mallocfail_trace = 0; /* Print a msg on malloc fail if true */
41.210 +
41.211 +/*
41.212 +** Check for a simulated memory allocation failure. Return true if
41.213 +** the failure should be simulated. Return false to proceed as normal.
41.214 +*/
41.215 +int sqlite3TestMallocFail(){
41.216 + if( sqlite3_isFail ){
41.217 + return 1;
41.218 + }
41.219 + if( sqlite3_iMallocFail>=0 ){
41.220 + sqlite3_iMallocFail--;
41.221 + if( sqlite3_iMallocFail==0 ){
41.222 + sqlite3_iMallocFail = sqlite3_iMallocReset;
41.223 + sqlite3_isFail = 1;
41.224 + if( sqlite3_mallocfail_trace ){
41.225 + sqlite3DebugPrintf("###_malloc_fails_###\n");
41.226 + }
41.227 + return 1;
41.228 + }
41.229 + }
41.230 + return 0;
41.231 +}
41.232 +
41.233 +/*
41.234 +** The argument is a pointer returned by sqlite3OsMalloc() or xRealloc().
41.235 +** assert() that the first and last (TESTALLOC_NGUARD*4) bytes are set to the
41.236 +** values set by the applyGuards() function.
41.237 +*/
41.238 +static void checkGuards(u32 *p)
41.239 +{
41.240 + int i;
41.241 + char *zAlloc = (char *)p;
41.242 + char *z;
41.243 +
41.244 + /* First set of guard words */
41.245 + z = &zAlloc[TESTALLOC_OFFSET_GUARD1(p)];
41.246 + for(i=0; i<TESTALLOC_NGUARD; i++){
41.247 + assert(((u32 *)z)[i]==0xdead1122);
41.248 + }
41.249 +
41.250 + /* Second set of guard words */
41.251 + z = &zAlloc[TESTALLOC_OFFSET_GUARD2(p)];
41.252 + for(i=0; i<TESTALLOC_NGUARD; i++){
41.253 + u32 guard = 0;
41.254 + memcpy(&guard, &z[i*sizeof(u32)], sizeof(u32));
41.255 + assert(guard==0xdead3344);
41.256 + }
41.257 +}
41.258 +
41.259 +/*
41.260 +** The argument is a pointer returned by sqlite3OsMalloc() or Realloc(). The
41.261 +** first and last (TESTALLOC_NGUARD*4) bytes are set to known values for use as
41.262 +** guard-posts.
41.263 +*/
41.264 +static void applyGuards(u32 *p)
41.265 +{
41.266 + int i;
41.267 + char *z;
41.268 + char *zAlloc = (char *)p;
41.269 +
41.270 + /* First set of guard words */
41.271 + z = &zAlloc[TESTALLOC_OFFSET_GUARD1(p)];
41.272 + for(i=0; i<TESTALLOC_NGUARD; i++){
41.273 + ((u32 *)z)[i] = 0xdead1122;
41.274 + }
41.275 +
41.276 + /* Second set of guard words */
41.277 + z = &zAlloc[TESTALLOC_OFFSET_GUARD2(p)];
41.278 + for(i=0; i<TESTALLOC_NGUARD; i++){
41.279 + static const int guard = 0xdead3344;
41.280 + memcpy(&z[i*sizeof(u32)], &guard, sizeof(u32));
41.281 + }
41.282 +
41.283 + /* Line number */
41.284 + z = &((char *)z)[TESTALLOC_NGUARD*sizeof(u32)]; /* Guard words */
41.285 + z = &zAlloc[TESTALLOC_OFFSET_LINENUMBER(p)];
41.286 + memcpy(z, &sqlite3_iLine, sizeof(u32));
41.287 +
41.288 + /* File name */
41.289 + z = &zAlloc[TESTALLOC_OFFSET_FILENAME(p)];
41.290 + strncpy(z, sqlite3_zFile, TESTALLOC_FILESIZE);
41.291 + z[TESTALLOC_FILESIZE - 1] = '\0';
41.292 +
41.293 + /* User string */
41.294 + z = &zAlloc[TESTALLOC_OFFSET_USER(p)];
41.295 + z[0] = 0;
41.296 + if( sqlite3_malloc_id ){
41.297 + strncpy(z, sqlite3_malloc_id, TESTALLOC_USERSIZE);
41.298 + z[TESTALLOC_USERSIZE-1] = 0;
41.299 + }
41.300 +
41.301 + /* backtrace() stack */
41.302 + z = &zAlloc[TESTALLOC_OFFSET_STACK(p)];
41.303 + backtrace((void **)z, TESTALLOC_STACKFRAMES);
41.304 +
41.305 + /* Sanity check to make sure checkGuards() is working */
41.306 + checkGuards(p);
41.307 +}
41.308 +
41.309 +/*
41.310 +** The argument is a malloc()ed pointer as returned by the test-wrapper.
41.311 +** Return a pointer to the Os level allocation.
41.312 +*/
41.313 +static void *getOsPointer(void *p)
41.314 +{
41.315 + char *z = (char *)p;
41.316 + return (void *)(&z[-1 * TESTALLOC_OFFSET_DATA(p)]);
41.317 +}
41.318 +
41.319 +
41.320 +#if SQLITE_MEMDEBUG>1
41.321 +/*
41.322 +** The argument points to an Os level allocation. Link it into the threads list
41.323 +** of allocations.
41.324 +*/
41.325 +static void linkAlloc(void *p){
41.326 + void **pp = (void **)p;
41.327 + pp[0] = 0;
41.328 + pp[1] = sqlite3_pFirst;
41.329 + if( sqlite3_pFirst ){
41.330 + ((void **)sqlite3_pFirst)[0] = p;
41.331 + }
41.332 + sqlite3_pFirst = p;
41.333 +}
41.334 +
41.335 +/*
41.336 +** The argument points to an Os level allocation. Unlinke it from the threads
41.337 +** list of allocations.
41.338 +*/
41.339 +static void unlinkAlloc(void *p)
41.340 +{
41.341 + void **pp = (void **)p;
41.342 + if( p==sqlite3_pFirst ){
41.343 + assert(!pp[0]);
41.344 + assert(!pp[1] || ((void **)(pp[1]))[0]==p);
41.345 + sqlite3_pFirst = pp[1];
41.346 + if( sqlite3_pFirst ){
41.347 + ((void **)sqlite3_pFirst)[0] = 0;
41.348 + }
41.349 + }else{
41.350 + void **pprev = pp[0];
41.351 + void **pnext = pp[1];
41.352 + assert(pprev);
41.353 + assert(pprev[1]==p);
41.354 + pprev[1] = (void *)pnext;
41.355 + if( pnext ){
41.356 + assert(pnext[0]==p);
41.357 + pnext[0] = (void *)pprev;
41.358 + }
41.359 + }
41.360 +}
41.361 +
41.362 +/*
41.363 +** Pointer p is a pointer to an OS level allocation that has just been
41.364 +** realloc()ed. Set the list pointers that point to this entry to it's new
41.365 +** location.
41.366 +*/
41.367 +static void relinkAlloc(void *p)
41.368 +{
41.369 + void **pp = (void **)p;
41.370 + if( pp[0] ){
41.371 + ((void **)(pp[0]))[1] = p;
41.372 + }else{
41.373 + sqlite3_pFirst = p;
41.374 + }
41.375 + if( pp[1] ){
41.376 + ((void **)(pp[1]))[0] = p;
41.377 + }
41.378 +}
41.379 +#else
41.380 +#define linkAlloc(x)
41.381 +#define relinkAlloc(x)
41.382 +#define unlinkAlloc(x)
41.383 +#endif
41.384 +
41.385 +/*
41.386 +** This function sets the result of the Tcl interpreter passed as an argument
41.387 +** to a list containing an entry for each currently outstanding call made to
41.388 +** sqliteMalloc and friends by the current thread. Each list entry is itself a
41.389 +** list, consisting of the following (in order):
41.390 +**
41.391 +** * The number of bytes allocated
41.392 +** * The __FILE__ macro at the time of the sqliteMalloc() call.
41.393 +** * The __LINE__ macro ...
41.394 +** * The value of the sqlite3_malloc_id variable ...
41.395 +** * The output of backtrace() (if available) ...
41.396 +**
41.397 +** Todo: We could have a version of this function that outputs to stdout,
41.398 +** to debug memory leaks when Tcl is not available.
41.399 +*/
41.400 +#if defined(TCLSH) && defined(SQLITE_DEBUG) && SQLITE_MEMDEBUG>1
41.401 +#include <tcl.h>
41.402 +int sqlite3OutstandingMallocs(Tcl_Interp *interp){
41.403 + void *p;
41.404 + Tcl_Obj *pRes = Tcl_NewObj();
41.405 + Tcl_IncrRefCount(pRes);
41.406 +
41.407 +
41.408 + for(p=sqlite3_pFirst; p; p=((void **)p)[1]){
41.409 + Tcl_Obj *pEntry = Tcl_NewObj();
41.410 + Tcl_Obj *pStack = Tcl_NewObj();
41.411 + char *z;
41.412 + u32 iLine;
41.413 + int nBytes = sqlite3OsAllocationSize(p) - TESTALLOC_OVERHEAD;
41.414 + char *zAlloc = (char *)p;
41.415 + int i;
41.416 +
41.417 + Tcl_ListObjAppendElement(0, pEntry, Tcl_NewIntObj(nBytes));
41.418 +
41.419 + z = &zAlloc[TESTALLOC_OFFSET_FILENAME(p)];
41.420 + Tcl_ListObjAppendElement(0, pEntry, Tcl_NewStringObj(z, -1));
41.421 +
41.422 + z = &zAlloc[TESTALLOC_OFFSET_LINENUMBER(p)];
41.423 + memcpy(&iLine, z, sizeof(u32));
41.424 + Tcl_ListObjAppendElement(0, pEntry, Tcl_NewIntObj(iLine));
41.425 +
41.426 + z = &zAlloc[TESTALLOC_OFFSET_USER(p)];
41.427 + Tcl_ListObjAppendElement(0, pEntry, Tcl_NewStringObj(z, -1));
41.428 +
41.429 + z = &zAlloc[TESTALLOC_OFFSET_STACK(p)];
41.430 + for(i=0; i<TESTALLOC_STACKFRAMES; i++){
41.431 + char zHex[128];
41.432 + sqlite3_snprintf(sizeof(zHex), zHex, "%p", ((void **)z)[i]);
41.433 + Tcl_ListObjAppendElement(0, pStack, Tcl_NewStringObj(zHex, -1));
41.434 + }
41.435 +
41.436 + Tcl_ListObjAppendElement(0, pEntry, pStack);
41.437 + Tcl_ListObjAppendElement(0, pRes, pEntry);
41.438 + }
41.439 +
41.440 + Tcl_ResetResult(interp);
41.441 + Tcl_SetObjResult(interp, pRes);
41.442 + Tcl_DecrRefCount(pRes);
41.443 + return TCL_OK;
41.444 +}
41.445 +#endif
41.446 +
41.447 +/*
41.448 +** This is the test layer's wrapper around sqlite3OsMalloc().
41.449 +*/
41.450 +static void * OSMALLOC(int n){
41.451 + sqlite3OsEnterMutex();
41.452 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
41.453 + sqlite3_nMaxAlloc =
41.454 + MAX(sqlite3_nMaxAlloc, sqlite3ThreadDataReadOnly()->nAlloc);
41.455 +#endif
41.456 + assert( !sqlite3_mallocDisallowed );
41.457 + if( !sqlite3TestMallocFail() ){
41.458 + u32 *p;
41.459 + p = (u32 *)sqlite3OsMalloc(n + TESTALLOC_OVERHEAD);
41.460 + assert(p);
41.461 + sqlite3_nMalloc++;
41.462 + applyGuards(p);
41.463 + linkAlloc(p);
41.464 + sqlite3OsLeaveMutex();
41.465 + return (void *)(&p[TESTALLOC_NGUARD + 2*sizeof(void *)/sizeof(u32)]);
41.466 + }
41.467 + sqlite3OsLeaveMutex();
41.468 + return 0;
41.469 +}
41.470 +
41.471 +static int OSSIZEOF(void *p){
41.472 + if( p ){
41.473 + u32 *pOs = (u32 *)getOsPointer(p);
41.474 + return sqlite3OsAllocationSize(pOs) - TESTALLOC_OVERHEAD;
41.475 + }
41.476 + return 0;
41.477 +}
41.478 +
41.479 +/*
41.480 +** This is the test layer's wrapper around sqlite3OsFree(). The argument is a
41.481 +** pointer to the space allocated for the application to use.
41.482 +*/
41.483 +static void OSFREE(void *pFree){
41.484 + u32 *p; /* Pointer to the OS-layer allocation */
41.485 + sqlite3OsEnterMutex();
41.486 + p = (u32 *)getOsPointer(pFree);
41.487 + checkGuards(p);
41.488 + unlinkAlloc(p);
41.489 + memset(pFree, 0x55, OSSIZEOF(pFree));
41.490 + sqlite3OsFree(p);
41.491 + sqlite3_nFree++;
41.492 + sqlite3OsLeaveMutex();
41.493 +}
41.494 +
41.495 +/*
41.496 +** This is the test layer's wrapper around sqlite3OsRealloc().
41.497 +*/
41.498 +static void * OSREALLOC(void *pRealloc, int n){
41.499 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
41.500 + sqlite3_nMaxAlloc =
41.501 + MAX(sqlite3_nMaxAlloc, sqlite3ThreadDataReadOnly()->nAlloc);
41.502 +#endif
41.503 + assert( !sqlite3_mallocDisallowed );
41.504 + if( !sqlite3TestMallocFail() ){
41.505 + u32 *p = (u32 *)getOsPointer(pRealloc);
41.506 + checkGuards(p);
41.507 + p = sqlite3OsRealloc(p, n + TESTALLOC_OVERHEAD);
41.508 + applyGuards(p);
41.509 + relinkAlloc(p);
41.510 + return (void *)(&p[TESTALLOC_NGUARD + 2*sizeof(void *)/sizeof(u32)]);
41.511 + }
41.512 + return 0;
41.513 +}
41.514 +
41.515 +static void OSMALLOC_FAILED(){
41.516 + sqlite3_isFail = 0;
41.517 +}
41.518 +
41.519 +#else
41.520 +/* Define macros to call the sqlite3OsXXX interface directly if
41.521 +** the SQLITE_MEMDEBUG macro is not defined.
41.522 +*/
41.523 +#define OSMALLOC(x) sqlite3OsMalloc(x)
41.524 +#define OSREALLOC(x,y) sqlite3OsRealloc(x,y)
41.525 +#define OSFREE(x) sqlite3OsFree(x)
41.526 +#define OSSIZEOF(x) sqlite3OsAllocationSize(x)
41.527 +#define OSMALLOC_FAILED()
41.528 +
41.529 +#endif /* SQLITE_MEMDEBUG */
41.530 +/*
41.531 +** End code for memory allocation system test layer.
41.532 +**--------------------------------------------------------------------------*/
41.533 +
41.534 +/*
41.535 +** This routine is called when we are about to allocate n additional bytes
41.536 +** of memory. If the new allocation will put is over the soft allocation
41.537 +** limit, then invoke sqlite3_release_memory() to try to release some
41.538 +** memory before continuing with the allocation.
41.539 +**
41.540 +** This routine also makes sure that the thread-specific-data (TSD) has
41.541 +** be allocated. If it has not and can not be allocated, then return
41.542 +** false. The updateMemoryUsedCount() routine below will deallocate
41.543 +** the TSD if it ought to be.
41.544 +**
41.545 +** If SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, this routine is
41.546 +** a no-op
41.547 +*/
41.548 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
41.549 +static int enforceSoftLimit(int n){
41.550 + ThreadData *pTsd = sqlite3ThreadData();
41.551 + if( pTsd==0 ){
41.552 + return 0;
41.553 + }
41.554 + assert( pTsd->nAlloc>=0 );
41.555 + if( n>0 && pTsd->nSoftHeapLimit>0 ){
41.556 + while( pTsd->nAlloc+n>pTsd->nSoftHeapLimit && sqlite3_release_memory(n) ){}
41.557 + }
41.558 + return 1;
41.559 +}
41.560 +#else
41.561 +# define enforceSoftLimit(X) 1
41.562 +#endif
41.563 +
41.564 +/*
41.565 +** Update the count of total outstanding memory that is held in
41.566 +** thread-specific-data (TSD). If after this update the TSD is
41.567 +** no longer being used, then deallocate it.
41.568 +**
41.569 +** If SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, this routine is
41.570 +** a no-op
41.571 +*/
41.572 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
41.573 +static void updateMemoryUsedCount(int n){
41.574 + ThreadData *pTsd = sqlite3ThreadData();
41.575 + if( pTsd ){
41.576 + pTsd->nAlloc += n;
41.577 + assert( pTsd->nAlloc>=0 );
41.578 + if( pTsd->nAlloc==0 && pTsd->nSoftHeapLimit==0 ){
41.579 + sqlite3ReleaseThreadData();
41.580 + }
41.581 + }
41.582 +}
41.583 +#else
41.584 +#define updateMemoryUsedCount(x) /* no-op */
41.585 +#endif
41.586 +
41.587 +/*
41.588 +** Allocate and return N bytes of uninitialised memory by calling
41.589 +** sqlite3OsMalloc(). If the Malloc() call fails, attempt to free memory
41.590 +** by calling sqlite3_release_memory().
41.591 +*/
41.592 +void *sqlite3MallocRaw(int n, int doMemManage){
41.593 + void *p = 0;
41.594 + if( n>0 && !sqlite3MallocFailed() && (!doMemManage || enforceSoftLimit(n)) ){
41.595 + while( (p = OSMALLOC(n))==0 && sqlite3_release_memory(n) ){}
41.596 + if( !p ){
41.597 + sqlite3FailedMalloc();
41.598 + OSMALLOC_FAILED();
41.599 + }else if( doMemManage ){
41.600 + updateMemoryUsedCount(OSSIZEOF(p));
41.601 + }
41.602 + }
41.603 + return p;
41.604 +}
41.605 +
41.606 +/*
41.607 +** Resize the allocation at p to n bytes by calling sqlite3OsRealloc(). The
41.608 +** pointer to the new allocation is returned. If the Realloc() call fails,
41.609 +** attempt to free memory by calling sqlite3_release_memory().
41.610 +*/
41.611 +void *sqlite3Realloc(void *p, int n){
41.612 + if( sqlite3MallocFailed() ){
41.613 + return 0;
41.614 + }
41.615 +
41.616 + if( !p ){
41.617 + return sqlite3Malloc(n, 1);
41.618 + }else{
41.619 + void *np = 0;
41.620 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
41.621 + int origSize = OSSIZEOF(p);
41.622 +#endif
41.623 + if( enforceSoftLimit(n - origSize) ){
41.624 + while( (np = OSREALLOC(p, n))==0 && sqlite3_release_memory(n) ){}
41.625 + if( !np ){
41.626 + sqlite3FailedMalloc();
41.627 + OSMALLOC_FAILED();
41.628 + }else{
41.629 + updateMemoryUsedCount(OSSIZEOF(np) - origSize);
41.630 + }
41.631 + }
41.632 + return np;
41.633 + }
41.634 +}
41.635 +
41.636 +/*
41.637 +** Free the memory pointed to by p. p must be either a NULL pointer or a
41.638 +** value returned by a previous call to sqlite3Malloc() or sqlite3Realloc().
41.639 +*/
41.640 +void sqlite3FreeX(void *p){
41.641 + if( p ){
41.642 + updateMemoryUsedCount(0 - OSSIZEOF(p));
41.643 + OSFREE(p);
41.644 + }
41.645 +}
41.646 +
41.647 +/*
41.648 +** A version of sqliteMalloc() that is always a function, not a macro.
41.649 +** Currently, this is used only to alloc to allocate the parser engine.
41.650 +*/
41.651 +void *sqlite3MallocX(int n){
41.652 + return sqliteMalloc(n);
41.653 +}
41.654 +
41.655 +/*
41.656 +** sqlite3Malloc
41.657 +** sqlite3ReallocOrFree
41.658 +**
41.659 +** These two are implemented as wrappers around sqlite3MallocRaw(),
41.660 +** sqlite3Realloc() and sqlite3Free().
41.661 +*/
41.662 +void *sqlite3Malloc(int n, int doMemManage){
41.663 + void *p = sqlite3MallocRaw(n, doMemManage);
41.664 + if( p ){
41.665 + memset(p, 0, n);
41.666 + }
41.667 + return p;
41.668 +}
41.669 +void *sqlite3ReallocOrFree(void *p, int n){
41.670 + void *pNew;
41.671 + pNew = sqlite3Realloc(p, n);
41.672 + if( !pNew ){
41.673 + sqlite3FreeX(p);
41.674 + }
41.675 + return pNew;
41.676 +}
41.677 +
41.678 +/*
41.679 +** sqlite3ThreadSafeMalloc() and sqlite3ThreadSafeFree() are used in those
41.680 +** rare scenarios where sqlite may allocate memory in one thread and free
41.681 +** it in another. They are exactly the same as sqlite3Malloc() and
41.682 +** sqlite3Free() except that:
41.683 +**
41.684 +** * The allocated memory is not included in any calculations with
41.685 +** respect to the soft-heap-limit, and
41.686 +**
41.687 +** * sqlite3ThreadSafeMalloc() must be matched with ThreadSafeFree(),
41.688 +** not sqlite3Free(). Calling sqlite3Free() on memory obtained from
41.689 +** ThreadSafeMalloc() will cause an error somewhere down the line.
41.690 +*/
41.691 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
41.692 +void *sqlite3ThreadSafeMalloc(int n){
41.693 + (void)ENTER_MALLOC;
41.694 + return sqlite3Malloc(n, 0);
41.695 +}
41.696 +void sqlite3ThreadSafeFree(void *p){
41.697 + (void)ENTER_MALLOC;
41.698 + if( p ){
41.699 + OSFREE(p);
41.700 + }
41.701 +}
41.702 +#endif
41.703 +
41.704 +
41.705 +/*
41.706 +** Return the number of bytes allocated at location p. p must be either
41.707 +** a NULL pointer (in which case 0 is returned) or a pointer returned by
41.708 +** sqlite3Malloc(), sqlite3Realloc() or sqlite3ReallocOrFree().
41.709 +**
41.710 +** The number of bytes allocated does not include any overhead inserted by
41.711 +** any malloc() wrapper functions that may be called. So the value returned
41.712 +** is the number of bytes that were available to SQLite using pointer p,
41.713 +** regardless of how much memory was actually allocated.
41.714 +*/
41.715 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
41.716 +int sqlite3AllocSize(void *p){
41.717 + return OSSIZEOF(p);
41.718 +}
41.719 +#endif
41.720 +
41.721 +/*
41.722 +** Make a copy of a string in memory obtained from sqliteMalloc(). These
41.723 +** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
41.724 +** is because when memory debugging is turned on, these two functions are
41.725 +** called via macros that record the current file and line number in the
41.726 +** ThreadData structure.
41.727 +*/
41.728 +char *sqlite3StrDup(const char *z){
41.729 + char *zNew;
41.730 + int n;
41.731 + if( z==0 ) return 0;
41.732 + n = strlen(z)+1;
41.733 + zNew = sqlite3MallocRaw(n, 1);
41.734 + if( zNew ) memcpy(zNew, z, n);
41.735 + return zNew;
41.736 +}
41.737 +char *sqlite3StrNDup(const char *z, int n){
41.738 + char *zNew;
41.739 + if( z==0 ) return 0;
41.740 + zNew = sqlite3MallocRaw(n+1, 1);
41.741 + if( zNew ){
41.742 + memcpy(zNew, z, n);
41.743 + zNew[n] = 0;
41.744 + }
41.745 + return zNew;
41.746 +}
41.747 +
41.748 +/*
41.749 +** Create a string from the 2nd and subsequent arguments (up to the
41.750 +** first NULL argument), store the string in memory obtained from
41.751 +** sqliteMalloc() and make the pointer indicated by the 1st argument
41.752 +** point to that string. The 1st argument must either be NULL or
41.753 +** point to memory obtained from sqliteMalloc().
41.754 +*/
41.755 +void sqlite3SetString(char **pz, ...){
41.756 + va_list ap;
41.757 + int nByte;
41.758 + const char *z;
41.759 + char *zResult;
41.760 +
41.761 + assert( pz!=0 );
41.762 + nByte = 1;
41.763 + va_start(ap, pz);
41.764 + while( (z = va_arg(ap, const char*))!=0 ){
41.765 + nByte += strlen(z);
41.766 + }
41.767 + va_end(ap);
41.768 + sqliteFree(*pz);
41.769 + *pz = zResult = sqliteMallocRaw( nByte );
41.770 + if( zResult==0 ){
41.771 + return;
41.772 + }
41.773 + *zResult = 0;
41.774 + va_start(ap, pz);
41.775 + while( (z = va_arg(ap, const char*))!=0 ){
41.776 + int n = strlen(z);
41.777 + memcpy(zResult, z, n);
41.778 + zResult += n;
41.779 + }
41.780 + zResult[0] = 0;
41.781 + va_end(ap);
41.782 +}
41.783 +
41.784 +
41.785 +/*
41.786 +** This function must be called before exiting any API function (i.e.
41.787 +** returning control to the user) that has called sqlite3Malloc or
41.788 +** sqlite3Realloc.
41.789 +**
41.790 +** The returned value is normally a copy of the second argument to this
41.791 +** function. However, if a malloc() failure has occured since the previous
41.792 +** invocation SQLITE_NOMEM is returned instead.
41.793 +**
41.794 +** If the first argument, db, is not NULL and a malloc() error has occured,
41.795 +** then the connection error-code (the value returned by sqlite3_errcode())
41.796 +** is set to SQLITE_NOMEM.
41.797 +*/
41.798 +int sqlite3_mallocHasFailed = 0;
41.799 +int sqlite3ApiExit(sqlite3* db, int rc){
41.800 + if( sqlite3MallocFailed() ){
41.801 + sqlite3_mallocHasFailed = 0;
41.802 + sqlite3OsLeaveMutex();
41.803 + sqlite3Error(db, SQLITE_NOMEM, 0);
41.804 + rc = SQLITE_NOMEM;
41.805 + }
41.806 + return rc & (db ? db->errMask : 0xff);
41.807 +}
41.808 +
41.809 +/*
41.810 +** Set the "malloc has failed" condition to true for this thread.
41.811 +*/
41.812 +void sqlite3FailedMalloc(){
41.813 + if( !sqlite3MallocFailed() ){
41.814 + sqlite3OsEnterMutex();
41.815 + assert( sqlite3_mallocHasFailed==0 );
41.816 + sqlite3_mallocHasFailed = 1;
41.817 + }
41.818 +}
41.819 +
41.820 +#ifdef SQLITE_MEMDEBUG
41.821 +/*
41.822 +** This function sets a flag in the thread-specific-data structure that will
41.823 +** cause an assert to fail if sqliteMalloc() or sqliteRealloc() is called.
41.824 +*/
41.825 +void sqlite3MallocDisallow(){
41.826 + assert( sqlite3_mallocDisallowed>=0 );
41.827 + sqlite3_mallocDisallowed++;
41.828 +}
41.829 +
41.830 +/*
41.831 +** This function clears the flag set in the thread-specific-data structure set
41.832 +** by sqlite3MallocDisallow().
41.833 +*/
41.834 +void sqlite3MallocAllow(){
41.835 + assert( sqlite3_mallocDisallowed>0 );
41.836 + sqlite3_mallocDisallowed--;
41.837 +}
41.838 +#endif
42.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
42.2 +++ b/extensions/sqlite/sqlite-source/opcodes.c Sun Jul 29 01:15:31 2007 +0000
42.3 @@ -0,0 +1,148 @@
42.4 +/* Automatically generated. Do not edit */
42.5 +/* See the mkopcodec.awk script for details. */
42.6 +#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
42.7 +const char *const sqlite3OpcodeNames[] = { "?",
42.8 + /* 1 */ "MemLoad",
42.9 + /* 2 */ "VNext",
42.10 + /* 3 */ "Column",
42.11 + /* 4 */ "SetCookie",
42.12 + /* 5 */ "IfMemPos",
42.13 + /* 6 */ "Sequence",
42.14 + /* 7 */ "MoveGt",
42.15 + /* 8 */ "RowKey",
42.16 + /* 9 */ "OpenWrite",
42.17 + /* 10 */ "If",
42.18 + /* 11 */ "Pop",
42.19 + /* 12 */ "VRowid",
42.20 + /* 13 */ "CollSeq",
42.21 + /* 14 */ "OpenRead",
42.22 + /* 15 */ "Expire",
42.23 + /* 16 */ "Not",
42.24 + /* 17 */ "AutoCommit",
42.25 + /* 18 */ "IntegrityCk",
42.26 + /* 19 */ "Sort",
42.27 + /* 20 */ "Function",
42.28 + /* 21 */ "Noop",
42.29 + /* 22 */ "Return",
42.30 + /* 23 */ "NewRowid",
42.31 + /* 24 */ "IfMemNeg",
42.32 + /* 25 */ "Variable",
42.33 + /* 26 */ "String",
42.34 + /* 27 */ "RealAffinity",
42.35 + /* 28 */ "VRename",
42.36 + /* 29 */ "ParseSchema",
42.37 + /* 30 */ "VOpen",
42.38 + /* 31 */ "Close",
42.39 + /* 32 */ "CreateIndex",
42.40 + /* 33 */ "IsUnique",
42.41 + /* 34 */ "NotFound",
42.42 + /* 35 */ "Int64",
42.43 + /* 36 */ "MustBeInt",
42.44 + /* 37 */ "Halt",
42.45 + /* 38 */ "Rowid",
42.46 + /* 39 */ "IdxLT",
42.47 + /* 40 */ "AddImm",
42.48 + /* 41 */ "Statement",
42.49 + /* 42 */ "RowData",
42.50 + /* 43 */ "MemMax",
42.51 + /* 44 */ "Push",
42.52 + /* 45 */ "NotExists",
42.53 + /* 46 */ "MemIncr",
42.54 + /* 47 */ "Gosub",
42.55 + /* 48 */ "Integer",
42.56 + /* 49 */ "MemInt",
42.57 + /* 50 */ "Prev",
42.58 + /* 51 */ "VColumn",
42.59 + /* 52 */ "CreateTable",
42.60 + /* 53 */ "Last",
42.61 + /* 54 */ "IncrVacuum",
42.62 + /* 55 */ "IdxRowid",
42.63 + /* 56 */ "MakeIdxRec",
42.64 + /* 57 */ "ResetCount",
42.65 + /* 58 */ "FifoWrite",
42.66 + /* 59 */ "Callback",
42.67 + /* 60 */ "Or",
42.68 + /* 61 */ "And",
42.69 + /* 62 */ "ContextPush",
42.70 + /* 63 */ "DropTrigger",
42.71 + /* 64 */ "DropIndex",
42.72 + /* 65 */ "IsNull",
42.73 + /* 66 */ "NotNull",
42.74 + /* 67 */ "Ne",
42.75 + /* 68 */ "Eq",
42.76 + /* 69 */ "Gt",
42.77 + /* 70 */ "Le",
42.78 + /* 71 */ "Lt",
42.79 + /* 72 */ "Ge",
42.80 + /* 73 */ "IdxGE",
42.81 + /* 74 */ "BitAnd",
42.82 + /* 75 */ "BitOr",
42.83 + /* 76 */ "ShiftLeft",
42.84 + /* 77 */ "ShiftRight",
42.85 + /* 78 */ "Add",
42.86 + /* 79 */ "Subtract",
42.87 + /* 80 */ "Multiply",
42.88 + /* 81 */ "Divide",
42.89 + /* 82 */ "Remainder",
42.90 + /* 83 */ "Concat",
42.91 + /* 84 */ "IdxDelete",
42.92 + /* 85 */ "Negative",
42.93 + /* 86 */ "Vacuum",
42.94 + /* 87 */ "BitNot",
42.95 + /* 88 */ "String8",
42.96 + /* 89 */ "MoveLe",
42.97 + /* 90 */ "IfNot",
42.98 + /* 91 */ "DropTable",
42.99 + /* 92 */ "MakeRecord",
42.100 + /* 93 */ "Delete",
42.101 + /* 94 */ "AggFinal",
42.102 + /* 95 */ "Dup",
42.103 + /* 96 */ "Goto",
42.104 + /* 97 */ "TableLock",
42.105 + /* 98 */ "FifoRead",
42.106 + /* 99 */ "Clear",
42.107 + /* 100 */ "IdxGT",
42.108 + /* 101 */ "MoveLt",
42.109 + /* 102 */ "VerifyCookie",
42.110 + /* 103 */ "AggStep",
42.111 + /* 104 */ "Pull",
42.112 + /* 105 */ "SetNumColumns",
42.113 + /* 106 */ "AbsValue",
42.114 + /* 107 */ "Transaction",
42.115 + /* 108 */ "VFilter",
42.116 + /* 109 */ "VDestroy",
42.117 + /* 110 */ "ContextPop",
42.118 + /* 111 */ "Next",
42.119 + /* 112 */ "IdxInsert",
42.120 + /* 113 */ "Distinct",
42.121 + /* 114 */ "Insert",
42.122 + /* 115 */ "Destroy",
42.123 + /* 116 */ "ReadCookie",
42.124 + /* 117 */ "ForceInt",
42.125 + /* 118 */ "LoadAnalysis",
42.126 + /* 119 */ "Explain",
42.127 + /* 120 */ "IfMemZero",
42.128 + /* 121 */ "OpenPseudo",
42.129 + /* 122 */ "OpenEphemeral",
42.130 + /* 123 */ "Null",
42.131 + /* 124 */ "Blob",
42.132 + /* 125 */ "Real",
42.133 + /* 126 */ "HexBlob",
42.134 + /* 127 */ "MemStore",
42.135 + /* 128 */ "Rewind",
42.136 + /* 129 */ "MoveGe",
42.137 + /* 130 */ "VBegin",
42.138 + /* 131 */ "VUpdate",
42.139 + /* 132 */ "VCreate",
42.140 + /* 133 */ "MemMove",
42.141 + /* 134 */ "MemNull",
42.142 + /* 135 */ "Found",
42.143 + /* 136 */ "NullRow",
42.144 + /* 137 */ "NotUsed_137",
42.145 + /* 138 */ "ToText",
42.146 + /* 139 */ "ToBlob",
42.147 + /* 140 */ "ToNumeric",
42.148 + /* 141 */ "ToInt",
42.149 + /* 142 */ "ToReal",
42.150 +};
42.151 +#endif
43.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
43.2 +++ b/extensions/sqlite/sqlite-source/opcodes.h Sun Jul 29 01:15:31 2007 +0000
43.3 @@ -0,0 +1,160 @@
43.4 +/* Automatically generated. Do not edit */
43.5 +/* See the mkopcodeh.awk script for details */
43.6 +#define OP_MemLoad 1
43.7 +#define OP_VNext 2
43.8 +#define OP_HexBlob 126 /* same as TK_BLOB */
43.9 +#define OP_Column 3
43.10 +#define OP_SetCookie 4
43.11 +#define OP_IfMemPos 5
43.12 +#define OP_Real 125 /* same as TK_FLOAT */
43.13 +#define OP_Sequence 6
43.14 +#define OP_MoveGt 7
43.15 +#define OP_Ge 72 /* same as TK_GE */
43.16 +#define OP_RowKey 8
43.17 +#define OP_Eq 68 /* same as TK_EQ */
43.18 +#define OP_OpenWrite 9
43.19 +#define OP_NotNull 66 /* same as TK_NOTNULL */
43.20 +#define OP_If 10
43.21 +#define OP_ToInt 141 /* same as TK_TO_INT */
43.22 +#define OP_String8 88 /* same as TK_STRING */
43.23 +#define OP_Pop 11
43.24 +#define OP_VRowid 12
43.25 +#define OP_CollSeq 13
43.26 +#define OP_OpenRead 14
43.27 +#define OP_Expire 15
43.28 +#define OP_AutoCommit 17
43.29 +#define OP_Gt 69 /* same as TK_GT */
43.30 +#define OP_IntegrityCk 18
43.31 +#define OP_Sort 19
43.32 +#define OP_Function 20
43.33 +#define OP_And 61 /* same as TK_AND */
43.34 +#define OP_Subtract 79 /* same as TK_MINUS */
43.35 +#define OP_Noop 21
43.36 +#define OP_Return 22
43.37 +#define OP_Remainder 82 /* same as TK_REM */
43.38 +#define OP_NewRowid 23
43.39 +#define OP_Multiply 80 /* same as TK_STAR */
43.40 +#define OP_IfMemNeg 24
43.41 +#define OP_Variable 25
43.42 +#define OP_String 26
43.43 +#define OP_RealAffinity 27
43.44 +#define OP_VRename 28
43.45 +#define OP_ParseSchema 29
43.46 +#define OP_VOpen 30
43.47 +#define OP_Close 31
43.48 +#define OP_CreateIndex 32
43.49 +#define OP_IsUnique 33
43.50 +#define OP_NotFound 34
43.51 +#define OP_Int64 35
43.52 +#define OP_MustBeInt 36
43.53 +#define OP_Halt 37
43.54 +#define OP_Rowid 38
43.55 +#define OP_IdxLT 39
43.56 +#define OP_AddImm 40
43.57 +#define OP_Statement 41
43.58 +#define OP_RowData 42
43.59 +#define OP_MemMax 43
43.60 +#define OP_Push 44
43.61 +#define OP_Or 60 /* same as TK_OR */
43.62 +#define OP_NotExists 45
43.63 +#define OP_MemIncr 46
43.64 +#define OP_Gosub 47
43.65 +#define OP_Divide 81 /* same as TK_SLASH */
43.66 +#define OP_Integer 48
43.67 +#define OP_ToNumeric 140 /* same as TK_TO_NUMERIC*/
43.68 +#define OP_MemInt 49
43.69 +#define OP_Prev 50
43.70 +#define OP_Concat 83 /* same as TK_CONCAT */
43.71 +#define OP_BitAnd 74 /* same as TK_BITAND */
43.72 +#define OP_VColumn 51
43.73 +#define OP_CreateTable 52
43.74 +#define OP_Last 53
43.75 +#define OP_IsNull 65 /* same as TK_ISNULL */
43.76 +#define OP_IncrVacuum 54
43.77 +#define OP_IdxRowid 55
43.78 +#define OP_MakeIdxRec 56
43.79 +#define OP_ShiftRight 77 /* same as TK_RSHIFT */
43.80 +#define OP_ResetCount 57
43.81 +#define OP_FifoWrite 58
43.82 +#define OP_Callback 59
43.83 +#define OP_ContextPush 62
43.84 +#define OP_DropTrigger 63
43.85 +#define OP_DropIndex 64
43.86 +#define OP_IdxGE 73
43.87 +#define OP_IdxDelete 84
43.88 +#define OP_Vacuum 86
43.89 +#define OP_MoveLe 89
43.90 +#define OP_IfNot 90
43.91 +#define OP_DropTable 91
43.92 +#define OP_MakeRecord 92
43.93 +#define OP_ToBlob 139 /* same as TK_TO_BLOB */
43.94 +#define OP_Delete 93
43.95 +#define OP_AggFinal 94
43.96 +#define OP_ShiftLeft 76 /* same as TK_LSHIFT */
43.97 +#define OP_Dup 95
43.98 +#define OP_Goto 96
43.99 +#define OP_TableLock 97
43.100 +#define OP_FifoRead 98
43.101 +#define OP_Clear 99
43.102 +#define OP_IdxGT 100
43.103 +#define OP_MoveLt 101
43.104 +#define OP_Le 70 /* same as TK_LE */
43.105 +#define OP_VerifyCookie 102
43.106 +#define OP_AggStep 103
43.107 +#define OP_Pull 104
43.108 +#define OP_ToText 138 /* same as TK_TO_TEXT */
43.109 +#define OP_Not 16 /* same as TK_NOT */
43.110 +#define OP_ToReal 142 /* same as TK_TO_REAL */
43.111 +#define OP_SetNumColumns 105
43.112 +#define OP_AbsValue 106
43.113 +#define OP_Transaction 107
43.114 +#define OP_VFilter 108
43.115 +#define OP_Negative 85 /* same as TK_UMINUS */
43.116 +#define OP_Ne 67 /* same as TK_NE */
43.117 +#define OP_VDestroy 109
43.118 +#define OP_ContextPop 110
43.119 +#define OP_BitOr 75 /* same as TK_BITOR */
43.120 +#define OP_Next 111
43.121 +#define OP_IdxInsert 112
43.122 +#define OP_Distinct 113
43.123 +#define OP_Lt 71 /* same as TK_LT */
43.124 +#define OP_Insert 114
43.125 +#define OP_Destroy 115
43.126 +#define OP_ReadCookie 116
43.127 +#define OP_ForceInt 117
43.128 +#define OP_LoadAnalysis 118
43.129 +#define OP_Explain 119
43.130 +#define OP_IfMemZero 120
43.131 +#define OP_OpenPseudo 121
43.132 +#define OP_OpenEphemeral 122
43.133 +#define OP_Null 123
43.134 +#define OP_Blob 124
43.135 +#define OP_Add 78 /* same as TK_PLUS */
43.136 +#define OP_MemStore 127
43.137 +#define OP_Rewind 128
43.138 +#define OP_MoveGe 129
43.139 +#define OP_VBegin 130
43.140 +#define OP_VUpdate 131
43.141 +#define OP_BitNot 87 /* same as TK_BITNOT */
43.142 +#define OP_VCreate 132
43.143 +#define OP_MemMove 133
43.144 +#define OP_MemNull 134
43.145 +#define OP_Found 135
43.146 +#define OP_NullRow 136
43.147 +
43.148 +/* The following opcode values are never used */
43.149 +#define OP_NotUsed_137 137
43.150 +
43.151 +/* Opcodes that are guaranteed to never push a value onto the stack
43.152 +** contain a 1 their corresponding position of the following mask
43.153 +** set. See the opcodeNoPush() function in vdbeaux.c */
43.154 +#define NOPUSH_MASK_0 0xeeb4
43.155 +#define NOPUSH_MASK_1 0xf96b
43.156 +#define NOPUSH_MASK_2 0xfbb6
43.157 +#define NOPUSH_MASK_3 0xfe64
43.158 +#define NOPUSH_MASK_4 0xffff
43.159 +#define NOPUSH_MASK_5 0x6ef7
43.160 +#define NOPUSH_MASK_6 0xfbfb
43.161 +#define NOPUSH_MASK_7 0x8767
43.162 +#define NOPUSH_MASK_8 0x7d9f
43.163 +#define NOPUSH_MASK_9 0x0000
44.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
44.2 +++ b/extensions/sqlite/sqlite-source/os.c Sun Jul 29 01:15:31 2007 +0000
44.3 @@ -0,0 +1,96 @@
44.4 +/*
44.5 +** 2005 November 29
44.6 +**
44.7 +** The author disclaims copyright to this source code. In place of
44.8 +** a legal notice, here is a blessing:
44.9 +**
44.10 +** May you do good and not evil.
44.11 +** May you find forgiveness for yourself and forgive others.
44.12 +** May you share freely, never taking more than you give.
44.13 +**
44.14 +******************************************************************************
44.15 +**
44.16 +** This file contains OS interface code that is common to all
44.17 +** architectures.
44.18 +*/
44.19 +#define _SQLITE_OS_C_ 1
44.20 +#include "sqliteInt.h"
44.21 +#include "os.h"
44.22 +#undef _SQLITE_OS_C_
44.23 +
44.24 +/*
44.25 +** The following routines are convenience wrappers around methods
44.26 +** of the OsFile object. This is mostly just syntactic sugar. All
44.27 +** of this would be completely automatic if SQLite were coded using
44.28 +** C++ instead of plain old C.
44.29 +*/
44.30 +int sqlite3OsClose(OsFile **pId){
44.31 + OsFile *id;
44.32 + if( pId!=0 && (id = *pId)!=0 ){
44.33 + return id->pMethod->xClose(pId);
44.34 + }else{
44.35 + return SQLITE_OK;
44.36 + }
44.37 +}
44.38 +int sqlite3OsOpenDirectory(OsFile *id, const char *zName){
44.39 + return id->pMethod->xOpenDirectory(id, zName);
44.40 +}
44.41 +int sqlite3OsRead(OsFile *id, void *pBuf, int amt){
44.42 + return id->pMethod->xRead(id, pBuf, amt);
44.43 +}
44.44 +int sqlite3OsWrite(OsFile *id, const void *pBuf, int amt){
44.45 + return id->pMethod->xWrite(id, pBuf, amt);
44.46 +}
44.47 +int sqlite3OsSeek(OsFile *id, i64 offset){
44.48 + return id->pMethod->xSeek(id, offset);
44.49 +}
44.50 +int sqlite3OsTruncate(OsFile *id, i64 size){
44.51 + return id->pMethod->xTruncate(id, size);
44.52 +}
44.53 +int sqlite3OsSync(OsFile *id, int fullsync){
44.54 + return id->pMethod->xSync(id, fullsync);
44.55 +}
44.56 +void sqlite3OsSetFullSync(OsFile *id, int value){
44.57 + id->pMethod->xSetFullSync(id, value);
44.58 +}
44.59 +int sqlite3OsFileSize(OsFile *id, i64 *pSize){
44.60 + return id->pMethod->xFileSize(id, pSize);
44.61 +}
44.62 +int sqlite3OsLock(OsFile *id, int lockType){
44.63 + return id->pMethod->xLock(id, lockType);
44.64 +}
44.65 +int sqlite3OsUnlock(OsFile *id, int lockType){
44.66 + return id->pMethod->xUnlock(id, lockType);
44.67 +}
44.68 +int sqlite3OsCheckReservedLock(OsFile *id){
44.69 + return id->pMethod->xCheckReservedLock(id);
44.70 +}
44.71 +int sqlite3OsSectorSize(OsFile *id){
44.72 + int (*xSectorSize)(OsFile*) = id->pMethod->xSectorSize;
44.73 + return xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE;
44.74 +}
44.75 +
44.76 +#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
44.77 + /* These methods are currently only used for testing and debugging. */
44.78 + int sqlite3OsFileHandle(OsFile *id){
44.79 + return id->pMethod->xFileHandle(id);
44.80 + }
44.81 + int sqlite3OsLockState(OsFile *id){
44.82 + return id->pMethod->xLockState(id);
44.83 + }
44.84 +#endif
44.85 +
44.86 +#ifdef SQLITE_ENABLE_REDEF_IO
44.87 +/*
44.88 +** A function to return a pointer to the virtual function table.
44.89 +** This routine really does not accomplish very much since the
44.90 +** virtual function table is a global variable and anybody who
44.91 +** can call this function can just as easily access the variable
44.92 +** for themselves. Nevertheless, we include this routine for
44.93 +** backwards compatibility with an earlier redefinable I/O
44.94 +** interface design.
44.95 +*/
44.96 +struct sqlite3OsVtbl *sqlite3_os_switch(void){
44.97 + return &sqlite3Os;
44.98 +}
44.99 +#endif
45.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
45.2 +++ b/extensions/sqlite/sqlite-source/os.h Sun Jul 29 01:15:31 2007 +0000
45.3 @@ -0,0 +1,548 @@
45.4 +/*
45.5 +** 2001 September 16
45.6 +**
45.7 +** The author disclaims copyright to this source code. In place of
45.8 +** a legal notice, here is a blessing:
45.9 +**
45.10 +** May you do good and not evil.
45.11 +** May you find forgiveness for yourself and forgive others.
45.12 +** May you share freely, never taking more than you give.
45.13 +**
45.14 +******************************************************************************
45.15 +**
45.16 +** This header file (together with is companion C source-code file
45.17 +** "os.c") attempt to abstract the underlying operating system so that
45.18 +** the SQLite library will work on both POSIX and windows systems.
45.19 +*/
45.20 +#ifndef _SQLITE_OS_H_
45.21 +#define _SQLITE_OS_H_
45.22 +
45.23 +/*
45.24 +** Figure out if we are dealing with Unix, Windows, or some other
45.25 +** operating system.
45.26 +*/
45.27 +#if defined(OS_OTHER)
45.28 +# if OS_OTHER==1
45.29 +# undef OS_UNIX
45.30 +# define OS_UNIX 0
45.31 +# undef OS_WIN
45.32 +# define OS_WIN 0
45.33 +# undef OS_OS2
45.34 +# define OS_OS2 0
45.35 +# else
45.36 +# undef OS_OTHER
45.37 +# endif
45.38 +#endif
45.39 +#if !defined(OS_UNIX) && !defined(OS_OTHER)
45.40 +# define OS_OTHER 0
45.41 +# ifndef OS_WIN
45.42 +# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
45.43 +# define OS_WIN 1
45.44 +# define OS_UNIX 0
45.45 +# define OS_OS2 0
45.46 +# elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
45.47 +# define OS_WIN 0
45.48 +# define OS_UNIX 0
45.49 +# define OS_OS2 1
45.50 +# else
45.51 +# define OS_WIN 0
45.52 +# define OS_UNIX 1
45.53 +# define OS_OS2 0
45.54 +# endif
45.55 +# else
45.56 +# define OS_UNIX 0
45.57 +# define OS_OS2 0
45.58 +# endif
45.59 +#else
45.60 +# ifndef OS_WIN
45.61 +# define OS_WIN 0
45.62 +# endif
45.63 +#endif
45.64 +
45.65 +
45.66 +/*
45.67 +** Define the maximum size of a temporary filename
45.68 +*/
45.69 +#if OS_WIN
45.70 +# include <windows.h>
45.71 +# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
45.72 +#elif OS_OS2
45.73 +# if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
45.74 +# include <os2safe.h> /* has to be included before os2.h for linking to work */
45.75 +# endif
45.76 +# define INCL_DOSDATETIME
45.77 +# define INCL_DOSFILEMGR
45.78 +# define INCL_DOSERRORS
45.79 +# define INCL_DOSMISC
45.80 +# define INCL_DOSPROCESS
45.81 +# define INCL_DOSMODULEMGR
45.82 +# include <os2.h>
45.83 +# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
45.84 +#else
45.85 +# define SQLITE_TEMPNAME_SIZE 200
45.86 +#endif
45.87 +
45.88 +/* If the SET_FULLSYNC macro is not defined above, then make it
45.89 +** a no-op
45.90 +*/
45.91 +#ifndef SET_FULLSYNC
45.92 +# define SET_FULLSYNC(x,y)
45.93 +#endif
45.94 +
45.95 +/*
45.96 +** The default size of a disk sector
45.97 +*/
45.98 +#ifndef SQLITE_DEFAULT_SECTOR_SIZE
45.99 +# define SQLITE_DEFAULT_SECTOR_SIZE 512
45.100 +#endif
45.101 +
45.102 +/*
45.103 +** Temporary files are named starting with this prefix followed by 16 random
45.104 +** alphanumeric characters, and no file extension. They are stored in the
45.105 +** OS's standard temporary file directory, and are deleted prior to exit.
45.106 +** If sqlite is being embedded in another program, you may wish to change the
45.107 +** prefix to reflect your program's name, so that if your program exits
45.108 +** prematurely, old temporary files can be easily identified. This can be done
45.109 +** using -DTEMP_FILE_PREFIX=myprefix_ on the compiler command line.
45.110 +**
45.111 +** 2006-10-31: The default prefix used to be "sqlite_". But then
45.112 +** Mcafee started using SQLite in their anti-virus product and it
45.113 +** started putting files with the "sqlite" name in the c:/temp folder.
45.114 +** This annoyed many windows users. Those users would then do a
45.115 +** Google search for "sqlite", find the telephone numbers of the
45.116 +** developers and call to wake them up at night and complain.
45.117 +** For this reason, the default name prefix is changed to be "sqlite"
45.118 +** spelled backwards. So the temp files are still identified, but
45.119 +** anybody smart enough to figure out the code is also likely smart
45.120 +** enough to know that calling the developer will not help get rid
45.121 +** of the file.
45.122 +*/
45.123 +#ifndef TEMP_FILE_PREFIX
45.124 +# define TEMP_FILE_PREFIX "etilqs_"
45.125 +#endif
45.126 +
45.127 +/*
45.128 +** Define the interfaces for Unix, Windows, and OS/2.
45.129 +*/
45.130 +#if OS_UNIX
45.131 +#define sqlite3OsOpenReadWrite sqlite3UnixOpenReadWrite
45.132 +#define sqlite3OsOpenExclusive sqlite3UnixOpenExclusive
45.133 +#define sqlite3OsOpenReadOnly sqlite3UnixOpenReadOnly
45.134 +#define sqlite3OsDelete sqlite3UnixDelete
45.135 +#define sqlite3OsFileExists sqlite3UnixFileExists
45.136 +#define sqlite3OsFullPathname sqlite3UnixFullPathname
45.137 +#define sqlite3OsIsDirWritable sqlite3UnixIsDirWritable
45.138 +#define sqlite3OsSyncDirectory sqlite3UnixSyncDirectory
45.139 +#define sqlite3OsTempFileName sqlite3UnixTempFileName
45.140 +#define sqlite3OsRandomSeed sqlite3UnixRandomSeed
45.141 +#define sqlite3OsSleep sqlite3UnixSleep
45.142 +#define sqlite3OsCurrentTime sqlite3UnixCurrentTime
45.143 +#define sqlite3OsEnterMutex sqlite3UnixEnterMutex
45.144 +#define sqlite3OsLeaveMutex sqlite3UnixLeaveMutex
45.145 +#define sqlite3OsInMutex sqlite3UnixInMutex
45.146 +#define sqlite3OsThreadSpecificData sqlite3UnixThreadSpecificData
45.147 +#define sqlite3OsMalloc sqlite3GenericMalloc
45.148 +#define sqlite3OsRealloc sqlite3GenericRealloc
45.149 +#define sqlite3OsFree sqlite3GenericFree
45.150 +#define sqlite3OsAllocationSize sqlite3GenericAllocationSize
45.151 +#define sqlite3OsDlopen sqlite3UnixDlopen
45.152 +#define sqlite3OsDlsym sqlite3UnixDlsym
45.153 +#define sqlite3OsDlclose sqlite3UnixDlclose
45.154 +#endif
45.155 +#if OS_WIN
45.156 +#define sqlite3OsOpenReadWrite sqlite3WinOpenReadWrite
45.157 +#define sqlite3OsOpenExclusive sqlite3WinOpenExclusive
45.158 +#define sqlite3OsOpenReadOnly sqlite3WinOpenReadOnly
45.159 +#define sqlite3OsDelete sqlite3WinDelete
45.160 +#define sqlite3OsFileExists sqlite3WinFileExists
45.161 +#define sqlite3OsFullPathname sqlite3WinFullPathname
45.162 +#define sqlite3OsIsDirWritable sqlite3WinIsDirWritable
45.163 +#define sqlite3OsSyncDirectory sqlite3WinSyncDirectory
45.164 +#define sqlite3OsTempFileName sqlite3WinTempFileName
45.165 +#define sqlite3OsRandomSeed sqlite3WinRandomSeed
45.166 +#define sqlite3OsSleep sqlite3WinSleep
45.167 +#define sqlite3OsCurrentTime sqlite3WinCurrentTime
45.168 +#define sqlite3OsEnterMutex sqlite3WinEnterMutex
45.169 +#define sqlite3OsLeaveMutex sqlite3WinLeaveMutex
45.170 +#define sqlite3OsInMutex sqlite3WinInMutex
45.171 +#define sqlite3OsThreadSpecificData sqlite3WinThreadSpecificData
45.172 +#define sqlite3OsMalloc sqlite3GenericMalloc
45.173 +#define sqlite3OsRealloc sqlite3GenericRealloc
45.174 +#define sqlite3OsFree sqlite3GenericFree
45.175 +#define sqlite3OsAllocationSize sqlite3GenericAllocationSize
45.176 +#define sqlite3OsDlopen sqlite3WinDlopen
45.177 +#define sqlite3OsDlsym sqlite3WinDlsym
45.178 +#define sqlite3OsDlclose sqlite3WinDlclose
45.179 +#endif
45.180 +#if OS_OS2
45.181 +#define sqlite3OsOpenReadWrite sqlite3Os2OpenReadWrite
45.182 +#define sqlite3OsOpenExclusive sqlite3Os2OpenExclusive
45.183 +#define sqlite3OsOpenReadOnly sqlite3Os2OpenReadOnly
45.184 +#define sqlite3OsDelete sqlite3Os2Delete
45.185 +#define sqlite3OsFileExists sqlite3Os2FileExists
45.186 +#define sqlite3OsFullPathname sqlite3Os2FullPathname
45.187 +#define sqlite3OsIsDirWritable sqlite3Os2IsDirWritable
45.188 +#define sqlite3OsSyncDirectory sqlite3Os2SyncDirectory
45.189 +#define sqlite3OsTempFileName sqlite3Os2TempFileName
45.190 +#define sqlite3OsRandomSeed sqlite3Os2RandomSeed
45.191 +#define sqlite3OsSleep sqlite3Os2Sleep
45.192 +#define sqlite3OsCurrentTime sqlite3Os2CurrentTime
45.193 +#define sqlite3OsEnterMutex sqlite3Os2EnterMutex
45.194 +#define sqlite3OsLeaveMutex sqlite3Os2LeaveMutex
45.195 +#define sqlite3OsInMutex sqlite3Os2InMutex
45.196 +#define sqlite3OsThreadSpecificData sqlite3Os2ThreadSpecificData
45.197 +#define sqlite3OsMalloc sqlite3GenericMalloc
45.198 +#define sqlite3OsRealloc sqlite3GenericRealloc
45.199 +#define sqlite3OsFree sqlite3GenericFree
45.200 +#define sqlite3OsAllocationSize sqlite3GenericAllocationSize
45.201 +#define sqlite3OsDlopen sqlite3Os2Dlopen
45.202 +#define sqlite3OsDlsym sqlite3Os2Dlsym
45.203 +#define sqlite3OsDlclose sqlite3Os2Dlclose
45.204 +#endif
45.205 +
45.206 +
45.207 +
45.208 +
45.209 +/*
45.210 +** If using an alternative OS interface, then we must have an "os_other.h"
45.211 +** header file available for that interface. Presumably the "os_other.h"
45.212 +** header file contains #defines similar to those above.
45.213 +*/
45.214 +#if OS_OTHER
45.215 +# include "os_other.h"
45.216 +#endif
45.217 +
45.218 +
45.219 +
45.220 +/*
45.221 +** Forward declarations
45.222 +*/
45.223 +typedef struct OsFile OsFile;
45.224 +typedef struct IoMethod IoMethod;
45.225 +
45.226 +/*
45.227 +** An instance of the following structure contains pointers to all
45.228 +** methods on an OsFile object.
45.229 +*/
45.230 +struct IoMethod {
45.231 + int (*xClose)(OsFile**);
45.232 + int (*xOpenDirectory)(OsFile*, const char*);
45.233 + int (*xRead)(OsFile*, void*, int amt);
45.234 + int (*xWrite)(OsFile*, const void*, int amt);
45.235 + int (*xSeek)(OsFile*, i64 offset);
45.236 + int (*xTruncate)(OsFile*, i64 size);
45.237 + int (*xSync)(OsFile*, int);
45.238 + void (*xSetFullSync)(OsFile *id, int setting);
45.239 + int (*xFileHandle)(OsFile *id);
45.240 + int (*xFileSize)(OsFile*, i64 *pSize);
45.241 + int (*xLock)(OsFile*, int);
45.242 + int (*xUnlock)(OsFile*, int);
45.243 + int (*xLockState)(OsFile *id);
45.244 + int (*xCheckReservedLock)(OsFile *id);
45.245 + int (*xSectorSize)(OsFile *id);
45.246 +};
45.247 +
45.248 +/*
45.249 +** The OsFile object describes an open disk file in an OS-dependent way.
45.250 +** The version of OsFile defined here is a generic version. Each OS
45.251 +** implementation defines its own subclass of this structure that contains
45.252 +** additional information needed to handle file I/O. But the pMethod
45.253 +** entry (pointing to the virtual function table) always occurs first
45.254 +** so that we can always find the appropriate methods.
45.255 +*/
45.256 +struct OsFile {
45.257 + IoMethod const *pMethod;
45.258 +};
45.259 +
45.260 +/*
45.261 +** The following values may be passed as the second argument to
45.262 +** sqlite3OsLock(). The various locks exhibit the following semantics:
45.263 +**
45.264 +** SHARED: Any number of processes may hold a SHARED lock simultaneously.
45.265 +** RESERVED: A single process may hold a RESERVED lock on a file at
45.266 +** any time. Other processes may hold and obtain new SHARED locks.
45.267 +** PENDING: A single process may hold a PENDING lock on a file at
45.268 +** any one time. Existing SHARED locks may persist, but no new
45.269 +** SHARED locks may be obtained by other processes.
45.270 +** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
45.271 +**
45.272 +** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
45.273 +** process that requests an EXCLUSIVE lock may actually obtain a PENDING
45.274 +** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
45.275 +** sqlite3OsLock().
45.276 +*/
45.277 +#define NO_LOCK 0
45.278 +#define SHARED_LOCK 1
45.279 +#define RESERVED_LOCK 2
45.280 +#define PENDING_LOCK 3
45.281 +#define EXCLUSIVE_LOCK 4
45.282 +
45.283 +/*
45.284 +** File Locking Notes: (Mostly about windows but also some info for Unix)
45.285 +**
45.286 +** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
45.287 +** those functions are not available. So we use only LockFile() and
45.288 +** UnlockFile().
45.289 +**
45.290 +** LockFile() prevents not just writing but also reading by other processes.
45.291 +** A SHARED_LOCK is obtained by locking a single randomly-chosen
45.292 +** byte out of a specific range of bytes. The lock byte is obtained at
45.293 +** random so two separate readers can probably access the file at the
45.294 +** same time, unless they are unlucky and choose the same lock byte.
45.295 +** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
45.296 +** There can only be one writer. A RESERVED_LOCK is obtained by locking
45.297 +** a single byte of the file that is designated as the reserved lock byte.
45.298 +** A PENDING_LOCK is obtained by locking a designated byte different from
45.299 +** the RESERVED_LOCK byte.
45.300 +**
45.301 +** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
45.302 +** which means we can use reader/writer locks. When reader/writer locks
45.303 +** are used, the lock is placed on the same range of bytes that is used
45.304 +** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
45.305 +** will support two or more Win95 readers or two or more WinNT readers.
45.306 +** But a single Win95 reader will lock out all WinNT readers and a single
45.307 +** WinNT reader will lock out all other Win95 readers.
45.308 +**
45.309 +** The following #defines specify the range of bytes used for locking.
45.310 +** SHARED_SIZE is the number of bytes available in the pool from which
45.311 +** a random byte is selected for a shared lock. The pool of bytes for
45.312 +** shared locks begins at SHARED_FIRST.
45.313 +**
45.314 +** These #defines are available in sqlite_aux.h so that adaptors for
45.315 +** connecting SQLite to other operating systems can use the same byte
45.316 +** ranges for locking. In particular, the same locking strategy and
45.317 +** byte ranges are used for Unix. This leaves open the possiblity of having
45.318 +** clients on win95, winNT, and unix all talking to the same shared file
45.319 +** and all locking correctly. To do so would require that samba (or whatever
45.320 +** tool is being used for file sharing) implements locks correctly between
45.321 +** windows and unix. I'm guessing that isn't likely to happen, but by
45.322 +** using the same locking range we are at least open to the possibility.
45.323 +**
45.324 +** Locking in windows is manditory. For this reason, we cannot store
45.325 +** actual data in the bytes used for locking. The pager never allocates
45.326 +** the pages involved in locking therefore. SHARED_SIZE is selected so
45.327 +** that all locks will fit on a single page even at the minimum page size.
45.328 +** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
45.329 +** is set high so that we don't have to allocate an unused page except
45.330 +** for very large databases. But one should test the page skipping logic
45.331 +** by setting PENDING_BYTE low and running the entire regression suite.
45.332 +**
45.333 +** Changing the value of PENDING_BYTE results in a subtly incompatible
45.334 +** file format. Depending on how it is changed, you might not notice
45.335 +** the incompatibility right away, even running a full regression test.
45.336 +** The default location of PENDING_BYTE is the first byte past the
45.337 +** 1GB boundary.
45.338 +**
45.339 +*/
45.340 +#ifndef SQLITE_TEST
45.341 +#define PENDING_BYTE 0x40000000 /* First byte past the 1GB boundary */
45.342 +#else
45.343 +extern unsigned int sqlite3_pending_byte;
45.344 +#define PENDING_BYTE sqlite3_pending_byte
45.345 +#endif
45.346 +
45.347 +#define RESERVED_BYTE (PENDING_BYTE+1)
45.348 +#define SHARED_FIRST (PENDING_BYTE+2)
45.349 +#define SHARED_SIZE 510
45.350 +
45.351 +/*
45.352 +** Prototypes for operating system interface routines.
45.353 +*/
45.354 +int sqlite3OsClose(OsFile**);
45.355 +int sqlite3OsOpenDirectory(OsFile*, const char*);
45.356 +int sqlite3OsRead(OsFile*, void*, int amt);
45.357 +int sqlite3OsWrite(OsFile*, const void*, int amt);
45.358 +int sqlite3OsSeek(OsFile*, i64 offset);
45.359 +int sqlite3OsTruncate(OsFile*, i64 size);
45.360 +int sqlite3OsSync(OsFile*, int);
45.361 +void sqlite3OsSetFullSync(OsFile *id, int setting);
45.362 +int sqlite3OsFileSize(OsFile*, i64 *pSize);
45.363 +int sqlite3OsLock(OsFile*, int);
45.364 +int sqlite3OsUnlock(OsFile*, int);
45.365 +int sqlite3OsCheckReservedLock(OsFile *id);
45.366 +int sqlite3OsOpenReadWrite(const char*, OsFile**, int*);
45.367 +int sqlite3OsOpenExclusive(const char*, OsFile**, int);
45.368 +int sqlite3OsOpenReadOnly(const char*, OsFile**);
45.369 +int sqlite3OsDelete(const char*);
45.370 +int sqlite3OsFileExists(const char*);
45.371 +char *sqlite3OsFullPathname(const char*);
45.372 +int sqlite3OsIsDirWritable(char*);
45.373 +int sqlite3OsSyncDirectory(const char*);
45.374 +int sqlite3OsSectorSize(OsFile *id);
45.375 +int sqlite3OsTempFileName(char*);
45.376 +int sqlite3OsRandomSeed(char*);
45.377 +int sqlite3OsSleep(int ms);
45.378 +int sqlite3OsCurrentTime(double*);
45.379 +void sqlite3OsEnterMutex(void);
45.380 +void sqlite3OsLeaveMutex(void);
45.381 +int sqlite3OsInMutex(int);
45.382 +ThreadData *sqlite3OsThreadSpecificData(int);
45.383 +void *sqlite3OsMalloc(int);
45.384 +void *sqlite3OsRealloc(void *, int);
45.385 +void sqlite3OsFree(void *);
45.386 +int sqlite3OsAllocationSize(void *);
45.387 +void *sqlite3OsDlopen(const char*);
45.388 +void *sqlite3OsDlsym(void*, const char*);
45.389 +int sqlite3OsDlclose(void*);
45.390 +
45.391 +#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
45.392 + int sqlite3OsFileHandle(OsFile *id);
45.393 + int sqlite3OsLockState(OsFile *id);
45.394 +#endif
45.395 +
45.396 +/*
45.397 +** If the SQLITE_ENABLE_REDEF_IO macro is defined, then the OS-layer
45.398 +** interface routines are not called directly but are invoked using
45.399 +** pointers to functions. This allows the implementation of various
45.400 +** OS-layer interface routines to be modified at run-time. There are
45.401 +** obscure but legitimate reasons for wanting to do this. But for
45.402 +** most users, a direct call to the underlying interface is preferable
45.403 +** so the the redefinable I/O interface is turned off by default.
45.404 +*/
45.405 +#ifdef SQLITE_ENABLE_REDEF_IO
45.406 +
45.407 +/*
45.408 +** When redefinable I/O is enabled, a single global instance of the
45.409 +** following structure holds pointers to the routines that SQLite
45.410 +** uses to talk with the underlying operating system. Modify this
45.411 +** structure (before using any SQLite API!) to accomodate perculiar
45.412 +** operating system interfaces or behaviors.
45.413 +*/
45.414 +struct sqlite3OsVtbl {
45.415 + int (*xOpenReadWrite)(const char*, OsFile**, int*);
45.416 + int (*xOpenExclusive)(const char*, OsFile**, int);
45.417 + int (*xOpenReadOnly)(const char*, OsFile**);
45.418 +
45.419 + int (*xDelete)(const char*);
45.420 + int (*xFileExists)(const char*);
45.421 + char *(*xFullPathname)(const char*);
45.422 + int (*xIsDirWritable)(char*);
45.423 + int (*xSyncDirectory)(const char*);
45.424 + int (*xTempFileName)(char*);
45.425 +
45.426 + int (*xRandomSeed)(char*);
45.427 + int (*xSleep)(int ms);
45.428 + int (*xCurrentTime)(double*);
45.429 +
45.430 + void (*xEnterMutex)(void);
45.431 + void (*xLeaveMutex)(void);
45.432 + int (*xInMutex)(int);
45.433 + ThreadData *(*xThreadSpecificData)(int);
45.434 +
45.435 + void *(*xMalloc)(int);
45.436 + void *(*xRealloc)(void *, int);
45.437 + void (*xFree)(void *);
45.438 + int (*xAllocationSize)(void *);
45.439 +
45.440 + void *(*xDlopen)(const char*);
45.441 + void *(*xDlsym)(void*, const char*);
45.442 + int (*xDlclose)(void*);
45.443 +};
45.444 +
45.445 +/* Macro used to comment out routines that do not exists when there is
45.446 +** no disk I/O or extension loading
45.447 +*/
45.448 +#ifdef SQLITE_OMIT_DISKIO
45.449 +# define IF_DISKIO(X) 0
45.450 +#else
45.451 +# define IF_DISKIO(X) X
45.452 +#endif
45.453 +#ifdef SQLITE_OMIT_LOAD_EXTENSION
45.454 +# define IF_DLOPEN(X) 0
45.455 +#else
45.456 +# define IF_DLOPEN(X) X
45.457 +#endif
45.458 +
45.459 +
45.460 +#if defined(_SQLITE_OS_C_) || defined(SQLITE_AMALGAMATION)
45.461 + /*
45.462 + ** The os.c file implements the global virtual function table.
45.463 + ** We have to put this file here because the initializers
45.464 + ** (ex: sqlite3OsRandomSeed) are macros that are about to be
45.465 + ** redefined.
45.466 + */
45.467 + struct sqlite3OsVtbl sqlite3Os = {
45.468 + IF_DISKIO( sqlite3OsOpenReadWrite ),
45.469 + IF_DISKIO( sqlite3OsOpenExclusive ),
45.470 + IF_DISKIO( sqlite3OsOpenReadOnly ),
45.471 + IF_DISKIO( sqlite3OsDelete ),
45.472 + IF_DISKIO( sqlite3OsFileExists ),
45.473 + IF_DISKIO( sqlite3OsFullPathname ),
45.474 + IF_DISKIO( sqlite3OsIsDirWritable ),
45.475 + IF_DISKIO( sqlite3OsSyncDirectory ),
45.476 + IF_DISKIO( sqlite3OsTempFileName ),
45.477 + sqlite3OsRandomSeed,
45.478 + sqlite3OsSleep,
45.479 + sqlite3OsCurrentTime,
45.480 + sqlite3OsEnterMutex,
45.481 + sqlite3OsLeaveMutex,
45.482 + sqlite3OsInMutex,
45.483 + sqlite3OsThreadSpecificData,
45.484 + sqlite3OsMalloc,
45.485 + sqlite3OsRealloc,
45.486 + sqlite3OsFree,
45.487 + sqlite3OsAllocationSize,
45.488 + IF_DLOPEN( sqlite3OsDlopen ),
45.489 + IF_DLOPEN( sqlite3OsDlsym ),
45.490 + IF_DLOPEN( sqlite3OsDlclose ),
45.491 + };
45.492 +#else
45.493 + /*
45.494 + ** Files other than os.c just reference the global virtual function table.
45.495 + */
45.496 + extern struct sqlite3OsVtbl sqlite3Os;
45.497 +#endif /* _SQLITE_OS_C_ */
45.498 +
45.499 +
45.500 +/* This additional API routine is available with redefinable I/O */
45.501 +struct sqlite3OsVtbl *sqlite3_os_switch(void);
45.502 +
45.503 +
45.504 +/*
45.505 +** Redefine the OS interface to go through the virtual function table
45.506 +** rather than calling routines directly.
45.507 +*/
45.508 +#undef sqlite3OsOpenReadWrite
45.509 +#undef sqlite3OsOpenExclusive
45.510 +#undef sqlite3OsOpenReadOnly
45.511 +#undef sqlite3OsDelete
45.512 +#undef sqlite3OsFileExists
45.513 +#undef sqlite3OsFullPathname
45.514 +#undef sqlite3OsIsDirWritable
45.515 +#undef sqlite3OsSyncDirectory
45.516 +#undef sqlite3OsTempFileName
45.517 +#undef sqlite3OsRandomSeed
45.518 +#undef sqlite3OsSleep
45.519 +#undef sqlite3OsCurrentTime
45.520 +#undef sqlite3OsEnterMutex
45.521 +#undef sqlite3OsLeaveMutex
45.522 +#undef sqlite3OsInMutex
45.523 +#undef sqlite3OsThreadSpecificData
45.524 +#undef sqlite3OsMalloc
45.525 +#undef sqlite3OsRealloc
45.526 +#undef sqlite3OsFree
45.527 +#undef sqlite3OsAllocationSize
45.528 +#define sqlite3OsOpenReadWrite sqlite3Os.xOpenReadWrite
45.529 +#define sqlite3OsOpenExclusive sqlite3Os.xOpenExclusive
45.530 +#define sqlite3OsOpenReadOnly sqlite3Os.xOpenReadOnly
45.531 +#define sqlite3OsDelete sqlite3Os.xDelete
45.532 +#define sqlite3OsFileExists sqlite3Os.xFileExists
45.533 +#define sqlite3OsFullPathname sqlite3Os.xFullPathname
45.534 +#define sqlite3OsIsDirWritable sqlite3Os.xIsDirWritable
45.535 +#define sqlite3OsSyncDirectory sqlite3Os.xSyncDirectory
45.536 +#define sqlite3OsTempFileName sqlite3Os.xTempFileName
45.537 +#define sqlite3OsRandomSeed sqlite3Os.xRandomSeed
45.538 +#define sqlite3OsSleep sqlite3Os.xSleep
45.539 +#define sqlite3OsCurrentTime sqlite3Os.xCurrentTime
45.540 +#define sqlite3OsEnterMutex sqlite3Os.xEnterMutex
45.541 +#define sqlite3OsLeaveMutex sqlite3Os.xLeaveMutex
45.542 +#define sqlite3OsInMutex sqlite3Os.xInMutex
45.543 +#define sqlite3OsThreadSpecificData sqlite3Os.xThreadSpecificData
45.544 +#define sqlite3OsMalloc sqlite3Os.xMalloc
45.545 +#define sqlite3OsRealloc sqlite3Os.xRealloc
45.546 +#define sqlite3OsFree sqlite3Os.xFree
45.547 +#define sqlite3OsAllocationSize sqlite3Os.xAllocationSize
45.548 +
45.549 +#endif /* SQLITE_ENABLE_REDEF_IO */
45.550 +
45.551 +#endif /* _SQLITE_OS_H_ */
46.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
46.2 +++ b/extensions/sqlite/sqlite-source/os_common.h Sun Jul 29 01:15:31 2007 +0000
46.3 @@ -0,0 +1,198 @@
46.4 +/*
46.5 +** 2004 May 22
46.6 +**
46.7 +** The author disclaims copyright to this source code. In place of
46.8 +** a legal notice, here is a blessing:
46.9 +**
46.10 +** May you do good and not evil.
46.11 +** May you find forgiveness for yourself and forgive others.
46.12 +** May you share freely, never taking more than you give.
46.13 +**
46.14 +******************************************************************************
46.15 +**
46.16 +** This file contains macros and a little bit of code that is common to
46.17 +** all of the platform-specific files (os_*.c) and is #included into those
46.18 +** files.
46.19 +**
46.20 +** This file should be #included by the os_*.c files only. It is not a
46.21 +** general purpose header file.
46.22 +*/
46.23 +
46.24 +/*
46.25 +** At least two bugs have slipped in because we changed the MEMORY_DEBUG
46.26 +** macro to SQLITE_DEBUG and some older makefiles have not yet made the
46.27 +** switch. The following code should catch this problem at compile-time.
46.28 +*/
46.29 +#ifdef MEMORY_DEBUG
46.30 +# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
46.31 +#endif
46.32 +
46.33 +
46.34 +/*
46.35 + * When testing, this global variable stores the location of the
46.36 + * pending-byte in the database file.
46.37 + */
46.38 +#ifdef SQLITE_TEST
46.39 +unsigned int sqlite3_pending_byte = 0x40000000;
46.40 +#endif
46.41 +
46.42 +int sqlite3_os_trace = 0;
46.43 +#ifdef SQLITE_DEBUG
46.44 +#define OSTRACE1(X) if( sqlite3_os_trace ) sqlite3DebugPrintf(X)
46.45 +#define OSTRACE2(X,Y) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y)
46.46 +#define OSTRACE3(X,Y,Z) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z)
46.47 +#define OSTRACE4(X,Y,Z,A) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A)
46.48 +#define OSTRACE5(X,Y,Z,A,B) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A,B)
46.49 +#define OSTRACE6(X,Y,Z,A,B,C) \
46.50 + if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
46.51 +#define OSTRACE7(X,Y,Z,A,B,C,D) \
46.52 + if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
46.53 +#else
46.54 +#define OSTRACE1(X)
46.55 +#define OSTRACE2(X,Y)
46.56 +#define OSTRACE3(X,Y,Z)
46.57 +#define OSTRACE4(X,Y,Z,A)
46.58 +#define OSTRACE5(X,Y,Z,A,B)
46.59 +#define OSTRACE6(X,Y,Z,A,B,C)
46.60 +#define OSTRACE7(X,Y,Z,A,B,C,D)
46.61 +#endif
46.62 +
46.63 +/*
46.64 +** Macros for performance tracing. Normally turned off. Only works
46.65 +** on i486 hardware.
46.66 +*/
46.67 +#ifdef SQLITE_PERFORMANCE_TRACE
46.68 +__inline__ unsigned long long int hwtime(void){
46.69 + unsigned long long int x;
46.70 + __asm__("rdtsc\n\t"
46.71 + "mov %%edx, %%ecx\n\t"
46.72 + :"=A" (x));
46.73 + return x;
46.74 +}
46.75 +static unsigned long long int g_start;
46.76 +static unsigned int elapse;
46.77 +#define TIMER_START g_start=hwtime()
46.78 +#define TIMER_END elapse=hwtime()-g_start
46.79 +#define TIMER_ELAPSED elapse
46.80 +#else
46.81 +#define TIMER_START
46.82 +#define TIMER_END
46.83 +#define TIMER_ELAPSED 0
46.84 +#endif
46.85 +
46.86 +/*
46.87 +** If we compile with the SQLITE_TEST macro set, then the following block
46.88 +** of code will give us the ability to simulate a disk I/O error. This
46.89 +** is used for testing the I/O recovery logic.
46.90 +*/
46.91 +#ifdef SQLITE_TEST
46.92 +int sqlite3_io_error_hit = 0;
46.93 +int sqlite3_io_error_pending = 0;
46.94 +int sqlite3_io_error_persist = 0;
46.95 +int sqlite3_diskfull_pending = 0;
46.96 +int sqlite3_diskfull = 0;
46.97 +#define SimulateIOError(CODE) \
46.98 + if( sqlite3_io_error_pending || sqlite3_io_error_hit ) \
46.99 + if( sqlite3_io_error_pending-- == 1 \
46.100 + || (sqlite3_io_error_persist && sqlite3_io_error_hit) ) \
46.101 + { local_ioerr(); CODE; }
46.102 +static void local_ioerr(){
46.103 + IOTRACE(("IOERR\n"));
46.104 + sqlite3_io_error_hit = 1;
46.105 +}
46.106 +#define SimulateDiskfullError(CODE) \
46.107 + if( sqlite3_diskfull_pending ){ \
46.108 + if( sqlite3_diskfull_pending == 1 ){ \
46.109 + local_ioerr(); \
46.110 + sqlite3_diskfull = 1; \
46.111 + sqlite3_io_error_hit = 1; \
46.112 + CODE; \
46.113 + }else{ \
46.114 + sqlite3_diskfull_pending--; \
46.115 + } \
46.116 + }
46.117 +#else
46.118 +#define SimulateIOError(A)
46.119 +#define SimulateDiskfullError(A)
46.120 +#endif
46.121 +
46.122 +/*
46.123 +** When testing, keep a count of the number of open files.
46.124 +*/
46.125 +#ifdef SQLITE_TEST
46.126 +int sqlite3_open_file_count = 0;
46.127 +#define OpenCounter(X) sqlite3_open_file_count+=(X)
46.128 +#else
46.129 +#define OpenCounter(X)
46.130 +#endif
46.131 +
46.132 +/*
46.133 +** sqlite3GenericMalloc
46.134 +** sqlite3GenericRealloc
46.135 +** sqlite3GenericOsFree
46.136 +** sqlite3GenericAllocationSize
46.137 +**
46.138 +** Implementation of the os level dynamic memory allocation interface in terms
46.139 +** of the standard malloc(), realloc() and free() found in many operating
46.140 +** systems. No rocket science here.
46.141 +**
46.142 +** There are two versions of these four functions here. The version
46.143 +** implemented here is only used if memory-management or memory-debugging is
46.144 +** enabled. This version allocates an extra 8-bytes at the beginning of each
46.145 +** block and stores the size of the allocation there.
46.146 +**
46.147 +** If neither memory-management or debugging is enabled, the second
46.148 +** set of implementations is used instead.
46.149 +*/
46.150 +#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || defined (SQLITE_MEMDEBUG)
46.151 +void *sqlite3GenericMalloc(int n){
46.152 + char *p = (char *)malloc(n+8);
46.153 + assert(n>0);
46.154 + assert(sizeof(int)<=8);
46.155 + if( p ){
46.156 + *(int *)p = n;
46.157 + p += 8;
46.158 + }
46.159 + return (void *)p;
46.160 +}
46.161 +void *sqlite3GenericRealloc(void *p, int n){
46.162 + char *p2 = ((char *)p - 8);
46.163 + assert(n>0);
46.164 + p2 = (char*)realloc(p2, n+8);
46.165 + if( p2 ){
46.166 + *(int *)p2 = n;
46.167 + p2 += 8;
46.168 + }
46.169 + return (void *)p2;
46.170 +}
46.171 +void sqlite3GenericFree(void *p){
46.172 + assert(p);
46.173 + free((void *)((char *)p - 8));
46.174 +}
46.175 +int sqlite3GenericAllocationSize(void *p){
46.176 + return p ? *(int *)((char *)p - 8) : 0;
46.177 +}
46.178 +#else
46.179 +void *sqlite3GenericMalloc(int n){
46.180 + char *p = (char *)malloc(n);
46.181 + return (void *)p;
46.182 +}
46.183 +void *sqlite3GenericRealloc(void *p, int n){
46.184 + assert(n>0);
46.185 + p = realloc(p, n);
46.186 + return p;
46.187 +}
46.188 +void sqlite3GenericFree(void *p){
46.189 + assert(p);
46.190 + free(p);
46.191 +}
46.192 +/* Never actually used, but needed for the linker */
46.193 +int sqlite3GenericAllocationSize(void *p){ return 0; }
46.194 +#endif
46.195 +
46.196 +/*
46.197 +** The default size of a disk sector
46.198 +*/
46.199 +#ifndef PAGER_SECTOR_SIZE
46.200 +# define PAGER_SECTOR_SIZE 512
46.201 +#endif
47.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
47.2 +++ b/extensions/sqlite/sqlite-source/os_unix.c Sun Jul 29 01:15:31 2007 +0000
47.3 @@ -0,0 +1,2935 @@
47.4 +/*
47.5 +** 2004 May 22
47.6 +**
47.7 +** The author disclaims copyright to this source code. In place of
47.8 +** a legal notice, here is a blessing:
47.9 +**
47.10 +** May you do good and not evil.
47.11 +** May you find forgiveness for yourself and forgive others.
47.12 +** May you share freely, never taking more than you give.
47.13 +**
47.14 +******************************************************************************
47.15 +**
47.16 +** This file contains code that is specific to Unix systems.
47.17 +*/
47.18 +#include "sqliteInt.h"
47.19 +#include "os.h"
47.20 +#if OS_UNIX /* This file is used on unix only */
47.21 +
47.22 +/* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
47.23 +
47.24 +/*
47.25 +** These #defines should enable >2GB file support on Posix if the
47.26 +** underlying operating system supports it. If the OS lacks
47.27 +** large file support, these should be no-ops.
47.28 +**
47.29 +** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
47.30 +** on the compiler command line. This is necessary if you are compiling
47.31 +** on a recent machine (ex: RedHat 7.2) but you want your code to work
47.32 +** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
47.33 +** without this option, LFS is enable. But LFS does not exist in the kernel
47.34 +** in RedHat 6.0, so the code won't work. Hence, for maximum binary
47.35 +** portability you should omit LFS.
47.36 +*/
47.37 +#ifndef SQLITE_DISABLE_LFS
47.38 +# define _LARGE_FILE 1
47.39 +# ifndef _FILE_OFFSET_BITS
47.40 +# define _FILE_OFFSET_BITS 64
47.41 +# endif
47.42 +# define _LARGEFILE_SOURCE 1
47.43 +#endif
47.44 +
47.45 +/*
47.46 +** standard include files.
47.47 +*/
47.48 +#include <sys/types.h>
47.49 +#include <sys/stat.h>
47.50 +#include <fcntl.h>
47.51 +#include <unistd.h>
47.52 +#include <time.h>
47.53 +#include <sys/time.h>
47.54 +#include <errno.h>
47.55 +#ifdef SQLITE_ENABLE_LOCKING_STYLE
47.56 +#include <sys/ioctl.h>
47.57 +#include <sys/param.h>
47.58 +#include <sys/mount.h>
47.59 +#endif /* SQLITE_ENABLE_LOCKING_STYLE */
47.60 +
47.61 +/*
47.62 +** If we are to be thread-safe, include the pthreads header and define
47.63 +** the SQLITE_UNIX_THREADS macro.
47.64 +*/
47.65 +#ifndef THREADSAFE
47.66 +# define THREADSAFE 1
47.67 +#endif
47.68 +#if THREADSAFE
47.69 +# include <pthread.h>
47.70 +# define SQLITE_UNIX_THREADS 1
47.71 +#endif
47.72 +
47.73 +/*
47.74 +** Default permissions when creating a new file
47.75 +*/
47.76 +#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
47.77 +# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
47.78 +#endif
47.79 +
47.80 +
47.81 +
47.82 +/*
47.83 +** The unixFile structure is subclass of OsFile specific for the unix
47.84 +** protability layer.
47.85 +*/
47.86 +typedef struct unixFile unixFile;
47.87 +struct unixFile {
47.88 + IoMethod const *pMethod; /* Always the first entry */
47.89 + struct openCnt *pOpen; /* Info about all open fd's on this inode */
47.90 + struct lockInfo *pLock; /* Info about locks on this inode */
47.91 +#ifdef SQLITE_ENABLE_LOCKING_STYLE
47.92 + void *lockingContext; /* Locking style specific state */
47.93 +#endif /* SQLITE_ENABLE_LOCKING_STYLE */
47.94 + int h; /* The file descriptor */
47.95 + unsigned char locktype; /* The type of lock held on this fd */
47.96 + unsigned char isOpen; /* True if needs to be closed */
47.97 + unsigned char fullSync; /* Use F_FULLSYNC if available */
47.98 + int dirfd; /* File descriptor for the directory */
47.99 + i64 offset; /* Seek offset */
47.100 +#ifdef SQLITE_UNIX_THREADS
47.101 + pthread_t tid; /* The thread that "owns" this OsFile */
47.102 +#endif
47.103 +};
47.104 +
47.105 +/*
47.106 +** Provide the ability to override some OS-layer functions during
47.107 +** testing. This is used to simulate OS crashes to verify that
47.108 +** commits are atomic even in the event of an OS crash.
47.109 +*/
47.110 +#ifdef SQLITE_CRASH_TEST
47.111 + extern int sqlite3CrashTestEnable;
47.112 + extern int sqlite3CrashOpenReadWrite(const char*, OsFile**, int*);
47.113 + extern int sqlite3CrashOpenExclusive(const char*, OsFile**, int);
47.114 + extern int sqlite3CrashOpenReadOnly(const char*, OsFile**, int);
47.115 +# define CRASH_TEST_OVERRIDE(X,A,B,C) \
47.116 + if(sqlite3CrashTestEnable){ return X(A,B,C); }
47.117 +#else
47.118 +# define CRASH_TEST_OVERRIDE(X,A,B,C) /* no-op */
47.119 +#endif
47.120 +
47.121 +
47.122 +/*
47.123 +** Include code that is common to all os_*.c files
47.124 +*/
47.125 +#include "os_common.h"
47.126 +
47.127 +/*
47.128 +** Do not include any of the File I/O interface procedures if the
47.129 +** SQLITE_OMIT_DISKIO macro is defined (indicating that the database
47.130 +** will be in-memory only)
47.131 +*/
47.132 +#ifndef SQLITE_OMIT_DISKIO
47.133 +
47.134 +
47.135 +/*
47.136 +** Define various macros that are missing from some systems.
47.137 +*/
47.138 +#ifndef O_LARGEFILE
47.139 +# define O_LARGEFILE 0
47.140 +#endif
47.141 +#ifdef SQLITE_DISABLE_LFS
47.142 +# undef O_LARGEFILE
47.143 +# define O_LARGEFILE 0
47.144 +#endif
47.145 +#ifndef O_NOFOLLOW
47.146 +# define O_NOFOLLOW 0
47.147 +#endif
47.148 +#ifndef O_BINARY
47.149 +# define O_BINARY 0
47.150 +#endif
47.151 +
47.152 +/*
47.153 +** The DJGPP compiler environment looks mostly like Unix, but it
47.154 +** lacks the fcntl() system call. So redefine fcntl() to be something
47.155 +** that always succeeds. This means that locking does not occur under
47.156 +** DJGPP. But it's DOS - what did you expect?
47.157 +*/
47.158 +#ifdef __DJGPP__
47.159 +# define fcntl(A,B,C) 0
47.160 +#endif
47.161 +
47.162 +/*
47.163 +** The threadid macro resolves to the thread-id or to 0. Used for
47.164 +** testing and debugging only.
47.165 +*/
47.166 +#ifdef SQLITE_UNIX_THREADS
47.167 +#define threadid pthread_self()
47.168 +#else
47.169 +#define threadid 0
47.170 +#endif
47.171 +
47.172 +/*
47.173 +** Set or check the OsFile.tid field. This field is set when an OsFile
47.174 +** is first opened. All subsequent uses of the OsFile verify that the
47.175 +** same thread is operating on the OsFile. Some operating systems do
47.176 +** not allow locks to be overridden by other threads and that restriction
47.177 +** means that sqlite3* database handles cannot be moved from one thread
47.178 +** to another. This logic makes sure a user does not try to do that
47.179 +** by mistake.
47.180 +**
47.181 +** Version 3.3.1 (2006-01-15): OsFiles can be moved from one thread to
47.182 +** another as long as we are running on a system that supports threads
47.183 +** overriding each others locks (which now the most common behavior)
47.184 +** or if no locks are held. But the OsFile.pLock field needs to be
47.185 +** recomputed because its key includes the thread-id. See the
47.186 +** transferOwnership() function below for additional information
47.187 +*/
47.188 +#if defined(SQLITE_UNIX_THREADS)
47.189 +# define SET_THREADID(X) (X)->tid = pthread_self()
47.190 +# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
47.191 + !pthread_equal((X)->tid, pthread_self()))
47.192 +#else
47.193 +# define SET_THREADID(X)
47.194 +# define CHECK_THREADID(X) 0
47.195 +#endif
47.196 +
47.197 +/*
47.198 +** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
47.199 +** section 6.5.2.2 lines 483 through 490 specify that when a process
47.200 +** sets or clears a lock, that operation overrides any prior locks set
47.201 +** by the same process. It does not explicitly say so, but this implies
47.202 +** that it overrides locks set by the same process using a different
47.203 +** file descriptor. Consider this test case:
47.204 +**
47.205 +** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
47.206 +** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
47.207 +**
47.208 +** Suppose ./file1 and ./file2 are really the same file (because
47.209 +** one is a hard or symbolic link to the other) then if you set
47.210 +** an exclusive lock on fd1, then try to get an exclusive lock
47.211 +** on fd2, it works. I would have expected the second lock to
47.212 +** fail since there was already a lock on the file due to fd1.
47.213 +** But not so. Since both locks came from the same process, the
47.214 +** second overrides the first, even though they were on different
47.215 +** file descriptors opened on different file names.
47.216 +**
47.217 +** Bummer. If you ask me, this is broken. Badly broken. It means
47.218 +** that we cannot use POSIX locks to synchronize file access among
47.219 +** competing threads of the same process. POSIX locks will work fine
47.220 +** to synchronize access for threads in separate processes, but not
47.221 +** threads within the same process.
47.222 +**
47.223 +** To work around the problem, SQLite has to manage file locks internally
47.224 +** on its own. Whenever a new database is opened, we have to find the
47.225 +** specific inode of the database file (the inode is determined by the
47.226 +** st_dev and st_ino fields of the stat structure that fstat() fills in)
47.227 +** and check for locks already existing on that inode. When locks are
47.228 +** created or removed, we have to look at our own internal record of the
47.229 +** locks to see if another thread has previously set a lock on that same
47.230 +** inode.
47.231 +**
47.232 +** The OsFile structure for POSIX is no longer just an integer file
47.233 +** descriptor. It is now a structure that holds the integer file
47.234 +** descriptor and a pointer to a structure that describes the internal
47.235 +** locks on the corresponding inode. There is one locking structure
47.236 +** per inode, so if the same inode is opened twice, both OsFile structures
47.237 +** point to the same locking structure. The locking structure keeps
47.238 +** a reference count (so we will know when to delete it) and a "cnt"
47.239 +** field that tells us its internal lock status. cnt==0 means the
47.240 +** file is unlocked. cnt==-1 means the file has an exclusive lock.
47.241 +** cnt>0 means there are cnt shared locks on the file.
47.242 +**
47.243 +** Any attempt to lock or unlock a file first checks the locking
47.244 +** structure. The fcntl() system call is only invoked to set a
47.245 +** POSIX lock if the internal lock structure transitions between
47.246 +** a locked and an unlocked state.
47.247 +**
47.248 +** 2004-Jan-11:
47.249 +** More recent discoveries about POSIX advisory locks. (The more
47.250 +** I discover, the more I realize the a POSIX advisory locks are
47.251 +** an abomination.)
47.252 +**
47.253 +** If you close a file descriptor that points to a file that has locks,
47.254 +** all locks on that file that are owned by the current process are
47.255 +** released. To work around this problem, each OsFile structure contains
47.256 +** a pointer to an openCnt structure. There is one openCnt structure
47.257 +** per open inode, which means that multiple OsFiles can point to a single
47.258 +** openCnt. When an attempt is made to close an OsFile, if there are
47.259 +** other OsFiles open on the same inode that are holding locks, the call
47.260 +** to close() the file descriptor is deferred until all of the locks clear.
47.261 +** The openCnt structure keeps a list of file descriptors that need to
47.262 +** be closed and that list is walked (and cleared) when the last lock
47.263 +** clears.
47.264 +**
47.265 +** First, under Linux threads, because each thread has a separate
47.266 +** process ID, lock operations in one thread do not override locks
47.267 +** to the same file in other threads. Linux threads behave like
47.268 +** separate processes in this respect. But, if you close a file
47.269 +** descriptor in linux threads, all locks are cleared, even locks
47.270 +** on other threads and even though the other threads have different
47.271 +** process IDs. Linux threads is inconsistent in this respect.
47.272 +** (I'm beginning to think that linux threads is an abomination too.)
47.273 +** The consequence of this all is that the hash table for the lockInfo
47.274 +** structure has to include the process id as part of its key because
47.275 +** locks in different threads are treated as distinct. But the
47.276 +** openCnt structure should not include the process id in its
47.277 +** key because close() clears lock on all threads, not just the current
47.278 +** thread. Were it not for this goofiness in linux threads, we could
47.279 +** combine the lockInfo and openCnt structures into a single structure.
47.280 +**
47.281 +** 2004-Jun-28:
47.282 +** On some versions of linux, threads can override each others locks.
47.283 +** On others not. Sometimes you can change the behavior on the same
47.284 +** system by setting the LD_ASSUME_KERNEL environment variable. The
47.285 +** POSIX standard is silent as to which behavior is correct, as far
47.286 +** as I can tell, so other versions of unix might show the same
47.287 +** inconsistency. There is no little doubt in my mind that posix
47.288 +** advisory locks and linux threads are profoundly broken.
47.289 +**
47.290 +** To work around the inconsistencies, we have to test at runtime
47.291 +** whether or not threads can override each others locks. This test
47.292 +** is run once, the first time any lock is attempted. A static
47.293 +** variable is set to record the results of this test for future
47.294 +** use.
47.295 +*/
47.296 +
47.297 +/*
47.298 +** An instance of the following structure serves as the key used
47.299 +** to locate a particular lockInfo structure given its inode.
47.300 +**
47.301 +** If threads cannot override each others locks, then we set the
47.302 +** lockKey.tid field to the thread ID. If threads can override
47.303 +** each others locks then tid is always set to zero. tid is omitted
47.304 +** if we compile without threading support.
47.305 +*/
47.306 +struct lockKey {
47.307 + dev_t dev; /* Device number */
47.308 + ino_t ino; /* Inode number */
47.309 +#ifdef SQLITE_UNIX_THREADS
47.310 + pthread_t tid; /* Thread ID or zero if threads can override each other */
47.311 +#endif
47.312 +};
47.313 +
47.314 +/*
47.315 +** An instance of the following structure is allocated for each open
47.316 +** inode on each thread with a different process ID. (Threads have
47.317 +** different process IDs on linux, but not on most other unixes.)
47.318 +**
47.319 +** A single inode can have multiple file descriptors, so each OsFile
47.320 +** structure contains a pointer to an instance of this object and this
47.321 +** object keeps a count of the number of OsFiles pointing to it.
47.322 +*/
47.323 +struct lockInfo {
47.324 + struct lockKey key; /* The lookup key */
47.325 + int cnt; /* Number of SHARED locks held */
47.326 + int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
47.327 + int nRef; /* Number of pointers to this structure */
47.328 +};
47.329 +
47.330 +/*
47.331 +** An instance of the following structure serves as the key used
47.332 +** to locate a particular openCnt structure given its inode. This
47.333 +** is the same as the lockKey except that the thread ID is omitted.
47.334 +*/
47.335 +struct openKey {
47.336 + dev_t dev; /* Device number */
47.337 + ino_t ino; /* Inode number */
47.338 +};
47.339 +
47.340 +/*
47.341 +** An instance of the following structure is allocated for each open
47.342 +** inode. This structure keeps track of the number of locks on that
47.343 +** inode. If a close is attempted against an inode that is holding
47.344 +** locks, the close is deferred until all locks clear by adding the
47.345 +** file descriptor to be closed to the pending list.
47.346 +*/
47.347 +struct openCnt {
47.348 + struct openKey key; /* The lookup key */
47.349 + int nRef; /* Number of pointers to this structure */
47.350 + int nLock; /* Number of outstanding locks */
47.351 + int nPending; /* Number of pending close() operations */
47.352 + int *aPending; /* Malloced space holding fd's awaiting a close() */
47.353 +};
47.354 +
47.355 +/*
47.356 +** These hash tables map inodes and file descriptors (really, lockKey and
47.357 +** openKey structures) into lockInfo and openCnt structures. Access to
47.358 +** these hash tables must be protected by a mutex.
47.359 +*/
47.360 +static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0,
47.361 + sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};
47.362 +static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0,
47.363 + sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};
47.364 +
47.365 +#ifdef SQLITE_ENABLE_LOCKING_STYLE
47.366 +/*
47.367 +** The locking styles are associated with the different file locking
47.368 +** capabilities supported by different file systems.
47.369 +**
47.370 +** POSIX locking style fully supports shared and exclusive byte-range locks
47.371 +** ADP locking only supports exclusive byte-range locks
47.372 +** FLOCK only supports a single file-global exclusive lock
47.373 +** DOTLOCK isn't a true locking style, it refers to the use of a special
47.374 +** file named the same as the database file with a '.lock' extension, this
47.375 +** can be used on file systems that do not offer any reliable file locking
47.376 +** NO locking means that no locking will be attempted, this is only used for
47.377 +** read-only file systems currently
47.378 +** UNSUPPORTED means that no locking will be attempted, this is only used for
47.379 +** file systems that are known to be unsupported
47.380 +*/
47.381 +typedef enum {
47.382 + posixLockingStyle = 0, /* standard posix-advisory locks */
47.383 + afpLockingStyle, /* use afp locks */
47.384 + flockLockingStyle, /* use flock() */
47.385 + dotlockLockingStyle, /* use <file>.lock files */
47.386 + noLockingStyle, /* useful for read-only file system */
47.387 + unsupportedLockingStyle /* indicates unsupported file system */
47.388 +} sqlite3LockingStyle;
47.389 +#endif /* SQLITE_ENABLE_LOCKING_STYLE */
47.390 +
47.391 +#ifdef SQLITE_UNIX_THREADS
47.392 +/*
47.393 +** This variable records whether or not threads can override each others
47.394 +** locks.
47.395 +**
47.396 +** 0: No. Threads cannot override each others locks.
47.397 +** 1: Yes. Threads can override each others locks.
47.398 +** -1: We don't know yet.
47.399 +**
47.400 +** On some systems, we know at compile-time if threads can override each
47.401 +** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
47.402 +** will be set appropriately. On other systems, we have to check at
47.403 +** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
47.404 +** undefined.
47.405 +**
47.406 +** This variable normally has file scope only. But during testing, we make
47.407 +** it a global so that the test code can change its value in order to verify
47.408 +** that the right stuff happens in either case.
47.409 +*/
47.410 +#ifndef SQLITE_THREAD_OVERRIDE_LOCK
47.411 +# define SQLITE_THREAD_OVERRIDE_LOCK -1
47.412 +#endif
47.413 +#ifdef SQLITE_TEST
47.414 +int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
47.415 +#else
47.416 +static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
47.417 +#endif
47.418 +
47.419 +/*
47.420 +** This structure holds information passed into individual test
47.421 +** threads by the testThreadLockingBehavior() routine.
47.422 +*/
47.423 +struct threadTestData {
47.424 + int fd; /* File to be locked */
47.425 + struct flock lock; /* The locking operation */
47.426 + int result; /* Result of the locking operation */
47.427 +};
47.428 +
47.429 +#ifdef SQLITE_LOCK_TRACE
47.430 +/*
47.431 +** Print out information about all locking operations.
47.432 +**
47.433 +** This routine is used for troubleshooting locks on multithreaded
47.434 +** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
47.435 +** command-line option on the compiler. This code is normally
47.436 +** turned off.
47.437 +*/
47.438 +static int lockTrace(int fd, int op, struct flock *p){
47.439 + char *zOpName, *zType;
47.440 + int s;
47.441 + int savedErrno;
47.442 + if( op==F_GETLK ){
47.443 + zOpName = "GETLK";
47.444 + }else if( op==F_SETLK ){
47.445 + zOpName = "SETLK";
47.446 + }else{
47.447 + s = fcntl(fd, op, p);
47.448 + sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
47.449 + return s;
47.450 + }
47.451 + if( p->l_type==F_RDLCK ){
47.452 + zType = "RDLCK";
47.453 + }else if( p->l_type==F_WRLCK ){
47.454 + zType = "WRLCK";
47.455 + }else if( p->l_type==F_UNLCK ){
47.456 + zType = "UNLCK";
47.457 + }else{
47.458 + assert( 0 );
47.459 + }
47.460 + assert( p->l_whence==SEEK_SET );
47.461 + s = fcntl(fd, op, p);
47.462 + savedErrno = errno;
47.463 + sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
47.464 + threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
47.465 + (int)p->l_pid, s);
47.466 + if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
47.467 + struct flock l2;
47.468 + l2 = *p;
47.469 + fcntl(fd, F_GETLK, &l2);
47.470 + if( l2.l_type==F_RDLCK ){
47.471 + zType = "RDLCK";
47.472 + }else if( l2.l_type==F_WRLCK ){
47.473 + zType = "WRLCK";
47.474 + }else if( l2.l_type==F_UNLCK ){
47.475 + zType = "UNLCK";
47.476 + }else{
47.477 + assert( 0 );
47.478 + }
47.479 + sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
47.480 + zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
47.481 + }
47.482 + errno = savedErrno;
47.483 + return s;
47.484 +}
47.485 +#define fcntl lockTrace
47.486 +#endif /* SQLITE_LOCK_TRACE */
47.487 +
47.488 +/*
47.489 +** The testThreadLockingBehavior() routine launches two separate
47.490 +** threads on this routine. This routine attempts to lock a file
47.491 +** descriptor then returns. The success or failure of that attempt
47.492 +** allows the testThreadLockingBehavior() procedure to determine
47.493 +** whether or not threads can override each others locks.
47.494 +*/
47.495 +static void *threadLockingTest(void *pArg){
47.496 + struct threadTestData *pData = (struct threadTestData*)pArg;
47.497 + pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
47.498 + return pArg;
47.499 +}
47.500 +
47.501 +/*
47.502 +** This procedure attempts to determine whether or not threads
47.503 +** can override each others locks then sets the
47.504 +** threadsOverrideEachOthersLocks variable appropriately.
47.505 +*/
47.506 +static void testThreadLockingBehavior(int fd_orig){
47.507 + int fd;
47.508 + struct threadTestData d[2];
47.509 + pthread_t t[2];
47.510 +
47.511 + fd = dup(fd_orig);
47.512 + if( fd<0 ) return;
47.513 + memset(d, 0, sizeof(d));
47.514 + d[0].fd = fd;
47.515 + d[0].lock.l_type = F_RDLCK;
47.516 + d[0].lock.l_len = 1;
47.517 + d[0].lock.l_start = 0;
47.518 + d[0].lock.l_whence = SEEK_SET;
47.519 + d[1] = d[0];
47.520 + d[1].lock.l_type = F_WRLCK;
47.521 + pthread_create(&t[0], 0, threadLockingTest, &d[0]);
47.522 + pthread_create(&t[1], 0, threadLockingTest, &d[1]);
47.523 + pthread_join(t[0], 0);
47.524 + pthread_join(t[1], 0);
47.525 + close(fd);
47.526 + threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
47.527 +}
47.528 +#endif /* SQLITE_UNIX_THREADS */
47.529 +
47.530 +/*
47.531 +** Release a lockInfo structure previously allocated by findLockInfo().
47.532 +*/
47.533 +static void releaseLockInfo(struct lockInfo *pLock){
47.534 + assert( sqlite3OsInMutex(1) );
47.535 + if (pLock == NULL)
47.536 + return;
47.537 + pLock->nRef--;
47.538 + if( pLock->nRef==0 ){
47.539 + sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
47.540 + sqlite3ThreadSafeFree(pLock);
47.541 + }
47.542 +}
47.543 +
47.544 +/*
47.545 +** Release a openCnt structure previously allocated by findLockInfo().
47.546 +*/
47.547 +static void releaseOpenCnt(struct openCnt *pOpen){
47.548 + assert( sqlite3OsInMutex(1) );
47.549 + if (pOpen == NULL)
47.550 + return;
47.551 + pOpen->nRef--;
47.552 + if( pOpen->nRef==0 ){
47.553 + sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
47.554 + free(pOpen->aPending);
47.555 + sqlite3ThreadSafeFree(pOpen);
47.556 + }
47.557 +}
47.558 +
47.559 +#ifdef SQLITE_ENABLE_LOCKING_STYLE
47.560 +/*
47.561 +** Tests a byte-range locking query to see if byte range locks are
47.562 +** supported, if not we fall back to dotlockLockingStyle.
47.563 +*/
47.564 +static sqlite3LockingStyle sqlite3TestLockingStyle(const char *filePath,
47.565 + int fd) {
47.566 + /* test byte-range lock using fcntl */
47.567 + struct flock lockInfo;
47.568 +
47.569 + lockInfo.l_len = 1;
47.570 + lockInfo.l_start = 0;
47.571 + lockInfo.l_whence = SEEK_SET;
47.572 + lockInfo.l_type = F_RDLCK;
47.573 +
47.574 + if (fcntl(fd, F_GETLK, &lockInfo) != -1) {
47.575 + return posixLockingStyle;
47.576 + }
47.577 +
47.578 + /* testing for flock can give false positives. So if if the above test
47.579 + ** fails, then we fall back to using dot-lock style locking.
47.580 + */
47.581 + return dotlockLockingStyle;
47.582 +}
47.583 +
47.584 +/*
47.585 +** Examines the f_fstypename entry in the statfs structure as returned by
47.586 +** stat() for the file system hosting the database file, assigns the
47.587 +** appropriate locking style based on it's value. These values and
47.588 +** assignments are based on Darwin/OSX behavior and have not been tested on
47.589 +** other systems.
47.590 +*/
47.591 +static sqlite3LockingStyle sqlite3DetectLockingStyle(const char *filePath,
47.592 + int fd) {
47.593 +
47.594 +#ifdef SQLITE_FIXED_LOCKING_STYLE
47.595 + return (sqlite3LockingStyle)SQLITE_FIXED_LOCKING_STYLE;
47.596 +#else
47.597 + struct statfs fsInfo;
47.598 +
47.599 + if (statfs(filePath, &fsInfo) == -1)
47.600 + return sqlite3TestLockingStyle(filePath, fd);
47.601 +
47.602 + if (fsInfo.f_flags & MNT_RDONLY)
47.603 + return noLockingStyle;
47.604 +
47.605 + if( (!strcmp(fsInfo.f_fstypename, "hfs")) ||
47.606 + (!strcmp(fsInfo.f_fstypename, "ufs")) )
47.607 + return posixLockingStyle;
47.608 +
47.609 + if(!strcmp(fsInfo.f_fstypename, "afpfs"))
47.610 + return afpLockingStyle;
47.611 +
47.612 + if(!strcmp(fsInfo.f_fstypename, "nfs"))
47.613 + return sqlite3TestLockingStyle(filePath, fd);
47.614 +
47.615 + if(!strcmp(fsInfo.f_fstypename, "smbfs"))
47.616 + return flockLockingStyle;
47.617 +
47.618 + if(!strcmp(fsInfo.f_fstypename, "msdos"))
47.619 + return dotlockLockingStyle;
47.620 +
47.621 + if(!strcmp(fsInfo.f_fstypename, "webdav"))
47.622 + return unsupportedLockingStyle;
47.623 +
47.624 + return sqlite3TestLockingStyle(filePath, fd);
47.625 +#endif /* SQLITE_FIXED_LOCKING_STYLE */
47.626 +}
47.627 +
47.628 +#endif /* SQLITE_ENABLE_LOCKING_STYLE */
47.629 +
47.630 +/*
47.631 +** Given a file descriptor, locate lockInfo and openCnt structures that
47.632 +** describes that file descriptor. Create new ones if necessary. The
47.633 +** return values might be uninitialized if an error occurs.
47.634 +**
47.635 +** Return the number of errors.
47.636 +*/
47.637 +static int findLockInfo(
47.638 + int fd, /* The file descriptor used in the key */
47.639 + struct lockInfo **ppLock, /* Return the lockInfo structure here */
47.640 + struct openCnt **ppOpen /* Return the openCnt structure here */
47.641 +){
47.642 + int rc;
47.643 + struct lockKey key1;
47.644 + struct openKey key2;
47.645 + struct stat statbuf;
47.646 + struct lockInfo *pLock;
47.647 + struct openCnt *pOpen;
47.648 + rc = fstat(fd, &statbuf);
47.649 + if( rc!=0 ) return 1;
47.650 +
47.651 + assert( sqlite3OsInMutex(1) );
47.652 + memset(&key1, 0, sizeof(key1));
47.653 + key1.dev = statbuf.st_dev;
47.654 + key1.ino = statbuf.st_ino;
47.655 +#ifdef SQLITE_UNIX_THREADS
47.656 + if( threadsOverrideEachOthersLocks<0 ){
47.657 + testThreadLockingBehavior(fd);
47.658 + }
47.659 + key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
47.660 +#endif
47.661 + memset(&key2, 0, sizeof(key2));
47.662 + key2.dev = statbuf.st_dev;
47.663 + key2.ino = statbuf.st_ino;
47.664 + pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
47.665 + if( pLock==0 ){
47.666 + struct lockInfo *pOld;
47.667 + pLock = sqlite3ThreadSafeMalloc( sizeof(*pLock) );
47.668 + if( pLock==0 ){
47.669 + rc = 1;
47.670 + goto exit_findlockinfo;
47.671 + }
47.672 + pLock->key = key1;
47.673 + pLock->nRef = 1;
47.674 + pLock->cnt = 0;
47.675 + pLock->locktype = 0;
47.676 + pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
47.677 + if( pOld!=0 ){
47.678 + assert( pOld==pLock );
47.679 + sqlite3ThreadSafeFree(pLock);
47.680 + rc = 1;
47.681 + goto exit_findlockinfo;
47.682 + }
47.683 + }else{
47.684 + pLock->nRef++;
47.685 + }
47.686 + *ppLock = pLock;
47.687 + if( ppOpen!=0 ){
47.688 + pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
47.689 + if( pOpen==0 ){
47.690 + struct openCnt *pOld;
47.691 + pOpen = sqlite3ThreadSafeMalloc( sizeof(*pOpen) );
47.692 + if( pOpen==0 ){
47.693 + releaseLockInfo(pLock);
47.694 + rc = 1;
47.695 + goto exit_findlockinfo;
47.696 + }
47.697 + pOpen->key = key2;
47.698 + pOpen->nRef = 1;
47.699 + pOpen->nLock = 0;
47.700 + pOpen->nPending = 0;
47.701 + pOpen->aPending = 0;
47.702 + pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
47.703 + if( pOld!=0 ){
47.704 + assert( pOld==pOpen );
47.705 + sqlite3ThreadSafeFree(pOpen);
47.706 + releaseLockInfo(pLock);
47.707 + rc = 1;
47.708 + goto exit_findlockinfo;
47.709 + }
47.710 + }else{
47.711 + pOpen->nRef++;
47.712 + }
47.713 + *ppOpen = pOpen;
47.714 + }
47.715 +
47.716 +exit_findlockinfo:
47.717 + return rc;
47.718 +}
47.719 +
47.720 +#ifdef SQLITE_DEBUG
47.721 +/*
47.722 +** Helper function for printing out trace information from debugging
47.723 +** binaries. This returns the string represetation of the supplied
47.724 +** integer lock-type.
47.725 +*/
47.726 +static const char *locktypeName(int locktype){
47.727 + switch( locktype ){
47.728 + case NO_LOCK: return "NONE";
47.729 + case SHARED_LOCK: return "SHARED";
47.730 + case RESERVED_LOCK: return "RESERVED";
47.731 + case PENDING_LOCK: return "PENDING";
47.732 + case EXCLUSIVE_LOCK: return "EXCLUSIVE";
47.733 + }
47.734 + return "ERROR";
47.735 +}
47.736 +#endif
47.737 +
47.738 +/*
47.739 +** If we are currently in a different thread than the thread that the
47.740 +** unixFile argument belongs to, then transfer ownership of the unixFile
47.741 +** over to the current thread.
47.742 +**
47.743 +** A unixFile is only owned by a thread on systems where one thread is
47.744 +** unable to override locks created by a different thread. RedHat9 is
47.745 +** an example of such a system.
47.746 +**
47.747 +** Ownership transfer is only allowed if the unixFile is currently unlocked.
47.748 +** If the unixFile is locked and an ownership is wrong, then return
47.749 +** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
47.750 +*/
47.751 +#ifdef SQLITE_UNIX_THREADS
47.752 +static int transferOwnership(unixFile *pFile){
47.753 + int rc;
47.754 + pthread_t hSelf;
47.755 + if( threadsOverrideEachOthersLocks ){
47.756 + /* Ownership transfers not needed on this system */
47.757 + return SQLITE_OK;
47.758 + }
47.759 + hSelf = pthread_self();
47.760 + if( pthread_equal(pFile->tid, hSelf) ){
47.761 + /* We are still in the same thread */
47.762 + OSTRACE1("No-transfer, same thread\n");
47.763 + return SQLITE_OK;
47.764 + }
47.765 + if( pFile->locktype!=NO_LOCK ){
47.766 + /* We cannot change ownership while we are holding a lock! */
47.767 + return SQLITE_MISUSE;
47.768 + }
47.769 + OSTRACE4("Transfer ownership of %d from %d to %d\n",
47.770 + pFile->h, pFile->tid, hSelf);
47.771 + pFile->tid = hSelf;
47.772 + if (pFile->pLock != NULL) {
47.773 + releaseLockInfo(pFile->pLock);
47.774 + rc = findLockInfo(pFile->h, &pFile->pLock, 0);
47.775 + OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
47.776 + locktypeName(pFile->locktype),
47.777 + locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
47.778 + return rc;
47.779 + } else {
47.780 + return SQLITE_OK;
47.781 + }
47.782 +}
47.783 +#else
47.784 + /* On single-threaded builds, ownership transfer is a no-op */
47.785 +# define transferOwnership(X) SQLITE_OK
47.786 +#endif
47.787 +
47.788 +/*
47.789 +** Delete the named file
47.790 +*/
47.791 +int sqlite3UnixDelete(const char *zFilename){
47.792 + SimulateIOError(return SQLITE_IOERR_DELETE);
47.793 + unlink(zFilename);
47.794 + return SQLITE_OK;
47.795 +}
47.796 +
47.797 +/*
47.798 +** Return TRUE if the named file exists.
47.799 +*/
47.800 +int sqlite3UnixFileExists(const char *zFilename){
47.801 + return access(zFilename, 0)==0;
47.802 +}
47.803 +
47.804 +/* Forward declaration */
47.805 +static int allocateUnixFile(
47.806 + int h, /* File descriptor of the open file */
47.807 + OsFile **pId, /* Write the real file descriptor here */
47.808 + const char *zFilename, /* Name of the file being opened */
47.809 + int delFlag /* If true, make sure the file deletes on close */
47.810 +);
47.811 +
47.812 +/*
47.813 +** Attempt to open a file for both reading and writing. If that
47.814 +** fails, try opening it read-only. If the file does not exist,
47.815 +** try to create it.
47.816 +**
47.817 +** On success, a handle for the open file is written to *id
47.818 +** and *pReadonly is set to 0 if the file was opened for reading and
47.819 +** writing or 1 if the file was opened read-only. The function returns
47.820 +** SQLITE_OK.
47.821 +**
47.822 +** On failure, the function returns SQLITE_CANTOPEN and leaves
47.823 +** *id and *pReadonly unchanged.
47.824 +*/
47.825 +int sqlite3UnixOpenReadWrite(
47.826 + const char *zFilename,
47.827 + OsFile **pId,
47.828 + int *pReadonly
47.829 +){
47.830 + int h;
47.831 +
47.832 + CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
47.833 + assert( 0==*pId );
47.834 + h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
47.835 + SQLITE_DEFAULT_FILE_PERMISSIONS);
47.836 + if( h<0 ){
47.837 +#ifdef EISDIR
47.838 + if( errno==EISDIR ){
47.839 + return SQLITE_CANTOPEN;
47.840 + }
47.841 +#endif
47.842 + h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
47.843 + if( h<0 ){
47.844 + return SQLITE_CANTOPEN;
47.845 + }
47.846 + *pReadonly = 1;
47.847 + }else{
47.848 + *pReadonly = 0;
47.849 + }
47.850 + return allocateUnixFile(h, pId, zFilename, 0);
47.851 +}
47.852 +
47.853 +
47.854 +/*
47.855 +** Attempt to open a new file for exclusive access by this process.
47.856 +** The file will be opened for both reading and writing. To avoid
47.857 +** a potential security problem, we do not allow the file to have
47.858 +** previously existed. Nor do we allow the file to be a symbolic
47.859 +** link.
47.860 +**
47.861 +** If delFlag is true, then make arrangements to automatically delete
47.862 +** the file when it is closed.
47.863 +**
47.864 +** On success, write the file handle into *id and return SQLITE_OK.
47.865 +**
47.866 +** On failure, return SQLITE_CANTOPEN.
47.867 +*/
47.868 +int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
47.869 + int h;
47.870 +
47.871 + CRASH_TEST_OVERRIDE(sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
47.872 + assert( 0==*pId );
47.873 + h = open(zFilename,
47.874 + O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
47.875 + delFlag ? 0600 : SQLITE_DEFAULT_FILE_PERMISSIONS);
47.876 + if( h<0 ){
47.877 + return SQLITE_CANTOPEN;
47.878 + }
47.879 + return allocateUnixFile(h, pId, zFilename, delFlag);
47.880 +}
47.881 +
47.882 +/*
47.883 +** Attempt to open a new file for read-only access.
47.884 +**
47.885 +** On success, write the file handle into *id and return SQLITE_OK.
47.886 +**
47.887 +** On failure, return SQLITE_CANTOPEN.
47.888 +*/
47.889 +int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
47.890 + int h;
47.891 +
47.892 + CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadOnly, zFilename, pId, 0);
47.893 + assert( 0==*pId );
47.894 + h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
47.895 + if( h<0 ){
47.896 + return SQLITE_CANTOPEN;
47.897 + }
47.898 + return allocateUnixFile(h, pId, zFilename, 0);
47.899 +}
47.900 +
47.901 +/*
47.902 +** Attempt to open a file descriptor for the directory that contains a
47.903 +** file. This file descriptor can be used to fsync() the directory
47.904 +** in order to make sure the creation of a new file is actually written
47.905 +** to disk.
47.906 +**
47.907 +** This routine is only meaningful for Unix. It is a no-op under
47.908 +** windows since windows does not support hard links.
47.909 +**
47.910 +** If FULL_FSYNC is enabled, this function is not longer useful,
47.911 +** a FULL_FSYNC sync applies to all pending disk operations.
47.912 +**
47.913 +** On success, a handle for a previously open file at *id is
47.914 +** updated with the new directory file descriptor and SQLITE_OK is
47.915 +** returned.
47.916 +**
47.917 +** On failure, the function returns SQLITE_CANTOPEN and leaves
47.918 +** *id unchanged.
47.919 +*/
47.920 +static int unixOpenDirectory(
47.921 + OsFile *id,
47.922 + const char *zDirname
47.923 +){
47.924 + int h;
47.925 + unixFile *pFile = (unixFile*)id;
47.926 + assert( pFile!=0 );
47.927 + SET_THREADID(pFile);
47.928 + assert( pFile->dirfd<0 );
47.929 + pFile->dirfd = h = open(zDirname, O_RDONLY|O_BINARY, 0);
47.930 + if( h<0 ){
47.931 + return SQLITE_CANTOPEN;
47.932 + }
47.933 +#ifdef FD_CLOEXEC
47.934 + fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
47.935 +#endif
47.936 + OSTRACE3("OPENDIR %-3d %s\n", h, zDirname);
47.937 + return SQLITE_OK;
47.938 +}
47.939 +
47.940 +/*
47.941 +** Create a temporary file name in zBuf. zBuf must be big enough to
47.942 +** hold at least SQLITE_TEMPNAME_SIZE characters.
47.943 +*/
47.944 +int sqlite3UnixTempFileName(char *zBuf){
47.945 + static const char *azDirs[] = {
47.946 + 0,
47.947 + "/var/tmp",
47.948 + "/usr/tmp",
47.949 + "/tmp",
47.950 + ".",
47.951 + };
47.952 + static const unsigned char zChars[] =
47.953 + "abcdefghijklmnopqrstuvwxyz"
47.954 + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
47.955 + "0123456789";
47.956 + int i, j;
47.957 + struct stat buf;
47.958 + const char *zDir = ".";
47.959 + azDirs[0] = sqlite3_temp_directory;
47.960 + for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
47.961 + if( azDirs[i]==0 ) continue;
47.962 + if( stat(azDirs[i], &buf) ) continue;
47.963 + if( !S_ISDIR(buf.st_mode) ) continue;
47.964 + if( access(azDirs[i], 07) ) continue;
47.965 + zDir = azDirs[i];
47.966 + break;
47.967 + }
47.968 + do{
47.969 + sqlite3_snprintf(SQLITE_TEMPNAME_SIZE, zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
47.970 + j = strlen(zBuf);
47.971 + sqlite3Randomness(15, &zBuf[j]);
47.972 + for(i=0; i<15; i++, j++){
47.973 + zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
47.974 + }
47.975 + zBuf[j] = 0;
47.976 + }while( access(zBuf,0)==0 );
47.977 + return SQLITE_OK;
47.978 +}
47.979 +
47.980 +/*
47.981 +** Check that a given pathname is a directory and is writable
47.982 +**
47.983 +*/
47.984 +int sqlite3UnixIsDirWritable(char *zBuf){
47.985 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
47.986 + struct stat buf;
47.987 + if( zBuf==0 ) return 0;
47.988 + if( zBuf[0]==0 ) return 0;
47.989 + if( stat(zBuf, &buf) ) return 0;
47.990 + if( !S_ISDIR(buf.st_mode) ) return 0;
47.991 + if( access(zBuf, 07) ) return 0;
47.992 +#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
47.993 + return 1;
47.994 +}
47.995 +
47.996 +/*
47.997 +** Seek to the offset in id->offset then read cnt bytes into pBuf.
47.998 +** Return the number of bytes actually read. Update the offset.
47.999 +*/
47.1000 +static int seekAndRead(unixFile *id, void *pBuf, int cnt){
47.1001 + int got;
47.1002 + i64 newOffset;
47.1003 + TIMER_START;
47.1004 +#if defined(USE_PREAD)
47.1005 + got = pread(id->h, pBuf, cnt, id->offset);
47.1006 + SimulateIOError( got = -1 );
47.1007 +#elif defined(USE_PREAD64)
47.1008 + got = pread64(id->h, pBuf, cnt, id->offset);
47.1009 + SimulateIOError( got = -1 );
47.1010 +#else
47.1011 + newOffset = lseek(id->h, id->offset, SEEK_SET);
47.1012 + SimulateIOError( newOffset-- );
47.1013 + if( newOffset!=id->offset ){
47.1014 + return -1;
47.1015 + }
47.1016 + got = read(id->h, pBuf, cnt);
47.1017 +#endif
47.1018 + TIMER_END;
47.1019 + OSTRACE5("READ %-3d %5d %7lld %d\n", id->h, got, id->offset, TIMER_ELAPSED);
47.1020 + if( got>0 ){
47.1021 + id->offset += got;
47.1022 + }
47.1023 + return got;
47.1024 +}
47.1025 +
47.1026 +/*
47.1027 +** Read data from a file into a buffer. Return SQLITE_OK if all
47.1028 +** bytes were read successfully and SQLITE_IOERR if anything goes
47.1029 +** wrong.
47.1030 +*/
47.1031 +static int unixRead(OsFile *id, void *pBuf, int amt){
47.1032 + int got;
47.1033 + assert( id );
47.1034 + got = seekAndRead((unixFile*)id, pBuf, amt);
47.1035 + if( got==amt ){
47.1036 + return SQLITE_OK;
47.1037 + }else if( got<0 ){
47.1038 + return SQLITE_IOERR_READ;
47.1039 + }else{
47.1040 + memset(&((char*)pBuf)[got], 0, amt-got);
47.1041 + return SQLITE_IOERR_SHORT_READ;
47.1042 + }
47.1043 +}
47.1044 +
47.1045 +/*
47.1046 +** Seek to the offset in id->offset then read cnt bytes into pBuf.
47.1047 +** Return the number of bytes actually read. Update the offset.
47.1048 +*/
47.1049 +static int seekAndWrite(unixFile *id, const void *pBuf, int cnt){
47.1050 + int got;
47.1051 + i64 newOffset;
47.1052 + TIMER_START;
47.1053 +#if defined(USE_PREAD)
47.1054 + got = pwrite(id->h, pBuf, cnt, id->offset);
47.1055 +#elif defined(USE_PREAD64)
47.1056 + got = pwrite64(id->h, pBuf, cnt, id->offset);
47.1057 +#else
47.1058 + newOffset = lseek(id->h, id->offset, SEEK_SET);
47.1059 + if( newOffset!=id->offset ){
47.1060 + return -1;
47.1061 + }
47.1062 + got = write(id->h, pBuf, cnt);
47.1063 +#endif
47.1064 + TIMER_END;
47.1065 + OSTRACE5("WRITE %-3d %5d %7lld %d\n", id->h, got, id->offset, TIMER_ELAPSED);
47.1066 + if( got>0 ){
47.1067 + id->offset += got;
47.1068 + }
47.1069 + return got;
47.1070 +}
47.1071 +
47.1072 +
47.1073 +/*
47.1074 +** Write data from a buffer into a file. Return SQLITE_OK on success
47.1075 +** or some other error code on failure.
47.1076 +*/
47.1077 +static int unixWrite(OsFile *id, const void *pBuf, int amt){
47.1078 + int wrote = 0;
47.1079 + assert( id );
47.1080 + assert( amt>0 );
47.1081 + while( amt>0 && (wrote = seekAndWrite((unixFile*)id, pBuf, amt))>0 ){
47.1082 + amt -= wrote;
47.1083 + pBuf = &((char*)pBuf)[wrote];
47.1084 + }
47.1085 + SimulateIOError(( wrote=(-1), amt=1 ));
47.1086 + SimulateDiskfullError(( wrote=0, amt=1 ));
47.1087 + if( amt>0 ){
47.1088 + if( wrote<0 ){
47.1089 + return SQLITE_IOERR_WRITE;
47.1090 + }else{
47.1091 + return SQLITE_FULL;
47.1092 + }
47.1093 + }
47.1094 + return SQLITE_OK;
47.1095 +}
47.1096 +
47.1097 +/*
47.1098 +** Move the read/write pointer in a file.
47.1099 +*/
47.1100 +static int unixSeek(OsFile *id, i64 offset){
47.1101 + assert( id );
47.1102 +#ifdef SQLITE_TEST
47.1103 + if( offset ) SimulateDiskfullError(return SQLITE_FULL);
47.1104 +#endif
47.1105 + ((unixFile*)id)->offset = offset;
47.1106 + return SQLITE_OK;
47.1107 +}
47.1108 +
47.1109 +#ifdef SQLITE_TEST
47.1110 +/*
47.1111 +** Count the number of fullsyncs and normal syncs. This is used to test
47.1112 +** that syncs and fullsyncs are occuring at the right times.
47.1113 +*/
47.1114 +int sqlite3_sync_count = 0;
47.1115 +int sqlite3_fullsync_count = 0;
47.1116 +#endif
47.1117 +
47.1118 +/*
47.1119 +** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
47.1120 +** Otherwise use fsync() in its place.
47.1121 +*/
47.1122 +#ifndef HAVE_FDATASYNC
47.1123 +# define fdatasync fsync
47.1124 +#endif
47.1125 +
47.1126 +/*
47.1127 +** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
47.1128 +** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
47.1129 +** only available on Mac OS X. But that could change.
47.1130 +*/
47.1131 +#ifdef F_FULLFSYNC
47.1132 +# define HAVE_FULLFSYNC 1
47.1133 +#else
47.1134 +# define HAVE_FULLFSYNC 0
47.1135 +#endif
47.1136 +
47.1137 +
47.1138 +/*
47.1139 +** The fsync() system call does not work as advertised on many
47.1140 +** unix systems. The following procedure is an attempt to make
47.1141 +** it work better.
47.1142 +**
47.1143 +** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
47.1144 +** for testing when we want to run through the test suite quickly.
47.1145 +** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
47.1146 +** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
47.1147 +** or power failure will likely corrupt the database file.
47.1148 +*/
47.1149 +static int full_fsync(int fd, int fullSync, int dataOnly){
47.1150 + int rc;
47.1151 +
47.1152 + /* Record the number of times that we do a normal fsync() and
47.1153 + ** FULLSYNC. This is used during testing to verify that this procedure
47.1154 + ** gets called with the correct arguments.
47.1155 + */
47.1156 +#ifdef SQLITE_TEST
47.1157 + if( fullSync ) sqlite3_fullsync_count++;
47.1158 + sqlite3_sync_count++;
47.1159 +#endif
47.1160 +
47.1161 + /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
47.1162 + ** no-op
47.1163 + */
47.1164 +#ifdef SQLITE_NO_SYNC
47.1165 + rc = SQLITE_OK;
47.1166 +#else
47.1167 +
47.1168 +#if HAVE_FULLFSYNC
47.1169 + if( fullSync ){
47.1170 + rc = fcntl(fd, F_FULLFSYNC, 0);
47.1171 + }else{
47.1172 + rc = 1;
47.1173 + }
47.1174 + /* If the FULLFSYNC failed, fall back to attempting an fsync().
47.1175 + * It shouldn't be possible for fullfsync to fail on the local
47.1176 + * file system (on OSX), so failure indicates that FULLFSYNC
47.1177 + * isn't supported for this file system. So, attempt an fsync
47.1178 + * and (for now) ignore the overhead of a superfluous fcntl call.
47.1179 + * It'd be better to detect fullfsync support once and avoid
47.1180 + * the fcntl call every time sync is called.
47.1181 + */
47.1182 + if( rc ) rc = fsync(fd);
47.1183 +
47.1184 +#else
47.1185 + if( dataOnly ){
47.1186 + rc = fdatasync(fd);
47.1187 + }else{
47.1188 + rc = fsync(fd);
47.1189 + }
47.1190 +#endif /* HAVE_FULLFSYNC */
47.1191 +#endif /* defined(SQLITE_NO_SYNC) */
47.1192 +
47.1193 + return rc;
47.1194 +}
47.1195 +
47.1196 +/*
47.1197 +** Make sure all writes to a particular file are committed to disk.
47.1198 +**
47.1199 +** If dataOnly==0 then both the file itself and its metadata (file
47.1200 +** size, access time, etc) are synced. If dataOnly!=0 then only the
47.1201 +** file data is synced.
47.1202 +**
47.1203 +** Under Unix, also make sure that the directory entry for the file
47.1204 +** has been created by fsync-ing the directory that contains the file.
47.1205 +** If we do not do this and we encounter a power failure, the directory
47.1206 +** entry for the journal might not exist after we reboot. The next
47.1207 +** SQLite to access the file will not know that the journal exists (because
47.1208 +** the directory entry for the journal was never created) and the transaction
47.1209 +** will not roll back - possibly leading to database corruption.
47.1210 +*/
47.1211 +static int unixSync(OsFile *id, int dataOnly){
47.1212 + int rc;
47.1213 + unixFile *pFile = (unixFile*)id;
47.1214 + assert( pFile );
47.1215 + OSTRACE2("SYNC %-3d\n", pFile->h);
47.1216 + rc = full_fsync(pFile->h, pFile->fullSync, dataOnly);
47.1217 + SimulateIOError( rc=1 );
47.1218 + if( rc ){
47.1219 + return SQLITE_IOERR_FSYNC;
47.1220 + }
47.1221 + if( pFile->dirfd>=0 ){
47.1222 + OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
47.1223 + HAVE_FULLFSYNC, pFile->fullSync);
47.1224 +#ifndef SQLITE_DISABLE_DIRSYNC
47.1225 + /* The directory sync is only attempted if full_fsync is
47.1226 + ** turned off or unavailable. If a full_fsync occurred above,
47.1227 + ** then the directory sync is superfluous.
47.1228 + */
47.1229 + if( (!HAVE_FULLFSYNC || !pFile->fullSync) && full_fsync(pFile->dirfd,0,0) ){
47.1230 + /*
47.1231 + ** We have received multiple reports of fsync() returning
47.1232 + ** errors when applied to directories on certain file systems.
47.1233 + ** A failed directory sync is not a big deal. So it seems
47.1234 + ** better to ignore the error. Ticket #1657
47.1235 + */
47.1236 + /* return SQLITE_IOERR; */
47.1237 + }
47.1238 +#endif
47.1239 + close(pFile->dirfd); /* Only need to sync once, so close the directory */
47.1240 + pFile->dirfd = -1; /* when we are done. */
47.1241 + }
47.1242 + return SQLITE_OK;
47.1243 +}
47.1244 +
47.1245 +/*
47.1246 +** Sync the directory zDirname. This is a no-op on operating systems other
47.1247 +** than UNIX.
47.1248 +**
47.1249 +** This is used to make sure the master journal file has truely been deleted
47.1250 +** before making changes to individual journals on a multi-database commit.
47.1251 +** The F_FULLFSYNC option is not needed here.
47.1252 +*/
47.1253 +int sqlite3UnixSyncDirectory(const char *zDirname){
47.1254 +#ifdef SQLITE_DISABLE_DIRSYNC
47.1255 + return SQLITE_OK;
47.1256 +#else
47.1257 + int fd;
47.1258 + int r;
47.1259 + fd = open(zDirname, O_RDONLY|O_BINARY, 0);
47.1260 + OSTRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
47.1261 + if( fd<0 ){
47.1262 + return SQLITE_CANTOPEN;
47.1263 + }
47.1264 + r = fsync(fd);
47.1265 + close(fd);
47.1266 + SimulateIOError( r=1 );
47.1267 + if( r ){
47.1268 + return SQLITE_IOERR_DIR_FSYNC;
47.1269 + }else{
47.1270 + return SQLITE_OK;
47.1271 + }
47.1272 +#endif
47.1273 +}
47.1274 +
47.1275 +/*
47.1276 +** Truncate an open file to a specified size
47.1277 +*/
47.1278 +static int unixTruncate(OsFile *id, i64 nByte){
47.1279 + int rc;
47.1280 + assert( id );
47.1281 + rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
47.1282 + SimulateIOError( rc=1 );
47.1283 + if( rc ){
47.1284 + return SQLITE_IOERR_TRUNCATE;
47.1285 + }else{
47.1286 + return SQLITE_OK;
47.1287 + }
47.1288 +}
47.1289 +
47.1290 +/*
47.1291 +** Determine the current size of a file in bytes
47.1292 +*/
47.1293 +static int unixFileSize(OsFile *id, i64 *pSize){
47.1294 + int rc;
47.1295 + struct stat buf;
47.1296 + assert( id );
47.1297 + rc = fstat(((unixFile*)id)->h, &buf);
47.1298 + SimulateIOError( rc=1 );
47.1299 + if( rc!=0 ){
47.1300 + return SQLITE_IOERR_FSTAT;
47.1301 + }
47.1302 + *pSize = buf.st_size;
47.1303 + return SQLITE_OK;
47.1304 +}
47.1305 +
47.1306 +/*
47.1307 +** This routine checks if there is a RESERVED lock held on the specified
47.1308 +** file by this or any other process. If such a lock is held, return
47.1309 +** non-zero. If the file is unlocked or holds only SHARED locks, then
47.1310 +** return zero.
47.1311 +*/
47.1312 +static int unixCheckReservedLock(OsFile *id){
47.1313 + int r = 0;
47.1314 + unixFile *pFile = (unixFile*)id;
47.1315 +
47.1316 + assert( pFile );
47.1317 + sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */
47.1318 +
47.1319 + /* Check if a thread in this process holds such a lock */
47.1320 + if( pFile->pLock->locktype>SHARED_LOCK ){
47.1321 + r = 1;
47.1322 + }
47.1323 +
47.1324 + /* Otherwise see if some other process holds it.
47.1325 + */
47.1326 + if( !r ){
47.1327 + struct flock lock;
47.1328 + lock.l_whence = SEEK_SET;
47.1329 + lock.l_start = RESERVED_BYTE;
47.1330 + lock.l_len = 1;
47.1331 + lock.l_type = F_WRLCK;
47.1332 + fcntl(pFile->h, F_GETLK, &lock);
47.1333 + if( lock.l_type!=F_UNLCK ){
47.1334 + r = 1;
47.1335 + }
47.1336 + }
47.1337 +
47.1338 + sqlite3OsLeaveMutex();
47.1339 + OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
47.1340 +
47.1341 + return r;
47.1342 +}
47.1343 +
47.1344 +/*
47.1345 +** Lock the file with the lock specified by parameter locktype - one
47.1346 +** of the following:
47.1347 +**
47.1348 +** (1) SHARED_LOCK
47.1349 +** (2) RESERVED_LOCK
47.1350 +** (3) PENDING_LOCK
47.1351 +** (4) EXCLUSIVE_LOCK
47.1352 +**
47.1353 +** Sometimes when requesting one lock state, additional lock states
47.1354 +** are inserted in between. The locking might fail on one of the later
47.1355 +** transitions leaving the lock state different from what it started but
47.1356 +** still short of its goal. The following chart shows the allowed
47.1357 +** transitions and the inserted intermediate states:
47.1358 +**
47.1359 +** UNLOCKED -> SHARED
47.1360 +** SHARED -> RESERVED
47.1361 +** SHARED -> (PENDING) -> EXCLUSIVE
47.1362 +** RESERVED -> (PENDING) -> EXCLUSIVE
47.1363 +** PENDING -> EXCLUSIVE
47.1364 +**
47.1365 +** This routine will only increase a lock. Use the sqlite3OsUnlock()
47.1366 +** routine to lower a locking level.
47.1367 +*/
47.1368 +static int unixLock(OsFile *id, int locktype){
47.1369 + /* The following describes the implementation of the various locks and
47.1370 + ** lock transitions in terms of the POSIX advisory shared and exclusive
47.1371 + ** lock primitives (called read-locks and write-locks below, to avoid
47.1372 + ** confusion with SQLite lock names). The algorithms are complicated
47.1373 + ** slightly in order to be compatible with windows systems simultaneously
47.1374 + ** accessing the same database file, in case that is ever required.
47.1375 + **
47.1376 + ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
47.1377 + ** byte', each single bytes at well known offsets, and the 'shared byte
47.1378 + ** range', a range of 510 bytes at a well known offset.
47.1379 + **
47.1380 + ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
47.1381 + ** byte'. If this is successful, a random byte from the 'shared byte
47.1382 + ** range' is read-locked and the lock on the 'pending byte' released.
47.1383 + **
47.1384 + ** A process may only obtain a RESERVED lock after it has a SHARED lock.
47.1385 + ** A RESERVED lock is implemented by grabbing a write-lock on the
47.1386 + ** 'reserved byte'.
47.1387 + **
47.1388 + ** A process may only obtain a PENDING lock after it has obtained a
47.1389 + ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
47.1390 + ** on the 'pending byte'. This ensures that no new SHARED locks can be
47.1391 + ** obtained, but existing SHARED locks are allowed to persist. A process
47.1392 + ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
47.1393 + ** This property is used by the algorithm for rolling back a journal file
47.1394 + ** after a crash.
47.1395 + **
47.1396 + ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
47.1397 + ** implemented by obtaining a write-lock on the entire 'shared byte
47.1398 + ** range'. Since all other locks require a read-lock on one of the bytes
47.1399 + ** within this range, this ensures that no other locks are held on the
47.1400 + ** database.
47.1401 + **
47.1402 + ** The reason a single byte cannot be used instead of the 'shared byte
47.1403 + ** range' is that some versions of windows do not support read-locks. By
47.1404 + ** locking a random byte from a range, concurrent SHARED locks may exist
47.1405 + ** even if the locking primitive used is always a write-lock.
47.1406 + */
47.1407 + int rc = SQLITE_OK;
47.1408 + unixFile *pFile = (unixFile*)id;
47.1409 + struct lockInfo *pLock = pFile->pLock;
47.1410 + struct flock lock;
47.1411 + int s;
47.1412 +
47.1413 + assert( pFile );
47.1414 + OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
47.1415 + locktypeName(locktype), locktypeName(pFile->locktype),
47.1416 + locktypeName(pLock->locktype), pLock->cnt , getpid());
47.1417 +
47.1418 + /* If there is already a lock of this type or more restrictive on the
47.1419 + ** OsFile, do nothing. Don't use the end_lock: exit path, as
47.1420 + ** sqlite3OsEnterMutex() hasn't been called yet.
47.1421 + */
47.1422 + if( pFile->locktype>=locktype ){
47.1423 + OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
47.1424 + locktypeName(locktype));
47.1425 + return SQLITE_OK;
47.1426 + }
47.1427 +
47.1428 + /* Make sure the locking sequence is correct
47.1429 + */
47.1430 + assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
47.1431 + assert( locktype!=PENDING_LOCK );
47.1432 + assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
47.1433 +
47.1434 + /* This mutex is needed because pFile->pLock is shared across threads
47.1435 + */
47.1436 + sqlite3OsEnterMutex();
47.1437 +
47.1438 + /* Make sure the current thread owns the pFile.
47.1439 + */
47.1440 + rc = transferOwnership(pFile);
47.1441 + if( rc!=SQLITE_OK ){
47.1442 + sqlite3OsLeaveMutex();
47.1443 + return rc;
47.1444 + }
47.1445 + pLock = pFile->pLock;
47.1446 +
47.1447 + /* If some thread using this PID has a lock via a different OsFile*
47.1448 + ** handle that precludes the requested lock, return BUSY.
47.1449 + */
47.1450 + if( (pFile->locktype!=pLock->locktype &&
47.1451 + (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
47.1452 + ){
47.1453 + rc = SQLITE_BUSY;
47.1454 + goto end_lock;
47.1455 + }
47.1456 +
47.1457 + /* If a SHARED lock is requested, and some thread using this PID already
47.1458 + ** has a SHARED or RESERVED lock, then increment reference counts and
47.1459 + ** return SQLITE_OK.
47.1460 + */
47.1461 + if( locktype==SHARED_LOCK &&
47.1462 + (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
47.1463 + assert( locktype==SHARED_LOCK );
47.1464 + assert( pFile->locktype==0 );
47.1465 + assert( pLock->cnt>0 );
47.1466 + pFile->locktype = SHARED_LOCK;
47.1467 + pLock->cnt++;
47.1468 + pFile->pOpen->nLock++;
47.1469 + goto end_lock;
47.1470 + }
47.1471 +
47.1472 + lock.l_len = 1L;
47.1473 +
47.1474 + lock.l_whence = SEEK_SET;
47.1475 +
47.1476 + /* A PENDING lock is needed before acquiring a SHARED lock and before
47.1477 + ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
47.1478 + ** be released.
47.1479 + */
47.1480 + if( locktype==SHARED_LOCK
47.1481 + || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
47.1482 + ){
47.1483 + lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
47.1484 + lock.l_start = PENDING_BYTE;
47.1485 + s = fcntl(pFile->h, F_SETLK, &lock);
47.1486 + if( s==(-1) ){
47.1487 + rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
47.1488 + goto end_lock;
47.1489 + }
47.1490 + }
47.1491 +
47.1492 +
47.1493 + /* If control gets to this point, then actually go ahead and make
47.1494 + ** operating system calls for the specified lock.
47.1495 + */
47.1496 + if( locktype==SHARED_LOCK ){
47.1497 + assert( pLock->cnt==0 );
47.1498 + assert( pLock->locktype==0 );
47.1499 +
47.1500 + /* Now get the read-lock */
47.1501 + lock.l_start = SHARED_FIRST;
47.1502 + lock.l_len = SHARED_SIZE;
47.1503 + s = fcntl(pFile->h, F_SETLK, &lock);
47.1504 +
47.1505 + /* Drop the temporary PENDING lock */
47.1506 + lock.l_start = PENDING_BYTE;
47.1507 + lock.l_len = 1L;
47.1508 + lock.l_type = F_UNLCK;
47.1509 + if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
47.1510 + rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
47.1511 + goto end_lock;
47.1512 + }
47.1513 + if( s==(-1) ){
47.1514 + rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
47.1515 + }else{
47.1516 + pFile->locktype = SHARED_LOCK;
47.1517 + pFile->pOpen->nLock++;
47.1518 + pLock->cnt = 1;
47.1519 + }
47.1520 + }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
47.1521 + /* We are trying for an exclusive lock but another thread in this
47.1522 + ** same process is still holding a shared lock. */
47.1523 + rc = SQLITE_BUSY;
47.1524 + }else{
47.1525 + /* The request was for a RESERVED or EXCLUSIVE lock. It is
47.1526 + ** assumed that there is a SHARED or greater lock on the file
47.1527 + ** already.
47.1528 + */
47.1529 + assert( 0!=pFile->locktype );
47.1530 + lock.l_type = F_WRLCK;
47.1531 + switch( locktype ){
47.1532 + case RESERVED_LOCK:
47.1533 + lock.l_start = RESERVED_BYTE;
47.1534 + break;
47.1535 + case EXCLUSIVE_LOCK:
47.1536 + lock.l_start = SHARED_FIRST;
47.1537 + lock.l_len = SHARED_SIZE;
47.1538 + break;
47.1539 + default:
47.1540 + assert(0);
47.1541 + }
47.1542 + s = fcntl(pFile->h, F_SETLK, &lock);
47.1543 + if( s==(-1) ){
47.1544 + rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
47.1545 + }
47.1546 + }
47.1547 +
47.1548 + if( rc==SQLITE_OK ){
47.1549 + pFile->locktype = locktype;
47.1550 + pLock->locktype = locktype;
47.1551 + }else if( locktype==EXCLUSIVE_LOCK ){
47.1552 + pFile->locktype = PENDING_LOCK;
47.1553 + pLock->locktype = PENDING_LOCK;
47.1554 + }
47.1555 +
47.1556 +end_lock:
47.1557 + sqlite3OsLeaveMutex();
47.1558 + OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
47.1559 + rc==SQLITE_OK ? "ok" : "failed");
47.1560 + return rc;
47.1561 +}
47.1562 +
47.1563 +/*
47.1564 +** Lower the locking level on file descriptor pFile to locktype. locktype
47.1565 +** must be either NO_LOCK or SHARED_LOCK.
47.1566 +**
47.1567 +** If the locking level of the file descriptor is already at or below
47.1568 +** the requested locking level, this routine is a no-op.
47.1569 +*/
47.1570 +static int unixUnlock(OsFile *id, int locktype){
47.1571 + struct lockInfo *pLock;
47.1572 + struct flock lock;
47.1573 + int rc = SQLITE_OK;
47.1574 + unixFile *pFile = (unixFile*)id;
47.1575 +
47.1576 + assert( pFile );
47.1577 + OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
47.1578 + pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
47.1579 +
47.1580 + assert( locktype<=SHARED_LOCK );
47.1581 + if( pFile->locktype<=locktype ){
47.1582 + return SQLITE_OK;
47.1583 + }
47.1584 + if( CHECK_THREADID(pFile) ){
47.1585 + return SQLITE_MISUSE;
47.1586 + }
47.1587 + sqlite3OsEnterMutex();
47.1588 + pLock = pFile->pLock;
47.1589 + assert( pLock->cnt!=0 );
47.1590 + if( pFile->locktype>SHARED_LOCK ){
47.1591 + assert( pLock->locktype==pFile->locktype );
47.1592 + if( locktype==SHARED_LOCK ){
47.1593 + lock.l_type = F_RDLCK;
47.1594 + lock.l_whence = SEEK_SET;
47.1595 + lock.l_start = SHARED_FIRST;
47.1596 + lock.l_len = SHARED_SIZE;
47.1597 + if( fcntl(pFile->h, F_SETLK, &lock)==(-1) ){
47.1598 + /* This should never happen */
47.1599 + rc = SQLITE_IOERR_RDLOCK;
47.1600 + }
47.1601 + }
47.1602 + lock.l_type = F_UNLCK;
47.1603 + lock.l_whence = SEEK_SET;
47.1604 + lock.l_start = PENDING_BYTE;
47.1605 + lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
47.1606 + if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
47.1607 + pLock->locktype = SHARED_LOCK;
47.1608 + }else{
47.1609 + rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
47.1610 + }
47.1611 + }
47.1612 + if( locktype==NO_LOCK ){
47.1613 + struct openCnt *pOpen;
47.1614 +
47.1615 + /* Decrement the shared lock counter. Release the lock using an
47.1616 + ** OS call only when all threads in this same process have released
47.1617 + ** the lock.
47.1618 + */
47.1619 + pLock->cnt--;
47.1620 + if( pLock->cnt==0 ){
47.1621 + lock.l_type = F_UNLCK;
47.1622 + lock.l_whence = SEEK_SET;
47.1623 + lock.l_start = lock.l_len = 0L;
47.1624 + if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
47.1625 + pLock->locktype = NO_LOCK;
47.1626 + }else{
47.1627 + rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
47.1628 + }
47.1629 + }
47.1630 +
47.1631 + /* Decrement the count of locks against this same file. When the
47.1632 + ** count reaches zero, close any other file descriptors whose close
47.1633 + ** was deferred because of outstanding locks.
47.1634 + */
47.1635 + pOpen = pFile->pOpen;
47.1636 + pOpen->nLock--;
47.1637 + assert( pOpen->nLock>=0 );
47.1638 + if( pOpen->nLock==0 && pOpen->nPending>0 ){
47.1639 + int i;
47.1640 + for(i=0; i<pOpen->nPending; i++){
47.1641 + close(pOpen->aPending[i]);
47.1642 + }
47.1643 + free(pOpen->aPending);
47.1644 + pOpen->nPending = 0;
47.1645 + pOpen->aPending = 0;
47.1646 + }
47.1647 + }
47.1648 + sqlite3OsLeaveMutex();
47.1649 + pFile->locktype = locktype;
47.1650 + return rc;
47.1651 +}
47.1652 +
47.1653 +/*
47.1654 +** Close a file.
47.1655 +*/
47.1656 +static int unixClose(OsFile **pId){
47.1657 + unixFile *id = (unixFile*)*pId;
47.1658 +
47.1659 + if( !id ) return SQLITE_OK;
47.1660 + unixUnlock(*pId, NO_LOCK);
47.1661 + if( id->dirfd>=0 ) close(id->dirfd);
47.1662 + id->dirfd = -1;
47.1663 + sqlite3OsEnterMutex();
47.1664 +
47.1665 + if( id->pOpen->nLock ){
47.1666 + /* If there are outstanding locks, do not actually close the file just
47.1667 + ** yet because that would clear those locks. Instead, add the file
47.1668 + ** descriptor to pOpen->aPending. It will be automatically closed when
47.1669 + ** the last lock is cleared.
47.1670 + */
47.1671 + int *aNew;
47.1672 + struct openCnt *pOpen = id->pOpen;
47.1673 + aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
47.1674 + if( aNew==0 ){
47.1675 + /* If a malloc fails, just leak the file descriptor */
47.1676 + }else{
47.1677 + pOpen->aPending = aNew;
47.1678 + pOpen->aPending[pOpen->nPending] = id->h;
47.1679 + pOpen->nPending++;
47.1680 + }
47.1681 + }else{
47.1682 + /* There are no outstanding locks so we can close the file immediately */
47.1683 + close(id->h);
47.1684 + }
47.1685 + releaseLockInfo(id->pLock);
47.1686 + releaseOpenCnt(id->pOpen);
47.1687 +
47.1688 + sqlite3OsLeaveMutex();
47.1689 + id->isOpen = 0;
47.1690 + OSTRACE2("CLOSE %-3d\n", id->h);
47.1691 + OpenCounter(-1);
47.1692 + sqlite3ThreadSafeFree(id);
47.1693 + *pId = 0;
47.1694 + return SQLITE_OK;
47.1695 +}
47.1696 +
47.1697 +
47.1698 +#ifdef SQLITE_ENABLE_LOCKING_STYLE
47.1699 +#pragma mark AFP Support
47.1700 +
47.1701 +/*
47.1702 + ** The afpLockingContext structure contains all afp lock specific state
47.1703 + */
47.1704 +typedef struct afpLockingContext afpLockingContext;
47.1705 +struct afpLockingContext {
47.1706 + unsigned long long sharedLockByte;
47.1707 + char *filePath;
47.1708 +};
47.1709 +
47.1710 +struct ByteRangeLockPB2
47.1711 +{
47.1712 + unsigned long long offset; /* offset to first byte to lock */
47.1713 + unsigned long long length; /* nbr of bytes to lock */
47.1714 + unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
47.1715 + unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
47.1716 + unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
47.1717 + int fd; /* file desc to assoc this lock with */
47.1718 +};
47.1719 +
47.1720 +#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
47.1721 +
47.1722 +/* return 0 on success, 1 on failure. To match the behavior of the
47.1723 + normal posix file locking (used in unixLock for example), we should
47.1724 + provide 'richer' return codes - specifically to differentiate between
47.1725 + 'file busy' and 'file system error' results */
47.1726 +static int _AFPFSSetLock(const char *path, int fd, unsigned long long offset,
47.1727 + unsigned long long length, int setLockFlag)
47.1728 +{
47.1729 + struct ByteRangeLockPB2 pb;
47.1730 + int err;
47.1731 +
47.1732 + pb.unLockFlag = setLockFlag ? 0 : 1;
47.1733 + pb.startEndFlag = 0;
47.1734 + pb.offset = offset;
47.1735 + pb.length = length;
47.1736 + pb.fd = fd;
47.1737 + OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n",
47.1738 + (setLockFlag?"ON":"OFF"), fd, offset, length);
47.1739 + err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
47.1740 + if ( err==-1 ) {
47.1741 + OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno,
47.1742 + strerror(errno));
47.1743 + return 1; /* error */
47.1744 + } else {
47.1745 + return 0;
47.1746 + }
47.1747 +}
47.1748 +
47.1749 +/*
47.1750 + ** This routine checks if there is a RESERVED lock held on the specified
47.1751 + ** file by this or any other process. If such a lock is held, return
47.1752 + ** non-zero. If the file is unlocked or holds only SHARED locks, then
47.1753 + ** return zero.
47.1754 + */
47.1755 +static int afpUnixCheckReservedLock(OsFile *id){
47.1756 + int r = 0;
47.1757 + unixFile *pFile = (unixFile*)id;
47.1758 +
47.1759 + assert( pFile );
47.1760 + afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
47.1761 +
47.1762 + /* Check if a thread in this process holds such a lock */
47.1763 + if( pFile->locktype>SHARED_LOCK ){
47.1764 + r = 1;
47.1765 + }
47.1766 +
47.1767 + /* Otherwise see if some other process holds it.
47.1768 + */
47.1769 + if ( !r ) {
47.1770 + /* lock the byte */
47.1771 + int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
47.1772 + if (failed) {
47.1773 + /* if we failed to get the lock then someone else must have it */
47.1774 + r = 1;
47.1775 + } else {
47.1776 + /* if we succeeded in taking the reserved lock, unlock it to restore
47.1777 + ** the original state */
47.1778 + _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
47.1779 + }
47.1780 + }
47.1781 + OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
47.1782 +
47.1783 + return r;
47.1784 +}
47.1785 +
47.1786 +/* AFP-style locking following the behavior of unixLock, see the unixLock
47.1787 +** function comments for details of lock management. */
47.1788 +static int afpUnixLock(OsFile *id, int locktype)
47.1789 +{
47.1790 + int rc = SQLITE_OK;
47.1791 + unixFile *pFile = (unixFile*)id;
47.1792 + afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
47.1793 + int gotPendingLock = 0;
47.1794 +
47.1795 + assert( pFile );
47.1796 + OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
47.1797 + locktypeName(locktype), locktypeName(pFile->locktype), getpid());
47.1798 + /* If there is already a lock of this type or more restrictive on the
47.1799 + ** OsFile, do nothing. Don't use the afp_end_lock: exit path, as
47.1800 + ** sqlite3OsEnterMutex() hasn't been called yet.
47.1801 + */
47.1802 + if( pFile->locktype>=locktype ){
47.1803 + OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
47.1804 + locktypeName(locktype));
47.1805 + return SQLITE_OK;
47.1806 + }
47.1807 +
47.1808 + /* Make sure the locking sequence is correct
47.1809 + */
47.1810 + assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
47.1811 + assert( locktype!=PENDING_LOCK );
47.1812 + assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
47.1813 +
47.1814 + /* This mutex is needed because pFile->pLock is shared across threads
47.1815 + */
47.1816 + sqlite3OsEnterMutex();
47.1817 +
47.1818 + /* Make sure the current thread owns the pFile.
47.1819 + */
47.1820 + rc = transferOwnership(pFile);
47.1821 + if( rc!=SQLITE_OK ){
47.1822 + sqlite3OsLeaveMutex();
47.1823 + return rc;
47.1824 + }
47.1825 +
47.1826 + /* A PENDING lock is needed before acquiring a SHARED lock and before
47.1827 + ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
47.1828 + ** be released.
47.1829 + */
47.1830 + if( locktype==SHARED_LOCK
47.1831 + || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
47.1832 + ){
47.1833 + int failed = _AFPFSSetLock(context->filePath, pFile->h,
47.1834 + PENDING_BYTE, 1, 1);
47.1835 + if (failed) {
47.1836 + rc = SQLITE_BUSY;
47.1837 + goto afp_end_lock;
47.1838 + }
47.1839 + }
47.1840 +
47.1841 + /* If control gets to this point, then actually go ahead and make
47.1842 + ** operating system calls for the specified lock.
47.1843 + */
47.1844 + if( locktype==SHARED_LOCK ){
47.1845 + int lk, failed;
47.1846 + int tries = 0;
47.1847 +
47.1848 + /* Now get the read-lock */
47.1849 + /* note that the quality of the randomness doesn't matter that much */
47.1850 + lk = random();
47.1851 + context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
47.1852 + failed = _AFPFSSetLock(context->filePath, pFile->h,
47.1853 + SHARED_FIRST+context->sharedLockByte, 1, 1);
47.1854 +
47.1855 + /* Drop the temporary PENDING lock */
47.1856 + if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
47.1857 + rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
47.1858 + goto afp_end_lock;
47.1859 + }
47.1860 +
47.1861 + if( failed ){
47.1862 + rc = SQLITE_BUSY;
47.1863 + } else {
47.1864 + pFile->locktype = SHARED_LOCK;
47.1865 + }
47.1866 + }else{
47.1867 + /* The request was for a RESERVED or EXCLUSIVE lock. It is
47.1868 + ** assumed that there is a SHARED or greater lock on the file
47.1869 + ** already.
47.1870 + */
47.1871 + int failed = 0;
47.1872 + assert( 0!=pFile->locktype );
47.1873 + if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
47.1874 + /* Acquire a RESERVED lock */
47.1875 + failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
47.1876 + }
47.1877 + if (!failed && locktype == EXCLUSIVE_LOCK) {
47.1878 + /* Acquire an EXCLUSIVE lock */
47.1879 +
47.1880 + /* Remove the shared lock before trying the range. we'll need to
47.1881 + ** reestablish the shared lock if we can't get the afpUnixUnlock
47.1882 + */
47.1883 + if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
47.1884 + context->sharedLockByte, 1, 0)) {
47.1885 + /* now attemmpt to get the exclusive lock range */
47.1886 + failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
47.1887 + SHARED_SIZE, 1);
47.1888 + if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
47.1889 + context->sharedLockByte, 1, 1)) {
47.1890 + rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
47.1891 + }
47.1892 + } else {
47.1893 + /* */
47.1894 + rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
47.1895 + }
47.1896 + }
47.1897 + if( failed && rc == SQLITE_OK){
47.1898 + rc = SQLITE_BUSY;
47.1899 + }
47.1900 + }
47.1901 +
47.1902 + if( rc==SQLITE_OK ){
47.1903 + pFile->locktype = locktype;
47.1904 + }else if( locktype==EXCLUSIVE_LOCK ){
47.1905 + pFile->locktype = PENDING_LOCK;
47.1906 + }
47.1907 +
47.1908 +afp_end_lock:
47.1909 + sqlite3OsLeaveMutex();
47.1910 + OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
47.1911 + rc==SQLITE_OK ? "ok" : "failed");
47.1912 + return rc;
47.1913 +}
47.1914 +
47.1915 +/*
47.1916 + ** Lower the locking level on file descriptor pFile to locktype. locktype
47.1917 + ** must be either NO_LOCK or SHARED_LOCK.
47.1918 + **
47.1919 + ** If the locking level of the file descriptor is already at or below
47.1920 + ** the requested locking level, this routine is a no-op.
47.1921 + */
47.1922 +static int afpUnixUnlock(OsFile *id, int locktype) {
47.1923 + struct flock lock;
47.1924 + int rc = SQLITE_OK;
47.1925 + unixFile *pFile = (unixFile*)id;
47.1926 + afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
47.1927 +
47.1928 + assert( pFile );
47.1929 + OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
47.1930 + pFile->locktype, getpid());
47.1931 +
47.1932 + assert( locktype<=SHARED_LOCK );
47.1933 + if( pFile->locktype<=locktype ){
47.1934 + return SQLITE_OK;
47.1935 + }
47.1936 + if( CHECK_THREADID(pFile) ){
47.1937 + return SQLITE_MISUSE;
47.1938 + }
47.1939 + sqlite3OsEnterMutex();
47.1940 + if( pFile->locktype>SHARED_LOCK ){
47.1941 + if( locktype==SHARED_LOCK ){
47.1942 + int failed = 0;
47.1943 +
47.1944 + /* unlock the exclusive range - then re-establish the shared lock */
47.1945 + if (pFile->locktype==EXCLUSIVE_LOCK) {
47.1946 + failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
47.1947 + SHARED_SIZE, 0);
47.1948 + if (!failed) {
47.1949 + /* successfully removed the exclusive lock */
47.1950 + if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
47.1951 + context->sharedLockByte, 1, 1)) {
47.1952 + /* failed to re-establish our shared lock */
47.1953 + rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
47.1954 + }
47.1955 + } else {
47.1956 + /* This should never happen - failed to unlock the exclusive range */
47.1957 + rc = SQLITE_IOERR_UNLOCK;
47.1958 + }
47.1959 + }
47.1960 + }
47.1961 + if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
47.1962 + if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
47.1963 + /* failed to release the pending lock */
47.1964 + rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
47.1965 + }
47.1966 + }
47.1967 + if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
47.1968 + if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
47.1969 + /* failed to release the reserved lock */
47.1970 + rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
47.1971 + }
47.1972 + }
47.1973 + }
47.1974 + if( locktype==NO_LOCK ){
47.1975 + int failed = _AFPFSSetLock(context->filePath, pFile->h,
47.1976 + SHARED_FIRST + context->sharedLockByte, 1, 0);
47.1977 + if (failed) {
47.1978 + rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
47.1979 + }
47.1980 + }
47.1981 + if (rc == SQLITE_OK)
47.1982 + pFile->locktype = locktype;
47.1983 + sqlite3OsLeaveMutex();
47.1984 + return rc;
47.1985 +}
47.1986 +
47.1987 +/*
47.1988 + ** Close a file & cleanup AFP specific locking context
47.1989 + */
47.1990 +static int afpUnixClose(OsFile **pId) {
47.1991 + unixFile *id = (unixFile*)*pId;
47.1992 +
47.1993 + if( !id ) return SQLITE_OK;
47.1994 + afpUnixUnlock(*pId, NO_LOCK);
47.1995 + /* free the AFP locking structure */
47.1996 + if (id->lockingContext != NULL) {
47.1997 + if (((afpLockingContext *)id->lockingContext)->filePath != NULL)
47.1998 + sqlite3ThreadSafeFree(((afpLockingContext*)id->lockingContext)->filePath);
47.1999 + sqlite3ThreadSafeFree(id->lockingContext);
47.2000 + }
47.2001 +
47.2002 + if( id->dirfd>=0 ) close(id->dirfd);
47.2003 + id->dirfd = -1;
47.2004 + close(id->h);
47.2005 + id->isOpen = 0;
47.2006 + OSTRACE2("CLOSE %-3d\n", id->h);
47.2007 + OpenCounter(-1);
47.2008 + sqlite3ThreadSafeFree(id);
47.2009 + *pId = 0;
47.2010 + return SQLITE_OK;
47.2011 +}
47.2012 +
47.2013 +
47.2014 +#pragma mark flock() style locking
47.2015 +
47.2016 +/*
47.2017 + ** The flockLockingContext is not used
47.2018 + */
47.2019 +typedef void flockLockingContext;
47.2020 +
47.2021 +static int flockUnixCheckReservedLock(OsFile *id) {
47.2022 + unixFile *pFile = (unixFile*)id;
47.2023 +
47.2024 + if (pFile->locktype == RESERVED_LOCK) {
47.2025 + return 1; /* already have a reserved lock */
47.2026 + } else {
47.2027 + /* attempt to get the lock */
47.2028 + int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
47.2029 + if (!rc) {
47.2030 + /* got the lock, unlock it */
47.2031 + flock(pFile->h, LOCK_UN);
47.2032 + return 0; /* no one has it reserved */
47.2033 + }
47.2034 + return 1; /* someone else might have it reserved */
47.2035 + }
47.2036 +}
47.2037 +
47.2038 +static int flockUnixLock(OsFile *id, int locktype) {
47.2039 + unixFile *pFile = (unixFile*)id;
47.2040 +
47.2041 + /* if we already have a lock, it is exclusive.
47.2042 + ** Just adjust level and punt on outta here. */
47.2043 + if (pFile->locktype > NO_LOCK) {
47.2044 + pFile->locktype = locktype;
47.2045 + return SQLITE_OK;
47.2046 + }
47.2047 +
47.2048 + /* grab an exclusive lock */
47.2049 + int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
47.2050 + if (rc) {
47.2051 + /* didn't get, must be busy */
47.2052 + return SQLITE_BUSY;
47.2053 + } else {
47.2054 + /* got it, set the type and return ok */
47.2055 + pFile->locktype = locktype;
47.2056 + return SQLITE_OK;
47.2057 + }
47.2058 +}
47.2059 +
47.2060 +static int flockUnixUnlock(OsFile *id, int locktype) {
47.2061 + unixFile *pFile = (unixFile*)id;
47.2062 +
47.2063 + assert( locktype<=SHARED_LOCK );
47.2064 +
47.2065 + /* no-op if possible */
47.2066 + if( pFile->locktype==locktype ){
47.2067 + return SQLITE_OK;
47.2068 + }
47.2069 +
47.2070 + /* shared can just be set because we always have an exclusive */
47.2071 + if (locktype==SHARED_LOCK) {
47.2072 + pFile->locktype = locktype;
47.2073 + return SQLITE_OK;
47.2074 + }
47.2075 +
47.2076 + /* no, really, unlock. */
47.2077 + int rc = flock(pFile->h, LOCK_UN);
47.2078 + if (rc)
47.2079 + return SQLITE_IOERR_UNLOCK;
47.2080 + else {
47.2081 + pFile->locktype = NO_LOCK;
47.2082 + return SQLITE_OK;
47.2083 + }
47.2084 +}
47.2085 +
47.2086 +/*
47.2087 + ** Close a file.
47.2088 + */
47.2089 +static int flockUnixClose(OsFile **pId) {
47.2090 + unixFile *id = (unixFile*)*pId;
47.2091 +
47.2092 + if( !id ) return SQLITE_OK;
47.2093 + flockUnixUnlock(*pId, NO_LOCK);
47.2094 +
47.2095 + if( id->dirfd>=0 ) close(id->dirfd);
47.2096 + id->dirfd = -1;
47.2097 + sqlite3OsEnterMutex();
47.2098 +
47.2099 + close(id->h);
47.2100 + sqlite3OsLeaveMutex();
47.2101 + id->isOpen = 0;
47.2102 + OSTRACE2("CLOSE %-3d\n", id->h);
47.2103 + OpenCounter(-1);
47.2104 + sqlite3ThreadSafeFree(id);
47.2105 + *pId = 0;
47.2106 + return SQLITE_OK;
47.2107 +}
47.2108 +
47.2109 +#pragma mark Old-School .lock file based locking
47.2110 +
47.2111 +/*
47.2112 + ** The dotlockLockingContext structure contains all dotlock (.lock) lock
47.2113 + ** specific state
47.2114 + */
47.2115 +typedef struct dotlockLockingContext dotlockLockingContext;
47.2116 +struct dotlockLockingContext {
47.2117 + char *lockPath;
47.2118 +};
47.2119 +
47.2120 +
47.2121 +static int dotlockUnixCheckReservedLock(OsFile *id) {
47.2122 + unixFile *pFile = (unixFile*)id;
47.2123 + dotlockLockingContext *context =
47.2124 + (dotlockLockingContext *) pFile->lockingContext;
47.2125 +
47.2126 + if (pFile->locktype == RESERVED_LOCK) {
47.2127 + return 1; /* already have a reserved lock */
47.2128 + } else {
47.2129 + struct stat statBuf;
47.2130 + if (lstat(context->lockPath,&statBuf) == 0)
47.2131 + /* file exists, someone else has the lock */
47.2132 + return 1;
47.2133 + else
47.2134 + /* file does not exist, we could have it if we want it */
47.2135 + return 0;
47.2136 + }
47.2137 +}
47.2138 +
47.2139 +static int dotlockUnixLock(OsFile *id, int locktype) {
47.2140 + unixFile *pFile = (unixFile*)id;
47.2141 + dotlockLockingContext *context =
47.2142 + (dotlockLockingContext *) pFile->lockingContext;
47.2143 +
47.2144 + /* if we already have a lock, it is exclusive.
47.2145 + ** Just adjust level and punt on outta here. */
47.2146 + if (pFile->locktype > NO_LOCK) {
47.2147 + pFile->locktype = locktype;
47.2148 +
47.2149 + /* Always update the timestamp on the old file */
47.2150 + utimes(context->lockPath,NULL);
47.2151 + return SQLITE_OK;
47.2152 + }
47.2153 +
47.2154 + /* check to see if lock file already exists */
47.2155 + struct stat statBuf;
47.2156 + if (lstat(context->lockPath,&statBuf) == 0){
47.2157 + return SQLITE_BUSY; /* it does, busy */
47.2158 + }
47.2159 +
47.2160 + /* grab an exclusive lock */
47.2161 + int fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
47.2162 + if (fd < 0) {
47.2163 + /* failed to open/create the file, someone else may have stolen the lock */
47.2164 + return SQLITE_BUSY;
47.2165 + }
47.2166 + close(fd);
47.2167 +
47.2168 + /* got it, set the type and return ok */
47.2169 + pFile->locktype = locktype;
47.2170 + return SQLITE_OK;
47.2171 +}
47.2172 +
47.2173 +static int dotlockUnixUnlock(OsFile *id, int locktype) {
47.2174 + unixFile *pFile = (unixFile*)id;
47.2175 + dotlockLockingContext *context =
47.2176 + (dotlockLockingContext *) pFile->lockingContext;
47.2177 +
47.2178 + assert( locktype<=SHARED_LOCK );
47.2179 +
47.2180 + /* no-op if possible */
47.2181 + if( pFile->locktype==locktype ){
47.2182 + return SQLITE_OK;
47.2183 + }
47.2184 +
47.2185 + /* shared can just be set because we always have an exclusive */
47.2186 + if (locktype==SHARED_LOCK) {
47.2187 + pFile->locktype = locktype;
47.2188 + return SQLITE_OK;
47.2189 + }
47.2190 +
47.2191 + /* no, really, unlock. */
47.2192 + unlink(context->lockPath);
47.2193 + pFile->locktype = NO_LOCK;
47.2194 + return SQLITE_OK;
47.2195 +}
47.2196 +
47.2197 +/*
47.2198 + ** Close a file.
47.2199 + */
47.2200 +static int dotlockUnixClose(OsFile **pId) {
47.2201 + unixFile *id = (unixFile*)*pId;
47.2202 +
47.2203 + if( !id ) return SQLITE_OK;
47.2204 + dotlockUnixUnlock(*pId, NO_LOCK);
47.2205 + /* free the dotlock locking structure */
47.2206 + if (id->lockingContext != NULL) {
47.2207 + if (((dotlockLockingContext *)id->lockingContext)->lockPath != NULL)
47.2208 + sqlite3ThreadSafeFree( ( (dotlockLockingContext *)
47.2209 + id->lockingContext)->lockPath);
47.2210 + sqlite3ThreadSafeFree(id->lockingContext);
47.2211 + }
47.2212 +
47.2213 + if( id->dirfd>=0 ) close(id->dirfd);
47.2214 + id->dirfd = -1;
47.2215 + sqlite3OsEnterMutex();
47.2216 +
47.2217 + close(id->h);
47.2218 +
47.2219 + sqlite3OsLeaveMutex();
47.2220 + id->isOpen = 0;
47.2221 + OSTRACE2("CLOSE %-3d\n", id->h);
47.2222 + OpenCounter(-1);
47.2223 + sqlite3ThreadSafeFree(id);
47.2224 + *pId = 0;
47.2225 + return SQLITE_OK;
47.2226 +}
47.2227 +
47.2228 +
47.2229 +#pragma mark No locking
47.2230 +
47.2231 +/*
47.2232 + ** The nolockLockingContext is void
47.2233 + */
47.2234 +typedef void nolockLockingContext;
47.2235 +
47.2236 +static int nolockUnixCheckReservedLock(OsFile *id) {
47.2237 + return 0;
47.2238 +}
47.2239 +
47.2240 +static int nolockUnixLock(OsFile *id, int locktype) {
47.2241 + return SQLITE_OK;
47.2242 +}
47.2243 +
47.2244 +static int nolockUnixUnlock(OsFile *id, int locktype) {
47.2245 + return SQLITE_OK;
47.2246 +}
47.2247 +
47.2248 +/*
47.2249 + ** Close a file.
47.2250 + */
47.2251 +static int nolockUnixClose(OsFile **pId) {
47.2252 + unixFile *id = (unixFile*)*pId;
47.2253 +
47.2254 + if( !id ) return SQLITE_OK;
47.2255 + if( id->dirfd>=0 ) close(id->dirfd);
47.2256 + id->dirfd = -1;
47.2257 + sqlite3OsEnterMutex();
47.2258 +
47.2259 + close(id->h);
47.2260 +
47.2261 + sqlite3OsLeaveMutex();
47.2262 + id->isOpen = 0;
47.2263 + OSTRACE2("CLOSE %-3d\n", id->h);
47.2264 + OpenCounter(-1);
47.2265 + sqlite3ThreadSafeFree(id);
47.2266 + *pId = 0;
47.2267 + return SQLITE_OK;
47.2268 +}
47.2269 +
47.2270 +#endif /* SQLITE_ENABLE_LOCKING_STYLE */
47.2271 +
47.2272 +/*
47.2273 +** Turn a relative pathname into a full pathname. Return a pointer
47.2274 +** to the full pathname stored in space obtained from sqliteMalloc().
47.2275 +** The calling function is responsible for freeing this space once it
47.2276 +** is no longer needed.
47.2277 +*/
47.2278 +char *sqlite3UnixFullPathname(const char *zRelative){
47.2279 + char *zFull = 0;
47.2280 + if( zRelative[0]=='/' ){
47.2281 + sqlite3SetString(&zFull, zRelative, (char*)0);
47.2282 + }else{
47.2283 + char *zBuf = sqliteMalloc(5000);
47.2284 + if( zBuf==0 ){
47.2285 + return 0;
47.2286 + }
47.2287 + zBuf[0] = 0;
47.2288 + sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
47.2289 + (char*)0);
47.2290 + sqliteFree(zBuf);
47.2291 + }
47.2292 +
47.2293 +#if 0
47.2294 + /*
47.2295 + ** Remove "/./" path elements and convert "/A/./" path elements
47.2296 + ** to just "/".
47.2297 + */
47.2298 + if( zFull ){
47.2299 + int i, j;
47.2300 + for(i=j=0; zFull[i]; i++){
47.2301 + if( zFull[i]=='/' ){
47.2302 + if( zFull[i+1]=='/' ) continue;
47.2303 + if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
47.2304 + i += 1;
47.2305 + continue;
47.2306 + }
47.2307 + if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
47.2308 + while( j>0 && zFull[j-1]!='/' ){ j--; }
47.2309 + i += 3;
47.2310 + continue;
47.2311 + }
47.2312 + }
47.2313 + zFull[j++] = zFull[i];
47.2314 + }
47.2315 + zFull[j] = 0;
47.2316 + }
47.2317 +#endif
47.2318 +
47.2319 + return zFull;
47.2320 +}
47.2321 +
47.2322 +/*
47.2323 +** Change the value of the fullsync flag in the given file descriptor.
47.2324 +*/
47.2325 +static void unixSetFullSync(OsFile *id, int v){
47.2326 + ((unixFile*)id)->fullSync = v;
47.2327 +}
47.2328 +
47.2329 +/*
47.2330 +** Return the underlying file handle for an OsFile
47.2331 +*/
47.2332 +static int unixFileHandle(OsFile *id){
47.2333 + return ((unixFile*)id)->h;
47.2334 +}
47.2335 +
47.2336 +/*
47.2337 +** Return an integer that indices the type of lock currently held
47.2338 +** by this handle. (Used for testing and analysis only.)
47.2339 +*/
47.2340 +static int unixLockState(OsFile *id){
47.2341 + return ((unixFile*)id)->locktype;
47.2342 +}
47.2343 +
47.2344 +/*
47.2345 +** Return the sector size in bytes of the underlying block device for
47.2346 +** the specified file. This is almost always 512 bytes, but may be
47.2347 +** larger for some devices.
47.2348 +**
47.2349 +** SQLite code assumes this function cannot fail. It also assumes that
47.2350 +** if two files are created in the same file-system directory (i.e.
47.2351 +** a database and it's journal file) that the sector size will be the
47.2352 +** same for both.
47.2353 +*/
47.2354 +static int unixSectorSize(OsFile *id){
47.2355 + return SQLITE_DEFAULT_SECTOR_SIZE;
47.2356 +}
47.2357 +
47.2358 +/*
47.2359 +** This vector defines all the methods that can operate on an OsFile
47.2360 +** for unix.
47.2361 +*/
47.2362 +static const IoMethod sqlite3UnixIoMethod = {
47.2363 + unixClose,
47.2364 + unixOpenDirectory,
47.2365 + unixRead,
47.2366 + unixWrite,
47.2367 + unixSeek,
47.2368 + unixTruncate,
47.2369 + unixSync,
47.2370 + unixSetFullSync,
47.2371 + unixFileHandle,
47.2372 + unixFileSize,
47.2373 + unixLock,
47.2374 + unixUnlock,
47.2375 + unixLockState,
47.2376 + unixCheckReservedLock,
47.2377 + unixSectorSize,
47.2378 +};
47.2379 +
47.2380 +#ifdef SQLITE_ENABLE_LOCKING_STYLE
47.2381 +/*
47.2382 + ** This vector defines all the methods that can operate on an OsFile
47.2383 + ** for unix with AFP style file locking.
47.2384 + */
47.2385 +static const IoMethod sqlite3AFPLockingUnixIoMethod = {
47.2386 + afpUnixClose,
47.2387 + unixOpenDirectory,
47.2388 + unixRead,
47.2389 + unixWrite,
47.2390 + unixSeek,
47.2391 + unixTruncate,
47.2392 + unixSync,
47.2393 + unixSetFullSync,
47.2394 + unixFileHandle,
47.2395 + unixFileSize,
47.2396 + afpUnixLock,
47.2397 + afpUnixUnlock,
47.2398 + unixLockState,
47.2399 + afpUnixCheckReservedLock,
47.2400 + unixSectorSize,
47.2401 +};
47.2402 +
47.2403 +/*
47.2404 + ** This vector defines all the methods that can operate on an OsFile
47.2405 + ** for unix with flock() style file locking.
47.2406 + */
47.2407 +static const IoMethod sqlite3FlockLockingUnixIoMethod = {
47.2408 + flockUnixClose,
47.2409 + unixOpenDirectory,
47.2410 + unixRead,
47.2411 + unixWrite,
47.2412 + unixSeek,
47.2413 + unixTruncate,
47.2414 + unixSync,
47.2415 + unixSetFullSync,
47.2416 + unixFileHandle,
47.2417 + unixFileSize,
47.2418 + flockUnixLock,
47.2419 + flockUnixUnlock,
47.2420 + unixLockState,
47.2421 + flockUnixCheckReservedLock,
47.2422 + unixSectorSize,
47.2423 +};
47.2424 +
47.2425 +/*
47.2426 + ** This vector defines all the methods that can operate on an OsFile
47.2427 + ** for unix with dotlock style file locking.
47.2428 + */
47.2429 +static const IoMethod sqlite3DotlockLockingUnixIoMethod = {
47.2430 + dotlockUnixClose,
47.2431 + unixOpenDirectory,
47.2432 + unixRead,
47.2433 + unixWrite,
47.2434 + unixSeek,
47.2435 + unixTruncate,
47.2436 + unixSync,
47.2437 + unixSetFullSync,
47.2438 + unixFileHandle,
47.2439 + unixFileSize,
47.2440 + dotlockUnixLock,
47.2441 + dotlockUnixUnlock,
47.2442 + unixLockState,
47.2443 + dotlockUnixCheckReservedLock,
47.2444 + unixSectorSize,
47.2445 +};
47.2446 +
47.2447 +/*
47.2448 + ** This vector defines all the methods that can operate on an OsFile
47.2449 + ** for unix with dotlock style file locking.
47.2450 + */
47.2451 +static const IoMethod sqlite3NolockLockingUnixIoMethod = {
47.2452 + nolockUnixClose,
47.2453 + unixOpenDirectory,
47.2454 + unixRead,
47.2455 + unixWrite,
47.2456 + unixSeek,
47.2457 + unixTruncate,
47.2458 + unixSync,
47.2459 + unixSetFullSync,
47.2460 + unixFileHandle,
47.2461 + unixFileSize,
47.2462 + nolockUnixLock,
47.2463 + nolockUnixUnlock,
47.2464 + unixLockState,
47.2465 + nolockUnixCheckReservedLock,
47.2466 + unixSectorSize,
47.2467 +};
47.2468 +
47.2469 +#endif /* SQLITE_ENABLE_LOCKING_STYLE */
47.2470 +
47.2471 +/*
47.2472 +** Allocate memory for a new unixFile and initialize that unixFile.
47.2473 +** Write a pointer to the new unixFile into *pId.
47.2474 +** If we run out of memory, close the file and return an error.
47.2475 +*/
47.2476 +#ifdef SQLITE_ENABLE_LOCKING_STYLE
47.2477 +/*
47.2478 + ** When locking extensions are enabled, the filepath and locking style
47.2479 + ** are needed to determine the unixFile pMethod to use for locking operations.
47.2480 + ** The locking-style specific lockingContext data structure is created
47.2481 + ** and assigned here also.
47.2482 + */
47.2483 +static int allocateUnixFile(
47.2484 + int h, /* Open file descriptor of file being opened */
47.2485 + OsFile **pId, /* Write completed initialization here */
47.2486 + const char *zFilename, /* Name of the file being opened */
47.2487 + int delFlag /* Delete-on-or-before-close flag */
47.2488 +){
47.2489 + sqlite3LockingStyle lockingStyle;
47.2490 + unixFile *pNew;
47.2491 + unixFile f;
47.2492 + int rc;
47.2493 +
47.2494 + memset(&f, 0, sizeof(f));
47.2495 + lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
47.2496 + if ( lockingStyle == posixLockingStyle ) {
47.2497 + sqlite3OsEnterMutex();
47.2498 + rc = findLockInfo(h, &f.pLock, &f.pOpen);
47.2499 + sqlite3OsLeaveMutex();
47.2500 + if( rc ){
47.2501 + close(h);
47.2502 + unlink(zFilename);
47.2503 + return SQLITE_NOMEM;
47.2504 + }
47.2505 + } else {
47.2506 + /* pLock and pOpen are only used for posix advisory locking */
47.2507 + f.pLock = NULL;
47.2508 + f.pOpen = NULL;
47.2509 + }
47.2510 + if( delFlag ){
47.2511 + unlink(zFilename);
47.2512 + }
47.2513 + f.dirfd = -1;
47.2514 + f.h = h;
47.2515 + SET_THREADID(&f);
47.2516 + pNew = sqlite3ThreadSafeMalloc( sizeof(unixFile) );
47.2517 + if( pNew==0 ){
47.2518 + close(h);
47.2519 + sqlite3OsEnterMutex();
47.2520 + releaseLockInfo(f.pLock);
47.2521 + releaseOpenCnt(f.pOpen);
47.2522 + sqlite3OsLeaveMutex();
47.2523 + *pId = 0;
47.2524 + return SQLITE_NOMEM;
47.2525 + }else{
47.2526 + *pNew = f;
47.2527 + switch(lockingStyle) {
47.2528 + case afpLockingStyle: {
47.2529 + /* afp locking uses the file path so it needs to be included in
47.2530 + ** the afpLockingContext */
47.2531 + int nFilename;
47.2532 + pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
47.2533 + pNew->lockingContext =
47.2534 + sqlite3ThreadSafeMalloc(sizeof(afpLockingContext));
47.2535 + nFilename = strlen(zFilename)+1;
47.2536 + ((afpLockingContext *)pNew->lockingContext)->filePath =
47.2537 + sqlite3ThreadSafeMalloc(nFilename);
47.2538 + memcpy(((afpLockingContext *)pNew->lockingContext)->filePath,
47.2539 + zFilename, nFilename);
47.2540 + srandomdev();
47.2541 + break;
47.2542 + }
47.2543 + case flockLockingStyle:
47.2544 + /* flock locking doesn't need additional lockingContext information */
47.2545 + pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
47.2546 + break;
47.2547 + case dotlockLockingStyle: {
47.2548 + /* dotlock locking uses the file path so it needs to be included in
47.2549 + ** the dotlockLockingContext */
47.2550 + int nFilename;
47.2551 + pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
47.2552 + pNew->lockingContext = sqlite3ThreadSafeMalloc(
47.2553 + sizeof(dotlockLockingContext));
47.2554 + nFilename = strlen(zFilename) + 6;
47.2555 + ((dotlockLockingContext *)pNew->lockingContext)->lockPath =
47.2556 + sqlite3ThreadSafeMalloc( nFilename );
47.2557 + sqlite3_snprintf(nFilename,
47.2558 + ((dotlockLockingContext *)pNew->lockingContext)->lockPath,
47.2559 + "%s.lock", zFilename);
47.2560 + break;
47.2561 + }
47.2562 + case posixLockingStyle:
47.2563 + /* posix locking doesn't need additional lockingContext information */
47.2564 + pNew->pMethod = &sqlite3UnixIoMethod;
47.2565 + break;
47.2566 + case noLockingStyle:
47.2567 + case unsupportedLockingStyle:
47.2568 + default:
47.2569 + pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
47.2570 + }
47.2571 + *pId = (OsFile*)pNew;
47.2572 + OpenCounter(+1);
47.2573 + return SQLITE_OK;
47.2574 + }
47.2575 +}
47.2576 +#else /* SQLITE_ENABLE_LOCKING_STYLE */
47.2577 +static int allocateUnixFile(
47.2578 + int h, /* Open file descriptor on file being opened */
47.2579 + OsFile **pId, /* Write the resul unixFile structure here */
47.2580 + const char *zFilename, /* Name of the file being opened */
47.2581 + int delFlag /* If true, delete the file on or before closing */
47.2582 +){
47.2583 + unixFile *pNew;
47.2584 + unixFile f;
47.2585 + int rc;
47.2586 +
47.2587 +#ifdef FD_CLOEXEC
47.2588 + fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
47.2589 +#endif
47.2590 + memset(&f, 0, sizeof(f));
47.2591 + sqlite3OsEnterMutex();
47.2592 + rc = findLockInfo(h, &f.pLock, &f.pOpen);
47.2593 + sqlite3OsLeaveMutex();
47.2594 + if( delFlag ){
47.2595 + unlink(zFilename);
47.2596 + }
47.2597 + if( rc ){
47.2598 + close(h);
47.2599 + return SQLITE_NOMEM;
47.2600 + }
47.2601 + OSTRACE3("OPEN %-3d %s\n", h, zFilename);
47.2602 + f.dirfd = -1;
47.2603 + f.h = h;
47.2604 + SET_THREADID(&f);
47.2605 + pNew = sqlite3ThreadSafeMalloc( sizeof(unixFile) );
47.2606 + if( pNew==0 ){
47.2607 + close(h);
47.2608 + sqlite3OsEnterMutex();
47.2609 + releaseLockInfo(f.pLock);
47.2610 + releaseOpenCnt(f.pOpen);
47.2611 + sqlite3OsLeaveMutex();
47.2612 + *pId = 0;
47.2613 + return SQLITE_NOMEM;
47.2614 + }else{
47.2615 + *pNew = f;
47.2616 + pNew->pMethod = &sqlite3UnixIoMethod;
47.2617 + *pId = (OsFile*)pNew;
47.2618 + OpenCounter(+1);
47.2619 + return SQLITE_OK;
47.2620 + }
47.2621 +}
47.2622 +#endif /* SQLITE_ENABLE_LOCKING_STYLE */
47.2623 +
47.2624 +#endif /* SQLITE_OMIT_DISKIO */
47.2625 +/***************************************************************************
47.2626 +** Everything above deals with file I/O. Everything that follows deals
47.2627 +** with other miscellanous aspects of the operating system interface
47.2628 +****************************************************************************/
47.2629 +
47.2630 +
47.2631 +#ifndef SQLITE_OMIT_LOAD_EXTENSION
47.2632 +/*
47.2633 +** Interfaces for opening a shared library, finding entry points
47.2634 +** within the shared library, and closing the shared library.
47.2635 +*/
47.2636 +#include <dlfcn.h>
47.2637 +void *sqlite3UnixDlopen(const char *zFilename){
47.2638 + return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
47.2639 +}
47.2640 +void *sqlite3UnixDlsym(void *pHandle, const char *zSymbol){
47.2641 + return dlsym(pHandle, zSymbol);
47.2642 +}
47.2643 +int sqlite3UnixDlclose(void *pHandle){
47.2644 + return dlclose(pHandle);
47.2645 +}
47.2646 +#endif /* SQLITE_OMIT_LOAD_EXTENSION */
47.2647 +
47.2648 +/*
47.2649 +** Get information to seed the random number generator. The seed
47.2650 +** is written into the buffer zBuf[256]. The calling function must
47.2651 +** supply a sufficiently large buffer.
47.2652 +*/
47.2653 +int sqlite3UnixRandomSeed(char *zBuf){
47.2654 + /* We have to initialize zBuf to prevent valgrind from reporting
47.2655 + ** errors. The reports issued by valgrind are incorrect - we would
47.2656 + ** prefer that the randomness be increased by making use of the
47.2657 + ** uninitialized space in zBuf - but valgrind errors tend to worry
47.2658 + ** some users. Rather than argue, it seems easier just to initialize
47.2659 + ** the whole array and silence valgrind, even if that means less randomness
47.2660 + ** in the random seed.
47.2661 + **
47.2662 + ** When testing, initializing zBuf[] to zero is all we do. That means
47.2663 + ** that we always use the same random number sequence. This makes the
47.2664 + ** tests repeatable.
47.2665 + */
47.2666 + memset(zBuf, 0, 256);
47.2667 +#if !defined(SQLITE_TEST)
47.2668 + {
47.2669 + int pid, fd;
47.2670 + fd = open("/dev/urandom", O_RDONLY);
47.2671 + if( fd<0 ){
47.2672 + time_t t;
47.2673 + time(&t);
47.2674 + memcpy(zBuf, &t, sizeof(t));
47.2675 + pid = getpid();
47.2676 + memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
47.2677 + }else{
47.2678 + read(fd, zBuf, 256);
47.2679 + close(fd);
47.2680 + }
47.2681 + }
47.2682 +#endif
47.2683 + return SQLITE_OK;
47.2684 +}
47.2685 +
47.2686 +/*
47.2687 +** Sleep for a little while. Return the amount of time slept.
47.2688 +** The argument is the number of milliseconds we want to sleep.
47.2689 +*/
47.2690 +int sqlite3UnixSleep(int ms){
47.2691 +#if defined(HAVE_USLEEP) && HAVE_USLEEP
47.2692 + usleep(ms*1000);
47.2693 + return ms;
47.2694 +#else
47.2695 + sleep((ms+999)/1000);
47.2696 + return 1000*((ms+999)/1000);
47.2697 +#endif
47.2698 +}
47.2699 +
47.2700 +/*
47.2701 +** Static variables used for thread synchronization.
47.2702 +**
47.2703 +** inMutex the nesting depth of the recursive mutex. The thread
47.2704 +** holding mutexMain can read this variable at any time.
47.2705 +** But is must hold mutexAux to change this variable. Other
47.2706 +** threads must hold mutexAux to read the variable and can
47.2707 +** never write.
47.2708 +**
47.2709 +** mutexOwner The thread id of the thread holding mutexMain. Same
47.2710 +** access rules as for inMutex.
47.2711 +**
47.2712 +** mutexOwnerValid True if the value in mutexOwner is valid. The same
47.2713 +** access rules apply as for inMutex.
47.2714 +**
47.2715 +** mutexMain The main mutex. Hold this mutex in order to get exclusive
47.2716 +** access to SQLite data structures.
47.2717 +**
47.2718 +** mutexAux An auxiliary mutex needed to access variables defined above.
47.2719 +**
47.2720 +** Mutexes are always acquired in this order: mutexMain mutexAux. It
47.2721 +** is not necessary to acquire mutexMain in order to get mutexAux - just
47.2722 +** do not attempt to acquire them in the reverse order: mutexAux mutexMain.
47.2723 +** Either get the mutexes with mutexMain first or get mutexAux only.
47.2724 +**
47.2725 +** When running on a platform where the three variables inMutex, mutexOwner,
47.2726 +** and mutexOwnerValid can be set atomically, the mutexAux is not required.
47.2727 +** On many systems, all three are 32-bit integers and writing to a 32-bit
47.2728 +** integer is atomic. I think. But there are no guarantees. So it seems
47.2729 +** safer to protect them using mutexAux.
47.2730 +*/
47.2731 +static int inMutex = 0;
47.2732 +#ifdef SQLITE_UNIX_THREADS
47.2733 +static pthread_t mutexOwner; /* Thread holding mutexMain */
47.2734 +static int mutexOwnerValid = 0; /* True if mutexOwner is valid */
47.2735 +static pthread_mutex_t mutexMain = PTHREAD_MUTEX_INITIALIZER; /* The mutex */
47.2736 +static pthread_mutex_t mutexAux = PTHREAD_MUTEX_INITIALIZER; /* Aux mutex */
47.2737 +#endif
47.2738 +
47.2739 +/*
47.2740 +** The following pair of routine implement mutual exclusion for
47.2741 +** multi-threaded processes. Only a single thread is allowed to
47.2742 +** executed code that is surrounded by EnterMutex() and LeaveMutex().
47.2743 +**
47.2744 +** SQLite uses only a single Mutex. There is not much critical
47.2745 +** code and what little there is executes quickly and without blocking.
47.2746 +**
47.2747 +** As of version 3.3.2, this mutex must be recursive.
47.2748 +*/
47.2749 +void sqlite3UnixEnterMutex(){
47.2750 +#ifdef SQLITE_UNIX_THREADS
47.2751 + pthread_mutex_lock(&mutexAux);
47.2752 + if( !mutexOwnerValid || !pthread_equal(mutexOwner, pthread_self()) ){
47.2753 + pthread_mutex_unlock(&mutexAux);
47.2754 + pthread_mutex_lock(&mutexMain);
47.2755 + assert( inMutex==0 );
47.2756 + assert( !mutexOwnerValid );
47.2757 + pthread_mutex_lock(&mutexAux);
47.2758 + mutexOwner = pthread_self();
47.2759 + mutexOwnerValid = 1;
47.2760 + }
47.2761 + inMutex++;
47.2762 + pthread_mutex_unlock(&mutexAux);
47.2763 +#else
47.2764 + inMutex++;
47.2765 +#endif
47.2766 +}
47.2767 +void sqlite3UnixLeaveMutex(){
47.2768 + assert( inMutex>0 );
47.2769 +#ifdef SQLITE_UNIX_THREADS
47.2770 + pthread_mutex_lock(&mutexAux);
47.2771 + inMutex--;
47.2772 + assert( pthread_equal(mutexOwner, pthread_self()) );
47.2773 + if( inMutex==0 ){
47.2774 + assert( mutexOwnerValid );
47.2775 + mutexOwnerValid = 0;
47.2776 + pthread_mutex_unlock(&mutexMain);
47.2777 + }
47.2778 + pthread_mutex_unlock(&mutexAux);
47.2779 +#else
47.2780 + inMutex--;
47.2781 +#endif
47.2782 +}
47.2783 +
47.2784 +/*
47.2785 +** Return TRUE if the mutex is currently held.
47.2786 +**
47.2787 +** If the thisThrd parameter is true, return true only if the
47.2788 +** calling thread holds the mutex. If the parameter is false, return
47.2789 +** true if any thread holds the mutex.
47.2790 +*/
47.2791 +int sqlite3UnixInMutex(int thisThrd){
47.2792 +#ifdef SQLITE_UNIX_THREADS
47.2793 + int rc;
47.2794 + pthread_mutex_lock(&mutexAux);
47.2795 + rc = inMutex>0 && (thisThrd==0 || pthread_equal(mutexOwner,pthread_self()));
47.2796 + pthread_mutex_unlock(&mutexAux);
47.2797 + return rc;
47.2798 +#else
47.2799 + return inMutex>0;
47.2800 +#endif
47.2801 +}
47.2802 +
47.2803 +/*
47.2804 +** Remember the number of thread-specific-data blocks allocated.
47.2805 +** Use this to verify that we are not leaking thread-specific-data.
47.2806 +** Ticket #1601
47.2807 +*/
47.2808 +#ifdef SQLITE_TEST
47.2809 +int sqlite3_tsd_count = 0;
47.2810 +# ifdef SQLITE_UNIX_THREADS
47.2811 + static pthread_mutex_t tsd_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
47.2812 +# define TSD_COUNTER(N) \
47.2813 + pthread_mutex_lock(&tsd_counter_mutex); \
47.2814 + sqlite3_tsd_count += N; \
47.2815 + pthread_mutex_unlock(&tsd_counter_mutex);
47.2816 +# else
47.2817 +# define TSD_COUNTER(N) sqlite3_tsd_count += N
47.2818 +# endif
47.2819 +#else
47.2820 +# define TSD_COUNTER(N) /* no-op */
47.2821 +#endif
47.2822 +
47.2823 +/*
47.2824 +** If called with allocateFlag>0, then return a pointer to thread
47.2825 +** specific data for the current thread. Allocate and zero the
47.2826 +** thread-specific data if it does not already exist.
47.2827 +**
47.2828 +** If called with allocateFlag==0, then check the current thread
47.2829 +** specific data. Return it if it exists. If it does not exist,
47.2830 +** then return NULL.
47.2831 +**
47.2832 +** If called with allocateFlag<0, check to see if the thread specific
47.2833 +** data is allocated and is all zero. If it is then deallocate it.
47.2834 +** Return a pointer to the thread specific data or NULL if it is
47.2835 +** unallocated or gets deallocated.
47.2836 +*/
47.2837 +ThreadData *sqlite3UnixThreadSpecificData(int allocateFlag){
47.2838 + static const ThreadData zeroData = {0}; /* Initializer to silence warnings
47.2839 + ** from broken compilers */
47.2840 +#ifdef SQLITE_UNIX_THREADS
47.2841 + static pthread_key_t key;
47.2842 + static int keyInit = 0;
47.2843 + ThreadData *pTsd;
47.2844 +
47.2845 + if( !keyInit ){
47.2846 + sqlite3OsEnterMutex();
47.2847 + if( !keyInit ){
47.2848 + int rc;
47.2849 + rc = pthread_key_create(&key, 0);
47.2850 + if( rc ){
47.2851 + sqlite3OsLeaveMutex();
47.2852 + return 0;
47.2853 + }
47.2854 + keyInit = 1;
47.2855 + }
47.2856 + sqlite3OsLeaveMutex();
47.2857 + }
47.2858 +
47.2859 + pTsd = pthread_getspecific(key);
47.2860 + if( allocateFlag>0 ){
47.2861 + if( pTsd==0 ){
47.2862 + if( !sqlite3TestMallocFail() ){
47.2863 + pTsd = sqlite3OsMalloc(sizeof(zeroData));
47.2864 + }
47.2865 +#ifdef SQLITE_MEMDEBUG
47.2866 + sqlite3_isFail = 0;
47.2867 +#endif
47.2868 + if( pTsd ){
47.2869 + *pTsd = zeroData;
47.2870 + pthread_setspecific(key, pTsd);
47.2871 + TSD_COUNTER(+1);
47.2872 + }
47.2873 + }
47.2874 + }else if( pTsd!=0 && allocateFlag<0
47.2875 + && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
47.2876 + sqlite3OsFree(pTsd);
47.2877 + pthread_setspecific(key, 0);
47.2878 + TSD_COUNTER(-1);
47.2879 + pTsd = 0;
47.2880 + }
47.2881 + return pTsd;
47.2882 +#else
47.2883 + static ThreadData *pTsd = 0;
47.2884 + if( allocateFlag>0 ){
47.2885 + if( pTsd==0 ){
47.2886 + if( !sqlite3TestMallocFail() ){
47.2887 + pTsd = sqlite3OsMalloc( sizeof(zeroData) );
47.2888 + }
47.2889 +#ifdef SQLITE_MEMDEBUG
47.2890 + sqlite3_isFail = 0;
47.2891 +#endif
47.2892 + if( pTsd ){
47.2893 + *pTsd = zeroData;
47.2894 + TSD_COUNTER(+1);
47.2895 + }
47.2896 + }
47.2897 + }else if( pTsd!=0 && allocateFlag<0
47.2898 + && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
47.2899 + sqlite3OsFree(pTsd);
47.2900 + TSD_COUNTER(-1);
47.2901 + pTsd = 0;
47.2902 + }
47.2903 + return pTsd;
47.2904 +#endif
47.2905 +}
47.2906 +
47.2907 +/*
47.2908 +** The following variable, if set to a non-zero value, becomes the result
47.2909 +** returned from sqlite3OsCurrentTime(). This is used for testing.
47.2910 +*/
47.2911 +#ifdef SQLITE_TEST
47.2912 +int sqlite3_current_time = 0;
47.2913 +#endif
47.2914 +
47.2915 +/*
47.2916 +** Find the current time (in Universal Coordinated Time). Write the
47.2917 +** current time and date as a Julian Day number into *prNow and
47.2918 +** return 0. Return 1 if the time and date cannot be found.
47.2919 +*/
47.2920 +int sqlite3UnixCurrentTime(double *prNow){
47.2921 +#ifdef NO_GETTOD
47.2922 + time_t t;
47.2923 + time(&t);
47.2924 + *prNow = t/86400.0 + 2440587.5;
47.2925 +#else
47.2926 + struct timeval sNow;
47.2927 + gettimeofday(&sNow, 0);
47.2928 + *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
47.2929 +#endif
47.2930 +#ifdef SQLITE_TEST
47.2931 + if( sqlite3_current_time ){
47.2932 + *prNow = sqlite3_current_time/86400.0 + 2440587.5;
47.2933 + }
47.2934 +#endif
47.2935 + return 0;
47.2936 +}
47.2937 +
47.2938 +#endif /* OS_UNIX */
48.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
48.2 +++ b/extensions/sqlite/sqlite-source/os_win.c Sun Jul 29 01:15:31 2007 +0000
48.3 @@ -0,0 +1,1758 @@
48.4 +/*
48.5 +** 2004 May 22
48.6 +**
48.7 +** The author disclaims copyright to this source code. In place of
48.8 +** a legal notice, here is a blessing:
48.9 +**
48.10 +** May you do good and not evil.
48.11 +** May you find forgiveness for yourself and forgive others.
48.12 +** May you share freely, never taking more than you give.
48.13 +**
48.14 +******************************************************************************
48.15 +**
48.16 +** This file contains code that is specific to windows.
48.17 +*/
48.18 +#include "sqliteInt.h"
48.19 +#include "os.h"
48.20 +#if OS_WIN /* This file is used for windows only */
48.21 +
48.22 +#include <winbase.h>
48.23 +
48.24 +#ifdef __CYGWIN__
48.25 +# include <sys/cygwin.h>
48.26 +#endif
48.27 +
48.28 +/*
48.29 +** Macros used to determine whether or not to use threads.
48.30 +*/
48.31 +#if defined(THREADSAFE) && THREADSAFE
48.32 +# define SQLITE_W32_THREADS 1
48.33 +#endif
48.34 +
48.35 +/*
48.36 +** Include code that is common to all os_*.c files
48.37 +*/
48.38 +#include "os_common.h"
48.39 +
48.40 +/*
48.41 +** Determine if we are dealing with WindowsCE - which has a much
48.42 +** reduced API.
48.43 +*/
48.44 +#if defined(_WIN32_WCE)
48.45 +# define OS_WINCE 1
48.46 +# define AreFileApisANSI() 1
48.47 +#else
48.48 +# define OS_WINCE 0
48.49 +#endif
48.50 +
48.51 +/*
48.52 +** WinCE lacks native support for file locking so we have to fake it
48.53 +** with some code of our own.
48.54 +*/
48.55 +#if OS_WINCE
48.56 +typedef struct winceLock {
48.57 + int nReaders; /* Number of reader locks obtained */
48.58 + BOOL bPending; /* Indicates a pending lock has been obtained */
48.59 + BOOL bReserved; /* Indicates a reserved lock has been obtained */
48.60 + BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
48.61 +} winceLock;
48.62 +#endif
48.63 +
48.64 +/*
48.65 +** The winFile structure is a subclass of OsFile specific to the win32
48.66 +** portability layer.
48.67 +*/
48.68 +typedef struct winFile winFile;
48.69 +struct winFile {
48.70 + IoMethod const *pMethod;/* Must be first */
48.71 + HANDLE h; /* Handle for accessing the file */
48.72 + unsigned char locktype; /* Type of lock currently held on this file */
48.73 + short sharedLockByte; /* Randomly chosen byte used as a shared lock */
48.74 +#if OS_WINCE
48.75 + WCHAR *zDeleteOnClose; /* Name of file to delete when closing */
48.76 + HANDLE hMutex; /* Mutex used to control access to shared lock */
48.77 + HANDLE hShared; /* Shared memory segment used for locking */
48.78 + winceLock local; /* Locks obtained by this instance of winFile */
48.79 + winceLock *shared; /* Global shared lock memory for the file */
48.80 +#endif
48.81 +};
48.82 +
48.83 +
48.84 +/*
48.85 +** Do not include any of the File I/O interface procedures if the
48.86 +** SQLITE_OMIT_DISKIO macro is defined (indicating that there database
48.87 +** will be in-memory only)
48.88 +*/
48.89 +#ifndef SQLITE_OMIT_DISKIO
48.90 +
48.91 +/*
48.92 +** The following variable is (normally) set once and never changes
48.93 +** thereafter. It records whether the operating system is Win95
48.94 +** or WinNT.
48.95 +**
48.96 +** 0: Operating system unknown.
48.97 +** 1: Operating system is Win95.
48.98 +** 2: Operating system is WinNT.
48.99 +**
48.100 +** In order to facilitate testing on a WinNT system, the test fixture
48.101 +** can manually set this value to 1 to emulate Win98 behavior.
48.102 +*/
48.103 +int sqlite3_os_type = 0;
48.104 +
48.105 +/*
48.106 +** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
48.107 +** or WinCE. Return false (zero) for Win95, Win98, or WinME.
48.108 +**
48.109 +** Here is an interesting observation: Win95, Win98, and WinME lack
48.110 +** the LockFileEx() API. But we can still statically link against that
48.111 +** API as long as we don't call it win running Win95/98/ME. A call to
48.112 +** this routine is used to determine if the host is Win95/98/ME or
48.113 +** WinNT/2K/XP so that we will know whether or not we can safely call
48.114 +** the LockFileEx() API.
48.115 +*/
48.116 +#if OS_WINCE
48.117 +# define isNT() (1)
48.118 +#else
48.119 + static int isNT(void){
48.120 + if( sqlite3_os_type==0 ){
48.121 + OSVERSIONINFO sInfo;
48.122 + sInfo.dwOSVersionInfoSize = sizeof(sInfo);
48.123 + GetVersionEx(&sInfo);
48.124 + sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
48.125 + }
48.126 + return sqlite3_os_type==2;
48.127 + }
48.128 +#endif /* OS_WINCE */
48.129 +
48.130 +/*
48.131 +** Convert a UTF-8 string to microsoft unicode (UTF-16?).
48.132 +**
48.133 +** Space to hold the returned string is obtained from sqliteMalloc.
48.134 +*/
48.135 +static WCHAR *utf8ToUnicode(const char *zFilename){
48.136 + int nChar;
48.137 + WCHAR *zWideFilename;
48.138 +
48.139 + nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
48.140 + zWideFilename = sqliteMalloc( nChar*sizeof(zWideFilename[0]) );
48.141 + if( zWideFilename==0 ){
48.142 + return 0;
48.143 + }
48.144 + nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
48.145 + if( nChar==0 ){
48.146 + sqliteFree(zWideFilename);
48.147 + zWideFilename = 0;
48.148 + }
48.149 + return zWideFilename;
48.150 +}
48.151 +
48.152 +/*
48.153 +** Convert microsoft unicode to UTF-8. Space to hold the returned string is
48.154 +** obtained from sqliteMalloc().
48.155 +*/
48.156 +static char *unicodeToUtf8(const WCHAR *zWideFilename){
48.157 + int nByte;
48.158 + char *zFilename;
48.159 +
48.160 + nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
48.161 + zFilename = sqliteMalloc( nByte );
48.162 + if( zFilename==0 ){
48.163 + return 0;
48.164 + }
48.165 + nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
48.166 + 0, 0);
48.167 + if( nByte == 0 ){
48.168 + sqliteFree(zFilename);
48.169 + zFilename = 0;
48.170 + }
48.171 + return zFilename;
48.172 +}
48.173 +
48.174 +/*
48.175 +** Convert an ansi string to microsoft unicode, based on the
48.176 +** current codepage settings for file apis.
48.177 +**
48.178 +** Space to hold the returned string is obtained
48.179 +** from sqliteMalloc.
48.180 +*/
48.181 +static WCHAR *mbcsToUnicode(const char *zFilename){
48.182 + int nByte;
48.183 + WCHAR *zMbcsFilename;
48.184 + int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
48.185 +
48.186 + nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
48.187 + zMbcsFilename = sqliteMalloc( nByte*sizeof(zMbcsFilename[0]) );
48.188 + if( zMbcsFilename==0 ){
48.189 + return 0;
48.190 + }
48.191 + nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
48.192 + if( nByte==0 ){
48.193 + sqliteFree(zMbcsFilename);
48.194 + zMbcsFilename = 0;
48.195 + }
48.196 + return zMbcsFilename;
48.197 +}
48.198 +
48.199 +/*
48.200 +** Convert microsoft unicode to multibyte character string, based on the
48.201 +** user's Ansi codepage.
48.202 +**
48.203 +** Space to hold the returned string is obtained from
48.204 +** sqliteMalloc().
48.205 +*/
48.206 +static char *unicodeToMbcs(const WCHAR *zWideFilename){
48.207 + int nByte;
48.208 + char *zFilename;
48.209 + int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
48.210 +
48.211 + nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
48.212 + zFilename = sqliteMalloc( nByte );
48.213 + if( zFilename==0 ){
48.214 + return 0;
48.215 + }
48.216 + nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
48.217 + 0, 0);
48.218 + if( nByte == 0 ){
48.219 + sqliteFree(zFilename);
48.220 + zFilename = 0;
48.221 + }
48.222 + return zFilename;
48.223 +}
48.224 +
48.225 +/*
48.226 +** Convert multibyte character string to UTF-8. Space to hold the
48.227 +** returned string is obtained from sqliteMalloc().
48.228 +*/
48.229 +static char *mbcsToUtf8(const char *zFilename){
48.230 + char *zFilenameUtf8;
48.231 + WCHAR *zTmpWide;
48.232 +
48.233 + zTmpWide = mbcsToUnicode(zFilename);
48.234 + if( zTmpWide==0 ){
48.235 + return 0;
48.236 + }
48.237 + zFilenameUtf8 = unicodeToUtf8(zTmpWide);
48.238 + sqliteFree(zTmpWide);
48.239 + return zFilenameUtf8;
48.240 +}
48.241 +
48.242 +/*
48.243 +** Convert UTF-8 to multibyte character string. Space to hold the
48.244 +** returned string is obtained from sqliteMalloc().
48.245 +*/
48.246 +static char *utf8ToMbcs(const char *zFilename){
48.247 + char *zFilenameMbcs;
48.248 + WCHAR *zTmpWide;
48.249 +
48.250 + zTmpWide = utf8ToUnicode(zFilename);
48.251 + if( zTmpWide==0 ){
48.252 + return 0;
48.253 + }
48.254 + zFilenameMbcs = unicodeToMbcs(zTmpWide);
48.255 + sqliteFree(zTmpWide);
48.256 + return zFilenameMbcs;
48.257 +}
48.258 +
48.259 +#if OS_WINCE
48.260 +/*************************************************************************
48.261 +** This section contains code for WinCE only.
48.262 +*/
48.263 +/*
48.264 +** WindowsCE does not have a localtime() function. So create a
48.265 +** substitute.
48.266 +*/
48.267 +#include <time.h>
48.268 +struct tm *__cdecl localtime(const time_t *t)
48.269 +{
48.270 + static struct tm y;
48.271 + FILETIME uTm, lTm;
48.272 + SYSTEMTIME pTm;
48.273 + i64 t64;
48.274 + t64 = *t;
48.275 + t64 = (t64 + 11644473600)*10000000;
48.276 + uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
48.277 + uTm.dwHighDateTime= t64 >> 32;
48.278 + FileTimeToLocalFileTime(&uTm,&lTm);
48.279 + FileTimeToSystemTime(&lTm,&pTm);
48.280 + y.tm_year = pTm.wYear - 1900;
48.281 + y.tm_mon = pTm.wMonth - 1;
48.282 + y.tm_wday = pTm.wDayOfWeek;
48.283 + y.tm_mday = pTm.wDay;
48.284 + y.tm_hour = pTm.wHour;
48.285 + y.tm_min = pTm.wMinute;
48.286 + y.tm_sec = pTm.wSecond;
48.287 + return &y;
48.288 +}
48.289 +
48.290 +/* This will never be called, but defined to make the code compile */
48.291 +#define GetTempPathA(a,b)
48.292 +
48.293 +#define LockFile(a,b,c,d,e) winceLockFile(&a, b, c, d, e)
48.294 +#define UnlockFile(a,b,c,d,e) winceUnlockFile(&a, b, c, d, e)
48.295 +#define LockFileEx(a,b,c,d,e,f) winceLockFileEx(&a, b, c, d, e, f)
48.296 +
48.297 +#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-offsetof(winFile,h)]
48.298 +
48.299 +/*
48.300 +** Acquire a lock on the handle h
48.301 +*/
48.302 +static void winceMutexAcquire(HANDLE h){
48.303 + DWORD dwErr;
48.304 + do {
48.305 + dwErr = WaitForSingleObject(h, INFINITE);
48.306 + } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
48.307 +}
48.308 +/*
48.309 +** Release a lock acquired by winceMutexAcquire()
48.310 +*/
48.311 +#define winceMutexRelease(h) ReleaseMutex(h)
48.312 +
48.313 +/*
48.314 +** Create the mutex and shared memory used for locking in the file
48.315 +** descriptor pFile
48.316 +*/
48.317 +static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
48.318 + WCHAR *zTok;
48.319 + WCHAR *zName = utf8ToUnicode(zFilename);
48.320 + BOOL bInit = TRUE;
48.321 +
48.322 + /* Initialize the local lockdata */
48.323 + ZeroMemory(&pFile->local, sizeof(pFile->local));
48.324 +
48.325 + /* Replace the backslashes from the filename and lowercase it
48.326 + ** to derive a mutex name. */
48.327 + zTok = CharLowerW(zName);
48.328 + for (;*zTok;zTok++){
48.329 + if (*zTok == '\\') *zTok = '_';
48.330 + }
48.331 +
48.332 + /* Create/open the named mutex */
48.333 + pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
48.334 + if (!pFile->hMutex){
48.335 + sqliteFree(zName);
48.336 + return FALSE;
48.337 + }
48.338 +
48.339 + /* Acquire the mutex before continuing */
48.340 + winceMutexAcquire(pFile->hMutex);
48.341 +
48.342 + /* Since the names of named mutexes, semaphores, file mappings etc are
48.343 + ** case-sensitive, take advantage of that by uppercasing the mutex name
48.344 + ** and using that as the shared filemapping name.
48.345 + */
48.346 + CharUpperW(zName);
48.347 + pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
48.348 + PAGE_READWRITE, 0, sizeof(winceLock),
48.349 + zName);
48.350 +
48.351 + /* Set a flag that indicates we're the first to create the memory so it
48.352 + ** must be zero-initialized */
48.353 + if (GetLastError() == ERROR_ALREADY_EXISTS){
48.354 + bInit = FALSE;
48.355 + }
48.356 +
48.357 + sqliteFree(zName);
48.358 +
48.359 + /* If we succeeded in making the shared memory handle, map it. */
48.360 + if (pFile->hShared){
48.361 + pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
48.362 + FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
48.363 + /* If mapping failed, close the shared memory handle and erase it */
48.364 + if (!pFile->shared){
48.365 + CloseHandle(pFile->hShared);
48.366 + pFile->hShared = NULL;
48.367 + }
48.368 + }
48.369 +
48.370 + /* If shared memory could not be created, then close the mutex and fail */
48.371 + if (pFile->hShared == NULL){
48.372 + winceMutexRelease(pFile->hMutex);
48.373 + CloseHandle(pFile->hMutex);
48.374 + pFile->hMutex = NULL;
48.375 + return FALSE;
48.376 + }
48.377 +
48.378 + /* Initialize the shared memory if we're supposed to */
48.379 + if (bInit) {
48.380 + ZeroMemory(pFile->shared, sizeof(winceLock));
48.381 + }
48.382 +
48.383 + winceMutexRelease(pFile->hMutex);
48.384 + return TRUE;
48.385 +}
48.386 +
48.387 +/*
48.388 +** Destroy the part of winFile that deals with wince locks
48.389 +*/
48.390 +static void winceDestroyLock(winFile *pFile){
48.391 + if (pFile->hMutex){
48.392 + /* Acquire the mutex */
48.393 + winceMutexAcquire(pFile->hMutex);
48.394 +
48.395 + /* The following blocks should probably assert in debug mode, but they
48.396 + are to cleanup in case any locks remained open */
48.397 + if (pFile->local.nReaders){
48.398 + pFile->shared->nReaders --;
48.399 + }
48.400 + if (pFile->local.bReserved){
48.401 + pFile->shared->bReserved = FALSE;
48.402 + }
48.403 + if (pFile->local.bPending){
48.404 + pFile->shared->bPending = FALSE;
48.405 + }
48.406 + if (pFile->local.bExclusive){
48.407 + pFile->shared->bExclusive = FALSE;
48.408 + }
48.409 +
48.410 + /* De-reference and close our copy of the shared memory handle */
48.411 + UnmapViewOfFile(pFile->shared);
48.412 + CloseHandle(pFile->hShared);
48.413 +
48.414 + if( pFile->zDeleteOnClose ){
48.415 + DeleteFileW(pFile->zDeleteOnClose);
48.416 + sqliteFree(pFile->zDeleteOnClose);
48.417 + pFile->zDeleteOnClose = 0;
48.418 + }
48.419 +
48.420 + /* Done with the mutex */
48.421 + winceMutexRelease(pFile->hMutex);
48.422 + CloseHandle(pFile->hMutex);
48.423 + pFile->hMutex = NULL;
48.424 + }
48.425 +}
48.426 +
48.427 +/*
48.428 +** An implementation of the LockFile() API of windows for wince
48.429 +*/
48.430 +static BOOL winceLockFile(
48.431 + HANDLE *phFile,
48.432 + DWORD dwFileOffsetLow,
48.433 + DWORD dwFileOffsetHigh,
48.434 + DWORD nNumberOfBytesToLockLow,
48.435 + DWORD nNumberOfBytesToLockHigh
48.436 +){
48.437 + winFile *pFile = HANDLE_TO_WINFILE(phFile);
48.438 + BOOL bReturn = FALSE;
48.439 +
48.440 + if (!pFile->hMutex) return TRUE;
48.441 + winceMutexAcquire(pFile->hMutex);
48.442 +
48.443 + /* Wanting an exclusive lock? */
48.444 + if (dwFileOffsetLow == SHARED_FIRST
48.445 + && nNumberOfBytesToLockLow == SHARED_SIZE){
48.446 + if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
48.447 + pFile->shared->bExclusive = TRUE;
48.448 + pFile->local.bExclusive = TRUE;
48.449 + bReturn = TRUE;
48.450 + }
48.451 + }
48.452 +
48.453 + /* Want a read-only lock? */
48.454 + else if ((dwFileOffsetLow >= SHARED_FIRST &&
48.455 + dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE) &&
48.456 + nNumberOfBytesToLockLow == 1){
48.457 + if (pFile->shared->bExclusive == 0){
48.458 + pFile->local.nReaders ++;
48.459 + if (pFile->local.nReaders == 1){
48.460 + pFile->shared->nReaders ++;
48.461 + }
48.462 + bReturn = TRUE;
48.463 + }
48.464 + }
48.465 +
48.466 + /* Want a pending lock? */
48.467 + else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){
48.468 + /* If no pending lock has been acquired, then acquire it */
48.469 + if (pFile->shared->bPending == 0) {
48.470 + pFile->shared->bPending = TRUE;
48.471 + pFile->local.bPending = TRUE;
48.472 + bReturn = TRUE;
48.473 + }
48.474 + }
48.475 + /* Want a reserved lock? */
48.476 + else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
48.477 + if (pFile->shared->bReserved == 0) {
48.478 + pFile->shared->bReserved = TRUE;
48.479 + pFile->local.bReserved = TRUE;
48.480 + bReturn = TRUE;
48.481 + }
48.482 + }
48.483 +
48.484 + winceMutexRelease(pFile->hMutex);
48.485 + return bReturn;
48.486 +}
48.487 +
48.488 +/*
48.489 +** An implementation of the UnlockFile API of windows for wince
48.490 +*/
48.491 +static BOOL winceUnlockFile(
48.492 + HANDLE *phFile,
48.493 + DWORD dwFileOffsetLow,
48.494 + DWORD dwFileOffsetHigh,
48.495 + DWORD nNumberOfBytesToUnlockLow,
48.496 + DWORD nNumberOfBytesToUnlockHigh
48.497 +){
48.498 + winFile *pFile = HANDLE_TO_WINFILE(phFile);
48.499 + BOOL bReturn = FALSE;
48.500 +
48.501 + if (!pFile->hMutex) return TRUE;
48.502 + winceMutexAcquire(pFile->hMutex);
48.503 +
48.504 + /* Releasing a reader lock or an exclusive lock */
48.505 + if (dwFileOffsetLow >= SHARED_FIRST &&
48.506 + dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){
48.507 + /* Did we have an exclusive lock? */
48.508 + if (pFile->local.bExclusive){
48.509 + pFile->local.bExclusive = FALSE;
48.510 + pFile->shared->bExclusive = FALSE;
48.511 + bReturn = TRUE;
48.512 + }
48.513 +
48.514 + /* Did we just have a reader lock? */
48.515 + else if (pFile->local.nReaders){
48.516 + pFile->local.nReaders --;
48.517 + if (pFile->local.nReaders == 0)
48.518 + {
48.519 + pFile->shared->nReaders --;
48.520 + }
48.521 + bReturn = TRUE;
48.522 + }
48.523 + }
48.524 +
48.525 + /* Releasing a pending lock */
48.526 + else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
48.527 + if (pFile->local.bPending){
48.528 + pFile->local.bPending = FALSE;
48.529 + pFile->shared->bPending = FALSE;
48.530 + bReturn = TRUE;
48.531 + }
48.532 + }
48.533 + /* Releasing a reserved lock */
48.534 + else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
48.535 + if (pFile->local.bReserved) {
48.536 + pFile->local.bReserved = FALSE;
48.537 + pFile->shared->bReserved = FALSE;
48.538 + bReturn = TRUE;
48.539 + }
48.540 + }
48.541 +
48.542 + winceMutexRelease(pFile->hMutex);
48.543 + return bReturn;
48.544 +}
48.545 +
48.546 +/*
48.547 +** An implementation of the LockFileEx() API of windows for wince
48.548 +*/
48.549 +static BOOL winceLockFileEx(
48.550 + HANDLE *phFile,
48.551 + DWORD dwFlags,
48.552 + DWORD dwReserved,
48.553 + DWORD nNumberOfBytesToLockLow,
48.554 + DWORD nNumberOfBytesToLockHigh,
48.555 + LPOVERLAPPED lpOverlapped
48.556 +){
48.557 + /* If the caller wants a shared read lock, forward this call
48.558 + ** to winceLockFile */
48.559 + if (lpOverlapped->Offset == SHARED_FIRST &&
48.560 + dwFlags == 1 &&
48.561 + nNumberOfBytesToLockLow == SHARED_SIZE){
48.562 + return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
48.563 + }
48.564 + return FALSE;
48.565 +}
48.566 +/*
48.567 +** End of the special code for wince
48.568 +*****************************************************************************/
48.569 +#endif /* OS_WINCE */
48.570 +
48.571 +/*
48.572 +** Convert a UTF-8 filename into whatever form the underlying
48.573 +** operating system wants filenames in. Space to hold the result
48.574 +** is obtained from sqliteMalloc and must be freed by the calling
48.575 +** function.
48.576 +*/
48.577 +static void *convertUtf8Filename(const char *zFilename){
48.578 + void *zConverted = 0;
48.579 + if( isNT() ){
48.580 + zConverted = utf8ToUnicode(zFilename);
48.581 + }else{
48.582 + zConverted = utf8ToMbcs(zFilename);
48.583 + }
48.584 + /* caller will handle out of memory */
48.585 + return zConverted;
48.586 +}
48.587 +
48.588 +/*
48.589 +** Delete the named file.
48.590 +**
48.591 +** Note that windows does not allow a file to be deleted if some other
48.592 +** process has it open. Sometimes a virus scanner or indexing program
48.593 +** will open a journal file shortly after it is created in order to do
48.594 +** whatever it is it does. While this other process is holding the
48.595 +** file open, we will be unable to delete it. To work around this
48.596 +** problem, we delay 100 milliseconds and try to delete again. Up
48.597 +** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
48.598 +** up and returning an error.
48.599 +*/
48.600 +#define MX_DELETION_ATTEMPTS 3
48.601 +int sqlite3WinDelete(const char *zFilename){
48.602 + int cnt = 0;
48.603 + int rc;
48.604 + void *zConverted = convertUtf8Filename(zFilename);
48.605 + if( zConverted==0 ){
48.606 + return SQLITE_NOMEM;
48.607 + }
48.608 + SimulateIOError(return SQLITE_IOERR_DELETE);
48.609 + if( isNT() ){
48.610 + do{
48.611 + rc = DeleteFileW(zConverted);
48.612 + }while( rc==0 && GetFileAttributesW(zConverted)!=0xffffffff
48.613 + && cnt++ < MX_DELETION_ATTEMPTS && (Sleep(100), 1) );
48.614 + }else{
48.615 +#if OS_WINCE
48.616 + return SQLITE_NOMEM;
48.617 +#else
48.618 + do{
48.619 + rc = DeleteFileA(zConverted);
48.620 + }while( rc==0 && GetFileAttributesA(zConverted)!=0xffffffff
48.621 + && cnt++ < MX_DELETION_ATTEMPTS && (Sleep(100), 1) );
48.622 +#endif
48.623 + }
48.624 + sqliteFree(zConverted);
48.625 + OSTRACE2("DELETE \"%s\"\n", zFilename);
48.626 + return rc!=0 ? SQLITE_OK : SQLITE_IOERR;
48.627 +}
48.628 +
48.629 +/*
48.630 +** Return TRUE if the named file exists.
48.631 +*/
48.632 +int sqlite3WinFileExists(const char *zFilename){
48.633 + int exists = 0;
48.634 + void *zConverted = convertUtf8Filename(zFilename);
48.635 + if( zConverted==0 ){
48.636 + return SQLITE_NOMEM;
48.637 + }
48.638 + if( isNT() ){
48.639 + exists = GetFileAttributesW((WCHAR*)zConverted) != 0xffffffff;
48.640 + }else{
48.641 +#if OS_WINCE
48.642 + return SQLITE_NOMEM;
48.643 +#else
48.644 + exists = GetFileAttributesA((char*)zConverted) != 0xffffffff;
48.645 +#endif
48.646 + }
48.647 + sqliteFree(zConverted);
48.648 + return exists;
48.649 +}
48.650 +
48.651 +/* Forward declaration */
48.652 +static int allocateWinFile(winFile *pInit, OsFile **pId);
48.653 +
48.654 +/*
48.655 +** Attempt to open a file for both reading and writing. If that
48.656 +** fails, try opening it read-only. If the file does not exist,
48.657 +** try to create it.
48.658 +**
48.659 +** On success, a handle for the open file is written to *id
48.660 +** and *pReadonly is set to 0 if the file was opened for reading and
48.661 +** writing or 1 if the file was opened read-only. The function returns
48.662 +** SQLITE_OK.
48.663 +**
48.664 +** On failure, the function returns SQLITE_CANTOPEN and leaves
48.665 +** *id and *pReadonly unchanged.
48.666 +*/
48.667 +int sqlite3WinOpenReadWrite(
48.668 + const char *zFilename,
48.669 + OsFile **pId,
48.670 + int *pReadonly
48.671 +){
48.672 + winFile f;
48.673 + HANDLE h;
48.674 + void *zConverted = convertUtf8Filename(zFilename);
48.675 + if( zConverted==0 ){
48.676 + return SQLITE_NOMEM;
48.677 + }
48.678 + assert( *pId==0 );
48.679 +
48.680 + if( isNT() ){
48.681 + h = CreateFileW((WCHAR*)zConverted,
48.682 + GENERIC_READ | GENERIC_WRITE,
48.683 + FILE_SHARE_READ | FILE_SHARE_WRITE,
48.684 + NULL,
48.685 + OPEN_ALWAYS,
48.686 + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
48.687 + NULL
48.688 + );
48.689 + if( h==INVALID_HANDLE_VALUE ){
48.690 + h = CreateFileW((WCHAR*)zConverted,
48.691 + GENERIC_READ,
48.692 + FILE_SHARE_READ | FILE_SHARE_WRITE,
48.693 + NULL,
48.694 + OPEN_ALWAYS,
48.695 + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
48.696 + NULL
48.697 + );
48.698 + if( h==INVALID_HANDLE_VALUE ){
48.699 + sqliteFree(zConverted);
48.700 + return SQLITE_CANTOPEN;
48.701 + }
48.702 + *pReadonly = 1;
48.703 + }else{
48.704 + *pReadonly = 0;
48.705 + }
48.706 +#if OS_WINCE
48.707 + if (!winceCreateLock(zFilename, &f)){
48.708 + CloseHandle(h);
48.709 + sqliteFree(zConverted);
48.710 + return SQLITE_CANTOPEN;
48.711 + }
48.712 +#endif
48.713 + }else{
48.714 +#if OS_WINCE
48.715 + return SQLITE_NOMEM;
48.716 +#else
48.717 + h = CreateFileA((char*)zConverted,
48.718 + GENERIC_READ | GENERIC_WRITE,
48.719 + FILE_SHARE_READ | FILE_SHARE_WRITE,
48.720 + NULL,
48.721 + OPEN_ALWAYS,
48.722 + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
48.723 + NULL
48.724 + );
48.725 + if( h==INVALID_HANDLE_VALUE ){
48.726 + h = CreateFileA((char*)zConverted,
48.727 + GENERIC_READ,
48.728 + FILE_SHARE_READ | FILE_SHARE_WRITE,
48.729 + NULL,
48.730 + OPEN_ALWAYS,
48.731 + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
48.732 + NULL
48.733 + );
48.734 + if( h==INVALID_HANDLE_VALUE ){
48.735 + sqliteFree(zConverted);
48.736 + return SQLITE_CANTOPEN;
48.737 + }
48.738 + *pReadonly = 1;
48.739 + }else{
48.740 + *pReadonly = 0;
48.741 + }
48.742 +#endif /* OS_WINCE */
48.743 + }
48.744 +
48.745 + sqliteFree(zConverted);
48.746 +
48.747 + f.h = h;
48.748 +#if OS_WINCE
48.749 + f.zDeleteOnClose = 0;
48.750 +#endif
48.751 + OSTRACE3("OPEN R/W %d \"%s\"\n", h, zFilename);
48.752 + return allocateWinFile(&f, pId);
48.753 +}
48.754 +
48.755 +
48.756 +/*
48.757 +** Attempt to open a new file for exclusive access by this process.
48.758 +** The file will be opened for both reading and writing. To avoid
48.759 +** a potential security problem, we do not allow the file to have
48.760 +** previously existed. Nor do we allow the file to be a symbolic
48.761 +** link.
48.762 +**
48.763 +** If delFlag is true, then make arrangements to automatically delete
48.764 +** the file when it is closed.
48.765 +**
48.766 +** On success, write the file handle into *id and return SQLITE_OK.
48.767 +**
48.768 +** On failure, return SQLITE_CANTOPEN.
48.769 +**
48.770 +** Sometimes if we have just deleted a prior journal file, windows
48.771 +** will fail to open a new one because there is a "pending delete".
48.772 +** To work around this bug, we pause for 100 milliseconds and attempt
48.773 +** a second open after the first one fails. The whole operation only
48.774 +** fails if both open attempts are unsuccessful.
48.775 +*/
48.776 +int sqlite3WinOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
48.777 + winFile f;
48.778 + HANDLE h;
48.779 + DWORD fileflags;
48.780 + void *zConverted = convertUtf8Filename(zFilename);
48.781 + if( zConverted==0 ){
48.782 + return SQLITE_NOMEM;
48.783 + }
48.784 + assert( *pId == 0 );
48.785 + fileflags = FILE_FLAG_RANDOM_ACCESS;
48.786 +#if !OS_WINCE
48.787 + if( delFlag ){
48.788 + fileflags |= FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE;
48.789 + }
48.790 +#endif
48.791 + if( isNT() ){
48.792 + int cnt = 0;
48.793 + do{
48.794 + h = CreateFileW((WCHAR*)zConverted,
48.795 + GENERIC_READ | GENERIC_WRITE,
48.796 + 0,
48.797 + NULL,
48.798 + CREATE_ALWAYS,
48.799 + fileflags,
48.800 + NULL
48.801 + );
48.802 + }while( h==INVALID_HANDLE_VALUE && cnt++ < 2 && (Sleep(100), 1) );
48.803 + }else{
48.804 +#if OS_WINCE
48.805 + return SQLITE_NOMEM;
48.806 +#else
48.807 + int cnt = 0;
48.808 + do{
48.809 + h = CreateFileA((char*)zConverted,
48.810 + GENERIC_READ | GENERIC_WRITE,
48.811 + 0,
48.812 + NULL,
48.813 + CREATE_ALWAYS,
48.814 + fileflags,
48.815 + NULL
48.816 + );
48.817 + }while( h==INVALID_HANDLE_VALUE && cnt++ < 2 && (Sleep(100), 1) );
48.818 +#endif /* OS_WINCE */
48.819 + }
48.820 +#if OS_WINCE
48.821 + if( delFlag && h!=INVALID_HANDLE_VALUE ){
48.822 + f.zDeleteOnClose = zConverted;
48.823 + zConverted = 0;
48.824 + }
48.825 + f.hMutex = NULL;
48.826 +#endif
48.827 + sqliteFree(zConverted);
48.828 + if( h==INVALID_HANDLE_VALUE ){
48.829 + return SQLITE_CANTOPEN;
48.830 + }
48.831 + f.h = h;
48.832 + OSTRACE3("OPEN EX %d \"%s\"\n", h, zFilename);
48.833 + return allocateWinFile(&f, pId);
48.834 +}
48.835 +
48.836 +/*
48.837 +** Attempt to open a new file for read-only access.
48.838 +**
48.839 +** On success, write the file handle into *id and return SQLITE_OK.
48.840 +**
48.841 +** On failure, return SQLITE_CANTOPEN.
48.842 +*/
48.843 +int sqlite3WinOpenReadOnly(const char *zFilename, OsFile **pId){
48.844 + winFile f;
48.845 + HANDLE h;
48.846 + void *zConverted = convertUtf8Filename(zFilename);
48.847 + if( zConverted==0 ){
48.848 + return SQLITE_NOMEM;
48.849 + }
48.850 + assert( *pId==0 );
48.851 + if( isNT() ){
48.852 + h = CreateFileW((WCHAR*)zConverted,
48.853 + GENERIC_READ,
48.854 + 0,
48.855 + NULL,
48.856 + OPEN_EXISTING,
48.857 + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
48.858 + NULL
48.859 + );
48.860 + }else{
48.861 +#if OS_WINCE
48.862 + return SQLITE_NOMEM;
48.863 +#else
48.864 + h = CreateFileA((char*)zConverted,
48.865 + GENERIC_READ,
48.866 + 0,
48.867 + NULL,
48.868 + OPEN_EXISTING,
48.869 + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
48.870 + NULL
48.871 + );
48.872 +#endif
48.873 + }
48.874 + sqliteFree(zConverted);
48.875 + if( h==INVALID_HANDLE_VALUE ){
48.876 + return SQLITE_CANTOPEN;
48.877 + }
48.878 + f.h = h;
48.879 +#if OS_WINCE
48.880 + f.zDeleteOnClose = 0;
48.881 + f.hMutex = NULL;
48.882 +#endif
48.883 + OSTRACE3("OPEN RO %d \"%s\"\n", h, zFilename);
48.884 + return allocateWinFile(&f, pId);
48.885 +}
48.886 +
48.887 +/*
48.888 +** Attempt to open a file descriptor for the directory that contains a
48.889 +** file. This file descriptor can be used to fsync() the directory
48.890 +** in order to make sure the creation of a new file is actually written
48.891 +** to disk.
48.892 +**
48.893 +** This routine is only meaningful for Unix. It is a no-op under
48.894 +** windows since windows does not support hard links.
48.895 +**
48.896 +** On success, a handle for a previously open file is at *id is
48.897 +** updated with the new directory file descriptor and SQLITE_OK is
48.898 +** returned.
48.899 +**
48.900 +** On failure, the function returns SQLITE_CANTOPEN and leaves
48.901 +** *id unchanged.
48.902 +*/
48.903 +static int winOpenDirectory(
48.904 + OsFile *id,
48.905 + const char *zDirname
48.906 +){
48.907 + return SQLITE_OK;
48.908 +}
48.909 +
48.910 +/*
48.911 +** Create a temporary file name in zBuf. zBuf must be big enough to
48.912 +** hold at least SQLITE_TEMPNAME_SIZE characters.
48.913 +*/
48.914 +int sqlite3WinTempFileName(char *zBuf){
48.915 + static char zChars[] =
48.916 + "abcdefghijklmnopqrstuvwxyz"
48.917 + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
48.918 + "0123456789";
48.919 + int i, j;
48.920 + char zTempPath[SQLITE_TEMPNAME_SIZE];
48.921 + if( sqlite3_temp_directory ){
48.922 + strncpy(zTempPath, sqlite3_temp_directory, SQLITE_TEMPNAME_SIZE-30);
48.923 + zTempPath[SQLITE_TEMPNAME_SIZE-30] = 0;
48.924 + }else if( isNT() ){
48.925 + char *zMulti;
48.926 + WCHAR zWidePath[SQLITE_TEMPNAME_SIZE];
48.927 + GetTempPathW(SQLITE_TEMPNAME_SIZE-30, zWidePath);
48.928 + zMulti = unicodeToUtf8(zWidePath);
48.929 + if( zMulti ){
48.930 + strncpy(zTempPath, zMulti, SQLITE_TEMPNAME_SIZE-30);
48.931 + zTempPath[SQLITE_TEMPNAME_SIZE-30] = 0;
48.932 + sqliteFree(zMulti);
48.933 + }else{
48.934 + return SQLITE_NOMEM;
48.935 + }
48.936 + }else{
48.937 + char *zUtf8;
48.938 + char zMbcsPath[SQLITE_TEMPNAME_SIZE];
48.939 + GetTempPathA(SQLITE_TEMPNAME_SIZE-30, zMbcsPath);
48.940 + zUtf8 = mbcsToUtf8(zMbcsPath);
48.941 + if( zUtf8 ){
48.942 + strncpy(zTempPath, zUtf8, SQLITE_TEMPNAME_SIZE-30);
48.943 + zTempPath[SQLITE_TEMPNAME_SIZE-30] = 0;
48.944 + sqliteFree(zUtf8);
48.945 + }else{
48.946 + return SQLITE_NOMEM;
48.947 + }
48.948 + }
48.949 + for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
48.950 + zTempPath[i] = 0;
48.951 + for(;;){
48.952 + sqlite3_snprintf(SQLITE_TEMPNAME_SIZE, zBuf,
48.953 + "%s\\"TEMP_FILE_PREFIX, zTempPath);
48.954 + j = strlen(zBuf);
48.955 + sqlite3Randomness(15, &zBuf[j]);
48.956 + for(i=0; i<15; i++, j++){
48.957 + zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
48.958 + }
48.959 + zBuf[j] = 0;
48.960 + if( !sqlite3OsFileExists(zBuf) ) break;
48.961 + }
48.962 + OSTRACE2("TEMP FILENAME: %s\n", zBuf);
48.963 + return SQLITE_OK;
48.964 +}
48.965 +
48.966 +/*
48.967 +** Close a file.
48.968 +**
48.969 +** It is reported that an attempt to close a handle might sometimes
48.970 +** fail. This is a very unreasonable result, but windows is notorious
48.971 +** for being unreasonable so I do not doubt that it might happen. If
48.972 +** the close fails, we pause for 100 milliseconds and try again. As
48.973 +** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
48.974 +** giving up and returning an error.
48.975 +*/
48.976 +#define MX_CLOSE_ATTEMPT 3
48.977 +static int winClose(OsFile **pId){
48.978 + winFile *pFile;
48.979 + int rc = 1;
48.980 + if( pId && (pFile = (winFile*)*pId)!=0 ){
48.981 + int rc, cnt = 0;
48.982 + OSTRACE2("CLOSE %d\n", pFile->h);
48.983 + do{
48.984 + rc = CloseHandle(pFile->h);
48.985 + }while( rc==0 && cnt++ < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
48.986 +#if OS_WINCE
48.987 + winceDestroyLock(pFile);
48.988 +#endif
48.989 + OpenCounter(-1);
48.990 + sqliteFree(pFile);
48.991 + *pId = 0;
48.992 + }
48.993 + return rc ? SQLITE_OK : SQLITE_IOERR;
48.994 +}
48.995 +
48.996 +/*
48.997 +** Read data from a file into a buffer. Return SQLITE_OK if all
48.998 +** bytes were read successfully and SQLITE_IOERR if anything goes
48.999 +** wrong.
48.1000 +*/
48.1001 +static int winRead(OsFile *id, void *pBuf, int amt){
48.1002 + DWORD got;
48.1003 + assert( id!=0 );
48.1004 + SimulateIOError(return SQLITE_IOERR_READ);
48.1005 + OSTRACE3("READ %d lock=%d\n", ((winFile*)id)->h, ((winFile*)id)->locktype);
48.1006 + if( !ReadFile(((winFile*)id)->h, pBuf, amt, &got, 0) ){
48.1007 + return SQLITE_IOERR_READ;
48.1008 + }
48.1009 + if( got==(DWORD)amt ){
48.1010 + return SQLITE_OK;
48.1011 + }else{
48.1012 + memset(&((char*)pBuf)[got], 0, amt-got);
48.1013 + return SQLITE_IOERR_SHORT_READ;
48.1014 + }
48.1015 +}
48.1016 +
48.1017 +/*
48.1018 +** Write data from a buffer into a file. Return SQLITE_OK on success
48.1019 +** or some other error code on failure.
48.1020 +*/
48.1021 +static int winWrite(OsFile *id, const void *pBuf, int amt){
48.1022 + int rc = 0;
48.1023 + DWORD wrote;
48.1024 + assert( id!=0 );
48.1025 + SimulateIOError(return SQLITE_IOERR_READ);
48.1026 + SimulateDiskfullError(return SQLITE_FULL);
48.1027 + OSTRACE3("WRITE %d lock=%d\n", ((winFile*)id)->h, ((winFile*)id)->locktype);
48.1028 + assert( amt>0 );
48.1029 + while( amt>0 && (rc = WriteFile(((winFile*)id)->h, pBuf, amt, &wrote, 0))!=0
48.1030 + && wrote>0 ){
48.1031 + amt -= wrote;
48.1032 + pBuf = &((char*)pBuf)[wrote];
48.1033 + }
48.1034 + if( !rc || amt>(int)wrote ){
48.1035 + return SQLITE_FULL;
48.1036 + }
48.1037 + return SQLITE_OK;
48.1038 +}
48.1039 +
48.1040 +/*
48.1041 +** Some microsoft compilers lack this definition.
48.1042 +*/
48.1043 +#ifndef INVALID_SET_FILE_POINTER
48.1044 +# define INVALID_SET_FILE_POINTER ((DWORD)-1)
48.1045 +#endif
48.1046 +
48.1047 +/*
48.1048 +** Move the read/write pointer in a file.
48.1049 +*/
48.1050 +static int winSeek(OsFile *id, i64 offset){
48.1051 + LONG upperBits = offset>>32;
48.1052 + LONG lowerBits = offset & 0xffffffff;
48.1053 + DWORD rc;
48.1054 + assert( id!=0 );
48.1055 +#ifdef SQLITE_TEST
48.1056 + if( offset ) SimulateDiskfullError(return SQLITE_FULL);
48.1057 +#endif
48.1058 + rc = SetFilePointer(((winFile*)id)->h, lowerBits, &upperBits, FILE_BEGIN);
48.1059 + OSTRACE3("SEEK %d %lld\n", ((winFile*)id)->h, offset);
48.1060 + if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
48.1061 + return SQLITE_FULL;
48.1062 + }
48.1063 + return SQLITE_OK;
48.1064 +}
48.1065 +
48.1066 +/*
48.1067 +** Make sure all writes to a particular file are committed to disk.
48.1068 +*/
48.1069 +static int winSync(OsFile *id, int dataOnly){
48.1070 + assert( id!=0 );
48.1071 + OSTRACE3("SYNC %d lock=%d\n", ((winFile*)id)->h, ((winFile*)id)->locktype);
48.1072 + if( FlushFileBuffers(((winFile*)id)->h) ){
48.1073 + return SQLITE_OK;
48.1074 + }else{
48.1075 + return SQLITE_IOERR;
48.1076 + }
48.1077 +}
48.1078 +
48.1079 +/*
48.1080 +** Sync the directory zDirname. This is a no-op on operating systems other
48.1081 +** than UNIX.
48.1082 +*/
48.1083 +int sqlite3WinSyncDirectory(const char *zDirname){
48.1084 + SimulateIOError(return SQLITE_IOERR_READ);
48.1085 + return SQLITE_OK;
48.1086 +}
48.1087 +
48.1088 +/*
48.1089 +** Truncate an open file to a specified size
48.1090 +*/
48.1091 +static int winTruncate(OsFile *id, i64 nByte){
48.1092 + LONG upperBits = nByte>>32;
48.1093 + assert( id!=0 );
48.1094 + OSTRACE3("TRUNCATE %d %lld\n", ((winFile*)id)->h, nByte);
48.1095 + SimulateIOError(return SQLITE_IOERR_TRUNCATE);
48.1096 + SetFilePointer(((winFile*)id)->h, nByte, &upperBits, FILE_BEGIN);
48.1097 + SetEndOfFile(((winFile*)id)->h);
48.1098 + return SQLITE_OK;
48.1099 +}
48.1100 +
48.1101 +/*
48.1102 +** Determine the current size of a file in bytes
48.1103 +*/
48.1104 +static int winFileSize(OsFile *id, i64 *pSize){
48.1105 + DWORD upperBits, lowerBits;
48.1106 + assert( id!=0 );
48.1107 + SimulateIOError(return SQLITE_IOERR_FSTAT);
48.1108 + lowerBits = GetFileSize(((winFile*)id)->h, &upperBits);
48.1109 + *pSize = (((i64)upperBits)<<32) + lowerBits;
48.1110 + return SQLITE_OK;
48.1111 +}
48.1112 +
48.1113 +/*
48.1114 +** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
48.1115 +*/
48.1116 +#ifndef LOCKFILE_FAIL_IMMEDIATELY
48.1117 +# define LOCKFILE_FAIL_IMMEDIATELY 1
48.1118 +#endif
48.1119 +
48.1120 +/*
48.1121 +** Acquire a reader lock.
48.1122 +** Different API routines are called depending on whether or not this
48.1123 +** is Win95 or WinNT.
48.1124 +*/
48.1125 +static int getReadLock(winFile *id){
48.1126 + int res;
48.1127 + if( isNT() ){
48.1128 + OVERLAPPED ovlp;
48.1129 + ovlp.Offset = SHARED_FIRST;
48.1130 + ovlp.OffsetHigh = 0;
48.1131 + ovlp.hEvent = 0;
48.1132 + res = LockFileEx(id->h, LOCKFILE_FAIL_IMMEDIATELY, 0, SHARED_SIZE,0,&ovlp);
48.1133 + }else{
48.1134 + int lk;
48.1135 + sqlite3Randomness(sizeof(lk), &lk);
48.1136 + id->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
48.1137 + res = LockFile(id->h, SHARED_FIRST+id->sharedLockByte, 0, 1, 0);
48.1138 + }
48.1139 + return res;
48.1140 +}
48.1141 +
48.1142 +/*
48.1143 +** Undo a readlock
48.1144 +*/
48.1145 +static int unlockReadLock(winFile *pFile){
48.1146 + int res;
48.1147 + if( isNT() ){
48.1148 + res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
48.1149 + }else{
48.1150 + res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
48.1151 + }
48.1152 + return res;
48.1153 +}
48.1154 +
48.1155 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
48.1156 +/*
48.1157 +** Check that a given pathname is a directory and is writable
48.1158 +**
48.1159 +*/
48.1160 +int sqlite3WinIsDirWritable(char *zDirname){
48.1161 + int fileAttr;
48.1162 + void *zConverted;
48.1163 + if( zDirname==0 ) return 0;
48.1164 + if( !isNT() && strlen(zDirname)>MAX_PATH ) return 0;
48.1165 +
48.1166 + zConverted = convertUtf8Filename(zDirname);
48.1167 + if( zConverted==0 ){
48.1168 + return SQLITE_NOMEM;
48.1169 + }
48.1170 + if( isNT() ){
48.1171 + fileAttr = GetFileAttributesW((WCHAR*)zConverted);
48.1172 + }else{
48.1173 +#if OS_WINCE
48.1174 + return 0;
48.1175 +#else
48.1176 + fileAttr = GetFileAttributesA((char*)zConverted);
48.1177 +#endif
48.1178 + }
48.1179 + sqliteFree(zConverted);
48.1180 + if( fileAttr == 0xffffffff ) return 0;
48.1181 + if( (fileAttr & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY ){
48.1182 + return 0;
48.1183 + }
48.1184 + return 1;
48.1185 +}
48.1186 +#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
48.1187 +
48.1188 +/*
48.1189 +** Lock the file with the lock specified by parameter locktype - one
48.1190 +** of the following:
48.1191 +**
48.1192 +** (1) SHARED_LOCK
48.1193 +** (2) RESERVED_LOCK
48.1194 +** (3) PENDING_LOCK
48.1195 +** (4) EXCLUSIVE_LOCK
48.1196 +**
48.1197 +** Sometimes when requesting one lock state, additional lock states
48.1198 +** are inserted in between. The locking might fail on one of the later
48.1199 +** transitions leaving the lock state different from what it started but
48.1200 +** still short of its goal. The following chart shows the allowed
48.1201 +** transitions and the inserted intermediate states:
48.1202 +**
48.1203 +** UNLOCKED -> SHARED
48.1204 +** SHARED -> RESERVED
48.1205 +** SHARED -> (PENDING) -> EXCLUSIVE
48.1206 +** RESERVED -> (PENDING) -> EXCLUSIVE
48.1207 +** PENDING -> EXCLUSIVE
48.1208 +**
48.1209 +** This routine will only increase a lock. The winUnlock() routine
48.1210 +** erases all locks at once and returns us immediately to locking level 0.
48.1211 +** It is not possible to lower the locking level one step at a time. You
48.1212 +** must go straight to locking level 0.
48.1213 +*/
48.1214 +static int winLock(OsFile *id, int locktype){
48.1215 + int rc = SQLITE_OK; /* Return code from subroutines */
48.1216 + int res = 1; /* Result of a windows lock call */
48.1217 + int newLocktype; /* Set id->locktype to this value before exiting */
48.1218 + int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
48.1219 + winFile *pFile = (winFile*)id;
48.1220 +
48.1221 + assert( pFile!=0 );
48.1222 + OSTRACE5("LOCK %d %d was %d(%d)\n",
48.1223 + pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
48.1224 +
48.1225 + /* If there is already a lock of this type or more restrictive on the
48.1226 + ** OsFile, do nothing. Don't use the end_lock: exit path, as
48.1227 + ** sqlite3OsEnterMutex() hasn't been called yet.
48.1228 + */
48.1229 + if( pFile->locktype>=locktype ){
48.1230 + return SQLITE_OK;
48.1231 + }
48.1232 +
48.1233 + /* Make sure the locking sequence is correct
48.1234 + */
48.1235 + assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
48.1236 + assert( locktype!=PENDING_LOCK );
48.1237 + assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
48.1238 +
48.1239 + /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
48.1240 + ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
48.1241 + ** the PENDING_LOCK byte is temporary.
48.1242 + */
48.1243 + newLocktype = pFile->locktype;
48.1244 + if( pFile->locktype==NO_LOCK
48.1245 + || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
48.1246 + ){
48.1247 + int cnt = 3;
48.1248 + while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
48.1249 + /* Try 3 times to get the pending lock. The pending lock might be
48.1250 + ** held by another reader process who will release it momentarily.
48.1251 + */
48.1252 + OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
48.1253 + Sleep(1);
48.1254 + }
48.1255 + gotPendingLock = res;
48.1256 + }
48.1257 +
48.1258 + /* Acquire a shared lock
48.1259 + */
48.1260 + if( locktype==SHARED_LOCK && res ){
48.1261 + assert( pFile->locktype==NO_LOCK );
48.1262 + res = getReadLock(pFile);
48.1263 + if( res ){
48.1264 + newLocktype = SHARED_LOCK;
48.1265 + }
48.1266 + }
48.1267 +
48.1268 + /* Acquire a RESERVED lock
48.1269 + */
48.1270 + if( locktype==RESERVED_LOCK && res ){
48.1271 + assert( pFile->locktype==SHARED_LOCK );
48.1272 + res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
48.1273 + if( res ){
48.1274 + newLocktype = RESERVED_LOCK;
48.1275 + }
48.1276 + }
48.1277 +
48.1278 + /* Acquire a PENDING lock
48.1279 + */
48.1280 + if( locktype==EXCLUSIVE_LOCK && res ){
48.1281 + newLocktype = PENDING_LOCK;
48.1282 + gotPendingLock = 0;
48.1283 + }
48.1284 +
48.1285 + /* Acquire an EXCLUSIVE lock
48.1286 + */
48.1287 + if( locktype==EXCLUSIVE_LOCK && res ){
48.1288 + assert( pFile->locktype>=SHARED_LOCK );
48.1289 + res = unlockReadLock(pFile);
48.1290 + OSTRACE2("unreadlock = %d\n", res);
48.1291 + res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
48.1292 + if( res ){
48.1293 + newLocktype = EXCLUSIVE_LOCK;
48.1294 + }else{
48.1295 + OSTRACE2("error-code = %d\n", GetLastError());
48.1296 + getReadLock(pFile);
48.1297 + }
48.1298 + }
48.1299 +
48.1300 + /* If we are holding a PENDING lock that ought to be released, then
48.1301 + ** release it now.
48.1302 + */
48.1303 + if( gotPendingLock && locktype==SHARED_LOCK ){
48.1304 + UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
48.1305 + }
48.1306 +
48.1307 + /* Update the state of the lock has held in the file descriptor then
48.1308 + ** return the appropriate result code.
48.1309 + */
48.1310 + if( res ){
48.1311 + rc = SQLITE_OK;
48.1312 + }else{
48.1313 + OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
48.1314 + locktype, newLocktype);
48.1315 + rc = SQLITE_BUSY;
48.1316 + }
48.1317 + pFile->locktype = newLocktype;
48.1318 + return rc;
48.1319 +}
48.1320 +
48.1321 +/*
48.1322 +** This routine checks if there is a RESERVED lock held on the specified
48.1323 +** file by this or any other process. If such a lock is held, return
48.1324 +** non-zero, otherwise zero.
48.1325 +*/
48.1326 +static int winCheckReservedLock(OsFile *id){
48.1327 + int rc;
48.1328 + winFile *pFile = (winFile*)id;
48.1329 + assert( pFile!=0 );
48.1330 + if( pFile->locktype>=RESERVED_LOCK ){
48.1331 + rc = 1;
48.1332 + OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
48.1333 + }else{
48.1334 + rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
48.1335 + if( rc ){
48.1336 + UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
48.1337 + }
48.1338 + rc = !rc;
48.1339 + OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
48.1340 + }
48.1341 + return rc;
48.1342 +}
48.1343 +
48.1344 +/*
48.1345 +** Lower the locking level on file descriptor id to locktype. locktype
48.1346 +** must be either NO_LOCK or SHARED_LOCK.
48.1347 +**
48.1348 +** If the locking level of the file descriptor is already at or below
48.1349 +** the requested locking level, this routine is a no-op.
48.1350 +**
48.1351 +** It is not possible for this routine to fail if the second argument
48.1352 +** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
48.1353 +** might return SQLITE_IOERR;
48.1354 +*/
48.1355 +static int winUnlock(OsFile *id, int locktype){
48.1356 + int type;
48.1357 + int rc = SQLITE_OK;
48.1358 + winFile *pFile = (winFile*)id;
48.1359 + assert( pFile!=0 );
48.1360 + assert( locktype<=SHARED_LOCK );
48.1361 + OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
48.1362 + pFile->locktype, pFile->sharedLockByte);
48.1363 + type = pFile->locktype;
48.1364 + if( type>=EXCLUSIVE_LOCK ){
48.1365 + UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
48.1366 + if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
48.1367 + /* This should never happen. We should always be able to
48.1368 + ** reacquire the read lock */
48.1369 + rc = SQLITE_IOERR_UNLOCK;
48.1370 + }
48.1371 + }
48.1372 + if( type>=RESERVED_LOCK ){
48.1373 + UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
48.1374 + }
48.1375 + if( locktype==NO_LOCK && type>=SHARED_LOCK ){
48.1376 + unlockReadLock(pFile);
48.1377 + }
48.1378 + if( type>=PENDING_LOCK ){
48.1379 + UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
48.1380 + }
48.1381 + pFile->locktype = locktype;
48.1382 + return rc;
48.1383 +}
48.1384 +
48.1385 +/*
48.1386 +** Turn a relative pathname into a full pathname. Return a pointer
48.1387 +** to the full pathname stored in space obtained from sqliteMalloc().
48.1388 +** The calling function is responsible for freeing this space once it
48.1389 +** is no longer needed.
48.1390 +*/
48.1391 +char *sqlite3WinFullPathname(const char *zRelative){
48.1392 + char *zFull;
48.1393 +#if defined(__CYGWIN__)
48.1394 + int nByte;
48.1395 + nByte = strlen(zRelative) + MAX_PATH + 1001;
48.1396 + zFull = sqliteMalloc( nByte );
48.1397 + if( zFull==0 ) return 0;
48.1398 + if( cygwin_conv_to_full_win32_path(zRelative, zFull) ) return 0;
48.1399 +#elif OS_WINCE
48.1400 + /* WinCE has no concept of a relative pathname, or so I am told. */
48.1401 + zFull = sqliteStrDup(zRelative);
48.1402 +#else
48.1403 + int nByte;
48.1404 + void *zConverted;
48.1405 + zConverted = convertUtf8Filename(zRelative);
48.1406 + if( isNT() ){
48.1407 + WCHAR *zTemp;
48.1408 + nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
48.1409 + zTemp = sqliteMalloc( nByte*sizeof(zTemp[0]) );
48.1410 + if( zTemp==0 ){
48.1411 + sqliteFree(zConverted);
48.1412 + return 0;
48.1413 + }
48.1414 + GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
48.1415 + sqliteFree(zConverted);
48.1416 + zFull = unicodeToUtf8(zTemp);
48.1417 + sqliteFree(zTemp);
48.1418 + }else{
48.1419 + char *zTemp;
48.1420 + nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
48.1421 + zTemp = sqliteMalloc( nByte*sizeof(zTemp[0]) );
48.1422 + if( zTemp==0 ){
48.1423 + sqliteFree(zConverted);
48.1424 + return 0;
48.1425 + }
48.1426 + GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
48.1427 + sqliteFree(zConverted);
48.1428 + zFull = mbcsToUtf8(zTemp);
48.1429 + sqliteFree(zTemp);
48.1430 + }
48.1431 +#endif
48.1432 + return zFull;
48.1433 +}
48.1434 +
48.1435 +/*
48.1436 +** The fullSync option is meaningless on windows. This is a no-op.
48.1437 +*/
48.1438 +static void winSetFullSync(OsFile *id, int v){
48.1439 + return;
48.1440 +}
48.1441 +
48.1442 +/*
48.1443 +** Return the underlying file handle for an OsFile
48.1444 +*/
48.1445 +static int winFileHandle(OsFile *id){
48.1446 + return (int)((winFile*)id)->h;
48.1447 +}
48.1448 +
48.1449 +/*
48.1450 +** Return an integer that indices the type of lock currently held
48.1451 +** by this handle. (Used for testing and analysis only.)
48.1452 +*/
48.1453 +static int winLockState(OsFile *id){
48.1454 + return ((winFile*)id)->locktype;
48.1455 +}
48.1456 +
48.1457 +/*
48.1458 +** Return the sector size in bytes of the underlying block device for
48.1459 +** the specified file. This is almost always 512 bytes, but may be
48.1460 +** larger for some devices.
48.1461 +**
48.1462 +** SQLite code assumes this function cannot fail. It also assumes that
48.1463 +** if two files are created in the same file-system directory (i.e.
48.1464 +** a database and it's journal file) that the sector size will be the
48.1465 +** same for both.
48.1466 +*/
48.1467 +static int winSectorSize(OsFile *id){
48.1468 + return SQLITE_DEFAULT_SECTOR_SIZE;
48.1469 +}
48.1470 +
48.1471 +/*
48.1472 +** This vector defines all the methods that can operate on an OsFile
48.1473 +** for win32.
48.1474 +*/
48.1475 +static const IoMethod sqlite3WinIoMethod = {
48.1476 + winClose,
48.1477 + winOpenDirectory,
48.1478 + winRead,
48.1479 + winWrite,
48.1480 + winSeek,
48.1481 + winTruncate,
48.1482 + winSync,
48.1483 + winSetFullSync,
48.1484 + winFileHandle,
48.1485 + winFileSize,
48.1486 + winLock,
48.1487 + winUnlock,
48.1488 + winLockState,
48.1489 + winCheckReservedLock,
48.1490 + winSectorSize,
48.1491 +};
48.1492 +
48.1493 +/*
48.1494 +** Allocate memory for an OsFile. Initialize the new OsFile
48.1495 +** to the value given in pInit and return a pointer to the new
48.1496 +** OsFile. If we run out of memory, close the file and return NULL.
48.1497 +*/
48.1498 +static int allocateWinFile(winFile *pInit, OsFile **pId){
48.1499 + winFile *pNew;
48.1500 + pNew = sqliteMalloc( sizeof(*pNew) );
48.1501 + if( pNew==0 ){
48.1502 + CloseHandle(pInit->h);
48.1503 +#if OS_WINCE
48.1504 + sqliteFree(pInit->zDeleteOnClose);
48.1505 +#endif
48.1506 + *pId = 0;
48.1507 + return SQLITE_NOMEM;
48.1508 + }else{
48.1509 + *pNew = *pInit;
48.1510 + pNew->pMethod = &sqlite3WinIoMethod;
48.1511 + pNew->locktype = NO_LOCK;
48.1512 + pNew->sharedLockByte = 0;
48.1513 + *pId = (OsFile*)pNew;
48.1514 + OpenCounter(+1);
48.1515 + return SQLITE_OK;
48.1516 + }
48.1517 +}
48.1518 +
48.1519 +
48.1520 +#endif /* SQLITE_OMIT_DISKIO */
48.1521 +/***************************************************************************
48.1522 +** Everything above deals with file I/O. Everything that follows deals
48.1523 +** with other miscellanous aspects of the operating system interface
48.1524 +****************************************************************************/
48.1525 +
48.1526 +#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
48.1527 +/*
48.1528 +** Interfaces for opening a shared library, finding entry points
48.1529 +** within the shared library, and closing the shared library.
48.1530 +*/
48.1531 +void *sqlite3WinDlopen(const char *zFilename){
48.1532 + HANDLE h;
48.1533 + void *zConverted = convertUtf8Filename(zFilename);
48.1534 + if( zConverted==0 ){
48.1535 + return 0;
48.1536 + }
48.1537 + if( isNT() ){
48.1538 + h = LoadLibraryW((WCHAR*)zConverted);
48.1539 + }else{
48.1540 +#if OS_WINCE
48.1541 + return 0;
48.1542 +#else
48.1543 + h = LoadLibraryA((char*)zConverted);
48.1544 +#endif
48.1545 + }
48.1546 + sqliteFree(zConverted);
48.1547 + return (void*)h;
48.1548 +
48.1549 +}
48.1550 +void *sqlite3WinDlsym(void *pHandle, const char *zSymbol){
48.1551 +#if OS_WINCE
48.1552 + /* The GetProcAddressA() routine is only available on wince. */
48.1553 + return GetProcAddressA((HANDLE)pHandle, zSymbol);
48.1554 +#else
48.1555 + /* All other windows platforms expect GetProcAddress() to take
48.1556 + ** an Ansi string regardless of the _UNICODE setting */
48.1557 + return GetProcAddress((HANDLE)pHandle, zSymbol);
48.1558 +#endif
48.1559 +}
48.1560 +int sqlite3WinDlclose(void *pHandle){
48.1561 + return FreeLibrary((HANDLE)pHandle);
48.1562 +}
48.1563 +#endif /* !SQLITE_OMIT_LOAD_EXTENSION */
48.1564 +
48.1565 +/*
48.1566 +** Get information to seed the random number generator. The seed
48.1567 +** is written into the buffer zBuf[256]. The calling function must
48.1568 +** supply a sufficiently large buffer.
48.1569 +*/
48.1570 +int sqlite3WinRandomSeed(char *zBuf){
48.1571 + /* We have to initialize zBuf to prevent valgrind from reporting
48.1572 + ** errors. The reports issued by valgrind are incorrect - we would
48.1573 + ** prefer that the randomness be increased by making use of the
48.1574 + ** uninitialized space in zBuf - but valgrind errors tend to worry
48.1575 + ** some users. Rather than argue, it seems easier just to initialize
48.1576 + ** the whole array and silence valgrind, even if that means less randomness
48.1577 + ** in the random seed.
48.1578 + **
48.1579 + ** When testing, initializing zBuf[] to zero is all we do. That means
48.1580 + ** that we always use the same random number sequence.* This makes the
48.1581 + ** tests repeatable.
48.1582 + */
48.1583 + memset(zBuf, 0, 256);
48.1584 + GetSystemTime((LPSYSTEMTIME)zBuf);
48.1585 + return SQLITE_OK;
48.1586 +}
48.1587 +
48.1588 +/*
48.1589 +** Sleep for a little while. Return the amount of time slept.
48.1590 +*/
48.1591 +int sqlite3WinSleep(int ms){
48.1592 + Sleep(ms);
48.1593 + return ms;
48.1594 +}
48.1595 +
48.1596 +/*
48.1597 +** Static variables used for thread synchronization
48.1598 +*/
48.1599 +static int inMutex = 0;
48.1600 +#ifdef SQLITE_W32_THREADS
48.1601 + static DWORD mutexOwner;
48.1602 + static CRITICAL_SECTION cs;
48.1603 +#endif
48.1604 +
48.1605 +/*
48.1606 +** The following pair of routines implement mutual exclusion for
48.1607 +** multi-threaded processes. Only a single thread is allowed to
48.1608 +** executed code that is surrounded by EnterMutex() and LeaveMutex().
48.1609 +**
48.1610 +** SQLite uses only a single Mutex. There is not much critical
48.1611 +** code and what little there is executes quickly and without blocking.
48.1612 +**
48.1613 +** Version 3.3.1 and earlier used a simple mutex. Beginning with
48.1614 +** version 3.3.2, a recursive mutex is required.
48.1615 +*/
48.1616 +void sqlite3WinEnterMutex(){
48.1617 +#ifdef SQLITE_W32_THREADS
48.1618 + static int isInit = 0;
48.1619 + while( !isInit ){
48.1620 + static long lock = 0;
48.1621 + if( InterlockedIncrement(&lock)==1 ){
48.1622 + InitializeCriticalSection(&cs);
48.1623 + isInit = 1;
48.1624 + }else{
48.1625 + Sleep(1);
48.1626 + }
48.1627 + }
48.1628 + EnterCriticalSection(&cs);
48.1629 + mutexOwner = GetCurrentThreadId();
48.1630 +#endif
48.1631 + inMutex++;
48.1632 +}
48.1633 +void sqlite3WinLeaveMutex(){
48.1634 + assert( inMutex );
48.1635 + inMutex--;
48.1636 +#ifdef SQLITE_W32_THREADS
48.1637 + assert( mutexOwner==GetCurrentThreadId() );
48.1638 + LeaveCriticalSection(&cs);
48.1639 +#endif
48.1640 +}
48.1641 +
48.1642 +/*
48.1643 +** Return TRUE if the mutex is currently held.
48.1644 +**
48.1645 +** If the thisThreadOnly parameter is true, return true if and only if the
48.1646 +** calling thread holds the mutex. If the parameter is false, return
48.1647 +** true if any thread holds the mutex.
48.1648 +*/
48.1649 +int sqlite3WinInMutex(int thisThreadOnly){
48.1650 +#ifdef SQLITE_W32_THREADS
48.1651 + return inMutex>0 && (thisThreadOnly==0 || mutexOwner==GetCurrentThreadId());
48.1652 +#else
48.1653 + return inMutex>0;
48.1654 +#endif
48.1655 +}
48.1656 +
48.1657 +
48.1658 +/*
48.1659 +** The following variable, if set to a non-zero value, becomes the result
48.1660 +** returned from sqlite3OsCurrentTime(). This is used for testing.
48.1661 +*/
48.1662 +#ifdef SQLITE_TEST
48.1663 +int sqlite3_current_time = 0;
48.1664 +#endif
48.1665 +
48.1666 +/*
48.1667 +** Find the current time (in Universal Coordinated Time). Write the
48.1668 +** current time and date as a Julian Day number into *prNow and
48.1669 +** return 0. Return 1 if the time and date cannot be found.
48.1670 +*/
48.1671 +int sqlite3WinCurrentTime(double *prNow){
48.1672 + FILETIME ft;
48.1673 + /* FILETIME structure is a 64-bit value representing the number of
48.1674 + 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
48.1675 + */
48.1676 + double now;
48.1677 +#if OS_WINCE
48.1678 + SYSTEMTIME time;
48.1679 + GetSystemTime(&time);
48.1680 + SystemTimeToFileTime(&time,&ft);
48.1681 +#else
48.1682 + GetSystemTimeAsFileTime( &ft );
48.1683 +#endif
48.1684 + now = ((double)ft.dwHighDateTime) * 4294967296.0;
48.1685 + *prNow = (now + ft.dwLowDateTime)/864000000000.0 + 2305813.5;
48.1686 +#ifdef SQLITE_TEST
48.1687 + if( sqlite3_current_time ){
48.1688 + *prNow = sqlite3_current_time/86400.0 + 2440587.5;
48.1689 + }
48.1690 +#endif
48.1691 + return 0;
48.1692 +}
48.1693 +
48.1694 +/*
48.1695 +** Remember the number of thread-specific-data blocks allocated.
48.1696 +** Use this to verify that we are not leaking thread-specific-data.
48.1697 +** Ticket #1601
48.1698 +*/
48.1699 +#ifdef SQLITE_TEST
48.1700 +int sqlite3_tsd_count = 0;
48.1701 +# define TSD_COUNTER_INCR InterlockedIncrement(&sqlite3_tsd_count)
48.1702 +# define TSD_COUNTER_DECR InterlockedDecrement(&sqlite3_tsd_count)
48.1703 +#else
48.1704 +# define TSD_COUNTER_INCR /* no-op */
48.1705 +# define TSD_COUNTER_DECR /* no-op */
48.1706 +#endif
48.1707 +
48.1708 +
48.1709 +
48.1710 +/*
48.1711 +** If called with allocateFlag>1, then return a pointer to thread
48.1712 +** specific data for the current thread. Allocate and zero the
48.1713 +** thread-specific data if it does not already exist necessary.
48.1714 +**
48.1715 +** If called with allocateFlag==0, then check the current thread
48.1716 +** specific data. Return it if it exists. If it does not exist,
48.1717 +** then return NULL.
48.1718 +**
48.1719 +** If called with allocateFlag<0, check to see if the thread specific
48.1720 +** data is allocated and is all zero. If it is then deallocate it.
48.1721 +** Return a pointer to the thread specific data or NULL if it is
48.1722 +** unallocated or gets deallocated.
48.1723 +*/
48.1724 +ThreadData *sqlite3WinThreadSpecificData(int allocateFlag){
48.1725 + static int key;
48.1726 + static int keyInit = 0;
48.1727 + static const ThreadData zeroData = {0};
48.1728 + ThreadData *pTsd;
48.1729 +
48.1730 + if( !keyInit ){
48.1731 + sqlite3OsEnterMutex();
48.1732 + if( !keyInit ){
48.1733 + key = TlsAlloc();
48.1734 + if( key==0xffffffff ){
48.1735 + sqlite3OsLeaveMutex();
48.1736 + return 0;
48.1737 + }
48.1738 + keyInit = 1;
48.1739 + }
48.1740 + sqlite3OsLeaveMutex();
48.1741 + }
48.1742 + pTsd = TlsGetValue(key);
48.1743 + if( allocateFlag>0 ){
48.1744 + if( !pTsd ){
48.1745 + pTsd = sqlite3OsMalloc( sizeof(zeroData) );
48.1746 + if( pTsd ){
48.1747 + *pTsd = zeroData;
48.1748 + TlsSetValue(key, pTsd);
48.1749 + TSD_COUNTER_INCR;
48.1750 + }
48.1751 + }
48.1752 + }else if( pTsd!=0 && allocateFlag<0
48.1753 + && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
48.1754 + sqlite3OsFree(pTsd);
48.1755 + TlsSetValue(key, 0);
48.1756 + TSD_COUNTER_DECR;
48.1757 + pTsd = 0;
48.1758 + }
48.1759 + return pTsd;
48.1760 +}
48.1761 +#endif /* OS_WIN */
49.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
49.2 +++ b/extensions/sqlite/sqlite-source/pager.c Sun Jul 29 01:15:31 2007 +0000
49.3 @@ -0,0 +1,4469 @@
49.4 +/*
49.5 +** 2001 September 15
49.6 +**
49.7 +** The author disclaims copyright to this source code. In place of
49.8 +** a legal notice, here is a blessing:
49.9 +**
49.10 +** May you do good and not evil.
49.11 +** May you find forgiveness for yourself and forgive others.
49.12 +** May you share freely, never taking more than you give.
49.13 +**
49.14 +*************************************************************************
49.15 +** This is the implementation of the page cache subsystem or "pager".
49.16 +**
49.17 +** The pager is used to access a database disk file. It implements
49.18 +** atomic commit and rollback through the use of a journal file that
49.19 +** is separate from the database file. The pager also implements file
49.20 +** locking to prevent two processes from writing the same database
49.21 +** file simultaneously, or one process from reading the database while
49.22 +** another is writing.
49.23 +**
49.24 +** @(#) $Id$
49.25 +*/
49.26 +#ifndef SQLITE_OMIT_DISKIO
49.27 +#include "sqliteInt.h"
49.28 +#include "os.h"
49.29 +#include "pager.h"
49.30 +#include <assert.h>
49.31 +#include <string.h>
49.32 +
49.33 +/*
49.34 +** Macros for troubleshooting. Normally turned off
49.35 +*/
49.36 +#if 0
49.37 +#define sqlite3DebugPrintf printf
49.38 +#define PAGERTRACE1(X) sqlite3DebugPrintf(X)
49.39 +#define PAGERTRACE2(X,Y) sqlite3DebugPrintf(X,Y)
49.40 +#define PAGERTRACE3(X,Y,Z) sqlite3DebugPrintf(X,Y,Z)
49.41 +#define PAGERTRACE4(X,Y,Z,W) sqlite3DebugPrintf(X,Y,Z,W)
49.42 +#define PAGERTRACE5(X,Y,Z,W,V) sqlite3DebugPrintf(X,Y,Z,W,V)
49.43 +#else
49.44 +#define PAGERTRACE1(X)
49.45 +#define PAGERTRACE2(X,Y)
49.46 +#define PAGERTRACE3(X,Y,Z)
49.47 +#define PAGERTRACE4(X,Y,Z,W)
49.48 +#define PAGERTRACE5(X,Y,Z,W,V)
49.49 +#endif
49.50 +
49.51 +/*
49.52 +** The following two macros are used within the PAGERTRACEX() macros above
49.53 +** to print out file-descriptors.
49.54 +**
49.55 +** PAGERID() takes a pointer to a Pager struct as it's argument. The
49.56 +** associated file-descriptor is returned. FILEHANDLEID() takes an OsFile
49.57 +** struct as it's argument.
49.58 +*/
49.59 +#define PAGERID(p) ((int)(p->fd))
49.60 +#define FILEHANDLEID(fd) ((int)fd)
49.61 +
49.62 +/*
49.63 +** The page cache as a whole is always in one of the following
49.64 +** states:
49.65 +**
49.66 +** PAGER_UNLOCK The page cache is not currently reading or
49.67 +** writing the database file. There is no
49.68 +** data held in memory. This is the initial
49.69 +** state.
49.70 +**
49.71 +** PAGER_SHARED The page cache is reading the database.
49.72 +** Writing is not permitted. There can be
49.73 +** multiple readers accessing the same database
49.74 +** file at the same time.
49.75 +**
49.76 +** PAGER_RESERVED This process has reserved the database for writing
49.77 +** but has not yet made any changes. Only one process
49.78 +** at a time can reserve the database. The original
49.79 +** database file has not been modified so other
49.80 +** processes may still be reading the on-disk
49.81 +** database file.
49.82 +**
49.83 +** PAGER_EXCLUSIVE The page cache is writing the database.
49.84 +** Access is exclusive. No other processes or
49.85 +** threads can be reading or writing while one
49.86 +** process is writing.
49.87 +**
49.88 +** PAGER_SYNCED The pager moves to this state from PAGER_EXCLUSIVE
49.89 +** after all dirty pages have been written to the
49.90 +** database file and the file has been synced to
49.91 +** disk. All that remains to do is to remove or
49.92 +** truncate the journal file and the transaction
49.93 +** will be committed.
49.94 +**
49.95 +** The page cache comes up in PAGER_UNLOCK. The first time a
49.96 +** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
49.97 +** After all pages have been released using sqlite_page_unref(),
49.98 +** the state transitions back to PAGER_UNLOCK. The first time
49.99 +** that sqlite3PagerWrite() is called, the state transitions to
49.100 +** PAGER_RESERVED. (Note that sqlite3PagerWrite() can only be
49.101 +** called on an outstanding page which means that the pager must
49.102 +** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
49.103 +** PAGER_RESERVED means that there is an open rollback journal.
49.104 +** The transition to PAGER_EXCLUSIVE occurs before any changes
49.105 +** are made to the database file, though writes to the rollback
49.106 +** journal occurs with just PAGER_RESERVED. After an sqlite3PagerRollback()
49.107 +** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
49.108 +** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
49.109 +*/
49.110 +#define PAGER_UNLOCK 0
49.111 +#define PAGER_SHARED 1 /* same as SHARED_LOCK */
49.112 +#define PAGER_RESERVED 2 /* same as RESERVED_LOCK */
49.113 +#define PAGER_EXCLUSIVE 4 /* same as EXCLUSIVE_LOCK */
49.114 +#define PAGER_SYNCED 5
49.115 +
49.116 +/*
49.117 +** If the SQLITE_BUSY_RESERVED_LOCK macro is set to true at compile-time,
49.118 +** then failed attempts to get a reserved lock will invoke the busy callback.
49.119 +** This is off by default. To see why, consider the following scenario:
49.120 +**
49.121 +** Suppose thread A already has a shared lock and wants a reserved lock.
49.122 +** Thread B already has a reserved lock and wants an exclusive lock. If
49.123 +** both threads are using their busy callbacks, it might be a long time
49.124 +** be for one of the threads give up and allows the other to proceed.
49.125 +** But if the thread trying to get the reserved lock gives up quickly
49.126 +** (if it never invokes its busy callback) then the contention will be
49.127 +** resolved quickly.
49.128 +*/
49.129 +#ifndef SQLITE_BUSY_RESERVED_LOCK
49.130 +# define SQLITE_BUSY_RESERVED_LOCK 0
49.131 +#endif
49.132 +
49.133 +/*
49.134 +** This macro rounds values up so that if the value is an address it
49.135 +** is guaranteed to be an address that is aligned to an 8-byte boundary.
49.136 +*/
49.137 +#define FORCE_ALIGNMENT(X) (((X)+7)&~7)
49.138 +
49.139 +/*
49.140 +** Each in-memory image of a page begins with the following header.
49.141 +** This header is only visible to this pager module. The client
49.142 +** code that calls pager sees only the data that follows the header.
49.143 +**
49.144 +** Client code should call sqlite3PagerWrite() on a page prior to making
49.145 +** any modifications to that page. The first time sqlite3PagerWrite()
49.146 +** is called, the original page contents are written into the rollback
49.147 +** journal and PgHdr.inJournal and PgHdr.needSync are set. Later, once
49.148 +** the journal page has made it onto the disk surface, PgHdr.needSync
49.149 +** is cleared. The modified page cannot be written back into the original
49.150 +** database file until the journal pages has been synced to disk and the
49.151 +** PgHdr.needSync has been cleared.
49.152 +**
49.153 +** The PgHdr.dirty flag is set when sqlite3PagerWrite() is called and
49.154 +** is cleared again when the page content is written back to the original
49.155 +** database file.
49.156 +**
49.157 +** Details of important structure elements:
49.158 +**
49.159 +** needSync
49.160 +**
49.161 +** If this is true, this means that it is not safe to write the page
49.162 +** content to the database because the original content needed
49.163 +** for rollback has not by synced to the main rollback journal.
49.164 +** The original content may have been written to the rollback journal
49.165 +** but it has not yet been synced. So we cannot write to the database
49.166 +** file because power failure might cause the page in the journal file
49.167 +** to never reach the disk. It is as if the write to the journal file
49.168 +** does not occur until the journal file is synced.
49.169 +**
49.170 +** This flag is false if the page content exactly matches what
49.171 +** currently exists in the database file. The needSync flag is also
49.172 +** false if the original content has been written to the main rollback
49.173 +** journal and synced. If the page represents a new page that has
49.174 +** been added onto the end of the database during the current
49.175 +** transaction, the needSync flag is true until the original database
49.176 +** size in the journal header has been synced to disk.
49.177 +**
49.178 +** inJournal
49.179 +**
49.180 +** This is true if the original page has been written into the main
49.181 +** rollback journal. This is always false for new pages added to
49.182 +** the end of the database file during the current transaction.
49.183 +** And this flag says nothing about whether or not the journal
49.184 +** has been synced to disk. For pages that are in the original
49.185 +** database file, the following expression should always be true:
49.186 +**
49.187 +** inJournal = (pPager->aInJournal[(pgno-1)/8] & (1<<((pgno-1)%8))!=0
49.188 +**
49.189 +** The pPager->aInJournal[] array is only valid for the original
49.190 +** pages of the database, not new pages that are added to the end
49.191 +** of the database, so obviously the above expression cannot be
49.192 +** valid for new pages. For new pages inJournal is always 0.
49.193 +**
49.194 +** dirty
49.195 +**
49.196 +** When true, this means that the content of the page has been
49.197 +** modified and needs to be written back to the database file.
49.198 +** If false, it means that either the content of the page is
49.199 +** unchanged or else the content is unimportant and we do not
49.200 +** care whether or not it is preserved.
49.201 +**
49.202 +** alwaysRollback
49.203 +**
49.204 +** This means that the sqlite3PagerDontRollback() API should be
49.205 +** ignored for this page. The DontRollback() API attempts to say
49.206 +** that the content of the page on disk is unimportant (it is an
49.207 +** unused page on the freelist) so that it is unnecessary to
49.208 +** rollback changes to this page because the content of the page
49.209 +** can change without changing the meaning of the database. This
49.210 +** flag overrides any DontRollback() attempt. This flag is set
49.211 +** when a page that originally contained valid data is added to
49.212 +** the freelist. Later in the same transaction, this page might
49.213 +** be pulled from the freelist and reused for something different
49.214 +** and at that point the DontRollback() API will be called because
49.215 +** pages taken from the freelist do not need to be protected by
49.216 +** the rollback journal. But this flag says that the page was
49.217 +** not originally part of the freelist so that it still needs to
49.218 +** be rolled back in spite of any subsequent DontRollback() calls.
49.219 +**
49.220 +** needRead
49.221 +**
49.222 +** This flag means (when true) that the content of the page has
49.223 +** not yet been loaded from disk. The in-memory content is just
49.224 +** garbage. (Actually, we zero the content, but you should not
49.225 +** make any assumptions about the content nevertheless.) If the
49.226 +** content is needed in the future, it should be read from the
49.227 +** original database file.
49.228 +*/
49.229 +typedef struct PgHdr PgHdr;
49.230 +struct PgHdr {
49.231 + Pager *pPager; /* The pager to which this page belongs */
49.232 + Pgno pgno; /* The page number for this page */
49.233 + PgHdr *pNextHash, *pPrevHash; /* Hash collision chain for PgHdr.pgno */
49.234 + PgHdr *pNextFree, *pPrevFree; /* Freelist of pages where nRef==0 */
49.235 + PgHdr *pNextAll; /* A list of all pages */
49.236 + u8 inJournal; /* TRUE if has been written to journal */
49.237 + u8 dirty; /* TRUE if we need to write back changes */
49.238 + u8 needSync; /* Sync journal before writing this page */
49.239 + u8 alwaysRollback; /* Disable DontRollback() for this page */
49.240 + u8 needRead; /* Read content if PagerWrite() is called */
49.241 + short int nRef; /* Number of users of this page */
49.242 + PgHdr *pDirty, *pPrevDirty; /* Dirty pages */
49.243 + u32 notUsed; /* Buffer space */
49.244 +#ifdef SQLITE_CHECK_PAGES
49.245 + u32 pageHash;
49.246 +#endif
49.247 + /* pPager->pageSize bytes of page data follow this header */
49.248 + /* Pager.nExtra bytes of local data follow the page data */
49.249 +};
49.250 +
49.251 +/*
49.252 +** For an in-memory only database, some extra information is recorded about
49.253 +** each page so that changes can be rolled back. (Journal files are not
49.254 +** used for in-memory databases.) The following information is added to
49.255 +** the end of every EXTRA block for in-memory databases.
49.256 +**
49.257 +** This information could have been added directly to the PgHdr structure.
49.258 +** But then it would take up an extra 8 bytes of storage on every PgHdr
49.259 +** even for disk-based databases. Splitting it out saves 8 bytes. This
49.260 +** is only a savings of 0.8% but those percentages add up.
49.261 +*/
49.262 +typedef struct PgHistory PgHistory;
49.263 +struct PgHistory {
49.264 + u8 *pOrig; /* Original page text. Restore to this on a full rollback */
49.265 + u8 *pStmt; /* Text as it was at the beginning of the current statement */
49.266 + PgHdr *pNextStmt, *pPrevStmt; /* List of pages in the statement journal */
49.267 + u8 inStmt; /* TRUE if in the statement subjournal */
49.268 +};
49.269 +
49.270 +/*
49.271 +** A macro used for invoking the codec if there is one
49.272 +*/
49.273 +#ifdef SQLITE_HAS_CODEC
49.274 +# define CODEC1(P,D,N,X) if( P->xCodec!=0 ){ P->xCodec(P->pCodecArg,D,N,X); }
49.275 +# define CODEC2(P,D,N,X) ((char*)(P->xCodec!=0?P->xCodec(P->pCodecArg,D,N,X):D))
49.276 +#else
49.277 +# define CODEC1(P,D,N,X) /* NO-OP */
49.278 +# define CODEC2(P,D,N,X) ((char*)D)
49.279 +#endif
49.280 +
49.281 +/*
49.282 +** Convert a pointer to a PgHdr into a pointer to its data
49.283 +** and back again.
49.284 +*/
49.285 +#define PGHDR_TO_DATA(P) ((void*)(&(P)[1]))
49.286 +#define DATA_TO_PGHDR(D) (&((PgHdr*)(D))[-1])
49.287 +#define PGHDR_TO_EXTRA(G,P) ((void*)&((char*)(&(G)[1]))[(P)->pageSize])
49.288 +#define PGHDR_TO_HIST(P,PGR) \
49.289 + ((PgHistory*)&((char*)(&(P)[1]))[(PGR)->pageSize+(PGR)->nExtra])
49.290 +
49.291 +/*
49.292 +** A open page cache is an instance of the following structure.
49.293 +**
49.294 +** Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
49.295 +** or SQLITE_FULL. Once one of the first three errors occurs, it persists
49.296 +** and is returned as the result of every major pager API call. The
49.297 +** SQLITE_FULL return code is slightly different. It persists only until the
49.298 +** next successful rollback is performed on the pager cache. Also,
49.299 +** SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
49.300 +** APIs, they may still be used successfully.
49.301 +*/
49.302 +struct Pager {
49.303 + u8 journalOpen; /* True if journal file descriptors is valid */
49.304 + u8 journalStarted; /* True if header of journal is synced */
49.305 + u8 useJournal; /* Use a rollback journal on this file */
49.306 + u8 noReadlock; /* Do not bother to obtain readlocks */
49.307 + u8 stmtOpen; /* True if the statement subjournal is open */
49.308 + u8 stmtInUse; /* True we are in a statement subtransaction */
49.309 + u8 stmtAutoopen; /* Open stmt journal when main journal is opened*/
49.310 + u8 noSync; /* Do not sync the journal if true */
49.311 + u8 fullSync; /* Do extra syncs of the journal for robustness */
49.312 + u8 full_fsync; /* Use F_FULLFSYNC when available */
49.313 + u8 state; /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
49.314 + u8 tempFile; /* zFilename is a temporary file */
49.315 + u8 readOnly; /* True for a read-only database */
49.316 + u8 needSync; /* True if an fsync() is needed on the journal */
49.317 + u8 dirtyCache; /* True if cached pages have changed */
49.318 + u8 alwaysRollback; /* Disable DontRollback() for all pages */
49.319 + u8 memDb; /* True to inhibit all file I/O */
49.320 + u8 setMaster; /* True if a m-j name has been written to jrnl */
49.321 + u8 doNotSync; /* Boolean. While true, do not spill the cache */
49.322 + u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
49.323 + u8 changeCountDone; /* Set after incrementing the change-counter */
49.324 + int errCode; /* One of several kinds of errors */
49.325 + int dbSize; /* Number of pages in the file */
49.326 + int origDbSize; /* dbSize before the current change */
49.327 + int stmtSize; /* Size of database (in pages) at stmt_begin() */
49.328 + int nRec; /* Number of pages written to the journal */
49.329 + u32 cksumInit; /* Quasi-random value added to every checksum */
49.330 + int stmtNRec; /* Number of records in stmt subjournal */
49.331 + int nExtra; /* Add this many bytes to each in-memory page */
49.332 + int pageSize; /* Number of bytes in a page */
49.333 + int nPage; /* Total number of in-memory pages */
49.334 + int nRef; /* Number of in-memory pages with PgHdr.nRef>0 */
49.335 + int mxPage; /* Maximum number of pages to hold in cache */
49.336 + Pgno mxPgno; /* Maximum allowed size of the database */
49.337 + u8 *aInJournal; /* One bit for each page in the database file */
49.338 + u8 *aInStmt; /* One bit for each page in the database */
49.339 + char *zFilename; /* Name of the database file */
49.340 + char *zJournal; /* Name of the journal file */
49.341 + char *zDirectory; /* Directory hold database and journal files */
49.342 + OsFile *fd, *jfd; /* File descriptors for database and journal */
49.343 + OsFile *stfd; /* File descriptor for the statement subjournal*/
49.344 + BusyHandler *pBusyHandler; /* Pointer to sqlite.busyHandler */
49.345 + PgHdr *pFirst, *pLast; /* List of free pages */
49.346 + PgHdr *pFirstSynced; /* First free page with PgHdr.needSync==0 */
49.347 + PgHdr *pAll; /* List of all pages */
49.348 + PgHdr *pStmt; /* List of pages in the statement subjournal */
49.349 + PgHdr *pDirty; /* List of all dirty pages */
49.350 + i64 journalOff; /* Current byte offset in the journal file */
49.351 + i64 journalHdr; /* Byte offset to previous journal header */
49.352 + i64 stmtHdrOff; /* First journal header written this statement */
49.353 + i64 stmtCksum; /* cksumInit when statement was started */
49.354 + i64 stmtJSize; /* Size of journal at stmt_begin() */
49.355 + int sectorSize; /* Assumed sector size during rollback */
49.356 +#ifdef SQLITE_TEST
49.357 + int nHit, nMiss; /* Cache hits and missing */
49.358 + int nRead, nWrite; /* Database pages read/written */
49.359 +#endif
49.360 + void (*xDestructor)(DbPage*,int); /* Call this routine when freeing pages */
49.361 + void (*xReiniter)(DbPage*,int); /* Call this routine when reloading pages */
49.362 +#ifdef SQLITE_HAS_CODEC
49.363 + void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
49.364 + void *pCodecArg; /* First argument to xCodec() */
49.365 +#endif
49.366 + int nHash; /* Size of the pager hash table */
49.367 + PgHdr **aHash; /* Hash table to map page number to PgHdr */
49.368 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
49.369 + Pager *pNext; /* Linked list of pagers in this thread */
49.370 +#endif
49.371 + char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
49.372 + char dbFileVers[16]; /* Changes whenever database file changes */
49.373 +};
49.374 +
49.375 +/*
49.376 +** The following global variables hold counters used for
49.377 +** testing purposes only. These variables do not exist in
49.378 +** a non-testing build. These variables are not thread-safe.
49.379 +*/
49.380 +#ifdef SQLITE_TEST
49.381 +int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
49.382 +int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
49.383 +int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
49.384 +int sqlite3_pager_pgfree_count = 0; /* Number of cache pages freed */
49.385 +# define PAGER_INCR(v) v++
49.386 +#else
49.387 +# define PAGER_INCR(v)
49.388 +#endif
49.389 +
49.390 +
49.391 +
49.392 +/*
49.393 +** Journal files begin with the following magic string. The data
49.394 +** was obtained from /dev/random. It is used only as a sanity check.
49.395 +**
49.396 +** Since version 2.8.0, the journal format contains additional sanity
49.397 +** checking information. If the power fails while the journal is begin
49.398 +** written, semi-random garbage data might appear in the journal
49.399 +** file after power is restored. If an attempt is then made
49.400 +** to roll the journal back, the database could be corrupted. The additional
49.401 +** sanity checking data is an attempt to discover the garbage in the
49.402 +** journal and ignore it.
49.403 +**
49.404 +** The sanity checking information for the new journal format consists
49.405 +** of a 32-bit checksum on each page of data. The checksum covers both
49.406 +** the page number and the pPager->pageSize bytes of data for the page.
49.407 +** This cksum is initialized to a 32-bit random value that appears in the
49.408 +** journal file right after the header. The random initializer is important,
49.409 +** because garbage data that appears at the end of a journal is likely
49.410 +** data that was once in other files that have now been deleted. If the
49.411 +** garbage data came from an obsolete journal file, the checksums might
49.412 +** be correct. But by initializing the checksum to random value which
49.413 +** is different for every journal, we minimize that risk.
49.414 +*/
49.415 +static const unsigned char aJournalMagic[] = {
49.416 + 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
49.417 +};
49.418 +
49.419 +/*
49.420 +** The size of the header and of each page in the journal is determined
49.421 +** by the following macros.
49.422 +*/
49.423 +#define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
49.424 +
49.425 +/*
49.426 +** The journal header size for this pager. In the future, this could be
49.427 +** set to some value read from the disk controller. The important
49.428 +** characteristic is that it is the same size as a disk sector.
49.429 +*/
49.430 +#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
49.431 +
49.432 +/*
49.433 +** The macro MEMDB is true if we are dealing with an in-memory database.
49.434 +** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
49.435 +** the value of MEMDB will be a constant and the compiler will optimize
49.436 +** out code that would never execute.
49.437 +*/
49.438 +#ifdef SQLITE_OMIT_MEMORYDB
49.439 +# define MEMDB 0
49.440 +#else
49.441 +# define MEMDB pPager->memDb
49.442 +#endif
49.443 +
49.444 +/*
49.445 +** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
49.446 +** reserved for working around a windows/posix incompatibility). It is
49.447 +** used in the journal to signify that the remainder of the journal file
49.448 +** is devoted to storing a master journal name - there are no more pages to
49.449 +** roll back. See comments for function writeMasterJournal() for details.
49.450 +*/
49.451 +/* #define PAGER_MJ_PGNO(x) (PENDING_BYTE/((x)->pageSize)) */
49.452 +#define PAGER_MJ_PGNO(x) ((PENDING_BYTE/((x)->pageSize))+1)
49.453 +
49.454 +/*
49.455 +** The maximum legal page number is (2^31 - 1).
49.456 +*/
49.457 +#define PAGER_MAX_PGNO 2147483647
49.458 +
49.459 +/*
49.460 +** Enable reference count tracking (for debugging) here:
49.461 +*/
49.462 +#ifdef SQLITE_DEBUG
49.463 + int pager3_refinfo_enable = 0;
49.464 + static void pager_refinfo(PgHdr *p){
49.465 + static int cnt = 0;
49.466 + if( !pager3_refinfo_enable ) return;
49.467 + sqlite3DebugPrintf(
49.468 + "REFCNT: %4d addr=%p nRef=%-3d total=%d\n",
49.469 + p->pgno, PGHDR_TO_DATA(p), p->nRef, p->pPager->nRef
49.470 + );
49.471 + cnt++; /* Something to set a breakpoint on */
49.472 + }
49.473 +# define REFINFO(X) pager_refinfo(X)
49.474 +#else
49.475 +# define REFINFO(X)
49.476 +#endif
49.477 +
49.478 +/*
49.479 +** Return true if page *pPg has already been written to the statement
49.480 +** journal (or statement snapshot has been created, if *pPg is part
49.481 +** of an in-memory database).
49.482 +*/
49.483 +static int pageInStatement(PgHdr *pPg){
49.484 + Pager *pPager = pPg->pPager;
49.485 + if( MEMDB ){
49.486 + return PGHDR_TO_HIST(pPg, pPager)->inStmt;
49.487 + }else{
49.488 + Pgno pgno = pPg->pgno;
49.489 + u8 *a = pPager->aInStmt;
49.490 + return (a && (int)pgno<=pPager->stmtSize && (a[pgno/8] & (1<<(pgno&7))));
49.491 + }
49.492 +}
49.493 +
49.494 +/*
49.495 +** Change the size of the pager hash table to N. N must be a power
49.496 +** of two.
49.497 +*/
49.498 +static void pager_resize_hash_table(Pager *pPager, int N){
49.499 + PgHdr **aHash, *pPg;
49.500 + assert( N>0 && (N&(N-1))==0 );
49.501 + aHash = sqliteMalloc( sizeof(aHash[0])*N );
49.502 + if( aHash==0 ){
49.503 + /* Failure to rehash is not an error. It is only a performance hit. */
49.504 + return;
49.505 + }
49.506 + sqliteFree(pPager->aHash);
49.507 + pPager->nHash = N;
49.508 + pPager->aHash = aHash;
49.509 + for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
49.510 + int h;
49.511 + if( pPg->pgno==0 ){
49.512 + assert( pPg->pNextHash==0 && pPg->pPrevHash==0 );
49.513 + continue;
49.514 + }
49.515 + h = pPg->pgno & (N-1);
49.516 + pPg->pNextHash = aHash[h];
49.517 + if( aHash[h] ){
49.518 + aHash[h]->pPrevHash = pPg;
49.519 + }
49.520 + aHash[h] = pPg;
49.521 + pPg->pPrevHash = 0;
49.522 + }
49.523 +}
49.524 +
49.525 +/*
49.526 +** Read a 32-bit integer from the given file descriptor. Store the integer
49.527 +** that is read in *pRes. Return SQLITE_OK if everything worked, or an
49.528 +** error code is something goes wrong.
49.529 +**
49.530 +** All values are stored on disk as big-endian.
49.531 +*/
49.532 +static int read32bits(OsFile *fd, u32 *pRes){
49.533 + unsigned char ac[4];
49.534 + int rc = sqlite3OsRead(fd, ac, sizeof(ac));
49.535 + if( rc==SQLITE_OK ){
49.536 + *pRes = sqlite3Get4byte(ac);
49.537 + }
49.538 + return rc;
49.539 +}
49.540 +
49.541 +/*
49.542 +** Write a 32-bit integer into a string buffer in big-endian byte order.
49.543 +*/
49.544 +#define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
49.545 +
49.546 +/*
49.547 +** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
49.548 +** on success or an error code is something goes wrong.
49.549 +*/
49.550 +static int write32bits(OsFile *fd, u32 val){
49.551 + char ac[4];
49.552 + put32bits(ac, val);
49.553 + return sqlite3OsWrite(fd, ac, 4);
49.554 +}
49.555 +
49.556 +/*
49.557 +** This function should be called when an error occurs within the pager
49.558 +** code. The first argument is a pointer to the pager structure, the
49.559 +** second the error-code about to be returned by a pager API function.
49.560 +** The value returned is a copy of the second argument to this function.
49.561 +**
49.562 +** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
49.563 +** the error becomes persistent. All subsequent API calls on this Pager
49.564 +** will immediately return the same error code.
49.565 +*/
49.566 +static int pager_error(Pager *pPager, int rc){
49.567 + int rc2 = rc & 0xff;
49.568 + assert( pPager->errCode==SQLITE_FULL || pPager->errCode==SQLITE_OK );
49.569 + if(
49.570 + rc2==SQLITE_FULL ||
49.571 + rc2==SQLITE_IOERR ||
49.572 + rc2==SQLITE_CORRUPT
49.573 + ){
49.574 + pPager->errCode = rc;
49.575 + }
49.576 + return rc;
49.577 +}
49.578 +
49.579 +/*
49.580 +** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
49.581 +** on the cache using a hash function. This is used for testing
49.582 +** and debugging only.
49.583 +*/
49.584 +#ifdef SQLITE_CHECK_PAGES
49.585 +/*
49.586 +** Return a 32-bit hash of the page data for pPage.
49.587 +*/
49.588 +static u32 pager_datahash(int nByte, unsigned char *pData){
49.589 + u32 hash = 0;
49.590 + int i;
49.591 + for(i=0; i<nByte; i++){
49.592 + hash = (hash*1039) + pData[i];
49.593 + }
49.594 + return hash;
49.595 +}
49.596 +static u32 pager_pagehash(PgHdr *pPage){
49.597 + return pager_datahash(pPage->pPager->pageSize,
49.598 + (unsigned char *)PGHDR_TO_DATA(pPage));
49.599 +}
49.600 +
49.601 +/*
49.602 +** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
49.603 +** is defined, and NDEBUG is not defined, an assert() statement checks
49.604 +** that the page is either dirty or still matches the calculated page-hash.
49.605 +*/
49.606 +#define CHECK_PAGE(x) checkPage(x)
49.607 +static void checkPage(PgHdr *pPg){
49.608 + Pager *pPager = pPg->pPager;
49.609 + assert( !pPg->pageHash || pPager->errCode || MEMDB || pPg->dirty ||
49.610 + pPg->pageHash==pager_pagehash(pPg) );
49.611 +}
49.612 +
49.613 +#else
49.614 +#define pager_datahash(X,Y) 0
49.615 +#define pager_pagehash(X) 0
49.616 +#define CHECK_PAGE(x)
49.617 +#endif
49.618 +
49.619 +/*
49.620 +** When this is called the journal file for pager pPager must be open.
49.621 +** The master journal file name is read from the end of the file and
49.622 +** written into memory obtained from sqliteMalloc(). *pzMaster is
49.623 +** set to point at the memory and SQLITE_OK returned. The caller must
49.624 +** sqliteFree() *pzMaster.
49.625 +**
49.626 +** If no master journal file name is present *pzMaster is set to 0 and
49.627 +** SQLITE_OK returned.
49.628 +*/
49.629 +static int readMasterJournal(OsFile *pJrnl, char **pzMaster){
49.630 + int rc;
49.631 + u32 len;
49.632 + i64 szJ;
49.633 + u32 cksum;
49.634 + int i;
49.635 + unsigned char aMagic[8]; /* A buffer to hold the magic header */
49.636 +
49.637 + *pzMaster = 0;
49.638 +
49.639 + rc = sqlite3OsFileSize(pJrnl, &szJ);
49.640 + if( rc!=SQLITE_OK || szJ<16 ) return rc;
49.641 +
49.642 + rc = sqlite3OsSeek(pJrnl, szJ-16);
49.643 + if( rc!=SQLITE_OK ) return rc;
49.644 +
49.645 + rc = read32bits(pJrnl, &len);
49.646 + if( rc!=SQLITE_OK ) return rc;
49.647 +
49.648 + rc = read32bits(pJrnl, &cksum);
49.649 + if( rc!=SQLITE_OK ) return rc;
49.650 +
49.651 + rc = sqlite3OsRead(pJrnl, aMagic, 8);
49.652 + if( rc!=SQLITE_OK || memcmp(aMagic, aJournalMagic, 8) ) return rc;
49.653 +
49.654 + rc = sqlite3OsSeek(pJrnl, szJ-16-len);
49.655 + if( rc!=SQLITE_OK ) return rc;
49.656 +
49.657 + *pzMaster = (char *)sqliteMalloc(len+1);
49.658 + if( !*pzMaster ){
49.659 + return SQLITE_NOMEM;
49.660 + }
49.661 + rc = sqlite3OsRead(pJrnl, *pzMaster, len);
49.662 + if( rc!=SQLITE_OK ){
49.663 + sqliteFree(*pzMaster);
49.664 + *pzMaster = 0;
49.665 + return rc;
49.666 + }
49.667 +
49.668 + /* See if the checksum matches the master journal name */
49.669 + for(i=0; i<len; i++){
49.670 + cksum -= (*pzMaster)[i];
49.671 + }
49.672 + if( cksum ){
49.673 + /* If the checksum doesn't add up, then one or more of the disk sectors
49.674 + ** containing the master journal filename is corrupted. This means
49.675 + ** definitely roll back, so just return SQLITE_OK and report a (nul)
49.676 + ** master-journal filename.
49.677 + */
49.678 + sqliteFree(*pzMaster);
49.679 + *pzMaster = 0;
49.680 + }else{
49.681 + (*pzMaster)[len] = '\0';
49.682 + }
49.683 +
49.684 + return SQLITE_OK;
49.685 +}
49.686 +
49.687 +/*
49.688 +** Seek the journal file descriptor to the next sector boundary where a
49.689 +** journal header may be read or written. Pager.journalOff is updated with
49.690 +** the new seek offset.
49.691 +**
49.692 +** i.e for a sector size of 512:
49.693 +**
49.694 +** Input Offset Output Offset
49.695 +** ---------------------------------------
49.696 +** 0 0
49.697 +** 512 512
49.698 +** 100 512
49.699 +** 2000 2048
49.700 +**
49.701 +*/
49.702 +static int seekJournalHdr(Pager *pPager){
49.703 + i64 offset = 0;
49.704 + i64 c = pPager->journalOff;
49.705 + if( c ){
49.706 + offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
49.707 + }
49.708 + assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
49.709 + assert( offset>=c );
49.710 + assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
49.711 + pPager->journalOff = offset;
49.712 + return sqlite3OsSeek(pPager->jfd, pPager->journalOff);
49.713 +}
49.714 +
49.715 +/*
49.716 +** The journal file must be open when this routine is called. A journal
49.717 +** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
49.718 +** current location.
49.719 +**
49.720 +** The format for the journal header is as follows:
49.721 +** - 8 bytes: Magic identifying journal format.
49.722 +** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
49.723 +** - 4 bytes: Random number used for page hash.
49.724 +** - 4 bytes: Initial database page count.
49.725 +** - 4 bytes: Sector size used by the process that wrote this journal.
49.726 +**
49.727 +** Followed by (JOURNAL_HDR_SZ - 24) bytes of unused space.
49.728 +*/
49.729 +static int writeJournalHdr(Pager *pPager){
49.730 + char zHeader[sizeof(aJournalMagic)+16];
49.731 + int rc;
49.732 +
49.733 + if( pPager->stmtHdrOff==0 ){
49.734 + pPager->stmtHdrOff = pPager->journalOff;
49.735 + }
49.736 +
49.737 + rc = seekJournalHdr(pPager);
49.738 + if( rc ) return rc;
49.739 +
49.740 + pPager->journalHdr = pPager->journalOff;
49.741 + pPager->journalOff += JOURNAL_HDR_SZ(pPager);
49.742 +
49.743 + /* FIX ME:
49.744 + **
49.745 + ** Possibly for a pager not in no-sync mode, the journal magic should not
49.746 + ** be written until nRec is filled in as part of next syncJournal().
49.747 + **
49.748 + ** Actually maybe the whole journal header should be delayed until that
49.749 + ** point. Think about this.
49.750 + */
49.751 + memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
49.752 + /* The nRec Field. 0xFFFFFFFF for no-sync journals. */
49.753 + put32bits(&zHeader[sizeof(aJournalMagic)], pPager->noSync ? 0xffffffff : 0);
49.754 + /* The random check-hash initialiser */
49.755 + sqlite3Randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
49.756 + put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
49.757 + /* The initial database size */
49.758 + put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbSize);
49.759 + /* The assumed sector size for this process */
49.760 + put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
49.761 + IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, sizeof(zHeader)))
49.762 + rc = sqlite3OsWrite(pPager->jfd, zHeader, sizeof(zHeader));
49.763 +
49.764 + /* The journal header has been written successfully. Seek the journal
49.765 + ** file descriptor to the end of the journal header sector.
49.766 + */
49.767 + if( rc==SQLITE_OK ){
49.768 + IOTRACE(("JTAIL %p %lld\n", pPager, pPager->journalOff-1))
49.769 + rc = sqlite3OsSeek(pPager->jfd, pPager->journalOff-1);
49.770 + if( rc==SQLITE_OK ){
49.771 + rc = sqlite3OsWrite(pPager->jfd, "\000", 1);
49.772 + }
49.773 + }
49.774 + return rc;
49.775 +}
49.776 +
49.777 +/*
49.778 +** The journal file must be open when this is called. A journal header file
49.779 +** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
49.780 +** file. See comments above function writeJournalHdr() for a description of
49.781 +** the journal header format.
49.782 +**
49.783 +** If the header is read successfully, *nRec is set to the number of
49.784 +** page records following this header and *dbSize is set to the size of the
49.785 +** database before the transaction began, in pages. Also, pPager->cksumInit
49.786 +** is set to the value read from the journal header. SQLITE_OK is returned
49.787 +** in this case.
49.788 +**
49.789 +** If the journal header file appears to be corrupted, SQLITE_DONE is
49.790 +** returned and *nRec and *dbSize are not set. If JOURNAL_HDR_SZ bytes
49.791 +** cannot be read from the journal file an error code is returned.
49.792 +*/
49.793 +static int readJournalHdr(
49.794 + Pager *pPager,
49.795 + i64 journalSize,
49.796 + u32 *pNRec,
49.797 + u32 *pDbSize
49.798 +){
49.799 + int rc;
49.800 + unsigned char aMagic[8]; /* A buffer to hold the magic header */
49.801 +
49.802 + rc = seekJournalHdr(pPager);
49.803 + if( rc ) return rc;
49.804 +
49.805 + if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
49.806 + return SQLITE_DONE;
49.807 + }
49.808 +
49.809 + rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic));
49.810 + if( rc ) return rc;
49.811 +
49.812 + if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
49.813 + return SQLITE_DONE;
49.814 + }
49.815 +
49.816 + rc = read32bits(pPager->jfd, pNRec);
49.817 + if( rc ) return rc;
49.818 +
49.819 + rc = read32bits(pPager->jfd, &pPager->cksumInit);
49.820 + if( rc ) return rc;
49.821 +
49.822 + rc = read32bits(pPager->jfd, pDbSize);
49.823 + if( rc ) return rc;
49.824 +
49.825 + /* Update the assumed sector-size to match the value used by
49.826 + ** the process that created this journal. If this journal was
49.827 + ** created by a process other than this one, then this routine
49.828 + ** is being called from within pager_playback(). The local value
49.829 + ** of Pager.sectorSize is restored at the end of that routine.
49.830 + */
49.831 + rc = read32bits(pPager->jfd, (u32 *)&pPager->sectorSize);
49.832 + if( rc ) return rc;
49.833 +
49.834 + pPager->journalOff += JOURNAL_HDR_SZ(pPager);
49.835 + rc = sqlite3OsSeek(pPager->jfd, pPager->journalOff);
49.836 + return rc;
49.837 +}
49.838 +
49.839 +
49.840 +/*
49.841 +** Write the supplied master journal name into the journal file for pager
49.842 +** pPager at the current location. The master journal name must be the last
49.843 +** thing written to a journal file. If the pager is in full-sync mode, the
49.844 +** journal file descriptor is advanced to the next sector boundary before
49.845 +** anything is written. The format is:
49.846 +**
49.847 +** + 4 bytes: PAGER_MJ_PGNO.
49.848 +** + N bytes: length of master journal name.
49.849 +** + 4 bytes: N
49.850 +** + 4 bytes: Master journal name checksum.
49.851 +** + 8 bytes: aJournalMagic[].
49.852 +**
49.853 +** The master journal page checksum is the sum of the bytes in the master
49.854 +** journal name.
49.855 +**
49.856 +** If zMaster is a NULL pointer (occurs for a single database transaction),
49.857 +** this call is a no-op.
49.858 +*/
49.859 +static int writeMasterJournal(Pager *pPager, const char *zMaster){
49.860 + int rc;
49.861 + int len;
49.862 + int i;
49.863 + u32 cksum = 0;
49.864 + char zBuf[sizeof(aJournalMagic)+2*4];
49.865 +
49.866 + if( !zMaster || pPager->setMaster) return SQLITE_OK;
49.867 + pPager->setMaster = 1;
49.868 +
49.869 + len = strlen(zMaster);
49.870 + for(i=0; i<len; i++){
49.871 + cksum += zMaster[i];
49.872 + }
49.873 +
49.874 + /* If in full-sync mode, advance to the next disk sector before writing
49.875 + ** the master journal name. This is in case the previous page written to
49.876 + ** the journal has already been synced.
49.877 + */
49.878 + if( pPager->fullSync ){
49.879 + rc = seekJournalHdr(pPager);
49.880 + if( rc!=SQLITE_OK ) return rc;
49.881 + }
49.882 + pPager->journalOff += (len+20);
49.883 +
49.884 + rc = write32bits(pPager->jfd, PAGER_MJ_PGNO(pPager));
49.885 + if( rc!=SQLITE_OK ) return rc;
49.886 +
49.887 + rc = sqlite3OsWrite(pPager->jfd, zMaster, len);
49.888 + if( rc!=SQLITE_OK ) return rc;
49.889 +
49.890 + put32bits(zBuf, len);
49.891 + put32bits(&zBuf[4], cksum);
49.892 + memcpy(&zBuf[8], aJournalMagic, sizeof(aJournalMagic));
49.893 + rc = sqlite3OsWrite(pPager->jfd, zBuf, 8+sizeof(aJournalMagic));
49.894 + pPager->needSync = !pPager->noSync;
49.895 + return rc;
49.896 +}
49.897 +
49.898 +/*
49.899 +** Add or remove a page from the list of all pages that are in the
49.900 +** statement journal.
49.901 +**
49.902 +** The Pager keeps a separate list of pages that are currently in
49.903 +** the statement journal. This helps the sqlite3PagerStmtCommit()
49.904 +** routine run MUCH faster for the common case where there are many
49.905 +** pages in memory but only a few are in the statement journal.
49.906 +*/
49.907 +static void page_add_to_stmt_list(PgHdr *pPg){
49.908 + Pager *pPager = pPg->pPager;
49.909 + PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
49.910 + assert( MEMDB );
49.911 + if( !pHist->inStmt ){
49.912 + assert( pHist->pPrevStmt==0 && pHist->pNextStmt==0 );
49.913 + if( pPager->pStmt ){
49.914 + PGHDR_TO_HIST(pPager->pStmt, pPager)->pPrevStmt = pPg;
49.915 + }
49.916 + pHist->pNextStmt = pPager->pStmt;
49.917 + pPager->pStmt = pPg;
49.918 + pHist->inStmt = 1;
49.919 + }
49.920 +}
49.921 +
49.922 +/*
49.923 +** Find a page in the hash table given its page number. Return
49.924 +** a pointer to the page or NULL if not found.
49.925 +*/
49.926 +static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
49.927 + PgHdr *p;
49.928 + if( pPager->aHash==0 ) return 0;
49.929 + p = pPager->aHash[pgno & (pPager->nHash-1)];
49.930 + while( p && p->pgno!=pgno ){
49.931 + p = p->pNextHash;
49.932 + }
49.933 + return p;
49.934 +}
49.935 +
49.936 +/*
49.937 +** Unlock the database file.
49.938 +*/
49.939 +static void pager_unlock(Pager *pPager){
49.940 + if( !pPager->exclusiveMode ){
49.941 + if( !MEMDB ){
49.942 + sqlite3OsUnlock(pPager->fd, NO_LOCK);
49.943 + pPager->dbSize = -1;
49.944 + IOTRACE(("UNLOCK %p\n", pPager))
49.945 + }
49.946 + pPager->state = PAGER_UNLOCK;
49.947 + pPager->changeCountDone = 0;
49.948 + }
49.949 +}
49.950 +
49.951 +/*
49.952 +** Execute a rollback if a transaction is active and unlock the
49.953 +** database file. This is a no-op if the pager has already entered
49.954 +** the error-state.
49.955 +*/
49.956 +static void pagerUnlockAndRollback(Pager *p){
49.957 + if( p->errCode ) return;
49.958 + assert( p->state>=PAGER_RESERVED || p->journalOpen==0 );
49.959 + if( p->state>=PAGER_RESERVED ){
49.960 + sqlite3PagerRollback(p);
49.961 + }
49.962 + pager_unlock(p);
49.963 + assert( p->errCode || !p->journalOpen || (p->exclusiveMode&&!p->journalOff) );
49.964 + assert( p->errCode || !p->stmtOpen || p->exclusiveMode );
49.965 +}
49.966 +
49.967 +
49.968 +/*
49.969 +** Clear the in-memory cache. This routine
49.970 +** sets the state of the pager back to what it was when it was first
49.971 +** opened. Any outstanding pages are invalidated and subsequent attempts
49.972 +** to access those pages will likely result in a coredump.
49.973 +*/
49.974 +static void pager_reset(Pager *pPager){
49.975 + PgHdr *pPg, *pNext;
49.976 + if( pPager->errCode ) return;
49.977 + for(pPg=pPager->pAll; pPg; pPg=pNext){
49.978 + IOTRACE(("PGFREE %p %d\n", pPager, pPg->pgno));
49.979 + PAGER_INCR(sqlite3_pager_pgfree_count);
49.980 + pNext = pPg->pNextAll;
49.981 + sqliteFree(pPg);
49.982 + }
49.983 + pPager->pStmt = 0;
49.984 + pPager->pFirst = 0;
49.985 + pPager->pFirstSynced = 0;
49.986 + pPager->pLast = 0;
49.987 + pPager->pAll = 0;
49.988 + pPager->nHash = 0;
49.989 + sqliteFree(pPager->aHash);
49.990 + pPager->nPage = 0;
49.991 + pPager->aHash = 0;
49.992 + pPager->nRef = 0;
49.993 +}
49.994 +
49.995 +/*
49.996 +** This routine ends a transaction. A transaction is ended by either
49.997 +** a COMMIT or a ROLLBACK.
49.998 +**
49.999 +** When this routine is called, the pager has the journal file open and
49.1000 +** a RESERVED or EXCLUSIVE lock on the database. This routine will release
49.1001 +** the database lock and acquires a SHARED lock in its place if that is
49.1002 +** the appropriate thing to do. Release locks usually is appropriate,
49.1003 +** unless we are in exclusive access mode or unless this is a
49.1004 +** COMMIT AND BEGIN or ROLLBACK AND BEGIN operation.
49.1005 +**
49.1006 +** The journal file is either deleted or truncated.
49.1007 +**
49.1008 +** TODO: Consider keeping the journal file open for temporary databases.
49.1009 +** This might give a performance improvement on windows where opening
49.1010 +** a file is an expensive operation.
49.1011 +*/
49.1012 +static int pager_end_transaction(Pager *pPager){
49.1013 + PgHdr *pPg;
49.1014 + int rc = SQLITE_OK;
49.1015 + int rc2 = SQLITE_OK;
49.1016 + assert( !MEMDB );
49.1017 + if( pPager->state<PAGER_RESERVED ){
49.1018 + return SQLITE_OK;
49.1019 + }
49.1020 + sqlite3PagerStmtCommit(pPager);
49.1021 + if( pPager->stmtOpen && !pPager->exclusiveMode ){
49.1022 + sqlite3OsClose(&pPager->stfd);
49.1023 + pPager->stmtOpen = 0;
49.1024 + }
49.1025 + if( pPager->journalOpen ){
49.1026 + if( pPager->exclusiveMode
49.1027 + && (rc = sqlite3OsTruncate(pPager->jfd, 0))==SQLITE_OK ){;
49.1028 + sqlite3OsSeek(pPager->jfd, 0);
49.1029 + pPager->journalOff = 0;
49.1030 + pPager->journalStarted = 0;
49.1031 + }else{
49.1032 + sqlite3OsClose(&pPager->jfd);
49.1033 + pPager->journalOpen = 0;
49.1034 + if( rc==SQLITE_OK ){
49.1035 + rc = sqlite3OsDelete(pPager->zJournal);
49.1036 + }
49.1037 + }
49.1038 + sqliteFree( pPager->aInJournal );
49.1039 + pPager->aInJournal = 0;
49.1040 + for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
49.1041 + pPg->inJournal = 0;
49.1042 + pPg->dirty = 0;
49.1043 + pPg->needSync = 0;
49.1044 + pPg->alwaysRollback = 0;
49.1045 +#ifdef SQLITE_CHECK_PAGES
49.1046 + pPg->pageHash = pager_pagehash(pPg);
49.1047 +#endif
49.1048 + }
49.1049 + pPager->pDirty = 0;
49.1050 + pPager->dirtyCache = 0;
49.1051 + pPager->nRec = 0;
49.1052 + }else{
49.1053 + assert( pPager->aInJournal==0 );
49.1054 + assert( pPager->dirtyCache==0 || pPager->useJournal==0 );
49.1055 + }
49.1056 +
49.1057 + if( !pPager->exclusiveMode ){
49.1058 + rc2 = sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
49.1059 + pPager->state = PAGER_SHARED;
49.1060 + }else if( pPager->state==PAGER_SYNCED ){
49.1061 + pPager->state = PAGER_EXCLUSIVE;
49.1062 + }
49.1063 + pPager->origDbSize = 0;
49.1064 + pPager->setMaster = 0;
49.1065 + pPager->needSync = 0;
49.1066 + pPager->pFirstSynced = pPager->pFirst;
49.1067 + pPager->dbSize = -1;
49.1068 +
49.1069 + return (rc==SQLITE_OK?rc2:rc);
49.1070 +}
49.1071 +
49.1072 +/*
49.1073 +** Compute and return a checksum for the page of data.
49.1074 +**
49.1075 +** This is not a real checksum. It is really just the sum of the
49.1076 +** random initial value and the page number. We experimented with
49.1077 +** a checksum of the entire data, but that was found to be too slow.
49.1078 +**
49.1079 +** Note that the page number is stored at the beginning of data and
49.1080 +** the checksum is stored at the end. This is important. If journal
49.1081 +** corruption occurs due to a power failure, the most likely scenario
49.1082 +** is that one end or the other of the record will be changed. It is
49.1083 +** much less likely that the two ends of the journal record will be
49.1084 +** correct and the middle be corrupt. Thus, this "checksum" scheme,
49.1085 +** though fast and simple, catches the mostly likely kind of corruption.
49.1086 +**
49.1087 +** FIX ME: Consider adding every 200th (or so) byte of the data to the
49.1088 +** checksum. That way if a single page spans 3 or more disk sectors and
49.1089 +** only the middle sector is corrupt, we will still have a reasonable
49.1090 +** chance of failing the checksum and thus detecting the problem.
49.1091 +*/
49.1092 +static u32 pager_cksum(Pager *pPager, const u8 *aData){
49.1093 + u32 cksum = pPager->cksumInit;
49.1094 + int i = pPager->pageSize-200;
49.1095 + while( i>0 ){
49.1096 + cksum += aData[i];
49.1097 + i -= 200;
49.1098 + }
49.1099 + return cksum;
49.1100 +}
49.1101 +
49.1102 +/* Forward declaration */
49.1103 +static void makeClean(PgHdr*);
49.1104 +
49.1105 +/*
49.1106 +** Read a single page from the journal file opened on file descriptor
49.1107 +** jfd. Playback this one page.
49.1108 +**
49.1109 +** If useCksum==0 it means this journal does not use checksums. Checksums
49.1110 +** are not used in statement journals because statement journals do not
49.1111 +** need to survive power failures.
49.1112 +*/
49.1113 +static int pager_playback_one_page(Pager *pPager, OsFile *jfd, int useCksum){
49.1114 + int rc;
49.1115 + PgHdr *pPg; /* An existing page in the cache */
49.1116 + Pgno pgno; /* The page number of a page in journal */
49.1117 + u32 cksum; /* Checksum used for sanity checking */
49.1118 + u8 *aData = (u8 *)pPager->pTmpSpace; /* Temp storage for a page */
49.1119 +
49.1120 + /* useCksum should be true for the main journal and false for
49.1121 + ** statement journals. Verify that this is always the case
49.1122 + */
49.1123 + assert( jfd == (useCksum ? pPager->jfd : pPager->stfd) );
49.1124 + assert( aData );
49.1125 +
49.1126 + rc = read32bits(jfd, &pgno);
49.1127 + if( rc!=SQLITE_OK ) return rc;
49.1128 + rc = sqlite3OsRead(jfd, aData, pPager->pageSize);
49.1129 + if( rc!=SQLITE_OK ) return rc;
49.1130 + pPager->journalOff += pPager->pageSize + 4;
49.1131 +
49.1132 + /* Sanity checking on the page. This is more important that I originally
49.1133 + ** thought. If a power failure occurs while the journal is being written,
49.1134 + ** it could cause invalid data to be written into the journal. We need to
49.1135 + ** detect this invalid data (with high probability) and ignore it.
49.1136 + */
49.1137 + if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
49.1138 + return SQLITE_DONE;
49.1139 + }
49.1140 + if( pgno>(unsigned)pPager->dbSize ){
49.1141 + return SQLITE_OK;
49.1142 + }
49.1143 + if( useCksum ){
49.1144 + rc = read32bits(jfd, &cksum);
49.1145 + if( rc ) return rc;
49.1146 + pPager->journalOff += 4;
49.1147 + if( pager_cksum(pPager, aData)!=cksum ){
49.1148 + return SQLITE_DONE;
49.1149 + }
49.1150 + }
49.1151 +
49.1152 + assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
49.1153 +
49.1154 + /* If the pager is in RESERVED state, then there must be a copy of this
49.1155 + ** page in the pager cache. In this case just update the pager cache,
49.1156 + ** not the database file. The page is left marked dirty in this case.
49.1157 + **
49.1158 + ** An exception to the above rule: If the database is in no-sync mode
49.1159 + ** and a page is moved during an incremental vacuum then the page may
49.1160 + ** not be in the pager cache. Later: if a malloc() or IO error occurs
49.1161 + ** during a Movepage() call, then the page may not be in the cache
49.1162 + ** either. So the condition described in the above paragraph is not
49.1163 + ** assert()able.
49.1164 + **
49.1165 + ** If in EXCLUSIVE state, then we update the pager cache if it exists
49.1166 + ** and the main file. The page is then marked not dirty.
49.1167 + **
49.1168 + ** Ticket #1171: The statement journal might contain page content that is
49.1169 + ** different from the page content at the start of the transaction.
49.1170 + ** This occurs when a page is changed prior to the start of a statement
49.1171 + ** then changed again within the statement. When rolling back such a
49.1172 + ** statement we must not write to the original database unless we know
49.1173 + ** for certain that original page contents are synced into the main rollback
49.1174 + ** journal. Otherwise, a power loss might leave modified data in the
49.1175 + ** database file without an entry in the rollback journal that can
49.1176 + ** restore the database to its original form. Two conditions must be
49.1177 + ** met before writing to the database files. (1) the database must be
49.1178 + ** locked. (2) we know that the original page content is fully synced
49.1179 + ** in the main journal either because the page is not in cache or else
49.1180 + ** the page is marked as needSync==0.
49.1181 + */
49.1182 + pPg = pager_lookup(pPager, pgno);
49.1183 + PAGERTRACE4("PLAYBACK %d page %d hash(%08x)\n",
49.1184 + PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, aData));
49.1185 + if( pPager->state>=PAGER_EXCLUSIVE && (pPg==0 || pPg->needSync==0) ){
49.1186 + rc = sqlite3OsSeek(pPager->fd, (pgno-1)*(i64)pPager->pageSize);
49.1187 + if( rc==SQLITE_OK ){
49.1188 + rc = sqlite3OsWrite(pPager->fd, aData, pPager->pageSize);
49.1189 + }
49.1190 + if( pPg ){
49.1191 + makeClean(pPg);
49.1192 + }
49.1193 + }
49.1194 + if( pPg ){
49.1195 + /* No page should ever be explicitly rolled back that is in use, except
49.1196 + ** for page 1 which is held in use in order to keep the lock on the
49.1197 + ** database active. However such a page may be rolled back as a result
49.1198 + ** of an internal error resulting in an automatic call to
49.1199 + ** sqlite3PagerRollback().
49.1200 + */
49.1201 + void *pData;
49.1202 + /* assert( pPg->nRef==0 || pPg->pgno==1 ); */
49.1203 + pData = PGHDR_TO_DATA(pPg);
49.1204 + memcpy(pData, aData, pPager->pageSize);
49.1205 + if( pPager->xReiniter ){
49.1206 + pPager->xReiniter(pPg, pPager->pageSize);
49.1207 + }
49.1208 +#ifdef SQLITE_CHECK_PAGES
49.1209 + pPg->pageHash = pager_pagehash(pPg);
49.1210 +#endif
49.1211 + /* If this was page 1, then restore the value of Pager.dbFileVers.
49.1212 + ** Do this before any decoding. */
49.1213 + if( pgno==1 ){
49.1214 + memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
49.1215 + }
49.1216 +
49.1217 + /* Decode the page just read from disk */
49.1218 + CODEC1(pPager, pData, pPg->pgno, 3);
49.1219 + }
49.1220 + return rc;
49.1221 +}
49.1222 +
49.1223 +/*
49.1224 +** Parameter zMaster is the name of a master journal file. A single journal
49.1225 +** file that referred to the master journal file has just been rolled back.
49.1226 +** This routine checks if it is possible to delete the master journal file,
49.1227 +** and does so if it is.
49.1228 +**
49.1229 +** The master journal file contains the names of all child journals.
49.1230 +** To tell if a master journal can be deleted, check to each of the
49.1231 +** children. If all children are either missing or do not refer to
49.1232 +** a different master journal, then this master journal can be deleted.
49.1233 +*/
49.1234 +static int pager_delmaster(const char *zMaster){
49.1235 + int rc;
49.1236 + int master_open = 0;
49.1237 + OsFile *master = 0;
49.1238 + char *zMasterJournal = 0; /* Contents of master journal file */
49.1239 + i64 nMasterJournal; /* Size of master journal file */
49.1240 +
49.1241 + /* Open the master journal file exclusively in case some other process
49.1242 + ** is running this routine also. Not that it makes too much difference.
49.1243 + */
49.1244 + rc = sqlite3OsOpenReadOnly(zMaster, &master);
49.1245 + assert( rc!=SQLITE_OK || master );
49.1246 + if( rc!=SQLITE_OK ) goto delmaster_out;
49.1247 + master_open = 1;
49.1248 + rc = sqlite3OsFileSize(master, &nMasterJournal);
49.1249 + if( rc!=SQLITE_OK ) goto delmaster_out;
49.1250 +
49.1251 + if( nMasterJournal>0 ){
49.1252 + char *zJournal;
49.1253 + char *zMasterPtr = 0;
49.1254 +
49.1255 + /* Load the entire master journal file into space obtained from
49.1256 + ** sqliteMalloc() and pointed to by zMasterJournal.
49.1257 + */
49.1258 + zMasterJournal = (char *)sqliteMalloc(nMasterJournal);
49.1259 + if( !zMasterJournal ){
49.1260 + rc = SQLITE_NOMEM;
49.1261 + goto delmaster_out;
49.1262 + }
49.1263 + rc = sqlite3OsRead(master, zMasterJournal, nMasterJournal);
49.1264 + if( rc!=SQLITE_OK ) goto delmaster_out;
49.1265 +
49.1266 + zJournal = zMasterJournal;
49.1267 + while( (zJournal-zMasterJournal)<nMasterJournal ){
49.1268 + if( sqlite3OsFileExists(zJournal) ){
49.1269 + /* One of the journals pointed to by the master journal exists.
49.1270 + ** Open it and check if it points at the master journal. If
49.1271 + ** so, return without deleting the master journal file.
49.1272 + */
49.1273 + OsFile *journal = 0;
49.1274 + int c;
49.1275 +
49.1276 + rc = sqlite3OsOpenReadOnly(zJournal, &journal);
49.1277 + assert( rc!=SQLITE_OK || journal );
49.1278 + if( rc!=SQLITE_OK ){
49.1279 + goto delmaster_out;
49.1280 + }
49.1281 +
49.1282 + rc = readMasterJournal(journal, &zMasterPtr);
49.1283 + sqlite3OsClose(&journal);
49.1284 + if( rc!=SQLITE_OK ){
49.1285 + goto delmaster_out;
49.1286 + }
49.1287 +
49.1288 + c = zMasterPtr!=0 && strcmp(zMasterPtr, zMaster)==0;
49.1289 + sqliteFree(zMasterPtr);
49.1290 + if( c ){
49.1291 + /* We have a match. Do not delete the master journal file. */
49.1292 + goto delmaster_out;
49.1293 + }
49.1294 + }
49.1295 + zJournal += (strlen(zJournal)+1);
49.1296 + }
49.1297 + }
49.1298 +
49.1299 + rc = sqlite3OsDelete(zMaster);
49.1300 +
49.1301 +delmaster_out:
49.1302 + if( zMasterJournal ){
49.1303 + sqliteFree(zMasterJournal);
49.1304 + }
49.1305 + if( master_open ){
49.1306 + sqlite3OsClose(&master);
49.1307 + }
49.1308 + return rc;
49.1309 +}
49.1310 +
49.1311 +
49.1312 +static void pager_truncate_cache(Pager *pPager);
49.1313 +
49.1314 +/*
49.1315 +** Truncate the main file of the given pager to the number of pages
49.1316 +** indicated. Also truncate the cached representation of the file.
49.1317 +*/
49.1318 +static int pager_truncate(Pager *pPager, int nPage){
49.1319 + int rc = SQLITE_OK;
49.1320 + if( pPager->state>=PAGER_EXCLUSIVE ){
49.1321 + rc = sqlite3OsTruncate(pPager->fd, pPager->pageSize*(i64)nPage);
49.1322 + }
49.1323 + if( rc==SQLITE_OK ){
49.1324 + pPager->dbSize = nPage;
49.1325 + pager_truncate_cache(pPager);
49.1326 + }
49.1327 + return rc;
49.1328 +}
49.1329 +
49.1330 +/*
49.1331 +** Set the sectorSize for the given pager.
49.1332 +**
49.1333 +** The sector size is the larger of the sector size reported
49.1334 +** by sqlite3OsSectorSize() and the pageSize.
49.1335 +*/
49.1336 +static void setSectorSize(Pager *pPager){
49.1337 + pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
49.1338 + if( pPager->sectorSize<pPager->pageSize ){
49.1339 + pPager->sectorSize = pPager->pageSize;
49.1340 + }
49.1341 +}
49.1342 +
49.1343 +/*
49.1344 +** Playback the journal and thus restore the database file to
49.1345 +** the state it was in before we started making changes.
49.1346 +**
49.1347 +** The journal file format is as follows:
49.1348 +**
49.1349 +** (1) 8 byte prefix. A copy of aJournalMagic[].
49.1350 +** (2) 4 byte big-endian integer which is the number of valid page records
49.1351 +** in the journal. If this value is 0xffffffff, then compute the
49.1352 +** number of page records from the journal size.
49.1353 +** (3) 4 byte big-endian integer which is the initial value for the
49.1354 +** sanity checksum.
49.1355 +** (4) 4 byte integer which is the number of pages to truncate the
49.1356 +** database to during a rollback.
49.1357 +** (5) 4 byte integer which is the number of bytes in the master journal
49.1358 +** name. The value may be zero (indicate that there is no master
49.1359 +** journal.)
49.1360 +** (6) N bytes of the master journal name. The name will be nul-terminated
49.1361 +** and might be shorter than the value read from (5). If the first byte
49.1362 +** of the name is \000 then there is no master journal. The master
49.1363 +** journal name is stored in UTF-8.
49.1364 +** (7) Zero or more pages instances, each as follows:
49.1365 +** + 4 byte page number.
49.1366 +** + pPager->pageSize bytes of data.
49.1367 +** + 4 byte checksum
49.1368 +**
49.1369 +** When we speak of the journal header, we mean the first 6 items above.
49.1370 +** Each entry in the journal is an instance of the 7th item.
49.1371 +**
49.1372 +** Call the value from the second bullet "nRec". nRec is the number of
49.1373 +** valid page entries in the journal. In most cases, you can compute the
49.1374 +** value of nRec from the size of the journal file. But if a power
49.1375 +** failure occurred while the journal was being written, it could be the
49.1376 +** case that the size of the journal file had already been increased but
49.1377 +** the extra entries had not yet made it safely to disk. In such a case,
49.1378 +** the value of nRec computed from the file size would be too large. For
49.1379 +** that reason, we always use the nRec value in the header.
49.1380 +**
49.1381 +** If the nRec value is 0xffffffff it means that nRec should be computed
49.1382 +** from the file size. This value is used when the user selects the
49.1383 +** no-sync option for the journal. A power failure could lead to corruption
49.1384 +** in this case. But for things like temporary table (which will be
49.1385 +** deleted when the power is restored) we don't care.
49.1386 +**
49.1387 +** If the file opened as the journal file is not a well-formed
49.1388 +** journal file then all pages up to the first corrupted page are rolled
49.1389 +** back (or no pages if the journal header is corrupted). The journal file
49.1390 +** is then deleted and SQLITE_OK returned, just as if no corruption had
49.1391 +** been encountered.
49.1392 +**
49.1393 +** If an I/O or malloc() error occurs, the journal-file is not deleted
49.1394 +** and an error code is returned.
49.1395 +*/
49.1396 +static int pager_playback(Pager *pPager, int isHot){
49.1397 + i64 szJ; /* Size of the journal file in bytes */
49.1398 + u32 nRec; /* Number of Records in the journal */
49.1399 + int i; /* Loop counter */
49.1400 + Pgno mxPg = 0; /* Size of the original file in pages */
49.1401 + int rc; /* Result code of a subroutine */
49.1402 + char *zMaster = 0; /* Name of master journal file if any */
49.1403 +
49.1404 + /* Figure out how many records are in the journal. Abort early if
49.1405 + ** the journal is empty.
49.1406 + */
49.1407 + assert( pPager->journalOpen );
49.1408 + rc = sqlite3OsFileSize(pPager->jfd, &szJ);
49.1409 + if( rc!=SQLITE_OK || szJ==0 ){
49.1410 + goto end_playback;
49.1411 + }
49.1412 +
49.1413 + /* Read the master journal name from the journal, if it is present.
49.1414 + ** If a master journal file name is specified, but the file is not
49.1415 + ** present on disk, then the journal is not hot and does not need to be
49.1416 + ** played back.
49.1417 + */
49.1418 + rc = readMasterJournal(pPager->jfd, &zMaster);
49.1419 + assert( rc!=SQLITE_DONE );
49.1420 + if( rc!=SQLITE_OK || (zMaster && !sqlite3OsFileExists(zMaster)) ){
49.1421 + sqliteFree(zMaster);
49.1422 + zMaster = 0;
49.1423 + if( rc==SQLITE_DONE ) rc = SQLITE_OK;
49.1424 + goto end_playback;
49.1425 + }
49.1426 + sqlite3OsSeek(pPager->jfd, 0);
49.1427 + pPager->journalOff = 0;
49.1428 +
49.1429 + /* This loop terminates either when the readJournalHdr() call returns
49.1430 + ** SQLITE_DONE or an IO error occurs. */
49.1431 + while( 1 ){
49.1432 +
49.1433 + /* Read the next journal header from the journal file. If there are
49.1434 + ** not enough bytes left in the journal file for a complete header, or
49.1435 + ** it is corrupted, then a process must of failed while writing it.
49.1436 + ** This indicates nothing more needs to be rolled back.
49.1437 + */
49.1438 + rc = readJournalHdr(pPager, szJ, &nRec, &mxPg);
49.1439 + if( rc!=SQLITE_OK ){
49.1440 + if( rc==SQLITE_DONE ){
49.1441 + rc = SQLITE_OK;
49.1442 + }
49.1443 + goto end_playback;
49.1444 + }
49.1445 +
49.1446 + /* If nRec is 0xffffffff, then this journal was created by a process
49.1447 + ** working in no-sync mode. This means that the rest of the journal
49.1448 + ** file consists of pages, there are no more journal headers. Compute
49.1449 + ** the value of nRec based on this assumption.
49.1450 + */
49.1451 + if( nRec==0xffffffff ){
49.1452 + assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
49.1453 + nRec = (szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager);
49.1454 + }
49.1455 +
49.1456 + /* If nRec is 0 and this rollback is of a transaction created by this
49.1457 + ** process. In this case the rest of the journal file consists of
49.1458 + ** journalled copies of pages that need to be read back into the cache.
49.1459 + */
49.1460 + if( nRec==0 && !isHot ){
49.1461 + nRec = (szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager);
49.1462 + }
49.1463 +
49.1464 + /* If this is the first header read from the journal, truncate the
49.1465 + ** database file back to it's original size.
49.1466 + */
49.1467 + if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
49.1468 + rc = pager_truncate(pPager, mxPg);
49.1469 + if( rc!=SQLITE_OK ){
49.1470 + goto end_playback;
49.1471 + }
49.1472 + }
49.1473 +
49.1474 + /* Copy original pages out of the journal and back into the database file.
49.1475 + */
49.1476 + for(i=0; i<nRec; i++){
49.1477 + rc = pager_playback_one_page(pPager, pPager->jfd, 1);
49.1478 + if( rc!=SQLITE_OK ){
49.1479 + if( rc==SQLITE_DONE ){
49.1480 + rc = SQLITE_OK;
49.1481 + pPager->journalOff = szJ;
49.1482 + break;
49.1483 + }else{
49.1484 + goto end_playback;
49.1485 + }
49.1486 + }
49.1487 + }
49.1488 + }
49.1489 + /*NOTREACHED*/
49.1490 + assert( 0 );
49.1491 +
49.1492 +end_playback:
49.1493 + if( rc==SQLITE_OK ){
49.1494 + rc = pager_end_transaction(pPager);
49.1495 + }
49.1496 + if( zMaster ){
49.1497 + /* If there was a master journal and this routine will return success,
49.1498 + ** see if it is possible to delete the master journal.
49.1499 + */
49.1500 + if( rc==SQLITE_OK ){
49.1501 + rc = pager_delmaster(zMaster);
49.1502 + }
49.1503 + sqliteFree(zMaster);
49.1504 + }
49.1505 +
49.1506 + /* The Pager.sectorSize variable may have been updated while rolling
49.1507 + ** back a journal created by a process with a different sector size
49.1508 + ** value. Reset it to the correct value for this process.
49.1509 + */
49.1510 + setSectorSize(pPager);
49.1511 + return rc;
49.1512 +}
49.1513 +
49.1514 +/*
49.1515 +** Playback the statement journal.
49.1516 +**
49.1517 +** This is similar to playing back the transaction journal but with
49.1518 +** a few extra twists.
49.1519 +**
49.1520 +** (1) The number of pages in the database file at the start of
49.1521 +** the statement is stored in pPager->stmtSize, not in the
49.1522 +** journal file itself.
49.1523 +**
49.1524 +** (2) In addition to playing back the statement journal, also
49.1525 +** playback all pages of the transaction journal beginning
49.1526 +** at offset pPager->stmtJSize.
49.1527 +*/
49.1528 +static int pager_stmt_playback(Pager *pPager){
49.1529 + i64 szJ; /* Size of the full journal */
49.1530 + i64 hdrOff;
49.1531 + int nRec; /* Number of Records */
49.1532 + int i; /* Loop counter */
49.1533 + int rc;
49.1534 +
49.1535 + szJ = pPager->journalOff;
49.1536 +#ifndef NDEBUG
49.1537 + {
49.1538 + i64 os_szJ;
49.1539 + rc = sqlite3OsFileSize(pPager->jfd, &os_szJ);
49.1540 + if( rc!=SQLITE_OK ) return rc;
49.1541 + assert( szJ==os_szJ );
49.1542 + }
49.1543 +#endif
49.1544 +
49.1545 + /* Set hdrOff to be the offset just after the end of the last journal
49.1546 + ** page written before the first journal-header for this statement
49.1547 + ** transaction was written, or the end of the file if no journal
49.1548 + ** header was written.
49.1549 + */
49.1550 + hdrOff = pPager->stmtHdrOff;
49.1551 + assert( pPager->fullSync || !hdrOff );
49.1552 + if( !hdrOff ){
49.1553 + hdrOff = szJ;
49.1554 + }
49.1555 +
49.1556 + /* Truncate the database back to its original size.
49.1557 + */
49.1558 + rc = pager_truncate(pPager, pPager->stmtSize);
49.1559 + assert( pPager->state>=PAGER_SHARED );
49.1560 +
49.1561 + /* Figure out how many records are in the statement journal.
49.1562 + */
49.1563 + assert( pPager->stmtInUse && pPager->journalOpen );
49.1564 + sqlite3OsSeek(pPager->stfd, 0);
49.1565 + nRec = pPager->stmtNRec;
49.1566 +
49.1567 + /* Copy original pages out of the statement journal and back into the
49.1568 + ** database file. Note that the statement journal omits checksums from
49.1569 + ** each record since power-failure recovery is not important to statement
49.1570 + ** journals.
49.1571 + */
49.1572 + for(i=nRec-1; i>=0; i--){
49.1573 + rc = pager_playback_one_page(pPager, pPager->stfd, 0);
49.1574 + assert( rc!=SQLITE_DONE );
49.1575 + if( rc!=SQLITE_OK ) goto end_stmt_playback;
49.1576 + }
49.1577 +
49.1578 + /* Now roll some pages back from the transaction journal. Pager.stmtJSize
49.1579 + ** was the size of the journal file when this statement was started, so
49.1580 + ** everything after that needs to be rolled back, either into the
49.1581 + ** database, the memory cache, or both.
49.1582 + **
49.1583 + ** If it is not zero, then Pager.stmtHdrOff is the offset to the start
49.1584 + ** of the first journal header written during this statement transaction.
49.1585 + */
49.1586 + rc = sqlite3OsSeek(pPager->jfd, pPager->stmtJSize);
49.1587 + if( rc!=SQLITE_OK ){
49.1588 + goto end_stmt_playback;
49.1589 + }
49.1590 + pPager->journalOff = pPager->stmtJSize;
49.1591 + pPager->cksumInit = pPager->stmtCksum;
49.1592 + while( pPager->journalOff < hdrOff ){
49.1593 + rc = pager_playback_one_page(pPager, pPager->jfd, 1);
49.1594 + assert( rc!=SQLITE_DONE );
49.1595 + if( rc!=SQLITE_OK ) goto end_stmt_playback;
49.1596 + }
49.1597 +
49.1598 + while( pPager->journalOff < szJ ){
49.1599 + u32 nJRec; /* Number of Journal Records */
49.1600 + u32 dummy;
49.1601 + rc = readJournalHdr(pPager, szJ, &nJRec, &dummy);
49.1602 + if( rc!=SQLITE_OK ){
49.1603 + assert( rc!=SQLITE_DONE );
49.1604 + goto end_stmt_playback;
49.1605 + }
49.1606 + if( nJRec==0 ){
49.1607 + nJRec = (szJ - pPager->journalOff) / (pPager->pageSize+8);
49.1608 + }
49.1609 + for(i=nJRec-1; i>=0 && pPager->journalOff < szJ; i--){
49.1610 + rc = pager_playback_one_page(pPager, pPager->jfd, 1);
49.1611 + assert( rc!=SQLITE_DONE );
49.1612 + if( rc!=SQLITE_OK ) goto end_stmt_playback;
49.1613 + }
49.1614 + }
49.1615 +
49.1616 + pPager->journalOff = szJ;
49.1617 +
49.1618 +end_stmt_playback:
49.1619 + if( rc==SQLITE_OK) {
49.1620 + pPager->journalOff = szJ;
49.1621 + /* pager_reload_cache(pPager); */
49.1622 + }
49.1623 + return rc;
49.1624 +}
49.1625 +
49.1626 +/*
49.1627 +** Change the maximum number of in-memory pages that are allowed.
49.1628 +*/
49.1629 +void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
49.1630 + if( mxPage>10 ){
49.1631 + pPager->mxPage = mxPage;
49.1632 + }else{
49.1633 + pPager->mxPage = 10;
49.1634 + }
49.1635 +}
49.1636 +
49.1637 +/*
49.1638 +** Adjust the robustness of the database to damage due to OS crashes
49.1639 +** or power failures by changing the number of syncs()s when writing
49.1640 +** the rollback journal. There are three levels:
49.1641 +**
49.1642 +** OFF sqlite3OsSync() is never called. This is the default
49.1643 +** for temporary and transient files.
49.1644 +**
49.1645 +** NORMAL The journal is synced once before writes begin on the
49.1646 +** database. This is normally adequate protection, but
49.1647 +** it is theoretically possible, though very unlikely,
49.1648 +** that an inopertune power failure could leave the journal
49.1649 +** in a state which would cause damage to the database
49.1650 +** when it is rolled back.
49.1651 +**
49.1652 +** FULL The journal is synced twice before writes begin on the
49.1653 +** database (with some additional information - the nRec field
49.1654 +** of the journal header - being written in between the two
49.1655 +** syncs). If we assume that writing a
49.1656 +** single disk sector is atomic, then this mode provides
49.1657 +** assurance that the journal will not be corrupted to the
49.1658 +** point of causing damage to the database during rollback.
49.1659 +**
49.1660 +** Numeric values associated with these states are OFF==1, NORMAL=2,
49.1661 +** and FULL=3.
49.1662 +*/
49.1663 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
49.1664 +void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int full_fsync){
49.1665 + pPager->noSync = level==1 || pPager->tempFile;
49.1666 + pPager->fullSync = level==3 && !pPager->tempFile;
49.1667 + pPager->full_fsync = full_fsync;
49.1668 + if( pPager->noSync ) pPager->needSync = 0;
49.1669 +}
49.1670 +#endif
49.1671 +
49.1672 +/*
49.1673 +** The following global variable is incremented whenever the library
49.1674 +** attempts to open a temporary file. This information is used for
49.1675 +** testing and analysis only.
49.1676 +*/
49.1677 +#ifdef SQLITE_TEST
49.1678 +int sqlite3_opentemp_count = 0;
49.1679 +#endif
49.1680 +
49.1681 +/*
49.1682 +** Open a temporary file.
49.1683 +**
49.1684 +** Write the file descriptor into *fd. Return SQLITE_OK on success or some
49.1685 +** other error code if we fail.
49.1686 +**
49.1687 +** The OS will automatically delete the temporary file when it is
49.1688 +** closed.
49.1689 +*/
49.1690 +static int sqlite3PagerOpentemp(OsFile **pFd){
49.1691 + int cnt = 8;
49.1692 + int rc;
49.1693 + char zFile[SQLITE_TEMPNAME_SIZE];
49.1694 +
49.1695 +#ifdef SQLITE_TEST
49.1696 + sqlite3_opentemp_count++; /* Used for testing and analysis only */
49.1697 +#endif
49.1698 + do{
49.1699 + cnt--;
49.1700 + sqlite3OsTempFileName(zFile);
49.1701 + rc = sqlite3OsOpenExclusive(zFile, pFd, 1);
49.1702 + assert( rc!=SQLITE_OK || *pFd );
49.1703 + }while( cnt>0 && rc!=SQLITE_OK && rc!=SQLITE_NOMEM );
49.1704 + return rc;
49.1705 +}
49.1706 +
49.1707 +/*
49.1708 +** Create a new page cache and put a pointer to the page cache in *ppPager.
49.1709 +** The file to be cached need not exist. The file is not locked until
49.1710 +** the first call to sqlite3PagerGet() and is only held open until the
49.1711 +** last page is released using sqlite3PagerUnref().
49.1712 +**
49.1713 +** If zFilename is NULL then a randomly-named temporary file is created
49.1714 +** and used as the file to be cached. The file will be deleted
49.1715 +** automatically when it is closed.
49.1716 +**
49.1717 +** If zFilename is ":memory:" then all information is held in cache.
49.1718 +** It is never written to disk. This can be used to implement an
49.1719 +** in-memory database.
49.1720 +*/
49.1721 +int sqlite3PagerOpen(
49.1722 + Pager **ppPager, /* Return the Pager structure here */
49.1723 + const char *zFilename, /* Name of the database file to open */
49.1724 + int nExtra, /* Extra bytes append to each in-memory page */
49.1725 + int flags /* flags controlling this file */
49.1726 +){
49.1727 + Pager *pPager = 0;
49.1728 + char *zFullPathname = 0;
49.1729 + int nameLen; /* Compiler is wrong. This is always initialized before use */
49.1730 + OsFile *fd = 0;
49.1731 + int rc = SQLITE_OK;
49.1732 + int i;
49.1733 + int tempFile = 0;
49.1734 + int memDb = 0;
49.1735 + int readOnly = 0;
49.1736 + int useJournal = (flags & PAGER_OMIT_JOURNAL)==0;
49.1737 + int noReadlock = (flags & PAGER_NO_READLOCK)!=0;
49.1738 + char zTemp[SQLITE_TEMPNAME_SIZE];
49.1739 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
49.1740 + /* A malloc() cannot fail in sqlite3ThreadData() as one or more calls to
49.1741 + ** malloc() must have already been made by this thread before it gets
49.1742 + ** to this point. This means the ThreadData must have been allocated already
49.1743 + ** so that ThreadData.nAlloc can be set. It would be nice to assert
49.1744 + ** that ThreadData.nAlloc is non-zero, but alas this breaks test cases
49.1745 + ** written to invoke the pager directly.
49.1746 + */
49.1747 + ThreadData *pTsd = sqlite3ThreadData();
49.1748 + assert( pTsd );
49.1749 +#endif
49.1750 +
49.1751 + /* We used to test if malloc() had already failed before proceeding.
49.1752 + ** But the way this function is used in SQLite means that can never
49.1753 + ** happen. Furthermore, if the malloc-failed flag is already set,
49.1754 + ** either the call to sqliteStrDup() or sqliteMalloc() below will
49.1755 + ** fail shortly and SQLITE_NOMEM returned anyway.
49.1756 + */
49.1757 + *ppPager = 0;
49.1758 +
49.1759 + /* Open the pager file and set zFullPathname to point at malloc()ed
49.1760 + ** memory containing the complete filename (i.e. including the directory).
49.1761 + */
49.1762 + if( zFilename && zFilename[0] ){
49.1763 +#ifndef SQLITE_OMIT_MEMORYDB
49.1764 + if( strcmp(zFilename,":memory:")==0 ){
49.1765 + memDb = 1;
49.1766 + zFullPathname = sqliteStrDup("");
49.1767 + }else
49.1768 +#endif
49.1769 + {
49.1770 + zFullPathname = sqlite3OsFullPathname(zFilename);
49.1771 + if( zFullPathname ){
49.1772 + rc = sqlite3OsOpenReadWrite(zFullPathname, &fd, &readOnly);
49.1773 + assert( rc!=SQLITE_OK || fd );
49.1774 + }
49.1775 + }
49.1776 + }else{
49.1777 + rc = sqlite3PagerOpentemp(&fd);
49.1778 + sqlite3OsTempFileName(zTemp);
49.1779 + zFilename = zTemp;
49.1780 + zFullPathname = sqlite3OsFullPathname(zFilename);
49.1781 + if( rc==SQLITE_OK ){
49.1782 + tempFile = 1;
49.1783 + }
49.1784 + }
49.1785 +
49.1786 + /* Allocate the Pager structure. As part of the same allocation, allocate
49.1787 + ** space for the full paths of the file, directory and journal
49.1788 + ** (Pager.zFilename, Pager.zDirectory and Pager.zJournal).
49.1789 + */
49.1790 + if( zFullPathname ){
49.1791 + nameLen = strlen(zFullPathname);
49.1792 + pPager = sqliteMalloc( sizeof(*pPager) + nameLen*3 + 30 );
49.1793 + if( pPager && rc==SQLITE_OK ){
49.1794 + pPager->pTmpSpace = (char *)sqliteMallocRaw(SQLITE_DEFAULT_PAGE_SIZE);
49.1795 + }
49.1796 + }
49.1797 +
49.1798 +
49.1799 + /* If an error occured in either of the blocks above, free the memory
49.1800 + ** pointed to by zFullPathname, free the Pager structure and close the
49.1801 + ** file. Since the pager is not allocated there is no need to set
49.1802 + ** any Pager.errMask variables.
49.1803 + */
49.1804 + if( !pPager || !zFullPathname || !pPager->pTmpSpace || rc!=SQLITE_OK ){
49.1805 + sqlite3OsClose(&fd);
49.1806 + sqliteFree(zFullPathname);
49.1807 + sqliteFree(pPager);
49.1808 + return ((rc==SQLITE_OK)?SQLITE_NOMEM:rc);
49.1809 + }
49.1810 +
49.1811 + PAGERTRACE3("OPEN %d %s\n", FILEHANDLEID(fd), zFullPathname);
49.1812 + IOTRACE(("OPEN %p %s\n", pPager, zFullPathname))
49.1813 + pPager->zFilename = (char*)&pPager[1];
49.1814 + pPager->zDirectory = &pPager->zFilename[nameLen+1];
49.1815 + pPager->zJournal = &pPager->zDirectory[nameLen+1];
49.1816 + memcpy(pPager->zFilename, zFullPathname, nameLen+1);
49.1817 + memcpy(pPager->zDirectory, zFullPathname, nameLen+1);
49.1818 +
49.1819 + for(i=nameLen; i>0 && pPager->zDirectory[i-1]!='/'; i--){}
49.1820 + if( i>0 ) pPager->zDirectory[i-1] = 0;
49.1821 + memcpy(pPager->zJournal, zFullPathname,nameLen);
49.1822 + sqliteFree(zFullPathname);
49.1823 + memcpy(&pPager->zJournal[nameLen], "-journal",sizeof("-journal"));
49.1824 + pPager->fd = fd;
49.1825 + /* pPager->journalOpen = 0; */
49.1826 + pPager->useJournal = useJournal && !memDb;
49.1827 + pPager->noReadlock = noReadlock && readOnly;
49.1828 + /* pPager->stmtOpen = 0; */
49.1829 + /* pPager->stmtInUse = 0; */
49.1830 + /* pPager->nRef = 0; */
49.1831 + pPager->dbSize = memDb-1;
49.1832 + pPager->pageSize = SQLITE_DEFAULT_PAGE_SIZE;
49.1833 + /* pPager->stmtSize = 0; */
49.1834 + /* pPager->stmtJSize = 0; */
49.1835 + /* pPager->nPage = 0; */
49.1836 + pPager->mxPage = 100;
49.1837 + pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
49.1838 + assert( PAGER_UNLOCK==0 );
49.1839 + /* pPager->state = PAGER_UNLOCK; */
49.1840 + /* pPager->errMask = 0; */
49.1841 + pPager->tempFile = tempFile;
49.1842 + assert( tempFile==PAGER_LOCKINGMODE_NORMAL
49.1843 + || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
49.1844 + assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
49.1845 + pPager->exclusiveMode = tempFile;
49.1846 + pPager->memDb = memDb;
49.1847 + pPager->readOnly = readOnly;
49.1848 + /* pPager->needSync = 0; */
49.1849 + pPager->noSync = pPager->tempFile || !useJournal;
49.1850 + pPager->fullSync = (pPager->noSync?0:1);
49.1851 + /* pPager->pFirst = 0; */
49.1852 + /* pPager->pFirstSynced = 0; */
49.1853 + /* pPager->pLast = 0; */
49.1854 + pPager->nExtra = FORCE_ALIGNMENT(nExtra);
49.1855 + assert(fd||memDb);
49.1856 + if( !memDb ){
49.1857 + setSectorSize(pPager);
49.1858 + }
49.1859 + /* pPager->pBusyHandler = 0; */
49.1860 + /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
49.1861 + *ppPager = pPager;
49.1862 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
49.1863 + pPager->pNext = pTsd->pPager;
49.1864 + pTsd->pPager = pPager;
49.1865 +#endif
49.1866 + return SQLITE_OK;
49.1867 +}
49.1868 +
49.1869 +/*
49.1870 +** Set the busy handler function.
49.1871 +*/
49.1872 +void sqlite3PagerSetBusyhandler(Pager *pPager, BusyHandler *pBusyHandler){
49.1873 + pPager->pBusyHandler = pBusyHandler;
49.1874 +}
49.1875 +
49.1876 +/*
49.1877 +** Set the destructor for this pager. If not NULL, the destructor is called
49.1878 +** when the reference count on each page reaches zero. The destructor can
49.1879 +** be used to clean up information in the extra segment appended to each page.
49.1880 +**
49.1881 +** The destructor is not called as a result sqlite3PagerClose().
49.1882 +** Destructors are only called by sqlite3PagerUnref().
49.1883 +*/
49.1884 +void sqlite3PagerSetDestructor(Pager *pPager, void (*xDesc)(DbPage*,int)){
49.1885 + pPager->xDestructor = xDesc;
49.1886 +}
49.1887 +
49.1888 +/*
49.1889 +** Set the reinitializer for this pager. If not NULL, the reinitializer
49.1890 +** is called when the content of a page in cache is restored to its original
49.1891 +** value as a result of a rollback. The callback gives higher-level code
49.1892 +** an opportunity to restore the EXTRA section to agree with the restored
49.1893 +** page data.
49.1894 +*/
49.1895 +void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*,int)){
49.1896 + pPager->xReiniter = xReinit;
49.1897 +}
49.1898 +
49.1899 +/*
49.1900 +** Set the page size. Return the new size. If the suggest new page
49.1901 +** size is inappropriate, then an alternative page size is selected
49.1902 +** and returned.
49.1903 +*/
49.1904 +int sqlite3PagerSetPagesize(Pager *pPager, int pageSize){
49.1905 + assert( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE );
49.1906 + if( !pPager->memDb && pPager->nRef==0 ){
49.1907 + pager_reset(pPager);
49.1908 + pPager->pageSize = pageSize;
49.1909 + pPager->pTmpSpace = sqlite3ReallocOrFree(pPager->pTmpSpace, pageSize);
49.1910 + }
49.1911 + return pPager->pageSize;
49.1912 +}
49.1913 +
49.1914 +/*
49.1915 +** Attempt to set the maximum database page count if mxPage is positive.
49.1916 +** Make no changes if mxPage is zero or negative. And never reduce the
49.1917 +** maximum page count below the current size of the database.
49.1918 +**
49.1919 +** Regardless of mxPage, return the current maximum page count.
49.1920 +*/
49.1921 +int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
49.1922 + if( mxPage>0 ){
49.1923 + pPager->mxPgno = mxPage;
49.1924 + }
49.1925 + sqlite3PagerPagecount(pPager);
49.1926 + return pPager->mxPgno;
49.1927 +}
49.1928 +
49.1929 +/*
49.1930 +** The following set of routines are used to disable the simulated
49.1931 +** I/O error mechanism. These routines are used to avoid simulated
49.1932 +** errors in places where we do not care about errors.
49.1933 +**
49.1934 +** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
49.1935 +** and generate no code.
49.1936 +*/
49.1937 +#ifdef SQLITE_TEST
49.1938 +extern int sqlite3_io_error_pending;
49.1939 +extern int sqlite3_io_error_hit;
49.1940 +static int saved_cnt;
49.1941 +void disable_simulated_io_errors(void){
49.1942 + saved_cnt = sqlite3_io_error_pending;
49.1943 + sqlite3_io_error_pending = -1;
49.1944 +}
49.1945 +void enable_simulated_io_errors(void){
49.1946 + sqlite3_io_error_pending = saved_cnt;
49.1947 +}
49.1948 +#else
49.1949 +# define disable_simulated_io_errors()
49.1950 +# define enable_simulated_io_errors()
49.1951 +#endif
49.1952 +
49.1953 +/*
49.1954 +** Read the first N bytes from the beginning of the file into memory
49.1955 +** that pDest points to.
49.1956 +**
49.1957 +** No error checking is done. The rational for this is that this function
49.1958 +** may be called even if the file does not exist or contain a header. In
49.1959 +** these cases sqlite3OsRead() will return an error, to which the correct
49.1960 +** response is to zero the memory at pDest and continue. A real IO error
49.1961 +** will presumably recur and be picked up later (Todo: Think about this).
49.1962 +*/
49.1963 +int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
49.1964 + int rc = SQLITE_OK;
49.1965 + memset(pDest, 0, N);
49.1966 + if( MEMDB==0 ){
49.1967 + disable_simulated_io_errors();
49.1968 + sqlite3OsSeek(pPager->fd, 0);
49.1969 + enable_simulated_io_errors();
49.1970 + IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
49.1971 + rc = sqlite3OsRead(pPager->fd, pDest, N);
49.1972 + if( rc==SQLITE_IOERR_SHORT_READ ){
49.1973 + rc = SQLITE_OK;
49.1974 + }
49.1975 + }
49.1976 + return rc;
49.1977 +}
49.1978 +
49.1979 +/*
49.1980 +** Return the total number of pages in the disk file associated with
49.1981 +** pPager.
49.1982 +**
49.1983 +** If the PENDING_BYTE lies on the page directly after the end of the
49.1984 +** file, then consider this page part of the file too. For example, if
49.1985 +** PENDING_BYTE is byte 4096 (the first byte of page 5) and the size of the
49.1986 +** file is 4096 bytes, 5 is returned instead of 4.
49.1987 +*/
49.1988 +int sqlite3PagerPagecount(Pager *pPager){
49.1989 + i64 n;
49.1990 + int rc;
49.1991 + assert( pPager!=0 );
49.1992 + if( pPager->errCode ){
49.1993 + return 0;
49.1994 + }
49.1995 + if( pPager->dbSize>=0 ){
49.1996 + n = pPager->dbSize;
49.1997 + } else {
49.1998 + if( (rc = sqlite3OsFileSize(pPager->fd, &n))!=SQLITE_OK ){
49.1999 + pager_error(pPager, rc);
49.2000 + return 0;
49.2001 + }
49.2002 + if( n>0 && n<pPager->pageSize ){
49.2003 + n = 1;
49.2004 + }else{
49.2005 + n /= pPager->pageSize;
49.2006 + }
49.2007 + if( pPager->state!=PAGER_UNLOCK ){
49.2008 + pPager->dbSize = n;
49.2009 + }
49.2010 + }
49.2011 + if( n==(PENDING_BYTE/pPager->pageSize) ){
49.2012 + n++;
49.2013 + }
49.2014 + if( n>pPager->mxPgno ){
49.2015 + pPager->mxPgno = n;
49.2016 + }
49.2017 + return n;
49.2018 +}
49.2019 +
49.2020 +
49.2021 +#ifndef SQLITE_OMIT_MEMORYDB
49.2022 +/*
49.2023 +** Clear a PgHistory block
49.2024 +*/
49.2025 +static void clearHistory(PgHistory *pHist){
49.2026 + sqliteFree(pHist->pOrig);
49.2027 + sqliteFree(pHist->pStmt);
49.2028 + pHist->pOrig = 0;
49.2029 + pHist->pStmt = 0;
49.2030 +}
49.2031 +#else
49.2032 +#define clearHistory(x)
49.2033 +#endif
49.2034 +
49.2035 +/*
49.2036 +** Forward declaration
49.2037 +*/
49.2038 +static int syncJournal(Pager*);
49.2039 +
49.2040 +/*
49.2041 +** Unlink pPg from it's hash chain. Also set the page number to 0 to indicate
49.2042 +** that the page is not part of any hash chain. This is required because the
49.2043 +** sqlite3PagerMovepage() routine can leave a page in the
49.2044 +** pNextFree/pPrevFree list that is not a part of any hash-chain.
49.2045 +*/
49.2046 +static void unlinkHashChain(Pager *pPager, PgHdr *pPg){
49.2047 + if( pPg->pgno==0 ){
49.2048 + assert( pPg->pNextHash==0 && pPg->pPrevHash==0 );
49.2049 + return;
49.2050 + }
49.2051 + if( pPg->pNextHash ){
49.2052 + pPg->pNextHash->pPrevHash = pPg->pPrevHash;
49.2053 + }
49.2054 + if( pPg->pPrevHash ){
49.2055 + assert( pPager->aHash[pPg->pgno & (pPager->nHash-1)]!=pPg );
49.2056 + pPg->pPrevHash->pNextHash = pPg->pNextHash;
49.2057 + }else{
49.2058 + int h = pPg->pgno & (pPager->nHash-1);
49.2059 + pPager->aHash[h] = pPg->pNextHash;
49.2060 + }
49.2061 + if( MEMDB ){
49.2062 + clearHistory(PGHDR_TO_HIST(pPg, pPager));
49.2063 + }
49.2064 + pPg->pgno = 0;
49.2065 + pPg->pNextHash = pPg->pPrevHash = 0;
49.2066 +}
49.2067 +
49.2068 +/*
49.2069 +** Unlink a page from the free list (the list of all pages where nRef==0)
49.2070 +** and from its hash collision chain.
49.2071 +*/
49.2072 +static void unlinkPage(PgHdr *pPg){
49.2073 + Pager *pPager = pPg->pPager;
49.2074 +
49.2075 + /* Keep the pFirstSynced pointer pointing at the first synchronized page */
49.2076 + if( pPg==pPager->pFirstSynced ){
49.2077 + PgHdr *p = pPg->pNextFree;
49.2078 + while( p && p->needSync ){ p = p->pNextFree; }
49.2079 + pPager->pFirstSynced = p;
49.2080 + }
49.2081 +
49.2082 + /* Unlink from the freelist */
49.2083 + if( pPg->pPrevFree ){
49.2084 + pPg->pPrevFree->pNextFree = pPg->pNextFree;
49.2085 + }else{
49.2086 + assert( pPager->pFirst==pPg );
49.2087 + pPager->pFirst = pPg->pNextFree;
49.2088 + }
49.2089 + if( pPg->pNextFree ){
49.2090 + pPg->pNextFree->pPrevFree = pPg->pPrevFree;
49.2091 + }else{
49.2092 + assert( pPager->pLast==pPg );
49.2093 + pPager->pLast = pPg->pPrevFree;
49.2094 + }
49.2095 + pPg->pNextFree = pPg->pPrevFree = 0;
49.2096 +
49.2097 + /* Unlink from the pgno hash table */
49.2098 + unlinkHashChain(pPager, pPg);
49.2099 +}
49.2100 +
49.2101 +/*
49.2102 +** This routine is used to truncate the cache when a database
49.2103 +** is truncated. Drop from the cache all pages whose pgno is
49.2104 +** larger than pPager->dbSize and is unreferenced.
49.2105 +**
49.2106 +** Referenced pages larger than pPager->dbSize are zeroed.
49.2107 +**
49.2108 +** Actually, at the point this routine is called, it would be
49.2109 +** an error to have a referenced page. But rather than delete
49.2110 +** that page and guarantee a subsequent segfault, it seems better
49.2111 +** to zero it and hope that we error out sanely.
49.2112 +*/
49.2113 +static void pager_truncate_cache(Pager *pPager){
49.2114 + PgHdr *pPg;
49.2115 + PgHdr **ppPg;
49.2116 + int dbSize = pPager->dbSize;
49.2117 +
49.2118 + ppPg = &pPager->pAll;
49.2119 + while( (pPg = *ppPg)!=0 ){
49.2120 + if( pPg->pgno<=dbSize ){
49.2121 + ppPg = &pPg->pNextAll;
49.2122 + }else if( pPg->nRef>0 ){
49.2123 + memset(PGHDR_TO_DATA(pPg), 0, pPager->pageSize);
49.2124 + ppPg = &pPg->pNextAll;
49.2125 + }else{
49.2126 + *ppPg = pPg->pNextAll;
49.2127 + IOTRACE(("PGFREE %p %d\n", pPager, pPg->pgno));
49.2128 + PAGER_INCR(sqlite3_pager_pgfree_count);
49.2129 + unlinkPage(pPg);
49.2130 + makeClean(pPg);
49.2131 + sqliteFree(pPg);
49.2132 + pPager->nPage--;
49.2133 + }
49.2134 + }
49.2135 +}
49.2136 +
49.2137 +/*
49.2138 +** Try to obtain a lock on a file. Invoke the busy callback if the lock
49.2139 +** is currently not available. Repeat until the busy callback returns
49.2140 +** false or until the lock succeeds.
49.2141 +**
49.2142 +** Return SQLITE_OK on success and an error code if we cannot obtain
49.2143 +** the lock.
49.2144 +*/
49.2145 +static int pager_wait_on_lock(Pager *pPager, int locktype){
49.2146 + int rc;
49.2147 +
49.2148 + /* The OS lock values must be the same as the Pager lock values */
49.2149 + assert( PAGER_SHARED==SHARED_LOCK );
49.2150 + assert( PAGER_RESERVED==RESERVED_LOCK );
49.2151 + assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
49.2152 +
49.2153 + /* If the file is currently unlocked then the size must be unknown */
49.2154 + assert( pPager->state>=PAGER_SHARED || pPager->dbSize<0 || MEMDB );
49.2155 +
49.2156 + if( pPager->state>=locktype ){
49.2157 + rc = SQLITE_OK;
49.2158 + }else{
49.2159 + do {
49.2160 + rc = sqlite3OsLock(pPager->fd, locktype);
49.2161 + }while( rc==SQLITE_BUSY && sqlite3InvokeBusyHandler(pPager->pBusyHandler) );
49.2162 + if( rc==SQLITE_OK ){
49.2163 + pPager->state = locktype;
49.2164 + IOTRACE(("LOCK %p %d\n", pPager, locktype))
49.2165 + }
49.2166 + }
49.2167 + return rc;
49.2168 +}
49.2169 +
49.2170 +/*
49.2171 +** Truncate the file to the number of pages specified.
49.2172 +*/
49.2173 +int sqlite3PagerTruncate(Pager *pPager, Pgno nPage){
49.2174 + int rc;
49.2175 + assert( pPager->state>=PAGER_SHARED || MEMDB );
49.2176 + sqlite3PagerPagecount(pPager);
49.2177 + if( pPager->errCode ){
49.2178 + rc = pPager->errCode;
49.2179 + return rc;
49.2180 + }
49.2181 + if( nPage>=(unsigned)pPager->dbSize ){
49.2182 + return SQLITE_OK;
49.2183 + }
49.2184 + if( MEMDB ){
49.2185 + pPager->dbSize = nPage;
49.2186 + pager_truncate_cache(pPager);
49.2187 + return SQLITE_OK;
49.2188 + }
49.2189 + rc = syncJournal(pPager);
49.2190 + if( rc!=SQLITE_OK ){
49.2191 + return rc;
49.2192 + }
49.2193 +
49.2194 + /* Get an exclusive lock on the database before truncating. */
49.2195 + rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
49.2196 + if( rc!=SQLITE_OK ){
49.2197 + return rc;
49.2198 + }
49.2199 +
49.2200 + rc = pager_truncate(pPager, nPage);
49.2201 + return rc;
49.2202 +}
49.2203 +
49.2204 +/*
49.2205 +** Shutdown the page cache. Free all memory and close all files.
49.2206 +**
49.2207 +** If a transaction was in progress when this routine is called, that
49.2208 +** transaction is rolled back. All outstanding pages are invalidated
49.2209 +** and their memory is freed. Any attempt to use a page associated
49.2210 +** with this page cache after this function returns will likely
49.2211 +** result in a coredump.
49.2212 +**
49.2213 +** This function always succeeds. If a transaction is active an attempt
49.2214 +** is made to roll it back. If an error occurs during the rollback
49.2215 +** a hot journal may be left in the filesystem but no error is returned
49.2216 +** to the caller.
49.2217 +*/
49.2218 +int sqlite3PagerClose(Pager *pPager){
49.2219 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
49.2220 + /* A malloc() cannot fail in sqlite3ThreadData() as one or more calls to
49.2221 + ** malloc() must have already been made by this thread before it gets
49.2222 + ** to this point. This means the ThreadData must have been allocated already
49.2223 + ** so that ThreadData.nAlloc can be set.
49.2224 + */
49.2225 + ThreadData *pTsd = sqlite3ThreadData();
49.2226 + assert( pPager );
49.2227 + assert( pTsd && pTsd->nAlloc );
49.2228 +#endif
49.2229 +
49.2230 + disable_simulated_io_errors();
49.2231 + pPager->errCode = 0;
49.2232 + pPager->exclusiveMode = 0;
49.2233 + pager_reset(pPager);
49.2234 + pagerUnlockAndRollback(pPager);
49.2235 + enable_simulated_io_errors();
49.2236 + PAGERTRACE2("CLOSE %d\n", PAGERID(pPager));
49.2237 + IOTRACE(("CLOSE %p\n", pPager))
49.2238 + assert( pPager->errCode || (pPager->journalOpen==0 && pPager->stmtOpen==0) );
49.2239 + if( pPager->journalOpen ){
49.2240 + sqlite3OsClose(&pPager->jfd);
49.2241 + }
49.2242 + sqliteFree(pPager->aInJournal);
49.2243 + if( pPager->stmtOpen ){
49.2244 + sqlite3OsClose(&pPager->stfd);
49.2245 + }
49.2246 + sqlite3OsClose(&pPager->fd);
49.2247 + /* Temp files are automatically deleted by the OS
49.2248 + ** if( pPager->tempFile ){
49.2249 + ** sqlite3OsDelete(pPager->zFilename);
49.2250 + ** }
49.2251 + */
49.2252 +
49.2253 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
49.2254 + /* Remove the pager from the linked list of pagers starting at
49.2255 + ** ThreadData.pPager if memory-management is enabled.
49.2256 + */
49.2257 + if( pPager==pTsd->pPager ){
49.2258 + pTsd->pPager = pPager->pNext;
49.2259 + }else{
49.2260 + Pager *pTmp;
49.2261 + for(pTmp = pTsd->pPager; pTmp->pNext!=pPager; pTmp=pTmp->pNext){}
49.2262 + pTmp->pNext = pPager->pNext;
49.2263 + }
49.2264 +#endif
49.2265 + sqliteFree(pPager->aHash);
49.2266 + sqliteFree(pPager->pTmpSpace);
49.2267 + sqliteFree(pPager);
49.2268 + return SQLITE_OK;
49.2269 +}
49.2270 +
49.2271 +#if !defined(NDEBUG) || defined(SQLITE_TEST)
49.2272 +/*
49.2273 +** Return the page number for the given page data.
49.2274 +*/
49.2275 +Pgno sqlite3PagerPagenumber(DbPage *p){
49.2276 + return p->pgno;
49.2277 +}
49.2278 +#endif
49.2279 +
49.2280 +/*
49.2281 +** The page_ref() function increments the reference count for a page.
49.2282 +** If the page is currently on the freelist (the reference count is zero) then
49.2283 +** remove it from the freelist.
49.2284 +**
49.2285 +** For non-test systems, page_ref() is a macro that calls _page_ref()
49.2286 +** online of the reference count is zero. For test systems, page_ref()
49.2287 +** is a real function so that we can set breakpoints and trace it.
49.2288 +*/
49.2289 +static void _page_ref(PgHdr *pPg){
49.2290 + if( pPg->nRef==0 ){
49.2291 + /* The page is currently on the freelist. Remove it. */
49.2292 + if( pPg==pPg->pPager->pFirstSynced ){
49.2293 + PgHdr *p = pPg->pNextFree;
49.2294 + while( p && p->needSync ){ p = p->pNextFree; }
49.2295 + pPg->pPager->pFirstSynced = p;
49.2296 + }
49.2297 + if( pPg->pPrevFree ){
49.2298 + pPg->pPrevFree->pNextFree = pPg->pNextFree;
49.2299 + }else{
49.2300 + pPg->pPager->pFirst = pPg->pNextFree;
49.2301 + }
49.2302 + if( pPg->pNextFree ){
49.2303 + pPg->pNextFree->pPrevFree = pPg->pPrevFree;
49.2304 + }else{
49.2305 + pPg->pPager->pLast = pPg->pPrevFree;
49.2306 + }
49.2307 + pPg->pPager->nRef++;
49.2308 + }
49.2309 + pPg->nRef++;
49.2310 + REFINFO(pPg);
49.2311 +}
49.2312 +#ifdef SQLITE_DEBUG
49.2313 + static void page_ref(PgHdr *pPg){
49.2314 + if( pPg->nRef==0 ){
49.2315 + _page_ref(pPg);
49.2316 + }else{
49.2317 + pPg->nRef++;
49.2318 + REFINFO(pPg);
49.2319 + }
49.2320 + }
49.2321 +#else
49.2322 +# define page_ref(P) ((P)->nRef==0?_page_ref(P):(void)(P)->nRef++)
49.2323 +#endif
49.2324 +
49.2325 +/*
49.2326 +** Increment the reference count for a page. The input pointer is
49.2327 +** a reference to the page data.
49.2328 +*/
49.2329 +int sqlite3PagerRef(DbPage *pPg){
49.2330 + page_ref(pPg);
49.2331 + return SQLITE_OK;
49.2332 +}
49.2333 +
49.2334 +/*
49.2335 +** Sync the journal. In other words, make sure all the pages that have
49.2336 +** been written to the journal have actually reached the surface of the
49.2337 +** disk. It is not safe to modify the original database file until after
49.2338 +** the journal has been synced. If the original database is modified before
49.2339 +** the journal is synced and a power failure occurs, the unsynced journal
49.2340 +** data would be lost and we would be unable to completely rollback the
49.2341 +** database changes. Database corruption would occur.
49.2342 +**
49.2343 +** This routine also updates the nRec field in the header of the journal.
49.2344 +** (See comments on the pager_playback() routine for additional information.)
49.2345 +** If the sync mode is FULL, two syncs will occur. First the whole journal
49.2346 +** is synced, then the nRec field is updated, then a second sync occurs.
49.2347 +**
49.2348 +** For temporary databases, we do not care if we are able to rollback
49.2349 +** after a power failure, so sync occurs.
49.2350 +**
49.2351 +** This routine clears the needSync field of every page current held in
49.2352 +** memory.
49.2353 +*/
49.2354 +static int syncJournal(Pager *pPager){
49.2355 + PgHdr *pPg;
49.2356 + int rc = SQLITE_OK;
49.2357 +
49.2358 + /* Sync the journal before modifying the main database
49.2359 + ** (assuming there is a journal and it needs to be synced.)
49.2360 + */
49.2361 + if( pPager->needSync ){
49.2362 + if( !pPager->tempFile ){
49.2363 + assert( pPager->journalOpen );
49.2364 + /* assert( !pPager->noSync ); // noSync might be set if synchronous
49.2365 + ** was turned off after the transaction was started. Ticket #615 */
49.2366 +#ifndef NDEBUG
49.2367 + {
49.2368 + /* Make sure the pPager->nRec counter we are keeping agrees
49.2369 + ** with the nRec computed from the size of the journal file.
49.2370 + */
49.2371 + i64 jSz;
49.2372 + rc = sqlite3OsFileSize(pPager->jfd, &jSz);
49.2373 + if( rc!=0 ) return rc;
49.2374 + assert( pPager->journalOff==jSz );
49.2375 + }
49.2376 +#endif
49.2377 + {
49.2378 + /* Write the nRec value into the journal file header. If in
49.2379 + ** full-synchronous mode, sync the journal first. This ensures that
49.2380 + ** all data has really hit the disk before nRec is updated to mark
49.2381 + ** it as a candidate for rollback.
49.2382 + */
49.2383 + if( pPager->fullSync ){
49.2384 + PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
49.2385 + IOTRACE(("JSYNC %p\n", pPager))
49.2386 + rc = sqlite3OsSync(pPager->jfd, 0);
49.2387 + if( rc!=0 ) return rc;
49.2388 + }
49.2389 + rc = sqlite3OsSeek(pPager->jfd,
49.2390 + pPager->journalHdr + sizeof(aJournalMagic));
49.2391 + if( rc ) return rc;
49.2392 + IOTRACE(("JHDR %p %lld %d\n", pPager,
49.2393 + pPager->journalHdr + sizeof(aJournalMagic), 4))
49.2394 + rc = write32bits(pPager->jfd, pPager->nRec);
49.2395 + if( rc ) return rc;
49.2396 +
49.2397 + rc = sqlite3OsSeek(pPager->jfd, pPager->journalOff);
49.2398 + if( rc ) return rc;
49.2399 + }
49.2400 + PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
49.2401 + IOTRACE(("JSYNC %p\n", pPager))
49.2402 + rc = sqlite3OsSync(pPager->jfd, pPager->full_fsync);
49.2403 + if( rc!=0 ) return rc;
49.2404 + pPager->journalStarted = 1;
49.2405 + }
49.2406 + pPager->needSync = 0;
49.2407 +
49.2408 + /* Erase the needSync flag from every page.
49.2409 + */
49.2410 + for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
49.2411 + pPg->needSync = 0;
49.2412 + }
49.2413 + pPager->pFirstSynced = pPager->pFirst;
49.2414 + }
49.2415 +
49.2416 +#ifndef NDEBUG
49.2417 + /* If the Pager.needSync flag is clear then the PgHdr.needSync
49.2418 + ** flag must also be clear for all pages. Verify that this
49.2419 + ** invariant is true.
49.2420 + */
49.2421 + else{
49.2422 + for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
49.2423 + assert( pPg->needSync==0 );
49.2424 + }
49.2425 + assert( pPager->pFirstSynced==pPager->pFirst );
49.2426 + }
49.2427 +#endif
49.2428 +
49.2429 + return rc;
49.2430 +}
49.2431 +
49.2432 +/*
49.2433 +** Merge two lists of pages connected by pDirty and in pgno order.
49.2434 +** Do not both fixing the pPrevDirty pointers.
49.2435 +*/
49.2436 +static PgHdr *merge_pagelist(PgHdr *pA, PgHdr *pB){
49.2437 + PgHdr result, *pTail;
49.2438 + pTail = &result;
49.2439 + while( pA && pB ){
49.2440 + if( pA->pgno<pB->pgno ){
49.2441 + pTail->pDirty = pA;
49.2442 + pTail = pA;
49.2443 + pA = pA->pDirty;
49.2444 + }else{
49.2445 + pTail->pDirty = pB;
49.2446 + pTail = pB;
49.2447 + pB = pB->pDirty;
49.2448 + }
49.2449 + }
49.2450 + if( pA ){
49.2451 + pTail->pDirty = pA;
49.2452 + }else if( pB ){
49.2453 + pTail->pDirty = pB;
49.2454 + }else{
49.2455 + pTail->pDirty = 0;
49.2456 + }
49.2457 + return result.pDirty;
49.2458 +}
49.2459 +
49.2460 +/*
49.2461 +** Sort the list of pages in accending order by pgno. Pages are
49.2462 +** connected by pDirty pointers. The pPrevDirty pointers are
49.2463 +** corrupted by this sort.
49.2464 +*/
49.2465 +#define N_SORT_BUCKET_ALLOC 25
49.2466 +#define N_SORT_BUCKET 25
49.2467 +#ifdef SQLITE_TEST
49.2468 + int sqlite3_pager_n_sort_bucket = 0;
49.2469 + #undef N_SORT_BUCKET
49.2470 + #define N_SORT_BUCKET \
49.2471 + (sqlite3_pager_n_sort_bucket?sqlite3_pager_n_sort_bucket:N_SORT_BUCKET_ALLOC)
49.2472 +#endif
49.2473 +static PgHdr *sort_pagelist(PgHdr *pIn){
49.2474 + PgHdr *a[N_SORT_BUCKET_ALLOC], *p;
49.2475 + int i;
49.2476 + memset(a, 0, sizeof(a));
49.2477 + while( pIn ){
49.2478 + p = pIn;
49.2479 + pIn = p->pDirty;
49.2480 + p->pDirty = 0;
49.2481 + for(i=0; i<N_SORT_BUCKET-1; i++){
49.2482 + if( a[i]==0 ){
49.2483 + a[i] = p;
49.2484 + break;
49.2485 + }else{
49.2486 + p = merge_pagelist(a[i], p);
49.2487 + a[i] = 0;
49.2488 + }
49.2489 + }
49.2490 + if( i==N_SORT_BUCKET-1 ){
49.2491 + /* Coverage: To get here, there need to be 2^(N_SORT_BUCKET)
49.2492 + ** elements in the input list. This is possible, but impractical.
49.2493 + ** Testing this line is the point of global variable
49.2494 + ** sqlite3_pager_n_sort_bucket.
49.2495 + */
49.2496 + a[i] = merge_pagelist(a[i], p);
49.2497 + }
49.2498 + }
49.2499 + p = a[0];
49.2500 + for(i=1; i<N_SORT_BUCKET; i++){
49.2501 + p = merge_pagelist(p, a[i]);
49.2502 + }
49.2503 + return p;
49.2504 +}
49.2505 +
49.2506 +/*
49.2507 +** Given a list of pages (connected by the PgHdr.pDirty pointer) write
49.2508 +** every one of those pages out to the database file and mark them all
49.2509 +** as clean.
49.2510 +*/
49.2511 +static int pager_write_pagelist(PgHdr *pList){
49.2512 + Pager *pPager;
49.2513 + int rc;
49.2514 +
49.2515 + if( pList==0 ) return SQLITE_OK;
49.2516 + pPager = pList->pPager;
49.2517 +
49.2518 + /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
49.2519 + ** database file. If there is already an EXCLUSIVE lock, the following
49.2520 + ** calls to sqlite3OsLock() are no-ops.
49.2521 + **
49.2522 + ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
49.2523 + ** through an intermediate state PENDING. A PENDING lock prevents new
49.2524 + ** readers from attaching to the database but is unsufficient for us to
49.2525 + ** write. The idea of a PENDING lock is to prevent new readers from
49.2526 + ** coming in while we wait for existing readers to clear.
49.2527 + **
49.2528 + ** While the pager is in the RESERVED state, the original database file
49.2529 + ** is unchanged and we can rollback without having to playback the
49.2530 + ** journal into the original database file. Once we transition to
49.2531 + ** EXCLUSIVE, it means the database file has been changed and any rollback
49.2532 + ** will require a journal playback.
49.2533 + */
49.2534 + rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
49.2535 + if( rc!=SQLITE_OK ){
49.2536 + return rc;
49.2537 + }
49.2538 +
49.2539 + pList = sort_pagelist(pList);
49.2540 + while( pList ){
49.2541 + assert( pList->dirty );
49.2542 + rc = sqlite3OsSeek(pPager->fd, (pList->pgno-1)*(i64)pPager->pageSize);
49.2543 + if( rc ) return rc;
49.2544 + /* If there are dirty pages in the page cache with page numbers greater
49.2545 + ** than Pager.dbSize, this means sqlite3PagerTruncate() was called to
49.2546 + ** make the file smaller (presumably by auto-vacuum code). Do not write
49.2547 + ** any such pages to the file.
49.2548 + */
49.2549 + if( pList->pgno<=pPager->dbSize ){
49.2550 + char *pData = CODEC2(pPager, PGHDR_TO_DATA(pList), pList->pgno, 6);
49.2551 + PAGERTRACE4("STORE %d page %d hash(%08x)\n",
49.2552 + PAGERID(pPager), pList->pgno, pager_pagehash(pList));
49.2553 + IOTRACE(("PGOUT %p %d\n", pPager, pList->pgno));
49.2554 + rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize);
49.2555 + PAGER_INCR(sqlite3_pager_writedb_count);
49.2556 + PAGER_INCR(pPager->nWrite);
49.2557 + if( pList->pgno==1 ){
49.2558 + memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
49.2559 + }
49.2560 + }
49.2561 +#ifndef NDEBUG
49.2562 + else{
49.2563 + PAGERTRACE3("NOSTORE %d page %d\n", PAGERID(pPager), pList->pgno);
49.2564 + }
49.2565 +#endif
49.2566 + if( rc ) return rc;
49.2567 + pList->dirty = 0;
49.2568 +#ifdef SQLITE_CHECK_PAGES
49.2569 + pList->pageHash = pager_pagehash(pList);
49.2570 +#endif
49.2571 + pList = pList->pDirty;
49.2572 + }
49.2573 + return SQLITE_OK;
49.2574 +}
49.2575 +
49.2576 +/*
49.2577 +** Collect every dirty page into a dirty list and
49.2578 +** return a pointer to the head of that list. All pages are
49.2579 +** collected even if they are still in use.
49.2580 +*/
49.2581 +static PgHdr *pager_get_all_dirty_pages(Pager *pPager){
49.2582 + return pPager->pDirty;
49.2583 +}
49.2584 +
49.2585 +/*
49.2586 +** Return TRUE if there is a hot journal on the given pager.
49.2587 +** A hot journal is one that needs to be played back.
49.2588 +**
49.2589 +** If the current size of the database file is 0 but a journal file
49.2590 +** exists, that is probably an old journal left over from a prior
49.2591 +** database with the same name. Just delete the journal.
49.2592 +*/
49.2593 +static int hasHotJournal(Pager *pPager){
49.2594 + if( !pPager->useJournal ) return 0;
49.2595 + if( !sqlite3OsFileExists(pPager->zJournal) ){
49.2596 + return 0;
49.2597 + }
49.2598 + if( sqlite3OsCheckReservedLock(pPager->fd) ){
49.2599 + return 0;
49.2600 + }
49.2601 + if( sqlite3PagerPagecount(pPager)==0 ){
49.2602 + sqlite3OsDelete(pPager->zJournal);
49.2603 + return 0;
49.2604 + }else{
49.2605 + return 1;
49.2606 + }
49.2607 +}
49.2608 +
49.2609 +/*
49.2610 +** Try to find a page in the cache that can be recycled.
49.2611 +**
49.2612 +** This routine may return SQLITE_IOERR, SQLITE_FULL or SQLITE_OK. It
49.2613 +** does not set the pPager->errCode variable.
49.2614 +*/
49.2615 +static int pager_recycle(Pager *pPager, int syncOk, PgHdr **ppPg){
49.2616 + PgHdr *pPg;
49.2617 + *ppPg = 0;
49.2618 +
49.2619 + assert(!MEMDB);
49.2620 +
49.2621 + /* Find a page to recycle. Try to locate a page that does not
49.2622 + ** require us to do an fsync() on the journal.
49.2623 + */
49.2624 + pPg = pPager->pFirstSynced;
49.2625 +
49.2626 + /* If we could not find a page that does not require an fsync()
49.2627 + ** on the journal file then fsync the journal file. This is a
49.2628 + ** very slow operation, so we work hard to avoid it. But sometimes
49.2629 + ** it can't be helped.
49.2630 + */
49.2631 + if( pPg==0 && pPager->pFirst && syncOk && !MEMDB){
49.2632 + int rc = syncJournal(pPager);
49.2633 + if( rc!=0 ){
49.2634 + return rc;
49.2635 + }
49.2636 + if( pPager->fullSync ){
49.2637 + /* If in full-sync mode, write a new journal header into the
49.2638 + ** journal file. This is done to avoid ever modifying a journal
49.2639 + ** header that is involved in the rollback of pages that have
49.2640 + ** already been written to the database (in case the header is
49.2641 + ** trashed when the nRec field is updated).
49.2642 + */
49.2643 + pPager->nRec = 0;
49.2644 + assert( pPager->journalOff > 0 );
49.2645 + assert( pPager->doNotSync==0 );
49.2646 + rc = writeJournalHdr(pPager);
49.2647 + if( rc!=0 ){
49.2648 + return rc;
49.2649 + }
49.2650 + }
49.2651 + pPg = pPager->pFirst;
49.2652 + }
49.2653 + if( pPg==0 ){
49.2654 + return SQLITE_OK;
49.2655 + }
49.2656 +
49.2657 + assert( pPg->nRef==0 );
49.2658 +
49.2659 + /* Write the page to the database file if it is dirty.
49.2660 + */
49.2661 + if( pPg->dirty ){
49.2662 + int rc;
49.2663 + assert( pPg->needSync==0 );
49.2664 + makeClean(pPg);
49.2665 + pPg->dirty = 1;
49.2666 + pPg->pDirty = 0;
49.2667 + rc = pager_write_pagelist( pPg );
49.2668 + if( rc!=SQLITE_OK ){
49.2669 + return rc;
49.2670 + }
49.2671 + }
49.2672 + assert( pPg->dirty==0 );
49.2673 +
49.2674 + /* If the page we are recycling is marked as alwaysRollback, then
49.2675 + ** set the global alwaysRollback flag, thus disabling the
49.2676 + ** sqlite3PagerDontRollback() optimization for the rest of this transaction.
49.2677 + ** It is necessary to do this because the page marked alwaysRollback
49.2678 + ** might be reloaded at a later time but at that point we won't remember
49.2679 + ** that is was marked alwaysRollback. This means that all pages must
49.2680 + ** be marked as alwaysRollback from here on out.
49.2681 + */
49.2682 + if( pPg->alwaysRollback ){
49.2683 + IOTRACE(("ALWAYS_ROLLBACK %p\n", pPager))
49.2684 + pPager->alwaysRollback = 1;
49.2685 + }
49.2686 +
49.2687 + /* Unlink the old page from the free list and the hash table
49.2688 + */
49.2689 + unlinkPage(pPg);
49.2690 + assert( pPg->pgno==0 );
49.2691 +
49.2692 + *ppPg = pPg;
49.2693 + return SQLITE_OK;
49.2694 +}
49.2695 +
49.2696 +/*
49.2697 +** This function is called to free superfluous dynamically allocated memory
49.2698 +** held by the pager system. Memory in use by any SQLite pager allocated
49.2699 +** by the current thread may be sqliteFree()ed.
49.2700 +**
49.2701 +** nReq is the number of bytes of memory required. Once this much has
49.2702 +** been released, the function returns. A negative value for nReq means
49.2703 +** free as much memory as possible. The return value is the total number
49.2704 +** of bytes of memory released.
49.2705 +*/
49.2706 +#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO)
49.2707 +int sqlite3PagerReleaseMemory(int nReq){
49.2708 + const ThreadData *pTsdro = sqlite3ThreadDataReadOnly();
49.2709 + int nReleased = 0;
49.2710 + int i;
49.2711 +
49.2712 + /* If the the global mutex is held, this subroutine becomes a
49.2713 + ** o-op; zero bytes of memory are freed. This is because
49.2714 + ** some of the code invoked by this function may also
49.2715 + ** try to obtain the mutex, resulting in a deadlock.
49.2716 + */
49.2717 + if( sqlite3OsInMutex(0) ){
49.2718 + return 0;
49.2719 + }
49.2720 +
49.2721 + /* Outermost loop runs for at most two iterations. First iteration we
49.2722 + ** try to find memory that can be released without calling fsync(). Second
49.2723 + ** iteration (which only runs if the first failed to free nReq bytes of
49.2724 + ** memory) is permitted to call fsync(). This is of course much more
49.2725 + ** expensive.
49.2726 + */
49.2727 + for(i=0; i<=1; i++){
49.2728 +
49.2729 + /* Loop through all the SQLite pagers opened by the current thread. */
49.2730 + Pager *pPager = pTsdro->pPager;
49.2731 + for( ; pPager && (nReq<0 || nReleased<nReq); pPager=pPager->pNext){
49.2732 + PgHdr *pPg;
49.2733 + int rc;
49.2734 +
49.2735 + if( MEMDB ){
49.2736 + continue;
49.2737 + }
49.2738 +
49.2739 + /* For each pager, try to free as many pages as possible (without
49.2740 + ** calling fsync() if this is the first iteration of the outermost
49.2741 + ** loop).
49.2742 + */
49.2743 + while( SQLITE_OK==(rc = pager_recycle(pPager, i, &pPg)) && pPg) {
49.2744 + /* We've found a page to free. At this point the page has been
49.2745 + ** removed from the page hash-table, free-list and synced-list
49.2746 + ** (pFirstSynced). It is still in the all pages (pAll) list.
49.2747 + ** Remove it from this list before freeing.
49.2748 + **
49.2749 + ** Todo: Check the Pager.pStmt list to make sure this is Ok. It
49.2750 + ** probably is though.
49.2751 + */
49.2752 + PgHdr *pTmp;
49.2753 + assert( pPg );
49.2754 + if( pPg==pPager->pAll ){
49.2755 + pPager->pAll = pPg->pNextAll;
49.2756 + }else{
49.2757 + for( pTmp=pPager->pAll; pTmp->pNextAll!=pPg; pTmp=pTmp->pNextAll ){}
49.2758 + pTmp->pNextAll = pPg->pNextAll;
49.2759 + }
49.2760 + nReleased += sqliteAllocSize(pPg);
49.2761 + IOTRACE(("PGFREE %p %d\n", pPager, pPg->pgno));
49.2762 + PAGER_INCR(sqlite3_pager_pgfree_count);
49.2763 + sqliteFree(pPg);
49.2764 + }
49.2765 +
49.2766 + if( rc!=SQLITE_OK ){
49.2767 + /* An error occured whilst writing to the database file or
49.2768 + ** journal in pager_recycle(). The error is not returned to the
49.2769 + ** caller of this function. Instead, set the Pager.errCode variable.
49.2770 + ** The error will be returned to the user (or users, in the case
49.2771 + ** of a shared pager cache) of the pager for which the error occured.
49.2772 + */
49.2773 + assert( (rc&0xff)==SQLITE_IOERR || rc==SQLITE_FULL );
49.2774 + assert( pPager->state>=PAGER_RESERVED );
49.2775 + pager_error(pPager, rc);
49.2776 + }
49.2777 + }
49.2778 + }
49.2779 +
49.2780 + return nReleased;
49.2781 +}
49.2782 +#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT && !SQLITE_OMIT_DISKIO */
49.2783 +
49.2784 +/*
49.2785 +** Read the content of page pPg out of the database file.
49.2786 +*/
49.2787 +static int readDbPage(Pager *pPager, PgHdr *pPg, Pgno pgno){
49.2788 + int rc;
49.2789 + assert( MEMDB==0 );
49.2790 + rc = sqlite3OsSeek(pPager->fd, (pgno-1)*(i64)pPager->pageSize);
49.2791 + if( rc==SQLITE_OK ){
49.2792 + rc = sqlite3OsRead(pPager->fd, PGHDR_TO_DATA(pPg),
49.2793 + pPager->pageSize);
49.2794 + }
49.2795 + PAGER_INCR(sqlite3_pager_readdb_count);
49.2796 + PAGER_INCR(pPager->nRead);
49.2797 + IOTRACE(("PGIN %p %d\n", pPager, pgno));
49.2798 + if( pgno==1 ){
49.2799 + memcpy(&pPager->dbFileVers, &((u8*)PGHDR_TO_DATA(pPg))[24],
49.2800 + sizeof(pPager->dbFileVers));
49.2801 + }
49.2802 + CODEC1(pPager, PGHDR_TO_DATA(pPg), pPg->pgno, 3);
49.2803 + PAGERTRACE4("FETCH %d page %d hash(%08x)\n",
49.2804 + PAGERID(pPager), pPg->pgno, pager_pagehash(pPg));
49.2805 + return rc;
49.2806 +}
49.2807 +
49.2808 +
49.2809 +/*
49.2810 +** This function is called to obtain the shared lock required before
49.2811 +** data may be read from the pager cache. If the shared lock has already
49.2812 +** been obtained, this function is a no-op.
49.2813 +**
49.2814 +** Immediately after obtaining the shared lock (if required), this function
49.2815 +** checks for a hot-journal file. If one is found, an emergency rollback
49.2816 +** is performed immediately.
49.2817 +*/
49.2818 +static int pagerSharedLock(Pager *pPager){
49.2819 + int rc = SQLITE_OK;
49.2820 +
49.2821 + if( pPager->state==PAGER_UNLOCK ){
49.2822 + if( !MEMDB ){
49.2823 + assert( pPager->nRef==0 );
49.2824 + if( !pPager->noReadlock ){
49.2825 + rc = pager_wait_on_lock(pPager, SHARED_LOCK);
49.2826 + if( rc!=SQLITE_OK ){
49.2827 + return pager_error(pPager, rc);
49.2828 + }
49.2829 + assert( pPager->state>=SHARED_LOCK );
49.2830 + }
49.2831 +
49.2832 + /* If a journal file exists, and there is no RESERVED lock on the
49.2833 + ** database file, then it either needs to be played back or deleted.
49.2834 + */
49.2835 + if( hasHotJournal(pPager) ){
49.2836 + /* Get an EXCLUSIVE lock on the database file. At this point it is
49.2837 + ** important that a RESERVED lock is not obtained on the way to the
49.2838 + ** EXCLUSIVE lock. If it were, another process might open the
49.2839 + ** database file, detect the RESERVED lock, and conclude that the
49.2840 + ** database is safe to read while this process is still rolling it
49.2841 + ** back.
49.2842 + **
49.2843 + ** Because the intermediate RESERVED lock is not requested, the
49.2844 + ** second process will get to this point in the code and fail to
49.2845 + ** obtain it's own EXCLUSIVE lock on the database file.
49.2846 + */
49.2847 + rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
49.2848 + if( rc!=SQLITE_OK ){
49.2849 + pager_unlock(pPager);
49.2850 + return pager_error(pPager, rc);
49.2851 + }
49.2852 + pPager->state = PAGER_EXCLUSIVE;
49.2853 +
49.2854 + /* Open the journal for reading only. Return SQLITE_BUSY if
49.2855 + ** we are unable to open the journal file.
49.2856 + **
49.2857 + ** The journal file does not need to be locked itself. The
49.2858 + ** journal file is never open unless the main database file holds
49.2859 + ** a write lock, so there is never any chance of two or more
49.2860 + ** processes opening the journal at the same time.
49.2861 + **
49.2862 + ** Open the journal for read/write access. This is because in
49.2863 + ** exclusive-access mode the file descriptor will be kept open and
49.2864 + ** possibly used for a transaction later on. On some systems, the
49.2865 + ** OsTruncate() call used in exclusive-access mode also requires
49.2866 + ** a read/write file handle.
49.2867 + */
49.2868 + rc = SQLITE_BUSY;
49.2869 + if( sqlite3OsFileExists(pPager->zJournal) ){
49.2870 + int ro;
49.2871 + assert( !pPager->tempFile );
49.2872 + rc = sqlite3OsOpenReadWrite(pPager->zJournal, &pPager->jfd, &ro);
49.2873 + assert( rc!=SQLITE_OK || pPager->jfd );
49.2874 + if( ro ){
49.2875 + rc = SQLITE_BUSY;
49.2876 + sqlite3OsClose(&pPager->jfd);
49.2877 + }
49.2878 + }
49.2879 + if( rc!=SQLITE_OK ){
49.2880 + pager_unlock(pPager);
49.2881 + return SQLITE_BUSY;
49.2882 + }
49.2883 + pPager->journalOpen = 1;
49.2884 + pPager->journalStarted = 0;
49.2885 + pPager->journalOff = 0;
49.2886 + pPager->setMaster = 0;
49.2887 + pPager->journalHdr = 0;
49.2888 +
49.2889 + /* Playback and delete the journal. Drop the database write
49.2890 + ** lock and reacquire the read lock.
49.2891 + */
49.2892 + rc = pager_playback(pPager, 1);
49.2893 + if( rc!=SQLITE_OK ){
49.2894 + return pager_error(pPager, rc);
49.2895 + }
49.2896 + assert(pPager->state==PAGER_SHARED ||
49.2897 + (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
49.2898 + );
49.2899 + }
49.2900 +
49.2901 + if( pPager->pAll ){
49.2902 + /* The shared-lock has just been acquired on the database file
49.2903 + ** and there are already pages in the cache (from a previous
49.2904 + ** read or write transaction). Check to see if the database
49.2905 + ** has been modified. If the database has changed, flush the
49.2906 + ** cache.
49.2907 + **
49.2908 + ** Database changes is detected by looking at 15 bytes beginning
49.2909 + ** at offset 24 into the file. The first 4 of these 16 bytes are
49.2910 + ** a 32-bit counter that is incremented with each change. The
49.2911 + ** other bytes change randomly with each file change when
49.2912 + ** a codec is in use.
49.2913 + **
49.2914 + ** There is a vanishingly small chance that a change will not be
49.2915 + ** detected. The chance of an undetected change is so small that
49.2916 + ** it can be neglected.
49.2917 + */
49.2918 + char dbFileVers[sizeof(pPager->dbFileVers)];
49.2919 + sqlite3PagerPagecount(pPager);
49.2920 +
49.2921 + if( pPager->errCode ){
49.2922 + return pPager->errCode;
49.2923 + }
49.2924 +
49.2925 + if( pPager->dbSize>0 ){
49.2926 + IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
49.2927 + rc = sqlite3OsSeek(pPager->fd, 24);
49.2928 + if( rc!=SQLITE_OK ){
49.2929 + return rc;
49.2930 + }
49.2931 + rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers));
49.2932 + if( rc!=SQLITE_OK ){
49.2933 + return rc;
49.2934 + }
49.2935 + }else{
49.2936 + memset(dbFileVers, 0, sizeof(dbFileVers));
49.2937 + }
49.2938 +
49.2939 + if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
49.2940 + pager_reset(pPager);
49.2941 + }
49.2942 + }
49.2943 + }
49.2944 + assert( pPager->exclusiveMode || pPager->state<=PAGER_SHARED );
49.2945 + if( pPager->state==PAGER_UNLOCK ){
49.2946 + pPager->state = PAGER_SHARED;
49.2947 + }
49.2948 + }
49.2949 +
49.2950 + return rc;
49.2951 +}
49.2952 +
49.2953 +/*
49.2954 +** Allocate a PgHdr object. Either create a new one or reuse
49.2955 +** an existing one that is not otherwise in use.
49.2956 +**
49.2957 +** A new PgHdr structure is created if any of the following are
49.2958 +** true:
49.2959 +**
49.2960 +** (1) We have not exceeded our maximum allocated cache size
49.2961 +** as set by the "PRAGMA cache_size" command.
49.2962 +**
49.2963 +** (2) There are no unused PgHdr objects available at this time.
49.2964 +**
49.2965 +** (3) This is an in-memory database.
49.2966 +**
49.2967 +** (4) There are no PgHdr objects that do not require a journal
49.2968 +** file sync and a sync of the journal file is currently
49.2969 +** prohibited.
49.2970 +**
49.2971 +** Otherwise, reuse an existing PgHdr. In other words, reuse an
49.2972 +** existing PgHdr if all of the following are true:
49.2973 +**
49.2974 +** (1) We have reached or exceeded the maximum cache size
49.2975 +** allowed by "PRAGMA cache_size".
49.2976 +**
49.2977 +** (2) There is a PgHdr available with PgHdr->nRef==0
49.2978 +**
49.2979 +** (3) We are not in an in-memory database
49.2980 +**
49.2981 +** (4) Either there is an available PgHdr that does not need
49.2982 +** to be synced to disk or else disk syncing is currently
49.2983 +** allowed.
49.2984 +*/
49.2985 +static int pagerAllocatePage(Pager *pPager, PgHdr **ppPg){
49.2986 + int rc = SQLITE_OK;
49.2987 + PgHdr *pPg;
49.2988 +
49.2989 + /* Create a new PgHdr if any of the four conditions defined
49.2990 + ** above is met: */
49.2991 + if( pPager->nPage<pPager->mxPage
49.2992 + || pPager->pFirst==0
49.2993 + || MEMDB
49.2994 + || (pPager->pFirstSynced==0 && pPager->doNotSync)
49.2995 + ){
49.2996 + if( pPager->nPage>=pPager->nHash ){
49.2997 + pager_resize_hash_table(pPager,
49.2998 + pPager->nHash<256 ? 256 : pPager->nHash*2);
49.2999 + if( pPager->nHash==0 ){
49.3000 + rc = SQLITE_NOMEM;
49.3001 + goto pager_allocate_out;
49.3002 + }
49.3003 + }
49.3004 + pPg = sqliteMallocRaw( sizeof(*pPg) + pPager->pageSize
49.3005 + + sizeof(u32) + pPager->nExtra
49.3006 + + MEMDB*sizeof(PgHistory) );
49.3007 + if( pPg==0 ){
49.3008 + rc = SQLITE_NOMEM;
49.3009 + goto pager_allocate_out;
49.3010 + }
49.3011 + memset(pPg, 0, sizeof(*pPg));
49.3012 + if( MEMDB ){
49.3013 + memset(PGHDR_TO_HIST(pPg, pPager), 0, sizeof(PgHistory));
49.3014 + }
49.3015 + pPg->pPager = pPager;
49.3016 + pPg->pNextAll = pPager->pAll;
49.3017 + pPager->pAll = pPg;
49.3018 + pPager->nPage++;
49.3019 + }else{
49.3020 + /* Recycle an existing page with a zero ref-count. */
49.3021 + rc = pager_recycle(pPager, 1, &pPg);
49.3022 + if( rc==SQLITE_BUSY ){
49.3023 + rc = SQLITE_IOERR_BLOCKED;
49.3024 + }
49.3025 + if( rc!=SQLITE_OK ){
49.3026 + goto pager_allocate_out;
49.3027 + }
49.3028 + assert( pPager->state>=SHARED_LOCK );
49.3029 + assert(pPg);
49.3030 + }
49.3031 + *ppPg = pPg;
49.3032 +
49.3033 +pager_allocate_out:
49.3034 + return rc;
49.3035 +}
49.3036 +
49.3037 +/*
49.3038 +** Make sure we have the content for a page. If the page was
49.3039 +** previously acquired with noContent==1, then the content was
49.3040 +** just initialized to zeros instead of being read from disk.
49.3041 +** But now we need the real data off of disk. So make sure we
49.3042 +** have it. Read it in if we do not have it already.
49.3043 +*/
49.3044 +static int pager_get_content(PgHdr *pPg){
49.3045 + if( pPg->needRead ){
49.3046 + int rc = readDbPage(pPg->pPager, pPg, pPg->pgno);
49.3047 + if( rc==SQLITE_OK ){
49.3048 + pPg->needRead = 0;
49.3049 + }else{
49.3050 + return rc;
49.3051 + }
49.3052 + }
49.3053 + return SQLITE_OK;
49.3054 +}
49.3055 +
49.3056 +/*
49.3057 +** Acquire a page.
49.3058 +**
49.3059 +** A read lock on the disk file is obtained when the first page is acquired.
49.3060 +** This read lock is dropped when the last page is released.
49.3061 +**
49.3062 +** This routine works for any page number greater than 0. If the database
49.3063 +** file is smaller than the requested page, then no actual disk
49.3064 +** read occurs and the memory image of the page is initialized to
49.3065 +** all zeros. The extra data appended to a page is always initialized
49.3066 +** to zeros the first time a page is loaded into memory.
49.3067 +**
49.3068 +** The acquisition might fail for several reasons. In all cases,
49.3069 +** an appropriate error code is returned and *ppPage is set to NULL.
49.3070 +**
49.3071 +** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
49.3072 +** to find a page in the in-memory cache first. If the page is not already
49.3073 +** in memory, this routine goes to disk to read it in whereas Lookup()
49.3074 +** just returns 0. This routine acquires a read-lock the first time it
49.3075 +** has to go to disk, and could also playback an old journal if necessary.
49.3076 +** Since Lookup() never goes to disk, it never has to deal with locks
49.3077 +** or journal files.
49.3078 +**
49.3079 +** If noContent is false, the page contents are actually read from disk.
49.3080 +** If noContent is true, it means that we do not care about the contents
49.3081 +** of the page at this time, so do not do a disk read. Just fill in the
49.3082 +** page content with zeros. But mark the fact that we have not read the
49.3083 +** content by setting the PgHdr.needRead flag. Later on, if
49.3084 +** sqlite3PagerWrite() is called on this page or if this routine is
49.3085 +** called again with noContent==0, that means that the content is needed
49.3086 +** and the disk read should occur at that point.
49.3087 +*/
49.3088 +int sqlite3PagerAcquire(
49.3089 + Pager *pPager, /* The pager open on the database file */
49.3090 + Pgno pgno, /* Page number to fetch */
49.3091 + DbPage **ppPage, /* Write a pointer to the page here */
49.3092 + int noContent /* Do not bother reading content from disk if true */
49.3093 +){
49.3094 + PgHdr *pPg;
49.3095 + int rc;
49.3096 +
49.3097 + assert( pPager->state==PAGER_UNLOCK || pPager->nRef>0 || pgno==1 );
49.3098 +
49.3099 + /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
49.3100 + ** number greater than this, or zero, is requested.
49.3101 + */
49.3102 + if( pgno>PAGER_MAX_PGNO || pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
49.3103 + return SQLITE_CORRUPT_BKPT;
49.3104 + }
49.3105 +
49.3106 + /* Make sure we have not hit any critical errors.
49.3107 + */
49.3108 + assert( pPager!=0 );
49.3109 + *ppPage = 0;
49.3110 + if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
49.3111 + return pPager->errCode;
49.3112 + }
49.3113 +
49.3114 + /* If this is the first page accessed, then get a SHARED lock
49.3115 + ** on the database file. pagerSharedLock() is a no-op if
49.3116 + ** a database lock is already held.
49.3117 + */
49.3118 + rc = pagerSharedLock(pPager);
49.3119 + if( rc!=SQLITE_OK ){
49.3120 + return rc;
49.3121 + }
49.3122 + assert( pPager->state!=PAGER_UNLOCK );
49.3123 +
49.3124 + pPg = pager_lookup(pPager, pgno);
49.3125 + if( pPg==0 ){
49.3126 + /* The requested page is not in the page cache. */
49.3127 + int nMax;
49.3128 + int h;
49.3129 + PAGER_INCR(pPager->nMiss);
49.3130 + rc = pagerAllocatePage(pPager, &pPg);
49.3131 + if( rc!=SQLITE_OK ){
49.3132 + return rc;
49.3133 + }
49.3134 +
49.3135 + pPg->pgno = pgno;
49.3136 + assert( !MEMDB || pgno>pPager->stmtSize );
49.3137 + if( pPager->aInJournal && (int)pgno<=pPager->origDbSize ){
49.3138 + sqlite3CheckMemory(pPager->aInJournal, pgno/8);
49.3139 + assert( pPager->journalOpen );
49.3140 + pPg->inJournal = (pPager->aInJournal[pgno/8] & (1<<(pgno&7)))!=0;
49.3141 + pPg->needSync = 0;
49.3142 + }else{
49.3143 + pPg->inJournal = 0;
49.3144 + pPg->needSync = 0;
49.3145 + }
49.3146 +
49.3147 + makeClean(pPg);
49.3148 + pPg->nRef = 1;
49.3149 + REFINFO(pPg);
49.3150 +
49.3151 + pPager->nRef++;
49.3152 + if( pPager->nExtra>0 ){
49.3153 + memset(PGHDR_TO_EXTRA(pPg, pPager), 0, pPager->nExtra);
49.3154 + }
49.3155 + nMax = sqlite3PagerPagecount(pPager);
49.3156 + if( pPager->errCode ){
49.3157 + sqlite3PagerUnref(pPg);
49.3158 + rc = pPager->errCode;
49.3159 + return rc;
49.3160 + }
49.3161 +
49.3162 + /* Populate the page with data, either by reading from the database
49.3163 + ** file, or by setting the entire page to zero.
49.3164 + */
49.3165 + if( nMax<(int)pgno || MEMDB || (noContent && !pPager->alwaysRollback) ){
49.3166 + if( pgno>pPager->mxPgno ){
49.3167 + sqlite3PagerUnref(pPg);
49.3168 + return SQLITE_FULL;
49.3169 + }
49.3170 + memset(PGHDR_TO_DATA(pPg), 0, pPager->pageSize);
49.3171 + pPg->needRead = noContent && !pPager->alwaysRollback;
49.3172 + IOTRACE(("ZERO %p %d\n", pPager, pgno));
49.3173 + }else{
49.3174 + rc = readDbPage(pPager, pPg, pgno);
49.3175 + if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
49.3176 + pPg->pgno = 0;
49.3177 + sqlite3PagerUnref(pPg);
49.3178 + return rc;
49.3179 + }
49.3180 + pPg->needRead = 0;
49.3181 + }
49.3182 +
49.3183 + /* Link the page into the page hash table */
49.3184 + h = pgno & (pPager->nHash-1);
49.3185 + assert( pgno!=0 );
49.3186 + pPg->pNextHash = pPager->aHash[h];
49.3187 + pPager->aHash[h] = pPg;
49.3188 + if( pPg->pNextHash ){
49.3189 + assert( pPg->pNextHash->pPrevHash==0 );
49.3190 + pPg->pNextHash->pPrevHash = pPg;
49.3191 + }
49.3192 +
49.3193 +#ifdef SQLITE_CHECK_PAGES
49.3194 + pPg->pageHash = pager_pagehash(pPg);
49.3195 +#endif
49.3196 + }else{
49.3197 + /* The requested page is in the page cache. */
49.3198 + assert(pPager->nRef>0 || pgno==1);
49.3199 + PAGER_INCR(pPager->nHit);
49.3200 + if( !noContent ){
49.3201 + rc = pager_get_content(pPg);
49.3202 + if( rc ){
49.3203 + return rc;
49.3204 + }
49.3205 + }
49.3206 + page_ref(pPg);
49.3207 + }
49.3208 + *ppPage = pPg;
49.3209 + return SQLITE_OK;
49.3210 +}
49.3211 +
49.3212 +/*
49.3213 +** Acquire a page if it is already in the in-memory cache. Do
49.3214 +** not read the page from disk. Return a pointer to the page,
49.3215 +** or 0 if the page is not in cache.
49.3216 +**
49.3217 +** See also sqlite3PagerGet(). The difference between this routine
49.3218 +** and sqlite3PagerGet() is that _get() will go to the disk and read
49.3219 +** in the page if the page is not already in cache. This routine
49.3220 +** returns NULL if the page is not in cache or if a disk I/O error
49.3221 +** has ever happened.
49.3222 +*/
49.3223 +DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
49.3224 + PgHdr *pPg;
49.3225 +
49.3226 + assert( pPager!=0 );
49.3227 + assert( pgno!=0 );
49.3228 +
49.3229 + if( pPager->state==PAGER_UNLOCK ){
49.3230 + assert( !pPager->pAll || pPager->exclusiveMode );
49.3231 + return 0;
49.3232 + }
49.3233 + if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
49.3234 + return 0;
49.3235 + }
49.3236 + pPg = pager_lookup(pPager, pgno);
49.3237 + if( pPg==0 ) return 0;
49.3238 + page_ref(pPg);
49.3239 + return pPg;
49.3240 +}
49.3241 +
49.3242 +/*
49.3243 +** Release a page.
49.3244 +**
49.3245 +** If the number of references to the page drop to zero, then the
49.3246 +** page is added to the LRU list. When all references to all pages
49.3247 +** are released, a rollback occurs and the lock on the database is
49.3248 +** removed.
49.3249 +*/
49.3250 +int sqlite3PagerUnref(DbPage *pPg){
49.3251 +
49.3252 + /* Decrement the reference count for this page
49.3253 + */
49.3254 + assert( pPg->nRef>0 );
49.3255 + pPg->nRef--;
49.3256 + REFINFO(pPg);
49.3257 +
49.3258 + CHECK_PAGE(pPg);
49.3259 +
49.3260 + /* When the number of references to a page reach 0, call the
49.3261 + ** destructor and add the page to the freelist.
49.3262 + */
49.3263 + if( pPg->nRef==0 ){
49.3264 + Pager *pPager;
49.3265 + pPager = pPg->pPager;
49.3266 + pPg->pNextFree = 0;
49.3267 + pPg->pPrevFree = pPager->pLast;
49.3268 + pPager->pLast = pPg;
49.3269 + if( pPg->pPrevFree ){
49.3270 + pPg->pPrevFree->pNextFree = pPg;
49.3271 + }else{
49.3272 + pPager->pFirst = pPg;
49.3273 + }
49.3274 + if( pPg->needSync==0 && pPager->pFirstSynced==0 ){
49.3275 + pPager->pFirstSynced = pPg;
49.3276 + }
49.3277 + if( pPager->xDestructor ){
49.3278 + pPager->xDestructor(pPg, pPager->pageSize);
49.3279 + }
49.3280 +
49.3281 + /* When all pages reach the freelist, drop the read lock from
49.3282 + ** the database file.
49.3283 + */
49.3284 + pPager->nRef--;
49.3285 + assert( pPager->nRef>=0 );
49.3286 + if( pPager->nRef==0 && (!pPager->exclusiveMode || pPager->journalOff>0) ){
49.3287 + pagerUnlockAndRollback(pPager);
49.3288 + }
49.3289 + }
49.3290 + return SQLITE_OK;
49.3291 +}
49.3292 +
49.3293 +/*
49.3294 +** Create a journal file for pPager. There should already be a RESERVED
49.3295 +** or EXCLUSIVE lock on the database file when this routine is called.
49.3296 +**
49.3297 +** Return SQLITE_OK if everything. Return an error code and release the
49.3298 +** write lock if anything goes wrong.
49.3299 +*/
49.3300 +static int pager_open_journal(Pager *pPager){
49.3301 + int rc;
49.3302 + assert( !MEMDB );
49.3303 + assert( pPager->state>=PAGER_RESERVED );
49.3304 + assert( pPager->journalOpen==0 );
49.3305 + assert( pPager->useJournal );
49.3306 + assert( pPager->aInJournal==0 );
49.3307 + sqlite3PagerPagecount(pPager);
49.3308 + pPager->aInJournal = sqliteMalloc( pPager->dbSize/8 + 1 );
49.3309 + if( pPager->aInJournal==0 ){
49.3310 + rc = SQLITE_NOMEM;
49.3311 + goto failed_to_open_journal;
49.3312 + }
49.3313 + rc = sqlite3OsOpenExclusive(pPager->zJournal, &pPager->jfd,
49.3314 + pPager->tempFile);
49.3315 + assert( rc!=SQLITE_OK || pPager->jfd );
49.3316 + pPager->journalOff = 0;
49.3317 + pPager->setMaster = 0;
49.3318 + pPager->journalHdr = 0;
49.3319 + if( rc!=SQLITE_OK ){
49.3320 + if( rc==SQLITE_NOMEM ){
49.3321 + sqlite3OsDelete(pPager->zJournal);
49.3322 + }
49.3323 + goto failed_to_open_journal;
49.3324 + }
49.3325 + sqlite3OsSetFullSync(pPager->jfd, pPager->full_fsync);
49.3326 + sqlite3OsSetFullSync(pPager->fd, pPager->full_fsync);
49.3327 + sqlite3OsOpenDirectory(pPager->jfd, pPager->zDirectory);
49.3328 + pPager->journalOpen = 1;
49.3329 + pPager->journalStarted = 0;
49.3330 + pPager->needSync = 0;
49.3331 + pPager->alwaysRollback = 0;
49.3332 + pPager->nRec = 0;
49.3333 + if( pPager->errCode ){
49.3334 + rc = pPager->errCode;
49.3335 + goto failed_to_open_journal;
49.3336 + }
49.3337 + pPager->origDbSize = pPager->dbSize;
49.3338 +
49.3339 + rc = writeJournalHdr(pPager);
49.3340 +
49.3341 + if( pPager->stmtAutoopen && rc==SQLITE_OK ){
49.3342 + rc = sqlite3PagerStmtBegin(pPager);
49.3343 + }
49.3344 + if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
49.3345 + rc = pager_end_transaction(pPager);
49.3346 + if( rc==SQLITE_OK ){
49.3347 + rc = SQLITE_FULL;
49.3348 + }
49.3349 + }
49.3350 + return rc;
49.3351 +
49.3352 +failed_to_open_journal:
49.3353 + sqliteFree(pPager->aInJournal);
49.3354 + pPager->aInJournal = 0;
49.3355 + return rc;
49.3356 +}
49.3357 +
49.3358 +/*
49.3359 +** Acquire a write-lock on the database. The lock is removed when
49.3360 +** the any of the following happen:
49.3361 +**
49.3362 +** * sqlite3PagerCommitPhaseTwo() is called.
49.3363 +** * sqlite3PagerRollback() is called.
49.3364 +** * sqlite3PagerClose() is called.
49.3365 +** * sqlite3PagerUnref() is called to on every outstanding page.
49.3366 +**
49.3367 +** The first parameter to this routine is a pointer to any open page of the
49.3368 +** database file. Nothing changes about the page - it is used merely to
49.3369 +** acquire a pointer to the Pager structure and as proof that there is
49.3370 +** already a read-lock on the database.
49.3371 +**
49.3372 +** The second parameter indicates how much space in bytes to reserve for a
49.3373 +** master journal file-name at the start of the journal when it is created.
49.3374 +**
49.3375 +** A journal file is opened if this is not a temporary file. For temporary
49.3376 +** files, the opening of the journal file is deferred until there is an
49.3377 +** actual need to write to the journal.
49.3378 +**
49.3379 +** If the database is already reserved for writing, this routine is a no-op.
49.3380 +**
49.3381 +** If exFlag is true, go ahead and get an EXCLUSIVE lock on the file
49.3382 +** immediately instead of waiting until we try to flush the cache. The
49.3383 +** exFlag is ignored if a transaction is already active.
49.3384 +*/
49.3385 +int sqlite3PagerBegin(DbPage *pPg, int exFlag){
49.3386 + Pager *pPager = pPg->pPager;
49.3387 + int rc = SQLITE_OK;
49.3388 + assert( pPg->nRef>0 );
49.3389 + assert( pPager->state!=PAGER_UNLOCK );
49.3390 + if( pPager->state==PAGER_SHARED ){
49.3391 + assert( pPager->aInJournal==0 );
49.3392 + if( MEMDB ){
49.3393 + pPager->state = PAGER_EXCLUSIVE;
49.3394 + pPager->origDbSize = pPager->dbSize;
49.3395 + }else{
49.3396 + rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
49.3397 + if( rc==SQLITE_OK ){
49.3398 + pPager->state = PAGER_RESERVED;
49.3399 + if( exFlag ){
49.3400 + rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
49.3401 + }
49.3402 + }
49.3403 + if( rc!=SQLITE_OK ){
49.3404 + return rc;
49.3405 + }
49.3406 + pPager->dirtyCache = 0;
49.3407 + PAGERTRACE2("TRANSACTION %d\n", PAGERID(pPager));
49.3408 + if( pPager->useJournal && !pPager->tempFile ){
49.3409 + rc = pager_open_journal(pPager);
49.3410 + }
49.3411 + }
49.3412 + }else if( pPager->journalOpen && pPager->journalOff==0 ){
49.3413 + /* This happens when the pager was in exclusive-access mode last
49.3414 + ** time a (read or write) transaction was successfully concluded
49.3415 + ** by this connection. Instead of deleting the journal file it was
49.3416 + ** kept open and truncated to 0 bytes.
49.3417 + */
49.3418 + assert( pPager->nRec==0 );
49.3419 + assert( pPager->origDbSize==0 );
49.3420 + assert( pPager->aInJournal==0 );
49.3421 + sqlite3PagerPagecount(pPager);
49.3422 + pPager->aInJournal = sqliteMalloc( pPager->dbSize/8 + 1 );
49.3423 + if( !pPager->aInJournal ){
49.3424 + rc = SQLITE_NOMEM;
49.3425 + }else{
49.3426 + pPager->origDbSize = pPager->dbSize;
49.3427 + rc = writeJournalHdr(pPager);
49.3428 + }
49.3429 + }
49.3430 + assert( !pPager->journalOpen || pPager->journalOff>0 || rc!=SQLITE_OK );
49.3431 + return rc;
49.3432 +}
49.3433 +
49.3434 +/*
49.3435 +** Make a page dirty. Set its dirty flag and add it to the dirty
49.3436 +** page list.
49.3437 +*/
49.3438 +static void makeDirty(PgHdr *pPg){
49.3439 + if( pPg->dirty==0 ){
49.3440 + Pager *pPager = pPg->pPager;
49.3441 + pPg->dirty = 1;
49.3442 + pPg->pDirty = pPager->pDirty;
49.3443 + if( pPager->pDirty ){
49.3444 + pPager->pDirty->pPrevDirty = pPg;
49.3445 + }
49.3446 + pPg->pPrevDirty = 0;
49.3447 + pPager->pDirty = pPg;
49.3448 + }
49.3449 +}
49.3450 +
49.3451 +/*
49.3452 +** Make a page clean. Clear its dirty bit and remove it from the
49.3453 +** dirty page list.
49.3454 +*/
49.3455 +static void makeClean(PgHdr *pPg){
49.3456 + if( pPg->dirty ){
49.3457 + pPg->dirty = 0;
49.3458 + if( pPg->pDirty ){
49.3459 + pPg->pDirty->pPrevDirty = pPg->pPrevDirty;
49.3460 + }
49.3461 + if( pPg->pPrevDirty ){
49.3462 + pPg->pPrevDirty->pDirty = pPg->pDirty;
49.3463 + }else{
49.3464 + pPg->pPager->pDirty = pPg->pDirty;
49.3465 + }
49.3466 + }
49.3467 +}
49.3468 +
49.3469 +
49.3470 +/*
49.3471 +** Mark a data page as writeable. The page is written into the journal
49.3472 +** if it is not there already. This routine must be called before making
49.3473 +** changes to a page.
49.3474 +**
49.3475 +** The first time this routine is called, the pager creates a new
49.3476 +** journal and acquires a RESERVED lock on the database. If the RESERVED
49.3477 +** lock could not be acquired, this routine returns SQLITE_BUSY. The
49.3478 +** calling routine must check for that return value and be careful not to
49.3479 +** change any page data until this routine returns SQLITE_OK.
49.3480 +**
49.3481 +** If the journal file could not be written because the disk is full,
49.3482 +** then this routine returns SQLITE_FULL and does an immediate rollback.
49.3483 +** All subsequent write attempts also return SQLITE_FULL until there
49.3484 +** is a call to sqlite3PagerCommit() or sqlite3PagerRollback() to
49.3485 +** reset.
49.3486 +*/
49.3487 +static int pager_write(PgHdr *pPg){
49.3488 + void *pData = PGHDR_TO_DATA(pPg);
49.3489 + Pager *pPager = pPg->pPager;
49.3490 + int rc = SQLITE_OK;
49.3491 +
49.3492 + /* Check for errors
49.3493 + */
49.3494 + if( pPager->errCode ){
49.3495 + return pPager->errCode;
49.3496 + }
49.3497 + if( pPager->readOnly ){
49.3498 + return SQLITE_PERM;
49.3499 + }
49.3500 +
49.3501 + assert( !pPager->setMaster );
49.3502 +
49.3503 + CHECK_PAGE(pPg);
49.3504 +
49.3505 + /* If this page was previously acquired with noContent==1, that means
49.3506 + ** we didn't really read in the content of the page. This can happen
49.3507 + ** (for example) when the page is being moved to the freelist. But
49.3508 + ** now we are (perhaps) moving the page off of the freelist for
49.3509 + ** reuse and we need to know its original content so that content
49.3510 + ** can be stored in the rollback journal. So do the read at this
49.3511 + ** time.
49.3512 + */
49.3513 + rc = pager_get_content(pPg);
49.3514 + if( rc ){
49.3515 + return rc;
49.3516 + }
49.3517 +
49.3518 + /* Mark the page as dirty. If the page has already been written
49.3519 + ** to the journal then we can return right away.
49.3520 + */
49.3521 + makeDirty(pPg);
49.3522 + if( pPg->inJournal && (pageInStatement(pPg) || pPager->stmtInUse==0) ){
49.3523 + pPager->dirtyCache = 1;
49.3524 + }else{
49.3525 +
49.3526 + /* If we get this far, it means that the page needs to be
49.3527 + ** written to the transaction journal or the ckeckpoint journal
49.3528 + ** or both.
49.3529 + **
49.3530 + ** First check to see that the transaction journal exists and
49.3531 + ** create it if it does not.
49.3532 + */
49.3533 + assert( pPager->state!=PAGER_UNLOCK );
49.3534 + rc = sqlite3PagerBegin(pPg, 0);
49.3535 + if( rc!=SQLITE_OK ){
49.3536 + return rc;
49.3537 + }
49.3538 + assert( pPager->state>=PAGER_RESERVED );
49.3539 + if( !pPager->journalOpen && pPager->useJournal ){
49.3540 + rc = pager_open_journal(pPager);
49.3541 + if( rc!=SQLITE_OK ) return rc;
49.3542 + }
49.3543 + assert( pPager->journalOpen || !pPager->useJournal );
49.3544 + pPager->dirtyCache = 1;
49.3545 +
49.3546 + /* The transaction journal now exists and we have a RESERVED or an
49.3547 + ** EXCLUSIVE lock on the main database file. Write the current page to
49.3548 + ** the transaction journal if it is not there already.
49.3549 + */
49.3550 + if( !pPg->inJournal && (pPager->useJournal || MEMDB) ){
49.3551 + if( (int)pPg->pgno <= pPager->origDbSize ){
49.3552 + int szPg;
49.3553 + if( MEMDB ){
49.3554 + PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
49.3555 + PAGERTRACE3("JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
49.3556 + assert( pHist->pOrig==0 );
49.3557 + pHist->pOrig = sqliteMallocRaw( pPager->pageSize );
49.3558 + if( pHist->pOrig ){
49.3559 + memcpy(pHist->pOrig, PGHDR_TO_DATA(pPg), pPager->pageSize);
49.3560 + }
49.3561 + }else{
49.3562 + u32 cksum, saved;
49.3563 + char *pData2, *pEnd;
49.3564 + /* We should never write to the journal file the page that
49.3565 + ** contains the database locks. The following assert verifies
49.3566 + ** that we do not. */
49.3567 + assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
49.3568 + pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
49.3569 + cksum = pager_cksum(pPager, (u8*)pData2);
49.3570 + pEnd = pData2 + pPager->pageSize;
49.3571 + pData2 -= 4;
49.3572 + saved = *(u32*)pEnd;
49.3573 + put32bits(pEnd, cksum);
49.3574 + szPg = pPager->pageSize+8;
49.3575 + put32bits(pData2, pPg->pgno);
49.3576 + rc = sqlite3OsWrite(pPager->jfd, pData2, szPg);
49.3577 + IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
49.3578 + pPager->journalOff, szPg));
49.3579 + PAGER_INCR(sqlite3_pager_writej_count);
49.3580 + pPager->journalOff += szPg;
49.3581 + PAGERTRACE5("JOURNAL %d page %d needSync=%d hash(%08x)\n",
49.3582 + PAGERID(pPager), pPg->pgno, pPg->needSync, pager_pagehash(pPg));
49.3583 + *(u32*)pEnd = saved;
49.3584 +
49.3585 + /* An error has occured writing to the journal file. The
49.3586 + ** transaction will be rolled back by the layer above.
49.3587 + */
49.3588 + if( rc!=SQLITE_OK ){
49.3589 + return rc;
49.3590 + }
49.3591 +
49.3592 + pPager->nRec++;
49.3593 + assert( pPager->aInJournal!=0 );
49.3594 + pPager->aInJournal[pPg->pgno/8] |= 1<<(pPg->pgno&7);
49.3595 + pPg->needSync = !pPager->noSync;
49.3596 + if( pPager->stmtInUse ){
49.3597 + pPager->aInStmt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
49.3598 + }
49.3599 + }
49.3600 + }else{
49.3601 + pPg->needSync = !pPager->journalStarted && !pPager->noSync;
49.3602 + PAGERTRACE4("APPEND %d page %d needSync=%d\n",
49.3603 + PAGERID(pPager), pPg->pgno, pPg->needSync);
49.3604 + }
49.3605 + if( pPg->needSync ){
49.3606 + pPager->needSync = 1;
49.3607 + }
49.3608 + pPg->inJournal = 1;
49.3609 + }
49.3610 +
49.3611 + /* If the statement journal is open and the page is not in it,
49.3612 + ** then write the current page to the statement journal. Note that
49.3613 + ** the statement journal format differs from the standard journal format
49.3614 + ** in that it omits the checksums and the header.
49.3615 + */
49.3616 + if( pPager->stmtInUse
49.3617 + && !pageInStatement(pPg)
49.3618 + && (int)pPg->pgno<=pPager->stmtSize
49.3619 + ){
49.3620 + assert( pPg->inJournal || (int)pPg->pgno>pPager->origDbSize );
49.3621 + if( MEMDB ){
49.3622 + PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
49.3623 + assert( pHist->pStmt==0 );
49.3624 + pHist->pStmt = sqliteMallocRaw( pPager->pageSize );
49.3625 + if( pHist->pStmt ){
49.3626 + memcpy(pHist->pStmt, PGHDR_TO_DATA(pPg), pPager->pageSize);
49.3627 + }
49.3628 + PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
49.3629 + page_add_to_stmt_list(pPg);
49.3630 + }else{
49.3631 + char *pData2 = CODEC2(pPager, pData, pPg->pgno, 7)-4;
49.3632 + put32bits(pData2, pPg->pgno);
49.3633 + rc = sqlite3OsWrite(pPager->stfd, pData2, pPager->pageSize+4);
49.3634 + PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
49.3635 + if( rc!=SQLITE_OK ){
49.3636 + return rc;
49.3637 + }
49.3638 + pPager->stmtNRec++;
49.3639 + assert( pPager->aInStmt!=0 );
49.3640 + pPager->aInStmt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
49.3641 + }
49.3642 + }
49.3643 + }
49.3644 +
49.3645 + /* Update the database size and return.
49.3646 + */
49.3647 + assert( pPager->state>=PAGER_SHARED );
49.3648 + if( pPager->dbSize<(int)pPg->pgno ){
49.3649 + pPager->dbSize = pPg->pgno;
49.3650 + if( !MEMDB && pPager->dbSize==PENDING_BYTE/pPager->pageSize ){
49.3651 + pPager->dbSize++;
49.3652 + }
49.3653 + }
49.3654 + return rc;
49.3655 +}
49.3656 +
49.3657 +/*
49.3658 +** This function is used to mark a data-page as writable. It uses
49.3659 +** pager_write() to open a journal file (if it is not already open)
49.3660 +** and write the page *pData to the journal.
49.3661 +**
49.3662 +** The difference between this function and pager_write() is that this
49.3663 +** function also deals with the special case where 2 or more pages
49.3664 +** fit on a single disk sector. In this case all co-resident pages
49.3665 +** must have been written to the journal file before returning.
49.3666 +*/
49.3667 +int sqlite3PagerWrite(DbPage *pDbPage){
49.3668 + int rc = SQLITE_OK;
49.3669 +
49.3670 + PgHdr *pPg = pDbPage;
49.3671 + Pager *pPager = pPg->pPager;
49.3672 + Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
49.3673 +
49.3674 + if( !MEMDB && nPagePerSector>1 ){
49.3675 + Pgno nPageCount; /* Total number of pages in database file */
49.3676 + Pgno pg1; /* First page of the sector pPg is located on. */
49.3677 + int nPage; /* Number of pages starting at pg1 to journal */
49.3678 + int ii;
49.3679 +
49.3680 + /* Set the doNotSync flag to 1. This is because we cannot allow a journal
49.3681 + ** header to be written between the pages journaled by this function.
49.3682 + */
49.3683 + assert( pPager->doNotSync==0 );
49.3684 + pPager->doNotSync = 1;
49.3685 +
49.3686 + /* This trick assumes that both the page-size and sector-size are
49.3687 + ** an integer power of 2. It sets variable pg1 to the identifier
49.3688 + ** of the first page of the sector pPg is located on.
49.3689 + */
49.3690 + pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
49.3691 +
49.3692 + nPageCount = sqlite3PagerPagecount(pPager);
49.3693 + if( pPg->pgno>nPageCount ){
49.3694 + nPage = (pPg->pgno - pg1)+1;
49.3695 + }else if( (pg1+nPagePerSector-1)>nPageCount ){
49.3696 + nPage = nPageCount+1-pg1;
49.3697 + }else{
49.3698 + nPage = nPagePerSector;
49.3699 + }
49.3700 + assert(nPage>0);
49.3701 + assert(pg1<=pPg->pgno);
49.3702 + assert((pg1+nPage)>pPg->pgno);
49.3703 +
49.3704 + for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
49.3705 + Pgno pg = pg1+ii;
49.3706 + if( !pPager->aInJournal || pg==pPg->pgno ||
49.3707 + pg>pPager->origDbSize || !(pPager->aInJournal[pg/8]&(1<<(pg&7)))
49.3708 + ) {
49.3709 + if( pg!=PAGER_MJ_PGNO(pPager) ){
49.3710 + PgHdr *pPage;
49.3711 + rc = sqlite3PagerGet(pPager, pg, &pPage);
49.3712 + if( rc==SQLITE_OK ){
49.3713 + rc = pager_write(pPage);
49.3714 + sqlite3PagerUnref(pPage);
49.3715 + }
49.3716 + }
49.3717 + }
49.3718 + }
49.3719 +
49.3720 + assert( pPager->doNotSync==1 );
49.3721 + pPager->doNotSync = 0;
49.3722 + }else{
49.3723 + rc = pager_write(pDbPage);
49.3724 + }
49.3725 + return rc;
49.3726 +}
49.3727 +
49.3728 +/*
49.3729 +** Return TRUE if the page given in the argument was previously passed
49.3730 +** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
49.3731 +** to change the content of the page.
49.3732 +*/
49.3733 +#ifndef NDEBUG
49.3734 +int sqlite3PagerIswriteable(DbPage *pPg){
49.3735 + return pPg->dirty;
49.3736 +}
49.3737 +#endif
49.3738 +
49.3739 +#ifndef SQLITE_OMIT_VACUUM
49.3740 +/*
49.3741 +** Replace the content of a single page with the information in the third
49.3742 +** argument.
49.3743 +*/
49.3744 +int sqlite3PagerOverwrite(Pager *pPager, Pgno pgno, void *pData){
49.3745 + PgHdr *pPg;
49.3746 + int rc;
49.3747 +
49.3748 + rc = sqlite3PagerGet(pPager, pgno, &pPg);
49.3749 + if( rc==SQLITE_OK ){
49.3750 + rc = sqlite3PagerWrite(pPg);
49.3751 + if( rc==SQLITE_OK ){
49.3752 + memcpy(sqlite3PagerGetData(pPg), pData, pPager->pageSize);
49.3753 + }
49.3754 + sqlite3PagerUnref(pPg);
49.3755 + }
49.3756 + return rc;
49.3757 +}
49.3758 +#endif
49.3759 +
49.3760 +/*
49.3761 +** A call to this routine tells the pager that it is not necessary to
49.3762 +** write the information on page pPg back to the disk, even though
49.3763 +** that page might be marked as dirty.
49.3764 +**
49.3765 +** The overlying software layer calls this routine when all of the data
49.3766 +** on the given page is unused. The pager marks the page as clean so
49.3767 +** that it does not get written to disk.
49.3768 +**
49.3769 +** Tests show that this optimization, together with the
49.3770 +** sqlite3PagerDontRollback() below, more than double the speed
49.3771 +** of large INSERT operations and quadruple the speed of large DELETEs.
49.3772 +**
49.3773 +** When this routine is called, set the alwaysRollback flag to true.
49.3774 +** Subsequent calls to sqlite3PagerDontRollback() for the same page
49.3775 +** will thereafter be ignored. This is necessary to avoid a problem
49.3776 +** where a page with data is added to the freelist during one part of
49.3777 +** a transaction then removed from the freelist during a later part
49.3778 +** of the same transaction and reused for some other purpose. When it
49.3779 +** is first added to the freelist, this routine is called. When reused,
49.3780 +** the sqlite3PagerDontRollback() routine is called. But because the
49.3781 +** page contains critical data, we still need to be sure it gets
49.3782 +** rolled back in spite of the sqlite3PagerDontRollback() call.
49.3783 +*/
49.3784 +void sqlite3PagerDontWrite(DbPage *pDbPage){
49.3785 + PgHdr *pPg = pDbPage;
49.3786 + Pager *pPager = pPg->pPager;
49.3787 +
49.3788 + if( MEMDB ) return;
49.3789 + pPg->alwaysRollback = 1;
49.3790 + if( pPg->dirty && !pPager->stmtInUse ){
49.3791 + assert( pPager->state>=PAGER_SHARED );
49.3792 + if( pPager->dbSize==(int)pPg->pgno && pPager->origDbSize<pPager->dbSize ){
49.3793 + /* If this pages is the last page in the file and the file has grown
49.3794 + ** during the current transaction, then do NOT mark the page as clean.
49.3795 + ** When the database file grows, we must make sure that the last page
49.3796 + ** gets written at least once so that the disk file will be the correct
49.3797 + ** size. If you do not write this page and the size of the file
49.3798 + ** on the disk ends up being too small, that can lead to database
49.3799 + ** corruption during the next transaction.
49.3800 + */
49.3801 + }else{
49.3802 + PAGERTRACE3("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager));
49.3803 + IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
49.3804 + makeClean(pPg);
49.3805 +#ifdef SQLITE_CHECK_PAGES
49.3806 + pPg->pageHash = pager_pagehash(pPg);
49.3807 +#endif
49.3808 + }
49.3809 + }
49.3810 +}
49.3811 +
49.3812 +/*
49.3813 +** A call to this routine tells the pager that if a rollback occurs,
49.3814 +** it is not necessary to restore the data on the given page. This
49.3815 +** means that the pager does not have to record the given page in the
49.3816 +** rollback journal.
49.3817 +**
49.3818 +** If we have not yet actually read the content of this page (if
49.3819 +** the PgHdr.needRead flag is set) then this routine acts as a promise
49.3820 +** that we will never need to read the page content in the future.
49.3821 +** so the needRead flag can be cleared at this point.
49.3822 +*/
49.3823 +void sqlite3PagerDontRollback(DbPage *pPg){
49.3824 + Pager *pPager = pPg->pPager;
49.3825 +
49.3826 + assert( pPager->state>=PAGER_RESERVED );
49.3827 + if( pPager->journalOpen==0 ) return;
49.3828 + if( pPg->alwaysRollback || pPager->alwaysRollback || MEMDB ) return;
49.3829 + if( !pPg->inJournal && (int)pPg->pgno <= pPager->origDbSize ){
49.3830 + assert( pPager->aInJournal!=0 );
49.3831 + pPager->aInJournal[pPg->pgno/8] |= 1<<(pPg->pgno&7);
49.3832 + pPg->inJournal = 1;
49.3833 + pPg->needRead = 0;
49.3834 + if( pPager->stmtInUse ){
49.3835 + pPager->aInStmt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
49.3836 + }
49.3837 + PAGERTRACE3("DONT_ROLLBACK page %d of %d\n", pPg->pgno, PAGERID(pPager));
49.3838 + IOTRACE(("GARBAGE %p %d\n", pPager, pPg->pgno))
49.3839 + }
49.3840 + if( pPager->stmtInUse
49.3841 + && !pageInStatement(pPg)
49.3842 + && (int)pPg->pgno<=pPager->stmtSize
49.3843 + ){
49.3844 + assert( pPg->inJournal || (int)pPg->pgno>pPager->origDbSize );
49.3845 + assert( pPager->aInStmt!=0 );
49.3846 + pPager->aInStmt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
49.3847 + }
49.3848 +}
49.3849 +
49.3850 +
49.3851 +/*
49.3852 +** This routine is called to increment the database file change-counter,
49.3853 +** stored at byte 24 of the pager file.
49.3854 +*/
49.3855 +static int pager_incr_changecounter(Pager *pPager){
49.3856 + PgHdr *pPgHdr;
49.3857 + u32 change_counter;
49.3858 + int rc;
49.3859 +
49.3860 + if( !pPager->changeCountDone ){
49.3861 + /* Open page 1 of the file for writing. */
49.3862 + rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
49.3863 + if( rc!=SQLITE_OK ) return rc;
49.3864 + rc = sqlite3PagerWrite(pPgHdr);
49.3865 + if( rc!=SQLITE_OK ) return rc;
49.3866 +
49.3867 + /* Increment the value just read and write it back to byte 24. */
49.3868 + change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
49.3869 + change_counter++;
49.3870 + put32bits(((char*)PGHDR_TO_DATA(pPgHdr))+24, change_counter);
49.3871 + /* Release the page reference. */
49.3872 + sqlite3PagerUnref(pPgHdr);
49.3873 + pPager->changeCountDone = 1;
49.3874 + }
49.3875 + return SQLITE_OK;
49.3876 +}
49.3877 +
49.3878 +/*
49.3879 +** Sync the database file for the pager pPager. zMaster points to the name
49.3880 +** of a master journal file that should be written into the individual
49.3881 +** journal file. zMaster may be NULL, which is interpreted as no master
49.3882 +** journal (a single database transaction).
49.3883 +**
49.3884 +** This routine ensures that the journal is synced, all dirty pages written
49.3885 +** to the database file and the database file synced. The only thing that
49.3886 +** remains to commit the transaction is to delete the journal file (or
49.3887 +** master journal file if specified).
49.3888 +**
49.3889 +** Note that if zMaster==NULL, this does not overwrite a previous value
49.3890 +** passed to an sqlite3PagerCommitPhaseOne() call.
49.3891 +**
49.3892 +** If parameter nTrunc is non-zero, then the pager file is truncated to
49.3893 +** nTrunc pages (this is used by auto-vacuum databases).
49.3894 +*/
49.3895 +int sqlite3PagerCommitPhaseOne(Pager *pPager, const char *zMaster, Pgno nTrunc){
49.3896 + int rc = SQLITE_OK;
49.3897 +
49.3898 + PAGERTRACE4("DATABASE SYNC: File=%s zMaster=%s nTrunc=%d\n",
49.3899 + pPager->zFilename, zMaster, nTrunc);
49.3900 +
49.3901 + /* If this is an in-memory db, or no pages have been written to, or this
49.3902 + ** function has already been called, it is a no-op.
49.3903 + */
49.3904 + if( pPager->state!=PAGER_SYNCED && !MEMDB && pPager->dirtyCache ){
49.3905 + PgHdr *pPg;
49.3906 + assert( pPager->journalOpen );
49.3907 +
49.3908 + /* If a master journal file name has already been written to the
49.3909 + ** journal file, then no sync is required. This happens when it is
49.3910 + ** written, then the process fails to upgrade from a RESERVED to an
49.3911 + ** EXCLUSIVE lock. The next time the process tries to commit the
49.3912 + ** transaction the m-j name will have already been written.
49.3913 + */
49.3914 + if( !pPager->setMaster ){
49.3915 + rc = pager_incr_changecounter(pPager);
49.3916 + if( rc!=SQLITE_OK ) goto sync_exit;
49.3917 +#ifndef SQLITE_OMIT_AUTOVACUUM
49.3918 + if( nTrunc!=0 ){
49.3919 + /* If this transaction has made the database smaller, then all pages
49.3920 + ** being discarded by the truncation must be written to the journal
49.3921 + ** file.
49.3922 + */
49.3923 + Pgno i;
49.3924 + int iSkip = PAGER_MJ_PGNO(pPager);
49.3925 + for( i=nTrunc+1; i<=pPager->origDbSize; i++ ){
49.3926 + if( !(pPager->aInJournal[i/8] & (1<<(i&7))) && i!=iSkip ){
49.3927 + rc = sqlite3PagerGet(pPager, i, &pPg);
49.3928 + if( rc!=SQLITE_OK ) goto sync_exit;
49.3929 + rc = sqlite3PagerWrite(pPg);
49.3930 + sqlite3PagerUnref(pPg);
49.3931 + if( rc!=SQLITE_OK ) goto sync_exit;
49.3932 + }
49.3933 + }
49.3934 + }
49.3935 +#endif
49.3936 + rc = writeMasterJournal(pPager, zMaster);
49.3937 + if( rc!=SQLITE_OK ) goto sync_exit;
49.3938 + rc = syncJournal(pPager);
49.3939 + if( rc!=SQLITE_OK ) goto sync_exit;
49.3940 + }
49.3941 +
49.3942 +#ifndef SQLITE_OMIT_AUTOVACUUM
49.3943 + if( nTrunc!=0 ){
49.3944 + rc = sqlite3PagerTruncate(pPager, nTrunc);
49.3945 + if( rc!=SQLITE_OK ) goto sync_exit;
49.3946 + }
49.3947 +#endif
49.3948 +
49.3949 + /* Write all dirty pages to the database file */
49.3950 + pPg = pager_get_all_dirty_pages(pPager);
49.3951 + rc = pager_write_pagelist(pPg);
49.3952 + if( rc!=SQLITE_OK ) goto sync_exit;
49.3953 + pPager->pDirty = 0;
49.3954 +
49.3955 + /* Sync the database file. */
49.3956 + if( !pPager->noSync ){
49.3957 + rc = sqlite3OsSync(pPager->fd, 0);
49.3958 + }
49.3959 + IOTRACE(("DBSYNC %p\n", pPager))
49.3960 +
49.3961 + pPager->state = PAGER_SYNCED;
49.3962 + }else if( MEMDB && nTrunc!=0 ){
49.3963 + rc = sqlite3PagerTruncate(pPager, nTrunc);
49.3964 + }
49.3965 +
49.3966 +sync_exit:
49.3967 + if( rc==SQLITE_IOERR_BLOCKED ){
49.3968 + /* pager_incr_changecounter() may attempt to obtain an exclusive
49.3969 + * lock to spill the cache and return IOERR_BLOCKED. But since
49.3970 + * there is no chance the cache is inconsistent, it's
49.3971 + * better to return SQLITE_BUSY.
49.3972 + */
49.3973 + rc = SQLITE_BUSY;
49.3974 + }
49.3975 + return rc;
49.3976 +}
49.3977 +
49.3978 +
49.3979 +/*
49.3980 +** Commit all changes to the database and release the write lock.
49.3981 +**
49.3982 +** If the commit fails for any reason, a rollback attempt is made
49.3983 +** and an error code is returned. If the commit worked, SQLITE_OK
49.3984 +** is returned.
49.3985 +*/
49.3986 +int sqlite3PagerCommitPhaseTwo(Pager *pPager){
49.3987 + int rc;
49.3988 + PgHdr *pPg;
49.3989 +
49.3990 + if( pPager->errCode ){
49.3991 + return pPager->errCode;
49.3992 + }
49.3993 + if( pPager->state<PAGER_RESERVED ){
49.3994 + return SQLITE_ERROR;
49.3995 + }
49.3996 + PAGERTRACE2("COMMIT %d\n", PAGERID(pPager));
49.3997 + if( MEMDB ){
49.3998 + pPg = pager_get_all_dirty_pages(pPager);
49.3999 + while( pPg ){
49.4000 + PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
49.4001 + clearHistory(pHist);
49.4002 + pPg->dirty = 0;
49.4003 + pPg->inJournal = 0;
49.4004 + pHist->inStmt = 0;
49.4005 + pPg->needSync = 0;
49.4006 + pHist->pPrevStmt = pHist->pNextStmt = 0;
49.4007 + pPg = pPg->pDirty;
49.4008 + }
49.4009 + pPager->pDirty = 0;
49.4010 +#ifndef NDEBUG
49.4011 + for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
49.4012 + PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
49.4013 + assert( !pPg->alwaysRollback );
49.4014 + assert( !pHist->pOrig );
49.4015 + assert( !pHist->pStmt );
49.4016 + }
49.4017 +#endif
49.4018 + pPager->pStmt = 0;
49.4019 + pPager->state = PAGER_SHARED;
49.4020 + return SQLITE_OK;
49.4021 + }
49.4022 + assert( pPager->journalOpen || !pPager->dirtyCache );
49.4023 + assert( pPager->state==PAGER_SYNCED || !pPager->dirtyCache );
49.4024 + rc = pager_end_transaction(pPager);
49.4025 + return pager_error(pPager, rc);
49.4026 +}
49.4027 +
49.4028 +/*
49.4029 +** Rollback all changes. The database falls back to PAGER_SHARED mode.
49.4030 +** All in-memory cache pages revert to their original data contents.
49.4031 +** The journal is deleted.
49.4032 +**
49.4033 +** This routine cannot fail unless some other process is not following
49.4034 +** the correct locking protocol or unless some other
49.4035 +** process is writing trash into the journal file (SQLITE_CORRUPT) or
49.4036 +** unless a prior malloc() failed (SQLITE_NOMEM). Appropriate error
49.4037 +** codes are returned for all these occasions. Otherwise,
49.4038 +** SQLITE_OK is returned.
49.4039 +*/
49.4040 +int sqlite3PagerRollback(Pager *pPager){
49.4041 + int rc;
49.4042 + PAGERTRACE2("ROLLBACK %d\n", PAGERID(pPager));
49.4043 + if( MEMDB ){
49.4044 + PgHdr *p;
49.4045 + for(p=pPager->pAll; p; p=p->pNextAll){
49.4046 + PgHistory *pHist;
49.4047 + assert( !p->alwaysRollback );
49.4048 + if( !p->dirty ){
49.4049 + assert( !((PgHistory *)PGHDR_TO_HIST(p, pPager))->pOrig );
49.4050 + assert( !((PgHistory *)PGHDR_TO_HIST(p, pPager))->pStmt );
49.4051 + continue;
49.4052 + }
49.4053 +
49.4054 + pHist = PGHDR_TO_HIST(p, pPager);
49.4055 + if( pHist->pOrig ){
49.4056 + memcpy(PGHDR_TO_DATA(p), pHist->pOrig, pPager->pageSize);
49.4057 + PAGERTRACE3("ROLLBACK-PAGE %d of %d\n", p->pgno, PAGERID(pPager));
49.4058 + }else{
49.4059 + PAGERTRACE3("PAGE %d is clean on %d\n", p->pgno, PAGERID(pPager));
49.4060 + }
49.4061 + clearHistory(pHist);
49.4062 + p->dirty = 0;
49.4063 + p->inJournal = 0;
49.4064 + pHist->inStmt = 0;
49.4065 + pHist->pPrevStmt = pHist->pNextStmt = 0;
49.4066 + if( pPager->xReiniter ){
49.4067 + pPager->xReiniter(p, pPager->pageSize);
49.4068 + }
49.4069 + }
49.4070 + pPager->pDirty = 0;
49.4071 + pPager->pStmt = 0;
49.4072 + pPager->dbSize = pPager->origDbSize;
49.4073 + pager_truncate_cache(pPager);
49.4074 + pPager->stmtInUse = 0;
49.4075 + pPager->state = PAGER_SHARED;
49.4076 + return SQLITE_OK;
49.4077 + }
49.4078 +
49.4079 + if( !pPager->dirtyCache || !pPager->journalOpen ){
49.4080 + rc = pager_end_transaction(pPager);
49.4081 + return rc;
49.4082 + }
49.4083 +
49.4084 + if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
49.4085 + if( pPager->state>=PAGER_EXCLUSIVE ){
49.4086 + pager_playback(pPager, 0);
49.4087 + }
49.4088 + return pPager->errCode;
49.4089 + }
49.4090 + if( pPager->state==PAGER_RESERVED ){
49.4091 + int rc2;
49.4092 + rc = pager_playback(pPager, 0);
49.4093 + rc2 = pager_end_transaction(pPager);
49.4094 + if( rc==SQLITE_OK ){
49.4095 + rc = rc2;
49.4096 + }
49.4097 + }else{
49.4098 + rc = pager_playback(pPager, 0);
49.4099 + }
49.4100 + /* pager_reset(pPager); */
49.4101 + pPager->dbSize = -1;
49.4102 +
49.4103 + /* If an error occurs during a ROLLBACK, we can no longer trust the pager
49.4104 + ** cache. So call pager_error() on the way out to make any error
49.4105 + ** persistent.
49.4106 + */
49.4107 + return pager_error(pPager, rc);
49.4108 +}
49.4109 +
49.4110 +/*
49.4111 +** Return TRUE if the database file is opened read-only. Return FALSE
49.4112 +** if the database is (in theory) writable.
49.4113 +*/
49.4114 +int sqlite3PagerIsreadonly(Pager *pPager){
49.4115 + return pPager->readOnly;
49.4116 +}
49.4117 +
49.4118 +/*
49.4119 +** Return the number of references to the pager.
49.4120 +*/
49.4121 +int sqlite3PagerRefcount(Pager *pPager){
49.4122 + return pPager->nRef;
49.4123 +}
49.4124 +
49.4125 +#ifdef SQLITE_TEST
49.4126 +/*
49.4127 +** This routine is used for testing and analysis only.
49.4128 +*/
49.4129 +int *sqlite3PagerStats(Pager *pPager){
49.4130 + static int a[11];
49.4131 + a[0] = pPager->nRef;
49.4132 + a[1] = pPager->nPage;
49.4133 + a[2] = pPager->mxPage;
49.4134 + a[3] = pPager->dbSize;
49.4135 + a[4] = pPager->state;
49.4136 + a[5] = pPager->errCode;
49.4137 + a[6] = pPager->nHit;
49.4138 + a[7] = pPager->nMiss;
49.4139 + a[8] = 0; /* Used to be pPager->nOvfl */
49.4140 + a[9] = pPager->nRead;
49.4141 + a[10] = pPager->nWrite;
49.4142 + return a;
49.4143 +}
49.4144 +#endif
49.4145 +
49.4146 +/*
49.4147 +** Set the statement rollback point.
49.4148 +**
49.4149 +** This routine should be called with the transaction journal already
49.4150 +** open. A new statement journal is created that can be used to rollback
49.4151 +** changes of a single SQL command within a larger transaction.
49.4152 +*/
49.4153 +int sqlite3PagerStmtBegin(Pager *pPager){
49.4154 + int rc;
49.4155 + assert( !pPager->stmtInUse );
49.4156 + assert( pPager->state>=PAGER_SHARED );
49.4157 + assert( pPager->dbSize>=0 );
49.4158 + PAGERTRACE2("STMT-BEGIN %d\n", PAGERID(pPager));
49.4159 + if( MEMDB ){
49.4160 + pPager->stmtInUse = 1;
49.4161 + pPager->stmtSize = pPager->dbSize;
49.4162 + return SQLITE_OK;
49.4163 + }
49.4164 + if( !pPager->journalOpen ){
49.4165 + pPager->stmtAutoopen = 1;
49.4166 + return SQLITE_OK;
49.4167 + }
49.4168 + assert( pPager->journalOpen );
49.4169 + pPager->aInStmt = sqliteMalloc( pPager->dbSize/8 + 1 );
49.4170 + if( pPager->aInStmt==0 ){
49.4171 + /* sqlite3OsLock(pPager->fd, SHARED_LOCK); */
49.4172 + return SQLITE_NOMEM;
49.4173 + }
49.4174 +#ifndef NDEBUG
49.4175 + rc = sqlite3OsFileSize(pPager->jfd, &pPager->stmtJSize);
49.4176 + if( rc ) goto stmt_begin_failed;
49.4177 + assert( pPager->stmtJSize == pPager->journalOff );
49.4178 +#endif
49.4179 + pPager->stmtJSize = pPager->journalOff;
49.4180 + pPager->stmtSize = pPager->dbSize;
49.4181 + pPager->stmtHdrOff = 0;
49.4182 + pPager->stmtCksum = pPager->cksumInit;
49.4183 + if( !pPager->stmtOpen ){
49.4184 + rc = sqlite3PagerOpentemp(&pPager->stfd);
49.4185 + if( rc ) goto stmt_begin_failed;
49.4186 + pPager->stmtOpen = 1;
49.4187 + pPager->stmtNRec = 0;
49.4188 + }
49.4189 + pPager->stmtInUse = 1;
49.4190 + return SQLITE_OK;
49.4191 +
49.4192 +stmt_begin_failed:
49.4193 + if( pPager->aInStmt ){
49.4194 + sqliteFree(pPager->aInStmt);
49.4195 + pPager->aInStmt = 0;
49.4196 + }
49.4197 + return rc;
49.4198 +}
49.4199 +
49.4200 +/*
49.4201 +** Commit a statement.
49.4202 +*/
49.4203 +int sqlite3PagerStmtCommit(Pager *pPager){
49.4204 + if( pPager->stmtInUse ){
49.4205 + PgHdr *pPg, *pNext;
49.4206 + PAGERTRACE2("STMT-COMMIT %d\n", PAGERID(pPager));
49.4207 + if( !MEMDB ){
49.4208 + sqlite3OsSeek(pPager->stfd, 0);
49.4209 + /* sqlite3OsTruncate(pPager->stfd, 0); */
49.4210 + sqliteFree( pPager->aInStmt );
49.4211 + pPager->aInStmt = 0;
49.4212 + }else{
49.4213 + for(pPg=pPager->pStmt; pPg; pPg=pNext){
49.4214 + PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
49.4215 + pNext = pHist->pNextStmt;
49.4216 + assert( pHist->inStmt );
49.4217 + pHist->inStmt = 0;
49.4218 + pHist->pPrevStmt = pHist->pNextStmt = 0;
49.4219 + sqliteFree(pHist->pStmt);
49.4220 + pHist->pStmt = 0;
49.4221 + }
49.4222 + }
49.4223 + pPager->stmtNRec = 0;
49.4224 + pPager->stmtInUse = 0;
49.4225 + pPager->pStmt = 0;
49.4226 + }
49.4227 + pPager->stmtAutoopen = 0;
49.4228 + return SQLITE_OK;
49.4229 +}
49.4230 +
49.4231 +/*
49.4232 +** Rollback a statement.
49.4233 +*/
49.4234 +int sqlite3PagerStmtRollback(Pager *pPager){
49.4235 + int rc;
49.4236 + if( pPager->stmtInUse ){
49.4237 + PAGERTRACE2("STMT-ROLLBACK %d\n", PAGERID(pPager));
49.4238 + if( MEMDB ){
49.4239 + PgHdr *pPg;
49.4240 + PgHistory *pHist;
49.4241 + for(pPg=pPager->pStmt; pPg; pPg=pHist->pNextStmt){
49.4242 + pHist = PGHDR_TO_HIST(pPg, pPager);
49.4243 + if( pHist->pStmt ){
49.4244 + memcpy(PGHDR_TO_DATA(pPg), pHist->pStmt, pPager->pageSize);
49.4245 + sqliteFree(pHist->pStmt);
49.4246 + pHist->pStmt = 0;
49.4247 + }
49.4248 + }
49.4249 + pPager->dbSize = pPager->stmtSize;
49.4250 + pager_truncate_cache(pPager);
49.4251 + rc = SQLITE_OK;
49.4252 + }else{
49.4253 + rc = pager_stmt_playback(pPager);
49.4254 + }
49.4255 + sqlite3PagerStmtCommit(pPager);
49.4256 + }else{
49.4257 + rc = SQLITE_OK;
49.4258 + }
49.4259 + pPager->stmtAutoopen = 0;
49.4260 + return rc;
49.4261 +}
49.4262 +
49.4263 +/*
49.4264 +** Return the full pathname of the database file.
49.4265 +*/
49.4266 +const char *sqlite3PagerFilename(Pager *pPager){
49.4267 + return pPager->zFilename;
49.4268 +}
49.4269 +
49.4270 +/*
49.4271 +** Return the directory of the database file.
49.4272 +*/
49.4273 +const char *sqlite3PagerDirname(Pager *pPager){
49.4274 + return pPager->zDirectory;
49.4275 +}
49.4276 +
49.4277 +/*
49.4278 +** Return the full pathname of the journal file.
49.4279 +*/
49.4280 +const char *sqlite3PagerJournalname(Pager *pPager){
49.4281 + return pPager->zJournal;
49.4282 +}
49.4283 +
49.4284 +/*
49.4285 +** Return true if fsync() calls are disabled for this pager. Return FALSE
49.4286 +** if fsync()s are executed normally.
49.4287 +*/
49.4288 +int sqlite3PagerNosync(Pager *pPager){
49.4289 + return pPager->noSync;
49.4290 +}
49.4291 +
49.4292 +#ifdef SQLITE_HAS_CODEC
49.4293 +/*
49.4294 +** Set the codec for this pager
49.4295 +*/
49.4296 +void sqlite3PagerSetCodec(
49.4297 + Pager *pPager,
49.4298 + void *(*xCodec)(void*,void*,Pgno,int),
49.4299 + void *pCodecArg
49.4300 +){
49.4301 + pPager->xCodec = xCodec;
49.4302 + pPager->pCodecArg = pCodecArg;
49.4303 +}
49.4304 +#endif
49.4305 +
49.4306 +#ifndef SQLITE_OMIT_AUTOVACUUM
49.4307 +/*
49.4308 +** Move the page pPg to location pgno in the file.
49.4309 +**
49.4310 +** There must be no references to the page previously located at
49.4311 +** pgno (which we call pPgOld) though that page is allowed to be
49.4312 +** in cache. If the page previous located at pgno is not already
49.4313 +** in the rollback journal, it is not put there by by this routine.
49.4314 +**
49.4315 +** References to the page pPg remain valid. Updating any
49.4316 +** meta-data associated with pPg (i.e. data stored in the nExtra bytes
49.4317 +** allocated along with the page) is the responsibility of the caller.
49.4318 +**
49.4319 +** A transaction must be active when this routine is called. It used to be
49.4320 +** required that a statement transaction was not active, but this restriction
49.4321 +** has been removed (CREATE INDEX needs to move a page when a statement
49.4322 +** transaction is active).
49.4323 +*/
49.4324 +int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno){
49.4325 + PgHdr *pPgOld; /* The page being overwritten. */
49.4326 + int h;
49.4327 + Pgno needSyncPgno = 0;
49.4328 +
49.4329 + assert( pPg->nRef>0 );
49.4330 +
49.4331 + PAGERTRACE5("MOVE %d page %d (needSync=%d) moves to %d\n",
49.4332 + PAGERID(pPager), pPg->pgno, pPg->needSync, pgno);
49.4333 + IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
49.4334 +
49.4335 + pager_get_content(pPg);
49.4336 + if( pPg->needSync ){
49.4337 + needSyncPgno = pPg->pgno;
49.4338 + assert( pPg->inJournal || (int)pgno>pPager->origDbSize );
49.4339 + assert( pPg->dirty );
49.4340 + assert( pPager->needSync );
49.4341 + }
49.4342 +
49.4343 + /* Unlink pPg from it's hash-chain */
49.4344 + unlinkHashChain(pPager, pPg);
49.4345 +
49.4346 + /* If the cache contains a page with page-number pgno, remove it
49.4347 + ** from it's hash chain. Also, if the PgHdr.needSync was set for
49.4348 + ** page pgno before the 'move' operation, it needs to be retained
49.4349 + ** for the page moved there.
49.4350 + */
49.4351 + pPg->needSync = 0;
49.4352 + pPgOld = pager_lookup(pPager, pgno);
49.4353 + if( pPgOld ){
49.4354 + assert( pPgOld->nRef==0 );
49.4355 + unlinkHashChain(pPager, pPgOld);
49.4356 + makeClean(pPgOld);
49.4357 + pPg->needSync = pPgOld->needSync;
49.4358 + }else{
49.4359 + pPg->needSync = 0;
49.4360 + }
49.4361 + if( pPager->aInJournal && (int)pgno<=pPager->origDbSize ){
49.4362 + pPg->inJournal = (pPager->aInJournal[pgno/8] & (1<<(pgno&7)))!=0;
49.4363 + }else{
49.4364 + pPg->inJournal = 0;
49.4365 + assert( pPg->needSync==0 || (int)pgno>pPager->origDbSize );
49.4366 + }
49.4367 +
49.4368 + /* Change the page number for pPg and insert it into the new hash-chain. */
49.4369 + assert( pgno!=0 );
49.4370 + pPg->pgno = pgno;
49.4371 + h = pgno & (pPager->nHash-1);
49.4372 + if( pPager->aHash[h] ){
49.4373 + assert( pPager->aHash[h]->pPrevHash==0 );
49.4374 + pPager->aHash[h]->pPrevHash = pPg;
49.4375 + }
49.4376 + pPg->pNextHash = pPager->aHash[h];
49.4377 + pPager->aHash[h] = pPg;
49.4378 + pPg->pPrevHash = 0;
49.4379 +
49.4380 + makeDirty(pPg);
49.4381 + pPager->dirtyCache = 1;
49.4382 +
49.4383 + if( needSyncPgno ){
49.4384 + /* If needSyncPgno is non-zero, then the journal file needs to be
49.4385 + ** sync()ed before any data is written to database file page needSyncPgno.
49.4386 + ** Currently, no such page exists in the page-cache and the
49.4387 + ** Pager.aInJournal bit has been set. This needs to be remedied by loading
49.4388 + ** the page into the pager-cache and setting the PgHdr.needSync flag.
49.4389 + **
49.4390 + ** The sqlite3PagerGet() call may cause the journal to sync. So make
49.4391 + ** sure the Pager.needSync flag is set too.
49.4392 + */
49.4393 + int rc;
49.4394 + PgHdr *pPgHdr;
49.4395 + assert( pPager->needSync );
49.4396 + rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
49.4397 + if( rc!=SQLITE_OK ) return rc;
49.4398 + pPager->needSync = 1;
49.4399 + pPgHdr->needSync = 1;
49.4400 + pPgHdr->inJournal = 1;
49.4401 + makeDirty(pPgHdr);
49.4402 + sqlite3PagerUnref(pPgHdr);
49.4403 + }
49.4404 +
49.4405 + return SQLITE_OK;
49.4406 +}
49.4407 +#endif
49.4408 +
49.4409 +/*
49.4410 +** Return a pointer to the data for the specified page.
49.4411 +*/
49.4412 +void *sqlite3PagerGetData(DbPage *pPg){
49.4413 + return PGHDR_TO_DATA(pPg);
49.4414 +}
49.4415 +
49.4416 +/*
49.4417 +** Return a pointer to the Pager.nExtra bytes of "extra" space
49.4418 +** allocated along with the specified page.
49.4419 +*/
49.4420 +void *sqlite3PagerGetExtra(DbPage *pPg){
49.4421 + Pager *pPager = pPg->pPager;
49.4422 + return (pPager?PGHDR_TO_EXTRA(pPg, pPager):0);
49.4423 +}
49.4424 +
49.4425 +/*
49.4426 +** Get/set the locking-mode for this pager. Parameter eMode must be one
49.4427 +** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
49.4428 +** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
49.4429 +** the locking-mode is set to the value specified.
49.4430 +**
49.4431 +** The returned value is either PAGER_LOCKINGMODE_NORMAL or
49.4432 +** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
49.4433 +** locking-mode.
49.4434 +*/
49.4435 +int sqlite3PagerLockingMode(Pager *pPager, int eMode){
49.4436 + assert( eMode==PAGER_LOCKINGMODE_QUERY
49.4437 + || eMode==PAGER_LOCKINGMODE_NORMAL
49.4438 + || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
49.4439 + assert( PAGER_LOCKINGMODE_QUERY<0 );
49.4440 + assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
49.4441 + if( eMode>=0 && !pPager->tempFile ){
49.4442 + pPager->exclusiveMode = eMode;
49.4443 + }
49.4444 + return (int)pPager->exclusiveMode;
49.4445 +}
49.4446 +
49.4447 +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
49.4448 +/*
49.4449 +** Return the current state of the file lock for the given pager.
49.4450 +** The return value is one of NO_LOCK, SHARED_LOCK, RESERVED_LOCK,
49.4451 +** PENDING_LOCK, or EXCLUSIVE_LOCK.
49.4452 +*/
49.4453 +int sqlite3PagerLockstate(Pager *pPager){
49.4454 + return sqlite3OsLockState(pPager->fd);
49.4455 +}
49.4456 +#endif
49.4457 +
49.4458 +#ifdef SQLITE_DEBUG
49.4459 +/*
49.4460 +** Print a listing of all referenced pages and their ref count.
49.4461 +*/
49.4462 +void sqlite3PagerRefdump(Pager *pPager){
49.4463 + PgHdr *pPg;
49.4464 + for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
49.4465 + if( pPg->nRef<=0 ) continue;
49.4466 + sqlite3DebugPrintf("PAGE %3d addr=%p nRef=%d\n",
49.4467 + pPg->pgno, PGHDR_TO_DATA(pPg), pPg->nRef);
49.4468 + }
49.4469 +}
49.4470 +#endif
49.4471 +
49.4472 +#endif /* SQLITE_OMIT_DISKIO */
50.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
50.2 +++ b/extensions/sqlite/sqlite-source/pager.h Sun Jul 29 01:15:31 2007 +0000
50.3 @@ -0,0 +1,128 @@
50.4 +/*
50.5 +** 2001 September 15
50.6 +**
50.7 +** The author disclaims copyright to this source code. In place of
50.8 +** a legal notice, here is a blessing:
50.9 +**
50.10 +** May you do good and not evil.
50.11 +** May you find forgiveness for yourself and forgive others.
50.12 +** May you share freely, never taking more than you give.
50.13 +**
50.14 +*************************************************************************
50.15 +** This header file defines the interface that the sqlite page cache
50.16 +** subsystem. The page cache subsystem reads and writes a file a page
50.17 +** at a time and provides a journal for rollback.
50.18 +**
50.19 +** @(#) $Id$
50.20 +*/
50.21 +
50.22 +#ifndef _PAGER_H_
50.23 +#define _PAGER_H_
50.24 +
50.25 +/*
50.26 +** The type used to represent a page number. The first page in a file
50.27 +** is called page 1. 0 is used to represent "not a page".
50.28 +*/
50.29 +typedef unsigned int Pgno;
50.30 +
50.31 +/*
50.32 +** Each open file is managed by a separate instance of the "Pager" structure.
50.33 +*/
50.34 +typedef struct Pager Pager;
50.35 +
50.36 +/*
50.37 +** Handle type for pages.
50.38 +*/
50.39 +typedef struct PgHdr DbPage;
50.40 +
50.41 +/*
50.42 +** Allowed values for the flags parameter to sqlite3PagerOpen().
50.43 +**
50.44 +** NOTE: This values must match the corresponding BTREE_ values in btree.h.
50.45 +*/
50.46 +#define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
50.47 +#define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */
50.48 +
50.49 +/*
50.50 +** Valid values for the second argument to sqlite3PagerLockingMode().
50.51 +*/
50.52 +#define PAGER_LOCKINGMODE_QUERY -1
50.53 +#define PAGER_LOCKINGMODE_NORMAL 0
50.54 +#define PAGER_LOCKINGMODE_EXCLUSIVE 1
50.55 +
50.56 +/*
50.57 +** See source code comments for a detailed description of the following
50.58 +** routines:
50.59 +*/
50.60 +int sqlite3PagerOpen(Pager **ppPager, const char *zFilename,
50.61 + int nExtra, int flags);
50.62 +void sqlite3PagerSetBusyhandler(Pager*, BusyHandler *pBusyHandler);
50.63 +void sqlite3PagerSetDestructor(Pager*, void(*)(DbPage*,int));
50.64 +void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*,int));
50.65 +int sqlite3PagerSetPagesize(Pager*, int);
50.66 +int sqlite3PagerMaxPageCount(Pager*, int);
50.67 +int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
50.68 +void sqlite3PagerSetCachesize(Pager*, int);
50.69 +int sqlite3PagerClose(Pager *pPager);
50.70 +int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
50.71 +#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
50.72 +DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
50.73 +int sqlite3PagerRef(DbPage*);
50.74 +int sqlite3PagerUnref(DbPage*);
50.75 +int sqlite3PagerWrite(DbPage*);
50.76 +int sqlite3PagerOverwrite(Pager *pPager, Pgno pgno, void*);
50.77 +int sqlite3PagerPagecount(Pager*);
50.78 +int sqlite3PagerTruncate(Pager*,Pgno);
50.79 +int sqlite3PagerBegin(DbPage*, int exFlag);
50.80 +int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, Pgno);
50.81 +int sqlite3PagerCommitPhaseTwo(Pager*);
50.82 +int sqlite3PagerRollback(Pager*);
50.83 +int sqlite3PagerIsreadonly(Pager*);
50.84 +int sqlite3PagerStmtBegin(Pager*);
50.85 +int sqlite3PagerStmtCommit(Pager*);
50.86 +int sqlite3PagerStmtRollback(Pager*);
50.87 +void sqlite3PagerDontRollback(DbPage*);
50.88 +void sqlite3PagerDontWrite(DbPage*);
50.89 +int sqlite3PagerRefcount(Pager*);
50.90 +void sqlite3PagerSetSafetyLevel(Pager*,int,int);
50.91 +const char *sqlite3PagerFilename(Pager*);
50.92 +const char *sqlite3PagerDirname(Pager*);
50.93 +const char *sqlite3PagerJournalname(Pager*);
50.94 +int sqlite3PagerNosync(Pager*);
50.95 +int sqlite3PagerMovepage(Pager*,DbPage*,Pgno);
50.96 +void *sqlite3PagerGetData(DbPage *);
50.97 +void *sqlite3PagerGetExtra(DbPage *);
50.98 +int sqlite3PagerLockingMode(Pager *, int);
50.99 +
50.100 +#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO)
50.101 + int sqlite3PagerReleaseMemory(int);
50.102 +#endif
50.103 +
50.104 +#ifdef SQLITE_HAS_CODEC
50.105 + void sqlite3PagerSetCodec(Pager*,void*(*)(void*,void*,Pgno,int),void*);
50.106 +#endif
50.107 +
50.108 +#if !defined(NDEBUG) || defined(SQLITE_TEST)
50.109 + Pgno sqlite3PagerPagenumber(DbPage*);
50.110 + int sqlite3PagerIswriteable(DbPage*);
50.111 +#endif
50.112 +
50.113 +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
50.114 + int sqlite3PagerLockstate(Pager*);
50.115 +#endif
50.116 +
50.117 +#ifdef SQLITE_TEST
50.118 + int *sqlite3PagerStats(Pager*);
50.119 + void sqlite3PagerRefdump(Pager*);
50.120 + int pager3_refinfo_enable;
50.121 +#endif
50.122 +
50.123 +#ifdef SQLITE_TEST
50.124 +void disable_simulated_io_errors(void);
50.125 +void enable_simulated_io_errors(void);
50.126 +#else
50.127 +# define disable_simulated_io_errors()
50.128 +# define enable_simulated_io_errors()
50.129 +#endif
50.130 +
50.131 +#endif /* _PAGER_H_ */
51.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
51.2 +++ b/extensions/sqlite/sqlite-source/parse.c Sun Jul 29 01:15:31 2007 +0000
51.3 @@ -0,0 +1,3503 @@
51.4 +/* Driver template for the LEMON parser generator.
51.5 +** The author disclaims copyright to this source code.
51.6 +*/
51.7 +/* First off, code is include which follows the "include" declaration
51.8 +** in the input file. */
51.9 +#include <stdio.h>
51.10 +#line 56 "parse.y"
51.11 +
51.12 +#include "sqliteInt.h"
51.13 +#include "parse.h"
51.14 +
51.15 +/*
51.16 +** An instance of this structure holds information about the
51.17 +** LIMIT clause of a SELECT statement.
51.18 +*/
51.19 +struct LimitVal {
51.20 + Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
51.21 + Expr *pOffset; /* The OFFSET expression. NULL if there is none */
51.22 +};
51.23 +
51.24 +/*
51.25 +** An instance of this structure is used to store the LIKE,
51.26 +** GLOB, NOT LIKE, and NOT GLOB operators.
51.27 +*/
51.28 +struct LikeOp {
51.29 + Token eOperator; /* "like" or "glob" or "regexp" */
51.30 + int not; /* True if the NOT keyword is present */
51.31 +};
51.32 +
51.33 +/*
51.34 +** An instance of the following structure describes the event of a
51.35 +** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
51.36 +** TK_DELETE, or TK_INSTEAD. If the event is of the form
51.37 +**
51.38 +** UPDATE ON (a,b,c)
51.39 +**
51.40 +** Then the "b" IdList records the list "a,b,c".
51.41 +*/
51.42 +struct TrigEvent { int a; IdList * b; };
51.43 +
51.44 +/*
51.45 +** An instance of this structure holds the ATTACH key and the key type.
51.46 +*/
51.47 +struct AttachKey { int type; Token key; };
51.48 +
51.49 +#line 48 "parse.c"
51.50 +/* Next is all token values, in a form suitable for use by makeheaders.
51.51 +** This section will be null unless lemon is run with the -m switch.
51.52 +*/
51.53 +/*
51.54 +** These constants (all generated automatically by the parser generator)
51.55 +** specify the various kinds of tokens (terminals) that the parser
51.56 +** understands.
51.57 +**
51.58 +** Each symbol here is a terminal symbol in the grammar.
51.59 +*/
51.60 +/* Make sure the INTERFACE macro is defined.
51.61 +*/
51.62 +#ifndef INTERFACE
51.63 +# define INTERFACE 1
51.64 +#endif
51.65 +/* The next thing included is series of defines which control
51.66 +** various aspects of the generated parser.
51.67 +** YYCODETYPE is the data type used for storing terminal
51.68 +** and nonterminal numbers. "unsigned char" is
51.69 +** used if there are fewer than 250 terminals
51.70 +** and nonterminals. "int" is used otherwise.
51.71 +** YYNOCODE is a number of type YYCODETYPE which corresponds
51.72 +** to no legal terminal or nonterminal number. This
51.73 +** number is used to fill in empty slots of the hash
51.74 +** table.
51.75 +** YYFALLBACK If defined, this indicates that one or more tokens
51.76 +** have fall-back values which should be used if the
51.77 +** original value of the token will not parse.
51.78 +** YYACTIONTYPE is the data type used for storing terminal
51.79 +** and nonterminal numbers. "unsigned char" is
51.80 +** used if there are fewer than 250 rules and
51.81 +** states combined. "int" is used otherwise.
51.82 +** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
51.83 +** directly to the parser from the tokenizer.
51.84 +** YYMINORTYPE is the data type used for all minor tokens.
51.85 +** This is typically a union of many types, one of
51.86 +** which is sqlite3ParserTOKENTYPE. The entry in the union
51.87 +** for base tokens is called "yy0".
51.88 +** YYSTACKDEPTH is the maximum depth of the parser's stack. If
51.89 +** zero the stack is dynamically sized using realloc()
51.90 +** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
51.91 +** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
51.92 +** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
51.93 +** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
51.94 +** YYNSTATE the combined number of states.
51.95 +** YYNRULE the number of rules in the grammar
51.96 +** YYERRORSYMBOL is the code number of the error symbol. If not
51.97 +** defined, then do no error processing.
51.98 +*/
51.99 +#define YYCODETYPE unsigned char
51.100 +#define YYNOCODE 248
51.101 +#define YYACTIONTYPE unsigned short int
51.102 +#define YYWILDCARD 59
51.103 +#define sqlite3ParserTOKENTYPE Token
51.104 +typedef union {
51.105 + sqlite3ParserTOKENTYPE yy0;
51.106 + int yy46;
51.107 + struct LikeOp yy72;
51.108 + Expr* yy172;
51.109 + ExprList* yy174;
51.110 + Select* yy219;
51.111 + struct LimitVal yy234;
51.112 + TriggerStep* yy243;
51.113 + struct TrigEvent yy370;
51.114 + SrcList* yy373;
51.115 + Expr * yy386;
51.116 + struct {int value; int mask;} yy405;
51.117 + Token yy410;
51.118 + IdList* yy432;
51.119 + int yy495;
51.120 +} YYMINORTYPE;
51.121 +#ifndef YYSTACKDEPTH
51.122 +#define YYSTACKDEPTH 100
51.123 +#endif
51.124 +#define sqlite3ParserARG_SDECL Parse *pParse;
51.125 +#define sqlite3ParserARG_PDECL ,Parse *pParse
51.126 +#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
51.127 +#define sqlite3ParserARG_STORE yypParser->pParse = pParse
51.128 +#define YYNSTATE 586
51.129 +#define YYNRULE 311
51.130 +#define YYERRORSYMBOL 138
51.131 +#define YYERRSYMDT yy495
51.132 +#define YYFALLBACK 1
51.133 +#define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
51.134 +#define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
51.135 +#define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
51.136 +
51.137 +/* Next are that tables used to determine what action to take based on the
51.138 +** current state and lookahead token. These tables are used to implement
51.139 +** functions that take a state number and lookahead value and return an
51.140 +** action integer.
51.141 +**
51.142 +** Suppose the action integer is N. Then the action is determined as
51.143 +** follows
51.144 +**
51.145 +** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
51.146 +** token onto the stack and goto state N.
51.147 +**
51.148 +** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
51.149 +**
51.150 +** N == YYNSTATE+YYNRULE A syntax error has occurred.
51.151 +**
51.152 +** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
51.153 +**
51.154 +** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
51.155 +** slots in the yy_action[] table.
51.156 +**
51.157 +** The action table is constructed as a single large table named yy_action[].
51.158 +** Given state S and lookahead X, the action is computed as
51.159 +**
51.160 +** yy_action[ yy_shift_ofst[S] + X ]
51.161 +**
51.162 +** If the index value yy_shift_ofst[S]+X is out of range or if the value
51.163 +** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
51.164 +** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
51.165 +** and that yy_default[S] should be used instead.
51.166 +**
51.167 +** The formula above is for computing the action when the lookahead is
51.168 +** a terminal symbol. If the lookahead is a non-terminal (as occurs after
51.169 +** a reduce action) then the yy_reduce_ofst[] array is used in place of
51.170 +** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
51.171 +** YY_SHIFT_USE_DFLT.
51.172 +**
51.173 +** The following are the tables generated in this section:
51.174 +**
51.175 +** yy_action[] A single table containing all actions.
51.176 +** yy_lookahead[] A table containing the lookahead for each entry in
51.177 +** yy_action. Used to detect hash collisions.
51.178 +** yy_shift_ofst[] For each state, the offset into yy_action for
51.179 +** shifting terminals.
51.180 +** yy_reduce_ofst[] For each state, the offset into yy_action for
51.181 +** shifting non-terminals after a reduce.
51.182 +** yy_default[] Default action for each state.
51.183 +*/
51.184 +static const YYACTIONTYPE yy_action[] = {
51.185 + /* 0 */ 290, 898, 122, 585, 407, 170, 2, 437, 61, 61,
51.186 + /* 10 */ 61, 61, 517, 63, 63, 63, 63, 64, 64, 65,
51.187 + /* 20 */ 65, 65, 66, 231, 445, 209, 422, 428, 68, 63,
51.188 + /* 30 */ 63, 63, 63, 64, 64, 65, 65, 65, 66, 231,
51.189 + /* 40 */ 389, 386, 394, 449, 60, 59, 295, 432, 433, 429,
51.190 + /* 50 */ 429, 62, 62, 61, 61, 61, 61, 261, 63, 63,
51.191 + /* 60 */ 63, 63, 64, 64, 65, 65, 65, 66, 231, 290,
51.192 + /* 70 */ 491, 492, 437, 487, 206, 81, 67, 417, 69, 152,
51.193 + /* 80 */ 63, 63, 63, 63, 64, 64, 65, 65, 65, 66,
51.194 + /* 90 */ 231, 67, 460, 69, 152, 422, 428, 571, 262, 58,
51.195 + /* 100 */ 64, 64, 65, 65, 65, 66, 231, 395, 396, 419,
51.196 + /* 110 */ 419, 419, 290, 60, 59, 295, 432, 433, 429, 429,
51.197 + /* 120 */ 62, 62, 61, 61, 61, 61, 315, 63, 63, 63,
51.198 + /* 130 */ 63, 64, 64, 65, 65, 65, 66, 231, 422, 428,
51.199 + /* 140 */ 93, 65, 65, 65, 66, 231, 394, 231, 412, 34,
51.200 + /* 150 */ 56, 296, 440, 441, 408, 486, 60, 59, 295, 432,
51.201 + /* 160 */ 433, 429, 429, 62, 62, 61, 61, 61, 61, 488,
51.202 + /* 170 */ 63, 63, 63, 63, 64, 64, 65, 65, 65, 66,
51.203 + /* 180 */ 231, 290, 255, 522, 293, 569, 112, 406, 520, 449,
51.204 + /* 190 */ 329, 315, 405, 20, 437, 338, 517, 394, 530, 529,
51.205 + /* 200 */ 503, 445, 209, 568, 567, 206, 528, 422, 428, 147,
51.206 + /* 210 */ 148, 395, 396, 412, 41, 208, 149, 531, 370, 487,
51.207 + /* 220 */ 259, 566, 257, 417, 290, 60, 59, 295, 432, 433,
51.208 + /* 230 */ 429, 429, 62, 62, 61, 61, 61, 61, 315, 63,
51.209 + /* 240 */ 63, 63, 63, 64, 64, 65, 65, 65, 66, 231,
51.210 + /* 250 */ 422, 428, 445, 331, 212, 419, 419, 419, 361, 437,
51.211 + /* 260 */ 412, 41, 395, 396, 364, 565, 208, 290, 60, 59,
51.212 + /* 270 */ 295, 432, 433, 429, 429, 62, 62, 61, 61, 61,
51.213 + /* 280 */ 61, 394, 63, 63, 63, 63, 64, 64, 65, 65,
51.214 + /* 290 */ 65, 66, 231, 422, 428, 489, 298, 522, 472, 66,
51.215 + /* 300 */ 231, 211, 472, 224, 409, 284, 532, 20, 447, 521,
51.216 + /* 310 */ 166, 60, 59, 295, 432, 433, 429, 429, 62, 62,
51.217 + /* 320 */ 61, 61, 61, 61, 472, 63, 63, 63, 63, 64,
51.218 + /* 330 */ 64, 65, 65, 65, 66, 231, 207, 478, 315, 76,
51.219 + /* 340 */ 290, 235, 298, 55, 482, 225, 395, 396, 179, 545,
51.220 + /* 350 */ 492, 343, 346, 347, 67, 150, 69, 152, 337, 522,
51.221 + /* 360 */ 412, 35, 348, 237, 249, 368, 422, 428, 576, 20,
51.222 + /* 370 */ 162, 116, 239, 341, 244, 342, 174, 320, 440, 441,
51.223 + /* 380 */ 412, 3, 79, 250, 60, 59, 295, 432, 433, 429,
51.224 + /* 390 */ 429, 62, 62, 61, 61, 61, 61, 172, 63, 63,
51.225 + /* 400 */ 63, 63, 64, 64, 65, 65, 65, 66, 231, 290,
51.226 + /* 410 */ 249, 548, 232, 485, 508, 351, 315, 116, 239, 341,
51.227 + /* 420 */ 244, 342, 174, 179, 315, 523, 343, 346, 347, 250,
51.228 + /* 430 */ 218, 413, 153, 462, 509, 422, 428, 348, 412, 34,
51.229 + /* 440 */ 463, 208, 175, 173, 158, 233, 412, 34, 336, 547,
51.230 + /* 450 */ 447, 321, 166, 60, 59, 295, 432, 433, 429, 429,
51.231 + /* 460 */ 62, 62, 61, 61, 61, 61, 413, 63, 63, 63,
51.232 + /* 470 */ 63, 64, 64, 65, 65, 65, 66, 231, 290, 540,
51.233 + /* 480 */ 333, 515, 502, 539, 454, 569, 300, 19, 329, 142,
51.234 + /* 490 */ 315, 388, 315, 328, 2, 360, 455, 292, 481, 371,
51.235 + /* 500 */ 267, 266, 250, 568, 422, 428, 586, 389, 386, 456,
51.236 + /* 510 */ 206, 493, 412, 49, 412, 49, 301, 583, 889, 157,
51.237 + /* 520 */ 889, 494, 60, 59, 295, 432, 433, 429, 429, 62,
51.238 + /* 530 */ 62, 61, 61, 61, 61, 199, 63, 63, 63, 63,
51.239 + /* 540 */ 64, 64, 65, 65, 65, 66, 231, 290, 315, 179,
51.240 + /* 550 */ 436, 253, 343, 346, 347, 368, 151, 580, 306, 248,
51.241 + /* 560 */ 307, 450, 75, 348, 77, 380, 208, 423, 424, 413,
51.242 + /* 570 */ 412, 27, 317, 422, 428, 438, 1, 22, 583, 888,
51.243 + /* 580 */ 394, 888, 542, 476, 318, 261, 435, 435, 426, 427,
51.244 + /* 590 */ 413, 60, 59, 295, 432, 433, 429, 429, 62, 62,
51.245 + /* 600 */ 61, 61, 61, 61, 326, 63, 63, 63, 63, 64,
51.246 + /* 610 */ 64, 65, 65, 65, 66, 231, 290, 425, 580, 372,
51.247 + /* 620 */ 219, 92, 515, 9, 334, 394, 555, 394, 454, 67,
51.248 + /* 630 */ 394, 69, 152, 397, 398, 399, 318, 234, 435, 435,
51.249 + /* 640 */ 455, 316, 422, 428, 297, 395, 396, 318, 430, 435,
51.250 + /* 650 */ 435, 579, 289, 456, 220, 325, 5, 217, 544, 290,
51.251 + /* 660 */ 60, 59, 295, 432, 433, 429, 429, 62, 62, 61,
51.252 + /* 670 */ 61, 61, 61, 393, 63, 63, 63, 63, 64, 64,
51.253 + /* 680 */ 65, 65, 65, 66, 231, 422, 428, 480, 311, 390,
51.254 + /* 690 */ 395, 396, 395, 396, 205, 395, 396, 821, 271, 515,
51.255 + /* 700 */ 248, 198, 290, 60, 59, 295, 432, 433, 429, 429,
51.256 + /* 710 */ 62, 62, 61, 61, 61, 61, 468, 63, 63, 63,
51.257 + /* 720 */ 63, 64, 64, 65, 65, 65, 66, 231, 422, 428,
51.258 + /* 730 */ 169, 158, 261, 261, 302, 413, 274, 117, 272, 261,
51.259 + /* 740 */ 515, 515, 261, 515, 190, 290, 60, 70, 295, 432,
51.260 + /* 750 */ 433, 429, 429, 62, 62, 61, 61, 61, 61, 377,
51.261 + /* 760 */ 63, 63, 63, 63, 64, 64, 65, 65, 65, 66,
51.262 + /* 770 */ 231, 422, 428, 382, 557, 303, 304, 248, 413, 318,
51.263 + /* 780 */ 558, 435, 435, 559, 538, 358, 538, 385, 290, 194,
51.264 + /* 790 */ 59, 295, 432, 433, 429, 429, 62, 62, 61, 61,
51.265 + /* 800 */ 61, 61, 369, 63, 63, 63, 63, 64, 64, 65,
51.266 + /* 810 */ 65, 65, 66, 231, 422, 428, 394, 273, 248, 248,
51.267 + /* 820 */ 170, 246, 437, 413, 384, 365, 176, 177, 178, 467,
51.268 + /* 830 */ 309, 121, 154, 126, 295, 432, 433, 429, 429, 62,
51.269 + /* 840 */ 62, 61, 61, 61, 61, 315, 63, 63, 63, 63,
51.270 + /* 850 */ 64, 64, 65, 65, 65, 66, 231, 72, 322, 175,
51.271 + /* 860 */ 4, 315, 261, 315, 294, 261, 413, 412, 28, 315,
51.272 + /* 870 */ 261, 315, 319, 72, 322, 315, 4, 418, 443, 443,
51.273 + /* 880 */ 294, 395, 396, 412, 23, 412, 32, 437, 319, 324,
51.274 + /* 890 */ 327, 412, 53, 412, 52, 315, 156, 412, 97, 449,
51.275 + /* 900 */ 315, 192, 315, 275, 315, 324, 376, 469, 500, 315,
51.276 + /* 910 */ 476, 277, 476, 163, 292, 449, 315, 412, 95, 74,
51.277 + /* 920 */ 73, 467, 412, 100, 412, 101, 412, 111, 72, 313,
51.278 + /* 930 */ 314, 412, 113, 417, 446, 74, 73, 479, 412, 16,
51.279 + /* 940 */ 379, 315, 181, 465, 72, 313, 314, 72, 322, 417,
51.280 + /* 950 */ 4, 206, 315, 184, 294, 315, 497, 498, 474, 206,
51.281 + /* 960 */ 171, 339, 319, 412, 98, 419, 419, 419, 420, 421,
51.282 + /* 970 */ 11, 359, 378, 305, 412, 33, 413, 412, 96, 324,
51.283 + /* 980 */ 458, 419, 419, 419, 420, 421, 11, 413, 411, 449,
51.284 + /* 990 */ 411, 160, 410, 315, 410, 466, 221, 222, 223, 103,
51.285 + /* 1000 */ 83, 471, 315, 507, 506, 315, 620, 475, 315, 74,
51.286 + /* 1010 */ 73, 245, 203, 21, 279, 412, 24, 437, 72, 313,
51.287 + /* 1020 */ 314, 280, 315, 417, 412, 54, 505, 412, 114, 315,
51.288 + /* 1030 */ 412, 115, 504, 201, 145, 547, 240, 510, 524, 200,
51.289 + /* 1040 */ 315, 511, 202, 315, 412, 25, 315, 241, 315, 18,
51.290 + /* 1050 */ 315, 412, 36, 315, 254, 419, 419, 419, 420, 421,
51.291 + /* 1060 */ 11, 256, 412, 37, 258, 412, 26, 315, 412, 38,
51.292 + /* 1070 */ 412, 39, 412, 40, 260, 412, 42, 315, 512, 315,
51.293 + /* 1080 */ 126, 315, 437, 315, 187, 375, 276, 266, 265, 412,
51.294 + /* 1090 */ 43, 291, 315, 252, 315, 126, 206, 581, 8, 412,
51.295 + /* 1100 */ 44, 412, 29, 412, 30, 412, 45, 350, 363, 126,
51.296 + /* 1110 */ 315, 543, 315, 126, 412, 46, 412, 47, 315, 355,
51.297 + /* 1120 */ 381, 551, 315, 171, 552, 315, 90, 562, 578, 90,
51.298 + /* 1130 */ 288, 366, 412, 48, 412, 31, 582, 367, 268, 269,
51.299 + /* 1140 */ 412, 10, 270, 554, 412, 50, 564, 412, 51, 278,
51.300 + /* 1150 */ 281, 282, 575, 144, 442, 403, 323, 226, 444, 461,
51.301 + /* 1160 */ 464, 242, 503, 550, 561, 513, 161, 392, 400, 516,
51.302 + /* 1170 */ 401, 345, 402, 7, 312, 83, 227, 332, 228, 82,
51.303 + /* 1180 */ 330, 57, 408, 416, 168, 78, 459, 123, 210, 414,
51.304 + /* 1190 */ 84, 335, 340, 299, 496, 500, 490, 229, 495, 243,
51.305 + /* 1200 */ 104, 247, 499, 501, 230, 285, 415, 215, 514, 518,
51.306 + /* 1210 */ 525, 526, 519, 236, 527, 473, 238, 352, 477, 286,
51.307 + /* 1220 */ 182, 356, 533, 354, 119, 183, 185, 87, 546, 130,
51.308 + /* 1230 */ 186, 535, 188, 140, 362, 191, 553, 216, 373, 374,
51.309 + /* 1240 */ 131, 560, 308, 132, 133, 572, 577, 136, 263, 134,
51.310 + /* 1250 */ 139, 536, 573, 391, 91, 94, 404, 574, 99, 214,
51.311 + /* 1260 */ 102, 621, 622, 431, 164, 434, 165, 71, 141, 17,
51.312 + /* 1270 */ 439, 448, 451, 155, 6, 452, 470, 110, 167, 453,
51.313 + /* 1280 */ 457, 124, 13, 213, 120, 80, 12, 125, 159, 483,
51.314 + /* 1290 */ 484, 85, 310, 105, 180, 251, 106, 118, 86, 107,
51.315 + /* 1300 */ 241, 344, 349, 353, 143, 534, 127, 357, 171, 189,
51.316 + /* 1310 */ 264, 108, 287, 128, 549, 129, 193, 537, 541, 14,
51.317 + /* 1320 */ 195, 88, 196, 556, 197, 137, 138, 135, 15, 563,
51.318 + /* 1330 */ 570, 109, 283, 146, 204, 383, 387, 899, 584, 899,
51.319 + /* 1340 */ 899, 899, 899, 899, 89,
51.320 +};
51.321 +static const YYCODETYPE yy_lookahead[] = {
51.322 + /* 0 */ 16, 139, 140, 141, 168, 21, 144, 23, 69, 70,
51.323 + /* 10 */ 71, 72, 176, 74, 75, 76, 77, 78, 79, 80,
51.324 + /* 20 */ 81, 82, 83, 84, 78, 79, 42, 43, 73, 74,
51.325 + /* 30 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
51.326 + /* 40 */ 1, 2, 23, 58, 60, 61, 62, 63, 64, 65,
51.327 + /* 50 */ 66, 67, 68, 69, 70, 71, 72, 147, 74, 75,
51.328 + /* 60 */ 76, 77, 78, 79, 80, 81, 82, 83, 84, 16,
51.329 + /* 70 */ 185, 186, 88, 88, 110, 22, 217, 92, 219, 220,
51.330 + /* 80 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
51.331 + /* 90 */ 84, 217, 218, 219, 220, 42, 43, 238, 188, 46,
51.332 + /* 100 */ 78, 79, 80, 81, 82, 83, 84, 88, 89, 124,
51.333 + /* 110 */ 125, 126, 16, 60, 61, 62, 63, 64, 65, 66,
51.334 + /* 120 */ 67, 68, 69, 70, 71, 72, 147, 74, 75, 76,
51.335 + /* 130 */ 77, 78, 79, 80, 81, 82, 83, 84, 42, 43,
51.336 + /* 140 */ 44, 80, 81, 82, 83, 84, 23, 84, 169, 170,
51.337 + /* 150 */ 19, 164, 165, 166, 23, 169, 60, 61, 62, 63,
51.338 + /* 160 */ 64, 65, 66, 67, 68, 69, 70, 71, 72, 169,
51.339 + /* 170 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
51.340 + /* 180 */ 84, 16, 14, 147, 150, 147, 21, 167, 168, 58,
51.341 + /* 190 */ 211, 147, 156, 157, 23, 216, 176, 23, 181, 176,
51.342 + /* 200 */ 177, 78, 79, 165, 166, 110, 183, 42, 43, 78,
51.343 + /* 210 */ 79, 88, 89, 169, 170, 228, 180, 181, 123, 88,
51.344 + /* 220 */ 52, 98, 54, 92, 16, 60, 61, 62, 63, 64,
51.345 + /* 230 */ 65, 66, 67, 68, 69, 70, 71, 72, 147, 74,
51.346 + /* 240 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
51.347 + /* 250 */ 42, 43, 78, 209, 210, 124, 125, 126, 224, 88,
51.348 + /* 260 */ 169, 170, 88, 89, 230, 227, 228, 16, 60, 61,
51.349 + /* 270 */ 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
51.350 + /* 280 */ 72, 23, 74, 75, 76, 77, 78, 79, 80, 81,
51.351 + /* 290 */ 82, 83, 84, 42, 43, 160, 16, 147, 161, 83,
51.352 + /* 300 */ 84, 210, 161, 153, 169, 158, 156, 157, 161, 162,
51.353 + /* 310 */ 163, 60, 61, 62, 63, 64, 65, 66, 67, 68,
51.354 + /* 320 */ 69, 70, 71, 72, 161, 74, 75, 76, 77, 78,
51.355 + /* 330 */ 79, 80, 81, 82, 83, 84, 192, 200, 147, 131,
51.356 + /* 340 */ 16, 200, 16, 199, 20, 190, 88, 89, 90, 185,
51.357 + /* 350 */ 186, 93, 94, 95, 217, 22, 219, 220, 147, 147,
51.358 + /* 360 */ 169, 170, 104, 200, 84, 147, 42, 43, 156, 157,
51.359 + /* 370 */ 90, 91, 92, 93, 94, 95, 96, 164, 165, 166,
51.360 + /* 380 */ 169, 170, 131, 103, 60, 61, 62, 63, 64, 65,
51.361 + /* 390 */ 66, 67, 68, 69, 70, 71, 72, 155, 74, 75,
51.362 + /* 400 */ 76, 77, 78, 79, 80, 81, 82, 83, 84, 16,
51.363 + /* 410 */ 84, 11, 221, 20, 30, 16, 147, 91, 92, 93,
51.364 + /* 420 */ 94, 95, 96, 90, 147, 181, 93, 94, 95, 103,
51.365 + /* 430 */ 212, 189, 155, 27, 50, 42, 43, 104, 169, 170,
51.366 + /* 440 */ 34, 228, 43, 201, 202, 147, 169, 170, 206, 49,
51.367 + /* 450 */ 161, 162, 163, 60, 61, 62, 63, 64, 65, 66,
51.368 + /* 460 */ 67, 68, 69, 70, 71, 72, 189, 74, 75, 76,
51.369 + /* 470 */ 77, 78, 79, 80, 81, 82, 83, 84, 16, 25,
51.370 + /* 480 */ 211, 147, 20, 29, 12, 147, 102, 19, 211, 21,
51.371 + /* 490 */ 147, 141, 147, 216, 144, 41, 24, 98, 20, 99,
51.372 + /* 500 */ 100, 101, 103, 165, 42, 43, 0, 1, 2, 37,
51.373 + /* 510 */ 110, 39, 169, 170, 169, 170, 182, 19, 20, 147,
51.374 + /* 520 */ 22, 49, 60, 61, 62, 63, 64, 65, 66, 67,
51.375 + /* 530 */ 68, 69, 70, 71, 72, 155, 74, 75, 76, 77,
51.376 + /* 540 */ 78, 79, 80, 81, 82, 83, 84, 16, 147, 90,
51.377 + /* 550 */ 20, 20, 93, 94, 95, 147, 155, 59, 215, 225,
51.378 + /* 560 */ 215, 20, 130, 104, 132, 227, 228, 42, 43, 189,
51.379 + /* 570 */ 169, 170, 16, 42, 43, 20, 19, 22, 19, 20,
51.380 + /* 580 */ 23, 22, 18, 147, 106, 147, 108, 109, 63, 64,
51.381 + /* 590 */ 189, 60, 61, 62, 63, 64, 65, 66, 67, 68,
51.382 + /* 600 */ 69, 70, 71, 72, 186, 74, 75, 76, 77, 78,
51.383 + /* 610 */ 79, 80, 81, 82, 83, 84, 16, 92, 59, 55,
51.384 + /* 620 */ 212, 21, 147, 19, 147, 23, 188, 23, 12, 217,
51.385 + /* 630 */ 23, 219, 220, 7, 8, 9, 106, 147, 108, 109,
51.386 + /* 640 */ 24, 147, 42, 43, 208, 88, 89, 106, 92, 108,
51.387 + /* 650 */ 109, 244, 245, 37, 145, 39, 191, 182, 94, 16,
51.388 + /* 660 */ 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
51.389 + /* 670 */ 70, 71, 72, 147, 74, 75, 76, 77, 78, 79,
51.390 + /* 680 */ 80, 81, 82, 83, 84, 42, 43, 80, 142, 143,
51.391 + /* 690 */ 88, 89, 88, 89, 148, 88, 89, 133, 14, 147,
51.392 + /* 700 */ 225, 155, 16, 60, 61, 62, 63, 64, 65, 66,
51.393 + /* 710 */ 67, 68, 69, 70, 71, 72, 114, 74, 75, 76,
51.394 + /* 720 */ 77, 78, 79, 80, 81, 82, 83, 84, 42, 43,
51.395 + /* 730 */ 201, 202, 147, 147, 182, 189, 52, 147, 54, 147,
51.396 + /* 740 */ 147, 147, 147, 147, 155, 16, 60, 61, 62, 63,
51.397 + /* 750 */ 64, 65, 66, 67, 68, 69, 70, 71, 72, 213,
51.398 + /* 760 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
51.399 + /* 770 */ 84, 42, 43, 188, 188, 182, 182, 225, 189, 106,
51.400 + /* 780 */ 188, 108, 109, 188, 99, 100, 101, 241, 16, 155,
51.401 + /* 790 */ 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
51.402 + /* 800 */ 71, 72, 213, 74, 75, 76, 77, 78, 79, 80,
51.403 + /* 810 */ 81, 82, 83, 84, 42, 43, 23, 133, 225, 225,
51.404 + /* 820 */ 21, 225, 23, 189, 239, 236, 99, 100, 101, 22,
51.405 + /* 830 */ 242, 243, 155, 22, 62, 63, 64, 65, 66, 67,
51.406 + /* 840 */ 68, 69, 70, 71, 72, 147, 74, 75, 76, 77,
51.407 + /* 850 */ 78, 79, 80, 81, 82, 83, 84, 16, 17, 43,
51.408 + /* 860 */ 19, 147, 147, 147, 23, 147, 189, 169, 170, 147,
51.409 + /* 870 */ 147, 147, 31, 16, 17, 147, 19, 147, 124, 125,
51.410 + /* 880 */ 23, 88, 89, 169, 170, 169, 170, 88, 31, 48,
51.411 + /* 890 */ 147, 169, 170, 169, 170, 147, 89, 169, 170, 58,
51.412 + /* 900 */ 147, 22, 147, 188, 147, 48, 188, 114, 97, 147,
51.413 + /* 910 */ 147, 188, 147, 19, 98, 58, 147, 169, 170, 78,
51.414 + /* 920 */ 79, 114, 169, 170, 169, 170, 169, 170, 87, 88,
51.415 + /* 930 */ 89, 169, 170, 92, 161, 78, 79, 80, 169, 170,
51.416 + /* 940 */ 91, 147, 155, 22, 87, 88, 89, 16, 17, 92,
51.417 + /* 950 */ 19, 110, 147, 155, 23, 147, 7, 8, 20, 110,
51.418 + /* 960 */ 22, 80, 31, 169, 170, 124, 125, 126, 127, 128,
51.419 + /* 970 */ 129, 208, 123, 208, 169, 170, 189, 169, 170, 48,
51.420 + /* 980 */ 147, 124, 125, 126, 127, 128, 129, 189, 107, 58,
51.421 + /* 990 */ 107, 5, 111, 147, 111, 203, 10, 11, 12, 13,
51.422 + /* 1000 */ 121, 147, 147, 91, 92, 147, 112, 147, 147, 78,
51.423 + /* 1010 */ 79, 147, 26, 19, 28, 169, 170, 23, 87, 88,
51.424 + /* 1020 */ 89, 35, 147, 92, 169, 170, 178, 169, 170, 147,
51.425 + /* 1030 */ 169, 170, 147, 47, 113, 49, 92, 178, 147, 53,
51.426 + /* 1040 */ 147, 178, 56, 147, 169, 170, 147, 103, 147, 19,
51.427 + /* 1050 */ 147, 169, 170, 147, 147, 124, 125, 126, 127, 128,
51.428 + /* 1060 */ 129, 147, 169, 170, 147, 169, 170, 147, 169, 170,
51.429 + /* 1070 */ 169, 170, 169, 170, 147, 169, 170, 147, 20, 147,
51.430 + /* 1080 */ 22, 147, 88, 147, 232, 99, 100, 101, 147, 169,
51.431 + /* 1090 */ 170, 105, 147, 20, 147, 22, 110, 20, 68, 169,
51.432 + /* 1100 */ 170, 169, 170, 169, 170, 169, 170, 20, 147, 22,
51.433 + /* 1110 */ 147, 20, 147, 22, 169, 170, 169, 170, 147, 233,
51.434 + /* 1120 */ 134, 20, 147, 22, 20, 147, 22, 20, 20, 22,
51.435 + /* 1130 */ 22, 147, 169, 170, 169, 170, 59, 147, 147, 147,
51.436 + /* 1140 */ 169, 170, 147, 147, 169, 170, 147, 169, 170, 147,
51.437 + /* 1150 */ 147, 147, 147, 191, 229, 149, 223, 193, 229, 172,
51.438 + /* 1160 */ 172, 172, 177, 194, 194, 172, 6, 146, 146, 172,
51.439 + /* 1170 */ 146, 173, 146, 22, 154, 121, 194, 118, 195, 119,
51.440 + /* 1180 */ 116, 120, 23, 160, 112, 130, 152, 152, 222, 189,
51.441 + /* 1190 */ 98, 115, 98, 40, 179, 97, 171, 196, 171, 171,
51.442 + /* 1200 */ 19, 84, 173, 171, 197, 174, 198, 226, 160, 160,
51.443 + /* 1210 */ 171, 171, 179, 204, 171, 205, 204, 15, 205, 174,
51.444 + /* 1220 */ 151, 38, 152, 152, 60, 151, 151, 130, 184, 19,
51.445 + /* 1230 */ 152, 152, 151, 214, 152, 184, 194, 226, 152, 15,
51.446 + /* 1240 */ 187, 194, 152, 187, 187, 33, 137, 184, 234, 187,
51.447 + /* 1250 */ 214, 235, 152, 1, 237, 237, 20, 152, 159, 175,
51.448 + /* 1260 */ 175, 112, 112, 92, 112, 107, 112, 19, 19, 231,
51.449 + /* 1270 */ 20, 20, 11, 19, 117, 20, 114, 240, 22, 20,
51.450 + /* 1280 */ 20, 19, 117, 44, 243, 22, 22, 20, 112, 20,
51.451 + /* 1290 */ 20, 19, 246, 19, 96, 20, 19, 32, 19, 19,
51.452 + /* 1300 */ 103, 44, 44, 16, 21, 17, 98, 36, 22, 98,
51.453 + /* 1310 */ 133, 19, 5, 45, 1, 102, 122, 51, 45, 19,
51.454 + /* 1320 */ 113, 68, 14, 17, 115, 102, 122, 113, 19, 123,
51.455 + /* 1330 */ 20, 14, 136, 19, 135, 57, 3, 247, 4, 247,
51.456 + /* 1340 */ 247, 247, 247, 247, 68,
51.457 +};
51.458 +#define YY_SHIFT_USE_DFLT (-62)
51.459 +#define YY_SHIFT_MAX 387
51.460 +static const short yy_shift_ofst[] = {
51.461 + /* 0 */ 39, 841, 986, -16, 841, 931, 931, 258, 123, -36,
51.462 + /* 10 */ 96, 931, 931, 931, 931, 931, -45, 400, 174, 19,
51.463 + /* 20 */ 171, -54, -54, 53, 165, 208, 251, 324, 393, 462,
51.464 + /* 30 */ 531, 600, 643, 686, 643, 643, 643, 643, 643, 643,
51.465 + /* 40 */ 643, 643, 643, 643, 643, 643, 643, 643, 643, 643,
51.466 + /* 50 */ 643, 643, 729, 772, 772, 857, 931, 931, 931, 931,
51.467 + /* 60 */ 931, 931, 931, 931, 931, 931, 931, 931, 931, 931,
51.468 + /* 70 */ 931, 931, 931, 931, 931, 931, 931, 931, 931, 931,
51.469 + /* 80 */ 931, 931, 931, 931, 931, 931, 931, 931, 931, 931,
51.470 + /* 90 */ 931, 931, 931, 931, 931, -61, -61, 6, 6, 280,
51.471 + /* 100 */ 22, 61, 399, 564, 19, 19, 19, 19, 19, 19,
51.472 + /* 110 */ 19, 216, 171, 63, -62, -62, 131, 326, 472, 472,
51.473 + /* 120 */ 498, 559, 506, 799, 19, 799, 19, 19, 19, 19,
51.474 + /* 130 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 849,
51.475 + /* 140 */ 95, -36, -36, -36, -62, -62, -62, -15, -15, 333,
51.476 + /* 150 */ 459, 478, 557, 530, 541, 616, 602, 793, 604, 607,
51.477 + /* 160 */ 626, 19, 19, 881, 19, 19, 994, 19, 19, 807,
51.478 + /* 170 */ 19, 19, 673, 807, 19, 19, 384, 384, 384, 19,
51.479 + /* 180 */ 19, 673, 19, 19, 673, 19, 454, 685, 19, 19,
51.480 + /* 190 */ 673, 19, 19, 19, 673, 19, 19, 19, 673, 673,
51.481 + /* 200 */ 19, 19, 19, 19, 19, 468, 883, 921, 754, 754,
51.482 + /* 210 */ 432, 406, 406, 406, 816, 406, 406, 811, 879, 879,
51.483 + /* 220 */ 1160, 1160, 1160, 1160, 1151, -36, 1054, 1059, 1060, 1064,
51.484 + /* 230 */ 1061, 1159, 1055, 1072, 1072, 1092, 1076, 1092, 1076, 1094,
51.485 + /* 240 */ 1094, 1153, 1094, 1098, 1094, 1181, 1117, 1159, 1117, 1159,
51.486 + /* 250 */ 1153, 1094, 1094, 1094, 1181, 1202, 1072, 1202, 1072, 1202,
51.487 + /* 260 */ 1072, 1072, 1183, 1097, 1202, 1072, 1164, 1164, 1210, 1054,
51.488 + /* 270 */ 1072, 1224, 1224, 1224, 1224, 1054, 1164, 1210, 1072, 1212,
51.489 + /* 280 */ 1212, 1072, 1072, 1109, -62, -62, -62, -62, -62, -62,
51.490 + /* 290 */ 525, 684, 727, 168, 894, 556, 555, 938, 944, 949,
51.491 + /* 300 */ 912, 1058, 1073, 1087, 1091, 1101, 1104, 1107, 1030, 1108,
51.492 + /* 310 */ 1077, 1252, 1236, 1149, 1150, 1152, 1154, 1171, 1158, 1248,
51.493 + /* 320 */ 1250, 1251, 1249, 1261, 1254, 1255, 1256, 1259, 1260, 1263,
51.494 + /* 330 */ 1157, 1264, 1165, 1263, 1162, 1262, 1267, 1176, 1269, 1270,
51.495 + /* 340 */ 1265, 1239, 1272, 1257, 1274, 1275, 1277, 1279, 1258, 1280,
51.496 + /* 350 */ 1198, 1197, 1287, 1288, 1283, 1208, 1271, 1266, 1268, 1286,
51.497 + /* 360 */ 1273, 1177, 1211, 1292, 1307, 1313, 1213, 1253, 1276, 1194,
51.498 + /* 370 */ 1300, 1207, 1308, 1209, 1306, 1214, 1223, 1204, 1309, 1206,
51.499 + /* 380 */ 1310, 1317, 1278, 1199, 1196, 1314, 1333, 1334,
51.500 +};
51.501 +#define YY_REDUCE_USE_DFLT (-165)
51.502 +#define YY_REDUCE_MAX 289
51.503 +static const short yy_reduce_ofst[] = {
51.504 + /* 0 */ -138, 277, 546, 137, 401, -21, 44, 36, 38, 242,
51.505 + /* 10 */ -141, 191, 91, 269, 343, 345, -126, 589, 338, 150,
51.506 + /* 20 */ 147, -13, 213, 412, 412, 412, 412, 412, 412, 412,
51.507 + /* 30 */ 412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
51.508 + /* 40 */ 412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
51.509 + /* 50 */ 412, 412, 412, 412, 412, 211, 698, 714, 716, 722,
51.510 + /* 60 */ 724, 728, 748, 753, 755, 757, 762, 769, 794, 805,
51.511 + /* 70 */ 808, 846, 855, 858, 861, 875, 882, 893, 896, 899,
51.512 + /* 80 */ 901, 903, 906, 920, 930, 932, 934, 936, 945, 947,
51.513 + /* 90 */ 963, 965, 971, 975, 978, 412, 412, 412, 412, 20,
51.514 + /* 100 */ 412, 412, 23, 34, 334, 475, 552, 593, 594, 585,
51.515 + /* 110 */ 212, 412, 289, 412, 412, 412, 135, -164, -115, 164,
51.516 + /* 120 */ 407, 407, 350, 141, 436, 163, 596, -90, 763, 218,
51.517 + /* 130 */ 765, 438, 586, 592, 595, 715, 718, 408, 723, 380,
51.518 + /* 140 */ 634, 677, 787, 798, 144, 529, 588, -14, 0, 17,
51.519 + /* 150 */ 244, 155, 298, 155, 155, 418, 372, 477, 490, 494,
51.520 + /* 160 */ 509, 526, 590, 465, 494, 730, 773, 743, 833, 792,
51.521 + /* 170 */ 854, 860, 155, 792, 864, 885, 848, 859, 863, 891,
51.522 + /* 180 */ 907, 155, 914, 917, 155, 927, 852, 886, 941, 961,
51.523 + /* 190 */ 155, 984, 990, 991, 155, 992, 995, 996, 155, 155,
51.524 + /* 200 */ 999, 1002, 1003, 1004, 1005, 1006, 962, 964, 925, 929,
51.525 + /* 210 */ 933, 987, 988, 989, 985, 993, 997, 998, 969, 970,
51.526 + /* 220 */ 1021, 1022, 1024, 1026, 1020, 1000, 982, 983, 1001, 1007,
51.527 + /* 230 */ 1008, 1023, 966, 1034, 1035, 1009, 1010, 1012, 1013, 1025,
51.528 + /* 240 */ 1027, 1015, 1028, 1029, 1032, 1031, 981, 1048, 1011, 1049,
51.529 + /* 250 */ 1033, 1039, 1040, 1043, 1045, 1069, 1070, 1074, 1071, 1075,
51.530 + /* 260 */ 1078, 1079, 1014, 1016, 1081, 1082, 1044, 1051, 1019, 1042,
51.531 + /* 270 */ 1086, 1053, 1056, 1057, 1062, 1047, 1063, 1036, 1090, 1017,
51.532 + /* 280 */ 1018, 1100, 1105, 1037, 1099, 1084, 1085, 1038, 1041, 1046,
51.533 +};
51.534 +static const YYACTIONTYPE yy_default[] = {
51.535 + /* 0 */ 592, 816, 897, 707, 897, 816, 897, 897, 843, 711,
51.536 + /* 10 */ 872, 814, 897, 897, 897, 897, 789, 897, 843, 897,
51.537 + /* 20 */ 623, 843, 843, 740, 897, 897, 897, 897, 897, 897,
51.538 + /* 30 */ 897, 897, 741, 897, 818, 813, 809, 811, 810, 817,
51.539 + /* 40 */ 742, 731, 738, 745, 723, 856, 747, 748, 754, 755,
51.540 + /* 50 */ 873, 871, 777, 776, 795, 897, 897, 897, 897, 897,
51.541 + /* 60 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
51.542 + /* 70 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
51.543 + /* 80 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
51.544 + /* 90 */ 897, 897, 897, 897, 897, 779, 800, 778, 788, 616,
51.545 + /* 100 */ 780, 781, 676, 611, 897, 897, 897, 897, 897, 897,
51.546 + /* 110 */ 897, 782, 897, 783, 796, 797, 897, 897, 897, 897,
51.547 + /* 120 */ 897, 897, 592, 707, 897, 707, 897, 897, 897, 897,
51.548 + /* 130 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
51.549 + /* 140 */ 897, 897, 897, 897, 701, 711, 890, 897, 897, 667,
51.550 + /* 150 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
51.551 + /* 160 */ 599, 597, 897, 699, 897, 897, 625, 897, 897, 709,
51.552 + /* 170 */ 897, 897, 714, 715, 897, 897, 897, 897, 897, 897,
51.553 + /* 180 */ 897, 613, 897, 897, 688, 897, 849, 897, 897, 897,
51.554 + /* 190 */ 863, 897, 897, 897, 861, 897, 897, 897, 690, 750,
51.555 + /* 200 */ 830, 897, 876, 878, 897, 897, 699, 708, 897, 897,
51.556 + /* 210 */ 812, 734, 734, 734, 646, 734, 734, 649, 744, 744,
51.557 + /* 220 */ 596, 596, 596, 596, 666, 897, 744, 735, 737, 727,
51.558 + /* 230 */ 739, 897, 897, 716, 716, 724, 726, 724, 726, 678,
51.559 + /* 240 */ 678, 663, 678, 649, 678, 822, 827, 897, 827, 897,
51.560 + /* 250 */ 663, 678, 678, 678, 822, 608, 716, 608, 716, 608,
51.561 + /* 260 */ 716, 716, 853, 855, 608, 716, 680, 680, 756, 744,
51.562 + /* 270 */ 716, 687, 687, 687, 687, 744, 680, 756, 716, 875,
51.563 + /* 280 */ 875, 716, 716, 883, 633, 651, 651, 858, 890, 895,
51.564 + /* 290 */ 897, 897, 897, 897, 763, 897, 897, 897, 897, 897,
51.565 + /* 300 */ 897, 897, 897, 897, 897, 897, 897, 897, 836, 897,
51.566 + /* 310 */ 897, 897, 897, 768, 764, 897, 765, 897, 693, 897,
51.567 + /* 320 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 815,
51.568 + /* 330 */ 897, 728, 897, 736, 897, 897, 897, 897, 897, 897,
51.569 + /* 340 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
51.570 + /* 350 */ 897, 897, 897, 897, 897, 897, 897, 897, 851, 852,
51.571 + /* 360 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
51.572 + /* 370 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
51.573 + /* 380 */ 897, 897, 882, 897, 897, 885, 593, 897, 587, 590,
51.574 + /* 390 */ 589, 591, 595, 598, 620, 621, 622, 600, 601, 602,
51.575 + /* 400 */ 603, 604, 605, 606, 612, 614, 632, 634, 618, 636,
51.576 + /* 410 */ 697, 698, 760, 691, 692, 696, 771, 762, 766, 767,
51.577 + /* 420 */ 769, 770, 784, 785, 787, 793, 799, 802, 786, 791,
51.578 + /* 430 */ 792, 794, 798, 801, 694, 695, 805, 619, 626, 627,
51.579 + /* 440 */ 630, 631, 839, 841, 840, 842, 629, 628, 772, 775,
51.580 + /* 450 */ 807, 808, 864, 865, 866, 867, 868, 803, 717, 806,
51.581 + /* 460 */ 790, 729, 732, 733, 730, 700, 710, 719, 720, 721,
51.582 + /* 470 */ 722, 705, 706, 712, 725, 758, 759, 713, 702, 703,
51.583 + /* 480 */ 704, 804, 761, 773, 774, 637, 638, 768, 639, 640,
51.584 + /* 490 */ 641, 679, 682, 683, 684, 642, 661, 664, 665, 643,
51.585 + /* 500 */ 650, 644, 645, 652, 653, 654, 657, 658, 659, 660,
51.586 + /* 510 */ 655, 656, 823, 824, 828, 826, 825, 647, 648, 662,
51.587 + /* 520 */ 635, 624, 617, 668, 671, 672, 673, 674, 675, 677,
51.588 + /* 530 */ 669, 670, 615, 607, 609, 718, 845, 854, 850, 846,
51.589 + /* 540 */ 847, 848, 610, 819, 820, 681, 752, 753, 844, 857,
51.590 + /* 550 */ 859, 757, 860, 862, 887, 685, 686, 689, 829, 869,
51.591 + /* 560 */ 743, 746, 749, 751, 831, 832, 833, 834, 837, 838,
51.592 + /* 570 */ 835, 870, 874, 877, 879, 880, 881, 884, 886, 891,
51.593 + /* 580 */ 892, 893, 896, 894, 594, 588,
51.594 +};
51.595 +#define YY_SZ_ACTTAB (int)(sizeof(yy_action)/sizeof(yy_action[0]))
51.596 +
51.597 +/* The next table maps tokens into fallback tokens. If a construct
51.598 +** like the following:
51.599 +**
51.600 +** %fallback ID X Y Z.
51.601 +**
51.602 +** appears in the grammer, then ID becomes a fallback token for X, Y,
51.603 +** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
51.604 +** but it does not parse, the type of the token is changed to ID and
51.605 +** the parse is retried before an error is thrown.
51.606 +*/
51.607 +#ifdef YYFALLBACK
51.608 +static const YYCODETYPE yyFallback[] = {
51.609 + 0, /* $ => nothing */
51.610 + 0, /* SEMI => nothing */
51.611 + 23, /* EXPLAIN => ID */
51.612 + 23, /* QUERY => ID */
51.613 + 23, /* PLAN => ID */
51.614 + 23, /* BEGIN => ID */
51.615 + 0, /* TRANSACTION => nothing */
51.616 + 23, /* DEFERRED => ID */
51.617 + 23, /* IMMEDIATE => ID */
51.618 + 23, /* EXCLUSIVE => ID */
51.619 + 0, /* COMMIT => nothing */
51.620 + 23, /* END => ID */
51.621 + 0, /* ROLLBACK => nothing */
51.622 + 0, /* CREATE => nothing */
51.623 + 0, /* TABLE => nothing */
51.624 + 23, /* IF => ID */
51.625 + 0, /* NOT => nothing */
51.626 + 0, /* EXISTS => nothing */
51.627 + 23, /* TEMP => ID */
51.628 + 0, /* LP => nothing */
51.629 + 0, /* RP => nothing */
51.630 + 0, /* AS => nothing */
51.631 + 0, /* COMMA => nothing */
51.632 + 0, /* ID => nothing */
51.633 + 23, /* ABORT => ID */
51.634 + 23, /* AFTER => ID */
51.635 + 23, /* ANALYZE => ID */
51.636 + 23, /* ASC => ID */
51.637 + 23, /* ATTACH => ID */
51.638 + 23, /* BEFORE => ID */
51.639 + 23, /* CASCADE => ID */
51.640 + 23, /* CAST => ID */
51.641 + 23, /* CONFLICT => ID */
51.642 + 23, /* DATABASE => ID */
51.643 + 23, /* DESC => ID */
51.644 + 23, /* DETACH => ID */
51.645 + 23, /* EACH => ID */
51.646 + 23, /* FAIL => ID */
51.647 + 23, /* FOR => ID */
51.648 + 23, /* IGNORE => ID */
51.649 + 23, /* INITIALLY => ID */
51.650 + 23, /* INSTEAD => ID */
51.651 + 23, /* LIKE_KW => ID */
51.652 + 23, /* MATCH => ID */
51.653 + 23, /* KEY => ID */
51.654 + 23, /* OF => ID */
51.655 + 23, /* OFFSET => ID */
51.656 + 23, /* PRAGMA => ID */
51.657 + 23, /* RAISE => ID */
51.658 + 23, /* REPLACE => ID */
51.659 + 23, /* RESTRICT => ID */
51.660 + 23, /* ROW => ID */
51.661 + 23, /* TRIGGER => ID */
51.662 + 23, /* VACUUM => ID */
51.663 + 23, /* VIEW => ID */
51.664 + 23, /* VIRTUAL => ID */
51.665 + 23, /* REINDEX => ID */
51.666 + 23, /* RENAME => ID */
51.667 + 23, /* CTIME_KW => ID */
51.668 + 0, /* ANY => nothing */
51.669 + 0, /* OR => nothing */
51.670 + 0, /* AND => nothing */
51.671 + 0, /* IS => nothing */
51.672 + 0, /* BETWEEN => nothing */
51.673 + 0, /* IN => nothing */
51.674 + 0, /* ISNULL => nothing */
51.675 + 0, /* NOTNULL => nothing */
51.676 + 0, /* NE => nothing */
51.677 + 0, /* EQ => nothing */
51.678 + 0, /* GT => nothing */
51.679 + 0, /* LE => nothing */
51.680 + 0, /* LT => nothing */
51.681 + 0, /* GE => nothing */
51.682 + 0, /* ESCAPE => nothing */
51.683 + 0, /* BITAND => nothing */
51.684 + 0, /* BITOR => nothing */
51.685 + 0, /* LSHIFT => nothing */
51.686 + 0, /* RSHIFT => nothing */
51.687 + 0, /* PLUS => nothing */
51.688 + 0, /* MINUS => nothing */
51.689 + 0, /* STAR => nothing */
51.690 + 0, /* SLASH => nothing */
51.691 + 0, /* REM => nothing */
51.692 + 0, /* CONCAT => nothing */
51.693 + 0, /* COLLATE => nothing */
51.694 + 0, /* UMINUS => nothing */
51.695 + 0, /* UPLUS => nothing */
51.696 + 0, /* BITNOT => nothing */
51.697 + 0, /* STRING => nothing */
51.698 + 0, /* JOIN_KW => nothing */
51.699 + 0, /* CONSTRAINT => nothing */
51.700 + 0, /* DEFAULT => nothing */
51.701 + 0, /* NULL => nothing */
51.702 + 0, /* PRIMARY => nothing */
51.703 + 0, /* UNIQUE => nothing */
51.704 + 0, /* CHECK => nothing */
51.705 + 0, /* REFERENCES => nothing */
51.706 + 0, /* AUTOINCR => nothing */
51.707 + 0, /* ON => nothing */
51.708 + 0, /* DELETE => nothing */
51.709 + 0, /* UPDATE => nothing */
51.710 + 0, /* INSERT => nothing */
51.711 + 0, /* SET => nothing */
51.712 + 0, /* DEFERRABLE => nothing */
51.713 + 0, /* FOREIGN => nothing */
51.714 + 0, /* DROP => nothing */
51.715 + 0, /* UNION => nothing */
51.716 + 0, /* ALL => nothing */
51.717 + 0, /* EXCEPT => nothing */
51.718 + 0, /* INTERSECT => nothing */
51.719 + 0, /* SELECT => nothing */
51.720 + 0, /* DISTINCT => nothing */
51.721 + 0, /* DOT => nothing */
51.722 + 0, /* FROM => nothing */
51.723 + 0, /* JOIN => nothing */
51.724 + 0, /* USING => nothing */
51.725 + 0, /* ORDER => nothing */
51.726 + 0, /* BY => nothing */
51.727 + 0, /* GROUP => nothing */
51.728 + 0, /* HAVING => nothing */
51.729 + 0, /* LIMIT => nothing */
51.730 + 0, /* WHERE => nothing */
51.731 + 0, /* INTO => nothing */
51.732 + 0, /* VALUES => nothing */
51.733 + 0, /* INTEGER => nothing */
51.734 + 0, /* FLOAT => nothing */
51.735 + 0, /* BLOB => nothing */
51.736 + 0, /* REGISTER => nothing */
51.737 + 0, /* VARIABLE => nothing */
51.738 + 0, /* CASE => nothing */
51.739 + 0, /* WHEN => nothing */
51.740 + 0, /* THEN => nothing */
51.741 + 0, /* ELSE => nothing */
51.742 + 0, /* INDEX => nothing */
51.743 + 0, /* ALTER => nothing */
51.744 + 0, /* TO => nothing */
51.745 + 0, /* ADD => nothing */
51.746 + 0, /* COLUMNKW => nothing */
51.747 +};
51.748 +#endif /* YYFALLBACK */
51.749 +
51.750 +/* The following structure represents a single element of the
51.751 +** parser's stack. Information stored includes:
51.752 +**
51.753 +** + The state number for the parser at this level of the stack.
51.754 +**
51.755 +** + The value of the token stored at this level of the stack.
51.756 +** (In other words, the "major" token.)
51.757 +**
51.758 +** + The semantic value stored at this level of the stack. This is
51.759 +** the information used by the action routines in the grammar.
51.760 +** It is sometimes called the "minor" token.
51.761 +*/
51.762 +struct yyStackEntry {
51.763 + int stateno; /* The state-number */
51.764 + int major; /* The major token value. This is the code
51.765 + ** number for the token at this stack level */
51.766 + YYMINORTYPE minor; /* The user-supplied minor token value. This
51.767 + ** is the value of the token */
51.768 +};
51.769 +typedef struct yyStackEntry yyStackEntry;
51.770 +
51.771 +/* The state of the parser is completely contained in an instance of
51.772 +** the following structure */
51.773 +struct yyParser {
51.774 + int yyidx; /* Index of top element in stack */
51.775 + int yyerrcnt; /* Shifts left before out of the error */
51.776 + sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
51.777 +#if YYSTACKDEPTH<=0
51.778 + int yystksz; /* Current side of the stack */
51.779 + yyStackEntry *yystack; /* The parser's stack */
51.780 +#else
51.781 + yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
51.782 +#endif
51.783 +};
51.784 +typedef struct yyParser yyParser;
51.785 +
51.786 +#ifndef NDEBUG
51.787 +#include <stdio.h>
51.788 +static FILE *yyTraceFILE = 0;
51.789 +static char *yyTracePrompt = 0;
51.790 +#endif /* NDEBUG */
51.791 +
51.792 +#ifndef NDEBUG
51.793 +/*
51.794 +** Turn parser tracing on by giving a stream to which to write the trace
51.795 +** and a prompt to preface each trace message. Tracing is turned off
51.796 +** by making either argument NULL
51.797 +**
51.798 +** Inputs:
51.799 +** <ul>
51.800 +** <li> A FILE* to which trace output should be written.
51.801 +** If NULL, then tracing is turned off.
51.802 +** <li> A prefix string written at the beginning of every
51.803 +** line of trace output. If NULL, then tracing is
51.804 +** turned off.
51.805 +** </ul>
51.806 +**
51.807 +** Outputs:
51.808 +** None.
51.809 +*/
51.810 +void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
51.811 + yyTraceFILE = TraceFILE;
51.812 + yyTracePrompt = zTracePrompt;
51.813 + if( yyTraceFILE==0 ) yyTracePrompt = 0;
51.814 + else if( yyTracePrompt==0 ) yyTraceFILE = 0;
51.815 +}
51.816 +#endif /* NDEBUG */
51.817 +
51.818 +#ifndef NDEBUG
51.819 +/* For tracing shifts, the names of all terminals and nonterminals
51.820 +** are required. The following table supplies these names */
51.821 +static const char *const yyTokenName[] = {
51.822 + "$", "SEMI", "EXPLAIN", "QUERY",
51.823 + "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
51.824 + "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
51.825 + "ROLLBACK", "CREATE", "TABLE", "IF",
51.826 + "NOT", "EXISTS", "TEMP", "LP",
51.827 + "RP", "AS", "COMMA", "ID",
51.828 + "ABORT", "AFTER", "ANALYZE", "ASC",
51.829 + "ATTACH", "BEFORE", "CASCADE", "CAST",
51.830 + "CONFLICT", "DATABASE", "DESC", "DETACH",
51.831 + "EACH", "FAIL", "FOR", "IGNORE",
51.832 + "INITIALLY", "INSTEAD", "LIKE_KW", "MATCH",
51.833 + "KEY", "OF", "OFFSET", "PRAGMA",
51.834 + "RAISE", "REPLACE", "RESTRICT", "ROW",
51.835 + "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
51.836 + "REINDEX", "RENAME", "CTIME_KW", "ANY",
51.837 + "OR", "AND", "IS", "BETWEEN",
51.838 + "IN", "ISNULL", "NOTNULL", "NE",
51.839 + "EQ", "GT", "LE", "LT",
51.840 + "GE", "ESCAPE", "BITAND", "BITOR",
51.841 + "LSHIFT", "RSHIFT", "PLUS", "MINUS",
51.842 + "STAR", "SLASH", "REM", "CONCAT",
51.843 + "COLLATE", "UMINUS", "UPLUS", "BITNOT",
51.844 + "STRING", "JOIN_KW", "CONSTRAINT", "DEFAULT",
51.845 + "NULL", "PRIMARY", "UNIQUE", "CHECK",
51.846 + "REFERENCES", "AUTOINCR", "ON", "DELETE",
51.847 + "UPDATE", "INSERT", "SET", "DEFERRABLE",
51.848 + "FOREIGN", "DROP", "UNION", "ALL",
51.849 + "EXCEPT", "INTERSECT", "SELECT", "DISTINCT",
51.850 + "DOT", "FROM", "JOIN", "USING",
51.851 + "ORDER", "BY", "GROUP", "HAVING",
51.852 + "LIMIT", "WHERE", "INTO", "VALUES",
51.853 + "INTEGER", "FLOAT", "BLOB", "REGISTER",
51.854 + "VARIABLE", "CASE", "WHEN", "THEN",
51.855 + "ELSE", "INDEX", "ALTER", "TO",
51.856 + "ADD", "COLUMNKW", "error", "input",
51.857 + "cmdlist", "ecmd", "cmdx", "cmd",
51.858 + "explain", "transtype", "trans_opt", "nm",
51.859 + "create_table", "create_table_args", "temp", "ifnotexists",
51.860 + "dbnm", "columnlist", "conslist_opt", "select",
51.861 + "column", "columnid", "type", "carglist",
51.862 + "id", "ids", "typetoken", "typename",
51.863 + "signed", "plus_num", "minus_num", "carg",
51.864 + "ccons", "term", "expr", "onconf",
51.865 + "sortorder", "autoinc", "idxlist_opt", "refargs",
51.866 + "defer_subclause", "refarg", "refact", "init_deferred_pred_opt",
51.867 + "conslist", "tcons", "idxlist", "defer_subclause_opt",
51.868 + "orconf", "resolvetype", "raisetype", "ifexists",
51.869 + "fullname", "oneselect", "multiselect_op", "distinct",
51.870 + "selcollist", "from", "where_opt", "groupby_opt",
51.871 + "having_opt", "orderby_opt", "limit_opt", "sclp",
51.872 + "as", "seltablist", "stl_prefix", "joinop",
51.873 + "on_opt", "using_opt", "seltablist_paren", "joinop2",
51.874 + "inscollist", "sortlist", "sortitem", "nexprlist",
51.875 + "setlist", "insert_cmd", "inscollist_opt", "itemlist",
51.876 + "exprlist", "likeop", "escape", "between_op",
51.877 + "in_op", "case_operand", "case_exprlist", "case_else",
51.878 + "uniqueflag", "idxitem", "collate", "nmnum",
51.879 + "plus_opt", "number", "trigger_decl", "trigger_cmd_list",
51.880 + "trigger_time", "trigger_event", "foreach_clause", "when_clause",
51.881 + "trigger_cmd", "database_kw_opt", "key_opt", "add_column_fullname",
51.882 + "kwcolumn_opt", "create_vtab", "vtabarglist", "vtabarg",
51.883 + "vtabargtoken", "lp", "anylist",
51.884 +};
51.885 +#endif /* NDEBUG */
51.886 +
51.887 +#ifndef NDEBUG
51.888 +/* For tracing reduce actions, the names of all rules are required.
51.889 +*/
51.890 +static const char *const yyRuleName[] = {
51.891 + /* 0 */ "input ::= cmdlist",
51.892 + /* 1 */ "cmdlist ::= cmdlist ecmd",
51.893 + /* 2 */ "cmdlist ::= ecmd",
51.894 + /* 3 */ "cmdx ::= cmd",
51.895 + /* 4 */ "ecmd ::= SEMI",
51.896 + /* 5 */ "ecmd ::= explain cmdx SEMI",
51.897 + /* 6 */ "explain ::=",
51.898 + /* 7 */ "explain ::= EXPLAIN",
51.899 + /* 8 */ "explain ::= EXPLAIN QUERY PLAN",
51.900 + /* 9 */ "cmd ::= BEGIN transtype trans_opt",
51.901 + /* 10 */ "trans_opt ::=",
51.902 + /* 11 */ "trans_opt ::= TRANSACTION",
51.903 + /* 12 */ "trans_opt ::= TRANSACTION nm",
51.904 + /* 13 */ "transtype ::=",
51.905 + /* 14 */ "transtype ::= DEFERRED",
51.906 + /* 15 */ "transtype ::= IMMEDIATE",
51.907 + /* 16 */ "transtype ::= EXCLUSIVE",
51.908 + /* 17 */ "cmd ::= COMMIT trans_opt",
51.909 + /* 18 */ "cmd ::= END trans_opt",
51.910 + /* 19 */ "cmd ::= ROLLBACK trans_opt",
51.911 + /* 20 */ "cmd ::= create_table create_table_args",
51.912 + /* 21 */ "create_table ::= CREATE temp TABLE ifnotexists nm dbnm",
51.913 + /* 22 */ "ifnotexists ::=",
51.914 + /* 23 */ "ifnotexists ::= IF NOT EXISTS",
51.915 + /* 24 */ "temp ::= TEMP",
51.916 + /* 25 */ "temp ::=",
51.917 + /* 26 */ "create_table_args ::= LP columnlist conslist_opt RP",
51.918 + /* 27 */ "create_table_args ::= AS select",
51.919 + /* 28 */ "columnlist ::= columnlist COMMA column",
51.920 + /* 29 */ "columnlist ::= column",
51.921 + /* 30 */ "column ::= columnid type carglist",
51.922 + /* 31 */ "columnid ::= nm",
51.923 + /* 32 */ "id ::= ID",
51.924 + /* 33 */ "ids ::= ID|STRING",
51.925 + /* 34 */ "nm ::= ID",
51.926 + /* 35 */ "nm ::= STRING",
51.927 + /* 36 */ "nm ::= JOIN_KW",
51.928 + /* 37 */ "type ::=",
51.929 + /* 38 */ "type ::= typetoken",
51.930 + /* 39 */ "typetoken ::= typename",
51.931 + /* 40 */ "typetoken ::= typename LP signed RP",
51.932 + /* 41 */ "typetoken ::= typename LP signed COMMA signed RP",
51.933 + /* 42 */ "typename ::= ids",
51.934 + /* 43 */ "typename ::= typename ids",
51.935 + /* 44 */ "signed ::= plus_num",
51.936 + /* 45 */ "signed ::= minus_num",
51.937 + /* 46 */ "carglist ::= carglist carg",
51.938 + /* 47 */ "carglist ::=",
51.939 + /* 48 */ "carg ::= CONSTRAINT nm ccons",
51.940 + /* 49 */ "carg ::= ccons",
51.941 + /* 50 */ "ccons ::= DEFAULT term",
51.942 + /* 51 */ "ccons ::= DEFAULT LP expr RP",
51.943 + /* 52 */ "ccons ::= DEFAULT PLUS term",
51.944 + /* 53 */ "ccons ::= DEFAULT MINUS term",
51.945 + /* 54 */ "ccons ::= DEFAULT id",
51.946 + /* 55 */ "ccons ::= NULL onconf",
51.947 + /* 56 */ "ccons ::= NOT NULL onconf",
51.948 + /* 57 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
51.949 + /* 58 */ "ccons ::= UNIQUE onconf",
51.950 + /* 59 */ "ccons ::= CHECK LP expr RP",
51.951 + /* 60 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
51.952 + /* 61 */ "ccons ::= defer_subclause",
51.953 + /* 62 */ "ccons ::= COLLATE id",
51.954 + /* 63 */ "autoinc ::=",
51.955 + /* 64 */ "autoinc ::= AUTOINCR",
51.956 + /* 65 */ "refargs ::=",
51.957 + /* 66 */ "refargs ::= refargs refarg",
51.958 + /* 67 */ "refarg ::= MATCH nm",
51.959 + /* 68 */ "refarg ::= ON DELETE refact",
51.960 + /* 69 */ "refarg ::= ON UPDATE refact",
51.961 + /* 70 */ "refarg ::= ON INSERT refact",
51.962 + /* 71 */ "refact ::= SET NULL",
51.963 + /* 72 */ "refact ::= SET DEFAULT",
51.964 + /* 73 */ "refact ::= CASCADE",
51.965 + /* 74 */ "refact ::= RESTRICT",
51.966 + /* 75 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
51.967 + /* 76 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
51.968 + /* 77 */ "init_deferred_pred_opt ::=",
51.969 + /* 78 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
51.970 + /* 79 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
51.971 + /* 80 */ "conslist_opt ::=",
51.972 + /* 81 */ "conslist_opt ::= COMMA conslist",
51.973 + /* 82 */ "conslist ::= conslist COMMA tcons",
51.974 + /* 83 */ "conslist ::= conslist tcons",
51.975 + /* 84 */ "conslist ::= tcons",
51.976 + /* 85 */ "tcons ::= CONSTRAINT nm",
51.977 + /* 86 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
51.978 + /* 87 */ "tcons ::= UNIQUE LP idxlist RP onconf",
51.979 + /* 88 */ "tcons ::= CHECK LP expr RP onconf",
51.980 + /* 89 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
51.981 + /* 90 */ "defer_subclause_opt ::=",
51.982 + /* 91 */ "defer_subclause_opt ::= defer_subclause",
51.983 + /* 92 */ "onconf ::=",
51.984 + /* 93 */ "onconf ::= ON CONFLICT resolvetype",
51.985 + /* 94 */ "orconf ::=",
51.986 + /* 95 */ "orconf ::= OR resolvetype",
51.987 + /* 96 */ "resolvetype ::= raisetype",
51.988 + /* 97 */ "resolvetype ::= IGNORE",
51.989 + /* 98 */ "resolvetype ::= REPLACE",
51.990 + /* 99 */ "cmd ::= DROP TABLE ifexists fullname",
51.991 + /* 100 */ "ifexists ::= IF EXISTS",
51.992 + /* 101 */ "ifexists ::=",
51.993 + /* 102 */ "cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select",
51.994 + /* 103 */ "cmd ::= DROP VIEW ifexists fullname",
51.995 + /* 104 */ "cmd ::= select",
51.996 + /* 105 */ "select ::= oneselect",
51.997 + /* 106 */ "select ::= select multiselect_op oneselect",
51.998 + /* 107 */ "multiselect_op ::= UNION",
51.999 + /* 108 */ "multiselect_op ::= UNION ALL",
51.1000 + /* 109 */ "multiselect_op ::= EXCEPT|INTERSECT",
51.1001 + /* 110 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
51.1002 + /* 111 */ "distinct ::= DISTINCT",
51.1003 + /* 112 */ "distinct ::= ALL",
51.1004 + /* 113 */ "distinct ::=",
51.1005 + /* 114 */ "sclp ::= selcollist COMMA",
51.1006 + /* 115 */ "sclp ::=",
51.1007 + /* 116 */ "selcollist ::= sclp expr as",
51.1008 + /* 117 */ "selcollist ::= sclp STAR",
51.1009 + /* 118 */ "selcollist ::= sclp nm DOT STAR",
51.1010 + /* 119 */ "as ::= AS nm",
51.1011 + /* 120 */ "as ::= ids",
51.1012 + /* 121 */ "as ::=",
51.1013 + /* 122 */ "from ::=",
51.1014 + /* 123 */ "from ::= FROM seltablist",
51.1015 + /* 124 */ "stl_prefix ::= seltablist joinop",
51.1016 + /* 125 */ "stl_prefix ::=",
51.1017 + /* 126 */ "seltablist ::= stl_prefix nm dbnm as on_opt using_opt",
51.1018 + /* 127 */ "seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt",
51.1019 + /* 128 */ "seltablist_paren ::= select",
51.1020 + /* 129 */ "seltablist_paren ::= seltablist",
51.1021 + /* 130 */ "dbnm ::=",
51.1022 + /* 131 */ "dbnm ::= DOT nm",
51.1023 + /* 132 */ "fullname ::= nm dbnm",
51.1024 + /* 133 */ "joinop ::= COMMA|JOIN",
51.1025 + /* 134 */ "joinop ::= JOIN_KW JOIN",
51.1026 + /* 135 */ "joinop ::= JOIN_KW nm JOIN",
51.1027 + /* 136 */ "joinop ::= JOIN_KW nm nm JOIN",
51.1028 + /* 137 */ "on_opt ::= ON expr",
51.1029 + /* 138 */ "on_opt ::=",
51.1030 + /* 139 */ "using_opt ::= USING LP inscollist RP",
51.1031 + /* 140 */ "using_opt ::=",
51.1032 + /* 141 */ "orderby_opt ::=",
51.1033 + /* 142 */ "orderby_opt ::= ORDER BY sortlist",
51.1034 + /* 143 */ "sortlist ::= sortlist COMMA sortitem sortorder",
51.1035 + /* 144 */ "sortlist ::= sortitem sortorder",
51.1036 + /* 145 */ "sortitem ::= expr",
51.1037 + /* 146 */ "sortorder ::= ASC",
51.1038 + /* 147 */ "sortorder ::= DESC",
51.1039 + /* 148 */ "sortorder ::=",
51.1040 + /* 149 */ "groupby_opt ::=",
51.1041 + /* 150 */ "groupby_opt ::= GROUP BY nexprlist",
51.1042 + /* 151 */ "having_opt ::=",
51.1043 + /* 152 */ "having_opt ::= HAVING expr",
51.1044 + /* 153 */ "limit_opt ::=",
51.1045 + /* 154 */ "limit_opt ::= LIMIT expr",
51.1046 + /* 155 */ "limit_opt ::= LIMIT expr OFFSET expr",
51.1047 + /* 156 */ "limit_opt ::= LIMIT expr COMMA expr",
51.1048 + /* 157 */ "cmd ::= DELETE FROM fullname where_opt",
51.1049 + /* 158 */ "where_opt ::=",
51.1050 + /* 159 */ "where_opt ::= WHERE expr",
51.1051 + /* 160 */ "cmd ::= UPDATE orconf fullname SET setlist where_opt",
51.1052 + /* 161 */ "setlist ::= setlist COMMA nm EQ expr",
51.1053 + /* 162 */ "setlist ::= nm EQ expr",
51.1054 + /* 163 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
51.1055 + /* 164 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
51.1056 + /* 165 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
51.1057 + /* 166 */ "insert_cmd ::= INSERT orconf",
51.1058 + /* 167 */ "insert_cmd ::= REPLACE",
51.1059 + /* 168 */ "itemlist ::= itemlist COMMA expr",
51.1060 + /* 169 */ "itemlist ::= expr",
51.1061 + /* 170 */ "inscollist_opt ::=",
51.1062 + /* 171 */ "inscollist_opt ::= LP inscollist RP",
51.1063 + /* 172 */ "inscollist ::= inscollist COMMA nm",
51.1064 + /* 173 */ "inscollist ::= nm",
51.1065 + /* 174 */ "expr ::= term",
51.1066 + /* 175 */ "expr ::= LP expr RP",
51.1067 + /* 176 */ "term ::= NULL",
51.1068 + /* 177 */ "expr ::= ID",
51.1069 + /* 178 */ "expr ::= JOIN_KW",
51.1070 + /* 179 */ "expr ::= nm DOT nm",
51.1071 + /* 180 */ "expr ::= nm DOT nm DOT nm",
51.1072 + /* 181 */ "term ::= INTEGER|FLOAT|BLOB",
51.1073 + /* 182 */ "term ::= STRING",
51.1074 + /* 183 */ "expr ::= REGISTER",
51.1075 + /* 184 */ "expr ::= VARIABLE",
51.1076 + /* 185 */ "expr ::= expr COLLATE id",
51.1077 + /* 186 */ "expr ::= CAST LP expr AS typetoken RP",
51.1078 + /* 187 */ "expr ::= ID LP distinct exprlist RP",
51.1079 + /* 188 */ "expr ::= ID LP STAR RP",
51.1080 + /* 189 */ "term ::= CTIME_KW",
51.1081 + /* 190 */ "expr ::= expr AND expr",
51.1082 + /* 191 */ "expr ::= expr OR expr",
51.1083 + /* 192 */ "expr ::= expr LT|GT|GE|LE expr",
51.1084 + /* 193 */ "expr ::= expr EQ|NE expr",
51.1085 + /* 194 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
51.1086 + /* 195 */ "expr ::= expr PLUS|MINUS expr",
51.1087 + /* 196 */ "expr ::= expr STAR|SLASH|REM expr",
51.1088 + /* 197 */ "expr ::= expr CONCAT expr",
51.1089 + /* 198 */ "likeop ::= LIKE_KW",
51.1090 + /* 199 */ "likeop ::= NOT LIKE_KW",
51.1091 + /* 200 */ "likeop ::= MATCH",
51.1092 + /* 201 */ "likeop ::= NOT MATCH",
51.1093 + /* 202 */ "escape ::= ESCAPE expr",
51.1094 + /* 203 */ "escape ::=",
51.1095 + /* 204 */ "expr ::= expr likeop expr escape",
51.1096 + /* 205 */ "expr ::= expr ISNULL|NOTNULL",
51.1097 + /* 206 */ "expr ::= expr IS NULL",
51.1098 + /* 207 */ "expr ::= expr NOT NULL",
51.1099 + /* 208 */ "expr ::= expr IS NOT NULL",
51.1100 + /* 209 */ "expr ::= NOT|BITNOT expr",
51.1101 + /* 210 */ "expr ::= MINUS expr",
51.1102 + /* 211 */ "expr ::= PLUS expr",
51.1103 + /* 212 */ "between_op ::= BETWEEN",
51.1104 + /* 213 */ "between_op ::= NOT BETWEEN",
51.1105 + /* 214 */ "expr ::= expr between_op expr AND expr",
51.1106 + /* 215 */ "in_op ::= IN",
51.1107 + /* 216 */ "in_op ::= NOT IN",
51.1108 + /* 217 */ "expr ::= expr in_op LP exprlist RP",
51.1109 + /* 218 */ "expr ::= LP select RP",
51.1110 + /* 219 */ "expr ::= expr in_op LP select RP",
51.1111 + /* 220 */ "expr ::= expr in_op nm dbnm",
51.1112 + /* 221 */ "expr ::= EXISTS LP select RP",
51.1113 + /* 222 */ "expr ::= CASE case_operand case_exprlist case_else END",
51.1114 + /* 223 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
51.1115 + /* 224 */ "case_exprlist ::= WHEN expr THEN expr",
51.1116 + /* 225 */ "case_else ::= ELSE expr",
51.1117 + /* 226 */ "case_else ::=",
51.1118 + /* 227 */ "case_operand ::= expr",
51.1119 + /* 228 */ "case_operand ::=",
51.1120 + /* 229 */ "exprlist ::= nexprlist",
51.1121 + /* 230 */ "exprlist ::=",
51.1122 + /* 231 */ "nexprlist ::= nexprlist COMMA expr",
51.1123 + /* 232 */ "nexprlist ::= expr",
51.1124 + /* 233 */ "cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
51.1125 + /* 234 */ "uniqueflag ::= UNIQUE",
51.1126 + /* 235 */ "uniqueflag ::=",
51.1127 + /* 236 */ "idxlist_opt ::=",
51.1128 + /* 237 */ "idxlist_opt ::= LP idxlist RP",
51.1129 + /* 238 */ "idxlist ::= idxlist COMMA idxitem collate sortorder",
51.1130 + /* 239 */ "idxlist ::= idxitem collate sortorder",
51.1131 + /* 240 */ "idxitem ::= nm",
51.1132 + /* 241 */ "collate ::=",
51.1133 + /* 242 */ "collate ::= COLLATE id",
51.1134 + /* 243 */ "cmd ::= DROP INDEX ifexists fullname",
51.1135 + /* 244 */ "cmd ::= VACUUM",
51.1136 + /* 245 */ "cmd ::= VACUUM nm",
51.1137 + /* 246 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
51.1138 + /* 247 */ "cmd ::= PRAGMA nm dbnm EQ ON",
51.1139 + /* 248 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
51.1140 + /* 249 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
51.1141 + /* 250 */ "cmd ::= PRAGMA nm dbnm",
51.1142 + /* 251 */ "nmnum ::= plus_num",
51.1143 + /* 252 */ "nmnum ::= nm",
51.1144 + /* 253 */ "plus_num ::= plus_opt number",
51.1145 + /* 254 */ "minus_num ::= MINUS number",
51.1146 + /* 255 */ "number ::= INTEGER|FLOAT",
51.1147 + /* 256 */ "plus_opt ::= PLUS",
51.1148 + /* 257 */ "plus_opt ::=",
51.1149 + /* 258 */ "cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END",
51.1150 + /* 259 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
51.1151 + /* 260 */ "trigger_time ::= BEFORE",
51.1152 + /* 261 */ "trigger_time ::= AFTER",
51.1153 + /* 262 */ "trigger_time ::= INSTEAD OF",
51.1154 + /* 263 */ "trigger_time ::=",
51.1155 + /* 264 */ "trigger_event ::= DELETE|INSERT",
51.1156 + /* 265 */ "trigger_event ::= UPDATE",
51.1157 + /* 266 */ "trigger_event ::= UPDATE OF inscollist",
51.1158 + /* 267 */ "foreach_clause ::=",
51.1159 + /* 268 */ "foreach_clause ::= FOR EACH ROW",
51.1160 + /* 269 */ "when_clause ::=",
51.1161 + /* 270 */ "when_clause ::= WHEN expr",
51.1162 + /* 271 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
51.1163 + /* 272 */ "trigger_cmd_list ::=",
51.1164 + /* 273 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt",
51.1165 + /* 274 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP",
51.1166 + /* 275 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt select",
51.1167 + /* 276 */ "trigger_cmd ::= DELETE FROM nm where_opt",
51.1168 + /* 277 */ "trigger_cmd ::= select",
51.1169 + /* 278 */ "expr ::= RAISE LP IGNORE RP",
51.1170 + /* 279 */ "expr ::= RAISE LP raisetype COMMA nm RP",
51.1171 + /* 280 */ "raisetype ::= ROLLBACK",
51.1172 + /* 281 */ "raisetype ::= ABORT",
51.1173 + /* 282 */ "raisetype ::= FAIL",
51.1174 + /* 283 */ "cmd ::= DROP TRIGGER ifexists fullname",
51.1175 + /* 284 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
51.1176 + /* 285 */ "cmd ::= DETACH database_kw_opt expr",
51.1177 + /* 286 */ "key_opt ::=",
51.1178 + /* 287 */ "key_opt ::= KEY expr",
51.1179 + /* 288 */ "database_kw_opt ::= DATABASE",
51.1180 + /* 289 */ "database_kw_opt ::=",
51.1181 + /* 290 */ "cmd ::= REINDEX",
51.1182 + /* 291 */ "cmd ::= REINDEX nm dbnm",
51.1183 + /* 292 */ "cmd ::= ANALYZE",
51.1184 + /* 293 */ "cmd ::= ANALYZE nm dbnm",
51.1185 + /* 294 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
51.1186 + /* 295 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
51.1187 + /* 296 */ "add_column_fullname ::= fullname",
51.1188 + /* 297 */ "kwcolumn_opt ::=",
51.1189 + /* 298 */ "kwcolumn_opt ::= COLUMNKW",
51.1190 + /* 299 */ "cmd ::= create_vtab",
51.1191 + /* 300 */ "cmd ::= create_vtab LP vtabarglist RP",
51.1192 + /* 301 */ "create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm",
51.1193 + /* 302 */ "vtabarglist ::= vtabarg",
51.1194 + /* 303 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
51.1195 + /* 304 */ "vtabarg ::=",
51.1196 + /* 305 */ "vtabarg ::= vtabarg vtabargtoken",
51.1197 + /* 306 */ "vtabargtoken ::= ANY",
51.1198 + /* 307 */ "vtabargtoken ::= lp anylist RP",
51.1199 + /* 308 */ "lp ::= LP",
51.1200 + /* 309 */ "anylist ::=",
51.1201 + /* 310 */ "anylist ::= anylist ANY",
51.1202 +};
51.1203 +#endif /* NDEBUG */
51.1204 +
51.1205 +
51.1206 +#if YYSTACKDEPTH<=0
51.1207 +/*
51.1208 +** Try to increase the size of the parser stack.
51.1209 +*/
51.1210 +static void yyGrowStack(yyParser *p){
51.1211 + int newSize;
51.1212 + yyStackEntry *pNew;
51.1213 +
51.1214 + newSize = p->yystksz*2 + 100;
51.1215 + pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
51.1216 + if( pNew ){
51.1217 + p->yystack = pNew;
51.1218 + p->yystksz = newSize;
51.1219 +#ifndef NDEBUG
51.1220 + if( yyTraceFILE ){
51.1221 + fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
51.1222 + yyTracePrompt, p->yystksz);
51.1223 + }
51.1224 +#endif
51.1225 + }
51.1226 +}
51.1227 +#endif
51.1228 +
51.1229 +/*
51.1230 +** This function allocates a new parser.
51.1231 +** The only argument is a pointer to a function which works like
51.1232 +** malloc.
51.1233 +**
51.1234 +** Inputs:
51.1235 +** A pointer to the function used to allocate memory.
51.1236 +**
51.1237 +** Outputs:
51.1238 +** A pointer to a parser. This pointer is used in subsequent calls
51.1239 +** to sqlite3Parser and sqlite3ParserFree.
51.1240 +*/
51.1241 +void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
51.1242 + yyParser *pParser;
51.1243 + pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
51.1244 + if( pParser ){
51.1245 + pParser->yyidx = -1;
51.1246 +#if YYSTACKDEPTH<=0
51.1247 + yyGrowStack(pParser);
51.1248 +#endif
51.1249 + }
51.1250 + return pParser;
51.1251 +}
51.1252 +
51.1253 +/* The following function deletes the value associated with a
51.1254 +** symbol. The symbol can be either a terminal or nonterminal.
51.1255 +** "yymajor" is the symbol code, and "yypminor" is a pointer to
51.1256 +** the value.
51.1257 +*/
51.1258 +static void yy_destructor(YYCODETYPE yymajor, YYMINORTYPE *yypminor){
51.1259 + switch( yymajor ){
51.1260 + /* Here is inserted the actions which take place when a
51.1261 + ** terminal or non-terminal is destroyed. This can happen
51.1262 + ** when the symbol is popped from the stack during a
51.1263 + ** reduce or during error processing or when a parser is
51.1264 + ** being destroyed before it is finished parsing.
51.1265 + **
51.1266 + ** Note: during a reduce, the only symbols destroyed are those
51.1267 + ** which appear on the RHS of the rule, but which are not used
51.1268 + ** inside the C code.
51.1269 + */
51.1270 + case 155:
51.1271 + case 189:
51.1272 + case 206:
51.1273 +#line 374 "parse.y"
51.1274 +{sqlite3SelectDelete((yypminor->yy219));}
51.1275 +#line 1274 "parse.c"
51.1276 + break;
51.1277 + case 169:
51.1278 + case 170:
51.1279 + case 194:
51.1280 + case 196:
51.1281 + case 204:
51.1282 + case 210:
51.1283 + case 218:
51.1284 + case 221:
51.1285 + case 223:
51.1286 + case 235:
51.1287 +#line 627 "parse.y"
51.1288 +{sqlite3ExprDelete((yypminor->yy172));}
51.1289 +#line 1288 "parse.c"
51.1290 + break;
51.1291 + case 174:
51.1292 + case 182:
51.1293 + case 192:
51.1294 + case 195:
51.1295 + case 197:
51.1296 + case 199:
51.1297 + case 209:
51.1298 + case 211:
51.1299 + case 212:
51.1300 + case 215:
51.1301 + case 216:
51.1302 + case 222:
51.1303 +#line 876 "parse.y"
51.1304 +{sqlite3ExprListDelete((yypminor->yy174));}
51.1305 +#line 1304 "parse.c"
51.1306 + break;
51.1307 + case 188:
51.1308 + case 193:
51.1309 + case 201:
51.1310 + case 202:
51.1311 +#line 489 "parse.y"
51.1312 +{sqlite3SrcListDelete((yypminor->yy373));}
51.1313 +#line 1312 "parse.c"
51.1314 + break;
51.1315 + case 205:
51.1316 + case 208:
51.1317 + case 214:
51.1318 +#line 506 "parse.y"
51.1319 +{sqlite3IdListDelete((yypminor->yy432));}
51.1320 +#line 1319 "parse.c"
51.1321 + break;
51.1322 + case 231:
51.1323 + case 236:
51.1324 +#line 979 "parse.y"
51.1325 +{sqlite3DeleteTriggerStep((yypminor->yy243));}
51.1326 +#line 1325 "parse.c"
51.1327 + break;
51.1328 + case 233:
51.1329 +#line 965 "parse.y"
51.1330 +{sqlite3IdListDelete((yypminor->yy370).b);}
51.1331 +#line 1330 "parse.c"
51.1332 + break;
51.1333 + case 238:
51.1334 +#line 1052 "parse.y"
51.1335 +{sqlite3ExprDelete((yypminor->yy386));}
51.1336 +#line 1335 "parse.c"
51.1337 + break;
51.1338 + default: break; /* If no destructor action specified: do nothing */
51.1339 + }
51.1340 +}
51.1341 +
51.1342 +/*
51.1343 +** Pop the parser's stack once.
51.1344 +**
51.1345 +** If there is a destructor routine associated with the token which
51.1346 +** is popped from the stack, then call it.
51.1347 +**
51.1348 +** Return the major token number for the symbol popped.
51.1349 +*/
51.1350 +static int yy_pop_parser_stack(yyParser *pParser){
51.1351 + YYCODETYPE yymajor;
51.1352 + yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
51.1353 +
51.1354 + if( pParser->yyidx<0 ) return 0;
51.1355 +#ifndef NDEBUG
51.1356 + if( yyTraceFILE && pParser->yyidx>=0 ){
51.1357 + fprintf(yyTraceFILE,"%sPopping %s\n",
51.1358 + yyTracePrompt,
51.1359 + yyTokenName[yytos->major]);
51.1360 + }
51.1361 +#endif
51.1362 + yymajor = yytos->major;
51.1363 + yy_destructor( yymajor, &yytos->minor);
51.1364 + pParser->yyidx--;
51.1365 + return yymajor;
51.1366 +}
51.1367 +
51.1368 +/*
51.1369 +** Deallocate and destroy a parser. Destructors are all called for
51.1370 +** all stack elements before shutting the parser down.
51.1371 +**
51.1372 +** Inputs:
51.1373 +** <ul>
51.1374 +** <li> A pointer to the parser. This should be a pointer
51.1375 +** obtained from sqlite3ParserAlloc.
51.1376 +** <li> A pointer to a function used to reclaim memory obtained
51.1377 +** from malloc.
51.1378 +** </ul>
51.1379 +*/
51.1380 +void sqlite3ParserFree(
51.1381 + void *p, /* The parser to be deleted */
51.1382 + void (*freeProc)(void*) /* Function used to reclaim memory */
51.1383 +){
51.1384 + yyParser *pParser = (yyParser*)p;
51.1385 + if( pParser==0 ) return;
51.1386 + while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
51.1387 +#if YYSTACKDEPTH<=0
51.1388 + free(pParser->yystack);
51.1389 +#endif
51.1390 + (*freeProc)((void*)pParser);
51.1391 +}
51.1392 +
51.1393 +/*
51.1394 +** Find the appropriate action for a parser given the terminal
51.1395 +** look-ahead token iLookAhead.
51.1396 +**
51.1397 +** If the look-ahead token is YYNOCODE, then check to see if the action is
51.1398 +** independent of the look-ahead. If it is, return the action, otherwise
51.1399 +** return YY_NO_ACTION.
51.1400 +*/
51.1401 +static int yy_find_shift_action(
51.1402 + yyParser *pParser, /* The parser */
51.1403 + YYCODETYPE iLookAhead /* The look-ahead token */
51.1404 +){
51.1405 + int i;
51.1406 + int stateno = pParser->yystack[pParser->yyidx].stateno;
51.1407 +
51.1408 + if( stateno>YY_SHIFT_MAX || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
51.1409 + return yy_default[stateno];
51.1410 + }
51.1411 + if( iLookAhead==YYNOCODE ){
51.1412 + return YY_NO_ACTION;
51.1413 + }
51.1414 + i += iLookAhead;
51.1415 + if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
51.1416 + if( iLookAhead>0 ){
51.1417 +#ifdef YYFALLBACK
51.1418 + int iFallback; /* Fallback token */
51.1419 + if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
51.1420 + && (iFallback = yyFallback[iLookAhead])!=0 ){
51.1421 +#ifndef NDEBUG
51.1422 + if( yyTraceFILE ){
51.1423 + fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
51.1424 + yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
51.1425 + }
51.1426 +#endif
51.1427 + return yy_find_shift_action(pParser, iFallback);
51.1428 + }
51.1429 +#endif
51.1430 +#ifdef YYWILDCARD
51.1431 + {
51.1432 + int j = i - iLookAhead + YYWILDCARD;
51.1433 + if( j>=0 && j<YY_SZ_ACTTAB && yy_lookahead[j]==YYWILDCARD ){
51.1434 +#ifndef NDEBUG
51.1435 + if( yyTraceFILE ){
51.1436 + fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
51.1437 + yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
51.1438 + }
51.1439 +#endif /* NDEBUG */
51.1440 + return yy_action[j];
51.1441 + }
51.1442 + }
51.1443 +#endif /* YYWILDCARD */
51.1444 + }
51.1445 + return yy_default[stateno];
51.1446 + }else{
51.1447 + return yy_action[i];
51.1448 + }
51.1449 +}
51.1450 +
51.1451 +/*
51.1452 +** Find the appropriate action for a parser given the non-terminal
51.1453 +** look-ahead token iLookAhead.
51.1454 +**
51.1455 +** If the look-ahead token is YYNOCODE, then check to see if the action is
51.1456 +** independent of the look-ahead. If it is, return the action, otherwise
51.1457 +** return YY_NO_ACTION.
51.1458 +*/
51.1459 +static int yy_find_reduce_action(
51.1460 + int stateno, /* Current state number */
51.1461 + YYCODETYPE iLookAhead /* The look-ahead token */
51.1462 +){
51.1463 + int i;
51.1464 + /* int stateno = pParser->yystack[pParser->yyidx].stateno; */
51.1465 +
51.1466 + if( stateno>YY_REDUCE_MAX ||
51.1467 + (i = yy_reduce_ofst[stateno])==YY_REDUCE_USE_DFLT ){
51.1468 + return yy_default[stateno];
51.1469 + }
51.1470 + if( iLookAhead==YYNOCODE ){
51.1471 + return YY_NO_ACTION;
51.1472 + }
51.1473 + i += iLookAhead;
51.1474 + if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
51.1475 + return yy_default[stateno];
51.1476 + }else{
51.1477 + return yy_action[i];
51.1478 + }
51.1479 +}
51.1480 +
51.1481 +/*
51.1482 +** The following routine is called if the stack overflows.
51.1483 +*/
51.1484 +static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
51.1485 + sqlite3ParserARG_FETCH;
51.1486 + yypParser->yyidx--;
51.1487 +#ifndef NDEBUG
51.1488 + if( yyTraceFILE ){
51.1489 + fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
51.1490 + }
51.1491 +#endif
51.1492 + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
51.1493 + /* Here code is inserted which will execute if the parser
51.1494 + ** stack every overflows */
51.1495 +#line 44 "parse.y"
51.1496 +
51.1497 + sqlite3ErrorMsg(pParse, "parser stack overflow");
51.1498 + pParse->parseError = 1;
51.1499 +#line 1499 "parse.c"
51.1500 + sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
51.1501 +}
51.1502 +
51.1503 +/*
51.1504 +** Perform a shift action.
51.1505 +*/
51.1506 +static void yy_shift(
51.1507 + yyParser *yypParser, /* The parser to be shifted */
51.1508 + int yyNewState, /* The new state to shift in */
51.1509 + int yyMajor, /* The major token to shift in */
51.1510 + YYMINORTYPE *yypMinor /* Pointer ot the minor token to shift in */
51.1511 +){
51.1512 + yyStackEntry *yytos;
51.1513 + yypParser->yyidx++;
51.1514 +#if YYSTACKDEPTH>0
51.1515 + if( yypParser->yyidx>=YYSTACKDEPTH ){
51.1516 + yyStackOverflow(yypParser, yypMinor);
51.1517 + return;
51.1518 + }
51.1519 +#else
51.1520 + if( yypParser->yyidx>=yypParser->yystksz ){
51.1521 + yyGrowStack(yypParser);
51.1522 + if( yypParser->yyidx>=yypParser->yystksz ){
51.1523 + yyStackOverflow(yypParser, yypMinor);
51.1524 + return;
51.1525 + }
51.1526 + }
51.1527 +#endif
51.1528 + yytos = &yypParser->yystack[yypParser->yyidx];
51.1529 + yytos->stateno = yyNewState;
51.1530 + yytos->major = yyMajor;
51.1531 + yytos->minor = *yypMinor;
51.1532 +#ifndef NDEBUG
51.1533 + if( yyTraceFILE && yypParser->yyidx>0 ){
51.1534 + int i;
51.1535 + fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
51.1536 + fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
51.1537 + for(i=1; i<=yypParser->yyidx; i++)
51.1538 + fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
51.1539 + fprintf(yyTraceFILE,"\n");
51.1540 + }
51.1541 +#endif
51.1542 +}
51.1543 +
51.1544 +/* The following table contains information about every rule that
51.1545 +** is used during the reduce.
51.1546 +*/
51.1547 +static const struct {
51.1548 + YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
51.1549 + unsigned char nrhs; /* Number of right-hand side symbols in the rule */
51.1550 +} yyRuleInfo[] = {
51.1551 + { 139, 1 },
51.1552 + { 140, 2 },
51.1553 + { 140, 1 },
51.1554 + { 142, 1 },
51.1555 + { 141, 1 },
51.1556 + { 141, 3 },
51.1557 + { 144, 0 },
51.1558 + { 144, 1 },
51.1559 + { 144, 3 },
51.1560 + { 143, 3 },
51.1561 + { 146, 0 },
51.1562 + { 146, 1 },
51.1563 + { 146, 2 },
51.1564 + { 145, 0 },
51.1565 + { 145, 1 },
51.1566 + { 145, 1 },
51.1567 + { 145, 1 },
51.1568 + { 143, 2 },
51.1569 + { 143, 2 },
51.1570 + { 143, 2 },
51.1571 + { 143, 2 },
51.1572 + { 148, 6 },
51.1573 + { 151, 0 },
51.1574 + { 151, 3 },
51.1575 + { 150, 1 },
51.1576 + { 150, 0 },
51.1577 + { 149, 4 },
51.1578 + { 149, 2 },
51.1579 + { 153, 3 },
51.1580 + { 153, 1 },
51.1581 + { 156, 3 },
51.1582 + { 157, 1 },
51.1583 + { 160, 1 },
51.1584 + { 161, 1 },
51.1585 + { 147, 1 },
51.1586 + { 147, 1 },
51.1587 + { 147, 1 },
51.1588 + { 158, 0 },
51.1589 + { 158, 1 },
51.1590 + { 162, 1 },
51.1591 + { 162, 4 },
51.1592 + { 162, 6 },
51.1593 + { 163, 1 },
51.1594 + { 163, 2 },
51.1595 + { 164, 1 },
51.1596 + { 164, 1 },
51.1597 + { 159, 2 },
51.1598 + { 159, 0 },
51.1599 + { 167, 3 },
51.1600 + { 167, 1 },
51.1601 + { 168, 2 },
51.1602 + { 168, 4 },
51.1603 + { 168, 3 },
51.1604 + { 168, 3 },
51.1605 + { 168, 2 },
51.1606 + { 168, 2 },
51.1607 + { 168, 3 },
51.1608 + { 168, 5 },
51.1609 + { 168, 2 },
51.1610 + { 168, 4 },
51.1611 + { 168, 4 },
51.1612 + { 168, 1 },
51.1613 + { 168, 2 },
51.1614 + { 173, 0 },
51.1615 + { 173, 1 },
51.1616 + { 175, 0 },
51.1617 + { 175, 2 },
51.1618 + { 177, 2 },
51.1619 + { 177, 3 },
51.1620 + { 177, 3 },
51.1621 + { 177, 3 },
51.1622 + { 178, 2 },
51.1623 + { 178, 2 },
51.1624 + { 178, 1 },
51.1625 + { 178, 1 },
51.1626 + { 176, 3 },
51.1627 + { 176, 2 },
51.1628 + { 179, 0 },
51.1629 + { 179, 2 },
51.1630 + { 179, 2 },
51.1631 + { 154, 0 },
51.1632 + { 154, 2 },
51.1633 + { 180, 3 },
51.1634 + { 180, 2 },
51.1635 + { 180, 1 },
51.1636 + { 181, 2 },
51.1637 + { 181, 7 },
51.1638 + { 181, 5 },
51.1639 + { 181, 5 },
51.1640 + { 181, 10 },
51.1641 + { 183, 0 },
51.1642 + { 183, 1 },
51.1643 + { 171, 0 },
51.1644 + { 171, 3 },
51.1645 + { 184, 0 },
51.1646 + { 184, 2 },
51.1647 + { 185, 1 },
51.1648 + { 185, 1 },
51.1649 + { 185, 1 },
51.1650 + { 143, 4 },
51.1651 + { 187, 2 },
51.1652 + { 187, 0 },
51.1653 + { 143, 8 },
51.1654 + { 143, 4 },
51.1655 + { 143, 1 },
51.1656 + { 155, 1 },
51.1657 + { 155, 3 },
51.1658 + { 190, 1 },
51.1659 + { 190, 2 },
51.1660 + { 190, 1 },
51.1661 + { 189, 9 },
51.1662 + { 191, 1 },
51.1663 + { 191, 1 },
51.1664 + { 191, 0 },
51.1665 + { 199, 2 },
51.1666 + { 199, 0 },
51.1667 + { 192, 3 },
51.1668 + { 192, 2 },
51.1669 + { 192, 4 },
51.1670 + { 200, 2 },
51.1671 + { 200, 1 },
51.1672 + { 200, 0 },
51.1673 + { 193, 0 },
51.1674 + { 193, 2 },
51.1675 + { 202, 2 },
51.1676 + { 202, 0 },
51.1677 + { 201, 6 },
51.1678 + { 201, 7 },
51.1679 + { 206, 1 },
51.1680 + { 206, 1 },
51.1681 + { 152, 0 },
51.1682 + { 152, 2 },
51.1683 + { 188, 2 },
51.1684 + { 203, 1 },
51.1685 + { 203, 2 },
51.1686 + { 203, 3 },
51.1687 + { 203, 4 },
51.1688 + { 204, 2 },
51.1689 + { 204, 0 },
51.1690 + { 205, 4 },
51.1691 + { 205, 0 },
51.1692 + { 197, 0 },
51.1693 + { 197, 3 },
51.1694 + { 209, 4 },
51.1695 + { 209, 2 },
51.1696 + { 210, 1 },
51.1697 + { 172, 1 },
51.1698 + { 172, 1 },
51.1699 + { 172, 0 },
51.1700 + { 195, 0 },
51.1701 + { 195, 3 },
51.1702 + { 196, 0 },
51.1703 + { 196, 2 },
51.1704 + { 198, 0 },
51.1705 + { 198, 2 },
51.1706 + { 198, 4 },
51.1707 + { 198, 4 },
51.1708 + { 143, 4 },
51.1709 + { 194, 0 },
51.1710 + { 194, 2 },
51.1711 + { 143, 6 },
51.1712 + { 212, 5 },
51.1713 + { 212, 3 },
51.1714 + { 143, 8 },
51.1715 + { 143, 5 },
51.1716 + { 143, 6 },
51.1717 + { 213, 2 },
51.1718 + { 213, 1 },
51.1719 + { 215, 3 },
51.1720 + { 215, 1 },
51.1721 + { 214, 0 },
51.1722 + { 214, 3 },
51.1723 + { 208, 3 },
51.1724 + { 208, 1 },
51.1725 + { 170, 1 },
51.1726 + { 170, 3 },
51.1727 + { 169, 1 },
51.1728 + { 170, 1 },
51.1729 + { 170, 1 },
51.1730 + { 170, 3 },
51.1731 + { 170, 5 },
51.1732 + { 169, 1 },
51.1733 + { 169, 1 },
51.1734 + { 170, 1 },
51.1735 + { 170, 1 },
51.1736 + { 170, 3 },
51.1737 + { 170, 6 },
51.1738 + { 170, 5 },
51.1739 + { 170, 4 },
51.1740 + { 169, 1 },
51.1741 + { 170, 3 },
51.1742 + { 170, 3 },
51.1743 + { 170, 3 },
51.1744 + { 170, 3 },
51.1745 + { 170, 3 },
51.1746 + { 170, 3 },
51.1747 + { 170, 3 },
51.1748 + { 170, 3 },
51.1749 + { 217, 1 },
51.1750 + { 217, 2 },
51.1751 + { 217, 1 },
51.1752 + { 217, 2 },
51.1753 + { 218, 2 },
51.1754 + { 218, 0 },
51.1755 + { 170, 4 },
51.1756 + { 170, 2 },
51.1757 + { 170, 3 },
51.1758 + { 170, 3 },
51.1759 + { 170, 4 },
51.1760 + { 170, 2 },
51.1761 + { 170, 2 },
51.1762 + { 170, 2 },
51.1763 + { 219, 1 },
51.1764 + { 219, 2 },
51.1765 + { 170, 5 },
51.1766 + { 220, 1 },
51.1767 + { 220, 2 },
51.1768 + { 170, 5 },
51.1769 + { 170, 3 },
51.1770 + { 170, 5 },
51.1771 + { 170, 4 },
51.1772 + { 170, 4 },
51.1773 + { 170, 5 },
51.1774 + { 222, 5 },
51.1775 + { 222, 4 },
51.1776 + { 223, 2 },
51.1777 + { 223, 0 },
51.1778 + { 221, 1 },
51.1779 + { 221, 0 },
51.1780 + { 216, 1 },
51.1781 + { 216, 0 },
51.1782 + { 211, 3 },
51.1783 + { 211, 1 },
51.1784 + { 143, 11 },
51.1785 + { 224, 1 },
51.1786 + { 224, 0 },
51.1787 + { 174, 0 },
51.1788 + { 174, 3 },
51.1789 + { 182, 5 },
51.1790 + { 182, 3 },
51.1791 + { 225, 1 },
51.1792 + { 226, 0 },
51.1793 + { 226, 2 },
51.1794 + { 143, 4 },
51.1795 + { 143, 1 },
51.1796 + { 143, 2 },
51.1797 + { 143, 5 },
51.1798 + { 143, 5 },
51.1799 + { 143, 5 },
51.1800 + { 143, 6 },
51.1801 + { 143, 3 },
51.1802 + { 227, 1 },
51.1803 + { 227, 1 },
51.1804 + { 165, 2 },
51.1805 + { 166, 2 },
51.1806 + { 229, 1 },
51.1807 + { 228, 1 },
51.1808 + { 228, 0 },
51.1809 + { 143, 5 },
51.1810 + { 230, 11 },
51.1811 + { 232, 1 },
51.1812 + { 232, 1 },
51.1813 + { 232, 2 },
51.1814 + { 232, 0 },
51.1815 + { 233, 1 },
51.1816 + { 233, 1 },
51.1817 + { 233, 3 },
51.1818 + { 234, 0 },
51.1819 + { 234, 3 },
51.1820 + { 235, 0 },
51.1821 + { 235, 2 },
51.1822 + { 231, 3 },
51.1823 + { 231, 0 },
51.1824 + { 236, 6 },
51.1825 + { 236, 8 },
51.1826 + { 236, 5 },
51.1827 + { 236, 4 },
51.1828 + { 236, 1 },
51.1829 + { 170, 4 },
51.1830 + { 170, 6 },
51.1831 + { 186, 1 },
51.1832 + { 186, 1 },
51.1833 + { 186, 1 },
51.1834 + { 143, 4 },
51.1835 + { 143, 6 },
51.1836 + { 143, 3 },
51.1837 + { 238, 0 },
51.1838 + { 238, 2 },
51.1839 + { 237, 1 },
51.1840 + { 237, 0 },
51.1841 + { 143, 1 },
51.1842 + { 143, 3 },
51.1843 + { 143, 1 },
51.1844 + { 143, 3 },
51.1845 + { 143, 6 },
51.1846 + { 143, 6 },
51.1847 + { 239, 1 },
51.1848 + { 240, 0 },
51.1849 + { 240, 1 },
51.1850 + { 143, 1 },
51.1851 + { 143, 4 },
51.1852 + { 241, 7 },
51.1853 + { 242, 1 },
51.1854 + { 242, 3 },
51.1855 + { 243, 0 },
51.1856 + { 243, 2 },
51.1857 + { 244, 1 },
51.1858 + { 244, 3 },
51.1859 + { 245, 1 },
51.1860 + { 246, 0 },
51.1861 + { 246, 2 },
51.1862 +};
51.1863 +
51.1864 +static void yy_accept(yyParser*); /* Forward Declaration */
51.1865 +
51.1866 +/*
51.1867 +** Perform a reduce action and the shift that must immediately
51.1868 +** follow the reduce.
51.1869 +*/
51.1870 +static void yy_reduce(
51.1871 + yyParser *yypParser, /* The parser */
51.1872 + int yyruleno /* Number of the rule by which to reduce */
51.1873 +){
51.1874 + int yygoto; /* The next state */
51.1875 + int yyact; /* The next action */
51.1876 + YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
51.1877 + yyStackEntry *yymsp; /* The top of the parser's stack */
51.1878 + int yysize; /* Amount to pop the stack */
51.1879 + sqlite3ParserARG_FETCH;
51.1880 + yymsp = &yypParser->yystack[yypParser->yyidx];
51.1881 +#ifndef NDEBUG
51.1882 + if( yyTraceFILE && yyruleno>=0
51.1883 + && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
51.1884 + fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
51.1885 + yyRuleName[yyruleno]);
51.1886 + }
51.1887 +#endif /* NDEBUG */
51.1888 +
51.1889 + /* Silence complaints from purify about yygotominor being uninitialized
51.1890 + ** in some cases when it is copied into the stack after the following
51.1891 + ** switch. yygotominor is uninitialized when a rule reduces that does
51.1892 + ** not set the value of its left-hand side nonterminal. Leaving the
51.1893 + ** value of the nonterminal uninitialized is utterly harmless as long
51.1894 + ** as the value is never used. So really the only thing this code
51.1895 + ** accomplishes is to quieten purify.
51.1896 + **
51.1897 + ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
51.1898 + ** without this code, their parser segfaults. I'm not sure what there
51.1899 + ** parser is doing to make this happen. This is the second bug report
51.1900 + ** from wireshark this week. Clearly they are stressing Lemon in ways
51.1901 + ** that it has not been previously stressed... (SQLite ticket #2172)
51.1902 + */
51.1903 + memset(&yygotominor, 0, sizeof(yygotominor));
51.1904 +
51.1905 +
51.1906 + switch( yyruleno ){
51.1907 + /* Beginning here are the reduction cases. A typical example
51.1908 + ** follows:
51.1909 + ** case 0:
51.1910 + ** #line <lineno> <grammarfile>
51.1911 + ** { ... } // User supplied code
51.1912 + ** #line <lineno> <thisfile>
51.1913 + ** break;
51.1914 + */
51.1915 + case 0:
51.1916 + case 1:
51.1917 + case 2:
51.1918 + case 4:
51.1919 + case 5:
51.1920 + case 10:
51.1921 + case 11:
51.1922 + case 12:
51.1923 + case 20:
51.1924 + case 28:
51.1925 + case 29:
51.1926 + case 37:
51.1927 + case 44:
51.1928 + case 45:
51.1929 + case 46:
51.1930 + case 47:
51.1931 + case 48:
51.1932 + case 49:
51.1933 + case 55:
51.1934 + case 82:
51.1935 + case 83:
51.1936 + case 84:
51.1937 + case 85:
51.1938 + case 256:
51.1939 + case 257:
51.1940 + case 267:
51.1941 + case 268:
51.1942 + case 288:
51.1943 + case 289:
51.1944 + case 297:
51.1945 + case 298:
51.1946 + case 302:
51.1947 + case 303:
51.1948 + case 305:
51.1949 + case 309:
51.1950 +#line 97 "parse.y"
51.1951 +{
51.1952 +}
51.1953 +#line 1953 "parse.c"
51.1954 + break;
51.1955 + case 3:
51.1956 +#line 100 "parse.y"
51.1957 +{ sqlite3FinishCoding(pParse); }
51.1958 +#line 1958 "parse.c"
51.1959 + break;
51.1960 + case 6:
51.1961 +#line 103 "parse.y"
51.1962 +{ sqlite3BeginParse(pParse, 0); }
51.1963 +#line 1963 "parse.c"
51.1964 + break;
51.1965 + case 7:
51.1966 +#line 105 "parse.y"
51.1967 +{ sqlite3BeginParse(pParse, 1); }
51.1968 +#line 1968 "parse.c"
51.1969 + break;
51.1970 + case 8:
51.1971 +#line 106 "parse.y"
51.1972 +{ sqlite3BeginParse(pParse, 2); }
51.1973 +#line 1973 "parse.c"
51.1974 + break;
51.1975 + case 9:
51.1976 +#line 112 "parse.y"
51.1977 +{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy46);}
51.1978 +#line 1978 "parse.c"
51.1979 + break;
51.1980 + case 13:
51.1981 +#line 117 "parse.y"
51.1982 +{yygotominor.yy46 = TK_DEFERRED;}
51.1983 +#line 1983 "parse.c"
51.1984 + break;
51.1985 + case 14:
51.1986 + case 15:
51.1987 + case 16:
51.1988 + case 107:
51.1989 + case 109:
51.1990 +#line 118 "parse.y"
51.1991 +{yygotominor.yy46 = yymsp[0].major;}
51.1992 +#line 1992 "parse.c"
51.1993 + break;
51.1994 + case 17:
51.1995 + case 18:
51.1996 +#line 121 "parse.y"
51.1997 +{sqlite3CommitTransaction(pParse);}
51.1998 +#line 1998 "parse.c"
51.1999 + break;
51.2000 + case 19:
51.2001 +#line 123 "parse.y"
51.2002 +{sqlite3RollbackTransaction(pParse);}
51.2003 +#line 2003 "parse.c"
51.2004 + break;
51.2005 + case 21:
51.2006 +#line 128 "parse.y"
51.2007 +{
51.2008 + sqlite3StartTable(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410,yymsp[-4].minor.yy46,0,0,yymsp[-2].minor.yy46);
51.2009 +}
51.2010 +#line 2010 "parse.c"
51.2011 + break;
51.2012 + case 22:
51.2013 + case 25:
51.2014 + case 63:
51.2015 + case 77:
51.2016 + case 79:
51.2017 + case 90:
51.2018 + case 101:
51.2019 + case 112:
51.2020 + case 113:
51.2021 + case 212:
51.2022 + case 215:
51.2023 +#line 132 "parse.y"
51.2024 +{yygotominor.yy46 = 0;}
51.2025 +#line 2025 "parse.c"
51.2026 + break;
51.2027 + case 23:
51.2028 + case 24:
51.2029 + case 64:
51.2030 + case 78:
51.2031 + case 100:
51.2032 + case 111:
51.2033 + case 213:
51.2034 + case 216:
51.2035 +#line 133 "parse.y"
51.2036 +{yygotominor.yy46 = 1;}
51.2037 +#line 2037 "parse.c"
51.2038 + break;
51.2039 + case 26:
51.2040 +#line 139 "parse.y"
51.2041 +{
51.2042 + sqlite3EndTable(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy0,0);
51.2043 +}
51.2044 +#line 2044 "parse.c"
51.2045 + break;
51.2046 + case 27:
51.2047 +#line 142 "parse.y"
51.2048 +{
51.2049 + sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy219);
51.2050 + sqlite3SelectDelete(yymsp[0].minor.yy219);
51.2051 +}
51.2052 +#line 2052 "parse.c"
51.2053 + break;
51.2054 + case 30:
51.2055 +#line 154 "parse.y"
51.2056 +{
51.2057 + yygotominor.yy410.z = yymsp[-2].minor.yy410.z;
51.2058 + yygotominor.yy410.n = (pParse->sLastToken.z-yymsp[-2].minor.yy410.z) + pParse->sLastToken.n;
51.2059 +}
51.2060 +#line 2060 "parse.c"
51.2061 + break;
51.2062 + case 31:
51.2063 +#line 158 "parse.y"
51.2064 +{
51.2065 + sqlite3AddColumn(pParse,&yymsp[0].minor.yy410);
51.2066 + yygotominor.yy410 = yymsp[0].minor.yy410;
51.2067 +}
51.2068 +#line 2068 "parse.c"
51.2069 + break;
51.2070 + case 32:
51.2071 + case 33:
51.2072 + case 34:
51.2073 + case 35:
51.2074 + case 36:
51.2075 + case 255:
51.2076 +#line 168 "parse.y"
51.2077 +{yygotominor.yy410 = yymsp[0].minor.yy0;}
51.2078 +#line 2078 "parse.c"
51.2079 + break;
51.2080 + case 38:
51.2081 +#line 229 "parse.y"
51.2082 +{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy410);}
51.2083 +#line 2083 "parse.c"
51.2084 + break;
51.2085 + case 39:
51.2086 + case 42:
51.2087 + case 119:
51.2088 + case 120:
51.2089 + case 131:
51.2090 + case 240:
51.2091 + case 242:
51.2092 + case 251:
51.2093 + case 252:
51.2094 + case 253:
51.2095 + case 254:
51.2096 +#line 230 "parse.y"
51.2097 +{yygotominor.yy410 = yymsp[0].minor.yy410;}
51.2098 +#line 2098 "parse.c"
51.2099 + break;
51.2100 + case 40:
51.2101 +#line 231 "parse.y"
51.2102 +{
51.2103 + yygotominor.yy410.z = yymsp[-3].minor.yy410.z;
51.2104 + yygotominor.yy410.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy410.z;
51.2105 +}
51.2106 +#line 2106 "parse.c"
51.2107 + break;
51.2108 + case 41:
51.2109 +#line 235 "parse.y"
51.2110 +{
51.2111 + yygotominor.yy410.z = yymsp[-5].minor.yy410.z;
51.2112 + yygotominor.yy410.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy410.z;
51.2113 +}
51.2114 +#line 2114 "parse.c"
51.2115 + break;
51.2116 + case 43:
51.2117 +#line 241 "parse.y"
51.2118 +{yygotominor.yy410.z=yymsp[-1].minor.yy410.z; yygotominor.yy410.n=yymsp[0].minor.yy410.n+(yymsp[0].minor.yy410.z-yymsp[-1].minor.yy410.z);}
51.2119 +#line 2119 "parse.c"
51.2120 + break;
51.2121 + case 50:
51.2122 + case 52:
51.2123 +#line 252 "parse.y"
51.2124 +{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy172);}
51.2125 +#line 2125 "parse.c"
51.2126 + break;
51.2127 + case 51:
51.2128 +#line 253 "parse.y"
51.2129 +{sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy172);}
51.2130 +#line 2130 "parse.c"
51.2131 + break;
51.2132 + case 53:
51.2133 +#line 255 "parse.y"
51.2134 +{
51.2135 + Expr *p = sqlite3Expr(TK_UMINUS, yymsp[0].minor.yy172, 0, 0);
51.2136 + sqlite3AddDefaultValue(pParse,p);
51.2137 +}
51.2138 +#line 2138 "parse.c"
51.2139 + break;
51.2140 + case 54:
51.2141 +#line 259 "parse.y"
51.2142 +{
51.2143 + Expr *p = sqlite3Expr(TK_STRING, 0, 0, &yymsp[0].minor.yy410);
51.2144 + sqlite3AddDefaultValue(pParse,p);
51.2145 +}
51.2146 +#line 2146 "parse.c"
51.2147 + break;
51.2148 + case 56:
51.2149 +#line 268 "parse.y"
51.2150 +{sqlite3AddNotNull(pParse, yymsp[0].minor.yy46);}
51.2151 +#line 2151 "parse.c"
51.2152 + break;
51.2153 + case 57:
51.2154 +#line 270 "parse.y"
51.2155 +{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy46,yymsp[0].minor.yy46,yymsp[-2].minor.yy46);}
51.2156 +#line 2156 "parse.c"
51.2157 + break;
51.2158 + case 58:
51.2159 +#line 271 "parse.y"
51.2160 +{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy46,0,0,0,0);}
51.2161 +#line 2161 "parse.c"
51.2162 + break;
51.2163 + case 59:
51.2164 +#line 272 "parse.y"
51.2165 +{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy172);}
51.2166 +#line 2166 "parse.c"
51.2167 + break;
51.2168 + case 60:
51.2169 +#line 274 "parse.y"
51.2170 +{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy410,yymsp[-1].minor.yy174,yymsp[0].minor.yy46);}
51.2171 +#line 2171 "parse.c"
51.2172 + break;
51.2173 + case 61:
51.2174 +#line 275 "parse.y"
51.2175 +{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy46);}
51.2176 +#line 2176 "parse.c"
51.2177 + break;
51.2178 + case 62:
51.2179 +#line 276 "parse.y"
51.2180 +{sqlite3AddCollateType(pParse, (char*)yymsp[0].minor.yy410.z, yymsp[0].minor.yy410.n);}
51.2181 +#line 2181 "parse.c"
51.2182 + break;
51.2183 + case 65:
51.2184 +#line 289 "parse.y"
51.2185 +{ yygotominor.yy46 = OE_Restrict * 0x010101; }
51.2186 +#line 2186 "parse.c"
51.2187 + break;
51.2188 + case 66:
51.2189 +#line 290 "parse.y"
51.2190 +{ yygotominor.yy46 = (yymsp[-1].minor.yy46 & yymsp[0].minor.yy405.mask) | yymsp[0].minor.yy405.value; }
51.2191 +#line 2191 "parse.c"
51.2192 + break;
51.2193 + case 67:
51.2194 +#line 292 "parse.y"
51.2195 +{ yygotominor.yy405.value = 0; yygotominor.yy405.mask = 0x000000; }
51.2196 +#line 2196 "parse.c"
51.2197 + break;
51.2198 + case 68:
51.2199 +#line 293 "parse.y"
51.2200 +{ yygotominor.yy405.value = yymsp[0].minor.yy46; yygotominor.yy405.mask = 0x0000ff; }
51.2201 +#line 2201 "parse.c"
51.2202 + break;
51.2203 + case 69:
51.2204 +#line 294 "parse.y"
51.2205 +{ yygotominor.yy405.value = yymsp[0].minor.yy46<<8; yygotominor.yy405.mask = 0x00ff00; }
51.2206 +#line 2206 "parse.c"
51.2207 + break;
51.2208 + case 70:
51.2209 +#line 295 "parse.y"
51.2210 +{ yygotominor.yy405.value = yymsp[0].minor.yy46<<16; yygotominor.yy405.mask = 0xff0000; }
51.2211 +#line 2211 "parse.c"
51.2212 + break;
51.2213 + case 71:
51.2214 +#line 297 "parse.y"
51.2215 +{ yygotominor.yy46 = OE_SetNull; }
51.2216 +#line 2216 "parse.c"
51.2217 + break;
51.2218 + case 72:
51.2219 +#line 298 "parse.y"
51.2220 +{ yygotominor.yy46 = OE_SetDflt; }
51.2221 +#line 2221 "parse.c"
51.2222 + break;
51.2223 + case 73:
51.2224 +#line 299 "parse.y"
51.2225 +{ yygotominor.yy46 = OE_Cascade; }
51.2226 +#line 2226 "parse.c"
51.2227 + break;
51.2228 + case 74:
51.2229 +#line 300 "parse.y"
51.2230 +{ yygotominor.yy46 = OE_Restrict; }
51.2231 +#line 2231 "parse.c"
51.2232 + break;
51.2233 + case 75:
51.2234 + case 76:
51.2235 + case 91:
51.2236 + case 93:
51.2237 + case 95:
51.2238 + case 96:
51.2239 + case 166:
51.2240 +#line 302 "parse.y"
51.2241 +{yygotominor.yy46 = yymsp[0].minor.yy46;}
51.2242 +#line 2242 "parse.c"
51.2243 + break;
51.2244 + case 80:
51.2245 +#line 312 "parse.y"
51.2246 +{yygotominor.yy410.n = 0; yygotominor.yy410.z = 0;}
51.2247 +#line 2247 "parse.c"
51.2248 + break;
51.2249 + case 81:
51.2250 +#line 313 "parse.y"
51.2251 +{yygotominor.yy410 = yymsp[-1].minor.yy0;}
51.2252 +#line 2252 "parse.c"
51.2253 + break;
51.2254 + case 86:
51.2255 +#line 319 "parse.y"
51.2256 +{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy174,yymsp[0].minor.yy46,yymsp[-2].minor.yy46,0);}
51.2257 +#line 2257 "parse.c"
51.2258 + break;
51.2259 + case 87:
51.2260 +#line 321 "parse.y"
51.2261 +{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy174,yymsp[0].minor.yy46,0,0,0,0);}
51.2262 +#line 2262 "parse.c"
51.2263 + break;
51.2264 + case 88:
51.2265 +#line 322 "parse.y"
51.2266 +{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy172);}
51.2267 +#line 2267 "parse.c"
51.2268 + break;
51.2269 + case 89:
51.2270 +#line 324 "parse.y"
51.2271 +{
51.2272 + sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy174, &yymsp[-3].minor.yy410, yymsp[-2].minor.yy174, yymsp[-1].minor.yy46);
51.2273 + sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy46);
51.2274 +}
51.2275 +#line 2275 "parse.c"
51.2276 + break;
51.2277 + case 92:
51.2278 + case 94:
51.2279 +#line 338 "parse.y"
51.2280 +{yygotominor.yy46 = OE_Default;}
51.2281 +#line 2281 "parse.c"
51.2282 + break;
51.2283 + case 97:
51.2284 +#line 343 "parse.y"
51.2285 +{yygotominor.yy46 = OE_Ignore;}
51.2286 +#line 2286 "parse.c"
51.2287 + break;
51.2288 + case 98:
51.2289 + case 167:
51.2290 +#line 344 "parse.y"
51.2291 +{yygotominor.yy46 = OE_Replace;}
51.2292 +#line 2292 "parse.c"
51.2293 + break;
51.2294 + case 99:
51.2295 +#line 348 "parse.y"
51.2296 +{
51.2297 + sqlite3DropTable(pParse, yymsp[0].minor.yy373, 0, yymsp[-1].minor.yy46);
51.2298 +}
51.2299 +#line 2299 "parse.c"
51.2300 + break;
51.2301 + case 102:
51.2302 +#line 358 "parse.y"
51.2303 +{
51.2304 + sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy410, &yymsp[-2].minor.yy410, yymsp[0].minor.yy219, yymsp[-6].minor.yy46, yymsp[-4].minor.yy46);
51.2305 +}
51.2306 +#line 2306 "parse.c"
51.2307 + break;
51.2308 + case 103:
51.2309 +#line 361 "parse.y"
51.2310 +{
51.2311 + sqlite3DropTable(pParse, yymsp[0].minor.yy373, 1, yymsp[-1].minor.yy46);
51.2312 +}
51.2313 +#line 2313 "parse.c"
51.2314 + break;
51.2315 + case 104:
51.2316 +#line 368 "parse.y"
51.2317 +{
51.2318 + sqlite3Select(pParse, yymsp[0].minor.yy219, SRT_Callback, 0, 0, 0, 0, 0);
51.2319 + sqlite3SelectDelete(yymsp[0].minor.yy219);
51.2320 +}
51.2321 +#line 2321 "parse.c"
51.2322 + break;
51.2323 + case 105:
51.2324 + case 128:
51.2325 +#line 378 "parse.y"
51.2326 +{yygotominor.yy219 = yymsp[0].minor.yy219;}
51.2327 +#line 2327 "parse.c"
51.2328 + break;
51.2329 + case 106:
51.2330 +#line 380 "parse.y"
51.2331 +{
51.2332 + if( yymsp[0].minor.yy219 ){
51.2333 + yymsp[0].minor.yy219->op = yymsp[-1].minor.yy46;
51.2334 + yymsp[0].minor.yy219->pPrior = yymsp[-2].minor.yy219;
51.2335 + }else{
51.2336 + sqlite3SelectDelete(yymsp[-2].minor.yy219);
51.2337 + }
51.2338 + yygotominor.yy219 = yymsp[0].minor.yy219;
51.2339 +}
51.2340 +#line 2340 "parse.c"
51.2341 + break;
51.2342 + case 108:
51.2343 +#line 391 "parse.y"
51.2344 +{yygotominor.yy46 = TK_ALL;}
51.2345 +#line 2345 "parse.c"
51.2346 + break;
51.2347 + case 110:
51.2348 +#line 395 "parse.y"
51.2349 +{
51.2350 + yygotominor.yy219 = sqlite3SelectNew(yymsp[-6].minor.yy174,yymsp[-5].minor.yy373,yymsp[-4].minor.yy172,yymsp[-3].minor.yy174,yymsp[-2].minor.yy172,yymsp[-1].minor.yy174,yymsp[-7].minor.yy46,yymsp[0].minor.yy234.pLimit,yymsp[0].minor.yy234.pOffset);
51.2351 +}
51.2352 +#line 2352 "parse.c"
51.2353 + break;
51.2354 + case 114:
51.2355 + case 237:
51.2356 +#line 416 "parse.y"
51.2357 +{yygotominor.yy174 = yymsp[-1].minor.yy174;}
51.2358 +#line 2358 "parse.c"
51.2359 + break;
51.2360 + case 115:
51.2361 + case 141:
51.2362 + case 149:
51.2363 + case 230:
51.2364 + case 236:
51.2365 +#line 417 "parse.y"
51.2366 +{yygotominor.yy174 = 0;}
51.2367 +#line 2367 "parse.c"
51.2368 + break;
51.2369 + case 116:
51.2370 +#line 418 "parse.y"
51.2371 +{
51.2372 + yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-2].minor.yy174,yymsp[-1].minor.yy172,yymsp[0].minor.yy410.n?&yymsp[0].minor.yy410:0);
51.2373 +}
51.2374 +#line 2374 "parse.c"
51.2375 + break;
51.2376 + case 117:
51.2377 +#line 421 "parse.y"
51.2378 +{
51.2379 + yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-1].minor.yy174, sqlite3Expr(TK_ALL, 0, 0, 0), 0);
51.2380 +}
51.2381 +#line 2381 "parse.c"
51.2382 + break;
51.2383 + case 118:
51.2384 +#line 424 "parse.y"
51.2385 +{
51.2386 + Expr *pRight = sqlite3Expr(TK_ALL, 0, 0, 0);
51.2387 + Expr *pLeft = sqlite3Expr(TK_ID, 0, 0, &yymsp[-2].minor.yy410);
51.2388 + yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-3].minor.yy174, sqlite3Expr(TK_DOT, pLeft, pRight, 0), 0);
51.2389 +}
51.2390 +#line 2390 "parse.c"
51.2391 + break;
51.2392 + case 121:
51.2393 +#line 436 "parse.y"
51.2394 +{yygotominor.yy410.n = 0;}
51.2395 +#line 2395 "parse.c"
51.2396 + break;
51.2397 + case 122:
51.2398 +#line 448 "parse.y"
51.2399 +{yygotominor.yy373 = sqliteMalloc(sizeof(*yygotominor.yy373));}
51.2400 +#line 2400 "parse.c"
51.2401 + break;
51.2402 + case 123:
51.2403 +#line 449 "parse.y"
51.2404 +{
51.2405 + yygotominor.yy373 = yymsp[0].minor.yy373;
51.2406 + sqlite3SrcListShiftJoinType(yygotominor.yy373);
51.2407 +}
51.2408 +#line 2408 "parse.c"
51.2409 + break;
51.2410 + case 124:
51.2411 +#line 457 "parse.y"
51.2412 +{
51.2413 + yygotominor.yy373 = yymsp[-1].minor.yy373;
51.2414 + if( yygotominor.yy373 && yygotominor.yy373->nSrc>0 ) yygotominor.yy373->a[yygotominor.yy373->nSrc-1].jointype = yymsp[0].minor.yy46;
51.2415 +}
51.2416 +#line 2416 "parse.c"
51.2417 + break;
51.2418 + case 125:
51.2419 +#line 461 "parse.y"
51.2420 +{yygotominor.yy373 = 0;}
51.2421 +#line 2421 "parse.c"
51.2422 + break;
51.2423 + case 126:
51.2424 +#line 462 "parse.y"
51.2425 +{
51.2426 + yygotominor.yy373 = sqlite3SrcListAppendFromTerm(yymsp[-5].minor.yy373,&yymsp[-4].minor.yy410,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,0,yymsp[-1].minor.yy172,yymsp[0].minor.yy432);
51.2427 +}
51.2428 +#line 2428 "parse.c"
51.2429 + break;
51.2430 + case 127:
51.2431 +#line 467 "parse.y"
51.2432 +{
51.2433 + yygotominor.yy373 = sqlite3SrcListAppendFromTerm(yymsp[-6].minor.yy373,0,0,&yymsp[-2].minor.yy410,yymsp[-4].minor.yy219,yymsp[-1].minor.yy172,yymsp[0].minor.yy432);
51.2434 + }
51.2435 +#line 2435 "parse.c"
51.2436 + break;
51.2437 + case 129:
51.2438 +#line 478 "parse.y"
51.2439 +{
51.2440 + sqlite3SrcListShiftJoinType(yymsp[0].minor.yy373);
51.2441 + yygotominor.yy219 = sqlite3SelectNew(0,yymsp[0].minor.yy373,0,0,0,0,0,0,0);
51.2442 + }
51.2443 +#line 2443 "parse.c"
51.2444 + break;
51.2445 + case 130:
51.2446 +#line 485 "parse.y"
51.2447 +{yygotominor.yy410.z=0; yygotominor.yy410.n=0;}
51.2448 +#line 2448 "parse.c"
51.2449 + break;
51.2450 + case 132:
51.2451 +#line 490 "parse.y"
51.2452 +{yygotominor.yy373 = sqlite3SrcListAppend(0,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410);}
51.2453 +#line 2453 "parse.c"
51.2454 + break;
51.2455 + case 133:
51.2456 +#line 494 "parse.y"
51.2457 +{ yygotominor.yy46 = JT_INNER; }
51.2458 +#line 2458 "parse.c"
51.2459 + break;
51.2460 + case 134:
51.2461 +#line 495 "parse.y"
51.2462 +{ yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
51.2463 +#line 2463 "parse.c"
51.2464 + break;
51.2465 + case 135:
51.2466 +#line 496 "parse.y"
51.2467 +{ yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy410,0); }
51.2468 +#line 2468 "parse.c"
51.2469 + break;
51.2470 + case 136:
51.2471 +#line 498 "parse.y"
51.2472 +{ yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy410,&yymsp[-1].minor.yy410); }
51.2473 +#line 2473 "parse.c"
51.2474 + break;
51.2475 + case 137:
51.2476 + case 145:
51.2477 + case 152:
51.2478 + case 159:
51.2479 + case 174:
51.2480 + case 202:
51.2481 + case 225:
51.2482 + case 227:
51.2483 +#line 502 "parse.y"
51.2484 +{yygotominor.yy172 = yymsp[0].minor.yy172;}
51.2485 +#line 2485 "parse.c"
51.2486 + break;
51.2487 + case 138:
51.2488 + case 151:
51.2489 + case 158:
51.2490 + case 203:
51.2491 + case 226:
51.2492 + case 228:
51.2493 +#line 503 "parse.y"
51.2494 +{yygotominor.yy172 = 0;}
51.2495 +#line 2495 "parse.c"
51.2496 + break;
51.2497 + case 139:
51.2498 + case 171:
51.2499 +#line 507 "parse.y"
51.2500 +{yygotominor.yy432 = yymsp[-1].minor.yy432;}
51.2501 +#line 2501 "parse.c"
51.2502 + break;
51.2503 + case 140:
51.2504 + case 170:
51.2505 +#line 508 "parse.y"
51.2506 +{yygotominor.yy432 = 0;}
51.2507 +#line 2507 "parse.c"
51.2508 + break;
51.2509 + case 142:
51.2510 + case 150:
51.2511 + case 229:
51.2512 +#line 519 "parse.y"
51.2513 +{yygotominor.yy174 = yymsp[0].minor.yy174;}
51.2514 +#line 2514 "parse.c"
51.2515 + break;
51.2516 + case 143:
51.2517 +#line 520 "parse.y"
51.2518 +{
51.2519 + yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-3].minor.yy174,yymsp[-1].minor.yy172,0);
51.2520 + if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
51.2521 +}
51.2522 +#line 2522 "parse.c"
51.2523 + break;
51.2524 + case 144:
51.2525 +#line 524 "parse.y"
51.2526 +{
51.2527 + yygotominor.yy174 = sqlite3ExprListAppend(0,yymsp[-1].minor.yy172,0);
51.2528 + if( yygotominor.yy174 && yygotominor.yy174->a ) yygotominor.yy174->a[0].sortOrder = yymsp[0].minor.yy46;
51.2529 +}
51.2530 +#line 2530 "parse.c"
51.2531 + break;
51.2532 + case 146:
51.2533 + case 148:
51.2534 +#line 532 "parse.y"
51.2535 +{yygotominor.yy46 = SQLITE_SO_ASC;}
51.2536 +#line 2536 "parse.c"
51.2537 + break;
51.2538 + case 147:
51.2539 +#line 533 "parse.y"
51.2540 +{yygotominor.yy46 = SQLITE_SO_DESC;}
51.2541 +#line 2541 "parse.c"
51.2542 + break;
51.2543 + case 153:
51.2544 +#line 559 "parse.y"
51.2545 +{yygotominor.yy234.pLimit = 0; yygotominor.yy234.pOffset = 0;}
51.2546 +#line 2546 "parse.c"
51.2547 + break;
51.2548 + case 154:
51.2549 +#line 560 "parse.y"
51.2550 +{yygotominor.yy234.pLimit = yymsp[0].minor.yy172; yygotominor.yy234.pOffset = 0;}
51.2551 +#line 2551 "parse.c"
51.2552 + break;
51.2553 + case 155:
51.2554 +#line 562 "parse.y"
51.2555 +{yygotominor.yy234.pLimit = yymsp[-2].minor.yy172; yygotominor.yy234.pOffset = yymsp[0].minor.yy172;}
51.2556 +#line 2556 "parse.c"
51.2557 + break;
51.2558 + case 156:
51.2559 +#line 564 "parse.y"
51.2560 +{yygotominor.yy234.pOffset = yymsp[-2].minor.yy172; yygotominor.yy234.pLimit = yymsp[0].minor.yy172;}
51.2561 +#line 2561 "parse.c"
51.2562 + break;
51.2563 + case 157:
51.2564 +#line 568 "parse.y"
51.2565 +{sqlite3DeleteFrom(pParse,yymsp[-1].minor.yy373,yymsp[0].minor.yy172);}
51.2566 +#line 2566 "parse.c"
51.2567 + break;
51.2568 + case 160:
51.2569 +#line 578 "parse.y"
51.2570 +{
51.2571 + sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy174,SQLITE_MAX_COLUMN,"set list");
51.2572 + sqlite3Update(pParse,yymsp[-3].minor.yy373,yymsp[-1].minor.yy174,yymsp[0].minor.yy172,yymsp[-4].minor.yy46);
51.2573 +}
51.2574 +#line 2574 "parse.c"
51.2575 + break;
51.2576 + case 161:
51.2577 +#line 587 "parse.y"
51.2578 +{yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-4].minor.yy174,yymsp[0].minor.yy172,&yymsp[-2].minor.yy410);}
51.2579 +#line 2579 "parse.c"
51.2580 + break;
51.2581 + case 162:
51.2582 +#line 588 "parse.y"
51.2583 +{yygotominor.yy174 = sqlite3ExprListAppend(0,yymsp[0].minor.yy172,&yymsp[-2].minor.yy410);}
51.2584 +#line 2584 "parse.c"
51.2585 + break;
51.2586 + case 163:
51.2587 +#line 594 "parse.y"
51.2588 +{sqlite3Insert(pParse, yymsp[-5].minor.yy373, yymsp[-1].minor.yy174, 0, yymsp[-4].minor.yy432, yymsp[-7].minor.yy46);}
51.2589 +#line 2589 "parse.c"
51.2590 + break;
51.2591 + case 164:
51.2592 +#line 596 "parse.y"
51.2593 +{sqlite3Insert(pParse, yymsp[-2].minor.yy373, 0, yymsp[0].minor.yy219, yymsp[-1].minor.yy432, yymsp[-4].minor.yy46);}
51.2594 +#line 2594 "parse.c"
51.2595 + break;
51.2596 + case 165:
51.2597 +#line 598 "parse.y"
51.2598 +{sqlite3Insert(pParse, yymsp[-3].minor.yy373, 0, 0, yymsp[-2].minor.yy432, yymsp[-5].minor.yy46);}
51.2599 +#line 2599 "parse.c"
51.2600 + break;
51.2601 + case 168:
51.2602 + case 231:
51.2603 +#line 608 "parse.y"
51.2604 +{yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-2].minor.yy174,yymsp[0].minor.yy172,0);}
51.2605 +#line 2605 "parse.c"
51.2606 + break;
51.2607 + case 169:
51.2608 + case 232:
51.2609 +#line 609 "parse.y"
51.2610 +{yygotominor.yy174 = sqlite3ExprListAppend(0,yymsp[0].minor.yy172,0);}
51.2611 +#line 2611 "parse.c"
51.2612 + break;
51.2613 + case 172:
51.2614 +#line 618 "parse.y"
51.2615 +{yygotominor.yy432 = sqlite3IdListAppend(yymsp[-2].minor.yy432,&yymsp[0].minor.yy410);}
51.2616 +#line 2616 "parse.c"
51.2617 + break;
51.2618 + case 173:
51.2619 +#line 619 "parse.y"
51.2620 +{yygotominor.yy432 = sqlite3IdListAppend(0,&yymsp[0].minor.yy410);}
51.2621 +#line 2621 "parse.c"
51.2622 + break;
51.2623 + case 175:
51.2624 +#line 630 "parse.y"
51.2625 +{yygotominor.yy172 = yymsp[-1].minor.yy172; sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
51.2626 +#line 2626 "parse.c"
51.2627 + break;
51.2628 + case 176:
51.2629 + case 181:
51.2630 + case 182:
51.2631 +#line 631 "parse.y"
51.2632 +{yygotominor.yy172 = sqlite3Expr(yymsp[0].major, 0, 0, &yymsp[0].minor.yy0);}
51.2633 +#line 2633 "parse.c"
51.2634 + break;
51.2635 + case 177:
51.2636 + case 178:
51.2637 +#line 632 "parse.y"
51.2638 +{yygotominor.yy172 = sqlite3Expr(TK_ID, 0, 0, &yymsp[0].minor.yy0);}
51.2639 +#line 2639 "parse.c"
51.2640 + break;
51.2641 + case 179:
51.2642 +#line 634 "parse.y"
51.2643 +{
51.2644 + Expr *temp1 = sqlite3Expr(TK_ID, 0, 0, &yymsp[-2].minor.yy410);
51.2645 + Expr *temp2 = sqlite3Expr(TK_ID, 0, 0, &yymsp[0].minor.yy410);
51.2646 + yygotominor.yy172 = sqlite3Expr(TK_DOT, temp1, temp2, 0);
51.2647 +}
51.2648 +#line 2648 "parse.c"
51.2649 + break;
51.2650 + case 180:
51.2651 +#line 639 "parse.y"
51.2652 +{
51.2653 + Expr *temp1 = sqlite3Expr(TK_ID, 0, 0, &yymsp[-4].minor.yy410);
51.2654 + Expr *temp2 = sqlite3Expr(TK_ID, 0, 0, &yymsp[-2].minor.yy410);
51.2655 + Expr *temp3 = sqlite3Expr(TK_ID, 0, 0, &yymsp[0].minor.yy410);
51.2656 + Expr *temp4 = sqlite3Expr(TK_DOT, temp2, temp3, 0);
51.2657 + yygotominor.yy172 = sqlite3Expr(TK_DOT, temp1, temp4, 0);
51.2658 +}
51.2659 +#line 2659 "parse.c"
51.2660 + break;
51.2661 + case 183:
51.2662 +#line 648 "parse.y"
51.2663 +{yygotominor.yy172 = sqlite3RegisterExpr(pParse, &yymsp[0].minor.yy0);}
51.2664 +#line 2664 "parse.c"
51.2665 + break;
51.2666 + case 184:
51.2667 +#line 649 "parse.y"
51.2668 +{
51.2669 + Token *pToken = &yymsp[0].minor.yy0;
51.2670 + Expr *pExpr = yygotominor.yy172 = sqlite3Expr(TK_VARIABLE, 0, 0, pToken);
51.2671 + sqlite3ExprAssignVarNumber(pParse, pExpr);
51.2672 +}
51.2673 +#line 2673 "parse.c"
51.2674 + break;
51.2675 + case 185:
51.2676 +#line 654 "parse.y"
51.2677 +{
51.2678 + yygotominor.yy172 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy172, &yymsp[0].minor.yy410);
51.2679 +}
51.2680 +#line 2680 "parse.c"
51.2681 + break;
51.2682 + case 186:
51.2683 +#line 658 "parse.y"
51.2684 +{
51.2685 + yygotominor.yy172 = sqlite3Expr(TK_CAST, yymsp[-3].minor.yy172, 0, &yymsp[-1].minor.yy410);
51.2686 + sqlite3ExprSpan(yygotominor.yy172,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
51.2687 +}
51.2688 +#line 2688 "parse.c"
51.2689 + break;
51.2690 + case 187:
51.2691 +#line 663 "parse.y"
51.2692 +{
51.2693 + if( yymsp[-1].minor.yy174 && yymsp[-1].minor.yy174->nExpr>SQLITE_MAX_FUNCTION_ARG ){
51.2694 + sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
51.2695 + }
51.2696 + yygotominor.yy172 = sqlite3ExprFunction(yymsp[-1].minor.yy174, &yymsp[-4].minor.yy0);
51.2697 + sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
51.2698 + if( yymsp[-2].minor.yy46 && yygotominor.yy172 ){
51.2699 + yygotominor.yy172->flags |= EP_Distinct;
51.2700 + }
51.2701 +}
51.2702 +#line 2702 "parse.c"
51.2703 + break;
51.2704 + case 188:
51.2705 +#line 673 "parse.y"
51.2706 +{
51.2707 + yygotominor.yy172 = sqlite3ExprFunction(0, &yymsp[-3].minor.yy0);
51.2708 + sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
51.2709 +}
51.2710 +#line 2710 "parse.c"
51.2711 + break;
51.2712 + case 189:
51.2713 +#line 677 "parse.y"
51.2714 +{
51.2715 + /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
51.2716 + ** treated as functions that return constants */
51.2717 + yygotominor.yy172 = sqlite3ExprFunction(0,&yymsp[0].minor.yy0);
51.2718 + if( yygotominor.yy172 ){
51.2719 + yygotominor.yy172->op = TK_CONST_FUNC;
51.2720 + yygotominor.yy172->span = yymsp[0].minor.yy0;
51.2721 + }
51.2722 +}
51.2723 +#line 2723 "parse.c"
51.2724 + break;
51.2725 + case 190:
51.2726 + case 191:
51.2727 + case 192:
51.2728 + case 193:
51.2729 + case 194:
51.2730 + case 195:
51.2731 + case 196:
51.2732 + case 197:
51.2733 +#line 686 "parse.y"
51.2734 +{yygotominor.yy172 = sqlite3Expr(yymsp[-1].major, yymsp[-2].minor.yy172, yymsp[0].minor.yy172, 0);}
51.2735 +#line 2735 "parse.c"
51.2736 + break;
51.2737 + case 198:
51.2738 + case 200:
51.2739 +#line 696 "parse.y"
51.2740 +{yygotominor.yy72.eOperator = yymsp[0].minor.yy0; yygotominor.yy72.not = 0;}
51.2741 +#line 2741 "parse.c"
51.2742 + break;
51.2743 + case 199:
51.2744 + case 201:
51.2745 +#line 697 "parse.y"
51.2746 +{yygotominor.yy72.eOperator = yymsp[0].minor.yy0; yygotominor.yy72.not = 1;}
51.2747 +#line 2747 "parse.c"
51.2748 + break;
51.2749 + case 204:
51.2750 +#line 704 "parse.y"
51.2751 +{
51.2752 + ExprList *pList;
51.2753 + pList = sqlite3ExprListAppend(0, yymsp[-1].minor.yy172, 0);
51.2754 + pList = sqlite3ExprListAppend(pList, yymsp[-3].minor.yy172, 0);
51.2755 + if( yymsp[0].minor.yy172 ){
51.2756 + pList = sqlite3ExprListAppend(pList, yymsp[0].minor.yy172, 0);
51.2757 + }
51.2758 + yygotominor.yy172 = sqlite3ExprFunction(pList, &yymsp[-2].minor.yy72.eOperator);
51.2759 + if( yymsp[-2].minor.yy72.not ) yygotominor.yy172 = sqlite3Expr(TK_NOT, yygotominor.yy172, 0, 0);
51.2760 + sqlite3ExprSpan(yygotominor.yy172, &yymsp[-3].minor.yy172->span, &yymsp[-1].minor.yy172->span);
51.2761 + if( yygotominor.yy172 ) yygotominor.yy172->flags |= EP_InfixFunc;
51.2762 +}
51.2763 +#line 2763 "parse.c"
51.2764 + break;
51.2765 + case 205:
51.2766 +#line 717 "parse.y"
51.2767 +{
51.2768 + yygotominor.yy172 = sqlite3Expr(yymsp[0].major, yymsp[-1].minor.yy172, 0, 0);
51.2769 + sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy172->span,&yymsp[0].minor.yy0);
51.2770 +}
51.2771 +#line 2771 "parse.c"
51.2772 + break;
51.2773 + case 206:
51.2774 +#line 721 "parse.y"
51.2775 +{
51.2776 + yygotominor.yy172 = sqlite3Expr(TK_ISNULL, yymsp[-2].minor.yy172, 0, 0);
51.2777 + sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy172->span,&yymsp[0].minor.yy0);
51.2778 +}
51.2779 +#line 2779 "parse.c"
51.2780 + break;
51.2781 + case 207:
51.2782 +#line 725 "parse.y"
51.2783 +{
51.2784 + yygotominor.yy172 = sqlite3Expr(TK_NOTNULL, yymsp[-2].minor.yy172, 0, 0);
51.2785 + sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy172->span,&yymsp[0].minor.yy0);
51.2786 +}
51.2787 +#line 2787 "parse.c"
51.2788 + break;
51.2789 + case 208:
51.2790 +#line 729 "parse.y"
51.2791 +{
51.2792 + yygotominor.yy172 = sqlite3Expr(TK_NOTNULL, yymsp[-3].minor.yy172, 0, 0);
51.2793 + sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy172->span,&yymsp[0].minor.yy0);
51.2794 +}
51.2795 +#line 2795 "parse.c"
51.2796 + break;
51.2797 + case 209:
51.2798 +#line 733 "parse.y"
51.2799 +{
51.2800 + yygotominor.yy172 = sqlite3Expr(yymsp[-1].major, yymsp[0].minor.yy172, 0, 0);
51.2801 + sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
51.2802 +}
51.2803 +#line 2803 "parse.c"
51.2804 + break;
51.2805 + case 210:
51.2806 +#line 737 "parse.y"
51.2807 +{
51.2808 + yygotominor.yy172 = sqlite3Expr(TK_UMINUS, yymsp[0].minor.yy172, 0, 0);
51.2809 + sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
51.2810 +}
51.2811 +#line 2811 "parse.c"
51.2812 + break;
51.2813 + case 211:
51.2814 +#line 741 "parse.y"
51.2815 +{
51.2816 + yygotominor.yy172 = sqlite3Expr(TK_UPLUS, yymsp[0].minor.yy172, 0, 0);
51.2817 + sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
51.2818 +}
51.2819 +#line 2819 "parse.c"
51.2820 + break;
51.2821 + case 214:
51.2822 +#line 748 "parse.y"
51.2823 +{
51.2824 + ExprList *pList = sqlite3ExprListAppend(0, yymsp[-2].minor.yy172, 0);
51.2825 + pList = sqlite3ExprListAppend(pList, yymsp[0].minor.yy172, 0);
51.2826 + yygotominor.yy172 = sqlite3Expr(TK_BETWEEN, yymsp[-4].minor.yy172, 0, 0);
51.2827 + if( yygotominor.yy172 ){
51.2828 + yygotominor.yy172->pList = pList;
51.2829 + }else{
51.2830 + sqlite3ExprListDelete(pList);
51.2831 + }
51.2832 + if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3Expr(TK_NOT, yygotominor.yy172, 0, 0);
51.2833 + sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy172->span);
51.2834 +}
51.2835 +#line 2835 "parse.c"
51.2836 + break;
51.2837 + case 217:
51.2838 +#line 764 "parse.y"
51.2839 +{
51.2840 + yygotominor.yy172 = sqlite3Expr(TK_IN, yymsp[-4].minor.yy172, 0, 0);
51.2841 + if( yygotominor.yy172 ){
51.2842 + yygotominor.yy172->pList = yymsp[-1].minor.yy174;
51.2843 + sqlite3ExprSetHeight(yygotominor.yy172);
51.2844 + }else{
51.2845 + sqlite3ExprListDelete(yymsp[-1].minor.yy174);
51.2846 + }
51.2847 + if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3Expr(TK_NOT, yygotominor.yy172, 0, 0);
51.2848 + sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy0);
51.2849 + }
51.2850 +#line 2850 "parse.c"
51.2851 + break;
51.2852 + case 218:
51.2853 +#line 775 "parse.y"
51.2854 +{
51.2855 + yygotominor.yy172 = sqlite3Expr(TK_SELECT, 0, 0, 0);
51.2856 + if( yygotominor.yy172 ){
51.2857 + yygotominor.yy172->pSelect = yymsp[-1].minor.yy219;
51.2858 + sqlite3ExprSetHeight(yygotominor.yy172);
51.2859 + }else{
51.2860 + sqlite3SelectDelete(yymsp[-1].minor.yy219);
51.2861 + }
51.2862 + sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
51.2863 + }
51.2864 +#line 2864 "parse.c"
51.2865 + break;
51.2866 + case 219:
51.2867 +#line 785 "parse.y"
51.2868 +{
51.2869 + yygotominor.yy172 = sqlite3Expr(TK_IN, yymsp[-4].minor.yy172, 0, 0);
51.2870 + if( yygotominor.yy172 ){
51.2871 + yygotominor.yy172->pSelect = yymsp[-1].minor.yy219;
51.2872 + sqlite3ExprSetHeight(yygotominor.yy172);
51.2873 + }else{
51.2874 + sqlite3SelectDelete(yymsp[-1].minor.yy219);
51.2875 + }
51.2876 + if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3Expr(TK_NOT, yygotominor.yy172, 0, 0);
51.2877 + sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy0);
51.2878 + }
51.2879 +#line 2879 "parse.c"
51.2880 + break;
51.2881 + case 220:
51.2882 +#line 796 "parse.y"
51.2883 +{
51.2884 + SrcList *pSrc = sqlite3SrcListAppend(0,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410);
51.2885 + yygotominor.yy172 = sqlite3Expr(TK_IN, yymsp[-3].minor.yy172, 0, 0);
51.2886 + if( yygotominor.yy172 ){
51.2887 + yygotominor.yy172->pSelect = sqlite3SelectNew(0,pSrc,0,0,0,0,0,0,0);
51.2888 + sqlite3ExprSetHeight(yygotominor.yy172);
51.2889 + }else{
51.2890 + sqlite3SrcListDelete(pSrc);
51.2891 + }
51.2892 + if( yymsp[-2].minor.yy46 ) yygotominor.yy172 = sqlite3Expr(TK_NOT, yygotominor.yy172, 0, 0);
51.2893 + sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy172->span,yymsp[0].minor.yy410.z?&yymsp[0].minor.yy410:&yymsp[-1].minor.yy410);
51.2894 + }
51.2895 +#line 2895 "parse.c"
51.2896 + break;
51.2897 + case 221:
51.2898 +#line 808 "parse.y"
51.2899 +{
51.2900 + Expr *p = yygotominor.yy172 = sqlite3Expr(TK_EXISTS, 0, 0, 0);
51.2901 + if( p ){
51.2902 + p->pSelect = yymsp[-1].minor.yy219;
51.2903 + sqlite3ExprSpan(p,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
51.2904 + sqlite3ExprSetHeight(yygotominor.yy172);
51.2905 + }else{
51.2906 + sqlite3SelectDelete(yymsp[-1].minor.yy219);
51.2907 + }
51.2908 + }
51.2909 +#line 2909 "parse.c"
51.2910 + break;
51.2911 + case 222:
51.2912 +#line 821 "parse.y"
51.2913 +{
51.2914 + yygotominor.yy172 = sqlite3Expr(TK_CASE, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, 0);
51.2915 + if( yygotominor.yy172 ){
51.2916 + yygotominor.yy172->pList = yymsp[-2].minor.yy174;
51.2917 + sqlite3ExprSetHeight(yygotominor.yy172);
51.2918 + }else{
51.2919 + sqlite3ExprListDelete(yymsp[-2].minor.yy174);
51.2920 + }
51.2921 + sqlite3ExprSpan(yygotominor.yy172, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
51.2922 +}
51.2923 +#line 2923 "parse.c"
51.2924 + break;
51.2925 + case 223:
51.2926 +#line 833 "parse.y"
51.2927 +{
51.2928 + yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-4].minor.yy174, yymsp[-2].minor.yy172, 0);
51.2929 + yygotominor.yy174 = sqlite3ExprListAppend(yygotominor.yy174, yymsp[0].minor.yy172, 0);
51.2930 +}
51.2931 +#line 2931 "parse.c"
51.2932 + break;
51.2933 + case 224:
51.2934 +#line 837 "parse.y"
51.2935 +{
51.2936 + yygotominor.yy174 = sqlite3ExprListAppend(0, yymsp[-2].minor.yy172, 0);
51.2937 + yygotominor.yy174 = sqlite3ExprListAppend(yygotominor.yy174, yymsp[0].minor.yy172, 0);
51.2938 +}
51.2939 +#line 2939 "parse.c"
51.2940 + break;
51.2941 + case 233:
51.2942 +#line 864 "parse.y"
51.2943 +{
51.2944 + sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy410, &yymsp[-5].minor.yy410, sqlite3SrcListAppend(0,&yymsp[-3].minor.yy410,0), yymsp[-1].minor.yy174, yymsp[-9].minor.yy46,
51.2945 + &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy46);
51.2946 +}
51.2947 +#line 2947 "parse.c"
51.2948 + break;
51.2949 + case 234:
51.2950 + case 281:
51.2951 +#line 870 "parse.y"
51.2952 +{yygotominor.yy46 = OE_Abort;}
51.2953 +#line 2953 "parse.c"
51.2954 + break;
51.2955 + case 235:
51.2956 +#line 871 "parse.y"
51.2957 +{yygotominor.yy46 = OE_None;}
51.2958 +#line 2958 "parse.c"
51.2959 + break;
51.2960 + case 238:
51.2961 +#line 881 "parse.y"
51.2962 +{
51.2963 + Expr *p = 0;
51.2964 + if( yymsp[-1].minor.yy410.n>0 ){
51.2965 + p = sqlite3Expr(TK_COLUMN, 0, 0, 0);
51.2966 + if( p ) p->pColl = sqlite3LocateCollSeq(pParse, (char*)yymsp[-1].minor.yy410.z, yymsp[-1].minor.yy410.n);
51.2967 + }
51.2968 + yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-4].minor.yy174, p, &yymsp[-2].minor.yy410);
51.2969 + sqlite3ExprListCheckLength(pParse, yygotominor.yy174, SQLITE_MAX_COLUMN, "index");
51.2970 + if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
51.2971 +}
51.2972 +#line 2972 "parse.c"
51.2973 + break;
51.2974 + case 239:
51.2975 +#line 891 "parse.y"
51.2976 +{
51.2977 + Expr *p = 0;
51.2978 + if( yymsp[-1].minor.yy410.n>0 ){
51.2979 + p = sqlite3Expr(TK_COLUMN, 0, 0, 0);
51.2980 + if( p ) p->pColl = sqlite3LocateCollSeq(pParse, (char*)yymsp[-1].minor.yy410.z, yymsp[-1].minor.yy410.n);
51.2981 + }
51.2982 + yygotominor.yy174 = sqlite3ExprListAppend(0, p, &yymsp[-2].minor.yy410);
51.2983 + sqlite3ExprListCheckLength(pParse, yygotominor.yy174, SQLITE_MAX_COLUMN, "index");
51.2984 + if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
51.2985 +}
51.2986 +#line 2986 "parse.c"
51.2987 + break;
51.2988 + case 241:
51.2989 +#line 904 "parse.y"
51.2990 +{yygotominor.yy410.z = 0; yygotominor.yy410.n = 0;}
51.2991 +#line 2991 "parse.c"
51.2992 + break;
51.2993 + case 243:
51.2994 +#line 910 "parse.y"
51.2995 +{sqlite3DropIndex(pParse, yymsp[0].minor.yy373, yymsp[-1].minor.yy46);}
51.2996 +#line 2996 "parse.c"
51.2997 + break;
51.2998 + case 244:
51.2999 + case 245:
51.3000 +#line 916 "parse.y"
51.3001 +{sqlite3Vacuum(pParse);}
51.3002 +#line 3002 "parse.c"
51.3003 + break;
51.3004 + case 246:
51.3005 +#line 924 "parse.y"
51.3006 +{sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy410,0);}
51.3007 +#line 3007 "parse.c"
51.3008 + break;
51.3009 + case 247:
51.3010 +#line 925 "parse.y"
51.3011 +{sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy0,0);}
51.3012 +#line 3012 "parse.c"
51.3013 + break;
51.3014 + case 248:
51.3015 +#line 926 "parse.y"
51.3016 +{
51.3017 + sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy410,1);
51.3018 +}
51.3019 +#line 3019 "parse.c"
51.3020 + break;
51.3021 + case 249:
51.3022 +#line 929 "parse.y"
51.3023 +{sqlite3Pragma(pParse,&yymsp[-4].minor.yy410,&yymsp[-3].minor.yy410,&yymsp[-1].minor.yy410,0);}
51.3024 +#line 3024 "parse.c"
51.3025 + break;
51.3026 + case 250:
51.3027 +#line 930 "parse.y"
51.3028 +{sqlite3Pragma(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410,0,0);}
51.3029 +#line 3029 "parse.c"
51.3030 + break;
51.3031 + case 258:
51.3032 +#line 944 "parse.y"
51.3033 +{
51.3034 + Token all;
51.3035 + all.z = yymsp[-3].minor.yy410.z;
51.3036 + all.n = (yymsp[0].minor.yy0.z - yymsp[-3].minor.yy410.z) + yymsp[0].minor.yy0.n;
51.3037 + sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy243, &all);
51.3038 +}
51.3039 +#line 3039 "parse.c"
51.3040 + break;
51.3041 + case 259:
51.3042 +#line 953 "parse.y"
51.3043 +{
51.3044 + sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy410, &yymsp[-6].minor.yy410, yymsp[-5].minor.yy46, yymsp[-4].minor.yy370.a, yymsp[-4].minor.yy370.b, yymsp[-2].minor.yy373, yymsp[0].minor.yy172, yymsp[-10].minor.yy46, yymsp[-8].minor.yy46);
51.3045 + yygotominor.yy410 = (yymsp[-6].minor.yy410.n==0?yymsp[-7].minor.yy410:yymsp[-6].minor.yy410);
51.3046 +}
51.3047 +#line 3047 "parse.c"
51.3048 + break;
51.3049 + case 260:
51.3050 + case 263:
51.3051 +#line 959 "parse.y"
51.3052 +{ yygotominor.yy46 = TK_BEFORE; }
51.3053 +#line 3053 "parse.c"
51.3054 + break;
51.3055 + case 261:
51.3056 +#line 960 "parse.y"
51.3057 +{ yygotominor.yy46 = TK_AFTER; }
51.3058 +#line 3058 "parse.c"
51.3059 + break;
51.3060 + case 262:
51.3061 +#line 961 "parse.y"
51.3062 +{ yygotominor.yy46 = TK_INSTEAD;}
51.3063 +#line 3063 "parse.c"
51.3064 + break;
51.3065 + case 264:
51.3066 + case 265:
51.3067 +#line 966 "parse.y"
51.3068 +{yygotominor.yy370.a = yymsp[0].major; yygotominor.yy370.b = 0;}
51.3069 +#line 3069 "parse.c"
51.3070 + break;
51.3071 + case 266:
51.3072 +#line 968 "parse.y"
51.3073 +{yygotominor.yy370.a = TK_UPDATE; yygotominor.yy370.b = yymsp[0].minor.yy432;}
51.3074 +#line 3074 "parse.c"
51.3075 + break;
51.3076 + case 269:
51.3077 +#line 975 "parse.y"
51.3078 +{ yygotominor.yy172 = 0; }
51.3079 +#line 3079 "parse.c"
51.3080 + break;
51.3081 + case 270:
51.3082 +#line 976 "parse.y"
51.3083 +{ yygotominor.yy172 = yymsp[0].minor.yy172; }
51.3084 +#line 3084 "parse.c"
51.3085 + break;
51.3086 + case 271:
51.3087 +#line 980 "parse.y"
51.3088 +{
51.3089 + if( yymsp[-2].minor.yy243 ){
51.3090 + yymsp[-2].minor.yy243->pLast->pNext = yymsp[-1].minor.yy243;
51.3091 + }else{
51.3092 + yymsp[-2].minor.yy243 = yymsp[-1].minor.yy243;
51.3093 + }
51.3094 + yymsp[-2].minor.yy243->pLast = yymsp[-1].minor.yy243;
51.3095 + yygotominor.yy243 = yymsp[-2].minor.yy243;
51.3096 +}
51.3097 +#line 3097 "parse.c"
51.3098 + break;
51.3099 + case 272:
51.3100 +#line 989 "parse.y"
51.3101 +{ yygotominor.yy243 = 0; }
51.3102 +#line 3102 "parse.c"
51.3103 + break;
51.3104 + case 273:
51.3105 +#line 995 "parse.y"
51.3106 +{ yygotominor.yy243 = sqlite3TriggerUpdateStep(&yymsp[-3].minor.yy410, yymsp[-1].minor.yy174, yymsp[0].minor.yy172, yymsp[-4].minor.yy46); }
51.3107 +#line 3107 "parse.c"
51.3108 + break;
51.3109 + case 274:
51.3110 +#line 1000 "parse.y"
51.3111 +{yygotominor.yy243 = sqlite3TriggerInsertStep(&yymsp[-5].minor.yy410, yymsp[-4].minor.yy432, yymsp[-1].minor.yy174, 0, yymsp[-7].minor.yy46);}
51.3112 +#line 3112 "parse.c"
51.3113 + break;
51.3114 + case 275:
51.3115 +#line 1003 "parse.y"
51.3116 +{yygotominor.yy243 = sqlite3TriggerInsertStep(&yymsp[-2].minor.yy410, yymsp[-1].minor.yy432, 0, yymsp[0].minor.yy219, yymsp[-4].minor.yy46);}
51.3117 +#line 3117 "parse.c"
51.3118 + break;
51.3119 + case 276:
51.3120 +#line 1007 "parse.y"
51.3121 +{yygotominor.yy243 = sqlite3TriggerDeleteStep(&yymsp[-1].minor.yy410, yymsp[0].minor.yy172);}
51.3122 +#line 3122 "parse.c"
51.3123 + break;
51.3124 + case 277:
51.3125 +#line 1010 "parse.y"
51.3126 +{yygotominor.yy243 = sqlite3TriggerSelectStep(yymsp[0].minor.yy219); }
51.3127 +#line 3127 "parse.c"
51.3128 + break;
51.3129 + case 278:
51.3130 +#line 1013 "parse.y"
51.3131 +{
51.3132 + yygotominor.yy172 = sqlite3Expr(TK_RAISE, 0, 0, 0);
51.3133 + if( yygotominor.yy172 ){
51.3134 + yygotominor.yy172->iColumn = OE_Ignore;
51.3135 + sqlite3ExprSpan(yygotominor.yy172, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
51.3136 + }
51.3137 +}
51.3138 +#line 3138 "parse.c"
51.3139 + break;
51.3140 + case 279:
51.3141 +#line 1020 "parse.y"
51.3142 +{
51.3143 + yygotominor.yy172 = sqlite3Expr(TK_RAISE, 0, 0, &yymsp[-1].minor.yy410);
51.3144 + if( yygotominor.yy172 ) {
51.3145 + yygotominor.yy172->iColumn = yymsp[-3].minor.yy46;
51.3146 + sqlite3ExprSpan(yygotominor.yy172, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
51.3147 + }
51.3148 +}
51.3149 +#line 3149 "parse.c"
51.3150 + break;
51.3151 + case 280:
51.3152 +#line 1030 "parse.y"
51.3153 +{yygotominor.yy46 = OE_Rollback;}
51.3154 +#line 3154 "parse.c"
51.3155 + break;
51.3156 + case 282:
51.3157 +#line 1032 "parse.y"
51.3158 +{yygotominor.yy46 = OE_Fail;}
51.3159 +#line 3159 "parse.c"
51.3160 + break;
51.3161 + case 283:
51.3162 +#line 1037 "parse.y"
51.3163 +{
51.3164 + sqlite3DropTrigger(pParse,yymsp[0].minor.yy373,yymsp[-1].minor.yy46);
51.3165 +}
51.3166 +#line 3166 "parse.c"
51.3167 + break;
51.3168 + case 284:
51.3169 +#line 1044 "parse.y"
51.3170 +{
51.3171 + sqlite3Attach(pParse, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, yymsp[0].minor.yy386);
51.3172 +}
51.3173 +#line 3173 "parse.c"
51.3174 + break;
51.3175 + case 285:
51.3176 +#line 1047 "parse.y"
51.3177 +{
51.3178 + sqlite3Detach(pParse, yymsp[0].minor.yy172);
51.3179 +}
51.3180 +#line 3180 "parse.c"
51.3181 + break;
51.3182 + case 286:
51.3183 +#line 1053 "parse.y"
51.3184 +{ yygotominor.yy386 = 0; }
51.3185 +#line 3185 "parse.c"
51.3186 + break;
51.3187 + case 287:
51.3188 +#line 1054 "parse.y"
51.3189 +{ yygotominor.yy386 = yymsp[0].minor.yy172; }
51.3190 +#line 3190 "parse.c"
51.3191 + break;
51.3192 + case 290:
51.3193 +#line 1062 "parse.y"
51.3194 +{sqlite3Reindex(pParse, 0, 0);}
51.3195 +#line 3195 "parse.c"
51.3196 + break;
51.3197 + case 291:
51.3198 +#line 1063 "parse.y"
51.3199 +{sqlite3Reindex(pParse, &yymsp[-1].minor.yy410, &yymsp[0].minor.yy410);}
51.3200 +#line 3200 "parse.c"
51.3201 + break;
51.3202 + case 292:
51.3203 +#line 1068 "parse.y"
51.3204 +{sqlite3Analyze(pParse, 0, 0);}
51.3205 +#line 3205 "parse.c"
51.3206 + break;
51.3207 + case 293:
51.3208 +#line 1069 "parse.y"
51.3209 +{sqlite3Analyze(pParse, &yymsp[-1].minor.yy410, &yymsp[0].minor.yy410);}
51.3210 +#line 3210 "parse.c"
51.3211 + break;
51.3212 + case 294:
51.3213 +#line 1074 "parse.y"
51.3214 +{
51.3215 + sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy373,&yymsp[0].minor.yy410);
51.3216 +}
51.3217 +#line 3217 "parse.c"
51.3218 + break;
51.3219 + case 295:
51.3220 +#line 1077 "parse.y"
51.3221 +{
51.3222 + sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy410);
51.3223 +}
51.3224 +#line 3224 "parse.c"
51.3225 + break;
51.3226 + case 296:
51.3227 +#line 1080 "parse.y"
51.3228 +{
51.3229 + sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy373);
51.3230 +}
51.3231 +#line 3231 "parse.c"
51.3232 + break;
51.3233 + case 299:
51.3234 +#line 1089 "parse.y"
51.3235 +{sqlite3VtabFinishParse(pParse,0);}
51.3236 +#line 3236 "parse.c"
51.3237 + break;
51.3238 + case 300:
51.3239 +#line 1090 "parse.y"
51.3240 +{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
51.3241 +#line 3241 "parse.c"
51.3242 + break;
51.3243 + case 301:
51.3244 +#line 1091 "parse.y"
51.3245 +{
51.3246 + sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy410, &yymsp[-2].minor.yy410, &yymsp[0].minor.yy410);
51.3247 +}
51.3248 +#line 3248 "parse.c"
51.3249 + break;
51.3250 + case 304:
51.3251 +#line 1096 "parse.y"
51.3252 +{sqlite3VtabArgInit(pParse);}
51.3253 +#line 3253 "parse.c"
51.3254 + break;
51.3255 + case 306:
51.3256 + case 307:
51.3257 + case 308:
51.3258 + case 310:
51.3259 +#line 1098 "parse.y"
51.3260 +{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
51.3261 +#line 3261 "parse.c"
51.3262 + break;
51.3263 + };
51.3264 + yygoto = yyRuleInfo[yyruleno].lhs;
51.3265 + yysize = yyRuleInfo[yyruleno].nrhs;
51.3266 + yypParser->yyidx -= yysize;
51.3267 + yyact = yy_find_reduce_action(yymsp[-yysize].stateno,yygoto);
51.3268 + if( yyact < YYNSTATE ){
51.3269 +#ifdef NDEBUG
51.3270 + /* If we are not debugging and the reduce action popped at least
51.3271 + ** one element off the stack, then we can push the new element back
51.3272 + ** onto the stack here, and skip the stack overflow test in yy_shift().
51.3273 + ** That gives a significant speed improvement. */
51.3274 + if( yysize ){
51.3275 + yypParser->yyidx++;
51.3276 + yymsp -= yysize-1;
51.3277 + yymsp->stateno = yyact;
51.3278 + yymsp->major = yygoto;
51.3279 + yymsp->minor = yygotominor;
51.3280 + }else
51.3281 +#endif
51.3282 + {
51.3283 + yy_shift(yypParser,yyact,yygoto,&yygotominor);
51.3284 + }
51.3285 + }else if( yyact == YYNSTATE + YYNRULE + 1 ){
51.3286 + yy_accept(yypParser);
51.3287 + }
51.3288 +}
51.3289 +
51.3290 +/*
51.3291 +** The following code executes when the parse fails
51.3292 +*/
51.3293 +static void yy_parse_failed(
51.3294 + yyParser *yypParser /* The parser */
51.3295 +){
51.3296 + sqlite3ParserARG_FETCH;
51.3297 +#ifndef NDEBUG
51.3298 + if( yyTraceFILE ){
51.3299 + fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
51.3300 + }
51.3301 +#endif
51.3302 + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
51.3303 + /* Here code is inserted which will be executed whenever the
51.3304 + ** parser fails */
51.3305 + sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
51.3306 +}
51.3307 +
51.3308 +/*
51.3309 +** The following code executes when a syntax error first occurs.
51.3310 +*/
51.3311 +static void yy_syntax_error(
51.3312 + yyParser *yypParser, /* The parser */
51.3313 + int yymajor, /* The major type of the error token */
51.3314 + YYMINORTYPE yyminor /* The minor type of the error token */
51.3315 +){
51.3316 + sqlite3ParserARG_FETCH;
51.3317 +#define TOKEN (yyminor.yy0)
51.3318 +#line 34 "parse.y"
51.3319 +
51.3320 + if( !pParse->parseError ){
51.3321 + if( TOKEN.z[0] ){
51.3322 + sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
51.3323 + }else{
51.3324 + sqlite3ErrorMsg(pParse, "incomplete SQL statement");
51.3325 + }
51.3326 + pParse->parseError = 1;
51.3327 + }
51.3328 +#line 3329 "parse.c"
51.3329 + sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
51.3330 +}
51.3331 +
51.3332 +/*
51.3333 +** The following is executed when the parser accepts
51.3334 +*/
51.3335 +static void yy_accept(
51.3336 + yyParser *yypParser /* The parser */
51.3337 +){
51.3338 + sqlite3ParserARG_FETCH;
51.3339 +#ifndef NDEBUG
51.3340 + if( yyTraceFILE ){
51.3341 + fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
51.3342 + }
51.3343 +#endif
51.3344 + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
51.3345 + /* Here code is inserted which will be executed whenever the
51.3346 + ** parser accepts */
51.3347 + sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
51.3348 +}
51.3349 +
51.3350 +/* The main parser program.
51.3351 +** The first argument is a pointer to a structure obtained from
51.3352 +** "sqlite3ParserAlloc" which describes the current state of the parser.
51.3353 +** The second argument is the major token number. The third is
51.3354 +** the minor token. The fourth optional argument is whatever the
51.3355 +** user wants (and specified in the grammar) and is available for
51.3356 +** use by the action routines.
51.3357 +**
51.3358 +** Inputs:
51.3359 +** <ul>
51.3360 +** <li> A pointer to the parser (an opaque structure.)
51.3361 +** <li> The major token number.
51.3362 +** <li> The minor token number.
51.3363 +** <li> An option argument of a grammar-specified type.
51.3364 +** </ul>
51.3365 +**
51.3366 +** Outputs:
51.3367 +** None.
51.3368 +*/
51.3369 +void sqlite3Parser(
51.3370 + void *yyp, /* The parser */
51.3371 + int yymajor, /* The major token code number */
51.3372 + sqlite3ParserTOKENTYPE yyminor /* The value for the token */
51.3373 + sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
51.3374 +){
51.3375 + YYMINORTYPE yyminorunion;
51.3376 + int yyact; /* The parser action. */
51.3377 + int yyendofinput; /* True if we are at the end of input */
51.3378 + int yyerrorhit = 0; /* True if yymajor has invoked an error */
51.3379 + yyParser *yypParser; /* The parser */
51.3380 +
51.3381 + /* (re)initialize the parser, if necessary */
51.3382 + yypParser = (yyParser*)yyp;
51.3383 + if( yypParser->yyidx<0 ){
51.3384 +#if YYSTACKDEPTH<=0
51.3385 + if( yypParser->yystksz <=0 ){
51.3386 + memset(&yyminorunion, 0, sizeof(yyminorunion));
51.3387 + yyStackOverflow(yypParser, &yyminorunion);
51.3388 + return;
51.3389 + }
51.3390 +#endif
51.3391 + yypParser->yyidx = 0;
51.3392 + yypParser->yyerrcnt = -1;
51.3393 + yypParser->yystack[0].stateno = 0;
51.3394 + yypParser->yystack[0].major = 0;
51.3395 + }
51.3396 + yyminorunion.yy0 = yyminor;
51.3397 + yyendofinput = (yymajor==0);
51.3398 + sqlite3ParserARG_STORE;
51.3399 +
51.3400 +#ifndef NDEBUG
51.3401 + if( yyTraceFILE ){
51.3402 + fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
51.3403 + }
51.3404 +#endif
51.3405 +
51.3406 + do{
51.3407 + yyact = yy_find_shift_action(yypParser,yymajor);
51.3408 + if( yyact<YYNSTATE ){
51.3409 + yy_shift(yypParser,yyact,yymajor,&yyminorunion);
51.3410 + yypParser->yyerrcnt--;
51.3411 + if( yyendofinput && yypParser->yyidx>=0 ){
51.3412 + yymajor = 0;
51.3413 + }else{
51.3414 + yymajor = YYNOCODE;
51.3415 + }
51.3416 + }else if( yyact < YYNSTATE + YYNRULE ){
51.3417 + yy_reduce(yypParser,yyact-YYNSTATE);
51.3418 + }else if( yyact == YY_ERROR_ACTION ){
51.3419 + int yymx;
51.3420 +#ifndef NDEBUG
51.3421 + if( yyTraceFILE ){
51.3422 + fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
51.3423 + }
51.3424 +#endif
51.3425 +#ifdef YYERRORSYMBOL
51.3426 + /* A syntax error has occurred.
51.3427 + ** The response to an error depends upon whether or not the
51.3428 + ** grammar defines an error token "ERROR".
51.3429 + **
51.3430 + ** This is what we do if the grammar does define ERROR:
51.3431 + **
51.3432 + ** * Call the %syntax_error function.
51.3433 + **
51.3434 + ** * Begin popping the stack until we enter a state where
51.3435 + ** it is legal to shift the error symbol, then shift
51.3436 + ** the error symbol.
51.3437 + **
51.3438 + ** * Set the error count to three.
51.3439 + **
51.3440 + ** * Begin accepting and shifting new tokens. No new error
51.3441 + ** processing will occur until three tokens have been
51.3442 + ** shifted successfully.
51.3443 + **
51.3444 + */
51.3445 + if( yypParser->yyerrcnt<0 ){
51.3446 + yy_syntax_error(yypParser,yymajor,yyminorunion);
51.3447 + }
51.3448 + yymx = yypParser->yystack[yypParser->yyidx].major;
51.3449 + if( yymx==YYERRORSYMBOL || yyerrorhit ){
51.3450 +#ifndef NDEBUG
51.3451 + if( yyTraceFILE ){
51.3452 + fprintf(yyTraceFILE,"%sDiscard input token %s\n",
51.3453 + yyTracePrompt,yyTokenName[yymajor]);
51.3454 + }
51.3455 +#endif
51.3456 + yy_destructor(yymajor,&yyminorunion);
51.3457 + yymajor = YYNOCODE;
51.3458 + }else{
51.3459 + while(
51.3460 + yypParser->yyidx >= 0 &&
51.3461 + yymx != YYERRORSYMBOL &&
51.3462 + (yyact = yy_find_reduce_action(
51.3463 + yypParser->yystack[yypParser->yyidx].stateno,
51.3464 + YYERRORSYMBOL)) >= YYNSTATE
51.3465 + ){
51.3466 + yy_pop_parser_stack(yypParser);
51.3467 + }
51.3468 + if( yypParser->yyidx < 0 || yymajor==0 ){
51.3469 + yy_destructor(yymajor,&yyminorunion);
51.3470 + yy_parse_failed(yypParser);
51.3471 + yymajor = YYNOCODE;
51.3472 + }else if( yymx!=YYERRORSYMBOL ){
51.3473 + YYMINORTYPE u2;
51.3474 + u2.YYERRSYMDT = 0;
51.3475 + yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
51.3476 + }
51.3477 + }
51.3478 + yypParser->yyerrcnt = 3;
51.3479 + yyerrorhit = 1;
51.3480 +#else /* YYERRORSYMBOL is not defined */
51.3481 + /* This is what we do if the grammar does not define ERROR:
51.3482 + **
51.3483 + ** * Report an error message, and throw away the input token.
51.3484 + **
51.3485 + ** * If the input token is $, then fail the parse.
51.3486 + **
51.3487 + ** As before, subsequent error messages are suppressed until
51.3488 + ** three input tokens have been successfully shifted.
51.3489 + */
51.3490 + if( yypParser->yyerrcnt<=0 ){
51.3491 + yy_syntax_error(yypParser,yymajor,yyminorunion);
51.3492 + }
51.3493 + yypParser->yyerrcnt = 3;
51.3494 + yy_destructor(yymajor,&yyminorunion);
51.3495 + if( yyendofinput ){
51.3496 + yy_parse_failed(yypParser);
51.3497 + }
51.3498 + yymajor = YYNOCODE;
51.3499 +#endif
51.3500 + }else{
51.3501 + yy_accept(yypParser);
51.3502 + yymajor = YYNOCODE;
51.3503 + }
51.3504 + }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
51.3505 + return;
51.3506 +}
52.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
52.2 +++ b/extensions/sqlite/sqlite-source/parse.h Sun Jul 29 01:15:31 2007 +0000
52.3 @@ -0,0 +1,152 @@
52.4 +#define TK_SEMI 1
52.5 +#define TK_EXPLAIN 2
52.6 +#define TK_QUERY 3
52.7 +#define TK_PLAN 4
52.8 +#define TK_BEGIN 5
52.9 +#define TK_TRANSACTION 6
52.10 +#define TK_DEFERRED 7
52.11 +#define TK_IMMEDIATE 8
52.12 +#define TK_EXCLUSIVE 9
52.13 +#define TK_COMMIT 10
52.14 +#define TK_END 11
52.15 +#define TK_ROLLBACK 12
52.16 +#define TK_CREATE 13
52.17 +#define TK_TABLE 14
52.18 +#define TK_IF 15
52.19 +#define TK_NOT 16
52.20 +#define TK_EXISTS 17
52.21 +#define TK_TEMP 18
52.22 +#define TK_LP 19
52.23 +#define TK_RP 20
52.24 +#define TK_AS 21
52.25 +#define TK_COMMA 22
52.26 +#define TK_ID 23
52.27 +#define TK_ABORT 24
52.28 +#define TK_AFTER 25
52.29 +#define TK_ANALYZE 26
52.30 +#define TK_ASC 27
52.31 +#define TK_ATTACH 28
52.32 +#define TK_BEFORE 29
52.33 +#define TK_CASCADE 30
52.34 +#define TK_CAST 31
52.35 +#define TK_CONFLICT 32
52.36 +#define TK_DATABASE 33
52.37 +#define TK_DESC 34
52.38 +#define TK_DETACH 35
52.39 +#define TK_EACH 36
52.40 +#define TK_FAIL 37
52.41 +#define TK_FOR 38
52.42 +#define TK_IGNORE 39
52.43 +#define TK_INITIALLY 40
52.44 +#define TK_INSTEAD 41
52.45 +#define TK_LIKE_KW 42
52.46 +#define TK_MATCH 43
52.47 +#define TK_KEY 44
52.48 +#define TK_OF 45
52.49 +#define TK_OFFSET 46
52.50 +#define TK_PRAGMA 47
52.51 +#define TK_RAISE 48
52.52 +#define TK_REPLACE 49
52.53 +#define TK_RESTRICT 50
52.54 +#define TK_ROW 51
52.55 +#define TK_TRIGGER 52
52.56 +#define TK_VACUUM 53
52.57 +#define TK_VIEW 54
52.58 +#define TK_VIRTUAL 55
52.59 +#define TK_REINDEX 56
52.60 +#define TK_RENAME 57
52.61 +#define TK_CTIME_KW 58
52.62 +#define TK_ANY 59
52.63 +#define TK_OR 60
52.64 +#define TK_AND 61
52.65 +#define TK_IS 62
52.66 +#define TK_BETWEEN 63
52.67 +#define TK_IN 64
52.68 +#define TK_ISNULL 65
52.69 +#define TK_NOTNULL 66
52.70 +#define TK_NE 67
52.71 +#define TK_EQ 68
52.72 +#define TK_GT 69
52.73 +#define TK_LE 70
52.74 +#define TK_LT 71
52.75 +#define TK_GE 72
52.76 +#define TK_ESCAPE 73
52.77 +#define TK_BITAND 74
52.78 +#define TK_BITOR 75
52.79 +#define TK_LSHIFT 76
52.80 +#define TK_RSHIFT 77
52.81 +#define TK_PLUS 78
52.82 +#define TK_MINUS 79
52.83 +#define TK_STAR 80
52.84 +#define TK_SLASH 81
52.85 +#define TK_REM 82
52.86 +#define TK_CONCAT 83
52.87 +#define TK_COLLATE 84
52.88 +#define TK_UMINUS 85
52.89 +#define TK_UPLUS 86
52.90 +#define TK_BITNOT 87
52.91 +#define TK_STRING 88
52.92 +#define TK_JOIN_KW 89
52.93 +#define TK_CONSTRAINT 90
52.94 +#define TK_DEFAULT 91
52.95 +#define TK_NULL 92
52.96 +#define TK_PRIMARY 93
52.97 +#define TK_UNIQUE 94
52.98 +#define TK_CHECK 95
52.99 +#define TK_REFERENCES 96
52.100 +#define TK_AUTOINCR 97
52.101 +#define TK_ON 98
52.102 +#define TK_DELETE 99
52.103 +#define TK_UPDATE 100
52.104 +#define TK_INSERT 101
52.105 +#define TK_SET 102
52.106 +#define TK_DEFERRABLE 103
52.107 +#define TK_FOREIGN 104
52.108 +#define TK_DROP 105
52.109 +#define TK_UNION 106
52.110 +#define TK_ALL 107
52.111 +#define TK_EXCEPT 108
52.112 +#define TK_INTERSECT 109
52.113 +#define TK_SELECT 110
52.114 +#define TK_DISTINCT 111
52.115 +#define TK_DOT 112
52.116 +#define TK_FROM 113
52.117 +#define TK_JOIN 114
52.118 +#define TK_USING 115
52.119 +#define TK_ORDER 116
52.120 +#define TK_BY 117
52.121 +#define TK_GROUP 118
52.122 +#define TK_HAVING 119
52.123 +#define TK_LIMIT 120
52.124 +#define TK_WHERE 121
52.125 +#define TK_INTO 122
52.126 +#define TK_VALUES 123
52.127 +#define TK_INTEGER 124
52.128 +#define TK_FLOAT 125
52.129 +#define TK_BLOB 126
52.130 +#define TK_REGISTER 127
52.131 +#define TK_VARIABLE 128
52.132 +#define TK_CASE 129
52.133 +#define TK_WHEN 130
52.134 +#define TK_THEN 131
52.135 +#define TK_ELSE 132
52.136 +#define TK_INDEX 133
52.137 +#define TK_ALTER 134
52.138 +#define TK_TO 135
52.139 +#define TK_ADD 136
52.140 +#define TK_COLUMNKW 137
52.141 +#define TK_TO_TEXT 138
52.142 +#define TK_TO_BLOB 139
52.143 +#define TK_TO_NUMERIC 140
52.144 +#define TK_TO_INT 141
52.145 +#define TK_TO_REAL 142
52.146 +#define TK_END_OF_FILE 143
52.147 +#define TK_ILLEGAL 144
52.148 +#define TK_SPACE 145
52.149 +#define TK_UNCLOSED_STRING 146
52.150 +#define TK_COMMENT 147
52.151 +#define TK_FUNCTION 148
52.152 +#define TK_COLUMN 149
52.153 +#define TK_AGG_FUNCTION 150
52.154 +#define TK_AGG_COLUMN 151
52.155 +#define TK_CONST_FUNC 152
53.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
53.2 +++ b/extensions/sqlite/sqlite-source/pragma.c Sun Jul 29 01:15:31 2007 +0000
53.3 @@ -0,0 +1,1180 @@
53.4 +/*
53.5 +** 2003 April 6
53.6 +**
53.7 +** The author disclaims copyright to this source code. In place of
53.8 +** a legal notice, here is a blessing:
53.9 +**
53.10 +** May you do good and not evil.
53.11 +** May you find forgiveness for yourself and forgive others.
53.12 +** May you share freely, never taking more than you give.
53.13 +**
53.14 +*************************************************************************
53.15 +** This file contains code used to implement the PRAGMA command.
53.16 +**
53.17 +** $Id$
53.18 +*/
53.19 +#include "sqliteInt.h"
53.20 +#include "os.h"
53.21 +#include <ctype.h>
53.22 +
53.23 +/* Ignore this whole file if pragmas are disabled
53.24 +*/
53.25 +#if !defined(SQLITE_OMIT_PRAGMA) && !defined(SQLITE_OMIT_PARSER)
53.26 +
53.27 +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
53.28 +# include "pager.h"
53.29 +# include "btree.h"
53.30 +#endif
53.31 +
53.32 +/*
53.33 +** Interpret the given string as a safety level. Return 0 for OFF,
53.34 +** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
53.35 +** unrecognized string argument.
53.36 +**
53.37 +** Note that the values returned are one less that the values that
53.38 +** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
53.39 +** to support legacy SQL code. The safety level used to be boolean
53.40 +** and older scripts may have used numbers 0 for OFF and 1 for ON.
53.41 +*/
53.42 +static int getSafetyLevel(const char *z){
53.43 + /* 123456789 123456789 */
53.44 + static const char zText[] = "onoffalseyestruefull";
53.45 + static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
53.46 + static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
53.47 + static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
53.48 + int i, n;
53.49 + if( isdigit(*z) ){
53.50 + return atoi(z);
53.51 + }
53.52 + n = strlen(z);
53.53 + for(i=0; i<sizeof(iLength); i++){
53.54 + if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
53.55 + return iValue[i];
53.56 + }
53.57 + }
53.58 + return 1;
53.59 +}
53.60 +
53.61 +/*
53.62 +** Interpret the given string as a boolean value.
53.63 +*/
53.64 +static int getBoolean(const char *z){
53.65 + return getSafetyLevel(z)&1;
53.66 +}
53.67 +
53.68 +/*
53.69 +** Interpret the given string as a locking mode value.
53.70 +*/
53.71 +static int getLockingMode(const char *z){
53.72 + if( z ){
53.73 + if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
53.74 + if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
53.75 + }
53.76 + return PAGER_LOCKINGMODE_QUERY;
53.77 +}
53.78 +
53.79 +#ifndef SQLITE_OMIT_AUTOVACUUM
53.80 +/*
53.81 +** Interpret the given string as an auto-vacuum mode value.
53.82 +**
53.83 +** The following strings, "none", "full" and "incremental" are
53.84 +** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
53.85 +*/
53.86 +static int getAutoVacuum(const char *z){
53.87 + int i;
53.88 + if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
53.89 + if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
53.90 + if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
53.91 + i = atoi(z);
53.92 + return ((i>=0&&i<=2)?i:0);
53.93 +}
53.94 +#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
53.95 +
53.96 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
53.97 +/*
53.98 +** Interpret the given string as a temp db location. Return 1 for file
53.99 +** backed temporary databases, 2 for the Red-Black tree in memory database
53.100 +** and 0 to use the compile-time default.
53.101 +*/
53.102 +static int getTempStore(const char *z){
53.103 + if( z[0]>='0' && z[0]<='2' ){
53.104 + return z[0] - '0';
53.105 + }else if( sqlite3StrICmp(z, "file")==0 ){
53.106 + return 1;
53.107 + }else if( sqlite3StrICmp(z, "memory")==0 ){
53.108 + return 2;
53.109 + }else{
53.110 + return 0;
53.111 + }
53.112 +}
53.113 +#endif /* SQLITE_PAGER_PRAGMAS */
53.114 +
53.115 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
53.116 +/*
53.117 +** Invalidate temp storage, either when the temp storage is changed
53.118 +** from default, or when 'file' and the temp_store_directory has changed
53.119 +*/
53.120 +static int invalidateTempStorage(Parse *pParse){
53.121 + sqlite3 *db = pParse->db;
53.122 + if( db->aDb[1].pBt!=0 ){
53.123 + if( !db->autoCommit ){
53.124 + sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
53.125 + "from within a transaction");
53.126 + return SQLITE_ERROR;
53.127 + }
53.128 + sqlite3BtreeClose(db->aDb[1].pBt);
53.129 + db->aDb[1].pBt = 0;
53.130 + sqlite3ResetInternalSchema(db, 0);
53.131 + }
53.132 + return SQLITE_OK;
53.133 +}
53.134 +#endif /* SQLITE_PAGER_PRAGMAS */
53.135 +
53.136 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
53.137 +/*
53.138 +** If the TEMP database is open, close it and mark the database schema
53.139 +** as needing reloading. This must be done when using the TEMP_STORE
53.140 +** or DEFAULT_TEMP_STORE pragmas.
53.141 +*/
53.142 +static int changeTempStorage(Parse *pParse, const char *zStorageType){
53.143 + int ts = getTempStore(zStorageType);
53.144 + sqlite3 *db = pParse->db;
53.145 + if( db->temp_store==ts ) return SQLITE_OK;
53.146 + if( invalidateTempStorage( pParse ) != SQLITE_OK ){
53.147 + return SQLITE_ERROR;
53.148 + }
53.149 + db->temp_store = ts;
53.150 + return SQLITE_OK;
53.151 +}
53.152 +#endif /* SQLITE_PAGER_PRAGMAS */
53.153 +
53.154 +/*
53.155 +** Generate code to return a single integer value.
53.156 +*/
53.157 +static void returnSingleInt(Parse *pParse, const char *zLabel, int value){
53.158 + Vdbe *v = sqlite3GetVdbe(pParse);
53.159 + sqlite3VdbeAddOp(v, OP_Integer, value, 0);
53.160 + if( pParse->explain==0 ){
53.161 + sqlite3VdbeSetNumCols(v, 1);
53.162 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, P3_STATIC);
53.163 + }
53.164 + sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
53.165 +}
53.166 +
53.167 +#ifndef SQLITE_OMIT_FLAG_PRAGMAS
53.168 +/*
53.169 +** Check to see if zRight and zLeft refer to a pragma that queries
53.170 +** or changes one of the flags in db->flags. Return 1 if so and 0 if not.
53.171 +** Also, implement the pragma.
53.172 +*/
53.173 +static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
53.174 + static const struct sPragmaType {
53.175 + const char *zName; /* Name of the pragma */
53.176 + int mask; /* Mask for the db->flags value */
53.177 + } aPragma[] = {
53.178 + { "full_column_names", SQLITE_FullColNames },
53.179 + { "short_column_names", SQLITE_ShortColNames },
53.180 + { "count_changes", SQLITE_CountRows },
53.181 + { "empty_result_callbacks", SQLITE_NullCallback },
53.182 + { "legacy_file_format", SQLITE_LegacyFileFmt },
53.183 + { "fullfsync", SQLITE_FullFSync },
53.184 +#ifdef SQLITE_DEBUG
53.185 + { "sql_trace", SQLITE_SqlTrace },
53.186 + { "vdbe_listing", SQLITE_VdbeListing },
53.187 + { "vdbe_trace", SQLITE_VdbeTrace },
53.188 +#endif
53.189 +#ifndef SQLITE_OMIT_CHECK
53.190 + { "ignore_check_constraints", SQLITE_IgnoreChecks },
53.191 +#endif
53.192 + /* The following is VERY experimental */
53.193 + { "writable_schema", SQLITE_WriteSchema|SQLITE_RecoveryMode },
53.194 + { "omit_readlock", SQLITE_NoReadlock },
53.195 +
53.196 + /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
53.197 + ** flag if there are any active statements. */
53.198 + { "read_uncommitted", SQLITE_ReadUncommitted },
53.199 + };
53.200 + int i;
53.201 + const struct sPragmaType *p;
53.202 + for(i=0, p=aPragma; i<sizeof(aPragma)/sizeof(aPragma[0]); i++, p++){
53.203 + if( sqlite3StrICmp(zLeft, p->zName)==0 ){
53.204 + sqlite3 *db = pParse->db;
53.205 + Vdbe *v;
53.206 + v = sqlite3GetVdbe(pParse);
53.207 + if( v ){
53.208 + if( zRight==0 ){
53.209 + returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
53.210 + }else{
53.211 + if( getBoolean(zRight) ){
53.212 + db->flags |= p->mask;
53.213 + }else{
53.214 + db->flags &= ~p->mask;
53.215 + }
53.216 + }
53.217 + }
53.218 + return 1;
53.219 + }
53.220 + }
53.221 + return 0;
53.222 +}
53.223 +#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
53.224 +
53.225 +/*
53.226 +** Process a pragma statement.
53.227 +**
53.228 +** Pragmas are of this form:
53.229 +**
53.230 +** PRAGMA [database.]id [= value]
53.231 +**
53.232 +** The identifier might also be a string. The value is a string, and
53.233 +** identifier, or a number. If minusFlag is true, then the value is
53.234 +** a number that was preceded by a minus sign.
53.235 +**
53.236 +** If the left side is "database.id" then pId1 is the database name
53.237 +** and pId2 is the id. If the left side is just "id" then pId1 is the
53.238 +** id and pId2 is any empty string.
53.239 +*/
53.240 +void sqlite3Pragma(
53.241 + Parse *pParse,
53.242 + Token *pId1, /* First part of [database.]id field */
53.243 + Token *pId2, /* Second part of [database.]id field, or NULL */
53.244 + Token *pValue, /* Token for <value>, or NULL */
53.245 + int minusFlag /* True if a '-' sign preceded <value> */
53.246 +){
53.247 + char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
53.248 + char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
53.249 + const char *zDb = 0; /* The database name */
53.250 + Token *pId; /* Pointer to <id> token */
53.251 + int iDb; /* Database index for <database> */
53.252 + sqlite3 *db = pParse->db;
53.253 + Db *pDb;
53.254 + Vdbe *v = sqlite3GetVdbe(pParse);
53.255 + if( v==0 ) return;
53.256 +
53.257 + /* Interpret the [database.] part of the pragma statement. iDb is the
53.258 + ** index of the database this pragma is being applied to in db.aDb[]. */
53.259 + iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
53.260 + if( iDb<0 ) return;
53.261 + pDb = &db->aDb[iDb];
53.262 +
53.263 + /* If the temp database has been explicitly named as part of the
53.264 + ** pragma, make sure it is open.
53.265 + */
53.266 + if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
53.267 + return;
53.268 + }
53.269 +
53.270 + zLeft = sqlite3NameFromToken(pId);
53.271 + if( !zLeft ) return;
53.272 + if( minusFlag ){
53.273 + zRight = sqlite3MPrintf("-%T", pValue);
53.274 + }else{
53.275 + zRight = sqlite3NameFromToken(pValue);
53.276 + }
53.277 +
53.278 + zDb = ((iDb>0)?pDb->zName:0);
53.279 + if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
53.280 + goto pragma_out;
53.281 + }
53.282 +
53.283 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
53.284 + /*
53.285 + ** PRAGMA [database.]default_cache_size
53.286 + ** PRAGMA [database.]default_cache_size=N
53.287 + **
53.288 + ** The first form reports the current persistent setting for the
53.289 + ** page cache size. The value returned is the maximum number of
53.290 + ** pages in the page cache. The second form sets both the current
53.291 + ** page cache size value and the persistent page cache size value
53.292 + ** stored in the database file.
53.293 + **
53.294 + ** The default cache size is stored in meta-value 2 of page 1 of the
53.295 + ** database file. The cache size is actually the absolute value of
53.296 + ** this memory location. The sign of meta-value 2 determines the
53.297 + ** synchronous setting. A negative value means synchronous is off
53.298 + ** and a positive value means synchronous is on.
53.299 + */
53.300 + if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
53.301 + static const VdbeOpList getCacheSize[] = {
53.302 + { OP_ReadCookie, 0, 2, 0}, /* 0 */
53.303 + { OP_AbsValue, 0, 0, 0},
53.304 + { OP_Dup, 0, 0, 0},
53.305 + { OP_Integer, 0, 0, 0},
53.306 + { OP_Ne, 0, 6, 0},
53.307 + { OP_Integer, 0, 0, 0}, /* 5 */
53.308 + { OP_Callback, 1, 0, 0},
53.309 + };
53.310 + int addr;
53.311 + if( sqlite3ReadSchema(pParse) ) goto pragma_out;
53.312 + if( !zRight ){
53.313 + sqlite3VdbeSetNumCols(v, 1);
53.314 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", P3_STATIC);
53.315 + addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
53.316 + sqlite3VdbeChangeP1(v, addr, iDb);
53.317 + sqlite3VdbeChangeP1(v, addr+5, SQLITE_DEFAULT_CACHE_SIZE);
53.318 + }else{
53.319 + int size = atoi(zRight);
53.320 + if( size<0 ) size = -size;
53.321 + sqlite3BeginWriteOperation(pParse, 0, iDb);
53.322 + sqlite3VdbeAddOp(v, OP_Integer, size, 0);
53.323 + sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 2);
53.324 + addr = sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
53.325 + sqlite3VdbeAddOp(v, OP_Ge, 0, addr+3);
53.326 + sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
53.327 + sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 2);
53.328 + pDb->pSchema->cache_size = size;
53.329 + sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
53.330 + }
53.331 + }else
53.332 +
53.333 + /*
53.334 + ** PRAGMA [database.]page_size
53.335 + ** PRAGMA [database.]page_size=N
53.336 + **
53.337 + ** The first form reports the current setting for the
53.338 + ** database page size in bytes. The second form sets the
53.339 + ** database page size value. The value can only be set if
53.340 + ** the database has not yet been created.
53.341 + */
53.342 + if( sqlite3StrICmp(zLeft,"page_size")==0 ){
53.343 + Btree *pBt = pDb->pBt;
53.344 + if( !zRight ){
53.345 + int size = pBt ? sqlite3BtreeGetPageSize(pBt) : 0;
53.346 + returnSingleInt(pParse, "page_size", size);
53.347 + }else{
53.348 + sqlite3BtreeSetPageSize(pBt, atoi(zRight), -1);
53.349 + }
53.350 + }else
53.351 +
53.352 + /*
53.353 + ** PRAGMA [database.]max_page_count
53.354 + ** PRAGMA [database.]max_page_count=N
53.355 + **
53.356 + ** The first form reports the current setting for the
53.357 + ** maximum number of pages in the database file. The
53.358 + ** second form attempts to change this setting. Both
53.359 + ** forms return the current setting.
53.360 + */
53.361 + if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
53.362 + Btree *pBt = pDb->pBt;
53.363 + int newMax = 0;
53.364 + if( zRight ){
53.365 + newMax = atoi(zRight);
53.366 + }
53.367 + if( pBt ){
53.368 + newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
53.369 + }
53.370 + returnSingleInt(pParse, "max_page_count", newMax);
53.371 + }else
53.372 +
53.373 + /*
53.374 + ** PRAGMA [database.]locking_mode
53.375 + ** PRAGMA [database.]locking_mode = (normal|exclusive)
53.376 + */
53.377 + if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
53.378 + const char *zRet = "normal";
53.379 + int eMode = getLockingMode(zRight);
53.380 +
53.381 + if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
53.382 + /* Simple "PRAGMA locking_mode;" statement. This is a query for
53.383 + ** the current default locking mode (which may be different to
53.384 + ** the locking-mode of the main database).
53.385 + */
53.386 + eMode = db->dfltLockMode;
53.387 + }else{
53.388 + Pager *pPager;
53.389 + if( pId2->n==0 ){
53.390 + /* This indicates that no database name was specified as part
53.391 + ** of the PRAGMA command. In this case the locking-mode must be
53.392 + ** set on all attached databases, as well as the main db file.
53.393 + **
53.394 + ** Also, the sqlite3.dfltLockMode variable is set so that
53.395 + ** any subsequently attached databases also use the specified
53.396 + ** locking mode.
53.397 + */
53.398 + int ii;
53.399 + assert(pDb==&db->aDb[0]);
53.400 + for(ii=2; ii<db->nDb; ii++){
53.401 + pPager = sqlite3BtreePager(db->aDb[ii].pBt);
53.402 + sqlite3PagerLockingMode(pPager, eMode);
53.403 + }
53.404 + db->dfltLockMode = eMode;
53.405 + }
53.406 + pPager = sqlite3BtreePager(pDb->pBt);
53.407 + eMode = sqlite3PagerLockingMode(pPager, eMode);
53.408 + }
53.409 +
53.410 + assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
53.411 + if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
53.412 + zRet = "exclusive";
53.413 + }
53.414 + sqlite3VdbeSetNumCols(v, 1);
53.415 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", P3_STATIC);
53.416 + sqlite3VdbeOp3(v, OP_String8, 0, 0, zRet, 0);
53.417 + sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
53.418 + }else
53.419 +#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
53.420 +
53.421 + /*
53.422 + ** PRAGMA [database.]auto_vacuum
53.423 + ** PRAGMA [database.]auto_vacuum=N
53.424 + **
53.425 + ** Get or set the (boolean) value of the database 'auto-vacuum' parameter.
53.426 + */
53.427 +#ifndef SQLITE_OMIT_AUTOVACUUM
53.428 + if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
53.429 + Btree *pBt = pDb->pBt;
53.430 + if( sqlite3ReadSchema(pParse) ){
53.431 + goto pragma_out;
53.432 + }
53.433 + if( !zRight ){
53.434 + int auto_vacuum =
53.435 + pBt ? sqlite3BtreeGetAutoVacuum(pBt) : SQLITE_DEFAULT_AUTOVACUUM;
53.436 + returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
53.437 + }else{
53.438 + int eAuto = getAutoVacuum(zRight);
53.439 + if( eAuto>=0 ){
53.440 + /* Call SetAutoVacuum() to set initialize the internal auto and
53.441 + ** incr-vacuum flags. This is required in case this connection
53.442 + ** creates the database file. It is important that it is created
53.443 + ** as an auto-vacuum capable db.
53.444 + */
53.445 + int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
53.446 + if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
53.447 + /* When setting the auto_vacuum mode to either "full" or
53.448 + ** "incremental", write the value of meta[6] in the database
53.449 + ** file. Before writing to meta[6], check that meta[3] indicates
53.450 + ** that this really is an auto-vacuum capable database.
53.451 + */
53.452 + static const VdbeOpList setMeta6[] = {
53.453 + { OP_Transaction, 0, 1, 0}, /* 0 */
53.454 + { OP_ReadCookie, 0, 3, 0}, /* 1 */
53.455 + { OP_If, 0, 0, 0}, /* 2 */
53.456 + { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
53.457 + { OP_Integer, 0, 0, 0}, /* 4 */
53.458 + { OP_SetCookie, 0, 6, 0}, /* 5 */
53.459 + };
53.460 + int iAddr;
53.461 + iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
53.462 + sqlite3VdbeChangeP1(v, iAddr, iDb);
53.463 + sqlite3VdbeChangeP1(v, iAddr+1, iDb);
53.464 + sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
53.465 + sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
53.466 + sqlite3VdbeChangeP1(v, iAddr+5, iDb);
53.467 + }
53.468 + }
53.469 + }
53.470 + }else
53.471 +#endif
53.472 +
53.473 + /*
53.474 + ** PRAGMA [database.]incremental_vacuum(N)
53.475 + **
53.476 + ** Do N steps of incremental vacuuming on a database.
53.477 + */
53.478 +#ifndef SQLITE_OMIT_AUTOVACUUM
53.479 + if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
53.480 + int iLimit, addr;
53.481 + if( sqlite3ReadSchema(pParse) ){
53.482 + goto pragma_out;
53.483 + }
53.484 + if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
53.485 + iLimit = 0x7fffffff;
53.486 + }
53.487 + sqlite3BeginWriteOperation(pParse, 0, iDb);
53.488 + sqlite3VdbeAddOp(v, OP_MemInt, iLimit, 0);
53.489 + addr = sqlite3VdbeAddOp(v, OP_IncrVacuum, iDb, 0);
53.490 + sqlite3VdbeAddOp(v, OP_Callback, 0, 0);
53.491 + sqlite3VdbeAddOp(v, OP_MemIncr, -1, 0);
53.492 + sqlite3VdbeAddOp(v, OP_IfMemPos, 0, addr);
53.493 + sqlite3VdbeJumpHere(v, addr);
53.494 + }else
53.495 +#endif
53.496 +
53.497 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
53.498 + /*
53.499 + ** PRAGMA [database.]cache_size
53.500 + ** PRAGMA [database.]cache_size=N
53.501 + **
53.502 + ** The first form reports the current local setting for the
53.503 + ** page cache size. The local setting can be different from
53.504 + ** the persistent cache size value that is stored in the database
53.505 + ** file itself. The value returned is the maximum number of
53.506 + ** pages in the page cache. The second form sets the local
53.507 + ** page cache size value. It does not change the persistent
53.508 + ** cache size stored on the disk so the cache size will revert
53.509 + ** to its default value when the database is closed and reopened.
53.510 + ** N should be a positive integer.
53.511 + */
53.512 + if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
53.513 + if( sqlite3ReadSchema(pParse) ) goto pragma_out;
53.514 + if( !zRight ){
53.515 + returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
53.516 + }else{
53.517 + int size = atoi(zRight);
53.518 + if( size<0 ) size = -size;
53.519 + pDb->pSchema->cache_size = size;
53.520 + sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
53.521 + }
53.522 + }else
53.523 +
53.524 + /*
53.525 + ** PRAGMA temp_store
53.526 + ** PRAGMA temp_store = "default"|"memory"|"file"
53.527 + **
53.528 + ** Return or set the local value of the temp_store flag. Changing
53.529 + ** the local value does not make changes to the disk file and the default
53.530 + ** value will be restored the next time the database is opened.
53.531 + **
53.532 + ** Note that it is possible for the library compile-time options to
53.533 + ** override this setting
53.534 + */
53.535 + if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
53.536 + if( !zRight ){
53.537 + returnSingleInt(pParse, "temp_store", db->temp_store);
53.538 + }else{
53.539 + changeTempStorage(pParse, zRight);
53.540 + }
53.541 + }else
53.542 +
53.543 + /*
53.544 + ** PRAGMA temp_store_directory
53.545 + ** PRAGMA temp_store_directory = ""|"directory_name"
53.546 + **
53.547 + ** Return or set the local value of the temp_store_directory flag. Changing
53.548 + ** the value sets a specific directory to be used for temporary files.
53.549 + ** Setting to a null string reverts to the default temporary directory search.
53.550 + ** If temporary directory is changed, then invalidateTempStorage.
53.551 + **
53.552 + */
53.553 + if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
53.554 + if( !zRight ){
53.555 + if( sqlite3_temp_directory ){
53.556 + sqlite3VdbeSetNumCols(v, 1);
53.557 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
53.558 + "temp_store_directory", P3_STATIC);
53.559 + sqlite3VdbeOp3(v, OP_String8, 0, 0, sqlite3_temp_directory, 0);
53.560 + sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
53.561 + }
53.562 + }else{
53.563 + if( zRight[0] && !sqlite3OsIsDirWritable(zRight) ){
53.564 + sqlite3ErrorMsg(pParse, "not a writable directory");
53.565 + goto pragma_out;
53.566 + }
53.567 + if( TEMP_STORE==0
53.568 + || (TEMP_STORE==1 && db->temp_store<=1)
53.569 + || (TEMP_STORE==2 && db->temp_store==1)
53.570 + ){
53.571 + invalidateTempStorage(pParse);
53.572 + }
53.573 + sqliteFree(sqlite3_temp_directory);
53.574 + if( zRight[0] ){
53.575 + sqlite3_temp_directory = zRight;
53.576 + zRight = 0;
53.577 + }else{
53.578 + sqlite3_temp_directory = 0;
53.579 + }
53.580 + }
53.581 + }else
53.582 +
53.583 + /*
53.584 + ** PRAGMA [database.]synchronous
53.585 + ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
53.586 + **
53.587 + ** Return or set the local value of the synchronous flag. Changing
53.588 + ** the local value does not make changes to the disk file and the
53.589 + ** default value will be restored the next time the database is
53.590 + ** opened.
53.591 + */
53.592 + if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
53.593 + if( sqlite3ReadSchema(pParse) ) goto pragma_out;
53.594 + if( !zRight ){
53.595 + returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
53.596 + }else{
53.597 + if( !db->autoCommit ){
53.598 + sqlite3ErrorMsg(pParse,
53.599 + "Safety level may not be changed inside a transaction");
53.600 + }else{
53.601 + pDb->safety_level = getSafetyLevel(zRight)+1;
53.602 + }
53.603 + }
53.604 + }else
53.605 +#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
53.606 +
53.607 +#ifndef SQLITE_OMIT_FLAG_PRAGMAS
53.608 + if( flagPragma(pParse, zLeft, zRight) ){
53.609 + /* The flagPragma() subroutine also generates any necessary code
53.610 + ** there is nothing more to do here */
53.611 + }else
53.612 +#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
53.613 +
53.614 +#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
53.615 + /*
53.616 + ** PRAGMA table_info(<table>)
53.617 + **
53.618 + ** Return a single row for each column of the named table. The columns of
53.619 + ** the returned data set are:
53.620 + **
53.621 + ** cid: Column id (numbered from left to right, starting at 0)
53.622 + ** name: Column name
53.623 + ** type: Column declaration type.
53.624 + ** notnull: True if 'NOT NULL' is part of column declaration
53.625 + ** dflt_value: The default value for the column, if any.
53.626 + */
53.627 + if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
53.628 + Table *pTab;
53.629 + if( sqlite3ReadSchema(pParse) ) goto pragma_out;
53.630 + pTab = sqlite3FindTable(db, zRight, zDb);
53.631 + if( pTab ){
53.632 + int i;
53.633 + int nHidden = 0;
53.634 + Column *pCol;
53.635 + sqlite3VdbeSetNumCols(v, 6);
53.636 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", P3_STATIC);
53.637 + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC);
53.638 + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", P3_STATIC);
53.639 + sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", P3_STATIC);
53.640 + sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", P3_STATIC);
53.641 + sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", P3_STATIC);
53.642 + sqlite3ViewGetColumnNames(pParse, pTab);
53.643 + for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
53.644 + const Token *pDflt;
53.645 + if( IsHiddenColumn(pCol) ){
53.646 + nHidden++;
53.647 + continue;
53.648 + }
53.649 + sqlite3VdbeAddOp(v, OP_Integer, i-nHidden, 0);
53.650 + sqlite3VdbeOp3(v, OP_String8, 0, 0, pCol->zName, 0);
53.651 + sqlite3VdbeOp3(v, OP_String8, 0, 0,
53.652 + pCol->zType ? pCol->zType : "", 0);
53.653 + sqlite3VdbeAddOp(v, OP_Integer, pCol->notNull, 0);
53.654 + if( pCol->pDflt && (pDflt = &pCol->pDflt->span)->z ){
53.655 + sqlite3VdbeOp3(v, OP_String8, 0, 0, (char*)pDflt->z, pDflt->n);
53.656 + }else{
53.657 + sqlite3VdbeAddOp(v, OP_Null, 0, 0);
53.658 + }
53.659 + sqlite3VdbeAddOp(v, OP_Integer, pCol->isPrimKey, 0);
53.660 + sqlite3VdbeAddOp(v, OP_Callback, 6, 0);
53.661 + }
53.662 + }
53.663 + }else
53.664 +
53.665 + if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
53.666 + Index *pIdx;
53.667 + Table *pTab;
53.668 + if( sqlite3ReadSchema(pParse) ) goto pragma_out;
53.669 + pIdx = sqlite3FindIndex(db, zRight, zDb);
53.670 + if( pIdx ){
53.671 + int i;
53.672 + pTab = pIdx->pTable;
53.673 + sqlite3VdbeSetNumCols(v, 3);
53.674 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", P3_STATIC);
53.675 + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", P3_STATIC);
53.676 + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", P3_STATIC);
53.677 + for(i=0; i<pIdx->nColumn; i++){
53.678 + int cnum = pIdx->aiColumn[i];
53.679 + sqlite3VdbeAddOp(v, OP_Integer, i, 0);
53.680 + sqlite3VdbeAddOp(v, OP_Integer, cnum, 0);
53.681 + assert( pTab->nCol>cnum );
53.682 + sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->aCol[cnum].zName, 0);
53.683 + sqlite3VdbeAddOp(v, OP_Callback, 3, 0);
53.684 + }
53.685 + }
53.686 + }else
53.687 +
53.688 + if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
53.689 + Index *pIdx;
53.690 + Table *pTab;
53.691 + if( sqlite3ReadSchema(pParse) ) goto pragma_out;
53.692 + pTab = sqlite3FindTable(db, zRight, zDb);
53.693 + if( pTab ){
53.694 + v = sqlite3GetVdbe(pParse);
53.695 + pIdx = pTab->pIndex;
53.696 + if( pIdx ){
53.697 + int i = 0;
53.698 + sqlite3VdbeSetNumCols(v, 3);
53.699 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P3_STATIC);
53.700 + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC);
53.701 + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", P3_STATIC);
53.702 + while(pIdx){
53.703 + sqlite3VdbeAddOp(v, OP_Integer, i, 0);
53.704 + sqlite3VdbeOp3(v, OP_String8, 0, 0, pIdx->zName, 0);
53.705 + sqlite3VdbeAddOp(v, OP_Integer, pIdx->onError!=OE_None, 0);
53.706 + sqlite3VdbeAddOp(v, OP_Callback, 3, 0);
53.707 + ++i;
53.708 + pIdx = pIdx->pNext;
53.709 + }
53.710 + }
53.711 + }
53.712 + }else
53.713 +
53.714 + if( sqlite3StrICmp(zLeft, "database_list")==0 ){
53.715 + int i;
53.716 + if( sqlite3ReadSchema(pParse) ) goto pragma_out;
53.717 + sqlite3VdbeSetNumCols(v, 3);
53.718 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P3_STATIC);
53.719 + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC);
53.720 + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", P3_STATIC);
53.721 + for(i=0; i<db->nDb; i++){
53.722 + if( db->aDb[i].pBt==0 ) continue;
53.723 + assert( db->aDb[i].zName!=0 );
53.724 + sqlite3VdbeAddOp(v, OP_Integer, i, 0);
53.725 + sqlite3VdbeOp3(v, OP_String8, 0, 0, db->aDb[i].zName, 0);
53.726 + sqlite3VdbeOp3(v, OP_String8, 0, 0,
53.727 + sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
53.728 + sqlite3VdbeAddOp(v, OP_Callback, 3, 0);
53.729 + }
53.730 + }else
53.731 +
53.732 + if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
53.733 + int i = 0;
53.734 + HashElem *p;
53.735 + sqlite3VdbeSetNumCols(v, 2);
53.736 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P3_STATIC);
53.737 + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC);
53.738 + for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
53.739 + CollSeq *pColl = (CollSeq *)sqliteHashData(p);
53.740 + sqlite3VdbeAddOp(v, OP_Integer, i++, 0);
53.741 + sqlite3VdbeOp3(v, OP_String8, 0, 0, pColl->zName, 0);
53.742 + sqlite3VdbeAddOp(v, OP_Callback, 2, 0);
53.743 + }
53.744 + }else
53.745 +#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
53.746 +
53.747 +#ifndef SQLITE_OMIT_FOREIGN_KEY
53.748 + if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
53.749 + FKey *pFK;
53.750 + Table *pTab;
53.751 + if( sqlite3ReadSchema(pParse) ) goto pragma_out;
53.752 + pTab = sqlite3FindTable(db, zRight, zDb);
53.753 + if( pTab ){
53.754 + v = sqlite3GetVdbe(pParse);
53.755 + pFK = pTab->pFKey;
53.756 + if( pFK ){
53.757 + int i = 0;
53.758 + sqlite3VdbeSetNumCols(v, 5);
53.759 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", P3_STATIC);
53.760 + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", P3_STATIC);
53.761 + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", P3_STATIC);
53.762 + sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", P3_STATIC);
53.763 + sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", P3_STATIC);
53.764 + while(pFK){
53.765 + int j;
53.766 + for(j=0; j<pFK->nCol; j++){
53.767 + char *zCol = pFK->aCol[j].zCol;
53.768 + sqlite3VdbeAddOp(v, OP_Integer, i, 0);
53.769 + sqlite3VdbeAddOp(v, OP_Integer, j, 0);
53.770 + sqlite3VdbeOp3(v, OP_String8, 0, 0, pFK->zTo, 0);
53.771 + sqlite3VdbeOp3(v, OP_String8, 0, 0,
53.772 + pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
53.773 + sqlite3VdbeOp3(v, zCol ? OP_String8 : OP_Null, 0, 0, zCol, 0);
53.774 + sqlite3VdbeAddOp(v, OP_Callback, 5, 0);
53.775 + }
53.776 + ++i;
53.777 + pFK = pFK->pNextFrom;
53.778 + }
53.779 + }
53.780 + }
53.781 + }else
53.782 +#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
53.783 +
53.784 +#ifndef NDEBUG
53.785 + if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
53.786 + if( zRight ){
53.787 + if( getBoolean(zRight) ){
53.788 + sqlite3ParserTrace(stderr, "parser: ");
53.789 + }else{
53.790 + sqlite3ParserTrace(0, 0);
53.791 + }
53.792 + }
53.793 + }else
53.794 +#endif
53.795 +
53.796 + /* Reinstall the LIKE and GLOB functions. The variant of LIKE
53.797 + ** used will be case sensitive or not depending on the RHS.
53.798 + */
53.799 + if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
53.800 + if( zRight ){
53.801 + sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
53.802 + }
53.803 + }else
53.804 +
53.805 +#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
53.806 +# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
53.807 +#endif
53.808 +
53.809 +#ifndef SQLITE_OMIT_INTEGRITY_CHECK
53.810 + if( sqlite3StrICmp(zLeft, "integrity_check")==0 ){
53.811 + int i, j, addr, mxErr;
53.812 +
53.813 + /* Code that appears at the end of the integrity check. If no error
53.814 + ** messages have been generated, output OK. Otherwise output the
53.815 + ** error message
53.816 + */
53.817 + static const VdbeOpList endCode[] = {
53.818 + { OP_MemLoad, 0, 0, 0},
53.819 + { OP_Integer, 0, 0, 0},
53.820 + { OP_Ne, 0, 0, 0}, /* 2 */
53.821 + { OP_String8, 0, 0, "ok"},
53.822 + { OP_Callback, 1, 0, 0},
53.823 + };
53.824 +
53.825 + /* Initialize the VDBE program */
53.826 + if( sqlite3ReadSchema(pParse) ) goto pragma_out;
53.827 + sqlite3VdbeSetNumCols(v, 1);
53.828 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", P3_STATIC);
53.829 +
53.830 + /* Set the maximum error count */
53.831 + mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
53.832 + if( zRight ){
53.833 + mxErr = atoi(zRight);
53.834 + if( mxErr<=0 ){
53.835 + mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
53.836 + }
53.837 + }
53.838 + sqlite3VdbeAddOp(v, OP_MemInt, mxErr, 0);
53.839 +
53.840 + /* Do an integrity check on each database file */
53.841 + for(i=0; i<db->nDb; i++){
53.842 + HashElem *x;
53.843 + Hash *pTbls;
53.844 + int cnt = 0;
53.845 +
53.846 + if( OMIT_TEMPDB && i==1 ) continue;
53.847 +
53.848 + sqlite3CodeVerifySchema(pParse, i);
53.849 + addr = sqlite3VdbeAddOp(v, OP_IfMemPos, 0, 0);
53.850 + sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
53.851 + sqlite3VdbeJumpHere(v, addr);
53.852 +
53.853 + /* Do an integrity check of the B-Tree
53.854 + */
53.855 + pTbls = &db->aDb[i].pSchema->tblHash;
53.856 + for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
53.857 + Table *pTab = sqliteHashData(x);
53.858 + Index *pIdx;
53.859 + sqlite3VdbeAddOp(v, OP_Integer, pTab->tnum, 0);
53.860 + cnt++;
53.861 + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
53.862 + sqlite3VdbeAddOp(v, OP_Integer, pIdx->tnum, 0);
53.863 + cnt++;
53.864 + }
53.865 + }
53.866 + if( cnt==0 ) continue;
53.867 + sqlite3VdbeAddOp(v, OP_IntegrityCk, 0, i);
53.868 + addr = sqlite3VdbeAddOp(v, OP_IsNull, -1, 0);
53.869 + sqlite3VdbeOp3(v, OP_String8, 0, 0,
53.870 + sqlite3MPrintf("*** in database %s ***\n", db->aDb[i].zName),
53.871 + P3_DYNAMIC);
53.872 + sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
53.873 + sqlite3VdbeAddOp(v, OP_Concat, 0, 0);
53.874 + sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
53.875 + sqlite3VdbeJumpHere(v, addr);
53.876 +
53.877 + /* Make sure all the indices are constructed correctly.
53.878 + */
53.879 + for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
53.880 + Table *pTab = sqliteHashData(x);
53.881 + Index *pIdx;
53.882 + int loopTop;
53.883 +
53.884 + if( pTab->pIndex==0 ) continue;
53.885 + addr = sqlite3VdbeAddOp(v, OP_IfMemPos, 0, 0);
53.886 + sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
53.887 + sqlite3VdbeJumpHere(v, addr);
53.888 + sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
53.889 + sqlite3VdbeAddOp(v, OP_MemInt, 0, 1);
53.890 + loopTop = sqlite3VdbeAddOp(v, OP_Rewind, 1, 0);
53.891 + sqlite3VdbeAddOp(v, OP_MemIncr, 1, 1);
53.892 + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
53.893 + int jmp2;
53.894 + static const VdbeOpList idxErr[] = {
53.895 + { OP_MemIncr, -1, 0, 0},
53.896 + { OP_String8, 0, 0, "rowid "},
53.897 + { OP_Rowid, 1, 0, 0},
53.898 + { OP_String8, 0, 0, " missing from index "},
53.899 + { OP_String8, 0, 0, 0}, /* 4 */
53.900 + { OP_Concat, 2, 0, 0},
53.901 + { OP_Callback, 1, 0, 0},
53.902 + };
53.903 + sqlite3GenerateIndexKey(v, pIdx, 1);
53.904 + jmp2 = sqlite3VdbeAddOp(v, OP_Found, j+2, 0);
53.905 + addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
53.906 + sqlite3VdbeChangeP3(v, addr+4, pIdx->zName, P3_STATIC);
53.907 + sqlite3VdbeJumpHere(v, jmp2);
53.908 + }
53.909 + sqlite3VdbeAddOp(v, OP_Next, 1, loopTop+1);
53.910 + sqlite3VdbeJumpHere(v, loopTop);
53.911 + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
53.912 + static const VdbeOpList cntIdx[] = {
53.913 + { OP_MemInt, 0, 2, 0},
53.914 + { OP_Rewind, 0, 0, 0}, /* 1 */
53.915 + { OP_MemIncr, 1, 2, 0},
53.916 + { OP_Next, 0, 0, 0}, /* 3 */
53.917 + { OP_MemLoad, 1, 0, 0},
53.918 + { OP_MemLoad, 2, 0, 0},
53.919 + { OP_Eq, 0, 0, 0}, /* 6 */
53.920 + { OP_MemIncr, -1, 0, 0},
53.921 + { OP_String8, 0, 0, "wrong # of entries in index "},
53.922 + { OP_String8, 0, 0, 0}, /* 9 */
53.923 + { OP_Concat, 0, 0, 0},
53.924 + { OP_Callback, 1, 0, 0},
53.925 + };
53.926 + if( pIdx->tnum==0 ) continue;
53.927 + addr = sqlite3VdbeAddOp(v, OP_IfMemPos, 0, 0);
53.928 + sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
53.929 + sqlite3VdbeJumpHere(v, addr);
53.930 + addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
53.931 + sqlite3VdbeChangeP1(v, addr+1, j+2);
53.932 + sqlite3VdbeChangeP2(v, addr+1, addr+4);
53.933 + sqlite3VdbeChangeP1(v, addr+3, j+2);
53.934 + sqlite3VdbeChangeP2(v, addr+3, addr+2);
53.935 + sqlite3VdbeJumpHere(v, addr+6);
53.936 + sqlite3VdbeChangeP3(v, addr+9, pIdx->zName, P3_STATIC);
53.937 + }
53.938 + }
53.939 + }
53.940 + addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
53.941 + sqlite3VdbeChangeP1(v, addr+1, mxErr);
53.942 + sqlite3VdbeJumpHere(v, addr+2);
53.943 + }else
53.944 +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
53.945 +
53.946 +#ifndef SQLITE_OMIT_UTF16
53.947 + /*
53.948 + ** PRAGMA encoding
53.949 + ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
53.950 + **
53.951 + ** In it's first form, this pragma returns the encoding of the main
53.952 + ** database. If the database is not initialized, it is initialized now.
53.953 + **
53.954 + ** The second form of this pragma is a no-op if the main database file
53.955 + ** has not already been initialized. In this case it sets the default
53.956 + ** encoding that will be used for the main database file if a new file
53.957 + ** is created. If an existing main database file is opened, then the
53.958 + ** default text encoding for the existing database is used.
53.959 + **
53.960 + ** In all cases new databases created using the ATTACH command are
53.961 + ** created to use the same default text encoding as the main database. If
53.962 + ** the main database has not been initialized and/or created when ATTACH
53.963 + ** is executed, this is done before the ATTACH operation.
53.964 + **
53.965 + ** In the second form this pragma sets the text encoding to be used in
53.966 + ** new database files created using this database handle. It is only
53.967 + ** useful if invoked immediately after the main database i
53.968 + */
53.969 + if( sqlite3StrICmp(zLeft, "encoding")==0 ){
53.970 + static const struct EncName {
53.971 + char *zName;
53.972 + u8 enc;
53.973 + } encnames[] = {
53.974 + { "UTF-8", SQLITE_UTF8 },
53.975 + { "UTF8", SQLITE_UTF8 },
53.976 + { "UTF-16le", SQLITE_UTF16LE },
53.977 + { "UTF16le", SQLITE_UTF16LE },
53.978 + { "UTF-16be", SQLITE_UTF16BE },
53.979 + { "UTF16be", SQLITE_UTF16BE },
53.980 + { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
53.981 + { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
53.982 + { 0, 0 }
53.983 + };
53.984 + const struct EncName *pEnc;
53.985 + if( !zRight ){ /* "PRAGMA encoding" */
53.986 + if( sqlite3ReadSchema(pParse) ) goto pragma_out;
53.987 + sqlite3VdbeSetNumCols(v, 1);
53.988 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", P3_STATIC);
53.989 + sqlite3VdbeAddOp(v, OP_String8, 0, 0);
53.990 + for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
53.991 + if( pEnc->enc==ENC(pParse->db) ){
53.992 + sqlite3VdbeChangeP3(v, -1, pEnc->zName, P3_STATIC);
53.993 + break;
53.994 + }
53.995 + }
53.996 + sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
53.997 + }else{ /* "PRAGMA encoding = XXX" */
53.998 + /* Only change the value of sqlite.enc if the database handle is not
53.999 + ** initialized. If the main database exists, the new sqlite.enc value
53.1000 + ** will be overwritten when the schema is next loaded. If it does not
53.1001 + ** already exists, it will be created to use the new encoding value.
53.1002 + */
53.1003 + if(
53.1004 + !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
53.1005 + DbHasProperty(db, 0, DB_Empty)
53.1006 + ){
53.1007 + for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
53.1008 + if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
53.1009 + ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
53.1010 + break;
53.1011 + }
53.1012 + }
53.1013 + if( !pEnc->zName ){
53.1014 + sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
53.1015 + }
53.1016 + }
53.1017 + }
53.1018 + }else
53.1019 +#endif /* SQLITE_OMIT_UTF16 */
53.1020 +
53.1021 +#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
53.1022 + /*
53.1023 + ** PRAGMA [database.]schema_version
53.1024 + ** PRAGMA [database.]schema_version = <integer>
53.1025 + **
53.1026 + ** PRAGMA [database.]user_version
53.1027 + ** PRAGMA [database.]user_version = <integer>
53.1028 + **
53.1029 + ** The pragma's schema_version and user_version are used to set or get
53.1030 + ** the value of the schema-version and user-version, respectively. Both
53.1031 + ** the schema-version and the user-version are 32-bit signed integers
53.1032 + ** stored in the database header.
53.1033 + **
53.1034 + ** The schema-cookie is usually only manipulated internally by SQLite. It
53.1035 + ** is incremented by SQLite whenever the database schema is modified (by
53.1036 + ** creating or dropping a table or index). The schema version is used by
53.1037 + ** SQLite each time a query is executed to ensure that the internal cache
53.1038 + ** of the schema used when compiling the SQL query matches the schema of
53.1039 + ** the database against which the compiled query is actually executed.
53.1040 + ** Subverting this mechanism by using "PRAGMA schema_version" to modify
53.1041 + ** the schema-version is potentially dangerous and may lead to program
53.1042 + ** crashes or database corruption. Use with caution!
53.1043 + **
53.1044 + ** The user-version is not used internally by SQLite. It may be used by
53.1045 + ** applications for any purpose.
53.1046 + */
53.1047 + if( sqlite3StrICmp(zLeft, "schema_version")==0
53.1048 + || sqlite3StrICmp(zLeft, "user_version")==0
53.1049 + || sqlite3StrICmp(zLeft, "freelist_count")==0
53.1050 + ){
53.1051 +
53.1052 + int iCookie; /* Cookie index. 0 for schema-cookie, 6 for user-cookie. */
53.1053 + switch( zLeft[0] ){
53.1054 + case 's': case 'S':
53.1055 + iCookie = 0;
53.1056 + break;
53.1057 + case 'f': case 'F':
53.1058 + iCookie = 1;
53.1059 + iDb = (-1*(iDb+1));
53.1060 + assert(iDb<=0);
53.1061 + break;
53.1062 + default:
53.1063 + iCookie = 5;
53.1064 + break;
53.1065 + }
53.1066 +
53.1067 + if( zRight && iDb>=0 ){
53.1068 + /* Write the specified cookie value */
53.1069 + static const VdbeOpList setCookie[] = {
53.1070 + { OP_Transaction, 0, 1, 0}, /* 0 */
53.1071 + { OP_Integer, 0, 0, 0}, /* 1 */
53.1072 + { OP_SetCookie, 0, 0, 0}, /* 2 */
53.1073 + };
53.1074 + int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
53.1075 + sqlite3VdbeChangeP1(v, addr, iDb);
53.1076 + sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
53.1077 + sqlite3VdbeChangeP1(v, addr+2, iDb);
53.1078 + sqlite3VdbeChangeP2(v, addr+2, iCookie);
53.1079 + }else{
53.1080 + /* Read the specified cookie value */
53.1081 + static const VdbeOpList readCookie[] = {
53.1082 + { OP_ReadCookie, 0, 0, 0}, /* 0 */
53.1083 + { OP_Callback, 1, 0, 0}
53.1084 + };
53.1085 + int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
53.1086 + sqlite3VdbeChangeP1(v, addr, iDb);
53.1087 + sqlite3VdbeChangeP2(v, addr, iCookie);
53.1088 + sqlite3VdbeSetNumCols(v, 1);
53.1089 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, P3_TRANSIENT);
53.1090 + }
53.1091 + }else
53.1092 +#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
53.1093 +
53.1094 +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
53.1095 + /*
53.1096 + ** Report the current state of file logs for all databases
53.1097 + */
53.1098 + if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
53.1099 + static const char *const azLockName[] = {
53.1100 + "unlocked", "shared", "reserved", "pending", "exclusive"
53.1101 + };
53.1102 + int i;
53.1103 + Vdbe *v = sqlite3GetVdbe(pParse);
53.1104 + sqlite3VdbeSetNumCols(v, 2);
53.1105 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", P3_STATIC);
53.1106 + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", P3_STATIC);
53.1107 + for(i=0; i<db->nDb; i++){
53.1108 + Btree *pBt;
53.1109 + Pager *pPager;
53.1110 + if( db->aDb[i].zName==0 ) continue;
53.1111 + sqlite3VdbeOp3(v, OP_String8, 0, 0, db->aDb[i].zName, P3_STATIC);
53.1112 + pBt = db->aDb[i].pBt;
53.1113 + if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
53.1114 + sqlite3VdbeOp3(v, OP_String8, 0, 0, "closed", P3_STATIC);
53.1115 + }else{
53.1116 + int j = sqlite3PagerLockstate(pPager);
53.1117 + sqlite3VdbeOp3(v, OP_String8, 0, 0,
53.1118 + (j>=0 && j<=4) ? azLockName[j] : "unknown", P3_STATIC);
53.1119 + }
53.1120 + sqlite3VdbeAddOp(v, OP_Callback, 2, 0);
53.1121 + }
53.1122 + }else
53.1123 +#endif
53.1124 +
53.1125 +#ifdef SQLITE_SSE
53.1126 + /*
53.1127 + ** Check to see if the sqlite_statements table exists. Create it
53.1128 + ** if it does not.
53.1129 + */
53.1130 + if( sqlite3StrICmp(zLeft, "create_sqlite_statement_table")==0 ){
53.1131 + extern int sqlite3CreateStatementsTable(Parse*);
53.1132 + sqlite3CreateStatementsTable(pParse);
53.1133 + }else
53.1134 +#endif
53.1135 +
53.1136 +#if SQLITE_HAS_CODEC
53.1137 + if( sqlite3StrICmp(zLeft, "key")==0 ){
53.1138 + sqlite3_key(db, zRight, strlen(zRight));
53.1139 + }else
53.1140 +#endif
53.1141 +#if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
53.1142 + if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
53.1143 +#if SQLITE_HAS_CODEC
53.1144 + if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
53.1145 + extern void sqlite3_activate_see(const char*);
53.1146 + sqlite3_activate_see(&zRight[4]);
53.1147 + }
53.1148 +#endif
53.1149 +#ifdef SQLITE_ENABLE_CEROD
53.1150 + if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
53.1151 + extern void sqlite3_activate_cerod(const char*);
53.1152 + sqlite3_activate_cerod(&zRight[6]);
53.1153 + }
53.1154 +#endif
53.1155 + }
53.1156 +#endif
53.1157 +
53.1158 + {}
53.1159 +
53.1160 + if( v ){
53.1161 + /* Code an OP_Expire at the end of each PRAGMA program to cause
53.1162 + ** the VDBE implementing the pragma to expire. Most (all?) pragmas
53.1163 + ** are only valid for a single execution.
53.1164 + */
53.1165 + sqlite3VdbeAddOp(v, OP_Expire, 1, 0);
53.1166 +
53.1167 + /*
53.1168 + ** Reset the safety level, in case the fullfsync flag or synchronous
53.1169 + ** setting changed.
53.1170 + */
53.1171 +#ifndef SQLITE_OMIT_PAGER_PRAGMAS
53.1172 + if( db->autoCommit ){
53.1173 + sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
53.1174 + (db->flags&SQLITE_FullFSync)!=0);
53.1175 + }
53.1176 +#endif
53.1177 + }
53.1178 +pragma_out:
53.1179 + sqliteFree(zLeft);
53.1180 + sqliteFree(zRight);
53.1181 +}
53.1182 +
53.1183 +#endif /* SQLITE_OMIT_PRAGMA || SQLITE_OMIT_PARSER */
54.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
54.2 +++ b/extensions/sqlite/sqlite-source/prepare.c Sun Jul 29 01:15:31 2007 +0000
54.3 @@ -0,0 +1,697 @@
54.4 +/*
54.5 +** 2005 May 25
54.6 +**
54.7 +** The author disclaims copyright to this source code. In place of
54.8 +** a legal notice, here is a blessing:
54.9 +**
54.10 +** May you do good and not evil.
54.11 +** May you find forgiveness for yourself and forgive others.
54.12 +** May you share freely, never taking more than you give.
54.13 +**
54.14 +*************************************************************************
54.15 +** This file contains the implementation of the sqlite3_prepare()
54.16 +** interface, and routines that contribute to loading the database schema
54.17 +** from disk.
54.18 +**
54.19 +** $Id$
54.20 +*/
54.21 +#include "sqliteInt.h"
54.22 +#include "os.h"
54.23 +#include <ctype.h>
54.24 +
54.25 +/*
54.26 +** Fill the InitData structure with an error message that indicates
54.27 +** that the database is corrupt.
54.28 +*/
54.29 +static void corruptSchema(InitData *pData, const char *zExtra){
54.30 + if( !sqlite3MallocFailed() ){
54.31 + sqlite3SetString(pData->pzErrMsg, "malformed database schema",
54.32 + zExtra!=0 && zExtra[0]!=0 ? " - " : (char*)0, zExtra, (char*)0);
54.33 + }
54.34 + pData->rc = SQLITE_CORRUPT;
54.35 +}
54.36 +
54.37 +/*
54.38 +** This is the callback routine for the code that initializes the
54.39 +** database. See sqlite3Init() below for additional information.
54.40 +** This routine is also called from the OP_ParseSchema opcode of the VDBE.
54.41 +**
54.42 +** Each callback contains the following information:
54.43 +**
54.44 +** argv[0] = name of thing being created
54.45 +** argv[1] = root page number for table or index. 0 for trigger or view.
54.46 +** argv[2] = SQL text for the CREATE statement.
54.47 +**
54.48 +*/
54.49 +int sqlite3InitCallback(void *pInit, int argc, char **argv, char **azColName){
54.50 + InitData *pData = (InitData*)pInit;
54.51 + sqlite3 *db = pData->db;
54.52 + int iDb = pData->iDb;
54.53 +
54.54 + pData->rc = SQLITE_OK;
54.55 + DbClearProperty(db, iDb, DB_Empty);
54.56 + if( sqlite3MallocFailed() ){
54.57 + corruptSchema(pData, 0);
54.58 + return SQLITE_NOMEM;
54.59 + }
54.60 +
54.61 + assert( argc==3 );
54.62 + if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
54.63 + if( argv[1]==0 ){
54.64 + corruptSchema(pData, 0);
54.65 + return 1;
54.66 + }
54.67 + assert( iDb>=0 && iDb<db->nDb );
54.68 + if( argv[2] && argv[2][0] ){
54.69 + /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
54.70 + ** But because db->init.busy is set to 1, no VDBE code is generated
54.71 + ** or executed. All the parser does is build the internal data
54.72 + ** structures that describe the table, index, or view.
54.73 + */
54.74 + char *zErr;
54.75 + int rc;
54.76 + assert( db->init.busy );
54.77 + db->init.iDb = iDb;
54.78 + db->init.newTnum = atoi(argv[1]);
54.79 + rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
54.80 + db->init.iDb = 0;
54.81 + assert( rc!=SQLITE_OK || zErr==0 );
54.82 + if( SQLITE_OK!=rc ){
54.83 + pData->rc = rc;
54.84 + if( rc==SQLITE_NOMEM ){
54.85 + sqlite3FailedMalloc();
54.86 + }else if( rc!=SQLITE_INTERRUPT ){
54.87 + corruptSchema(pData, zErr);
54.88 + }
54.89 + sqlite3_free(zErr);
54.90 + return 1;
54.91 + }
54.92 + }else{
54.93 + /* If the SQL column is blank it means this is an index that
54.94 + ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
54.95 + ** constraint for a CREATE TABLE. The index should have already
54.96 + ** been created when we processed the CREATE TABLE. All we have
54.97 + ** to do here is record the root page number for that index.
54.98 + */
54.99 + Index *pIndex;
54.100 + pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
54.101 + if( pIndex==0 || pIndex->tnum!=0 ){
54.102 + /* This can occur if there exists an index on a TEMP table which
54.103 + ** has the same name as another index on a permanent index. Since
54.104 + ** the permanent table is hidden by the TEMP table, we can also
54.105 + ** safely ignore the index on the permanent table.
54.106 + */
54.107 + /* Do Nothing */;
54.108 + }else{
54.109 + pIndex->tnum = atoi(argv[1]);
54.110 + }
54.111 + }
54.112 + return 0;
54.113 +}
54.114 +
54.115 +/*
54.116 +** Attempt to read the database schema and initialize internal
54.117 +** data structures for a single database file. The index of the
54.118 +** database file is given by iDb. iDb==0 is used for the main
54.119 +** database. iDb==1 should never be used. iDb>=2 is used for
54.120 +** auxiliary databases. Return one of the SQLITE_ error codes to
54.121 +** indicate success or failure.
54.122 +*/
54.123 +static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
54.124 + int rc;
54.125 + BtCursor *curMain;
54.126 + int size;
54.127 + Table *pTab;
54.128 + Db *pDb;
54.129 + char const *azArg[4];
54.130 + int meta[10];
54.131 + InitData initData;
54.132 + char const *zMasterSchema;
54.133 + char const *zMasterName = SCHEMA_TABLE(iDb);
54.134 +
54.135 + /*
54.136 + ** The master database table has a structure like this
54.137 + */
54.138 + static const char master_schema[] =
54.139 + "CREATE TABLE sqlite_master(\n"
54.140 + " type text,\n"
54.141 + " name text,\n"
54.142 + " tbl_name text,\n"
54.143 + " rootpage integer,\n"
54.144 + " sql text\n"
54.145 + ")"
54.146 + ;
54.147 +#ifndef SQLITE_OMIT_TEMPDB
54.148 + static const char temp_master_schema[] =
54.149 + "CREATE TEMP TABLE sqlite_temp_master(\n"
54.150 + " type text,\n"
54.151 + " name text,\n"
54.152 + " tbl_name text,\n"
54.153 + " rootpage integer,\n"
54.154 + " sql text\n"
54.155 + ")"
54.156 + ;
54.157 +#else
54.158 + #define temp_master_schema 0
54.159 +#endif
54.160 +
54.161 + assert( iDb>=0 && iDb<db->nDb );
54.162 + assert( db->aDb[iDb].pSchema );
54.163 +
54.164 + /* zMasterSchema and zInitScript are set to point at the master schema
54.165 + ** and initialisation script appropriate for the database being
54.166 + ** initialised. zMasterName is the name of the master table.
54.167 + */
54.168 + if( !OMIT_TEMPDB && iDb==1 ){
54.169 + zMasterSchema = temp_master_schema;
54.170 + }else{
54.171 + zMasterSchema = master_schema;
54.172 + }
54.173 + zMasterName = SCHEMA_TABLE(iDb);
54.174 +
54.175 + /* Construct the schema tables. */
54.176 + sqlite3SafetyOff(db);
54.177 + azArg[0] = zMasterName;
54.178 + azArg[1] = "1";
54.179 + azArg[2] = zMasterSchema;
54.180 + azArg[3] = 0;
54.181 + initData.db = db;
54.182 + initData.iDb = iDb;
54.183 + initData.pzErrMsg = pzErrMsg;
54.184 + rc = sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
54.185 + if( rc ){
54.186 + sqlite3SafetyOn(db);
54.187 + return initData.rc;
54.188 + }
54.189 + pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
54.190 + if( pTab ){
54.191 + pTab->readOnly = 1;
54.192 + }
54.193 + sqlite3SafetyOn(db);
54.194 +
54.195 + /* Create a cursor to hold the database open
54.196 + */
54.197 + pDb = &db->aDb[iDb];
54.198 + if( pDb->pBt==0 ){
54.199 + if( !OMIT_TEMPDB && iDb==1 ){
54.200 + DbSetProperty(db, 1, DB_SchemaLoaded);
54.201 + }
54.202 + return SQLITE_OK;
54.203 + }
54.204 + rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, 0, &curMain);
54.205 + if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
54.206 + sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);
54.207 + return rc;
54.208 + }
54.209 +
54.210 + /* Get the database meta information.
54.211 + **
54.212 + ** Meta values are as follows:
54.213 + ** meta[0] Schema cookie. Changes with each schema change.
54.214 + ** meta[1] File format of schema layer.
54.215 + ** meta[2] Size of the page cache.
54.216 + ** meta[3] Use freelist if 0. Autovacuum if greater than zero.
54.217 + ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
54.218 + ** meta[5] The user cookie. Used by the application.
54.219 + ** meta[6] Incremental-vacuum flag.
54.220 + ** meta[7]
54.221 + ** meta[8]
54.222 + ** meta[9]
54.223 + **
54.224 + ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
54.225 + ** the possible values of meta[4].
54.226 + */
54.227 + if( rc==SQLITE_OK ){
54.228 + int i;
54.229 + for(i=0; rc==SQLITE_OK && i<sizeof(meta)/sizeof(meta[0]); i++){
54.230 + rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
54.231 + }
54.232 + if( rc ){
54.233 + sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);
54.234 + sqlite3BtreeCloseCursor(curMain);
54.235 + return rc;
54.236 + }
54.237 + }else{
54.238 + memset(meta, 0, sizeof(meta));
54.239 + }
54.240 + pDb->pSchema->schema_cookie = meta[0];
54.241 +
54.242 + /* If opening a non-empty database, check the text encoding. For the
54.243 + ** main database, set sqlite3.enc to the encoding of the main database.
54.244 + ** For an attached db, it is an error if the encoding is not the same
54.245 + ** as sqlite3.enc.
54.246 + */
54.247 + if( meta[4] ){ /* text encoding */
54.248 + if( iDb==0 ){
54.249 + /* If opening the main database, set ENC(db). */
54.250 + ENC(db) = (u8)meta[4];
54.251 + db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
54.252 + }else{
54.253 + /* If opening an attached database, the encoding much match ENC(db) */
54.254 + if( meta[4]!=ENC(db) ){
54.255 + sqlite3BtreeCloseCursor(curMain);
54.256 + sqlite3SetString(pzErrMsg, "attached databases must use the same"
54.257 + " text encoding as main database", (char*)0);
54.258 + return SQLITE_ERROR;
54.259 + }
54.260 + }
54.261 + }else{
54.262 + DbSetProperty(db, iDb, DB_Empty);
54.263 + }
54.264 + pDb->pSchema->enc = ENC(db);
54.265 +
54.266 + size = meta[2];
54.267 + if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
54.268 + pDb->pSchema->cache_size = size;
54.269 + sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
54.270 +
54.271 + /*
54.272 + ** file_format==1 Version 3.0.0.
54.273 + ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
54.274 + ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
54.275 + ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
54.276 + */
54.277 + pDb->pSchema->file_format = meta[1];
54.278 + if( pDb->pSchema->file_format==0 ){
54.279 + pDb->pSchema->file_format = 1;
54.280 + }
54.281 + if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
54.282 + sqlite3BtreeCloseCursor(curMain);
54.283 + sqlite3SetString(pzErrMsg, "unsupported file format", (char*)0);
54.284 + return SQLITE_ERROR;
54.285 + }
54.286 +
54.287 +
54.288 + /* Read the schema information out of the schema tables
54.289 + */
54.290 + assert( db->init.busy );
54.291 + if( rc==SQLITE_EMPTY ){
54.292 + /* For an empty database, there is nothing to read */
54.293 + rc = SQLITE_OK;
54.294 + }else{
54.295 + char *zSql;
54.296 + zSql = sqlite3MPrintf(
54.297 + "SELECT name, rootpage, sql FROM '%q'.%s",
54.298 + db->aDb[iDb].zName, zMasterName);
54.299 + sqlite3SafetyOff(db);
54.300 + rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
54.301 + if( rc==SQLITE_ABORT ) rc = initData.rc;
54.302 + sqlite3SafetyOn(db);
54.303 + sqliteFree(zSql);
54.304 +#ifndef SQLITE_OMIT_ANALYZE
54.305 + if( rc==SQLITE_OK ){
54.306 + sqlite3AnalysisLoad(db, iDb);
54.307 + }
54.308 +#endif
54.309 + sqlite3BtreeCloseCursor(curMain);
54.310 + }
54.311 + if( sqlite3MallocFailed() ){
54.312 + /* sqlite3SetString(pzErrMsg, "out of memory", (char*)0); */
54.313 + rc = SQLITE_NOMEM;
54.314 + sqlite3ResetInternalSchema(db, 0);
54.315 + }
54.316 + if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
54.317 + /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
54.318 + ** the schema loaded, even if errors occured. In this situation the
54.319 + ** current sqlite3_prepare() operation will fail, but the following one
54.320 + ** will attempt to compile the supplied statement against whatever subset
54.321 + ** of the schema was loaded before the error occured. The primary
54.322 + ** purpose of this is to allow access to the sqlite_master table
54.323 + ** even when it's contents have been corrupted.
54.324 + */
54.325 + DbSetProperty(db, iDb, DB_SchemaLoaded);
54.326 + rc = SQLITE_OK;
54.327 + }
54.328 + return rc;
54.329 +}
54.330 +
54.331 +/*
54.332 +** Initialize all database files - the main database file, the file
54.333 +** used to store temporary tables, and any additional database files
54.334 +** created using ATTACH statements. Return a success code. If an
54.335 +** error occurs, write an error message into *pzErrMsg.
54.336 +**
54.337 +** After a database is initialized, the DB_SchemaLoaded bit is set
54.338 +** bit is set in the flags field of the Db structure. If the database
54.339 +** file was of zero-length, then the DB_Empty flag is also set.
54.340 +*/
54.341 +int sqlite3Init(sqlite3 *db, char **pzErrMsg){
54.342 + int i, rc;
54.343 + int called_initone = 0;
54.344 +
54.345 + if( db->init.busy ) return SQLITE_OK;
54.346 + rc = SQLITE_OK;
54.347 + db->init.busy = 1;
54.348 + for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
54.349 + if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
54.350 + rc = sqlite3InitOne(db, i, pzErrMsg);
54.351 + if( rc ){
54.352 + sqlite3ResetInternalSchema(db, i);
54.353 + }
54.354 + called_initone = 1;
54.355 + }
54.356 +
54.357 + /* Once all the other databases have been initialised, load the schema
54.358 + ** for the TEMP database. This is loaded last, as the TEMP database
54.359 + ** schema may contain references to objects in other databases.
54.360 + */
54.361 +#ifndef SQLITE_OMIT_TEMPDB
54.362 + if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
54.363 + rc = sqlite3InitOne(db, 1, pzErrMsg);
54.364 + if( rc ){
54.365 + sqlite3ResetInternalSchema(db, 1);
54.366 + }
54.367 + called_initone = 1;
54.368 + }
54.369 +#endif
54.370 +
54.371 + db->init.busy = 0;
54.372 + if( rc==SQLITE_OK && called_initone ){
54.373 + sqlite3CommitInternalChanges(db);
54.374 + }
54.375 +
54.376 + return rc;
54.377 +}
54.378 +
54.379 +/*
54.380 +** This routine is a no-op if the database schema is already initialised.
54.381 +** Otherwise, the schema is loaded. An error code is returned.
54.382 +*/
54.383 +int sqlite3ReadSchema(Parse *pParse){
54.384 + int rc = SQLITE_OK;
54.385 + sqlite3 *db = pParse->db;
54.386 + if( !db->init.busy ){
54.387 + rc = sqlite3Init(db, &pParse->zErrMsg);
54.388 + }
54.389 + if( rc!=SQLITE_OK ){
54.390 + pParse->rc = rc;
54.391 + pParse->nErr++;
54.392 + }
54.393 + return rc;
54.394 +}
54.395 +
54.396 +
54.397 +/*
54.398 +** Check schema cookies in all databases. If any cookie is out
54.399 +** of date, return 0. If all schema cookies are current, return 1.
54.400 +*/
54.401 +static int schemaIsValid(sqlite3 *db){
54.402 + int iDb;
54.403 + int rc;
54.404 + BtCursor *curTemp;
54.405 + int cookie;
54.406 + int allOk = 1;
54.407 +
54.408 + for(iDb=0; allOk && iDb<db->nDb; iDb++){
54.409 + Btree *pBt;
54.410 + pBt = db->aDb[iDb].pBt;
54.411 + if( pBt==0 ) continue;
54.412 + rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, 0, &curTemp);
54.413 + if( rc==SQLITE_OK ){
54.414 + rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie);
54.415 + if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){
54.416 + allOk = 0;
54.417 + }
54.418 + sqlite3BtreeCloseCursor(curTemp);
54.419 + }
54.420 + }
54.421 + return allOk;
54.422 +}
54.423 +
54.424 +/*
54.425 +** Convert a schema pointer into the iDb index that indicates
54.426 +** which database file in db->aDb[] the schema refers to.
54.427 +**
54.428 +** If the same database is attached more than once, the first
54.429 +** attached database is returned.
54.430 +*/
54.431 +int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
54.432 + int i = -1000000;
54.433 +
54.434 + /* If pSchema is NULL, then return -1000000. This happens when code in
54.435 + ** expr.c is trying to resolve a reference to a transient table (i.e. one
54.436 + ** created by a sub-select). In this case the return value of this
54.437 + ** function should never be used.
54.438 + **
54.439 + ** We return -1000000 instead of the more usual -1 simply because using
54.440 + ** -1000000 as incorrectly using -1000000 index into db->aDb[] is much
54.441 + ** more likely to cause a segfault than -1 (of course there are assert()
54.442 + ** statements too, but it never hurts to play the odds).
54.443 + */
54.444 + if( pSchema ){
54.445 + for(i=0; i<db->nDb; i++){
54.446 + if( db->aDb[i].pSchema==pSchema ){
54.447 + break;
54.448 + }
54.449 + }
54.450 + assert( i>=0 &&i>=0 && i<db->nDb );
54.451 + }
54.452 + return i;
54.453 +}
54.454 +
54.455 +/*
54.456 +** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
54.457 +*/
54.458 +int sqlite3Prepare(
54.459 + sqlite3 *db, /* Database handle. */
54.460 + const char *zSql, /* UTF-8 encoded SQL statement. */
54.461 + int nBytes, /* Length of zSql in bytes. */
54.462 + int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
54.463 + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
54.464 + const char **pzTail /* OUT: End of parsed string */
54.465 +){
54.466 + Parse sParse;
54.467 + char *zErrMsg = 0;
54.468 + int rc = SQLITE_OK;
54.469 + int i;
54.470 +
54.471 + /* Assert that malloc() has not failed */
54.472 + assert( !sqlite3MallocFailed() );
54.473 +
54.474 + assert( ppStmt );
54.475 + *ppStmt = 0;
54.476 + if( sqlite3SafetyOn(db) ){
54.477 + return SQLITE_MISUSE;
54.478 + }
54.479 +
54.480 + /* If any attached database schemas are locked, do not proceed with
54.481 + ** compilation. Instead return SQLITE_LOCKED immediately.
54.482 + */
54.483 + for(i=0; i<db->nDb; i++) {
54.484 + Btree *pBt = db->aDb[i].pBt;
54.485 + if( pBt && sqlite3BtreeSchemaLocked(pBt) ){
54.486 + const char *zDb = db->aDb[i].zName;
54.487 + sqlite3Error(db, SQLITE_LOCKED, "database schema is locked: %s", zDb);
54.488 + sqlite3SafetyOff(db);
54.489 + return SQLITE_LOCKED;
54.490 + }
54.491 + }
54.492 +
54.493 + memset(&sParse, 0, sizeof(sParse));
54.494 + sParse.db = db;
54.495 + if( nBytes>=0 && zSql[nBytes]!=0 ){
54.496 + char *zSqlCopy;
54.497 + if( nBytes>SQLITE_MAX_SQL_LENGTH ){
54.498 + return SQLITE_TOOBIG;
54.499 + }
54.500 + zSqlCopy = sqlite3StrNDup(zSql, nBytes);
54.501 + if( zSqlCopy ){
54.502 + sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
54.503 + sqliteFree(zSqlCopy);
54.504 + }
54.505 + sParse.zTail = &zSql[nBytes];
54.506 + }else{
54.507 + sqlite3RunParser(&sParse, zSql, &zErrMsg);
54.508 + }
54.509 +
54.510 + if( sqlite3MallocFailed() ){
54.511 + sParse.rc = SQLITE_NOMEM;
54.512 + }
54.513 + if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
54.514 + if( sParse.checkSchema && !schemaIsValid(db) ){
54.515 + sParse.rc = SQLITE_SCHEMA;
54.516 + }
54.517 + if( sParse.rc==SQLITE_SCHEMA ){
54.518 + sqlite3ResetInternalSchema(db, 0);
54.519 + }
54.520 + if( sqlite3MallocFailed() ){
54.521 + sParse.rc = SQLITE_NOMEM;
54.522 + }
54.523 + if( pzTail ){
54.524 + *pzTail = sParse.zTail;
54.525 + }
54.526 + rc = sParse.rc;
54.527 +
54.528 +#ifndef SQLITE_OMIT_EXPLAIN
54.529 + if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
54.530 + if( sParse.explain==2 ){
54.531 + sqlite3VdbeSetNumCols(sParse.pVdbe, 3);
54.532 + sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "order", P3_STATIC);
54.533 + sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "from", P3_STATIC);
54.534 + sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "detail", P3_STATIC);
54.535 + }else{
54.536 + sqlite3VdbeSetNumCols(sParse.pVdbe, 5);
54.537 + sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "addr", P3_STATIC);
54.538 + sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "opcode", P3_STATIC);
54.539 + sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "p1", P3_STATIC);
54.540 + sqlite3VdbeSetColName(sParse.pVdbe, 3, COLNAME_NAME, "p2", P3_STATIC);
54.541 + sqlite3VdbeSetColName(sParse.pVdbe, 4, COLNAME_NAME, "p3", P3_STATIC);
54.542 + }
54.543 + }
54.544 +#endif
54.545 +
54.546 + if( sqlite3SafetyOff(db) ){
54.547 + rc = SQLITE_MISUSE;
54.548 + }
54.549 +
54.550 + if( saveSqlFlag ){
54.551 + sqlite3VdbeSetSql(sParse.pVdbe, zSql, sParse.zTail - zSql);
54.552 + }
54.553 + if( rc!=SQLITE_OK || sqlite3MallocFailed() ){
54.554 + sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
54.555 + assert(!(*ppStmt));
54.556 + }else{
54.557 + *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
54.558 + }
54.559 +
54.560 + if( zErrMsg ){
54.561 + sqlite3Error(db, rc, "%s", zErrMsg);
54.562 + sqliteFree(zErrMsg);
54.563 + }else{
54.564 + sqlite3Error(db, rc, 0);
54.565 + }
54.566 +
54.567 + rc = sqlite3ApiExit(db, rc);
54.568 + sqlite3ReleaseThreadData();
54.569 + assert( (rc&db->errMask)==rc );
54.570 + return rc;
54.571 +}
54.572 +
54.573 +/*
54.574 +** Rerun the compilation of a statement after a schema change.
54.575 +** Return true if the statement was recompiled successfully.
54.576 +** Return false if there is an error of some kind.
54.577 +*/
54.578 +int sqlite3Reprepare(Vdbe *p){
54.579 + int rc;
54.580 + sqlite3_stmt *pNew;
54.581 + const char *zSql;
54.582 + sqlite3 *db;
54.583 +
54.584 + zSql = sqlite3VdbeGetSql(p);
54.585 + if( zSql==0 ){
54.586 + return 0;
54.587 + }
54.588 + db = sqlite3VdbeDb(p);
54.589 + rc = sqlite3Prepare(db, zSql, -1, 0, &pNew, 0);
54.590 + if( rc ){
54.591 + assert( pNew==0 );
54.592 + return 0;
54.593 + }else{
54.594 + assert( pNew!=0 );
54.595 + }
54.596 + sqlite3VdbeSwap((Vdbe*)pNew, p);
54.597 + sqlite3_transfer_bindings(pNew, (sqlite3_stmt*)p);
54.598 + sqlite3VdbeResetStepResult((Vdbe*)pNew);
54.599 + sqlite3VdbeFinalize((Vdbe*)pNew);
54.600 + return 1;
54.601 +}
54.602 +
54.603 +
54.604 +/*
54.605 +** Two versions of the official API. Legacy and new use. In the legacy
54.606 +** version, the original SQL text is not saved in the prepared statement
54.607 +** and so if a schema change occurs, SQLITE_SCHEMA is returned by
54.608 +** sqlite3_step(). In the new version, the original SQL text is retained
54.609 +** and the statement is automatically recompiled if an schema change
54.610 +** occurs.
54.611 +*/
54.612 +int sqlite3_prepare(
54.613 + sqlite3 *db, /* Database handle. */
54.614 + const char *zSql, /* UTF-8 encoded SQL statement. */
54.615 + int nBytes, /* Length of zSql in bytes. */
54.616 + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
54.617 + const char **pzTail /* OUT: End of parsed string */
54.618 +){
54.619 + return sqlite3Prepare(db,zSql,nBytes,0,ppStmt,pzTail);
54.620 +}
54.621 +int sqlite3_prepare_v2(
54.622 + sqlite3 *db, /* Database handle. */
54.623 + const char *zSql, /* UTF-8 encoded SQL statement. */
54.624 + int nBytes, /* Length of zSql in bytes. */
54.625 + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
54.626 + const char **pzTail /* OUT: End of parsed string */
54.627 +){
54.628 + return sqlite3Prepare(db,zSql,nBytes,1,ppStmt,pzTail);
54.629 +}
54.630 +
54.631 +
54.632 +#ifndef SQLITE_OMIT_UTF16
54.633 +/*
54.634 +** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
54.635 +*/
54.636 +static int sqlite3Prepare16(
54.637 + sqlite3 *db, /* Database handle. */
54.638 + const void *zSql, /* UTF-8 encoded SQL statement. */
54.639 + int nBytes, /* Length of zSql in bytes. */
54.640 + int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
54.641 + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
54.642 + const void **pzTail /* OUT: End of parsed string */
54.643 +){
54.644 + /* This function currently works by first transforming the UTF-16
54.645 + ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
54.646 + ** tricky bit is figuring out the pointer to return in *pzTail.
54.647 + */
54.648 + char *zSql8;
54.649 + const char *zTail8 = 0;
54.650 + int rc = SQLITE_OK;
54.651 +
54.652 + if( sqlite3SafetyCheck(db) ){
54.653 + return SQLITE_MISUSE;
54.654 + }
54.655 + zSql8 = sqlite3Utf16to8(zSql, nBytes);
54.656 + if( zSql8 ){
54.657 + rc = sqlite3Prepare(db, zSql8, -1, saveSqlFlag, ppStmt, &zTail8);
54.658 + }
54.659 +
54.660 + if( zTail8 && pzTail ){
54.661 + /* If sqlite3_prepare returns a tail pointer, we calculate the
54.662 + ** equivalent pointer into the UTF-16 string by counting the unicode
54.663 + ** characters between zSql8 and zTail8, and then returning a pointer
54.664 + ** the same number of characters into the UTF-16 string.
54.665 + */
54.666 + int chars_parsed = sqlite3Utf8CharLen(zSql8, zTail8-zSql8);
54.667 + *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
54.668 + }
54.669 + sqliteFree(zSql8);
54.670 + return sqlite3ApiExit(db, rc);
54.671 +}
54.672 +
54.673 +/*
54.674 +** Two versions of the official API. Legacy and new use. In the legacy
54.675 +** version, the original SQL text is not saved in the prepared statement
54.676 +** and so if a schema change occurs, SQLITE_SCHEMA is returned by
54.677 +** sqlite3_step(). In the new version, the original SQL text is retained
54.678 +** and the statement is automatically recompiled if an schema change
54.679 +** occurs.
54.680 +*/
54.681 +int sqlite3_prepare16(
54.682 + sqlite3 *db, /* Database handle. */
54.683 + const void *zSql, /* UTF-8 encoded SQL statement. */
54.684 + int nBytes, /* Length of zSql in bytes. */
54.685 + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
54.686 + const void **pzTail /* OUT: End of parsed string */
54.687 +){
54.688 + return sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
54.689 +}
54.690 +int sqlite3_prepare16_v2(
54.691 + sqlite3 *db, /* Database handle. */
54.692 + const void *zSql, /* UTF-8 encoded SQL statement. */
54.693 + int nBytes, /* Length of zSql in bytes. */
54.694 + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
54.695 + const void **pzTail /* OUT: End of parsed string */
54.696 +){
54.697 + return sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
54.698 +}
54.699 +
54.700 +#endif /* SQLITE_OMIT_UTF16 */
55.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
55.2 +++ b/extensions/sqlite/sqlite-source/printf.c Sun Jul 29 01:15:31 2007 +0000
55.3 @@ -0,0 +1,885 @@
55.4 +/*
55.5 +** The "printf" code that follows dates from the 1980's. It is in
55.6 +** the public domain. The original comments are included here for
55.7 +** completeness. They are very out-of-date but might be useful as
55.8 +** an historical reference. Most of the "enhancements" have been backed
55.9 +** out so that the functionality is now the same as standard printf().
55.10 +**
55.11 +**************************************************************************
55.12 +**
55.13 +** The following modules is an enhanced replacement for the "printf" subroutines
55.14 +** found in the standard C library. The following enhancements are
55.15 +** supported:
55.16 +**
55.17 +** + Additional functions. The standard set of "printf" functions
55.18 +** includes printf, fprintf, sprintf, vprintf, vfprintf, and
55.19 +** vsprintf. This module adds the following:
55.20 +**
55.21 +** * snprintf -- Works like sprintf, but has an extra argument
55.22 +** which is the size of the buffer written to.
55.23 +**
55.24 +** * mprintf -- Similar to sprintf. Writes output to memory
55.25 +** obtained from malloc.
55.26 +**
55.27 +** * xprintf -- Calls a function to dispose of output.
55.28 +**
55.29 +** * nprintf -- No output, but returns the number of characters
55.30 +** that would have been output by printf.
55.31 +**
55.32 +** * A v- version (ex: vsnprintf) of every function is also
55.33 +** supplied.
55.34 +**
55.35 +** + A few extensions to the formatting notation are supported:
55.36 +**
55.37 +** * The "=" flag (similar to "-") causes the output to be
55.38 +** be centered in the appropriately sized field.
55.39 +**
55.40 +** * The %b field outputs an integer in binary notation.
55.41 +**
55.42 +** * The %c field now accepts a precision. The character output
55.43 +** is repeated by the number of times the precision specifies.
55.44 +**
55.45 +** * The %' field works like %c, but takes as its character the
55.46 +** next character of the format string, instead of the next
55.47 +** argument. For example, printf("%.78'-") prints 78 minus
55.48 +** signs, the same as printf("%.78c",'-').
55.49 +**
55.50 +** + When compiled using GCC on a SPARC, this version of printf is
55.51 +** faster than the library printf for SUN OS 4.1.
55.52 +**
55.53 +** + All functions are fully reentrant.
55.54 +**
55.55 +*/
55.56 +#include "sqliteInt.h"
55.57 +#include <math.h>
55.58 +
55.59 +/*
55.60 +** Conversion types fall into various categories as defined by the
55.61 +** following enumeration.
55.62 +*/
55.63 +#define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
55.64 +#define etFLOAT 2 /* Floating point. %f */
55.65 +#define etEXP 3 /* Exponentional notation. %e and %E */
55.66 +#define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
55.67 +#define etSIZE 5 /* Return number of characters processed so far. %n */
55.68 +#define etSTRING 6 /* Strings. %s */
55.69 +#define etDYNSTRING 7 /* Dynamically allocated strings. %z */
55.70 +#define etPERCENT 8 /* Percent symbol. %% */
55.71 +#define etCHARX 9 /* Characters. %c */
55.72 +/* The rest are extensions, not normally found in printf() */
55.73 +#define etCHARLIT 10 /* Literal characters. %' */
55.74 +#define etSQLESCAPE 11 /* Strings with '\'' doubled. %q */
55.75 +#define etSQLESCAPE2 12 /* Strings with '\'' doubled and enclosed in '',
55.76 + NULL pointers replaced by SQL NULL. %Q */
55.77 +#define etTOKEN 13 /* a pointer to a Token structure */
55.78 +#define etSRCLIST 14 /* a pointer to a SrcList */
55.79 +#define etPOINTER 15 /* The %p conversion */
55.80 +#define etSQLESCAPE3 16 /* %w -> Strings with '\"' doubled */
55.81 +
55.82 +
55.83 +/*
55.84 +** An "etByte" is an 8-bit unsigned value.
55.85 +*/
55.86 +typedef unsigned char etByte;
55.87 +
55.88 +/*
55.89 +** Each builtin conversion character (ex: the 'd' in "%d") is described
55.90 +** by an instance of the following structure
55.91 +*/
55.92 +typedef struct et_info { /* Information about each format field */
55.93 + char fmttype; /* The format field code letter */
55.94 + etByte base; /* The base for radix conversion */
55.95 + etByte flags; /* One or more of FLAG_ constants below */
55.96 + etByte type; /* Conversion paradigm */
55.97 + etByte charset; /* Offset into aDigits[] of the digits string */
55.98 + etByte prefix; /* Offset into aPrefix[] of the prefix string */
55.99 +} et_info;
55.100 +
55.101 +/*
55.102 +** Allowed values for et_info.flags
55.103 +*/
55.104 +#define FLAG_SIGNED 1 /* True if the value to convert is signed */
55.105 +#define FLAG_INTERN 2 /* True if for internal use only */
55.106 +#define FLAG_STRING 4 /* Allow infinity precision */
55.107 +
55.108 +
55.109 +/*
55.110 +** The following table is searched linearly, so it is good to put the
55.111 +** most frequently used conversion types first.
55.112 +*/
55.113 +static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
55.114 +static const char aPrefix[] = "-x0\000X0";
55.115 +static const et_info fmtinfo[] = {
55.116 + { 'd', 10, 1, etRADIX, 0, 0 },
55.117 + { 's', 0, 4, etSTRING, 0, 0 },
55.118 + { 'g', 0, 1, etGENERIC, 30, 0 },
55.119 + { 'z', 0, 6, etDYNSTRING, 0, 0 },
55.120 + { 'q', 0, 4, etSQLESCAPE, 0, 0 },
55.121 + { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
55.122 + { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
55.123 + { 'c', 0, 0, etCHARX, 0, 0 },
55.124 + { 'o', 8, 0, etRADIX, 0, 2 },
55.125 + { 'u', 10, 0, etRADIX, 0, 0 },
55.126 + { 'x', 16, 0, etRADIX, 16, 1 },
55.127 + { 'X', 16, 0, etRADIX, 0, 4 },
55.128 +#ifndef SQLITE_OMIT_FLOATING_POINT
55.129 + { 'f', 0, 1, etFLOAT, 0, 0 },
55.130 + { 'e', 0, 1, etEXP, 30, 0 },
55.131 + { 'E', 0, 1, etEXP, 14, 0 },
55.132 + { 'G', 0, 1, etGENERIC, 14, 0 },
55.133 +#endif
55.134 + { 'i', 10, 1, etRADIX, 0, 0 },
55.135 + { 'n', 0, 0, etSIZE, 0, 0 },
55.136 + { '%', 0, 0, etPERCENT, 0, 0 },
55.137 + { 'p', 16, 0, etPOINTER, 0, 1 },
55.138 + { 'T', 0, 2, etTOKEN, 0, 0 },
55.139 + { 'S', 0, 2, etSRCLIST, 0, 0 },
55.140 +};
55.141 +#define etNINFO (sizeof(fmtinfo)/sizeof(fmtinfo[0]))
55.142 +
55.143 +/*
55.144 +** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
55.145 +** conversions will work.
55.146 +*/
55.147 +#ifndef SQLITE_OMIT_FLOATING_POINT
55.148 +/*
55.149 +** "*val" is a double such that 0.1 <= *val < 10.0
55.150 +** Return the ascii code for the leading digit of *val, then
55.151 +** multiply "*val" by 10.0 to renormalize.
55.152 +**
55.153 +** Example:
55.154 +** input: *val = 3.14159
55.155 +** output: *val = 1.4159 function return = '3'
55.156 +**
55.157 +** The counter *cnt is incremented each time. After counter exceeds
55.158 +** 16 (the number of significant digits in a 64-bit float) '0' is
55.159 +** always returned.
55.160 +*/
55.161 +static int et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
55.162 + int digit;
55.163 + LONGDOUBLE_TYPE d;
55.164 + if( (*cnt)++ >= 16 ) return '0';
55.165 + digit = (int)*val;
55.166 + d = digit;
55.167 + digit += '0';
55.168 + *val = (*val - d)*10.0;
55.169 + return digit;
55.170 +}
55.171 +#endif /* SQLITE_OMIT_FLOATING_POINT */
55.172 +
55.173 +/*
55.174 +** On machines with a small stack size, you can redefine the
55.175 +** SQLITE_PRINT_BUF_SIZE to be less than 350. But beware - for
55.176 +** smaller values some %f conversions may go into an infinite loop.
55.177 +*/
55.178 +#ifndef SQLITE_PRINT_BUF_SIZE
55.179 +# define SQLITE_PRINT_BUF_SIZE 350
55.180 +#endif
55.181 +#define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
55.182 +
55.183 +/*
55.184 +** The root program. All variations call this core.
55.185 +**
55.186 +** INPUTS:
55.187 +** func This is a pointer to a function taking three arguments
55.188 +** 1. A pointer to anything. Same as the "arg" parameter.
55.189 +** 2. A pointer to the list of characters to be output
55.190 +** (Note, this list is NOT null terminated.)
55.191 +** 3. An integer number of characters to be output.
55.192 +** (Note: This number might be zero.)
55.193 +**
55.194 +** arg This is the pointer to anything which will be passed as the
55.195 +** first argument to "func". Use it for whatever you like.
55.196 +**
55.197 +** fmt This is the format string, as in the usual print.
55.198 +**
55.199 +** ap This is a pointer to a list of arguments. Same as in
55.200 +** vfprint.
55.201 +**
55.202 +** OUTPUTS:
55.203 +** The return value is the total number of characters sent to
55.204 +** the function "func". Returns -1 on a error.
55.205 +**
55.206 +** Note that the order in which automatic variables are declared below
55.207 +** seems to make a big difference in determining how fast this beast
55.208 +** will run.
55.209 +*/
55.210 +static int vxprintf(
55.211 + void (*func)(void*,const char*,int), /* Consumer of text */
55.212 + void *arg, /* First argument to the consumer */
55.213 + int useExtended, /* Allow extended %-conversions */
55.214 + const char *fmt, /* Format string */
55.215 + va_list ap /* arguments */
55.216 +){
55.217 + int c; /* Next character in the format string */
55.218 + char *bufpt; /* Pointer to the conversion buffer */
55.219 + int precision; /* Precision of the current field */
55.220 + int length; /* Length of the field */
55.221 + int idx; /* A general purpose loop counter */
55.222 + int count; /* Total number of characters output */
55.223 + int width; /* Width of the current field */
55.224 + etByte flag_leftjustify; /* True if "-" flag is present */
55.225 + etByte flag_plussign; /* True if "+" flag is present */
55.226 + etByte flag_blanksign; /* True if " " flag is present */
55.227 + etByte flag_alternateform; /* True if "#" flag is present */
55.228 + etByte flag_altform2; /* True if "!" flag is present */
55.229 + etByte flag_zeropad; /* True if field width constant starts with zero */
55.230 + etByte flag_long; /* True if "l" flag is present */
55.231 + etByte flag_longlong; /* True if the "ll" flag is present */
55.232 + etByte done; /* Loop termination flag */
55.233 + sqlite_uint64 longvalue; /* Value for integer types */
55.234 + LONGDOUBLE_TYPE realvalue; /* Value for real types */
55.235 + const et_info *infop; /* Pointer to the appropriate info structure */
55.236 + char buf[etBUFSIZE]; /* Conversion buffer */
55.237 + char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
55.238 + etByte errorflag = 0; /* True if an error is encountered */
55.239 + etByte xtype; /* Conversion paradigm */
55.240 + char *zExtra; /* Extra memory used for etTCLESCAPE conversions */
55.241 + static const char spaces[] =
55.242 + " ";
55.243 +#define etSPACESIZE (sizeof(spaces)-1)
55.244 +#ifndef SQLITE_OMIT_FLOATING_POINT
55.245 + int exp, e2; /* exponent of real numbers */
55.246 + double rounder; /* Used for rounding floating point values */
55.247 + etByte flag_dp; /* True if decimal point should be shown */
55.248 + etByte flag_rtz; /* True if trailing zeros should be removed */
55.249 + etByte flag_exp; /* True to force display of the exponent */
55.250 + int nsd; /* Number of significant digits returned */
55.251 +#endif
55.252 +
55.253 + func(arg,"",0);
55.254 + count = length = 0;
55.255 + bufpt = 0;
55.256 + for(; (c=(*fmt))!=0; ++fmt){
55.257 + if( c!='%' ){
55.258 + int amt;
55.259 + bufpt = (char *)fmt;
55.260 + amt = 1;
55.261 + while( (c=(*++fmt))!='%' && c!=0 ) amt++;
55.262 + (*func)(arg,bufpt,amt);
55.263 + count += amt;
55.264 + if( c==0 ) break;
55.265 + }
55.266 + if( (c=(*++fmt))==0 ){
55.267 + errorflag = 1;
55.268 + (*func)(arg,"%",1);
55.269 + count++;
55.270 + break;
55.271 + }
55.272 + /* Find out what flags are present */
55.273 + flag_leftjustify = flag_plussign = flag_blanksign =
55.274 + flag_alternateform = flag_altform2 = flag_zeropad = 0;
55.275 + done = 0;
55.276 + do{
55.277 + switch( c ){
55.278 + case '-': flag_leftjustify = 1; break;
55.279 + case '+': flag_plussign = 1; break;
55.280 + case ' ': flag_blanksign = 1; break;
55.281 + case '#': flag_alternateform = 1; break;
55.282 + case '!': flag_altform2 = 1; break;
55.283 + case '0': flag_zeropad = 1; break;
55.284 + default: done = 1; break;
55.285 + }
55.286 + }while( !done && (c=(*++fmt))!=0 );
55.287 + /* Get the field width */
55.288 + width = 0;
55.289 + if( c=='*' ){
55.290 + width = va_arg(ap,int);
55.291 + if( width<0 ){
55.292 + flag_leftjustify = 1;
55.293 + width = -width;
55.294 + }
55.295 + c = *++fmt;
55.296 + }else{
55.297 + while( c>='0' && c<='9' ){
55.298 + width = width*10 + c - '0';
55.299 + c = *++fmt;
55.300 + }
55.301 + }
55.302 + if( width > etBUFSIZE-10 ){
55.303 + width = etBUFSIZE-10;
55.304 + }
55.305 + /* Get the precision */
55.306 + if( c=='.' ){
55.307 + precision = 0;
55.308 + c = *++fmt;
55.309 + if( c=='*' ){
55.310 + precision = va_arg(ap,int);
55.311 + if( precision<0 ) precision = -precision;
55.312 + c = *++fmt;
55.313 + }else{
55.314 + while( c>='0' && c<='9' ){
55.315 + precision = precision*10 + c - '0';
55.316 + c = *++fmt;
55.317 + }
55.318 + }
55.319 + }else{
55.320 + precision = -1;
55.321 + }
55.322 + /* Get the conversion type modifier */
55.323 + if( c=='l' ){
55.324 + flag_long = 1;
55.325 + c = *++fmt;
55.326 + if( c=='l' ){
55.327 + flag_longlong = 1;
55.328 + c = *++fmt;
55.329 + }else{
55.330 + flag_longlong = 0;
55.331 + }
55.332 + }else{
55.333 + flag_long = flag_longlong = 0;
55.334 + }
55.335 + /* Fetch the info entry for the field */
55.336 + infop = 0;
55.337 + for(idx=0; idx<etNINFO; idx++){
55.338 + if( c==fmtinfo[idx].fmttype ){
55.339 + infop = &fmtinfo[idx];
55.340 + if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
55.341 + xtype = infop->type;
55.342 + }else{
55.343 + return -1;
55.344 + }
55.345 + break;
55.346 + }
55.347 + }
55.348 + zExtra = 0;
55.349 + if( infop==0 ){
55.350 + return -1;
55.351 + }
55.352 +
55.353 +
55.354 + /* Limit the precision to prevent overflowing buf[] during conversion */
55.355 + if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
55.356 + precision = etBUFSIZE-40;
55.357 + }
55.358 +
55.359 + /*
55.360 + ** At this point, variables are initialized as follows:
55.361 + **
55.362 + ** flag_alternateform TRUE if a '#' is present.
55.363 + ** flag_altform2 TRUE if a '!' is present.
55.364 + ** flag_plussign TRUE if a '+' is present.
55.365 + ** flag_leftjustify TRUE if a '-' is present or if the
55.366 + ** field width was negative.
55.367 + ** flag_zeropad TRUE if the width began with 0.
55.368 + ** flag_long TRUE if the letter 'l' (ell) prefixed
55.369 + ** the conversion character.
55.370 + ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
55.371 + ** the conversion character.
55.372 + ** flag_blanksign TRUE if a ' ' is present.
55.373 + ** width The specified field width. This is
55.374 + ** always non-negative. Zero is the default.
55.375 + ** precision The specified precision. The default
55.376 + ** is -1.
55.377 + ** xtype The class of the conversion.
55.378 + ** infop Pointer to the appropriate info struct.
55.379 + */
55.380 + switch( xtype ){
55.381 + case etPOINTER:
55.382 + flag_longlong = sizeof(char*)==sizeof(i64);
55.383 + flag_long = sizeof(char*)==sizeof(long int);
55.384 + /* Fall through into the next case */
55.385 + case etRADIX:
55.386 + if( infop->flags & FLAG_SIGNED ){
55.387 + i64 v;
55.388 + if( flag_longlong ) v = va_arg(ap,i64);
55.389 + else if( flag_long ) v = va_arg(ap,long int);
55.390 + else v = va_arg(ap,int);
55.391 + if( v<0 ){
55.392 + longvalue = -v;
55.393 + prefix = '-';
55.394 + }else{
55.395 + longvalue = v;
55.396 + if( flag_plussign ) prefix = '+';
55.397 + else if( flag_blanksign ) prefix = ' ';
55.398 + else prefix = 0;
55.399 + }
55.400 + }else{
55.401 + if( flag_longlong ) longvalue = va_arg(ap,u64);
55.402 + else if( flag_long ) longvalue = va_arg(ap,unsigned long int);
55.403 + else longvalue = va_arg(ap,unsigned int);
55.404 + prefix = 0;
55.405 + }
55.406 + if( longvalue==0 ) flag_alternateform = 0;
55.407 + if( flag_zeropad && precision<width-(prefix!=0) ){
55.408 + precision = width-(prefix!=0);
55.409 + }
55.410 + bufpt = &buf[etBUFSIZE-1];
55.411 + {
55.412 + register const char *cset; /* Use registers for speed */
55.413 + register int base;
55.414 + cset = &aDigits[infop->charset];
55.415 + base = infop->base;
55.416 + do{ /* Convert to ascii */
55.417 + *(--bufpt) = cset[longvalue%base];
55.418 + longvalue = longvalue/base;
55.419 + }while( longvalue>0 );
55.420 + }
55.421 + length = &buf[etBUFSIZE-1]-bufpt;
55.422 + for(idx=precision-length; idx>0; idx--){
55.423 + *(--bufpt) = '0'; /* Zero pad */
55.424 + }
55.425 + if( prefix ) *(--bufpt) = prefix; /* Add sign */
55.426 + if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
55.427 + const char *pre;
55.428 + char x;
55.429 + pre = &aPrefix[infop->prefix];
55.430 + if( *bufpt!=pre[0] ){
55.431 + for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
55.432 + }
55.433 + }
55.434 + length = &buf[etBUFSIZE-1]-bufpt;
55.435 + break;
55.436 + case etFLOAT:
55.437 + case etEXP:
55.438 + case etGENERIC:
55.439 + realvalue = va_arg(ap,double);
55.440 +#ifndef SQLITE_OMIT_FLOATING_POINT
55.441 + if( precision<0 ) precision = 6; /* Set default precision */
55.442 + if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
55.443 + if( realvalue<0.0 ){
55.444 + realvalue = -realvalue;
55.445 + prefix = '-';
55.446 + }else{
55.447 + if( flag_plussign ) prefix = '+';
55.448 + else if( flag_blanksign ) prefix = ' ';
55.449 + else prefix = 0;
55.450 + }
55.451 + if( xtype==etGENERIC && precision>0 ) precision--;
55.452 +#if 0
55.453 + /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
55.454 + for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
55.455 +#else
55.456 + /* It makes more sense to use 0.5 */
55.457 + for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
55.458 +#endif
55.459 + if( xtype==etFLOAT ) realvalue += rounder;
55.460 + /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
55.461 + exp = 0;
55.462 + if( sqlite3_isnan(realvalue) ){
55.463 + bufpt = "NaN";
55.464 + length = 3;
55.465 + break;
55.466 + }
55.467 + if( realvalue>0.0 ){
55.468 + while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
55.469 + while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
55.470 + while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
55.471 + while( realvalue<1e-8 && exp>=-350 ){ realvalue *= 1e8; exp-=8; }
55.472 + while( realvalue<1.0 && exp>=-350 ){ realvalue *= 10.0; exp--; }
55.473 + if( exp>350 || exp<-350 ){
55.474 + if( prefix=='-' ){
55.475 + bufpt = "-Inf";
55.476 + }else if( prefix=='+' ){
55.477 + bufpt = "+Inf";
55.478 + }else{
55.479 + bufpt = "Inf";
55.480 + }
55.481 + length = strlen(bufpt);
55.482 + break;
55.483 + }
55.484 + }
55.485 + bufpt = buf;
55.486 + /*
55.487 + ** If the field type is etGENERIC, then convert to either etEXP
55.488 + ** or etFLOAT, as appropriate.
55.489 + */
55.490 + flag_exp = xtype==etEXP;
55.491 + if( xtype!=etFLOAT ){
55.492 + realvalue += rounder;
55.493 + if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
55.494 + }
55.495 + if( xtype==etGENERIC ){
55.496 + flag_rtz = !flag_alternateform;
55.497 + if( exp<-4 || exp>precision ){
55.498 + xtype = etEXP;
55.499 + }else{
55.500 + precision = precision - exp;
55.501 + xtype = etFLOAT;
55.502 + }
55.503 + }else{
55.504 + flag_rtz = 0;
55.505 + }
55.506 + if( xtype==etEXP ){
55.507 + e2 = 0;
55.508 + }else{
55.509 + e2 = exp;
55.510 + }
55.511 + nsd = 0;
55.512 + flag_dp = (precision>0) | flag_alternateform | flag_altform2;
55.513 + /* The sign in front of the number */
55.514 + if( prefix ){
55.515 + *(bufpt++) = prefix;
55.516 + }
55.517 + /* Digits prior to the decimal point */
55.518 + if( e2<0 ){
55.519 + *(bufpt++) = '0';
55.520 + }else{
55.521 + for(; e2>=0; e2--){
55.522 + *(bufpt++) = et_getdigit(&realvalue,&nsd);
55.523 + }
55.524 + }
55.525 + /* The decimal point */
55.526 + if( flag_dp ){
55.527 + *(bufpt++) = '.';
55.528 + }
55.529 + /* "0" digits after the decimal point but before the first
55.530 + ** significant digit of the number */
55.531 + for(e2++; e2<0 && precision>0; precision--, e2++){
55.532 + *(bufpt++) = '0';
55.533 + }
55.534 + /* Significant digits after the decimal point */
55.535 + while( (precision--)>0 ){
55.536 + *(bufpt++) = et_getdigit(&realvalue,&nsd);
55.537 + }
55.538 + /* Remove trailing zeros and the "." if no digits follow the "." */
55.539 + if( flag_rtz && flag_dp ){
55.540 + while( bufpt[-1]=='0' ) *(--bufpt) = 0;
55.541 + assert( bufpt>buf );
55.542 + if( bufpt[-1]=='.' ){
55.543 + if( flag_altform2 ){
55.544 + *(bufpt++) = '0';
55.545 + }else{
55.546 + *(--bufpt) = 0;
55.547 + }
55.548 + }
55.549 + }
55.550 + /* Add the "eNNN" suffix */
55.551 + if( flag_exp || (xtype==etEXP && exp) ){
55.552 + *(bufpt++) = aDigits[infop->charset];
55.553 + if( exp<0 ){
55.554 + *(bufpt++) = '-'; exp = -exp;
55.555 + }else{
55.556 + *(bufpt++) = '+';
55.557 + }
55.558 + if( exp>=100 ){
55.559 + *(bufpt++) = (exp/100)+'0'; /* 100's digit */
55.560 + exp %= 100;
55.561 + }
55.562 + *(bufpt++) = exp/10+'0'; /* 10's digit */
55.563 + *(bufpt++) = exp%10+'0'; /* 1's digit */
55.564 + }
55.565 + *bufpt = 0;
55.566 +
55.567 + /* The converted number is in buf[] and zero terminated. Output it.
55.568 + ** Note that the number is in the usual order, not reversed as with
55.569 + ** integer conversions. */
55.570 + length = bufpt-buf;
55.571 + bufpt = buf;
55.572 +
55.573 + /* Special case: Add leading zeros if the flag_zeropad flag is
55.574 + ** set and we are not left justified */
55.575 + if( flag_zeropad && !flag_leftjustify && length < width){
55.576 + int i;
55.577 + int nPad = width - length;
55.578 + for(i=width; i>=nPad; i--){
55.579 + bufpt[i] = bufpt[i-nPad];
55.580 + }
55.581 + i = prefix!=0;
55.582 + while( nPad-- ) bufpt[i++] = '0';
55.583 + length = width;
55.584 + }
55.585 +#endif
55.586 + break;
55.587 + case etSIZE:
55.588 + *(va_arg(ap,int*)) = count;
55.589 + length = width = 0;
55.590 + break;
55.591 + case etPERCENT:
55.592 + buf[0] = '%';
55.593 + bufpt = buf;
55.594 + length = 1;
55.595 + break;
55.596 + case etCHARLIT:
55.597 + case etCHARX:
55.598 + c = buf[0] = (xtype==etCHARX ? va_arg(ap,int) : *++fmt);
55.599 + if( precision>=0 ){
55.600 + for(idx=1; idx<precision; idx++) buf[idx] = c;
55.601 + length = precision;
55.602 + }else{
55.603 + length =1;
55.604 + }
55.605 + bufpt = buf;
55.606 + break;
55.607 + case etSTRING:
55.608 + case etDYNSTRING:
55.609 + bufpt = va_arg(ap,char*);
55.610 + if( bufpt==0 ){
55.611 + bufpt = "";
55.612 + }else if( xtype==etDYNSTRING ){
55.613 + zExtra = bufpt;
55.614 + }
55.615 + length = strlen(bufpt);
55.616 + if( precision>=0 && precision<length ) length = precision;
55.617 + break;
55.618 + case etSQLESCAPE:
55.619 + case etSQLESCAPE2:
55.620 + case etSQLESCAPE3: {
55.621 + int i, j, n, ch, isnull;
55.622 + int needQuote;
55.623 + char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
55.624 + char *escarg = va_arg(ap,char*);
55.625 + isnull = escarg==0;
55.626 + if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
55.627 + for(i=n=0; (ch=escarg[i])!=0; i++){
55.628 + if( ch==q ) n++;
55.629 + }
55.630 + needQuote = !isnull && xtype==etSQLESCAPE2;
55.631 + n += i + 1 + needQuote*2;
55.632 + if( n>etBUFSIZE ){
55.633 + bufpt = zExtra = sqliteMalloc( n );
55.634 + if( bufpt==0 ) return -1;
55.635 + }else{
55.636 + bufpt = buf;
55.637 + }
55.638 + j = 0;
55.639 + if( needQuote ) bufpt[j++] = q;
55.640 + for(i=0; (ch=escarg[i])!=0; i++){
55.641 + bufpt[j++] = ch;
55.642 + if( ch==q ) bufpt[j++] = ch;
55.643 + }
55.644 + if( needQuote ) bufpt[j++] = q;
55.645 + bufpt[j] = 0;
55.646 + length = j;
55.647 + /* The precision is ignored on %q and %Q */
55.648 + /* if( precision>=0 && precision<length ) length = precision; */
55.649 + break;
55.650 + }
55.651 + case etTOKEN: {
55.652 + Token *pToken = va_arg(ap, Token*);
55.653 + if( pToken && pToken->z ){
55.654 + (*func)(arg, (char*)pToken->z, pToken->n);
55.655 + }
55.656 + length = width = 0;
55.657 + break;
55.658 + }
55.659 + case etSRCLIST: {
55.660 + SrcList *pSrc = va_arg(ap, SrcList*);
55.661 + int k = va_arg(ap, int);
55.662 + struct SrcList_item *pItem = &pSrc->a[k];
55.663 + assert( k>=0 && k<pSrc->nSrc );
55.664 + if( pItem->zDatabase && pItem->zDatabase[0] ){
55.665 + (*func)(arg, pItem->zDatabase, strlen(pItem->zDatabase));
55.666 + (*func)(arg, ".", 1);
55.667 + }
55.668 + (*func)(arg, pItem->zName, strlen(pItem->zName));
55.669 + length = width = 0;
55.670 + break;
55.671 + }
55.672 + }/* End switch over the format type */
55.673 + /*
55.674 + ** The text of the conversion is pointed to by "bufpt" and is
55.675 + ** "length" characters long. The field width is "width". Do
55.676 + ** the output.
55.677 + */
55.678 + if( !flag_leftjustify ){
55.679 + register int nspace;
55.680 + nspace = width-length;
55.681 + if( nspace>0 ){
55.682 + count += nspace;
55.683 + while( nspace>=etSPACESIZE ){
55.684 + (*func)(arg,spaces,etSPACESIZE);
55.685 + nspace -= etSPACESIZE;
55.686 + }
55.687 + if( nspace>0 ) (*func)(arg,spaces,nspace);
55.688 + }
55.689 + }
55.690 + if( length>0 ){
55.691 + (*func)(arg,bufpt,length);
55.692 + count += length;
55.693 + }
55.694 + if( flag_leftjustify ){
55.695 + register int nspace;
55.696 + nspace = width-length;
55.697 + if( nspace>0 ){
55.698 + count += nspace;
55.699 + while( nspace>=etSPACESIZE ){
55.700 + (*func)(arg,spaces,etSPACESIZE);
55.701 + nspace -= etSPACESIZE;
55.702 + }
55.703 + if( nspace>0 ) (*func)(arg,spaces,nspace);
55.704 + }
55.705 + }
55.706 + if( zExtra ){
55.707 + sqliteFree(zExtra);
55.708 + }
55.709 + }/* End for loop over the format string */
55.710 + return errorflag ? -1 : count;
55.711 +} /* End of function */
55.712 +
55.713 +
55.714 +/* This structure is used to store state information about the
55.715 +** write to memory that is currently in progress.
55.716 +*/
55.717 +struct sgMprintf {
55.718 + char *zBase; /* A base allocation */
55.719 + char *zText; /* The string collected so far */
55.720 + int nChar; /* Length of the string so far */
55.721 + int nTotal; /* Output size if unconstrained */
55.722 + int nAlloc; /* Amount of space allocated in zText */
55.723 + void *(*xRealloc)(void*,int); /* Function used to realloc memory */
55.724 +};
55.725 +
55.726 +/*
55.727 +** This function implements the callback from vxprintf.
55.728 +**
55.729 +** This routine add nNewChar characters of text in zNewText to
55.730 +** the sgMprintf structure pointed to by "arg".
55.731 +*/
55.732 +static void mout(void *arg, const char *zNewText, int nNewChar){
55.733 + struct sgMprintf *pM = (struct sgMprintf*)arg;
55.734 + pM->nTotal += nNewChar;
55.735 + if( pM->nChar + nNewChar + 1 > pM->nAlloc ){
55.736 + if( pM->xRealloc==0 ){
55.737 + nNewChar = pM->nAlloc - pM->nChar - 1;
55.738 + }else{
55.739 + int nAlloc = pM->nChar + nNewChar*2 + 1;
55.740 + if( pM->zText==pM->zBase ){
55.741 + pM->zText = pM->xRealloc(0, nAlloc);
55.742 + if( pM->zText && pM->nChar ){
55.743 + memcpy(pM->zText, pM->zBase, pM->nChar);
55.744 + }
55.745 + }else{
55.746 + char *zNew;
55.747 + zNew = pM->xRealloc(pM->zText, nAlloc);
55.748 + if( zNew ){
55.749 + pM->zText = zNew;
55.750 + }else{
55.751 + return;
55.752 + }
55.753 + }
55.754 + pM->nAlloc = nAlloc;
55.755 + }
55.756 + }
55.757 + if( pM->zText ){
55.758 + if( nNewChar>0 ){
55.759 + memcpy(&pM->zText[pM->nChar], zNewText, nNewChar);
55.760 + pM->nChar += nNewChar;
55.761 + }
55.762 + pM->zText[pM->nChar] = 0;
55.763 + }
55.764 +}
55.765 +
55.766 +/*
55.767 +** This routine is a wrapper around xprintf() that invokes mout() as
55.768 +** the consumer.
55.769 +*/
55.770 +static char *base_vprintf(
55.771 + void *(*xRealloc)(void*,int), /* Routine to realloc memory. May be NULL */
55.772 + int useInternal, /* Use internal %-conversions if true */
55.773 + char *zInitBuf, /* Initially write here, before mallocing */
55.774 + int nInitBuf, /* Size of zInitBuf[] */
55.775 + const char *zFormat, /* format string */
55.776 + va_list ap /* arguments */
55.777 +){
55.778 + struct sgMprintf sM;
55.779 + sM.zBase = sM.zText = zInitBuf;
55.780 + sM.nChar = sM.nTotal = 0;
55.781 + sM.nAlloc = nInitBuf;
55.782 + sM.xRealloc = xRealloc;
55.783 + vxprintf(mout, &sM, useInternal, zFormat, ap);
55.784 + if( xRealloc ){
55.785 + if( sM.zText==sM.zBase ){
55.786 + sM.zText = xRealloc(0, sM.nChar+1);
55.787 + if( sM.zText ){
55.788 + memcpy(sM.zText, sM.zBase, sM.nChar+1);
55.789 + }
55.790 + }else if( sM.nAlloc>sM.nChar+10 ){
55.791 + char *zNew = xRealloc(sM.zText, sM.nChar+1);
55.792 + if( zNew ){
55.793 + sM.zText = zNew;
55.794 + }
55.795 + }
55.796 + }
55.797 + return sM.zText;
55.798 +}
55.799 +
55.800 +/*
55.801 +** Realloc that is a real function, not a macro.
55.802 +*/
55.803 +static void *printf_realloc(void *old, int size){
55.804 + return sqliteRealloc(old,size);
55.805 +}
55.806 +
55.807 +/*
55.808 +** Print into memory obtained from sqliteMalloc(). Use the internal
55.809 +** %-conversion extensions.
55.810 +*/
55.811 +char *sqlite3VMPrintf(const char *zFormat, va_list ap){
55.812 + char zBase[SQLITE_PRINT_BUF_SIZE];
55.813 + return base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
55.814 +}
55.815 +
55.816 +/*
55.817 +** Print into memory obtained from sqliteMalloc(). Use the internal
55.818 +** %-conversion extensions.
55.819 +*/
55.820 +char *sqlite3MPrintf(const char *zFormat, ...){
55.821 + va_list ap;
55.822 + char *z;
55.823 + char zBase[SQLITE_PRINT_BUF_SIZE];
55.824 + va_start(ap, zFormat);
55.825 + z = base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
55.826 + va_end(ap);
55.827 + return z;
55.828 +}
55.829 +
55.830 +/*
55.831 +** Print into memory obtained from sqlite3_malloc(). Omit the internal
55.832 +** %-conversion extensions.
55.833 +*/
55.834 +char *sqlite3_vmprintf(const char *zFormat, va_list ap){
55.835 + char zBase[SQLITE_PRINT_BUF_SIZE];
55.836 + return base_vprintf(sqlite3_realloc, 0, zBase, sizeof(zBase), zFormat, ap);
55.837 +}
55.838 +
55.839 +/*
55.840 +** Print into memory obtained from sqlite3_malloc()(). Omit the internal
55.841 +** %-conversion extensions.
55.842 +*/
55.843 +char *sqlite3_mprintf(const char *zFormat, ...){
55.844 + va_list ap;
55.845 + char *z;
55.846 + va_start(ap, zFormat);
55.847 + z = sqlite3_vmprintf(zFormat, ap);
55.848 + va_end(ap);
55.849 + return z;
55.850 +}
55.851 +
55.852 +/*
55.853 +** sqlite3_snprintf() works like snprintf() except that it ignores the
55.854 +** current locale settings. This is important for SQLite because we
55.855 +** are not able to use a "," as the decimal point in place of "." as
55.856 +** specified by some locales.
55.857 +*/
55.858 +char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
55.859 + char *z;
55.860 + va_list ap;
55.861 +
55.862 + if( n<=0 ){
55.863 + return zBuf;
55.864 + }
55.865 + zBuf[0] = 0;
55.866 + va_start(ap,zFormat);
55.867 + z = base_vprintf(0, 0, zBuf, n, zFormat, ap);
55.868 + va_end(ap);
55.869 + return z;
55.870 +}
55.871 +
55.872 +#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) || defined(SQLITE_MEMDEBUG)
55.873 +/*
55.874 +** A version of printf() that understands %lld. Used for debugging.
55.875 +** The printf() built into some versions of windows does not understand %lld
55.876 +** and segfaults if you give it a long long int.
55.877 +*/
55.878 +void sqlite3DebugPrintf(const char *zFormat, ...){
55.879 + extern int getpid(void);
55.880 + va_list ap;
55.881 + char zBuf[500];
55.882 + va_start(ap, zFormat);
55.883 + base_vprintf(0, 0, zBuf, sizeof(zBuf), zFormat, ap);
55.884 + va_end(ap);
55.885 + fprintf(stdout,"%s", zBuf);
55.886 + fflush(stdout);
55.887 +}
55.888 +#endif
56.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
56.2 +++ b/extensions/sqlite/sqlite-source/random.c Sun Jul 29 01:15:31 2007 +0000
56.3 @@ -0,0 +1,100 @@
56.4 +/*
56.5 +** 2001 September 15
56.6 +**
56.7 +** The author disclaims copyright to this source code. In place of
56.8 +** a legal notice, here is a blessing:
56.9 +**
56.10 +** May you do good and not evil.
56.11 +** May you find forgiveness for yourself and forgive others.
56.12 +** May you share freely, never taking more than you give.
56.13 +**
56.14 +*************************************************************************
56.15 +** This file contains code to implement a pseudo-random number
56.16 +** generator (PRNG) for SQLite.
56.17 +**
56.18 +** Random numbers are used by some of the database backends in order
56.19 +** to generate random integer keys for tables or random filenames.
56.20 +**
56.21 +** $Id$
56.22 +*/
56.23 +#include "sqliteInt.h"
56.24 +#include "os.h"
56.25 +
56.26 +
56.27 +/*
56.28 +** Get a single 8-bit random value from the RC4 PRNG. The Mutex
56.29 +** must be held while executing this routine.
56.30 +**
56.31 +** Why not just use a library random generator like lrand48() for this?
56.32 +** Because the OP_NewRowid opcode in the VDBE depends on having a very
56.33 +** good source of random numbers. The lrand48() library function may
56.34 +** well be good enough. But maybe not. Or maybe lrand48() has some
56.35 +** subtle problems on some systems that could cause problems. It is hard
56.36 +** to know. To minimize the risk of problems due to bad lrand48()
56.37 +** implementations, SQLite uses this random number generator based
56.38 +** on RC4, which we know works very well.
56.39 +**
56.40 +** (Later): Actually, OP_NewRowid does not depend on a good source of
56.41 +** randomness any more. But we will leave this code in all the same.
56.42 +*/
56.43 +static int randomByte(void){
56.44 + unsigned char t;
56.45 +
56.46 + /* All threads share a single random number generator.
56.47 + ** This structure is the current state of the generator.
56.48 + */
56.49 + static struct {
56.50 + unsigned char isInit; /* True if initialized */
56.51 + unsigned char i, j; /* State variables */
56.52 + unsigned char s[256]; /* State variables */
56.53 + } prng;
56.54 +
56.55 + /* Initialize the state of the random number generator once,
56.56 + ** the first time this routine is called. The seed value does
56.57 + ** not need to contain a lot of randomness since we are not
56.58 + ** trying to do secure encryption or anything like that...
56.59 + **
56.60 + ** Nothing in this file or anywhere else in SQLite does any kind of
56.61 + ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
56.62 + ** number generator) not as an encryption device.
56.63 + */
56.64 + if( !prng.isInit ){
56.65 + int i;
56.66 + char k[256];
56.67 + prng.j = 0;
56.68 + prng.i = 0;
56.69 + sqlite3OsRandomSeed(k);
56.70 + for(i=0; i<256; i++){
56.71 + prng.s[i] = i;
56.72 + }
56.73 + for(i=0; i<256; i++){
56.74 + prng.j += prng.s[i] + k[i];
56.75 + t = prng.s[prng.j];
56.76 + prng.s[prng.j] = prng.s[i];
56.77 + prng.s[i] = t;
56.78 + }
56.79 + prng.isInit = 1;
56.80 + }
56.81 +
56.82 + /* Generate and return single random byte
56.83 + */
56.84 + prng.i++;
56.85 + t = prng.s[prng.i];
56.86 + prng.j += t;
56.87 + prng.s[prng.i] = prng.s[prng.j];
56.88 + prng.s[prng.j] = t;
56.89 + t += prng.s[prng.i];
56.90 + return prng.s[t];
56.91 +}
56.92 +
56.93 +/*
56.94 +** Return N random bytes.
56.95 +*/
56.96 +void sqlite3Randomness(int N, void *pBuf){
56.97 + unsigned char *zBuf = pBuf;
56.98 + sqlite3OsEnterMutex();
56.99 + while( N-- ){
56.100 + *(zBuf++) = randomByte();
56.101 + }
56.102 + sqlite3OsLeaveMutex();
56.103 +}
57.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
57.2 +++ b/extensions/sqlite/sqlite-source/select.c Sun Jul 29 01:15:31 2007 +0000
57.3 @@ -0,0 +1,3505 @@
57.4 +/*
57.5 +** 2001 September 15
57.6 +**
57.7 +** The author disclaims copyright to this source code. In place of
57.8 +** a legal notice, here is a blessing:
57.9 +**
57.10 +** May you do good and not evil.
57.11 +** May you find forgiveness for yourself and forgive others.
57.12 +** May you share freely, never taking more than you give.
57.13 +**
57.14 +*************************************************************************
57.15 +** This file contains C code routines that are called by the parser
57.16 +** to handle SELECT statements in SQLite.
57.17 +**
57.18 +** $Id$
57.19 +*/
57.20 +#include "sqliteInt.h"
57.21 +
57.22 +
57.23 +/*
57.24 +** Delete all the content of a Select structure but do not deallocate
57.25 +** the select structure itself.
57.26 +*/
57.27 +static void clearSelect(Select *p){
57.28 + sqlite3ExprListDelete(p->pEList);
57.29 + sqlite3SrcListDelete(p->pSrc);
57.30 + sqlite3ExprDelete(p->pWhere);
57.31 + sqlite3ExprListDelete(p->pGroupBy);
57.32 + sqlite3ExprDelete(p->pHaving);
57.33 + sqlite3ExprListDelete(p->pOrderBy);
57.34 + sqlite3SelectDelete(p->pPrior);
57.35 + sqlite3ExprDelete(p->pLimit);
57.36 + sqlite3ExprDelete(p->pOffset);
57.37 +}
57.38 +
57.39 +
57.40 +/*
57.41 +** Allocate a new Select structure and return a pointer to that
57.42 +** structure.
57.43 +*/
57.44 +Select *sqlite3SelectNew(
57.45 + ExprList *pEList, /* which columns to include in the result */
57.46 + SrcList *pSrc, /* the FROM clause -- which tables to scan */
57.47 + Expr *pWhere, /* the WHERE clause */
57.48 + ExprList *pGroupBy, /* the GROUP BY clause */
57.49 + Expr *pHaving, /* the HAVING clause */
57.50 + ExprList *pOrderBy, /* the ORDER BY clause */
57.51 + int isDistinct, /* true if the DISTINCT keyword is present */
57.52 + Expr *pLimit, /* LIMIT value. NULL means not used */
57.53 + Expr *pOffset /* OFFSET value. NULL means no offset */
57.54 +){
57.55 + Select *pNew;
57.56 + Select standin;
57.57 + pNew = sqliteMalloc( sizeof(*pNew) );
57.58 + assert( !pOffset || pLimit ); /* Can't have OFFSET without LIMIT. */
57.59 + if( pNew==0 ){
57.60 + pNew = &standin;
57.61 + memset(pNew, 0, sizeof(*pNew));
57.62 + }
57.63 + if( pEList==0 ){
57.64 + pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
57.65 + }
57.66 + pNew->pEList = pEList;
57.67 + pNew->pSrc = pSrc;
57.68 + pNew->pWhere = pWhere;
57.69 + pNew->pGroupBy = pGroupBy;
57.70 + pNew->pHaving = pHaving;
57.71 + pNew->pOrderBy = pOrderBy;
57.72 + pNew->isDistinct = isDistinct;
57.73 + pNew->op = TK_SELECT;
57.74 + assert( pOffset==0 || pLimit!=0 );
57.75 + pNew->pLimit = pLimit;
57.76 + pNew->pOffset = pOffset;
57.77 + pNew->iLimit = -1;
57.78 + pNew->iOffset = -1;
57.79 + pNew->addrOpenEphm[0] = -1;
57.80 + pNew->addrOpenEphm[1] = -1;
57.81 + pNew->addrOpenEphm[2] = -1;
57.82 + if( pNew==&standin) {
57.83 + clearSelect(pNew);
57.84 + pNew = 0;
57.85 + }
57.86 + return pNew;
57.87 +}
57.88 +
57.89 +/*
57.90 +** Delete the given Select structure and all of its substructures.
57.91 +*/
57.92 +void sqlite3SelectDelete(Select *p){
57.93 + if( p ){
57.94 + clearSelect(p);
57.95 + sqliteFree(p);
57.96 + }
57.97 +}
57.98 +
57.99 +/*
57.100 +** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
57.101 +** type of join. Return an integer constant that expresses that type
57.102 +** in terms of the following bit values:
57.103 +**
57.104 +** JT_INNER
57.105 +** JT_CROSS
57.106 +** JT_OUTER
57.107 +** JT_NATURAL
57.108 +** JT_LEFT
57.109 +** JT_RIGHT
57.110 +**
57.111 +** A full outer join is the combination of JT_LEFT and JT_RIGHT.
57.112 +**
57.113 +** If an illegal or unsupported join type is seen, then still return
57.114 +** a join type, but put an error in the pParse structure.
57.115 +*/
57.116 +int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
57.117 + int jointype = 0;
57.118 + Token *apAll[3];
57.119 + Token *p;
57.120 + static const struct {
57.121 + const char zKeyword[8];
57.122 + u8 nChar;
57.123 + u8 code;
57.124 + } keywords[] = {
57.125 + { "natural", 7, JT_NATURAL },
57.126 + { "left", 4, JT_LEFT|JT_OUTER },
57.127 + { "right", 5, JT_RIGHT|JT_OUTER },
57.128 + { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
57.129 + { "outer", 5, JT_OUTER },
57.130 + { "inner", 5, JT_INNER },
57.131 + { "cross", 5, JT_INNER|JT_CROSS },
57.132 + };
57.133 + int i, j;
57.134 + apAll[0] = pA;
57.135 + apAll[1] = pB;
57.136 + apAll[2] = pC;
57.137 + for(i=0; i<3 && apAll[i]; i++){
57.138 + p = apAll[i];
57.139 + for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
57.140 + if( p->n==keywords[j].nChar
57.141 + && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
57.142 + jointype |= keywords[j].code;
57.143 + break;
57.144 + }
57.145 + }
57.146 + if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
57.147 + jointype |= JT_ERROR;
57.148 + break;
57.149 + }
57.150 + }
57.151 + if(
57.152 + (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
57.153 + (jointype & JT_ERROR)!=0
57.154 + ){
57.155 + const char *zSp1 = " ";
57.156 + const char *zSp2 = " ";
57.157 + if( pB==0 ){ zSp1++; }
57.158 + if( pC==0 ){ zSp2++; }
57.159 + sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
57.160 + "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
57.161 + jointype = JT_INNER;
57.162 + }else if( jointype & JT_RIGHT ){
57.163 + sqlite3ErrorMsg(pParse,
57.164 + "RIGHT and FULL OUTER JOINs are not currently supported");
57.165 + jointype = JT_INNER;
57.166 + }
57.167 + return jointype;
57.168 +}
57.169 +
57.170 +/*
57.171 +** Return the index of a column in a table. Return -1 if the column
57.172 +** is not contained in the table.
57.173 +*/
57.174 +static int columnIndex(Table *pTab, const char *zCol){
57.175 + int i;
57.176 + for(i=0; i<pTab->nCol; i++){
57.177 + if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
57.178 + }
57.179 + return -1;
57.180 +}
57.181 +
57.182 +/*
57.183 +** Set the value of a token to a '\000'-terminated string.
57.184 +*/
57.185 +static void setToken(Token *p, const char *z){
57.186 + p->z = (u8*)z;
57.187 + p->n = z ? strlen(z) : 0;
57.188 + p->dyn = 0;
57.189 +}
57.190 +
57.191 +/*
57.192 +** Set the token to the double-quoted and escaped version of the string pointed
57.193 +** to by z. For example;
57.194 +**
57.195 +** {a"bc} -> {"a""bc"}
57.196 +*/
57.197 +static void setQuotedToken(Token *p, const char *z){
57.198 + p->z = (u8 *)sqlite3MPrintf("\"%w\"", z);
57.199 + p->dyn = 1;
57.200 + if( p->z ){
57.201 + p->n = strlen((char *)p->z);
57.202 + }
57.203 +}
57.204 +
57.205 +/*
57.206 +** Create an expression node for an identifier with the name of zName
57.207 +*/
57.208 +Expr *sqlite3CreateIdExpr(const char *zName){
57.209 + Token dummy;
57.210 + setToken(&dummy, zName);
57.211 + return sqlite3Expr(TK_ID, 0, 0, &dummy);
57.212 +}
57.213 +
57.214 +
57.215 +/*
57.216 +** Add a term to the WHERE expression in *ppExpr that requires the
57.217 +** zCol column to be equal in the two tables pTab1 and pTab2.
57.218 +*/
57.219 +static void addWhereTerm(
57.220 + const char *zCol, /* Name of the column */
57.221 + const Table *pTab1, /* First table */
57.222 + const char *zAlias1, /* Alias for first table. May be NULL */
57.223 + const Table *pTab2, /* Second table */
57.224 + const char *zAlias2, /* Alias for second table. May be NULL */
57.225 + int iRightJoinTable, /* VDBE cursor for the right table */
57.226 + Expr **ppExpr /* Add the equality term to this expression */
57.227 +){
57.228 + Expr *pE1a, *pE1b, *pE1c;
57.229 + Expr *pE2a, *pE2b, *pE2c;
57.230 + Expr *pE;
57.231 +
57.232 + pE1a = sqlite3CreateIdExpr(zCol);
57.233 + pE2a = sqlite3CreateIdExpr(zCol);
57.234 + if( zAlias1==0 ){
57.235 + zAlias1 = pTab1->zName;
57.236 + }
57.237 + pE1b = sqlite3CreateIdExpr(zAlias1);
57.238 + if( zAlias2==0 ){
57.239 + zAlias2 = pTab2->zName;
57.240 + }
57.241 + pE2b = sqlite3CreateIdExpr(zAlias2);
57.242 + pE1c = sqlite3ExprOrFree(TK_DOT, pE1b, pE1a, 0);
57.243 + pE2c = sqlite3ExprOrFree(TK_DOT, pE2b, pE2a, 0);
57.244 + pE = sqlite3ExprOrFree(TK_EQ, pE1c, pE2c, 0);
57.245 + if( pE ){
57.246 + ExprSetProperty(pE, EP_FromJoin);
57.247 + pE->iRightJoinTable = iRightJoinTable;
57.248 + }
57.249 + pE = sqlite3ExprAnd(*ppExpr, pE);
57.250 + if( pE ){
57.251 + *ppExpr = pE;
57.252 + }
57.253 +}
57.254 +
57.255 +/*
57.256 +** Set the EP_FromJoin property on all terms of the given expression.
57.257 +** And set the Expr.iRightJoinTable to iTable for every term in the
57.258 +** expression.
57.259 +**
57.260 +** The EP_FromJoin property is used on terms of an expression to tell
57.261 +** the LEFT OUTER JOIN processing logic that this term is part of the
57.262 +** join restriction specified in the ON or USING clause and not a part
57.263 +** of the more general WHERE clause. These terms are moved over to the
57.264 +** WHERE clause during join processing but we need to remember that they
57.265 +** originated in the ON or USING clause.
57.266 +**
57.267 +** The Expr.iRightJoinTable tells the WHERE clause processing that the
57.268 +** expression depends on table iRightJoinTable even if that table is not
57.269 +** explicitly mentioned in the expression. That information is needed
57.270 +** for cases like this:
57.271 +**
57.272 +** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
57.273 +**
57.274 +** The where clause needs to defer the handling of the t1.x=5
57.275 +** term until after the t2 loop of the join. In that way, a
57.276 +** NULL t2 row will be inserted whenever t1.x!=5. If we do not
57.277 +** defer the handling of t1.x=5, it will be processed immediately
57.278 +** after the t1 loop and rows with t1.x!=5 will never appear in
57.279 +** the output, which is incorrect.
57.280 +*/
57.281 +static void setJoinExpr(Expr *p, int iTable){
57.282 + while( p ){
57.283 + ExprSetProperty(p, EP_FromJoin);
57.284 + p->iRightJoinTable = iTable;
57.285 + setJoinExpr(p->pLeft, iTable);
57.286 + p = p->pRight;
57.287 + }
57.288 +}
57.289 +
57.290 +/*
57.291 +** This routine processes the join information for a SELECT statement.
57.292 +** ON and USING clauses are converted into extra terms of the WHERE clause.
57.293 +** NATURAL joins also create extra WHERE clause terms.
57.294 +**
57.295 +** The terms of a FROM clause are contained in the Select.pSrc structure.
57.296 +** The left most table is the first entry in Select.pSrc. The right-most
57.297 +** table is the last entry. The join operator is held in the entry to
57.298 +** the left. Thus entry 0 contains the join operator for the join between
57.299 +** entries 0 and 1. Any ON or USING clauses associated with the join are
57.300 +** also attached to the left entry.
57.301 +**
57.302 +** This routine returns the number of errors encountered.
57.303 +*/
57.304 +static int sqliteProcessJoin(Parse *pParse, Select *p){
57.305 + SrcList *pSrc; /* All tables in the FROM clause */
57.306 + int i, j; /* Loop counters */
57.307 + struct SrcList_item *pLeft; /* Left table being joined */
57.308 + struct SrcList_item *pRight; /* Right table being joined */
57.309 +
57.310 + pSrc = p->pSrc;
57.311 + pLeft = &pSrc->a[0];
57.312 + pRight = &pLeft[1];
57.313 + for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
57.314 + Table *pLeftTab = pLeft->pTab;
57.315 + Table *pRightTab = pRight->pTab;
57.316 +
57.317 + if( pLeftTab==0 || pRightTab==0 ) continue;
57.318 +
57.319 + /* When the NATURAL keyword is present, add WHERE clause terms for
57.320 + ** every column that the two tables have in common.
57.321 + */
57.322 + if( pRight->jointype & JT_NATURAL ){
57.323 + if( pRight->pOn || pRight->pUsing ){
57.324 + sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
57.325 + "an ON or USING clause", 0);
57.326 + return 1;
57.327 + }
57.328 + for(j=0; j<pLeftTab->nCol; j++){
57.329 + char *zName = pLeftTab->aCol[j].zName;
57.330 + if( columnIndex(pRightTab, zName)>=0 ){
57.331 + addWhereTerm(zName, pLeftTab, pLeft->zAlias,
57.332 + pRightTab, pRight->zAlias,
57.333 + pRight->iCursor, &p->pWhere);
57.334 +
57.335 + }
57.336 + }
57.337 + }
57.338 +
57.339 + /* Disallow both ON and USING clauses in the same join
57.340 + */
57.341 + if( pRight->pOn && pRight->pUsing ){
57.342 + sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
57.343 + "clauses in the same join");
57.344 + return 1;
57.345 + }
57.346 +
57.347 + /* Add the ON clause to the end of the WHERE clause, connected by
57.348 + ** an AND operator.
57.349 + */
57.350 + if( pRight->pOn ){
57.351 + setJoinExpr(pRight->pOn, pRight->iCursor);
57.352 + p->pWhere = sqlite3ExprAnd(p->pWhere, pRight->pOn);
57.353 + pRight->pOn = 0;
57.354 + }
57.355 +
57.356 + /* Create extra terms on the WHERE clause for each column named
57.357 + ** in the USING clause. Example: If the two tables to be joined are
57.358 + ** A and B and the USING clause names X, Y, and Z, then add this
57.359 + ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
57.360 + ** Report an error if any column mentioned in the USING clause is
57.361 + ** not contained in both tables to be joined.
57.362 + */
57.363 + if( pRight->pUsing ){
57.364 + IdList *pList = pRight->pUsing;
57.365 + for(j=0; j<pList->nId; j++){
57.366 + char *zName = pList->a[j].zName;
57.367 + if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
57.368 + sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
57.369 + "not present in both tables", zName);
57.370 + return 1;
57.371 + }
57.372 + addWhereTerm(zName, pLeftTab, pLeft->zAlias,
57.373 + pRightTab, pRight->zAlias,
57.374 + pRight->iCursor, &p->pWhere);
57.375 + }
57.376 + }
57.377 + }
57.378 + return 0;
57.379 +}
57.380 +
57.381 +/*
57.382 +** Insert code into "v" that will push the record on the top of the
57.383 +** stack into the sorter.
57.384 +*/
57.385 +static void pushOntoSorter(
57.386 + Parse *pParse, /* Parser context */
57.387 + ExprList *pOrderBy, /* The ORDER BY clause */
57.388 + Select *pSelect /* The whole SELECT statement */
57.389 +){
57.390 + Vdbe *v = pParse->pVdbe;
57.391 + sqlite3ExprCodeExprList(pParse, pOrderBy);
57.392 + sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0);
57.393 + sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0);
57.394 + sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0);
57.395 + sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0);
57.396 + if( pSelect->iLimit>=0 ){
57.397 + int addr1, addr2;
57.398 + addr1 = sqlite3VdbeAddOp(v, OP_IfMemZero, pSelect->iLimit+1, 0);
57.399 + sqlite3VdbeAddOp(v, OP_MemIncr, -1, pSelect->iLimit+1);
57.400 + addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
57.401 + sqlite3VdbeJumpHere(v, addr1);
57.402 + sqlite3VdbeAddOp(v, OP_Last, pOrderBy->iECursor, 0);
57.403 + sqlite3VdbeAddOp(v, OP_Delete, pOrderBy->iECursor, 0);
57.404 + sqlite3VdbeJumpHere(v, addr2);
57.405 + pSelect->iLimit = -1;
57.406 + }
57.407 +}
57.408 +
57.409 +/*
57.410 +** Add code to implement the OFFSET
57.411 +*/
57.412 +static void codeOffset(
57.413 + Vdbe *v, /* Generate code into this VM */
57.414 + Select *p, /* The SELECT statement being coded */
57.415 + int iContinue, /* Jump here to skip the current record */
57.416 + int nPop /* Number of times to pop stack when jumping */
57.417 +){
57.418 + if( p->iOffset>=0 && iContinue!=0 ){
57.419 + int addr;
57.420 + sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iOffset);
57.421 + addr = sqlite3VdbeAddOp(v, OP_IfMemNeg, p->iOffset, 0);
57.422 + if( nPop>0 ){
57.423 + sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
57.424 + }
57.425 + sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
57.426 + VdbeComment((v, "# skip OFFSET records"));
57.427 + sqlite3VdbeJumpHere(v, addr);
57.428 + }
57.429 +}
57.430 +
57.431 +/*
57.432 +** Add code that will check to make sure the top N elements of the
57.433 +** stack are distinct. iTab is a sorting index that holds previously
57.434 +** seen combinations of the N values. A new entry is made in iTab
57.435 +** if the current N values are new.
57.436 +**
57.437 +** A jump to addrRepeat is made and the N+1 values are popped from the
57.438 +** stack if the top N elements are not distinct.
57.439 +*/
57.440 +static void codeDistinct(
57.441 + Vdbe *v, /* Generate code into this VM */
57.442 + int iTab, /* A sorting index used to test for distinctness */
57.443 + int addrRepeat, /* Jump to here if not distinct */
57.444 + int N /* The top N elements of the stack must be distinct */
57.445 +){
57.446 + sqlite3VdbeAddOp(v, OP_MakeRecord, -N, 0);
57.447 + sqlite3VdbeAddOp(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3);
57.448 + sqlite3VdbeAddOp(v, OP_Pop, N+1, 0);
57.449 + sqlite3VdbeAddOp(v, OP_Goto, 0, addrRepeat);
57.450 + VdbeComment((v, "# skip indistinct records"));
57.451 + sqlite3VdbeAddOp(v, OP_IdxInsert, iTab, 0);
57.452 +}
57.453 +
57.454 +/*
57.455 +** Generate an error message when a SELECT is used within a subexpression
57.456 +** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
57.457 +** column. We do this in a subroutine because the error occurs in multiple
57.458 +** places.
57.459 +*/
57.460 +static int checkForMultiColumnSelectError(Parse *pParse, int eDest, int nExpr){
57.461 + if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
57.462 + sqlite3ErrorMsg(pParse, "only a single result allowed for "
57.463 + "a SELECT that is part of an expression");
57.464 + return 1;
57.465 + }else{
57.466 + return 0;
57.467 + }
57.468 +}
57.469 +
57.470 +/*
57.471 +** This routine generates the code for the inside of the inner loop
57.472 +** of a SELECT.
57.473 +**
57.474 +** If srcTab and nColumn are both zero, then the pEList expressions
57.475 +** are evaluated in order to get the data for this row. If nColumn>0
57.476 +** then data is pulled from srcTab and pEList is used only to get the
57.477 +** datatypes for each column.
57.478 +*/
57.479 +static int selectInnerLoop(
57.480 + Parse *pParse, /* The parser context */
57.481 + Select *p, /* The complete select statement being coded */
57.482 + ExprList *pEList, /* List of values being extracted */
57.483 + int srcTab, /* Pull data from this table */
57.484 + int nColumn, /* Number of columns in the source table */
57.485 + ExprList *pOrderBy, /* If not NULL, sort results using this key */
57.486 + int distinct, /* If >=0, make sure results are distinct */
57.487 + int eDest, /* How to dispose of the results */
57.488 + int iParm, /* An argument to the disposal method */
57.489 + int iContinue, /* Jump here to continue with next row */
57.490 + int iBreak, /* Jump here to break out of the inner loop */
57.491 + char *aff /* affinity string if eDest is SRT_Union */
57.492 +){
57.493 + Vdbe *v = pParse->pVdbe;
57.494 + int i;
57.495 + int hasDistinct; /* True if the DISTINCT keyword is present */
57.496 +
57.497 + if( v==0 ) return 0;
57.498 + assert( pEList!=0 );
57.499 +
57.500 + /* If there was a LIMIT clause on the SELECT statement, then do the check
57.501 + ** to see if this row should be output.
57.502 + */
57.503 + hasDistinct = distinct>=0 && pEList->nExpr>0;
57.504 + if( pOrderBy==0 && !hasDistinct ){
57.505 + codeOffset(v, p, iContinue, 0);
57.506 + }
57.507 +
57.508 + /* Pull the requested columns.
57.509 + */
57.510 + if( nColumn>0 ){
57.511 + for(i=0; i<nColumn; i++){
57.512 + sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
57.513 + }
57.514 + }else{
57.515 + nColumn = pEList->nExpr;
57.516 + sqlite3ExprCodeExprList(pParse, pEList);
57.517 + }
57.518 +
57.519 + /* If the DISTINCT keyword was present on the SELECT statement
57.520 + ** and this row has been seen before, then do not make this row
57.521 + ** part of the result.
57.522 + */
57.523 + if( hasDistinct ){
57.524 + assert( pEList!=0 );
57.525 + assert( pEList->nExpr==nColumn );
57.526 + codeDistinct(v, distinct, iContinue, nColumn);
57.527 + if( pOrderBy==0 ){
57.528 + codeOffset(v, p, iContinue, nColumn);
57.529 + }
57.530 + }
57.531 +
57.532 + if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){
57.533 + return 0;
57.534 + }
57.535 +
57.536 + switch( eDest ){
57.537 + /* In this mode, write each query result to the key of the temporary
57.538 + ** table iParm.
57.539 + */
57.540 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
57.541 + case SRT_Union: {
57.542 + sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
57.543 + if( aff ){
57.544 + sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
57.545 + }
57.546 + sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0);
57.547 + break;
57.548 + }
57.549 +
57.550 + /* Construct a record from the query result, but instead of
57.551 + ** saving that record, use it as a key to delete elements from
57.552 + ** the temporary table iParm.
57.553 + */
57.554 + case SRT_Except: {
57.555 + int addr;
57.556 + addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
57.557 + sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
57.558 + sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
57.559 + sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
57.560 + break;
57.561 + }
57.562 +#endif
57.563 +
57.564 + /* Store the result as data using a unique key.
57.565 + */
57.566 + case SRT_Table:
57.567 + case SRT_EphemTab: {
57.568 + sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
57.569 + if( pOrderBy ){
57.570 + pushOntoSorter(pParse, pOrderBy, p);
57.571 + }else{
57.572 + sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
57.573 + sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
57.574 + sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
57.575 + }
57.576 + break;
57.577 + }
57.578 +
57.579 +#ifndef SQLITE_OMIT_SUBQUERY
57.580 + /* If we are creating a set for an "expr IN (SELECT ...)" construct,
57.581 + ** then there should be a single item on the stack. Write this
57.582 + ** item into the set table with bogus data.
57.583 + */
57.584 + case SRT_Set: {
57.585 + int addr1 = sqlite3VdbeCurrentAddr(v);
57.586 + int addr2;
57.587 +
57.588 + assert( nColumn==1 );
57.589 + sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
57.590 + sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
57.591 + addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
57.592 + p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr,(iParm>>16)&0xff);
57.593 + if( pOrderBy ){
57.594 + /* At first glance you would think we could optimize out the
57.595 + ** ORDER BY in this case since the order of entries in the set
57.596 + ** does not matter. But there might be a LIMIT clause, in which
57.597 + ** case the order does matter */
57.598 + pushOntoSorter(pParse, pOrderBy, p);
57.599 + }else{
57.600 + sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
57.601 + sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
57.602 + }
57.603 + sqlite3VdbeJumpHere(v, addr2);
57.604 + break;
57.605 + }
57.606 +
57.607 + /* If any row exist in the result set, record that fact and abort.
57.608 + */
57.609 + case SRT_Exists: {
57.610 + sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm);
57.611 + sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
57.612 + /* The LIMIT clause will terminate the loop for us */
57.613 + break;
57.614 + }
57.615 +
57.616 + /* If this is a scalar select that is part of an expression, then
57.617 + ** store the results in the appropriate memory cell and break out
57.618 + ** of the scan loop.
57.619 + */
57.620 + case SRT_Mem: {
57.621 + assert( nColumn==1 );
57.622 + if( pOrderBy ){
57.623 + pushOntoSorter(pParse, pOrderBy, p);
57.624 + }else{
57.625 + sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
57.626 + /* The LIMIT clause will jump out of the loop for us */
57.627 + }
57.628 + break;
57.629 + }
57.630 +#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
57.631 +
57.632 + /* Send the data to the callback function or to a subroutine. In the
57.633 + ** case of a subroutine, the subroutine itself is responsible for
57.634 + ** popping the data from the stack.
57.635 + */
57.636 + case SRT_Subroutine:
57.637 + case SRT_Callback: {
57.638 + if( pOrderBy ){
57.639 + sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
57.640 + pushOntoSorter(pParse, pOrderBy, p);
57.641 + }else if( eDest==SRT_Subroutine ){
57.642 + sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
57.643 + }else{
57.644 + sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
57.645 + }
57.646 + break;
57.647 + }
57.648 +
57.649 +#if !defined(SQLITE_OMIT_TRIGGER)
57.650 + /* Discard the results. This is used for SELECT statements inside
57.651 + ** the body of a TRIGGER. The purpose of such selects is to call
57.652 + ** user-defined functions that have side effects. We do not care
57.653 + ** about the actual results of the select.
57.654 + */
57.655 + default: {
57.656 + assert( eDest==SRT_Discard );
57.657 + sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
57.658 + break;
57.659 + }
57.660 +#endif
57.661 + }
57.662 +
57.663 + /* Jump to the end of the loop if the LIMIT is reached.
57.664 + */
57.665 + if( p->iLimit>=0 && pOrderBy==0 ){
57.666 + sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
57.667 + sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak);
57.668 + }
57.669 + return 0;
57.670 +}
57.671 +
57.672 +/*
57.673 +** Given an expression list, generate a KeyInfo structure that records
57.674 +** the collating sequence for each expression in that expression list.
57.675 +**
57.676 +** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
57.677 +** KeyInfo structure is appropriate for initializing a virtual index to
57.678 +** implement that clause. If the ExprList is the result set of a SELECT
57.679 +** then the KeyInfo structure is appropriate for initializing a virtual
57.680 +** index to implement a DISTINCT test.
57.681 +**
57.682 +** Space to hold the KeyInfo structure is obtain from malloc. The calling
57.683 +** function is responsible for seeing that this structure is eventually
57.684 +** freed. Add the KeyInfo structure to the P3 field of an opcode using
57.685 +** P3_KEYINFO_HANDOFF is the usual way of dealing with this.
57.686 +*/
57.687 +static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
57.688 + sqlite3 *db = pParse->db;
57.689 + int nExpr;
57.690 + KeyInfo *pInfo;
57.691 + struct ExprList_item *pItem;
57.692 + int i;
57.693 +
57.694 + nExpr = pList->nExpr;
57.695 + pInfo = sqliteMalloc( sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
57.696 + if( pInfo ){
57.697 + pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
57.698 + pInfo->nField = nExpr;
57.699 + pInfo->enc = ENC(db);
57.700 + for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
57.701 + CollSeq *pColl;
57.702 + pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
57.703 + if( !pColl ){
57.704 + pColl = db->pDfltColl;
57.705 + }
57.706 + pInfo->aColl[i] = pColl;
57.707 + pInfo->aSortOrder[i] = pItem->sortOrder;
57.708 + }
57.709 + }
57.710 + return pInfo;
57.711 +}
57.712 +
57.713 +
57.714 +/*
57.715 +** If the inner loop was generated using a non-null pOrderBy argument,
57.716 +** then the results were placed in a sorter. After the loop is terminated
57.717 +** we need to run the sorter and output the results. The following
57.718 +** routine generates the code needed to do that.
57.719 +*/
57.720 +static void generateSortTail(
57.721 + Parse *pParse, /* Parsing context */
57.722 + Select *p, /* The SELECT statement */
57.723 + Vdbe *v, /* Generate code into this VDBE */
57.724 + int nColumn, /* Number of columns of data */
57.725 + int eDest, /* Write the sorted results here */
57.726 + int iParm /* Optional parameter associated with eDest */
57.727 +){
57.728 + int brk = sqlite3VdbeMakeLabel(v);
57.729 + int cont = sqlite3VdbeMakeLabel(v);
57.730 + int addr;
57.731 + int iTab;
57.732 + int pseudoTab = 0;
57.733 + ExprList *pOrderBy = p->pOrderBy;
57.734 +
57.735 + iTab = pOrderBy->iECursor;
57.736 + if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
57.737 + pseudoTab = pParse->nTab++;
57.738 + sqlite3VdbeAddOp(v, OP_OpenPseudo, pseudoTab, 0);
57.739 + sqlite3VdbeAddOp(v, OP_SetNumColumns, pseudoTab, nColumn);
57.740 + }
57.741 + addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk);
57.742 + codeOffset(v, p, cont, 0);
57.743 + if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
57.744 + sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
57.745 + }
57.746 + sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1);
57.747 + switch( eDest ){
57.748 + case SRT_Table:
57.749 + case SRT_EphemTab: {
57.750 + sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
57.751 + sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
57.752 + sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
57.753 + break;
57.754 + }
57.755 +#ifndef SQLITE_OMIT_SUBQUERY
57.756 + case SRT_Set: {
57.757 + assert( nColumn==1 );
57.758 + sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
57.759 + sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
57.760 + sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
57.761 + sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
57.762 + sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
57.763 + break;
57.764 + }
57.765 + case SRT_Mem: {
57.766 + assert( nColumn==1 );
57.767 + sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
57.768 + /* The LIMIT clause will terminate the loop for us */
57.769 + break;
57.770 + }
57.771 +#endif
57.772 + case SRT_Callback:
57.773 + case SRT_Subroutine: {
57.774 + int i;
57.775 + sqlite3VdbeAddOp(v, OP_Insert, pseudoTab, 0);
57.776 + for(i=0; i<nColumn; i++){
57.777 + sqlite3VdbeAddOp(v, OP_Column, pseudoTab, i);
57.778 + }
57.779 + if( eDest==SRT_Callback ){
57.780 + sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
57.781 + }else{
57.782 + sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
57.783 + }
57.784 + break;
57.785 + }
57.786 + default: {
57.787 + /* Do nothing */
57.788 + break;
57.789 + }
57.790 + }
57.791 +
57.792 + /* Jump to the end of the loop when the LIMIT is reached
57.793 + */
57.794 + if( p->iLimit>=0 ){
57.795 + sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
57.796 + sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk);
57.797 + }
57.798 +
57.799 + /* The bottom of the loop
57.800 + */
57.801 + sqlite3VdbeResolveLabel(v, cont);
57.802 + sqlite3VdbeAddOp(v, OP_Next, iTab, addr);
57.803 + sqlite3VdbeResolveLabel(v, brk);
57.804 + if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
57.805 + sqlite3VdbeAddOp(v, OP_Close, pseudoTab, 0);
57.806 + }
57.807 +
57.808 +}
57.809 +
57.810 +/*
57.811 +** Return a pointer to a string containing the 'declaration type' of the
57.812 +** expression pExpr. The string may be treated as static by the caller.
57.813 +**
57.814 +** The declaration type is the exact datatype definition extracted from the
57.815 +** original CREATE TABLE statement if the expression is a column. The
57.816 +** declaration type for a ROWID field is INTEGER. Exactly when an expression
57.817 +** is considered a column can be complex in the presence of subqueries. The
57.818 +** result-set expression in all of the following SELECT statements is
57.819 +** considered a column by this function.
57.820 +**
57.821 +** SELECT col FROM tbl;
57.822 +** SELECT (SELECT col FROM tbl;
57.823 +** SELECT (SELECT col FROM tbl);
57.824 +** SELECT abc FROM (SELECT col AS abc FROM tbl);
57.825 +**
57.826 +** The declaration type for any expression other than a column is NULL.
57.827 +*/
57.828 +static const char *columnType(
57.829 + NameContext *pNC,
57.830 + Expr *pExpr,
57.831 + const char **pzOriginDb,
57.832 + const char **pzOriginTab,
57.833 + const char **pzOriginCol
57.834 +){
57.835 + char const *zType = 0;
57.836 + char const *zOriginDb = 0;
57.837 + char const *zOriginTab = 0;
57.838 + char const *zOriginCol = 0;
57.839 + int j;
57.840 + if( pExpr==0 || pNC->pSrcList==0 ) return 0;
57.841 +
57.842 + switch( pExpr->op ){
57.843 + case TK_AGG_COLUMN:
57.844 + case TK_COLUMN: {
57.845 + /* The expression is a column. Locate the table the column is being
57.846 + ** extracted from in NameContext.pSrcList. This table may be real
57.847 + ** database table or a subquery.
57.848 + */
57.849 + Table *pTab = 0; /* Table structure column is extracted from */
57.850 + Select *pS = 0; /* Select the column is extracted from */
57.851 + int iCol = pExpr->iColumn; /* Index of column in pTab */
57.852 + while( pNC && !pTab ){
57.853 + SrcList *pTabList = pNC->pSrcList;
57.854 + for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
57.855 + if( j<pTabList->nSrc ){
57.856 + pTab = pTabList->a[j].pTab;
57.857 + pS = pTabList->a[j].pSelect;
57.858 + }else{
57.859 + pNC = pNC->pNext;
57.860 + }
57.861 + }
57.862 +
57.863 + if( pTab==0 ){
57.864 + /* FIX ME:
57.865 + ** This can occurs if you have something like "SELECT new.x;" inside
57.866 + ** a trigger. In other words, if you reference the special "new"
57.867 + ** table in the result set of a select. We do not have a good way
57.868 + ** to find the actual table type, so call it "TEXT". This is really
57.869 + ** something of a bug, but I do not know how to fix it.
57.870 + **
57.871 + ** This code does not produce the correct answer - it just prevents
57.872 + ** a segfault. See ticket #1229.
57.873 + */
57.874 + zType = "TEXT";
57.875 + break;
57.876 + }
57.877 +
57.878 + assert( pTab );
57.879 + if( pS ){
57.880 + /* The "table" is actually a sub-select or a view in the FROM clause
57.881 + ** of the SELECT statement. Return the declaration type and origin
57.882 + ** data for the result-set column of the sub-select.
57.883 + */
57.884 + if( iCol>=0 && iCol<pS->pEList->nExpr ){
57.885 + /* If iCol is less than zero, then the expression requests the
57.886 + ** rowid of the sub-select or view. This expression is legal (see
57.887 + ** test case misc2.2.2) - it always evaluates to NULL.
57.888 + */
57.889 + NameContext sNC;
57.890 + Expr *p = pS->pEList->a[iCol].pExpr;
57.891 + sNC.pSrcList = pS->pSrc;
57.892 + sNC.pNext = 0;
57.893 + sNC.pParse = pNC->pParse;
57.894 + zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
57.895 + }
57.896 + }else if( pTab->pSchema ){
57.897 + /* A real table */
57.898 + assert( !pS );
57.899 + if( iCol<0 ) iCol = pTab->iPKey;
57.900 + assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
57.901 + if( iCol<0 ){
57.902 + zType = "INTEGER";
57.903 + zOriginCol = "rowid";
57.904 + }else{
57.905 + zType = pTab->aCol[iCol].zType;
57.906 + zOriginCol = pTab->aCol[iCol].zName;
57.907 + }
57.908 + zOriginTab = pTab->zName;
57.909 + if( pNC->pParse ){
57.910 + int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
57.911 + zOriginDb = pNC->pParse->db->aDb[iDb].zName;
57.912 + }
57.913 + }
57.914 + break;
57.915 + }
57.916 +#ifndef SQLITE_OMIT_SUBQUERY
57.917 + case TK_SELECT: {
57.918 + /* The expression is a sub-select. Return the declaration type and
57.919 + ** origin info for the single column in the result set of the SELECT
57.920 + ** statement.
57.921 + */
57.922 + NameContext sNC;
57.923 + Select *pS = pExpr->pSelect;
57.924 + Expr *p = pS->pEList->a[0].pExpr;
57.925 + sNC.pSrcList = pS->pSrc;
57.926 + sNC.pNext = pNC;
57.927 + sNC.pParse = pNC->pParse;
57.928 + zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
57.929 + break;
57.930 + }
57.931 +#endif
57.932 + }
57.933 +
57.934 + if( pzOriginDb ){
57.935 + assert( pzOriginTab && pzOriginCol );
57.936 + *pzOriginDb = zOriginDb;
57.937 + *pzOriginTab = zOriginTab;
57.938 + *pzOriginCol = zOriginCol;
57.939 + }
57.940 + return zType;
57.941 +}
57.942 +
57.943 +/*
57.944 +** Generate code that will tell the VDBE the declaration types of columns
57.945 +** in the result set.
57.946 +*/
57.947 +static void generateColumnTypes(
57.948 + Parse *pParse, /* Parser context */
57.949 + SrcList *pTabList, /* List of tables */
57.950 + ExprList *pEList /* Expressions defining the result set */
57.951 +){
57.952 + Vdbe *v = pParse->pVdbe;
57.953 + int i;
57.954 + NameContext sNC;
57.955 + sNC.pSrcList = pTabList;
57.956 + sNC.pParse = pParse;
57.957 + for(i=0; i<pEList->nExpr; i++){
57.958 + Expr *p = pEList->a[i].pExpr;
57.959 + const char *zOrigDb = 0;
57.960 + const char *zOrigTab = 0;
57.961 + const char *zOrigCol = 0;
57.962 + const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
57.963 +
57.964 + /* The vdbe must make it's own copy of the column-type and other
57.965 + ** column specific strings, in case the schema is reset before this
57.966 + ** virtual machine is deleted.
57.967 + */
57.968 + sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P3_TRANSIENT);
57.969 + sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P3_TRANSIENT);
57.970 + sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P3_TRANSIENT);
57.971 + sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P3_TRANSIENT);
57.972 + }
57.973 +}
57.974 +
57.975 +/*
57.976 +** Generate code that will tell the VDBE the names of columns
57.977 +** in the result set. This information is used to provide the
57.978 +** azCol[] values in the callback.
57.979 +*/
57.980 +static void generateColumnNames(
57.981 + Parse *pParse, /* Parser context */
57.982 + SrcList *pTabList, /* List of tables */
57.983 + ExprList *pEList /* Expressions defining the result set */
57.984 +){
57.985 + Vdbe *v = pParse->pVdbe;
57.986 + int i, j;
57.987 + sqlite3 *db = pParse->db;
57.988 + int fullNames, shortNames;
57.989 +
57.990 +#ifndef SQLITE_OMIT_EXPLAIN
57.991 + /* If this is an EXPLAIN, skip this step */
57.992 + if( pParse->explain ){
57.993 + return;
57.994 + }
57.995 +#endif
57.996 +
57.997 + assert( v!=0 );
57.998 + if( pParse->colNamesSet || v==0 || sqlite3MallocFailed() ) return;
57.999 + pParse->colNamesSet = 1;
57.1000 + fullNames = (db->flags & SQLITE_FullColNames)!=0;
57.1001 + shortNames = (db->flags & SQLITE_ShortColNames)!=0;
57.1002 + sqlite3VdbeSetNumCols(v, pEList->nExpr);
57.1003 + for(i=0; i<pEList->nExpr; i++){
57.1004 + Expr *p;
57.1005 + p = pEList->a[i].pExpr;
57.1006 + if( p==0 ) continue;
57.1007 + if( pEList->a[i].zName ){
57.1008 + char *zName = pEList->a[i].zName;
57.1009 + sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
57.1010 + continue;
57.1011 + }
57.1012 + if( p->op==TK_COLUMN && pTabList ){
57.1013 + Table *pTab;
57.1014 + char *zCol;
57.1015 + int iCol = p->iColumn;
57.1016 + for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
57.1017 + assert( j<pTabList->nSrc );
57.1018 + pTab = pTabList->a[j].pTab;
57.1019 + if( iCol<0 ) iCol = pTab->iPKey;
57.1020 + assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
57.1021 + if( iCol<0 ){
57.1022 + zCol = "rowid";
57.1023 + }else{
57.1024 + zCol = pTab->aCol[iCol].zName;
57.1025 + }
57.1026 + if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
57.1027 + sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
57.1028 + }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
57.1029 + char *zName = 0;
57.1030 + char *zTab;
57.1031 +
57.1032 + zTab = pTabList->a[j].zAlias;
57.1033 + if( fullNames || zTab==0 ) zTab = pTab->zName;
57.1034 + sqlite3SetString(&zName, zTab, ".", zCol, (char*)0);
57.1035 + sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P3_DYNAMIC);
57.1036 + }else{
57.1037 + sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
57.1038 + }
57.1039 + }else if( p->span.z && p->span.z[0] ){
57.1040 + sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
57.1041 + /* sqlite3VdbeCompressSpace(v, addr); */
57.1042 + }else{
57.1043 + char zName[30];
57.1044 + assert( p->op!=TK_COLUMN || pTabList==0 );
57.1045 + sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1);
57.1046 + sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0);
57.1047 + }
57.1048 + }
57.1049 + generateColumnTypes(pParse, pTabList, pEList);
57.1050 +}
57.1051 +
57.1052 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
57.1053 +/*
57.1054 +** Name of the connection operator, used for error messages.
57.1055 +*/
57.1056 +static const char *selectOpName(int id){
57.1057 + char *z;
57.1058 + switch( id ){
57.1059 + case TK_ALL: z = "UNION ALL"; break;
57.1060 + case TK_INTERSECT: z = "INTERSECT"; break;
57.1061 + case TK_EXCEPT: z = "EXCEPT"; break;
57.1062 + default: z = "UNION"; break;
57.1063 + }
57.1064 + return z;
57.1065 +}
57.1066 +#endif /* SQLITE_OMIT_COMPOUND_SELECT */
57.1067 +
57.1068 +/*
57.1069 +** Forward declaration
57.1070 +*/
57.1071 +static int prepSelectStmt(Parse*, Select*);
57.1072 +
57.1073 +/*
57.1074 +** Given a SELECT statement, generate a Table structure that describes
57.1075 +** the result set of that SELECT.
57.1076 +*/
57.1077 +Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
57.1078 + Table *pTab;
57.1079 + int i, j;
57.1080 + ExprList *pEList;
57.1081 + Column *aCol, *pCol;
57.1082 +
57.1083 + while( pSelect->pPrior ) pSelect = pSelect->pPrior;
57.1084 + if( prepSelectStmt(pParse, pSelect) ){
57.1085 + return 0;
57.1086 + }
57.1087 + if( sqlite3SelectResolve(pParse, pSelect, 0) ){
57.1088 + return 0;
57.1089 + }
57.1090 + pTab = sqliteMalloc( sizeof(Table) );
57.1091 + if( pTab==0 ){
57.1092 + return 0;
57.1093 + }
57.1094 + pTab->nRef = 1;
57.1095 + pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
57.1096 + pEList = pSelect->pEList;
57.1097 + pTab->nCol = pEList->nExpr;
57.1098 + assert( pTab->nCol>0 );
57.1099 + pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
57.1100 + for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
57.1101 + Expr *p, *pR;
57.1102 + char *zType;
57.1103 + char *zName;
57.1104 + int nName;
57.1105 + CollSeq *pColl;
57.1106 + int cnt;
57.1107 + NameContext sNC;
57.1108 +
57.1109 + /* Get an appropriate name for the column
57.1110 + */
57.1111 + p = pEList->a[i].pExpr;
57.1112 + assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
57.1113 + if( (zName = pEList->a[i].zName)!=0 ){
57.1114 + /* If the column contains an "AS <name>" phrase, use <name> as the name */
57.1115 + zName = sqliteStrDup(zName);
57.1116 + }else if( p->op==TK_DOT
57.1117 + && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
57.1118 + /* For columns of the from A.B use B as the name */
57.1119 + zName = sqlite3MPrintf("%T", &pR->token);
57.1120 + }else if( p->span.z && p->span.z[0] ){
57.1121 + /* Use the original text of the column expression as its name */
57.1122 + zName = sqlite3MPrintf("%T", &p->span);
57.1123 + }else{
57.1124 + /* If all else fails, make up a name */
57.1125 + zName = sqlite3MPrintf("column%d", i+1);
57.1126 + }
57.1127 + sqlite3Dequote(zName);
57.1128 + if( sqlite3MallocFailed() ){
57.1129 + sqliteFree(zName);
57.1130 + sqlite3DeleteTable(pTab);
57.1131 + return 0;
57.1132 + }
57.1133 +
57.1134 + /* Make sure the column name is unique. If the name is not unique,
57.1135 + ** append a integer to the name so that it becomes unique.
57.1136 + */
57.1137 + nName = strlen(zName);
57.1138 + for(j=cnt=0; j<i; j++){
57.1139 + if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
57.1140 + zName[nName] = 0;
57.1141 + zName = sqlite3MPrintf("%z:%d", zName, ++cnt);
57.1142 + j = -1;
57.1143 + if( zName==0 ) break;
57.1144 + }
57.1145 + }
57.1146 + pCol->zName = zName;
57.1147 +
57.1148 + /* Get the typename, type affinity, and collating sequence for the
57.1149 + ** column.
57.1150 + */
57.1151 + memset(&sNC, 0, sizeof(sNC));
57.1152 + sNC.pSrcList = pSelect->pSrc;
57.1153 + zType = sqliteStrDup(columnType(&sNC, p, 0, 0, 0));
57.1154 + pCol->zType = zType;
57.1155 + pCol->affinity = sqlite3ExprAffinity(p);
57.1156 + pColl = sqlite3ExprCollSeq(pParse, p);
57.1157 + if( pColl ){
57.1158 + pCol->zColl = sqliteStrDup(pColl->zName);
57.1159 + }
57.1160 + }
57.1161 + pTab->iPKey = -1;
57.1162 + return pTab;
57.1163 +}
57.1164 +
57.1165 +/*
57.1166 +** Prepare a SELECT statement for processing by doing the following
57.1167 +** things:
57.1168 +**
57.1169 +** (1) Make sure VDBE cursor numbers have been assigned to every
57.1170 +** element of the FROM clause.
57.1171 +**
57.1172 +** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
57.1173 +** defines FROM clause. When views appear in the FROM clause,
57.1174 +** fill pTabList->a[].pSelect with a copy of the SELECT statement
57.1175 +** that implements the view. A copy is made of the view's SELECT
57.1176 +** statement so that we can freely modify or delete that statement
57.1177 +** without worrying about messing up the presistent representation
57.1178 +** of the view.
57.1179 +**
57.1180 +** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
57.1181 +** on joins and the ON and USING clause of joins.
57.1182 +**
57.1183 +** (4) Scan the list of columns in the result set (pEList) looking
57.1184 +** for instances of the "*" operator or the TABLE.* operator.
57.1185 +** If found, expand each "*" to be every column in every table
57.1186 +** and TABLE.* to be every column in TABLE.
57.1187 +**
57.1188 +** Return 0 on success. If there are problems, leave an error message
57.1189 +** in pParse and return non-zero.
57.1190 +*/
57.1191 +static int prepSelectStmt(Parse *pParse, Select *p){
57.1192 + int i, j, k, rc;
57.1193 + SrcList *pTabList;
57.1194 + ExprList *pEList;
57.1195 + struct SrcList_item *pFrom;
57.1196 +
57.1197 + if( p==0 || p->pSrc==0 || sqlite3MallocFailed() ){
57.1198 + return 1;
57.1199 + }
57.1200 + pTabList = p->pSrc;
57.1201 + pEList = p->pEList;
57.1202 +
57.1203 + /* Make sure cursor numbers have been assigned to all entries in
57.1204 + ** the FROM clause of the SELECT statement.
57.1205 + */
57.1206 + sqlite3SrcListAssignCursors(pParse, p->pSrc);
57.1207 +
57.1208 + /* Look up every table named in the FROM clause of the select. If
57.1209 + ** an entry of the FROM clause is a subquery instead of a table or view,
57.1210 + ** then create a transient table structure to describe the subquery.
57.1211 + */
57.1212 + for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
57.1213 + Table *pTab;
57.1214 + if( pFrom->pTab!=0 ){
57.1215 + /* This statement has already been prepared. There is no need
57.1216 + ** to go further. */
57.1217 + assert( i==0 );
57.1218 + return 0;
57.1219 + }
57.1220 + if( pFrom->zName==0 ){
57.1221 +#ifndef SQLITE_OMIT_SUBQUERY
57.1222 + /* A sub-query in the FROM clause of a SELECT */
57.1223 + assert( pFrom->pSelect!=0 );
57.1224 + if( pFrom->zAlias==0 ){
57.1225 + pFrom->zAlias =
57.1226 + sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
57.1227 + }
57.1228 + assert( pFrom->pTab==0 );
57.1229 + pFrom->pTab = pTab =
57.1230 + sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
57.1231 + if( pTab==0 ){
57.1232 + return 1;
57.1233 + }
57.1234 + /* The isEphem flag indicates that the Table structure has been
57.1235 + ** dynamically allocated and may be freed at any time. In other words,
57.1236 + ** pTab is not pointing to a persistent table structure that defines
57.1237 + ** part of the schema. */
57.1238 + pTab->isEphem = 1;
57.1239 +#endif
57.1240 + }else{
57.1241 + /* An ordinary table or view name in the FROM clause */
57.1242 + assert( pFrom->pTab==0 );
57.1243 + pFrom->pTab = pTab =
57.1244 + sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
57.1245 + if( pTab==0 ){
57.1246 + return 1;
57.1247 + }
57.1248 + pTab->nRef++;
57.1249 +#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
57.1250 + if( pTab->pSelect || IsVirtual(pTab) ){
57.1251 + /* We reach here if the named table is a really a view */
57.1252 + if( sqlite3ViewGetColumnNames(pParse, pTab) ){
57.1253 + return 1;
57.1254 + }
57.1255 + /* If pFrom->pSelect!=0 it means we are dealing with a
57.1256 + ** view within a view. The SELECT structure has already been
57.1257 + ** copied by the outer view so we can skip the copy step here
57.1258 + ** in the inner view.
57.1259 + */
57.1260 + if( pFrom->pSelect==0 ){
57.1261 + pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
57.1262 + }
57.1263 + }
57.1264 +#endif
57.1265 + }
57.1266 + }
57.1267 +
57.1268 + /* Process NATURAL keywords, and ON and USING clauses of joins.
57.1269 + */
57.1270 + if( sqliteProcessJoin(pParse, p) ) return 1;
57.1271 +
57.1272 + /* For every "*" that occurs in the column list, insert the names of
57.1273 + ** all columns in all tables. And for every TABLE.* insert the names
57.1274 + ** of all columns in TABLE. The parser inserted a special expression
57.1275 + ** with the TK_ALL operator for each "*" that it found in the column list.
57.1276 + ** The following code just has to locate the TK_ALL expressions and expand
57.1277 + ** each one to the list of all columns in all tables.
57.1278 + **
57.1279 + ** The first loop just checks to see if there are any "*" operators
57.1280 + ** that need expanding.
57.1281 + */
57.1282 + for(k=0; k<pEList->nExpr; k++){
57.1283 + Expr *pE = pEList->a[k].pExpr;
57.1284 + if( pE->op==TK_ALL ) break;
57.1285 + if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
57.1286 + && pE->pLeft && pE->pLeft->op==TK_ID ) break;
57.1287 + }
57.1288 + rc = 0;
57.1289 + if( k<pEList->nExpr ){
57.1290 + /*
57.1291 + ** If we get here it means the result set contains one or more "*"
57.1292 + ** operators that need to be expanded. Loop through each expression
57.1293 + ** in the result set and expand them one by one.
57.1294 + */
57.1295 + struct ExprList_item *a = pEList->a;
57.1296 + ExprList *pNew = 0;
57.1297 + int flags = pParse->db->flags;
57.1298 + int longNames = (flags & SQLITE_FullColNames)!=0 &&
57.1299 + (flags & SQLITE_ShortColNames)==0;
57.1300 +
57.1301 + for(k=0; k<pEList->nExpr; k++){
57.1302 + Expr *pE = a[k].pExpr;
57.1303 + if( pE->op!=TK_ALL &&
57.1304 + (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
57.1305 + /* This particular expression does not need to be expanded.
57.1306 + */
57.1307 + pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
57.1308 + if( pNew ){
57.1309 + pNew->a[pNew->nExpr-1].zName = a[k].zName;
57.1310 + }else{
57.1311 + rc = 1;
57.1312 + }
57.1313 + a[k].pExpr = 0;
57.1314 + a[k].zName = 0;
57.1315 + }else{
57.1316 + /* This expression is a "*" or a "TABLE.*" and needs to be
57.1317 + ** expanded. */
57.1318 + int tableSeen = 0; /* Set to 1 when TABLE matches */
57.1319 + char *zTName; /* text of name of TABLE */
57.1320 + if( pE->op==TK_DOT && pE->pLeft ){
57.1321 + zTName = sqlite3NameFromToken(&pE->pLeft->token);
57.1322 + }else{
57.1323 + zTName = 0;
57.1324 + }
57.1325 + for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
57.1326 + Table *pTab = pFrom->pTab;
57.1327 + char *zTabName = pFrom->zAlias;
57.1328 + if( zTabName==0 || zTabName[0]==0 ){
57.1329 + zTabName = pTab->zName;
57.1330 + }
57.1331 + if( zTName && (zTabName==0 || zTabName[0]==0 ||
57.1332 + sqlite3StrICmp(zTName, zTabName)!=0) ){
57.1333 + continue;
57.1334 + }
57.1335 + tableSeen = 1;
57.1336 + for(j=0; j<pTab->nCol; j++){
57.1337 + Expr *pExpr, *pRight;
57.1338 + char *zName = pTab->aCol[j].zName;
57.1339 +
57.1340 + /* If a column is marked as 'hidden' (currently only possible
57.1341 + ** for virtual tables), do not include it in the expanded
57.1342 + ** result-set list.
57.1343 + */
57.1344 + if( IsHiddenColumn(&pTab->aCol[j]) ){
57.1345 + assert(IsVirtual(pTab));
57.1346 + continue;
57.1347 + }
57.1348 +
57.1349 + if( i>0 ){
57.1350 + struct SrcList_item *pLeft = &pTabList->a[i-1];
57.1351 + if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
57.1352 + columnIndex(pLeft->pTab, zName)>=0 ){
57.1353 + /* In a NATURAL join, omit the join columns from the
57.1354 + ** table on the right */
57.1355 + continue;
57.1356 + }
57.1357 + if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
57.1358 + /* In a join with a USING clause, omit columns in the
57.1359 + ** using clause from the table on the right. */
57.1360 + continue;
57.1361 + }
57.1362 + }
57.1363 + pRight = sqlite3Expr(TK_ID, 0, 0, 0);
57.1364 + if( pRight==0 ) break;
57.1365 + setQuotedToken(&pRight->token, zName);
57.1366 + if( zTabName && (longNames || pTabList->nSrc>1) ){
57.1367 + Expr *pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
57.1368 + pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
57.1369 + if( pExpr==0 ) break;
57.1370 + setQuotedToken(&pLeft->token, zTabName);
57.1371 + setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
57.1372 + pExpr->span.dyn = 1;
57.1373 + pExpr->token.z = 0;
57.1374 + pExpr->token.n = 0;
57.1375 + pExpr->token.dyn = 0;
57.1376 + }else{
57.1377 + pExpr = pRight;
57.1378 + pExpr->span = pExpr->token;
57.1379 + pExpr->span.dyn = 0;
57.1380 + }
57.1381 + if( longNames ){
57.1382 + pNew = sqlite3ExprListAppend(pNew, pExpr, &pExpr->span);
57.1383 + }else{
57.1384 + pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token);
57.1385 + }
57.1386 + }
57.1387 + }
57.1388 + if( !tableSeen ){
57.1389 + if( zTName ){
57.1390 + sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
57.1391 + }else{
57.1392 + sqlite3ErrorMsg(pParse, "no tables specified");
57.1393 + }
57.1394 + rc = 1;
57.1395 + }
57.1396 + sqliteFree(zTName);
57.1397 + }
57.1398 + }
57.1399 + sqlite3ExprListDelete(pEList);
57.1400 + p->pEList = pNew;
57.1401 + }
57.1402 + if( p->pEList && p->pEList->nExpr>SQLITE_MAX_COLUMN ){
57.1403 + sqlite3ErrorMsg(pParse, "too many columns in result set");
57.1404 + rc = SQLITE_ERROR;
57.1405 + }
57.1406 + if( sqlite3MallocFailed() ){
57.1407 + rc = SQLITE_NOMEM;
57.1408 + }
57.1409 + return rc;
57.1410 +}
57.1411 +
57.1412 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
57.1413 +/*
57.1414 +** This routine associates entries in an ORDER BY expression list with
57.1415 +** columns in a result. For each ORDER BY expression, the opcode of
57.1416 +** the top-level node is changed to TK_COLUMN and the iColumn value of
57.1417 +** the top-level node is filled in with column number and the iTable
57.1418 +** value of the top-level node is filled with iTable parameter.
57.1419 +**
57.1420 +** If there are prior SELECT clauses, they are processed first. A match
57.1421 +** in an earlier SELECT takes precedence over a later SELECT.
57.1422 +**
57.1423 +** Any entry that does not match is flagged as an error. The number
57.1424 +** of errors is returned.
57.1425 +*/
57.1426 +static int matchOrderbyToColumn(
57.1427 + Parse *pParse, /* A place to leave error messages */
57.1428 + Select *pSelect, /* Match to result columns of this SELECT */
57.1429 + ExprList *pOrderBy, /* The ORDER BY values to match against columns */
57.1430 + int iTable, /* Insert this value in iTable */
57.1431 + int mustComplete /* If TRUE all ORDER BYs must match */
57.1432 +){
57.1433 + int nErr = 0;
57.1434 + int i, j;
57.1435 + ExprList *pEList;
57.1436 +
57.1437 + if( pSelect==0 || pOrderBy==0 ) return 1;
57.1438 + if( mustComplete ){
57.1439 + for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
57.1440 + }
57.1441 + if( prepSelectStmt(pParse, pSelect) ){
57.1442 + return 1;
57.1443 + }
57.1444 + if( pSelect->pPrior ){
57.1445 + if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
57.1446 + return 1;
57.1447 + }
57.1448 + }
57.1449 + pEList = pSelect->pEList;
57.1450 + for(i=0; i<pOrderBy->nExpr; i++){
57.1451 + struct ExprList_item *pItem;
57.1452 + Expr *pE = pOrderBy->a[i].pExpr;
57.1453 + int iCol = -1;
57.1454 + char *zLabel;
57.1455 +
57.1456 + if( pOrderBy->a[i].done ) continue;
57.1457 + if( sqlite3ExprIsInteger(pE, &iCol) ){
57.1458 + if( iCol<=0 || iCol>pEList->nExpr ){
57.1459 + sqlite3ErrorMsg(pParse,
57.1460 + "ORDER BY position %d should be between 1 and %d",
57.1461 + iCol, pEList->nExpr);
57.1462 + nErr++;
57.1463 + break;
57.1464 + }
57.1465 + if( !mustComplete ) continue;
57.1466 + iCol--;
57.1467 + }
57.1468 + if( iCol<0 && (zLabel = sqlite3NameFromToken(&pE->token))!=0 ){
57.1469 + for(j=0, pItem=pEList->a; j<pEList->nExpr; j++, pItem++){
57.1470 + char *zName;
57.1471 + int isMatch;
57.1472 + if( pItem->zName ){
57.1473 + zName = sqlite3StrDup(pItem->zName);
57.1474 + }else{
57.1475 + zName = sqlite3NameFromToken(&pItem->pExpr->token);
57.1476 + }
57.1477 + isMatch = zName && sqlite3StrICmp(zName, zLabel)==0;
57.1478 + sqliteFree(zName);
57.1479 + if( isMatch ){
57.1480 + iCol = j;
57.1481 + break;
57.1482 + }
57.1483 + }
57.1484 + sqliteFree(zLabel);
57.1485 + }
57.1486 + if( iCol>=0 ){
57.1487 + pE->op = TK_COLUMN;
57.1488 + pE->iColumn = iCol;
57.1489 + pE->iTable = iTable;
57.1490 + pE->iAgg = -1;
57.1491 + pOrderBy->a[i].done = 1;
57.1492 + }else if( mustComplete ){
57.1493 + sqlite3ErrorMsg(pParse,
57.1494 + "ORDER BY term number %d does not match any result column", i+1);
57.1495 + nErr++;
57.1496 + break;
57.1497 + }
57.1498 + }
57.1499 + return nErr;
57.1500 +}
57.1501 +#endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
57.1502 +
57.1503 +/*
57.1504 +** Get a VDBE for the given parser context. Create a new one if necessary.
57.1505 +** If an error occurs, return NULL and leave a message in pParse.
57.1506 +*/
57.1507 +Vdbe *sqlite3GetVdbe(Parse *pParse){
57.1508 + Vdbe *v = pParse->pVdbe;
57.1509 + if( v==0 ){
57.1510 + v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
57.1511 + }
57.1512 + return v;
57.1513 +}
57.1514 +
57.1515 +
57.1516 +/*
57.1517 +** Compute the iLimit and iOffset fields of the SELECT based on the
57.1518 +** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
57.1519 +** that appear in the original SQL statement after the LIMIT and OFFSET
57.1520 +** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
57.1521 +** are the integer memory register numbers for counters used to compute
57.1522 +** the limit and offset. If there is no limit and/or offset, then
57.1523 +** iLimit and iOffset are negative.
57.1524 +**
57.1525 +** This routine changes the values of iLimit and iOffset only if
57.1526 +** a limit or offset is defined by pLimit and pOffset. iLimit and
57.1527 +** iOffset should have been preset to appropriate default values
57.1528 +** (usually but not always -1) prior to calling this routine.
57.1529 +** Only if pLimit!=0 or pOffset!=0 do the limit registers get
57.1530 +** redefined. The UNION ALL operator uses this property to force
57.1531 +** the reuse of the same limit and offset registers across multiple
57.1532 +** SELECT statements.
57.1533 +*/
57.1534 +static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
57.1535 + Vdbe *v = 0;
57.1536 + int iLimit = 0;
57.1537 + int iOffset;
57.1538 + int addr1, addr2;
57.1539 +
57.1540 + /*
57.1541 + ** "LIMIT -1" always shows all rows. There is some
57.1542 + ** contraversy about what the correct behavior should be.
57.1543 + ** The current implementation interprets "LIMIT 0" to mean
57.1544 + ** no rows.
57.1545 + */
57.1546 + if( p->pLimit ){
57.1547 + p->iLimit = iLimit = pParse->nMem;
57.1548 + pParse->nMem += 2;
57.1549 + v = sqlite3GetVdbe(pParse);
57.1550 + if( v==0 ) return;
57.1551 + sqlite3ExprCode(pParse, p->pLimit);
57.1552 + sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
57.1553 + sqlite3VdbeAddOp(v, OP_MemStore, iLimit, 1);
57.1554 + VdbeComment((v, "# LIMIT counter"));
57.1555 + sqlite3VdbeAddOp(v, OP_IfMemZero, iLimit, iBreak);
57.1556 + sqlite3VdbeAddOp(v, OP_MemLoad, iLimit, 0);
57.1557 + }
57.1558 + if( p->pOffset ){
57.1559 + p->iOffset = iOffset = pParse->nMem++;
57.1560 + v = sqlite3GetVdbe(pParse);
57.1561 + if( v==0 ) return;
57.1562 + sqlite3ExprCode(pParse, p->pOffset);
57.1563 + sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
57.1564 + sqlite3VdbeAddOp(v, OP_MemStore, iOffset, p->pLimit==0);
57.1565 + VdbeComment((v, "# OFFSET counter"));
57.1566 + addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iOffset, 0);
57.1567 + sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
57.1568 + sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
57.1569 + sqlite3VdbeJumpHere(v, addr1);
57.1570 + if( p->pLimit ){
57.1571 + sqlite3VdbeAddOp(v, OP_Add, 0, 0);
57.1572 + }
57.1573 + }
57.1574 + if( p->pLimit ){
57.1575 + addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iLimit, 0);
57.1576 + sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
57.1577 + sqlite3VdbeAddOp(v, OP_MemInt, -1, iLimit+1);
57.1578 + addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
57.1579 + sqlite3VdbeJumpHere(v, addr1);
57.1580 + sqlite3VdbeAddOp(v, OP_MemStore, iLimit+1, 1);
57.1581 + VdbeComment((v, "# LIMIT+OFFSET"));
57.1582 + sqlite3VdbeJumpHere(v, addr2);
57.1583 + }
57.1584 +}
57.1585 +
57.1586 +/*
57.1587 +** Allocate a virtual index to use for sorting.
57.1588 +*/
57.1589 +static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
57.1590 + if( pOrderBy ){
57.1591 + int addr;
57.1592 + assert( pOrderBy->iECursor==0 );
57.1593 + pOrderBy->iECursor = pParse->nTab++;
57.1594 + addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenEphemeral,
57.1595 + pOrderBy->iECursor, pOrderBy->nExpr+1);
57.1596 + assert( p->addrOpenEphm[2] == -1 );
57.1597 + p->addrOpenEphm[2] = addr;
57.1598 + }
57.1599 +}
57.1600 +
57.1601 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
57.1602 +/*
57.1603 +** Return the appropriate collating sequence for the iCol-th column of
57.1604 +** the result set for the compound-select statement "p". Return NULL if
57.1605 +** the column has no default collating sequence.
57.1606 +**
57.1607 +** The collating sequence for the compound select is taken from the
57.1608 +** left-most term of the select that has a collating sequence.
57.1609 +*/
57.1610 +static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
57.1611 + CollSeq *pRet;
57.1612 + if( p->pPrior ){
57.1613 + pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
57.1614 + }else{
57.1615 + pRet = 0;
57.1616 + }
57.1617 + if( pRet==0 ){
57.1618 + pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
57.1619 + }
57.1620 + return pRet;
57.1621 +}
57.1622 +#endif /* SQLITE_OMIT_COMPOUND_SELECT */
57.1623 +
57.1624 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
57.1625 +/*
57.1626 +** This routine is called to process a query that is really the union
57.1627 +** or intersection of two or more separate queries.
57.1628 +**
57.1629 +** "p" points to the right-most of the two queries. the query on the
57.1630 +** left is p->pPrior. The left query could also be a compound query
57.1631 +** in which case this routine will be called recursively.
57.1632 +**
57.1633 +** The results of the total query are to be written into a destination
57.1634 +** of type eDest with parameter iParm.
57.1635 +**
57.1636 +** Example 1: Consider a three-way compound SQL statement.
57.1637 +**
57.1638 +** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
57.1639 +**
57.1640 +** This statement is parsed up as follows:
57.1641 +**
57.1642 +** SELECT c FROM t3
57.1643 +** |
57.1644 +** `-----> SELECT b FROM t2
57.1645 +** |
57.1646 +** `------> SELECT a FROM t1
57.1647 +**
57.1648 +** The arrows in the diagram above represent the Select.pPrior pointer.
57.1649 +** So if this routine is called with p equal to the t3 query, then
57.1650 +** pPrior will be the t2 query. p->op will be TK_UNION in this case.
57.1651 +**
57.1652 +** Notice that because of the way SQLite parses compound SELECTs, the
57.1653 +** individual selects always group from left to right.
57.1654 +*/
57.1655 +static int multiSelect(
57.1656 + Parse *pParse, /* Parsing context */
57.1657 + Select *p, /* The right-most of SELECTs to be coded */
57.1658 + int eDest, /* \___ Store query results as specified */
57.1659 + int iParm, /* / by these two parameters. */
57.1660 + char *aff /* If eDest is SRT_Union, the affinity string */
57.1661 +){
57.1662 + int rc = SQLITE_OK; /* Success code from a subroutine */
57.1663 + Select *pPrior; /* Another SELECT immediately to our left */
57.1664 + Vdbe *v; /* Generate code to this VDBE */
57.1665 + int nCol; /* Number of columns in the result set */
57.1666 + ExprList *pOrderBy; /* The ORDER BY clause on p */
57.1667 + int aSetP2[2]; /* Set P2 value of these op to number of columns */
57.1668 + int nSetP2 = 0; /* Number of slots in aSetP2[] used */
57.1669 +
57.1670 + /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
57.1671 + ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
57.1672 + */
57.1673 + if( p==0 || p->pPrior==0 ){
57.1674 + rc = 1;
57.1675 + goto multi_select_end;
57.1676 + }
57.1677 + pPrior = p->pPrior;
57.1678 + assert( pPrior->pRightmost!=pPrior );
57.1679 + assert( pPrior->pRightmost==p->pRightmost );
57.1680 + if( pPrior->pOrderBy ){
57.1681 + sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
57.1682 + selectOpName(p->op));
57.1683 + rc = 1;
57.1684 + goto multi_select_end;
57.1685 + }
57.1686 + if( pPrior->pLimit ){
57.1687 + sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
57.1688 + selectOpName(p->op));
57.1689 + rc = 1;
57.1690 + goto multi_select_end;
57.1691 + }
57.1692 +
57.1693 + /* Make sure we have a valid query engine. If not, create a new one.
57.1694 + */
57.1695 + v = sqlite3GetVdbe(pParse);
57.1696 + if( v==0 ){
57.1697 + rc = 1;
57.1698 + goto multi_select_end;
57.1699 + }
57.1700 +
57.1701 + /* Create the destination temporary table if necessary
57.1702 + */
57.1703 + if( eDest==SRT_EphemTab ){
57.1704 + assert( p->pEList );
57.1705 + assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
57.1706 + aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 0);
57.1707 + eDest = SRT_Table;
57.1708 + }
57.1709 +
57.1710 + /* Generate code for the left and right SELECT statements.
57.1711 + */
57.1712 + pOrderBy = p->pOrderBy;
57.1713 + switch( p->op ){
57.1714 + case TK_ALL: {
57.1715 + if( pOrderBy==0 ){
57.1716 + int addr = 0;
57.1717 + assert( !pPrior->pLimit );
57.1718 + pPrior->pLimit = p->pLimit;
57.1719 + pPrior->pOffset = p->pOffset;
57.1720 + rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
57.1721 + p->pLimit = 0;
57.1722 + p->pOffset = 0;
57.1723 + if( rc ){
57.1724 + goto multi_select_end;
57.1725 + }
57.1726 + p->pPrior = 0;
57.1727 + p->iLimit = pPrior->iLimit;
57.1728 + p->iOffset = pPrior->iOffset;
57.1729 + if( p->iLimit>=0 ){
57.1730 + addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0);
57.1731 + VdbeComment((v, "# Jump ahead if LIMIT reached"));
57.1732 + }
57.1733 + rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
57.1734 + p->pPrior = pPrior;
57.1735 + if( rc ){
57.1736 + goto multi_select_end;
57.1737 + }
57.1738 + if( addr ){
57.1739 + sqlite3VdbeJumpHere(v, addr);
57.1740 + }
57.1741 + break;
57.1742 + }
57.1743 + /* For UNION ALL ... ORDER BY fall through to the next case */
57.1744 + }
57.1745 + case TK_EXCEPT:
57.1746 + case TK_UNION: {
57.1747 + int unionTab; /* Cursor number of the temporary table holding result */
57.1748 + int op = 0; /* One of the SRT_ operations to apply to self */
57.1749 + int priorOp; /* The SRT_ operation to apply to prior selects */
57.1750 + Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
57.1751 + int addr;
57.1752 +
57.1753 + priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
57.1754 + if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
57.1755 + /* We can reuse a temporary table generated by a SELECT to our
57.1756 + ** right.
57.1757 + */
57.1758 + unionTab = iParm;
57.1759 + }else{
57.1760 + /* We will need to create our own temporary table to hold the
57.1761 + ** intermediate results.
57.1762 + */
57.1763 + unionTab = pParse->nTab++;
57.1764 + if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){
57.1765 + rc = 1;
57.1766 + goto multi_select_end;
57.1767 + }
57.1768 + addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, unionTab, 0);
57.1769 + if( priorOp==SRT_Table ){
57.1770 + assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
57.1771 + aSetP2[nSetP2++] = addr;
57.1772 + }else{
57.1773 + assert( p->addrOpenEphm[0] == -1 );
57.1774 + p->addrOpenEphm[0] = addr;
57.1775 + p->pRightmost->usesEphm = 1;
57.1776 + }
57.1777 + createSortingIndex(pParse, p, pOrderBy);
57.1778 + assert( p->pEList );
57.1779 + }
57.1780 +
57.1781 + /* Code the SELECT statements to our left
57.1782 + */
57.1783 + assert( !pPrior->pOrderBy );
57.1784 + rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
57.1785 + if( rc ){
57.1786 + goto multi_select_end;
57.1787 + }
57.1788 +
57.1789 + /* Code the current SELECT statement
57.1790 + */
57.1791 + switch( p->op ){
57.1792 + case TK_EXCEPT: op = SRT_Except; break;
57.1793 + case TK_UNION: op = SRT_Union; break;
57.1794 + case TK_ALL: op = SRT_Table; break;
57.1795 + }
57.1796 + p->pPrior = 0;
57.1797 + p->pOrderBy = 0;
57.1798 + p->disallowOrderBy = pOrderBy!=0;
57.1799 + pLimit = p->pLimit;
57.1800 + p->pLimit = 0;
57.1801 + pOffset = p->pOffset;
57.1802 + p->pOffset = 0;
57.1803 + rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
57.1804 + /* Query flattening in sqlite3Select() might refill p->pOrderBy.
57.1805 + ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
57.1806 + sqlite3ExprListDelete(p->pOrderBy);
57.1807 + p->pPrior = pPrior;
57.1808 + p->pOrderBy = pOrderBy;
57.1809 + sqlite3ExprDelete(p->pLimit);
57.1810 + p->pLimit = pLimit;
57.1811 + p->pOffset = pOffset;
57.1812 + p->iLimit = -1;
57.1813 + p->iOffset = -1;
57.1814 + if( rc ){
57.1815 + goto multi_select_end;
57.1816 + }
57.1817 +
57.1818 +
57.1819 + /* Convert the data in the temporary table into whatever form
57.1820 + ** it is that we currently need.
57.1821 + */
57.1822 + if( eDest!=priorOp || unionTab!=iParm ){
57.1823 + int iCont, iBreak, iStart;
57.1824 + assert( p->pEList );
57.1825 + if( eDest==SRT_Callback ){
57.1826 + Select *pFirst = p;
57.1827 + while( pFirst->pPrior ) pFirst = pFirst->pPrior;
57.1828 + generateColumnNames(pParse, 0, pFirst->pEList);
57.1829 + }
57.1830 + iBreak = sqlite3VdbeMakeLabel(v);
57.1831 + iCont = sqlite3VdbeMakeLabel(v);
57.1832 + computeLimitRegisters(pParse, p, iBreak);
57.1833 + sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
57.1834 + iStart = sqlite3VdbeCurrentAddr(v);
57.1835 + rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
57.1836 + pOrderBy, -1, eDest, iParm,
57.1837 + iCont, iBreak, 0);
57.1838 + if( rc ){
57.1839 + rc = 1;
57.1840 + goto multi_select_end;
57.1841 + }
57.1842 + sqlite3VdbeResolveLabel(v, iCont);
57.1843 + sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
57.1844 + sqlite3VdbeResolveLabel(v, iBreak);
57.1845 + sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
57.1846 + }
57.1847 + break;
57.1848 + }
57.1849 + case TK_INTERSECT: {
57.1850 + int tab1, tab2;
57.1851 + int iCont, iBreak, iStart;
57.1852 + Expr *pLimit, *pOffset;
57.1853 + int addr;
57.1854 +
57.1855 + /* INTERSECT is different from the others since it requires
57.1856 + ** two temporary tables. Hence it has its own case. Begin
57.1857 + ** by allocating the tables we will need.
57.1858 + */
57.1859 + tab1 = pParse->nTab++;
57.1860 + tab2 = pParse->nTab++;
57.1861 + if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){
57.1862 + rc = 1;
57.1863 + goto multi_select_end;
57.1864 + }
57.1865 + createSortingIndex(pParse, p, pOrderBy);
57.1866 +
57.1867 + addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab1, 0);
57.1868 + assert( p->addrOpenEphm[0] == -1 );
57.1869 + p->addrOpenEphm[0] = addr;
57.1870 + p->pRightmost->usesEphm = 1;
57.1871 + assert( p->pEList );
57.1872 +
57.1873 + /* Code the SELECTs to our left into temporary table "tab1".
57.1874 + */
57.1875 + rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
57.1876 + if( rc ){
57.1877 + goto multi_select_end;
57.1878 + }
57.1879 +
57.1880 + /* Code the current SELECT into temporary table "tab2"
57.1881 + */
57.1882 + addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab2, 0);
57.1883 + assert( p->addrOpenEphm[1] == -1 );
57.1884 + p->addrOpenEphm[1] = addr;
57.1885 + p->pPrior = 0;
57.1886 + pLimit = p->pLimit;
57.1887 + p->pLimit = 0;
57.1888 + pOffset = p->pOffset;
57.1889 + p->pOffset = 0;
57.1890 + rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
57.1891 + p->pPrior = pPrior;
57.1892 + sqlite3ExprDelete(p->pLimit);
57.1893 + p->pLimit = pLimit;
57.1894 + p->pOffset = pOffset;
57.1895 + if( rc ){
57.1896 + goto multi_select_end;
57.1897 + }
57.1898 +
57.1899 + /* Generate code to take the intersection of the two temporary
57.1900 + ** tables.
57.1901 + */
57.1902 + assert( p->pEList );
57.1903 + if( eDest==SRT_Callback ){
57.1904 + Select *pFirst = p;
57.1905 + while( pFirst->pPrior ) pFirst = pFirst->pPrior;
57.1906 + generateColumnNames(pParse, 0, pFirst->pEList);
57.1907 + }
57.1908 + iBreak = sqlite3VdbeMakeLabel(v);
57.1909 + iCont = sqlite3VdbeMakeLabel(v);
57.1910 + computeLimitRegisters(pParse, p, iBreak);
57.1911 + sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
57.1912 + iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
57.1913 + sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
57.1914 + rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
57.1915 + pOrderBy, -1, eDest, iParm,
57.1916 + iCont, iBreak, 0);
57.1917 + if( rc ){
57.1918 + rc = 1;
57.1919 + goto multi_select_end;
57.1920 + }
57.1921 + sqlite3VdbeResolveLabel(v, iCont);
57.1922 + sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
57.1923 + sqlite3VdbeResolveLabel(v, iBreak);
57.1924 + sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
57.1925 + sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
57.1926 + break;
57.1927 + }
57.1928 + }
57.1929 +
57.1930 + /* Make sure all SELECTs in the statement have the same number of elements
57.1931 + ** in their result sets.
57.1932 + */
57.1933 + assert( p->pEList && pPrior->pEList );
57.1934 + if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
57.1935 + sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
57.1936 + " do not have the same number of result columns", selectOpName(p->op));
57.1937 + rc = 1;
57.1938 + goto multi_select_end;
57.1939 + }
57.1940 +
57.1941 + /* Set the number of columns in temporary tables
57.1942 + */
57.1943 + nCol = p->pEList->nExpr;
57.1944 + while( nSetP2 ){
57.1945 + sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
57.1946 + }
57.1947 +
57.1948 + /* Compute collating sequences used by either the ORDER BY clause or
57.1949 + ** by any temporary tables needed to implement the compound select.
57.1950 + ** Attach the KeyInfo structure to all temporary tables. Invoke the
57.1951 + ** ORDER BY processing if there is an ORDER BY clause.
57.1952 + **
57.1953 + ** This section is run by the right-most SELECT statement only.
57.1954 + ** SELECT statements to the left always skip this part. The right-most
57.1955 + ** SELECT might also skip this part if it has no ORDER BY clause and
57.1956 + ** no temp tables are required.
57.1957 + */
57.1958 + if( pOrderBy || p->usesEphm ){
57.1959 + int i; /* Loop counter */
57.1960 + KeyInfo *pKeyInfo; /* Collating sequence for the result set */
57.1961 + Select *pLoop; /* For looping through SELECT statements */
57.1962 + int nKeyCol; /* Number of entries in pKeyInfo->aCol[] */
57.1963 + CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
57.1964 + CollSeq **aCopy; /* A copy of pKeyInfo->aColl[] */
57.1965 +
57.1966 + assert( p->pRightmost==p );
57.1967 + nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0);
57.1968 + pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1));
57.1969 + if( !pKeyInfo ){
57.1970 + rc = SQLITE_NOMEM;
57.1971 + goto multi_select_end;
57.1972 + }
57.1973 +
57.1974 + pKeyInfo->enc = ENC(pParse->db);
57.1975 + pKeyInfo->nField = nCol;
57.1976 +
57.1977 + for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
57.1978 + *apColl = multiSelectCollSeq(pParse, p, i);
57.1979 + if( 0==*apColl ){
57.1980 + *apColl = pParse->db->pDfltColl;
57.1981 + }
57.1982 + }
57.1983 +
57.1984 + for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
57.1985 + for(i=0; i<2; i++){
57.1986 + int addr = pLoop->addrOpenEphm[i];
57.1987 + if( addr<0 ){
57.1988 + /* If [0] is unused then [1] is also unused. So we can
57.1989 + ** always safely abort as soon as the first unused slot is found */
57.1990 + assert( pLoop->addrOpenEphm[1]<0 );
57.1991 + break;
57.1992 + }
57.1993 + sqlite3VdbeChangeP2(v, addr, nCol);
57.1994 + sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
57.1995 + pLoop->addrOpenEphm[i] = -1;
57.1996 + }
57.1997 + }
57.1998 +
57.1999 + if( pOrderBy ){
57.2000 + struct ExprList_item *pOTerm = pOrderBy->a;
57.2001 + int nOrderByExpr = pOrderBy->nExpr;
57.2002 + int addr;
57.2003 + u8 *pSortOrder;
57.2004 +
57.2005 + /* Reuse the same pKeyInfo for the ORDER BY as was used above for
57.2006 + ** the compound select statements. Except we have to change out the
57.2007 + ** pKeyInfo->aColl[] values. Some of the aColl[] values will be
57.2008 + ** reused when constructing the pKeyInfo for the ORDER BY, so make
57.2009 + ** a copy. Sufficient space to hold both the nCol entries for
57.2010 + ** the compound select and the nOrderbyExpr entries for the ORDER BY
57.2011 + ** was allocated above. But we need to move the compound select
57.2012 + ** entries out of the way before constructing the ORDER BY entries.
57.2013 + ** Move the compound select entries into aCopy[] where they can be
57.2014 + ** accessed and reused when constructing the ORDER BY entries.
57.2015 + ** Because nCol might be greater than or less than nOrderByExpr
57.2016 + ** we have to use memmove() when doing the copy.
57.2017 + */
57.2018 + aCopy = &pKeyInfo->aColl[nOrderByExpr];
57.2019 + pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
57.2020 + memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
57.2021 +
57.2022 + apColl = pKeyInfo->aColl;
57.2023 + for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
57.2024 + Expr *pExpr = pOTerm->pExpr;
57.2025 + if( (pExpr->flags & EP_ExpCollate) ){
57.2026 + assert( pExpr->pColl!=0 );
57.2027 + *apColl = pExpr->pColl;
57.2028 + }else{
57.2029 + *apColl = aCopy[pExpr->iColumn];
57.2030 + }
57.2031 + *pSortOrder = pOTerm->sortOrder;
57.2032 + }
57.2033 + assert( p->pRightmost==p );
57.2034 + assert( p->addrOpenEphm[2]>=0 );
57.2035 + addr = p->addrOpenEphm[2];
57.2036 + sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2);
57.2037 + pKeyInfo->nField = nOrderByExpr;
57.2038 + sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
57.2039 + pKeyInfo = 0;
57.2040 + generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
57.2041 + }
57.2042 +
57.2043 + sqliteFree(pKeyInfo);
57.2044 + }
57.2045 +
57.2046 +multi_select_end:
57.2047 + return rc;
57.2048 +}
57.2049 +#endif /* SQLITE_OMIT_COMPOUND_SELECT */
57.2050 +
57.2051 +#ifndef SQLITE_OMIT_VIEW
57.2052 +/*
57.2053 +** Scan through the expression pExpr. Replace every reference to
57.2054 +** a column in table number iTable with a copy of the iColumn-th
57.2055 +** entry in pEList. (But leave references to the ROWID column
57.2056 +** unchanged.)
57.2057 +**
57.2058 +** This routine is part of the flattening procedure. A subquery
57.2059 +** whose result set is defined by pEList appears as entry in the
57.2060 +** FROM clause of a SELECT such that the VDBE cursor assigned to that
57.2061 +** FORM clause entry is iTable. This routine make the necessary
57.2062 +** changes to pExpr so that it refers directly to the source table
57.2063 +** of the subquery rather the result set of the subquery.
57.2064 +*/
57.2065 +static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
57.2066 +static void substSelect(Select *, int, ExprList *); /* Forward Decl */
57.2067 +static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
57.2068 + if( pExpr==0 ) return;
57.2069 + if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
57.2070 + if( pExpr->iColumn<0 ){
57.2071 + pExpr->op = TK_NULL;
57.2072 + }else{
57.2073 + Expr *pNew;
57.2074 + assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
57.2075 + assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
57.2076 + pNew = pEList->a[pExpr->iColumn].pExpr;
57.2077 + assert( pNew!=0 );
57.2078 + pExpr->op = pNew->op;
57.2079 + assert( pExpr->pLeft==0 );
57.2080 + pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
57.2081 + assert( pExpr->pRight==0 );
57.2082 + pExpr->pRight = sqlite3ExprDup(pNew->pRight);
57.2083 + assert( pExpr->pList==0 );
57.2084 + pExpr->pList = sqlite3ExprListDup(pNew->pList);
57.2085 + pExpr->iTable = pNew->iTable;
57.2086 + pExpr->pTab = pNew->pTab;
57.2087 + pExpr->iColumn = pNew->iColumn;
57.2088 + pExpr->iAgg = pNew->iAgg;
57.2089 + sqlite3TokenCopy(&pExpr->token, &pNew->token);
57.2090 + sqlite3TokenCopy(&pExpr->span, &pNew->span);
57.2091 + pExpr->pSelect = sqlite3SelectDup(pNew->pSelect);
57.2092 + pExpr->flags = pNew->flags;
57.2093 + }
57.2094 + }else{
57.2095 + substExpr(pExpr->pLeft, iTable, pEList);
57.2096 + substExpr(pExpr->pRight, iTable, pEList);
57.2097 + substSelect(pExpr->pSelect, iTable, pEList);
57.2098 + substExprList(pExpr->pList, iTable, pEList);
57.2099 + }
57.2100 +}
57.2101 +static void substExprList(ExprList *pList, int iTable, ExprList *pEList){
57.2102 + int i;
57.2103 + if( pList==0 ) return;
57.2104 + for(i=0; i<pList->nExpr; i++){
57.2105 + substExpr(pList->a[i].pExpr, iTable, pEList);
57.2106 + }
57.2107 +}
57.2108 +static void substSelect(Select *p, int iTable, ExprList *pEList){
57.2109 + if( !p ) return;
57.2110 + substExprList(p->pEList, iTable, pEList);
57.2111 + substExprList(p->pGroupBy, iTable, pEList);
57.2112 + substExprList(p->pOrderBy, iTable, pEList);
57.2113 + substExpr(p->pHaving, iTable, pEList);
57.2114 + substExpr(p->pWhere, iTable, pEList);
57.2115 + substSelect(p->pPrior, iTable, pEList);
57.2116 +}
57.2117 +#endif /* !defined(SQLITE_OMIT_VIEW) */
57.2118 +
57.2119 +#ifndef SQLITE_OMIT_VIEW
57.2120 +/*
57.2121 +** This routine attempts to flatten subqueries in order to speed
57.2122 +** execution. It returns 1 if it makes changes and 0 if no flattening
57.2123 +** occurs.
57.2124 +**
57.2125 +** To understand the concept of flattening, consider the following
57.2126 +** query:
57.2127 +**
57.2128 +** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
57.2129 +**
57.2130 +** The default way of implementing this query is to execute the
57.2131 +** subquery first and store the results in a temporary table, then
57.2132 +** run the outer query on that temporary table. This requires two
57.2133 +** passes over the data. Furthermore, because the temporary table
57.2134 +** has no indices, the WHERE clause on the outer query cannot be
57.2135 +** optimized.
57.2136 +**
57.2137 +** This routine attempts to rewrite queries such as the above into
57.2138 +** a single flat select, like this:
57.2139 +**
57.2140 +** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
57.2141 +**
57.2142 +** The code generated for this simpification gives the same result
57.2143 +** but only has to scan the data once. And because indices might
57.2144 +** exist on the table t1, a complete scan of the data might be
57.2145 +** avoided.
57.2146 +**
57.2147 +** Flattening is only attempted if all of the following are true:
57.2148 +**
57.2149 +** (1) The subquery and the outer query do not both use aggregates.
57.2150 +**
57.2151 +** (2) The subquery is not an aggregate or the outer query is not a join.
57.2152 +**
57.2153 +** (3) The subquery is not the right operand of a left outer join, or
57.2154 +** the subquery is not itself a join. (Ticket #306)
57.2155 +**
57.2156 +** (4) The subquery is not DISTINCT or the outer query is not a join.
57.2157 +**
57.2158 +** (5) The subquery is not DISTINCT or the outer query does not use
57.2159 +** aggregates.
57.2160 +**
57.2161 +** (6) The subquery does not use aggregates or the outer query is not
57.2162 +** DISTINCT.
57.2163 +**
57.2164 +** (7) The subquery has a FROM clause.
57.2165 +**
57.2166 +** (8) The subquery does not use LIMIT or the outer query is not a join.
57.2167 +**
57.2168 +** (9) The subquery does not use LIMIT or the outer query does not use
57.2169 +** aggregates.
57.2170 +**
57.2171 +** (10) The subquery does not use aggregates or the outer query does not
57.2172 +** use LIMIT.
57.2173 +**
57.2174 +** (11) The subquery and the outer query do not both have ORDER BY clauses.
57.2175 +**
57.2176 +** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
57.2177 +** subquery has no WHERE clause. (added by ticket #350)
57.2178 +**
57.2179 +** (13) The subquery and outer query do not both use LIMIT
57.2180 +**
57.2181 +** (14) The subquery does not use OFFSET
57.2182 +**
57.2183 +** (15) The outer query is not part of a compound select or the
57.2184 +** subquery does not have both an ORDER BY and a LIMIT clause.
57.2185 +** (See ticket #2339)
57.2186 +**
57.2187 +** In this routine, the "p" parameter is a pointer to the outer query.
57.2188 +** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
57.2189 +** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
57.2190 +**
57.2191 +** If flattening is not attempted, this routine is a no-op and returns 0.
57.2192 +** If flattening is attempted this routine returns 1.
57.2193 +**
57.2194 +** All of the expression analysis must occur on both the outer query and
57.2195 +** the subquery before this routine runs.
57.2196 +*/
57.2197 +static int flattenSubquery(
57.2198 + Select *p, /* The parent or outer SELECT statement */
57.2199 + int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
57.2200 + int isAgg, /* True if outer SELECT uses aggregate functions */
57.2201 + int subqueryIsAgg /* True if the subquery uses aggregate functions */
57.2202 +){
57.2203 + Select *pSub; /* The inner query or "subquery" */
57.2204 + SrcList *pSrc; /* The FROM clause of the outer query */
57.2205 + SrcList *pSubSrc; /* The FROM clause of the subquery */
57.2206 + ExprList *pList; /* The result set of the outer query */
57.2207 + int iParent; /* VDBE cursor number of the pSub result set temp table */
57.2208 + int i; /* Loop counter */
57.2209 + Expr *pWhere; /* The WHERE clause */
57.2210 + struct SrcList_item *pSubitem; /* The subquery */
57.2211 +
57.2212 + /* Check to see if flattening is permitted. Return 0 if not.
57.2213 + */
57.2214 + if( p==0 ) return 0;
57.2215 + pSrc = p->pSrc;
57.2216 + assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
57.2217 + pSubitem = &pSrc->a[iFrom];
57.2218 + pSub = pSubitem->pSelect;
57.2219 + assert( pSub!=0 );
57.2220 + if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
57.2221 + if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
57.2222 + pSubSrc = pSub->pSrc;
57.2223 + assert( pSubSrc );
57.2224 + /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
57.2225 + ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
57.2226 + ** because they could be computed at compile-time. But when LIMIT and OFFSET
57.2227 + ** became arbitrary expressions, we were forced to add restrictions (13)
57.2228 + ** and (14). */
57.2229 + if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
57.2230 + if( pSub->pOffset ) return 0; /* Restriction (14) */
57.2231 + if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
57.2232 + return 0; /* Restriction (15) */
57.2233 + }
57.2234 + if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
57.2235 + if( (pSub->isDistinct || pSub->pLimit)
57.2236 + && (pSrc->nSrc>1 || isAgg) ){ /* Restrictions (4)(5)(8)(9) */
57.2237 + return 0;
57.2238 + }
57.2239 + if( p->isDistinct && subqueryIsAgg ) return 0; /* Restriction (6) */
57.2240 + if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){
57.2241 + return 0; /* Restriction (11) */
57.2242 + }
57.2243 +
57.2244 + /* Restriction 3: If the subquery is a join, make sure the subquery is
57.2245 + ** not used as the right operand of an outer join. Examples of why this
57.2246 + ** is not allowed:
57.2247 + **
57.2248 + ** t1 LEFT OUTER JOIN (t2 JOIN t3)
57.2249 + **
57.2250 + ** If we flatten the above, we would get
57.2251 + **
57.2252 + ** (t1 LEFT OUTER JOIN t2) JOIN t3
57.2253 + **
57.2254 + ** which is not at all the same thing.
57.2255 + */
57.2256 + if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){
57.2257 + return 0;
57.2258 + }
57.2259 +
57.2260 + /* Restriction 12: If the subquery is the right operand of a left outer
57.2261 + ** join, make sure the subquery has no WHERE clause.
57.2262 + ** An examples of why this is not allowed:
57.2263 + **
57.2264 + ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
57.2265 + **
57.2266 + ** If we flatten the above, we would get
57.2267 + **
57.2268 + ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
57.2269 + **
57.2270 + ** But the t2.x>0 test will always fail on a NULL row of t2, which
57.2271 + ** effectively converts the OUTER JOIN into an INNER JOIN.
57.2272 + */
57.2273 + if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){
57.2274 + return 0;
57.2275 + }
57.2276 +
57.2277 + /* If we reach this point, it means flattening is permitted for the
57.2278 + ** iFrom-th entry of the FROM clause in the outer query.
57.2279 + */
57.2280 +
57.2281 + /* Move all of the FROM elements of the subquery into the
57.2282 + ** the FROM clause of the outer query. Before doing this, remember
57.2283 + ** the cursor number for the original outer query FROM element in
57.2284 + ** iParent. The iParent cursor will never be used. Subsequent code
57.2285 + ** will scan expressions looking for iParent references and replace
57.2286 + ** those references with expressions that resolve to the subquery FROM
57.2287 + ** elements we are now copying in.
57.2288 + */
57.2289 + iParent = pSubitem->iCursor;
57.2290 + {
57.2291 + int nSubSrc = pSubSrc->nSrc;
57.2292 + int jointype = pSubitem->jointype;
57.2293 +
57.2294 + sqlite3DeleteTable(pSubitem->pTab);
57.2295 + sqliteFree(pSubitem->zDatabase);
57.2296 + sqliteFree(pSubitem->zName);
57.2297 + sqliteFree(pSubitem->zAlias);
57.2298 + if( nSubSrc>1 ){
57.2299 + int extra = nSubSrc - 1;
57.2300 + for(i=1; i<nSubSrc; i++){
57.2301 + pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
57.2302 + }
57.2303 + p->pSrc = pSrc;
57.2304 + for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
57.2305 + pSrc->a[i] = pSrc->a[i-extra];
57.2306 + }
57.2307 + }
57.2308 + for(i=0; i<nSubSrc; i++){
57.2309 + pSrc->a[i+iFrom] = pSubSrc->a[i];
57.2310 + memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
57.2311 + }
57.2312 + pSrc->a[iFrom].jointype = jointype;
57.2313 + }
57.2314 +
57.2315 + /* Now begin substituting subquery result set expressions for
57.2316 + ** references to the iParent in the outer query.
57.2317 + **
57.2318 + ** Example:
57.2319 + **
57.2320 + ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
57.2321 + ** \ \_____________ subquery __________/ /
57.2322 + ** \_____________________ outer query ______________________________/
57.2323 + **
57.2324 + ** We look at every expression in the outer query and every place we see
57.2325 + ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
57.2326 + */
57.2327 + pList = p->pEList;
57.2328 + for(i=0; i<pList->nExpr; i++){
57.2329 + Expr *pExpr;
57.2330 + if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
57.2331 + pList->a[i].zName = sqliteStrNDup((char*)pExpr->span.z, pExpr->span.n);
57.2332 + }
57.2333 + }
57.2334 + substExprList(p->pEList, iParent, pSub->pEList);
57.2335 + if( isAgg ){
57.2336 + substExprList(p->pGroupBy, iParent, pSub->pEList);
57.2337 + substExpr(p->pHaving, iParent, pSub->pEList);
57.2338 + }
57.2339 + if( pSub->pOrderBy ){
57.2340 + assert( p->pOrderBy==0 );
57.2341 + p->pOrderBy = pSub->pOrderBy;
57.2342 + pSub->pOrderBy = 0;
57.2343 + }else if( p->pOrderBy ){
57.2344 + substExprList(p->pOrderBy, iParent, pSub->pEList);
57.2345 + }
57.2346 + if( pSub->pWhere ){
57.2347 + pWhere = sqlite3ExprDup(pSub->pWhere);
57.2348 + }else{
57.2349 + pWhere = 0;
57.2350 + }
57.2351 + if( subqueryIsAgg ){
57.2352 + assert( p->pHaving==0 );
57.2353 + p->pHaving = p->pWhere;
57.2354 + p->pWhere = pWhere;
57.2355 + substExpr(p->pHaving, iParent, pSub->pEList);
57.2356 + p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
57.2357 + assert( p->pGroupBy==0 );
57.2358 + p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
57.2359 + }else{
57.2360 + substExpr(p->pWhere, iParent, pSub->pEList);
57.2361 + p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
57.2362 + }
57.2363 +
57.2364 + /* The flattened query is distinct if either the inner or the
57.2365 + ** outer query is distinct.
57.2366 + */
57.2367 + p->isDistinct = p->isDistinct || pSub->isDistinct;
57.2368 +
57.2369 + /*
57.2370 + ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
57.2371 + **
57.2372 + ** One is tempted to try to add a and b to combine the limits. But this
57.2373 + ** does not work if either limit is negative.
57.2374 + */
57.2375 + if( pSub->pLimit ){
57.2376 + p->pLimit = pSub->pLimit;
57.2377 + pSub->pLimit = 0;
57.2378 + }
57.2379 +
57.2380 + /* Finially, delete what is left of the subquery and return
57.2381 + ** success.
57.2382 + */
57.2383 + sqlite3SelectDelete(pSub);
57.2384 + return 1;
57.2385 +}
57.2386 +#endif /* SQLITE_OMIT_VIEW */
57.2387 +
57.2388 +/*
57.2389 +** Analyze the SELECT statement passed in as an argument to see if it
57.2390 +** is a simple min() or max() query. If it is and this query can be
57.2391 +** satisfied using a single seek to the beginning or end of an index,
57.2392 +** then generate the code for this SELECT and return 1. If this is not a
57.2393 +** simple min() or max() query, then return 0;
57.2394 +**
57.2395 +** A simply min() or max() query looks like this:
57.2396 +**
57.2397 +** SELECT min(a) FROM table;
57.2398 +** SELECT max(a) FROM table;
57.2399 +**
57.2400 +** The query may have only a single table in its FROM argument. There
57.2401 +** can be no GROUP BY or HAVING or WHERE clauses. The result set must
57.2402 +** be the min() or max() of a single column of the table. The column
57.2403 +** in the min() or max() function must be indexed.
57.2404 +**
57.2405 +** The parameters to this routine are the same as for sqlite3Select().
57.2406 +** See the header comment on that routine for additional information.
57.2407 +*/
57.2408 +static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
57.2409 + Expr *pExpr;
57.2410 + int iCol;
57.2411 + Table *pTab;
57.2412 + Index *pIdx;
57.2413 + int base;
57.2414 + Vdbe *v;
57.2415 + int seekOp;
57.2416 + ExprList *pEList, *pList, eList;
57.2417 + struct ExprList_item eListItem;
57.2418 + SrcList *pSrc;
57.2419 + int brk;
57.2420 + int iDb;
57.2421 +
57.2422 + /* Check to see if this query is a simple min() or max() query. Return
57.2423 + ** zero if it is not.
57.2424 + */
57.2425 + if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
57.2426 + pSrc = p->pSrc;
57.2427 + if( pSrc->nSrc!=1 ) return 0;
57.2428 + pEList = p->pEList;
57.2429 + if( pEList->nExpr!=1 ) return 0;
57.2430 + pExpr = pEList->a[0].pExpr;
57.2431 + if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
57.2432 + pList = pExpr->pList;
57.2433 + if( pList==0 || pList->nExpr!=1 ) return 0;
57.2434 + if( pExpr->token.n!=3 ) return 0;
57.2435 + if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
57.2436 + seekOp = OP_Rewind;
57.2437 + }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
57.2438 + seekOp = OP_Last;
57.2439 + }else{
57.2440 + return 0;
57.2441 + }
57.2442 + pExpr = pList->a[0].pExpr;
57.2443 + if( pExpr->op!=TK_COLUMN ) return 0;
57.2444 + iCol = pExpr->iColumn;
57.2445 + pTab = pSrc->a[0].pTab;
57.2446 +
57.2447 + /* This optimization cannot be used with virtual tables. */
57.2448 + if( IsVirtual(pTab) ) return 0;
57.2449 +
57.2450 + /* If we get to here, it means the query is of the correct form.
57.2451 + ** Check to make sure we have an index and make pIdx point to the
57.2452 + ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
57.2453 + ** key column, no index is necessary so set pIdx to NULL. If no
57.2454 + ** usable index is found, return 0.
57.2455 + */
57.2456 + if( iCol<0 ){
57.2457 + pIdx = 0;
57.2458 + }else{
57.2459 + CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
57.2460 + if( pColl==0 ) return 0;
57.2461 + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
57.2462 + assert( pIdx->nColumn>=1 );
57.2463 + if( pIdx->aiColumn[0]==iCol &&
57.2464 + 0==sqlite3StrICmp(pIdx->azColl[0], pColl->zName) ){
57.2465 + break;
57.2466 + }
57.2467 + }
57.2468 + if( pIdx==0 ) return 0;
57.2469 + }
57.2470 +
57.2471 + /* Identify column types if we will be using the callback. This
57.2472 + ** step is skipped if the output is going to a table or a memory cell.
57.2473 + ** The column names have already been generated in the calling function.
57.2474 + */
57.2475 + v = sqlite3GetVdbe(pParse);
57.2476 + if( v==0 ) return 0;
57.2477 +
57.2478 + /* If the output is destined for a temporary table, open that table.
57.2479 + */
57.2480 + if( eDest==SRT_EphemTab ){
57.2481 + sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 1);
57.2482 + }
57.2483 +
57.2484 + /* Generating code to find the min or the max. Basically all we have
57.2485 + ** to do is find the first or the last entry in the chosen index. If
57.2486 + ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
57.2487 + ** or last entry in the main table.
57.2488 + */
57.2489 + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
57.2490 + assert( iDb>=0 || pTab->isEphem );
57.2491 + sqlite3CodeVerifySchema(pParse, iDb);
57.2492 + sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
57.2493 + base = pSrc->a[0].iCursor;
57.2494 + brk = sqlite3VdbeMakeLabel(v);
57.2495 + computeLimitRegisters(pParse, p, brk);
57.2496 + if( pSrc->a[0].pSelect==0 ){
57.2497 + sqlite3OpenTable(pParse, base, iDb, pTab, OP_OpenRead);
57.2498 + }
57.2499 + if( pIdx==0 ){
57.2500 + sqlite3VdbeAddOp(v, seekOp, base, 0);
57.2501 + }else{
57.2502 + /* Even though the cursor used to open the index here is closed
57.2503 + ** as soon as a single value has been read from it, allocate it
57.2504 + ** using (pParse->nTab++) to prevent the cursor id from being
57.2505 + ** reused. This is important for statements of the form
57.2506 + ** "INSERT INTO x SELECT max() FROM x".
57.2507 + */
57.2508 + int iIdx;
57.2509 + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
57.2510 + iIdx = pParse->nTab++;
57.2511 + assert( pIdx->pSchema==pTab->pSchema );
57.2512 + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
57.2513 + sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
57.2514 + (char*)pKey, P3_KEYINFO_HANDOFF);
57.2515 + if( seekOp==OP_Rewind ){
57.2516 + sqlite3VdbeAddOp(v, OP_Null, 0, 0);
57.2517 + sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
57.2518 + seekOp = OP_MoveGt;
57.2519 + }
57.2520 + if( pIdx->aSortOrder[0]==SQLITE_SO_DESC ){
57.2521 + /* Ticket #2514: invert the seek operator if we are using
57.2522 + ** a descending index. */
57.2523 + if( seekOp==OP_Last ){
57.2524 + seekOp = OP_Rewind;
57.2525 + }else{
57.2526 + assert( seekOp==OP_MoveGt );
57.2527 + seekOp = OP_MoveLt;
57.2528 + }
57.2529 + }
57.2530 + sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
57.2531 + sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
57.2532 + sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
57.2533 + sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
57.2534 + }
57.2535 + eList.nExpr = 1;
57.2536 + memset(&eListItem, 0, sizeof(eListItem));
57.2537 + eList.a = &eListItem;
57.2538 + eList.a[0].pExpr = pExpr;
57.2539 + selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0);
57.2540 + sqlite3VdbeResolveLabel(v, brk);
57.2541 + sqlite3VdbeAddOp(v, OP_Close, base, 0);
57.2542 +
57.2543 + return 1;
57.2544 +}
57.2545 +
57.2546 +/*
57.2547 +** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return
57.2548 +** the number of errors seen.
57.2549 +**
57.2550 +** An ORDER BY or GROUP BY is a list of expressions. If any expression
57.2551 +** is an integer constant, then that expression is replaced by the
57.2552 +** corresponding entry in the result set.
57.2553 +*/
57.2554 +static int processOrderGroupBy(
57.2555 + NameContext *pNC, /* Name context of the SELECT statement. */
57.2556 + ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
57.2557 + const char *zType /* Either "ORDER" or "GROUP", as appropriate */
57.2558 +){
57.2559 + int i;
57.2560 + ExprList *pEList = pNC->pEList; /* The result set of the SELECT */
57.2561 + Parse *pParse = pNC->pParse; /* The result set of the SELECT */
57.2562 + assert( pEList );
57.2563 +
57.2564 + if( pOrderBy==0 ) return 0;
57.2565 + if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){
57.2566 + sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
57.2567 + return 1;
57.2568 + }
57.2569 + for(i=0; i<pOrderBy->nExpr; i++){
57.2570 + int iCol;
57.2571 + Expr *pE = pOrderBy->a[i].pExpr;
57.2572 + if( sqlite3ExprIsInteger(pE, &iCol) ){
57.2573 + if( iCol>0 && iCol<=pEList->nExpr ){
57.2574 + CollSeq *pColl = pE->pColl;
57.2575 + int flags = pE->flags & EP_ExpCollate;
57.2576 + sqlite3ExprDelete(pE);
57.2577 + pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
57.2578 + if( pColl && flags ){
57.2579 + pE->pColl = pColl;
57.2580 + pE->flags |= flags;
57.2581 + }
57.2582 + }else{
57.2583 + sqlite3ErrorMsg(pParse,
57.2584 + "%s BY column number %d out of range - should be "
57.2585 + "between 1 and %d", zType, iCol, pEList->nExpr);
57.2586 + return 1;
57.2587 + }
57.2588 + }
57.2589 + if( sqlite3ExprResolveNames(pNC, pE) ){
57.2590 + return 1;
57.2591 + }
57.2592 + }
57.2593 + return 0;
57.2594 +}
57.2595 +
57.2596 +/*
57.2597 +** This routine resolves any names used in the result set of the
57.2598 +** supplied SELECT statement. If the SELECT statement being resolved
57.2599 +** is a sub-select, then pOuterNC is a pointer to the NameContext
57.2600 +** of the parent SELECT.
57.2601 +*/
57.2602 +int sqlite3SelectResolve(
57.2603 + Parse *pParse, /* The parser context */
57.2604 + Select *p, /* The SELECT statement being coded. */
57.2605 + NameContext *pOuterNC /* The outer name context. May be NULL. */
57.2606 +){
57.2607 + ExprList *pEList; /* Result set. */
57.2608 + int i; /* For-loop variable used in multiple places */
57.2609 + NameContext sNC; /* Local name-context */
57.2610 + ExprList *pGroupBy; /* The group by clause */
57.2611 +
57.2612 + /* If this routine has run before, return immediately. */
57.2613 + if( p->isResolved ){
57.2614 + assert( !pOuterNC );
57.2615 + return SQLITE_OK;
57.2616 + }
57.2617 + p->isResolved = 1;
57.2618 +
57.2619 + /* If there have already been errors, do nothing. */
57.2620 + if( pParse->nErr>0 ){
57.2621 + return SQLITE_ERROR;
57.2622 + }
57.2623 +
57.2624 + /* Prepare the select statement. This call will allocate all cursors
57.2625 + ** required to handle the tables and subqueries in the FROM clause.
57.2626 + */
57.2627 + if( prepSelectStmt(pParse, p) ){
57.2628 + return SQLITE_ERROR;
57.2629 + }
57.2630 +
57.2631 + /* Resolve the expressions in the LIMIT and OFFSET clauses. These
57.2632 + ** are not allowed to refer to any names, so pass an empty NameContext.
57.2633 + */
57.2634 + memset(&sNC, 0, sizeof(sNC));
57.2635 + sNC.pParse = pParse;
57.2636 + if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
57.2637 + sqlite3ExprResolveNames(&sNC, p->pOffset) ){
57.2638 + return SQLITE_ERROR;
57.2639 + }
57.2640 +
57.2641 + /* Set up the local name-context to pass to ExprResolveNames() to
57.2642 + ** resolve the expression-list.
57.2643 + */
57.2644 + sNC.allowAgg = 1;
57.2645 + sNC.pSrcList = p->pSrc;
57.2646 + sNC.pNext = pOuterNC;
57.2647 +
57.2648 + /* Resolve names in the result set. */
57.2649 + pEList = p->pEList;
57.2650 + if( !pEList ) return SQLITE_ERROR;
57.2651 + for(i=0; i<pEList->nExpr; i++){
57.2652 + Expr *pX = pEList->a[i].pExpr;
57.2653 + if( sqlite3ExprResolveNames(&sNC, pX) ){
57.2654 + return SQLITE_ERROR;
57.2655 + }
57.2656 + }
57.2657 +
57.2658 + /* If there are no aggregate functions in the result-set, and no GROUP BY
57.2659 + ** expression, do not allow aggregates in any of the other expressions.
57.2660 + */
57.2661 + assert( !p->isAgg );
57.2662 + pGroupBy = p->pGroupBy;
57.2663 + if( pGroupBy || sNC.hasAgg ){
57.2664 + p->isAgg = 1;
57.2665 + }else{
57.2666 + sNC.allowAgg = 0;
57.2667 + }
57.2668 +
57.2669 + /* If a HAVING clause is present, then there must be a GROUP BY clause.
57.2670 + */
57.2671 + if( p->pHaving && !pGroupBy ){
57.2672 + sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
57.2673 + return SQLITE_ERROR;
57.2674 + }
57.2675 +
57.2676 + /* Add the expression list to the name-context before parsing the
57.2677 + ** other expressions in the SELECT statement. This is so that
57.2678 + ** expressions in the WHERE clause (etc.) can refer to expressions by
57.2679 + ** aliases in the result set.
57.2680 + **
57.2681 + ** Minor point: If this is the case, then the expression will be
57.2682 + ** re-evaluated for each reference to it.
57.2683 + */
57.2684 + sNC.pEList = p->pEList;
57.2685 + if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
57.2686 + sqlite3ExprResolveNames(&sNC, p->pHaving) ){
57.2687 + return SQLITE_ERROR;
57.2688 + }
57.2689 + if( p->pPrior==0 ){
57.2690 + if( processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
57.2691 + processOrderGroupBy(&sNC, pGroupBy, "GROUP") ){
57.2692 + return SQLITE_ERROR;
57.2693 + }
57.2694 + }
57.2695 +
57.2696 + if( sqlite3MallocFailed() ){
57.2697 + return SQLITE_NOMEM;
57.2698 + }
57.2699 +
57.2700 + /* Make sure the GROUP BY clause does not contain aggregate functions.
57.2701 + */
57.2702 + if( pGroupBy ){
57.2703 + struct ExprList_item *pItem;
57.2704 +
57.2705 + for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
57.2706 + if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
57.2707 + sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
57.2708 + "the GROUP BY clause");
57.2709 + return SQLITE_ERROR;
57.2710 + }
57.2711 + }
57.2712 + }
57.2713 +
57.2714 + /* If this is one SELECT of a compound, be sure to resolve names
57.2715 + ** in the other SELECTs.
57.2716 + */
57.2717 + if( p->pPrior ){
57.2718 + return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC);
57.2719 + }else{
57.2720 + return SQLITE_OK;
57.2721 + }
57.2722 +}
57.2723 +
57.2724 +/*
57.2725 +** Reset the aggregate accumulator.
57.2726 +**
57.2727 +** The aggregate accumulator is a set of memory cells that hold
57.2728 +** intermediate results while calculating an aggregate. This
57.2729 +** routine simply stores NULLs in all of those memory cells.
57.2730 +*/
57.2731 +static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
57.2732 + Vdbe *v = pParse->pVdbe;
57.2733 + int i;
57.2734 + struct AggInfo_func *pFunc;
57.2735 + if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
57.2736 + return;
57.2737 + }
57.2738 + for(i=0; i<pAggInfo->nColumn; i++){
57.2739 + sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0);
57.2740 + }
57.2741 + for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
57.2742 + sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0);
57.2743 + if( pFunc->iDistinct>=0 ){
57.2744 + Expr *pE = pFunc->pExpr;
57.2745 + if( pE->pList==0 || pE->pList->nExpr!=1 ){
57.2746 + sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
57.2747 + "by an expression");
57.2748 + pFunc->iDistinct = -1;
57.2749 + }else{
57.2750 + KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
57.2751 + sqlite3VdbeOp3(v, OP_OpenEphemeral, pFunc->iDistinct, 0,
57.2752 + (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
57.2753 + }
57.2754 + }
57.2755 + }
57.2756 +}
57.2757 +
57.2758 +/*
57.2759 +** Invoke the OP_AggFinalize opcode for every aggregate function
57.2760 +** in the AggInfo structure.
57.2761 +*/
57.2762 +static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
57.2763 + Vdbe *v = pParse->pVdbe;
57.2764 + int i;
57.2765 + struct AggInfo_func *pF;
57.2766 + for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
57.2767 + ExprList *pList = pF->pExpr->pList;
57.2768 + sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0,
57.2769 + (void*)pF->pFunc, P3_FUNCDEF);
57.2770 + }
57.2771 +}
57.2772 +
57.2773 +/*
57.2774 +** Update the accumulator memory cells for an aggregate based on
57.2775 +** the current cursor position.
57.2776 +*/
57.2777 +static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
57.2778 + Vdbe *v = pParse->pVdbe;
57.2779 + int i;
57.2780 + struct AggInfo_func *pF;
57.2781 + struct AggInfo_col *pC;
57.2782 +
57.2783 + pAggInfo->directMode = 1;
57.2784 + for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
57.2785 + int nArg;
57.2786 + int addrNext = 0;
57.2787 + ExprList *pList = pF->pExpr->pList;
57.2788 + if( pList ){
57.2789 + nArg = pList->nExpr;
57.2790 + sqlite3ExprCodeExprList(pParse, pList);
57.2791 + }else{
57.2792 + nArg = 0;
57.2793 + }
57.2794 + if( pF->iDistinct>=0 ){
57.2795 + addrNext = sqlite3VdbeMakeLabel(v);
57.2796 + assert( nArg==1 );
57.2797 + codeDistinct(v, pF->iDistinct, addrNext, 1);
57.2798 + }
57.2799 + if( pF->pFunc->needCollSeq ){
57.2800 + CollSeq *pColl = 0;
57.2801 + struct ExprList_item *pItem;
57.2802 + int j;
57.2803 + assert( pList!=0 ); /* pList!=0 if pF->pFunc->needCollSeq is true */
57.2804 + for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
57.2805 + pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
57.2806 + }
57.2807 + if( !pColl ){
57.2808 + pColl = pParse->db->pDfltColl;
57.2809 + }
57.2810 + sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
57.2811 + }
57.2812 + sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF);
57.2813 + if( addrNext ){
57.2814 + sqlite3VdbeResolveLabel(v, addrNext);
57.2815 + }
57.2816 + }
57.2817 + for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
57.2818 + sqlite3ExprCode(pParse, pC->pExpr);
57.2819 + sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1);
57.2820 + }
57.2821 + pAggInfo->directMode = 0;
57.2822 +}
57.2823 +
57.2824 +
57.2825 +/*
57.2826 +** Generate code for the given SELECT statement.
57.2827 +**
57.2828 +** The results are distributed in various ways depending on the
57.2829 +** value of eDest and iParm.
57.2830 +**
57.2831 +** eDest Value Result
57.2832 +** ------------ -------------------------------------------
57.2833 +** SRT_Callback Invoke the callback for each row of the result.
57.2834 +**
57.2835 +** SRT_Mem Store first result in memory cell iParm
57.2836 +**
57.2837 +** SRT_Set Store results as keys of table iParm.
57.2838 +**
57.2839 +** SRT_Union Store results as a key in a temporary table iParm
57.2840 +**
57.2841 +** SRT_Except Remove results from the temporary table iParm.
57.2842 +**
57.2843 +** SRT_Table Store results in temporary table iParm
57.2844 +**
57.2845 +** The table above is incomplete. Additional eDist value have be added
57.2846 +** since this comment was written. See the selectInnerLoop() function for
57.2847 +** a complete listing of the allowed values of eDest and their meanings.
57.2848 +**
57.2849 +** This routine returns the number of errors. If any errors are
57.2850 +** encountered, then an appropriate error message is left in
57.2851 +** pParse->zErrMsg.
57.2852 +**
57.2853 +** This routine does NOT free the Select structure passed in. The
57.2854 +** calling function needs to do that.
57.2855 +**
57.2856 +** The pParent, parentTab, and *pParentAgg fields are filled in if this
57.2857 +** SELECT is a subquery. This routine may try to combine this SELECT
57.2858 +** with its parent to form a single flat query. In so doing, it might
57.2859 +** change the parent query from a non-aggregate to an aggregate query.
57.2860 +** For that reason, the pParentAgg flag is passed as a pointer, so it
57.2861 +** can be changed.
57.2862 +**
57.2863 +** Example 1: The meaning of the pParent parameter.
57.2864 +**
57.2865 +** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
57.2866 +** \ \_______ subquery _______/ /
57.2867 +** \ /
57.2868 +** \____________________ outer query ___________________/
57.2869 +**
57.2870 +** This routine is called for the outer query first. For that call,
57.2871 +** pParent will be NULL. During the processing of the outer query, this
57.2872 +** routine is called recursively to handle the subquery. For the recursive
57.2873 +** call, pParent will point to the outer query. Because the subquery is
57.2874 +** the second element in a three-way join, the parentTab parameter will
57.2875 +** be 1 (the 2nd value of a 0-indexed array.)
57.2876 +*/
57.2877 +int sqlite3Select(
57.2878 + Parse *pParse, /* The parser context */
57.2879 + Select *p, /* The SELECT statement being coded. */
57.2880 + int eDest, /* How to dispose of the results */
57.2881 + int iParm, /* A parameter used by the eDest disposal method */
57.2882 + Select *pParent, /* Another SELECT for which this is a sub-query */
57.2883 + int parentTab, /* Index in pParent->pSrc of this query */
57.2884 + int *pParentAgg, /* True if pParent uses aggregate functions */
57.2885 + char *aff /* If eDest is SRT_Union, the affinity string */
57.2886 +){
57.2887 + int i, j; /* Loop counters */
57.2888 + WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
57.2889 + Vdbe *v; /* The virtual machine under construction */
57.2890 + int isAgg; /* True for select lists like "count(*)" */
57.2891 + ExprList *pEList; /* List of columns to extract. */
57.2892 + SrcList *pTabList; /* List of tables to select from */
57.2893 + Expr *pWhere; /* The WHERE clause. May be NULL */
57.2894 + ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
57.2895 + ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
57.2896 + Expr *pHaving; /* The HAVING clause. May be NULL */
57.2897 + int isDistinct; /* True if the DISTINCT keyword is present */
57.2898 + int distinct; /* Table to use for the distinct set */
57.2899 + int rc = 1; /* Value to return from this function */
57.2900 + int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
57.2901 + AggInfo sAggInfo; /* Information used by aggregate queries */
57.2902 + int iEnd; /* Address of the end of the query */
57.2903 +
57.2904 + if( p==0 || sqlite3MallocFailed() || pParse->nErr ){
57.2905 + return 1;
57.2906 + }
57.2907 + if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
57.2908 + memset(&sAggInfo, 0, sizeof(sAggInfo));
57.2909 +
57.2910 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
57.2911 + /* If there is are a sequence of queries, do the earlier ones first.
57.2912 + */
57.2913 + if( p->pPrior ){
57.2914 + if( p->pRightmost==0 ){
57.2915 + Select *pLoop;
57.2916 + int cnt = 0;
57.2917 + for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
57.2918 + pLoop->pRightmost = p;
57.2919 + }
57.2920 + if( SQLITE_MAX_COMPOUND_SELECT>0 && cnt>SQLITE_MAX_COMPOUND_SELECT ){
57.2921 + sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
57.2922 + return 1;
57.2923 + }
57.2924 + }
57.2925 + return multiSelect(pParse, p, eDest, iParm, aff);
57.2926 + }
57.2927 +#endif
57.2928 +
57.2929 + pOrderBy = p->pOrderBy;
57.2930 + if( IgnorableOrderby(eDest) ){
57.2931 + p->pOrderBy = 0;
57.2932 + }
57.2933 + if( sqlite3SelectResolve(pParse, p, 0) ){
57.2934 + goto select_end;
57.2935 + }
57.2936 + p->pOrderBy = pOrderBy;
57.2937 +
57.2938 + /* Make local copies of the parameters for this query.
57.2939 + */
57.2940 + pTabList = p->pSrc;
57.2941 + pWhere = p->pWhere;
57.2942 + pGroupBy = p->pGroupBy;
57.2943 + pHaving = p->pHaving;
57.2944 + isAgg = p->isAgg;
57.2945 + isDistinct = p->isDistinct;
57.2946 + pEList = p->pEList;
57.2947 + if( pEList==0 ) goto select_end;
57.2948 +
57.2949 + /*
57.2950 + ** Do not even attempt to generate any code if we have already seen
57.2951 + ** errors before this routine starts.
57.2952 + */
57.2953 + if( pParse->nErr>0 ) goto select_end;
57.2954 +
57.2955 + /* If writing to memory or generating a set
57.2956 + ** only a single column may be output.
57.2957 + */
57.2958 +#ifndef SQLITE_OMIT_SUBQUERY
57.2959 + if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){
57.2960 + goto select_end;
57.2961 + }
57.2962 +#endif
57.2963 +
57.2964 + /* ORDER BY is ignored for some destinations.
57.2965 + */
57.2966 + if( IgnorableOrderby(eDest) ){
57.2967 + pOrderBy = 0;
57.2968 + }
57.2969 +
57.2970 + /* Begin generating code.
57.2971 + */
57.2972 + v = sqlite3GetVdbe(pParse);
57.2973 + if( v==0 ) goto select_end;
57.2974 +
57.2975 + /* Generate code for all sub-queries in the FROM clause
57.2976 + */
57.2977 +#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
57.2978 + for(i=0; i<pTabList->nSrc; i++){
57.2979 + const char *zSavedAuthContext = 0;
57.2980 + int needRestoreContext;
57.2981 + struct SrcList_item *pItem = &pTabList->a[i];
57.2982 +
57.2983 + if( pItem->pSelect==0 || pItem->isPopulated ) continue;
57.2984 + if( pItem->zName!=0 ){
57.2985 + zSavedAuthContext = pParse->zAuthContext;
57.2986 + pParse->zAuthContext = pItem->zName;
57.2987 + needRestoreContext = 1;
57.2988 + }else{
57.2989 + needRestoreContext = 0;
57.2990 + }
57.2991 +#if SQLITE_MAX_EXPR_DEPTH>0
57.2992 + /* Increment Parse.nHeight by the height of the largest expression
57.2993 + ** tree refered to by this, the parent select. The child select
57.2994 + ** may contain expression trees of at most
57.2995 + ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
57.2996 + ** more conservative than necessary, but much easier than enforcing
57.2997 + ** an exact limit.
57.2998 + */
57.2999 + pParse->nHeight += sqlite3SelectExprHeight(p);
57.3000 +#endif
57.3001 + sqlite3Select(pParse, pItem->pSelect, SRT_EphemTab,
57.3002 + pItem->iCursor, p, i, &isAgg, 0);
57.3003 +#if SQLITE_MAX_EXPR_DEPTH>0
57.3004 + pParse->nHeight -= sqlite3SelectExprHeight(p);
57.3005 +#endif
57.3006 + if( needRestoreContext ){
57.3007 + pParse->zAuthContext = zSavedAuthContext;
57.3008 + }
57.3009 + pTabList = p->pSrc;
57.3010 + pWhere = p->pWhere;
57.3011 + if( !IgnorableOrderby(eDest) ){
57.3012 + pOrderBy = p->pOrderBy;
57.3013 + }
57.3014 + pGroupBy = p->pGroupBy;
57.3015 + pHaving = p->pHaving;
57.3016 + isDistinct = p->isDistinct;
57.3017 + }
57.3018 +#endif
57.3019 +
57.3020 + /* Check for the special case of a min() or max() function by itself
57.3021 + ** in the result set.
57.3022 + */
57.3023 + if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
57.3024 + rc = 0;
57.3025 + goto select_end;
57.3026 + }
57.3027 +
57.3028 + /* Check to see if this is a subquery that can be "flattened" into its parent.
57.3029 + ** If flattening is a possiblity, do so and return immediately.
57.3030 + */
57.3031 +#ifndef SQLITE_OMIT_VIEW
57.3032 + if( pParent && pParentAgg &&
57.3033 + flattenSubquery(pParent, parentTab, *pParentAgg, isAgg) ){
57.3034 + if( isAgg ) *pParentAgg = 1;
57.3035 + goto select_end;
57.3036 + }
57.3037 +#endif
57.3038 +
57.3039 + /* If there is an ORDER BY clause, then this sorting
57.3040 + ** index might end up being unused if the data can be
57.3041 + ** extracted in pre-sorted order. If that is the case, then the
57.3042 + ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
57.3043 + ** we figure out that the sorting index is not needed. The addrSortIndex
57.3044 + ** variable is used to facilitate that change.
57.3045 + */
57.3046 + if( pOrderBy ){
57.3047 + KeyInfo *pKeyInfo;
57.3048 + if( pParse->nErr ){
57.3049 + goto select_end;
57.3050 + }
57.3051 + pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
57.3052 + pOrderBy->iECursor = pParse->nTab++;
57.3053 + p->addrOpenEphm[2] = addrSortIndex =
57.3054 + sqlite3VdbeOp3(v, OP_OpenEphemeral, pOrderBy->iECursor, pOrderBy->nExpr+2, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
57.3055 + }else{
57.3056 + addrSortIndex = -1;
57.3057 + }
57.3058 +
57.3059 + /* If the output is destined for a temporary table, open that table.
57.3060 + */
57.3061 + if( eDest==SRT_EphemTab ){
57.3062 + sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, pEList->nExpr);
57.3063 + }
57.3064 +
57.3065 + /* Set the limiter.
57.3066 + */
57.3067 + iEnd = sqlite3VdbeMakeLabel(v);
57.3068 + computeLimitRegisters(pParse, p, iEnd);
57.3069 +
57.3070 + /* Open a virtual index to use for the distinct set.
57.3071 + */
57.3072 + if( isDistinct ){
57.3073 + KeyInfo *pKeyInfo;
57.3074 + distinct = pParse->nTab++;
57.3075 + pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
57.3076 + sqlite3VdbeOp3(v, OP_OpenEphemeral, distinct, 0,
57.3077 + (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
57.3078 + }else{
57.3079 + distinct = -1;
57.3080 + }
57.3081 +
57.3082 + /* Aggregate and non-aggregate queries are handled differently */
57.3083 + if( !isAgg && pGroupBy==0 ){
57.3084 + /* This case is for non-aggregate queries
57.3085 + ** Begin the database scan
57.3086 + */
57.3087 + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy);
57.3088 + if( pWInfo==0 ) goto select_end;
57.3089 +
57.3090 + /* If sorting index that was created by a prior OP_OpenEphemeral
57.3091 + ** instruction ended up not being needed, then change the OP_OpenEphemeral
57.3092 + ** into an OP_Noop.
57.3093 + */
57.3094 + if( addrSortIndex>=0 && pOrderBy==0 ){
57.3095 + sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
57.3096 + p->addrOpenEphm[2] = -1;
57.3097 + }
57.3098 +
57.3099 + /* Use the standard inner loop
57.3100 + */
57.3101 + if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
57.3102 + iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
57.3103 + goto select_end;
57.3104 + }
57.3105 +
57.3106 + /* End the database scan loop.
57.3107 + */
57.3108 + sqlite3WhereEnd(pWInfo);
57.3109 + }else{
57.3110 + /* This is the processing for aggregate queries */
57.3111 + NameContext sNC; /* Name context for processing aggregate information */
57.3112 + int iAMem; /* First Mem address for storing current GROUP BY */
57.3113 + int iBMem; /* First Mem address for previous GROUP BY */
57.3114 + int iUseFlag; /* Mem address holding flag indicating that at least
57.3115 + ** one row of the input to the aggregator has been
57.3116 + ** processed */
57.3117 + int iAbortFlag; /* Mem address which causes query abort if positive */
57.3118 + int groupBySort; /* Rows come from source in GROUP BY order */
57.3119 +
57.3120 +
57.3121 + /* The following variables hold addresses or labels for parts of the
57.3122 + ** virtual machine program we are putting together */
57.3123 + int addrOutputRow; /* Start of subroutine that outputs a result row */
57.3124 + int addrSetAbort; /* Set the abort flag and return */
57.3125 + int addrInitializeLoop; /* Start of code that initializes the input loop */
57.3126 + int addrTopOfLoop; /* Top of the input loop */
57.3127 + int addrGroupByChange; /* Code that runs when any GROUP BY term changes */
57.3128 + int addrProcessRow; /* Code to process a single input row */
57.3129 + int addrEnd; /* End of all processing */
57.3130 + int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
57.3131 + int addrReset; /* Subroutine for resetting the accumulator */
57.3132 +
57.3133 + addrEnd = sqlite3VdbeMakeLabel(v);
57.3134 +
57.3135 + /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
57.3136 + ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
57.3137 + ** SELECT statement.
57.3138 + */
57.3139 + memset(&sNC, 0, sizeof(sNC));
57.3140 + sNC.pParse = pParse;
57.3141 + sNC.pSrcList = pTabList;
57.3142 + sNC.pAggInfo = &sAggInfo;
57.3143 + sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
57.3144 + sAggInfo.pGroupBy = pGroupBy;
57.3145 + if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
57.3146 + goto select_end;
57.3147 + }
57.3148 + if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
57.3149 + goto select_end;
57.3150 + }
57.3151 + if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
57.3152 + goto select_end;
57.3153 + }
57.3154 + sAggInfo.nAccumulator = sAggInfo.nColumn;
57.3155 + for(i=0; i<sAggInfo.nFunc; i++){
57.3156 + if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
57.3157 + goto select_end;
57.3158 + }
57.3159 + }
57.3160 + if( sqlite3MallocFailed() ) goto select_end;
57.3161 +
57.3162 + /* Processing for aggregates with GROUP BY is very different and
57.3163 + ** much more complex tha aggregates without a GROUP BY.
57.3164 + */
57.3165 + if( pGroupBy ){
57.3166 + KeyInfo *pKeyInfo; /* Keying information for the group by clause */
57.3167 +
57.3168 + /* Create labels that we will be needing
57.3169 + */
57.3170 +
57.3171 + addrInitializeLoop = sqlite3VdbeMakeLabel(v);
57.3172 + addrGroupByChange = sqlite3VdbeMakeLabel(v);
57.3173 + addrProcessRow = sqlite3VdbeMakeLabel(v);
57.3174 +
57.3175 + /* If there is a GROUP BY clause we might need a sorting index to
57.3176 + ** implement it. Allocate that sorting index now. If it turns out
57.3177 + ** that we do not need it after all, the OpenEphemeral instruction
57.3178 + ** will be converted into a Noop.
57.3179 + */
57.3180 + sAggInfo.sortingIdx = pParse->nTab++;
57.3181 + pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
57.3182 + addrSortingIdx =
57.3183 + sqlite3VdbeOp3(v, OP_OpenEphemeral, sAggInfo.sortingIdx,
57.3184 + sAggInfo.nSortingColumn,
57.3185 + (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
57.3186 +
57.3187 + /* Initialize memory locations used by GROUP BY aggregate processing
57.3188 + */
57.3189 + iUseFlag = pParse->nMem++;
57.3190 + iAbortFlag = pParse->nMem++;
57.3191 + iAMem = pParse->nMem;
57.3192 + pParse->nMem += pGroupBy->nExpr;
57.3193 + iBMem = pParse->nMem;
57.3194 + pParse->nMem += pGroupBy->nExpr;
57.3195 + sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag);
57.3196 + VdbeComment((v, "# clear abort flag"));
57.3197 + sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag);
57.3198 + VdbeComment((v, "# indicate accumulator empty"));
57.3199 + sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop);
57.3200 +
57.3201 + /* Generate a subroutine that outputs a single row of the result
57.3202 + ** set. This subroutine first looks at the iUseFlag. If iUseFlag
57.3203 + ** is less than or equal to zero, the subroutine is a no-op. If
57.3204 + ** the processing calls for the query to abort, this subroutine
57.3205 + ** increments the iAbortFlag memory location before returning in
57.3206 + ** order to signal the caller to abort.
57.3207 + */
57.3208 + addrSetAbort = sqlite3VdbeCurrentAddr(v);
57.3209 + sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag);
57.3210 + VdbeComment((v, "# set abort flag"));
57.3211 + sqlite3VdbeAddOp(v, OP_Return, 0, 0);
57.3212 + addrOutputRow = sqlite3VdbeCurrentAddr(v);
57.3213 + sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2);
57.3214 + VdbeComment((v, "# Groupby result generator entry point"));
57.3215 + sqlite3VdbeAddOp(v, OP_Return, 0, 0);
57.3216 + finalizeAggFunctions(pParse, &sAggInfo);
57.3217 + if( pHaving ){
57.3218 + sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1);
57.3219 + }
57.3220 + rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
57.3221 + distinct, eDest, iParm,
57.3222 + addrOutputRow+1, addrSetAbort, aff);
57.3223 + if( rc ){
57.3224 + goto select_end;
57.3225 + }
57.3226 + sqlite3VdbeAddOp(v, OP_Return, 0, 0);
57.3227 + VdbeComment((v, "# end groupby result generator"));
57.3228 +
57.3229 + /* Generate a subroutine that will reset the group-by accumulator
57.3230 + */
57.3231 + addrReset = sqlite3VdbeCurrentAddr(v);
57.3232 + resetAccumulator(pParse, &sAggInfo);
57.3233 + sqlite3VdbeAddOp(v, OP_Return, 0, 0);
57.3234 +
57.3235 + /* Begin a loop that will extract all source rows in GROUP BY order.
57.3236 + ** This might involve two separate loops with an OP_Sort in between, or
57.3237 + ** it might be a single loop that uses an index to extract information
57.3238 + ** in the right order to begin with.
57.3239 + */
57.3240 + sqlite3VdbeResolveLabel(v, addrInitializeLoop);
57.3241 + sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
57.3242 + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy);
57.3243 + if( pWInfo==0 ) goto select_end;
57.3244 + if( pGroupBy==0 ){
57.3245 + /* The optimizer is able to deliver rows in group by order so
57.3246 + ** we do not have to sort. The OP_OpenEphemeral table will be
57.3247 + ** cancelled later because we still need to use the pKeyInfo
57.3248 + */
57.3249 + pGroupBy = p->pGroupBy;
57.3250 + groupBySort = 0;
57.3251 + }else{
57.3252 + /* Rows are coming out in undetermined order. We have to push
57.3253 + ** each row into a sorting index, terminate the first loop,
57.3254 + ** then loop over the sorting index in order to get the output
57.3255 + ** in sorted order
57.3256 + */
57.3257 + groupBySort = 1;
57.3258 + sqlite3ExprCodeExprList(pParse, pGroupBy);
57.3259 + sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0);
57.3260 + j = pGroupBy->nExpr+1;
57.3261 + for(i=0; i<sAggInfo.nColumn; i++){
57.3262 + struct AggInfo_col *pCol = &sAggInfo.aCol[i];
57.3263 + if( pCol->iSorterColumn<j ) continue;
57.3264 + sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable);
57.3265 + j++;
57.3266 + }
57.3267 + sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0);
57.3268 + sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0);
57.3269 + sqlite3WhereEnd(pWInfo);
57.3270 + sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
57.3271 + VdbeComment((v, "# GROUP BY sort"));
57.3272 + sAggInfo.useSortingIdx = 1;
57.3273 + }
57.3274 +
57.3275 + /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
57.3276 + ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
57.3277 + ** Then compare the current GROUP BY terms against the GROUP BY terms
57.3278 + ** from the previous row currently stored in a0, a1, a2...
57.3279 + */
57.3280 + addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
57.3281 + for(j=0; j<pGroupBy->nExpr; j++){
57.3282 + if( groupBySort ){
57.3283 + sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j);
57.3284 + }else{
57.3285 + sAggInfo.directMode = 1;
57.3286 + sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr);
57.3287 + }
57.3288 + sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1);
57.3289 + }
57.3290 + for(j=pGroupBy->nExpr-1; j>=0; j--){
57.3291 + if( j<pGroupBy->nExpr-1 ){
57.3292 + sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0);
57.3293 + }
57.3294 + sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0);
57.3295 + if( j==0 ){
57.3296 + sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow);
57.3297 + }else{
57.3298 + sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange);
57.3299 + }
57.3300 + sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ);
57.3301 + }
57.3302 +
57.3303 + /* Generate code that runs whenever the GROUP BY changes.
57.3304 + ** Change in the GROUP BY are detected by the previous code
57.3305 + ** block. If there were no changes, this block is skipped.
57.3306 + **
57.3307 + ** This code copies current group by terms in b0,b1,b2,...
57.3308 + ** over to a0,a1,a2. It then calls the output subroutine
57.3309 + ** and resets the aggregate accumulator registers in preparation
57.3310 + ** for the next GROUP BY batch.
57.3311 + */
57.3312 + sqlite3VdbeResolveLabel(v, addrGroupByChange);
57.3313 + for(j=0; j<pGroupBy->nExpr; j++){
57.3314 + sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j);
57.3315 + }
57.3316 + sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
57.3317 + VdbeComment((v, "# output one row"));
57.3318 + sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd);
57.3319 + VdbeComment((v, "# check abort flag"));
57.3320 + sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
57.3321 + VdbeComment((v, "# reset accumulator"));
57.3322 +
57.3323 + /* Update the aggregate accumulators based on the content of
57.3324 + ** the current row
57.3325 + */
57.3326 + sqlite3VdbeResolveLabel(v, addrProcessRow);
57.3327 + updateAccumulator(pParse, &sAggInfo);
57.3328 + sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag);
57.3329 + VdbeComment((v, "# indicate data in accumulator"));
57.3330 +
57.3331 + /* End of the loop
57.3332 + */
57.3333 + if( groupBySort ){
57.3334 + sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
57.3335 + }else{
57.3336 + sqlite3WhereEnd(pWInfo);
57.3337 + sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
57.3338 + }
57.3339 +
57.3340 + /* Output the final row of result
57.3341 + */
57.3342 + sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
57.3343 + VdbeComment((v, "# output final row"));
57.3344 +
57.3345 + } /* endif pGroupBy */
57.3346 + else {
57.3347 + /* This case runs if the aggregate has no GROUP BY clause. The
57.3348 + ** processing is much simpler since there is only a single row
57.3349 + ** of output.
57.3350 + */
57.3351 + resetAccumulator(pParse, &sAggInfo);
57.3352 + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
57.3353 + if( pWInfo==0 ) goto select_end;
57.3354 + updateAccumulator(pParse, &sAggInfo);
57.3355 + sqlite3WhereEnd(pWInfo);
57.3356 + finalizeAggFunctions(pParse, &sAggInfo);
57.3357 + pOrderBy = 0;
57.3358 + if( pHaving ){
57.3359 + sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1);
57.3360 + }
57.3361 + selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
57.3362 + eDest, iParm, addrEnd, addrEnd, aff);
57.3363 + }
57.3364 + sqlite3VdbeResolveLabel(v, addrEnd);
57.3365 +
57.3366 + } /* endif aggregate query */
57.3367 +
57.3368 + /* If there is an ORDER BY clause, then we need to sort the results
57.3369 + ** and send them to the callback one by one.
57.3370 + */
57.3371 + if( pOrderBy ){
57.3372 + generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
57.3373 + }
57.3374 +
57.3375 +#ifndef SQLITE_OMIT_SUBQUERY
57.3376 + /* If this was a subquery, we have now converted the subquery into a
57.3377 + ** temporary table. So set the SrcList_item.isPopulated flag to prevent
57.3378 + ** this subquery from being evaluated again and to force the use of
57.3379 + ** the temporary table.
57.3380 + */
57.3381 + if( pParent ){
57.3382 + assert( pParent->pSrc->nSrc>parentTab );
57.3383 + assert( pParent->pSrc->a[parentTab].pSelect==p );
57.3384 + pParent->pSrc->a[parentTab].isPopulated = 1;
57.3385 + }
57.3386 +#endif
57.3387 +
57.3388 + /* Jump here to skip this query
57.3389 + */
57.3390 + sqlite3VdbeResolveLabel(v, iEnd);
57.3391 +
57.3392 + /* The SELECT was successfully coded. Set the return code to 0
57.3393 + ** to indicate no errors.
57.3394 + */
57.3395 + rc = 0;
57.3396 +
57.3397 + /* Control jumps to here if an error is encountered above, or upon
57.3398 + ** successful coding of the SELECT.
57.3399 + */
57.3400 +select_end:
57.3401 +
57.3402 + /* Identify column names if we will be using them in a callback. This
57.3403 + ** step is skipped if the output is going to some other destination.
57.3404 + */
57.3405 + if( rc==SQLITE_OK && eDest==SRT_Callback ){
57.3406 + generateColumnNames(pParse, pTabList, pEList);
57.3407 + }
57.3408 +
57.3409 + sqliteFree(sAggInfo.aCol);
57.3410 + sqliteFree(sAggInfo.aFunc);
57.3411 + return rc;
57.3412 +}
57.3413 +
57.3414 +#if defined(SQLITE_DEBUG)
57.3415 +/*
57.3416 +*******************************************************************************
57.3417 +** The following code is used for testing and debugging only. The code
57.3418 +** that follows does not appear in normal builds.
57.3419 +**
57.3420 +** These routines are used to print out the content of all or part of a
57.3421 +** parse structures such as Select or Expr. Such printouts are useful
57.3422 +** for helping to understand what is happening inside the code generator
57.3423 +** during the execution of complex SELECT statements.
57.3424 +**
57.3425 +** These routine are not called anywhere from within the normal
57.3426 +** code base. Then are intended to be called from within the debugger
57.3427 +** or from temporary "printf" statements inserted for debugging.
57.3428 +*/
57.3429 +void sqlite3PrintExpr(Expr *p){
57.3430 + if( p->token.z && p->token.n>0 ){
57.3431 + sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
57.3432 + }else{
57.3433 + sqlite3DebugPrintf("(%d", p->op);
57.3434 + }
57.3435 + if( p->pLeft ){
57.3436 + sqlite3DebugPrintf(" ");
57.3437 + sqlite3PrintExpr(p->pLeft);
57.3438 + }
57.3439 + if( p->pRight ){
57.3440 + sqlite3DebugPrintf(" ");
57.3441 + sqlite3PrintExpr(p->pRight);
57.3442 + }
57.3443 + sqlite3DebugPrintf(")");
57.3444 +}
57.3445 +void sqlite3PrintExprList(ExprList *pList){
57.3446 + int i;
57.3447 + for(i=0; i<pList->nExpr; i++){
57.3448 + sqlite3PrintExpr(pList->a[i].pExpr);
57.3449 + if( i<pList->nExpr-1 ){
57.3450 + sqlite3DebugPrintf(", ");
57.3451 + }
57.3452 + }
57.3453 +}
57.3454 +void sqlite3PrintSelect(Select *p, int indent){
57.3455 + sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
57.3456 + sqlite3PrintExprList(p->pEList);
57.3457 + sqlite3DebugPrintf("\n");
57.3458 + if( p->pSrc ){
57.3459 + char *zPrefix;
57.3460 + int i;
57.3461 + zPrefix = "FROM";
57.3462 + for(i=0; i<p->pSrc->nSrc; i++){
57.3463 + struct SrcList_item *pItem = &p->pSrc->a[i];
57.3464 + sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
57.3465 + zPrefix = "";
57.3466 + if( pItem->pSelect ){
57.3467 + sqlite3DebugPrintf("(\n");
57.3468 + sqlite3PrintSelect(pItem->pSelect, indent+10);
57.3469 + sqlite3DebugPrintf("%*s)", indent+8, "");
57.3470 + }else if( pItem->zName ){
57.3471 + sqlite3DebugPrintf("%s", pItem->zName);
57.3472 + }
57.3473 + if( pItem->pTab ){
57.3474 + sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
57.3475 + }
57.3476 + if( pItem->zAlias ){
57.3477 + sqlite3DebugPrintf(" AS %s", pItem->zAlias);
57.3478 + }
57.3479 + if( i<p->pSrc->nSrc-1 ){
57.3480 + sqlite3DebugPrintf(",");
57.3481 + }
57.3482 + sqlite3DebugPrintf("\n");
57.3483 + }
57.3484 + }
57.3485 + if( p->pWhere ){
57.3486 + sqlite3DebugPrintf("%*s WHERE ", indent, "");
57.3487 + sqlite3PrintExpr(p->pWhere);
57.3488 + sqlite3DebugPrintf("\n");
57.3489 + }
57.3490 + if( p->pGroupBy ){
57.3491 + sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
57.3492 + sqlite3PrintExprList(p->pGroupBy);
57.3493 + sqlite3DebugPrintf("\n");
57.3494 + }
57.3495 + if( p->pHaving ){
57.3496 + sqlite3DebugPrintf("%*s HAVING ", indent, "");
57.3497 + sqlite3PrintExpr(p->pHaving);
57.3498 + sqlite3DebugPrintf("\n");
57.3499 + }
57.3500 + if( p->pOrderBy ){
57.3501 + sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
57.3502 + sqlite3PrintExprList(p->pOrderBy);
57.3503 + sqlite3DebugPrintf("\n");
57.3504 + }
57.3505 +}
57.3506 +/* End of the structure debug printing code
57.3507 +*****************************************************************************/
57.3508 +#endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
58.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
58.2 +++ b/extensions/sqlite/sqlite-source/sqlite3.h Sun Jul 29 01:15:31 2007 +0000
58.3 @@ -0,0 +1,2702 @@
58.4 +/*
58.5 +** 2001 September 15
58.6 +**
58.7 +** The author disclaims copyright to this source code. In place of
58.8 +** a legal notice, here is a blessing:
58.9 +**
58.10 +** May you do good and not evil.
58.11 +** May you find forgiveness for yourself and forgive others.
58.12 +** May you share freely, never taking more than you give.
58.13 +**
58.14 +*************************************************************************
58.15 +** This header file defines the interface that the SQLite library
58.16 +** presents to client programs. If a C-function, structure, datatype,
58.17 +** or constant definition does not appear in this file, then it is
58.18 +** not a published API of SQLite, is subject to change without
58.19 +** notice, and should not be referenced by programs that use SQLite.
58.20 +**
58.21 +** Some of the definitions that are in this file are marked as
58.22 +** "experimental". Experimental interfaces are normally new
58.23 +** features recently added to SQLite. We do not anticipate changes
58.24 +** to experimental interfaces but reserve to make minor changes if
58.25 +** experience from use "in the wild" suggest such changes are prudent.
58.26 +**
58.27 +** The official C-language API documentation for SQLite is derived
58.28 +** from comments in this file. This file is the authoritative source
58.29 +** on how SQLite interfaces are suppose to operate.
58.30 +**
58.31 +** The name of this file under configuration management is "sqlite.h.in".
58.32 +** The makefile makes some minor changes to this file (such as inserting
58.33 +** the version number) and changes its name to "sqlite3.h" as
58.34 +** part of the build process.
58.35 +**
58.36 +** @(#) $Id$
58.37 +*/
58.38 +#ifndef _SQLITE3_H_
58.39 +#define _SQLITE3_H_
58.40 +#include <stdarg.h> /* Needed for the definition of va_list */
58.41 +
58.42 +/*
58.43 +** Make sure we can call this stuff from C++.
58.44 +*/
58.45 +#ifdef __cplusplus
58.46 +extern "C" {
58.47 +#endif
58.48 +
58.49 +/*
58.50 +** Make sure these symbols where not defined by some previous header
58.51 +** file.
58.52 +*/
58.53 +#ifdef SQLITE_VERSION
58.54 +# undef SQLITE_VERSION
58.55 +#endif
58.56 +#ifdef SQLITE_VERSION_NUMBER
58.57 +# undef SQLITE_VERSION_NUMBER
58.58 +#endif
58.59 +
58.60 +/*
58.61 +** CAPI3REF: Compile-Time Library Version Numbers
58.62 +**
58.63 +** The version of the SQLite library is contained in the sqlite3.h
58.64 +** header file in a #define named SQLITE_VERSION. The SQLITE_VERSION
58.65 +** macro resolves to a string constant.
58.66 +**
58.67 +** The format of the version string is "X.Y.Z", where
58.68 +** X is the major version number, Y is the minor version number and Z
58.69 +** is the release number. The X.Y.Z might be followed by "alpha" or "beta".
58.70 +** For example "3.1.1beta".
58.71 +**
58.72 +** The X value is always 3 in SQLite. The X value only changes when
58.73 +** backwards compatibility is broken and we intend to never break
58.74 +** backwards compatibility. The Y value only changes when
58.75 +** there are major feature enhancements that are forwards compatible
58.76 +** but not backwards compatible. The Z value is incremented with
58.77 +** each release but resets back to 0 when Y is incremented.
58.78 +**
58.79 +** The SQLITE_VERSION_NUMBER is an integer with the value
58.80 +** (X*1000000 + Y*1000 + Z). For example, for version "3.1.1beta",
58.81 +** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using
58.82 +** version 3.1.1 or greater at compile time, programs may use the test
58.83 +** (SQLITE_VERSION_NUMBER>=3001001).
58.84 +**
58.85 +** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
58.86 +*/
58.87 +#define SQLITE_VERSION "3.4.1"
58.88 +#define SQLITE_VERSION_NUMBER 3004001
58.89 +
58.90 +/*
58.91 +** CAPI3REF: Run-Time Library Version Numbers
58.92 +**
58.93 +** These routines return values equivalent to the header constants
58.94 +** [SQLITE_VERSION] and [SQLITE_VERSION_NUMBER]. The values returned
58.95 +** by this routines should only be different from the header values
58.96 +** if you compile your program using an sqlite3.h header from a
58.97 +** different version of SQLite that the version of the library you
58.98 +** link against.
58.99 +**
58.100 +** The sqlite3_version[] string constant contains the text of the
58.101 +** [SQLITE_VERSION] string. The sqlite3_libversion() function returns
58.102 +** a poiner to the sqlite3_version[] string constant. The function
58.103 +** is provided for DLL users who can only access functions and not
58.104 +** constants within the DLL.
58.105 +*/
58.106 +extern const char sqlite3_version[];
58.107 +const char *sqlite3_libversion(void);
58.108 +int sqlite3_libversion_number(void);
58.109 +
58.110 +/*
58.111 +** CAPI3REF: Database Connection Handle
58.112 +**
58.113 +** Each open SQLite database is represented by pointer to an instance of the
58.114 +** opaque structure named "sqlite3". It is useful to think of an sqlite3
58.115 +** pointer as an object. The [sqlite3_open] interface is its constructor
58.116 +** and [sqlite3_close] is its destructor. There are many other interfaces
58.117 +** (such as [sqlite3_prepare_v2], [sqlite3_create_function], and
58.118 +** [sqlite3_busy_timeout] to name but three) that are methods on this
58.119 +** object.
58.120 +*/
58.121 +typedef struct sqlite3 sqlite3;
58.122 +
58.123 +
58.124 +/*
58.125 +** CAPI3REF: 64-Bit Integer Types
58.126 +**
58.127 +** Some compilers do not support the "long long" datatype. So we have
58.128 +** to do compiler-specific typedefs for 64-bit signed and unsigned integers.
58.129 +**
58.130 +** Many SQLite interface functions require a 64-bit integer arguments.
58.131 +** Those interfaces are declared using this typedef.
58.132 +*/
58.133 +#ifdef SQLITE_INT64_TYPE
58.134 + typedef SQLITE_INT64_TYPE sqlite_int64;
58.135 + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
58.136 +#elif defined(_MSC_VER) || defined(__BORLANDC__)
58.137 + typedef __int64 sqlite_int64;
58.138 + typedef unsigned __int64 sqlite_uint64;
58.139 +#else
58.140 + typedef long long int sqlite_int64;
58.141 + typedef unsigned long long int sqlite_uint64;
58.142 +#endif
58.143 +
58.144 +/*
58.145 +** If compiling for a processor that lacks floating point support,
58.146 +** substitute integer for floating-point
58.147 +*/
58.148 +#ifdef SQLITE_OMIT_FLOATING_POINT
58.149 +# define double sqlite_int64
58.150 +#endif
58.151 +
58.152 +/*
58.153 +** CAPI3REF: Closing A Database Connection
58.154 +**
58.155 +** Call this function with a pointer to a structure that was previously
58.156 +** returned from [sqlite3_open()] and the corresponding database will by
58.157 +** closed.
58.158 +**
58.159 +** All SQL statements prepared using [sqlite3_prepare_v2()] or
58.160 +** [sqlite3_prepare16_v2()] must be destroyed using [sqlite3_finalize()]
58.161 +** before this routine is called. Otherwise, SQLITE_BUSY is returned and the
58.162 +** database connection remains open.
58.163 +*/
58.164 +int sqlite3_close(sqlite3 *);
58.165 +
58.166 +/*
58.167 +** The type for a callback function.
58.168 +** This is legacy and deprecated. It is included for historical
58.169 +** compatibility and is not documented.
58.170 +*/
58.171 +typedef int (*sqlite3_callback)(void*,int,char**, char**);
58.172 +
58.173 +/*
58.174 +** CAPI3REF: One-Step Query Execution Interface
58.175 +**
58.176 +** This interface is used to do a one-time evaluatation of zero
58.177 +** or more SQL statements. UTF-8 text of the SQL statements to
58.178 +** be evaluted is passed in as the second parameter. The statements
58.179 +** are prepared one by one using [sqlite3_prepare()], evaluated
58.180 +** using [sqlite3_step()], then destroyed using [sqlite3_finalize()].
58.181 +**
58.182 +** If one or more of the SQL statements are queries, then
58.183 +** the callback function specified by the 3rd parameter is
58.184 +** invoked once for each row of the query result. This callback
58.185 +** should normally return 0. If the callback returns a non-zero
58.186 +** value then the query is aborted, all subsequent SQL statements
58.187 +** are skipped and the sqlite3_exec() function returns the SQLITE_ABORT.
58.188 +**
58.189 +** The 4th parameter to this interface is an arbitrary pointer that is
58.190 +** passed through to the callback function as its first parameter.
58.191 +**
58.192 +** The 2nd parameter to the callback function is the number of
58.193 +** columns in the query result. The 3rd parameter to the callback
58.194 +** is an array of strings holding the values for each column
58.195 +** as extracted using [sqlite3_column_text()].
58.196 +** The 4th parameter to the callback is an array of strings
58.197 +** obtained using [sqlite3_column_name()] and holding
58.198 +** the names of each column.
58.199 +**
58.200 +** The callback function may be NULL, even for queries. A NULL
58.201 +** callback is not an error. It just means that no callback
58.202 +** will be invoked.
58.203 +**
58.204 +** If an error occurs while parsing or evaluating the SQL (but
58.205 +** not while executing the callback) then an appropriate error
58.206 +** message is written into memory obtained from [sqlite3_malloc()] and
58.207 +** *errmsg is made to point to that message. The calling function
58.208 +** is responsible for freeing the memory that holds the error
58.209 +** message. Use [sqlite3_free()] for this. If errmsg==NULL,
58.210 +** then no error message is ever written.
58.211 +**
58.212 +** The return value is is SQLITE_OK if there are no errors and
58.213 +** some other [SQLITE_OK | return code] if there is an error.
58.214 +** The particular return value depends on the type of error.
58.215 +**
58.216 +*/
58.217 +int sqlite3_exec(
58.218 + sqlite3*, /* An open database */
58.219 + const char *sql, /* SQL to be evaluted */
58.220 + int (*callback)(void*,int,char**,char**), /* Callback function */
58.221 + void *, /* 1st argument to callback */
58.222 + char **errmsg /* Error msg written here */
58.223 +);
58.224 +
58.225 +/*
58.226 +** CAPI3REF: Result Codes
58.227 +** KEYWORDS: SQLITE_OK
58.228 +**
58.229 +** Many SQLite functions return an integer result code from the set shown
58.230 +** above in order to indicates success or failure.
58.231 +**
58.232 +** The result codes above are the only ones returned by SQLite in its
58.233 +** default configuration. However, the [sqlite3_extended_result_codes()]
58.234 +** API can be used to set a database connectoin to return more detailed
58.235 +** result codes.
58.236 +**
58.237 +** See also: [SQLITE_IOERR_READ | extended result codes]
58.238 +**
58.239 +*/
58.240 +#define SQLITE_OK 0 /* Successful result */
58.241 +/* beginning-of-error-codes */
58.242 +#define SQLITE_ERROR 1 /* SQL error or missing database */
58.243 +#define SQLITE_INTERNAL 2 /* NOT USED. Internal logic error in SQLite */
58.244 +#define SQLITE_PERM 3 /* Access permission denied */
58.245 +#define SQLITE_ABORT 4 /* Callback routine requested an abort */
58.246 +#define SQLITE_BUSY 5 /* The database file is locked */
58.247 +#define SQLITE_LOCKED 6 /* A table in the database is locked */
58.248 +#define SQLITE_NOMEM 7 /* A malloc() failed */
58.249 +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */
58.250 +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
58.251 +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
58.252 +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */
58.253 +#define SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */
58.254 +#define SQLITE_FULL 13 /* Insertion failed because database is full */
58.255 +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */
58.256 +#define SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */
58.257 +#define SQLITE_EMPTY 16 /* Database is empty */
58.258 +#define SQLITE_SCHEMA 17 /* The database schema changed */
58.259 +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
58.260 +#define SQLITE_CONSTRAINT 19 /* Abort due to contraint violation */
58.261 +#define SQLITE_MISMATCH 20 /* Data type mismatch */
58.262 +#define SQLITE_MISUSE 21 /* Library used incorrectly */
58.263 +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
58.264 +#define SQLITE_AUTH 23 /* Authorization denied */
58.265 +#define SQLITE_FORMAT 24 /* Auxiliary database format error */
58.266 +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
58.267 +#define SQLITE_NOTADB 26 /* File opened that is not a database file */
58.268 +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
58.269 +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
58.270 +/* end-of-error-codes */
58.271 +
58.272 +/*
58.273 +** CAPI3REF: Extended Result Codes
58.274 +**
58.275 +** In its default configuration, SQLite API routines return one of 26 integer
58.276 +** result codes described at result-codes. However, experience has shown that
58.277 +** many of these result codes are too course-grained. They do not provide as
58.278 +** much information about problems as users might like. In an effort to
58.279 +** address this, newer versions of SQLite (version 3.3.8 and later) include
58.280 +** support for additional result codes that provide more detailed information
58.281 +** about errors. The extended result codes are enabled (or disabled) for
58.282 +** each database
58.283 +** connection using the [sqlite3_extended_result_codes()] API.
58.284 +**
58.285 +** Some of the available extended result codes are listed above.
58.286 +** We expect the number of extended result codes will be expand
58.287 +** over time. Software that uses extended result codes should expect
58.288 +** to see new result codes in future releases of SQLite.
58.289 +**
58.290 +** The symbolic name for an extended result code always contains a related
58.291 +** primary result code as a prefix. Primary result codes contain a single
58.292 +** "_" character. Extended result codes contain two or more "_" characters.
58.293 +** The numeric value of an extended result code can be converted to its
58.294 +** corresponding primary result code by masking off the lower 8 bytes.
58.295 +**
58.296 +** The SQLITE_OK result code will never be extended. It will always
58.297 +** be exactly zero.
58.298 +*/
58.299 +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
58.300 +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
58.301 +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
58.302 +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
58.303 +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
58.304 +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
58.305 +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
58.306 +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
58.307 +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
58.308 +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
58.309 +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
58.310 +
58.311 +/*
58.312 +** CAPI3REF: Enable Or Disable Extended Result Codes
58.313 +**
58.314 +** This routine enables or disables the
58.315 +** [SQLITE_IOERR_READ | extended result codes] feature.
58.316 +** By default, SQLite API routines return one of only 26 integer
58.317 +** [SQLITE_OK | result codes]. When extended result codes
58.318 +** are enabled by this routine, the repetoire of result codes can be
58.319 +** much larger and can (hopefully) provide more detailed information
58.320 +** about the cause of an error.
58.321 +**
58.322 +** The second argument is a boolean value that turns extended result
58.323 +** codes on and off. Extended result codes are off by default for
58.324 +** backwards compatibility with older versions of SQLite.
58.325 +*/
58.326 +int sqlite3_extended_result_codes(sqlite3*, int onoff);
58.327 +
58.328 +/*
58.329 +** CAPI3REF: Last Insert Rowid
58.330 +**
58.331 +** Each entry in an SQLite table has a unique 64-bit signed integer key
58.332 +** called the "rowid". The rowid is always available as an undeclared
58.333 +** column named ROWID, OID, or _ROWID_. If the table has a column of
58.334 +** type INTEGER PRIMARY KEY then that column is another an alias for the
58.335 +** rowid.
58.336 +**
58.337 +** This routine returns the rowid of the most recent INSERT into
58.338 +** the database from the database connection given in the first
58.339 +** argument. If no inserts have ever occurred on this database
58.340 +** connection, zero is returned.
58.341 +**
58.342 +** If an INSERT occurs within a trigger, then the rowid of the
58.343 +** inserted row is returned by this routine as long as the trigger
58.344 +** is running. But once the trigger terminates, the value returned
58.345 +** by this routine reverts to the last value inserted before the
58.346 +** trigger fired.
58.347 +*/
58.348 +sqlite_int64 sqlite3_last_insert_rowid(sqlite3*);
58.349 +
58.350 +/*
58.351 +** CAPI3REF: Count The Number Of Rows Modified
58.352 +**
58.353 +** This function returns the number of database rows that were changed
58.354 +** (or inserted or deleted) by the most recent SQL statement. Only
58.355 +** changes that are directly specified by the INSERT, UPDATE, or
58.356 +** DELETE statement are counted. Auxiliary changes caused by
58.357 +** triggers are not counted. Use the [sqlite3_total_changes()] function
58.358 +** to find the total number of changes including changes caused by triggers.
58.359 +**
58.360 +** Within the body of a trigger, the sqlite3_changes() interface can be
58.361 +** called to find the number of
58.362 +** changes in the most recently completed INSERT, UPDATE, or DELETE
58.363 +** statement within the body of the trigger.
58.364 +**
58.365 +** All changes are counted, even if they were later undone by a
58.366 +** ROLLBACK or ABORT. Except, changes associated with creating and
58.367 +** dropping tables are not counted.
58.368 +**
58.369 +** If a callback invokes [sqlite3_exec()] or [sqlite3_step()] recursively,
58.370 +** then the changes in the inner, recursive call are counted together
58.371 +** with the changes in the outer call.
58.372 +**
58.373 +** SQLite implements the command "DELETE FROM table" without a WHERE clause
58.374 +** by dropping and recreating the table. (This is much faster than going
58.375 +** through and deleting individual elements from the table.) Because of
58.376 +** this optimization, the change count for "DELETE FROM table" will be
58.377 +** zero regardless of the number of elements that were originally in the
58.378 +** table. To get an accurate count of the number of rows deleted, use
58.379 +** "DELETE FROM table WHERE 1" instead.
58.380 +*/
58.381 +int sqlite3_changes(sqlite3*);
58.382 +
58.383 +/*
58.384 +** CAPI3REF: Total Number Of Rows Modified
58.385 +***
58.386 +** This function returns the number of database rows that have been
58.387 +** modified by INSERT, UPDATE or DELETE statements since the database handle
58.388 +** was opened. This includes UPDATE, INSERT and DELETE statements executed
58.389 +** as part of trigger programs. All changes are counted as soon as the
58.390 +** statement that makes them is completed (when the statement handle is
58.391 +** passed to [sqlite3_reset()] or [sqlite_finalise()]).
58.392 +**
58.393 +** See also the [sqlite3_change()] interface.
58.394 +**
58.395 +** SQLite implements the command "DELETE FROM table" without a WHERE clause
58.396 +** by dropping and recreating the table. (This is much faster than going
58.397 +** through and deleting individual elements form the table.) Because of
58.398 +** this optimization, the change count for "DELETE FROM table" will be
58.399 +** zero regardless of the number of elements that were originally in the
58.400 +** table. To get an accurate count of the number of rows deleted, use
58.401 +** "DELETE FROM table WHERE 1" instead.
58.402 +*/
58.403 +int sqlite3_total_changes(sqlite3*);
58.404 +
58.405 +/*
58.406 +** CAPI3REF: Interrupt A Long-Running Query
58.407 +**
58.408 +** This function causes any pending database operation to abort and
58.409 +** return at its earliest opportunity. This routine is typically
58.410 +** called in response to a user action such as pressing "Cancel"
58.411 +** or Ctrl-C where the user wants a long query operation to halt
58.412 +** immediately.
58.413 +**
58.414 +** It is safe to call this routine from a thread different from the
58.415 +** thread that is currently running the database operation.
58.416 +**
58.417 +** The SQL operation that is interrupted will return [SQLITE_INTERRUPT].
58.418 +** If an interrupted operation was an update that is inside an
58.419 +** explicit transaction, then the entire transaction will be rolled
58.420 +** back automatically.
58.421 +*/
58.422 +void sqlite3_interrupt(sqlite3*);
58.423 +
58.424 +/*
58.425 +** CAPI3REF: Determine If An SQL Statement Is Complete
58.426 +**
58.427 +** These functions return true if the given input string comprises
58.428 +** one or more complete SQL statements. For the sqlite3_complete() call,
58.429 +** the parameter must be a nul-terminated UTF-8 string. For
58.430 +** sqlite3_complete16(), a nul-terminated machine byte order UTF-16 string
58.431 +** is required.
58.432 +**
58.433 +** These routines are useful for command-line input to determine if the
58.434 +** currently entered text forms one or more complete SQL statements or
58.435 +** if additional input is needed before sending the statements into
58.436 +** SQLite for parsing. The algorithm is simple. If the
58.437 +** last token other than spaces and comments is a semicolon, then return
58.438 +** true. Actually, the algorithm is a little more complicated than that
58.439 +** in order to deal with triggers, but the basic idea is the same: the
58.440 +** statement is not complete unless it ends in a semicolon.
58.441 +*/
58.442 +int sqlite3_complete(const char *sql);
58.443 +int sqlite3_complete16(const void *sql);
58.444 +
58.445 +/*
58.446 +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
58.447 +**
58.448 +** This routine identifies a callback function that might be invoked
58.449 +** whenever an attempt is made to open a database table
58.450 +** that another thread or process has locked.
58.451 +** If the busy callback is NULL, then [SQLITE_BUSY]
58.452 +** (or sometimes [SQLITE_IOERR_BLOCKED])
58.453 +** is returned immediately upon encountering the lock.
58.454 +** If the busy callback is not NULL, then the
58.455 +** callback will be invoked with two arguments. The
58.456 +** first argument to the handler is a copy of the void* pointer which
58.457 +** is the third argument to this routine. The second argument to
58.458 +** the handler is the number of times that the busy handler has
58.459 +** been invoked for this locking event. If the
58.460 +** busy callback returns 0, then no additional attempts are made to
58.461 +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
58.462 +** If the callback returns non-zero, then another attempt is made to open the
58.463 +** database for reading and the cycle repeats.
58.464 +**
58.465 +** The presence of a busy handler does not guarantee that
58.466 +** it will be invoked when there is lock contention.
58.467 +** If SQLite determines that invoking the busy handler could result in
58.468 +** a deadlock, it will return [SQLITE_BUSY] instead.
58.469 +** Consider a scenario where one process is holding a read lock that
58.470 +** it is trying to promote to a reserved lock and
58.471 +** a second process is holding a reserved lock that it is trying
58.472 +** to promote to an exclusive lock. The first process cannot proceed
58.473 +** because it is blocked by the second and the second process cannot
58.474 +** proceed because it is blocked by the first. If both processes
58.475 +** invoke the busy handlers, neither will make any progress. Therefore,
58.476 +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
58.477 +** will induce the first process to release its read lock and allow
58.478 +** the second process to proceed.
58.479 +**
58.480 +** The default busy callback is NULL.
58.481 +**
58.482 +** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] when
58.483 +** SQLite is in the middle of a large transaction where all the
58.484 +** changes will not fit into the in-memory cache. SQLite will
58.485 +** already hold a RESERVED lock on the database file, but it needs
58.486 +** to promote this lock to EXCLUSIVE so that it can spill cache
58.487 +** pages into the database file without harm to concurrent
58.488 +** readers. If it is unable to promote the lock, then the in-memory
58.489 +** cache will be left in an inconsistent state and so the error
58.490 +** code is promoted from the relatively benign [SQLITE_BUSY] to
58.491 +** the more severe [SQLITE_IOERR_BLOCKED]. This error code promotion
58.492 +** forces an automatic rollback of the changes. See the
58.493 +** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError">
58.494 +** CorruptionFollowingBusyError</a> wiki page for a discussion of why
58.495 +** this is important.
58.496 +**
58.497 +** Sqlite is re-entrant, so the busy handler may start a new query.
58.498 +** (It is not clear why anyone would every want to do this, but it
58.499 +** is allowed, in theory.) But the busy handler may not close the
58.500 +** database. Closing the database from a busy handler will delete
58.501 +** data structures out from under the executing query and will
58.502 +** probably result in a segmentation fault or other runtime error.
58.503 +**
58.504 +** There can only be a single busy handler defined for each database
58.505 +** connection. Setting a new busy handler clears any previous one.
58.506 +** Note that calling [sqlite3_busy_timeout()] will also set or clear
58.507 +** the busy handler.
58.508 +*/
58.509 +int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
58.510 +
58.511 +/*
58.512 +** CAPI3REF: Set A Busy Timeout
58.513 +**
58.514 +** This routine sets a busy handler that sleeps for a while when a
58.515 +** table is locked. The handler will sleep multiple times until
58.516 +** at least "ms" milliseconds of sleeping have been done. After
58.517 +** "ms" milliseconds of sleeping, the handler returns 0 which
58.518 +** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
58.519 +**
58.520 +** Calling this routine with an argument less than or equal to zero
58.521 +** turns off all busy handlers.
58.522 +**
58.523 +** There can only be a single busy handler for a particular database
58.524 +** connection. If another busy handler was defined
58.525 +** (using [sqlite3_busy_handler()]) prior to calling
58.526 +** this routine, that other busy handler is cleared.
58.527 +*/
58.528 +int sqlite3_busy_timeout(sqlite3*, int ms);
58.529 +
58.530 +/*
58.531 +** CAPI3REF: Convenience Routines For Running Queries
58.532 +**
58.533 +** This next routine is a convenience wrapper around [sqlite3_exec()].
58.534 +** Instead of invoking a user-supplied callback for each row of the
58.535 +** result, this routine remembers each row of the result in memory
58.536 +** obtained from [sqlite3_malloc()], then returns all of the result after the
58.537 +** query has finished.
58.538 +**
58.539 +** As an example, suppose the query result where this table:
58.540 +**
58.541 +** <pre>
58.542 +** Name | Age
58.543 +** -----------------------
58.544 +** Alice | 43
58.545 +** Bob | 28
58.546 +** Cindy | 21
58.547 +** </pre>
58.548 +**
58.549 +** If the 3rd argument were &azResult then after the function returns
58.550 +** azResult will contain the following data:
58.551 +**
58.552 +** <pre>
58.553 +** azResult[0] = "Name";
58.554 +** azResult[1] = "Age";
58.555 +** azResult[2] = "Alice";
58.556 +** azResult[3] = "43";
58.557 +** azResult[4] = "Bob";
58.558 +** azResult[5] = "28";
58.559 +** azResult[6] = "Cindy";
58.560 +** azResult[7] = "21";
58.561 +** </pre>
58.562 +**
58.563 +** Notice that there is an extra row of data containing the column
58.564 +** headers. But the *nrow return value is still 3. *ncolumn is
58.565 +** set to 2. In general, the number of values inserted into azResult
58.566 +** will be ((*nrow) + 1)*(*ncolumn).
58.567 +**
58.568 +** After the calling function has finished using the result, it should
58.569 +** pass the result data pointer to sqlite3_free_table() in order to
58.570 +** release the memory that was malloc-ed. Because of the way the
58.571 +** [sqlite3_malloc()] happens, the calling function must not try to call
58.572 +** [sqlite3_free()] directly. Only [sqlite3_free_table()] is able to release
58.573 +** the memory properly and safely.
58.574 +**
58.575 +** The return value of this routine is the same as from [sqlite3_exec()].
58.576 +*/
58.577 +int sqlite3_get_table(
58.578 + sqlite3*, /* An open database */
58.579 + const char *sql, /* SQL to be executed */
58.580 + char ***resultp, /* Result written to a char *[] that this points to */
58.581 + int *nrow, /* Number of result rows written here */
58.582 + int *ncolumn, /* Number of result columns written here */
58.583 + char **errmsg /* Error msg written here */
58.584 +);
58.585 +void sqlite3_free_table(char **result);
58.586 +
58.587 +/*
58.588 +** CAPI3REF: Formatted String Printing Functions
58.589 +**
58.590 +** These routines are workalikes of the "printf()" family of functions
58.591 +** from the standard C library.
58.592 +**
58.593 +** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
58.594 +** results into memory obtained from [sqlite_malloc()].
58.595 +** The strings returned by these two routines should be
58.596 +** released by [sqlite3_free()]. Both routines return a
58.597 +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
58.598 +** memory to hold the resulting string.
58.599 +**
58.600 +** In sqlite3_snprintf() routine is similar to "snprintf()" from
58.601 +** the standard C library. The result is written into the
58.602 +** buffer supplied as the second parameter whose size is given by
58.603 +** the first parameter. Note that the order of the
58.604 +** first two parameters is reversed from snprintf(). This is an
58.605 +** historical accident that cannot be fixed without breaking
58.606 +** backwards compatibility. Note also that sqlite3_snprintf()
58.607 +** returns a pointer to its buffer instead of the number of
58.608 +** characters actually written into the buffer. We admit that
58.609 +** the number of characters written would be a more useful return
58.610 +** value but we cannot change the implementation of sqlite3_snprintf()
58.611 +** now without breaking compatibility.
58.612 +**
58.613 +** As long as the buffer size is greater than zero, sqlite3_snprintf()
58.614 +** guarantees that the buffer is always zero-terminated. The first
58.615 +** parameter "n" is the total size of the buffer, including space for
58.616 +** the zero terminator. So the longest string that can be completely
58.617 +** written will be n-1 characters.
58.618 +**
58.619 +** These routines all implement some additional formatting
58.620 +** options that are useful for constructing SQL statements.
58.621 +** All of the usual printf formatting options apply. In addition, there
58.622 +** is are "%q" and "%Q" options.
58.623 +**
58.624 +** The %q option works like %s in that it substitutes a null-terminated
58.625 +** string from the argument list. But %q also doubles every '\'' character.
58.626 +** %q is designed for use inside a string literal. By doubling each '\''
58.627 +** character it escapes that character and allows it to be inserted into
58.628 +** the string.
58.629 +**
58.630 +** For example, so some string variable contains text as follows:
58.631 +**
58.632 +** <blockquote><pre>
58.633 +** char *zText = "It's a happy day!";
58.634 +** </pre></blockquote>
58.635 +**
58.636 +** One can use this text in an SQL statement as follows:
58.637 +**
58.638 +** <blockquote><pre>
58.639 +** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
58.640 +** sqlite3_exec(db, zSQL, 0, 0, 0);
58.641 +** sqlite3_free(zSQL);
58.642 +** </pre></blockquote>
58.643 +**
58.644 +** Because the %q format string is used, the '\'' character in zText
58.645 +** is escaped and the SQL generated is as follows:
58.646 +**
58.647 +** <blockquote><pre>
58.648 +** INSERT INTO table1 VALUES('It''s a happy day!')
58.649 +** </pre></blockquote>
58.650 +**
58.651 +** This is correct. Had we used %s instead of %q, the generated SQL
58.652 +** would have looked like this:
58.653 +**
58.654 +** <blockquote><pre>
58.655 +** INSERT INTO table1 VALUES('It's a happy day!');
58.656 +** </pre></blockquote>
58.657 +**
58.658 +** This second example is an SQL syntax error. As a general rule you
58.659 +** should always use %q instead of %s when inserting text into a string
58.660 +** literal.
58.661 +**
58.662 +** The %Q option works like %q except it also adds single quotes around
58.663 +** the outside of the total string. Or if the parameter in the argument
58.664 +** list is a NULL pointer, %Q substitutes the text "NULL" (without single
58.665 +** quotes) in place of the %Q option. So, for example, one could say:
58.666 +**
58.667 +** <blockquote><pre>
58.668 +** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
58.669 +** sqlite3_exec(db, zSQL, 0, 0, 0);
58.670 +** sqlite3_free(zSQL);
58.671 +** </pre></blockquote>
58.672 +**
58.673 +** The code above will render a correct SQL statement in the zSQL
58.674 +** variable even if the zText variable is a NULL pointer.
58.675 +*/
58.676 +char *sqlite3_mprintf(const char*,...);
58.677 +char *sqlite3_vmprintf(const char*, va_list);
58.678 +char *sqlite3_snprintf(int,char*,const char*, ...);
58.679 +
58.680 +/*
58.681 +** CAPI3REF: Memory Allocation Functions
58.682 +**
58.683 +** SQLite uses its own memory allocator. On some installations, this
58.684 +** memory allocator is identical to the standard malloc()/realloc()/free()
58.685 +** and can be used interchangable. On others, the implementations are
58.686 +** different. For maximum portability, it is best not to mix calls
58.687 +** to the standard malloc/realloc/free with the sqlite versions.
58.688 +*/
58.689 +void *sqlite3_malloc(int);
58.690 +void *sqlite3_realloc(void*, int);
58.691 +void sqlite3_free(void*);
58.692 +
58.693 +/*
58.694 +** CAPI3REF: Compile-Time Authorization Callbacks
58.695 +***
58.696 +** This routine registers a authorizer callback with the SQLite library.
58.697 +** The authorizer callback is invoked as SQL statements are being compiled
58.698 +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
58.699 +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. At various
58.700 +** points during the compilation process, as logic is being created
58.701 +** to perform various actions, the authorizer callback is invoked to
58.702 +** see if those actions are allowed. The authorizer callback should
58.703 +** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the
58.704 +** specific action but allow the SQL statement to continue to be
58.705 +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
58.706 +** rejected with an error.
58.707 +**
58.708 +** Depending on the action, the [SQLITE_IGNORE] and [SQLITE_DENY] return
58.709 +** codes might mean something different or they might mean the same
58.710 +** thing. If the action is, for example, to perform a delete opertion,
58.711 +** then [SQLITE_IGNORE] and [SQLITE_DENY] both cause the statement compilation
58.712 +** to fail with an error. But if the action is to read a specific column
58.713 +** from a specific table, then [SQLITE_DENY] will cause the entire
58.714 +** statement to fail but [SQLITE_IGNORE] will cause a NULL value to be
58.715 +** read instead of the actual column value.
58.716 +**
58.717 +** The first parameter to the authorizer callback is a copy of
58.718 +** the third parameter to the sqlite3_set_authorizer() interface.
58.719 +** The second parameter to the callback is an integer
58.720 +** [SQLITE_COPY | action code] that specifies the particular action
58.721 +** to be authorized. The available action codes are
58.722 +** [SQLITE_COPY | documented separately]. The third through sixth
58.723 +** parameters to the callback are strings that contain additional
58.724 +** details about the action to be authorized.
58.725 +**
58.726 +** An authorizer is used when preparing SQL statements from an untrusted
58.727 +** source, to ensure that the SQL statements do not try to access data
58.728 +** that they are not allowed to see, or that they do not try to
58.729 +** execute malicious statements that damage the database. For
58.730 +** example, an application may allow a user to enter arbitrary
58.731 +** SQL queries for evaluation by a database. But the application does
58.732 +** not want the user to be able to make arbitrary changes to the
58.733 +** database. An authorizer could then be put in place while the
58.734 +** user-entered SQL is being prepared that disallows everything
58.735 +** except SELECT statements.
58.736 +**
58.737 +** Only a single authorizer can be in place on a database connection
58.738 +** at a time. Each call to sqlite3_set_authorizer overrides the
58.739 +** previous call. A NULL authorizer means that no authorization
58.740 +** callback is invoked. The default authorizer is NULL.
58.741 +**
58.742 +** Note that the authorizer callback is invoked only during
58.743 +** [sqlite3_prepare()] or its variants. Authorization is not
58.744 +** performed during statement evaluation in [sqlite3_step()].
58.745 +*/
58.746 +int sqlite3_set_authorizer(
58.747 + sqlite3*,
58.748 + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
58.749 + void *pUserData
58.750 +);
58.751 +
58.752 +/*
58.753 +** CAPI3REF: Authorizer Return Codes
58.754 +**
58.755 +** The [sqlite3_set_authorizer | authorizer callback function] must
58.756 +** return either [SQLITE_OK] or one of these two constants in order
58.757 +** to signal SQLite whether or not the action is permitted. See the
58.758 +** [sqlite3_set_authorizer | authorizer documentation] for additional
58.759 +** information.
58.760 +*/
58.761 +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */
58.762 +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
58.763 +
58.764 +/*
58.765 +** CAPI3REF: Authorizer Action Codes
58.766 +**
58.767 +** The [sqlite3_set_authorizer()] interface registers a callback function
58.768 +** that is invoked to authorizer certain SQL statement actions. The
58.769 +** second parameter to the callback is an integer code that specifies
58.770 +** what action is being authorized. These are the integer action codes that
58.771 +** the authorizer callback may be passed.
58.772 +**
58.773 +** These action code values signify what kind of operation is to be
58.774 +** authorized. The 3rd and 4th parameters to the authorization callback
58.775 +** function will be parameters or NULL depending on which of these
58.776 +** codes is used as the second parameter. The 5th parameter to the
58.777 +** authorizer callback is the name of the database ("main", "temp",
58.778 +** etc.) if applicable. The 6th parameter to the authorizer callback
58.779 +** is the name of the inner-most trigger or view that is responsible for
58.780 +** the access attempt or NULL if this access attempt is directly from
58.781 +** top-level SQL code.
58.782 +*/
58.783 +/******************************************* 3rd ************ 4th ***********/
58.784 +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
58.785 +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
58.786 +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
58.787 +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
58.788 +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
58.789 +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
58.790 +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
58.791 +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */
58.792 +#define SQLITE_DELETE 9 /* Table Name NULL */
58.793 +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
58.794 +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */
58.795 +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
58.796 +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
58.797 +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
58.798 +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
58.799 +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
58.800 +#define SQLITE_DROP_VIEW 17 /* View Name NULL */
58.801 +#define SQLITE_INSERT 18 /* Table Name NULL */
58.802 +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
58.803 +#define SQLITE_READ 20 /* Table Name Column Name */
58.804 +#define SQLITE_SELECT 21 /* NULL NULL */
58.805 +#define SQLITE_TRANSACTION 22 /* NULL NULL */
58.806 +#define SQLITE_UPDATE 23 /* Table Name Column Name */
58.807 +#define SQLITE_ATTACH 24 /* Filename NULL */
58.808 +#define SQLITE_DETACH 25 /* Database Name NULL */
58.809 +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
58.810 +#define SQLITE_REINDEX 27 /* Index Name NULL */
58.811 +#define SQLITE_ANALYZE 28 /* Table Name NULL */
58.812 +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
58.813 +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
58.814 +#define SQLITE_FUNCTION 31 /* Function Name NULL */
58.815 +#define SQLITE_COPY 0 /* No longer used */
58.816 +
58.817 +/*
58.818 +** CAPI3REF: Tracing And Profiling Functions
58.819 +**
58.820 +** These routines register callback functions that can be used for
58.821 +** tracing and profiling the execution of SQL statements.
58.822 +** The callback function registered by sqlite3_trace() is invoked
58.823 +** at the first [sqlite3_step()] for the evaluation of an SQL statement.
58.824 +** The callback function registered by sqlite3_profile() is invoked
58.825 +** as each SQL statement finishes and includes
58.826 +** information on how long that statement ran.
58.827 +**
58.828 +** The sqlite3_profile() API is currently considered experimental and
58.829 +** is subject to change.
58.830 +*/
58.831 +void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
58.832 +void *sqlite3_profile(sqlite3*,
58.833 + void(*xProfile)(void*,const char*,sqlite_uint64), void*);
58.834 +
58.835 +/*
58.836 +** CAPI3REF: Query Progress Callbacks
58.837 +**
58.838 +** This routine configures a callback function - the progress callback - that
58.839 +** is invoked periodically during long running calls to [sqlite3_exec()],
58.840 +** [sqlite3_step()] and [sqlite3_get_table()]. An example use for this
58.841 +** interface is to keep a GUI updated during a large query.
58.842 +**
58.843 +** The progress callback is invoked once for every N virtual machine opcodes,
58.844 +** where N is the second argument to this function. The progress callback
58.845 +** itself is identified by the third argument to this function. The fourth
58.846 +** argument to this function is a void pointer passed to the progress callback
58.847 +** function each time it is invoked.
58.848 +**
58.849 +** If a call to [sqlite3_exec()], [sqlite3_step()], or [sqlite3_get_table()]
58.850 +** results in fewer than N opcodes being executed, then the progress
58.851 +** callback is never invoked.
58.852 +**
58.853 +** Only a single progress callback function may be registered for each
58.854 +** open database connection. Every call to sqlite3_progress_handler()
58.855 +** overwrites the results of the previous call.
58.856 +** To remove the progress callback altogether, pass NULL as the third
58.857 +** argument to this function.
58.858 +**
58.859 +** If the progress callback returns a result other than 0, then the current
58.860 +** query is immediately terminated and any database changes rolled back.
58.861 +** The containing [sqlite3_exec()], [sqlite3_step()], or
58.862 +** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. This feature
58.863 +** can be used, for example, to implement the "Cancel" button on a
58.864 +** progress dialog box in a GUI.
58.865 +*/
58.866 +void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
58.867 +
58.868 +/*
58.869 +** CAPI3REF: Opening A New Database Connection
58.870 +**
58.871 +** Open the sqlite database file "filename". The "filename" is UTF-8
58.872 +** encoded for sqlite3_open() and UTF-16 encoded in the native byte order
58.873 +** for sqlite3_open16(). An [sqlite3*] handle is returned in *ppDb, even
58.874 +** if an error occurs. If the database is opened (or created) successfully,
58.875 +** then SQLITE_OK is returned. Otherwise an error code is returned. The
58.876 +** sqlite3_errmsg() or sqlite3_errmsg16() routines can be used to obtain
58.877 +** an English language description of the error.
58.878 +**
58.879 +** If the database file does not exist, then a new database will be created
58.880 +** as needed. The default encoding for the database will be UTF-8 if
58.881 +** sqlite3_open() is called and UTF-16 if sqlite3_open16 is used.
58.882 +**
58.883 +** Whether or not an error occurs when it is opened, resources associated
58.884 +** with the [sqlite3*] handle should be released by passing it to
58.885 +** sqlite3_close() when it is no longer required.
58.886 +**
58.887 +** Note to windows users: The encoding used for the filename argument
58.888 +** of sqlite3_open() must be UTF-8, not whatever codepage is currently
58.889 +** defined. Filenames containing international characters must be converted
58.890 +** to UTF-8 prior to passing them into sqlite3_open().
58.891 +*/
58.892 +int sqlite3_open(
58.893 + const char *filename, /* Database filename (UTF-8) */
58.894 + sqlite3 **ppDb /* OUT: SQLite db handle */
58.895 +);
58.896 +int sqlite3_open16(
58.897 + const void *filename, /* Database filename (UTF-16) */
58.898 + sqlite3 **ppDb /* OUT: SQLite db handle */
58.899 +);
58.900 +
58.901 +/*
58.902 +** CAPI3REF: Error Codes And Messages
58.903 +**
58.904 +** The sqlite3_errcode() interface returns the numeric
58.905 +** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code]
58.906 +** for the most recent failed sqlite3_* API call associated
58.907 +** with [sqlite3] handle 'db'. If a prior API call failed but the
58.908 +** most recent API call succeeded, the return value from sqlite3_errcode()
58.909 +** is undefined.
58.910 +**
58.911 +** The sqlite3_errmsg() and sqlite3_errmsg16() return English-langauge
58.912 +** text that describes the error, as either UTF8 or UTF16 respectively.
58.913 +** Memory to hold the error message string is managed internally. The
58.914 +** string may be overwritten or deallocated by subsequent calls to SQLite
58.915 +** interface functions.
58.916 +**
58.917 +** Calls to many sqlite3_* functions set the error code and string returned
58.918 +** by [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()]
58.919 +** (overwriting the previous values). Note that calls to [sqlite3_errcode()],
58.920 +** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the
58.921 +** results of future invocations. Calls to API routines that do not return
58.922 +** an error code (examples: [sqlite3_data_count()] or [sqlite3_mprintf()]) do
58.923 +** not change the error code returned by this routine.
58.924 +**
58.925 +** Assuming no other intervening sqlite3_* API calls are made, the error
58.926 +** code returned by this function is associated with the same error as
58.927 +** the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()].
58.928 +*/
58.929 +int sqlite3_errcode(sqlite3 *db);
58.930 +const char *sqlite3_errmsg(sqlite3*);
58.931 +const void *sqlite3_errmsg16(sqlite3*);
58.932 +
58.933 +/*
58.934 +** CAPI3REF: SQL Statement Object
58.935 +**
58.936 +** Instance of this object represent single SQL statements. This
58.937 +** is variously known as a "prepared statement" or a
58.938 +** "compiled SQL statement" or simply as a "statement".
58.939 +**
58.940 +** The life of a statement object goes something like this:
58.941 +**
58.942 +** <ol>
58.943 +** <li> Create the object using [sqlite3_prepare_v2()] or a related
58.944 +** function.
58.945 +** <li> Bind values to host parameters using
58.946 +** [sqlite3_bind_blob | sqlite3_bind_* interfaces].
58.947 +** <li> Run the SQL by calling [sqlite3_step()] one or more times.
58.948 +** <li> Reset the statement using [sqlite3_reset()] then go back
58.949 +** to step 2. Do this zero or more times.
58.950 +** <li> Destroy the object using [sqlite3_finalize()].
58.951 +** </ol>
58.952 +**
58.953 +** Refer to documentation on individual methods above for additional
58.954 +** information.
58.955 +*/
58.956 +typedef struct sqlite3_stmt sqlite3_stmt;
58.957 +
58.958 +/*
58.959 +** CAPI3REF: Compiling An SQL Statement
58.960 +**
58.961 +** To execute an SQL query, it must first be compiled into a byte-code
58.962 +** program using one of these routines.
58.963 +**
58.964 +** The first argument "db" is an [sqlite3 | SQLite database handle]
58.965 +** obtained from a prior call to [sqlite3_open()] or [sqlite3_open16()].
58.966 +** The second argument "zSql" is the statement to be compiled, encoded
58.967 +** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
58.968 +** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2()
58.969 +** use UTF-16.
58.970 +**
58.971 +** If the nByte argument is less
58.972 +** than zero, then zSql is read up to the first zero terminator. If
58.973 +** nByte is non-negative, then it is the maximum number of
58.974 +** bytes read from zSql. When nByte is non-negative, the
58.975 +** zSql string ends at either the first '\000' character or
58.976 +** until the nByte-th byte, whichever comes first.
58.977 +**
58.978 +** *pzTail is made to point to the first byte past the end of the first
58.979 +** SQL statement in zSql. This routine only compiles the first statement
58.980 +** in zSql, so *pzTail is left pointing to what remains uncompiled.
58.981 +**
58.982 +** *ppStmt is left pointing to a compiled
58.983 +** [sqlite3_stmt | SQL statement structure] that can be
58.984 +** executed using [sqlite3_step()]. Or if there is an error, *ppStmt may be
58.985 +** set to NULL. If the input text contained no SQL (if the input is and
58.986 +** empty string or a comment) then *ppStmt is set to NULL. The calling
58.987 +** procedure is responsible for deleting the compiled SQL statement
58.988 +** using [sqlite3_finalize()] after it has finished with it.
58.989 +**
58.990 +** On success, [SQLITE_OK] is returned. Otherwise an
58.991 +** [SQLITE_ERROR | error code] is returned.
58.992 +**
58.993 +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
58.994 +** recommended for all new programs. The two older interfaces are retained
58.995 +** for backwards compatibility, but their use is discouraged.
58.996 +** In the "v2" interfaces, the prepared statement
58.997 +** that is returned (the [sqlite3_stmt] object) contains a copy of the
58.998 +** original SQL text. This causes the [sqlite3_step()] interface to
58.999 +** behave a differently in two ways:
58.1000 +**
58.1001 +** <ol>
58.1002 +** <li>
58.1003 +** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
58.1004 +** always used to do, [sqlite3_step()] will automatically recompile the SQL
58.1005 +** statement and try to run it again. If the schema has changed in a way
58.1006 +** that makes the statement no longer valid, [sqlite3_step()] will still
58.1007 +** return [SQLITE_SCHEMA]. But unlike the legacy behavior, [SQLITE_SCHEMA] is
58.1008 +** now a fatal error. Calling [sqlite3_prepare_v2()] again will not make the
58.1009 +** error go away. Note: use [sqlite3_errmsg()] to find the text of the parsing
58.1010 +** error that results in an [SQLITE_SCHEMA] return.
58.1011 +** </li>
58.1012 +**
58.1013 +** <li>
58.1014 +** When an error occurs,
58.1015 +** [sqlite3_step()] will return one of the detailed
58.1016 +** [SQLITE_ERROR | result codes] or
58.1017 +** [SQLITE_IOERR_READ | extended result codes] such as directly.
58.1018 +** The legacy behavior was that [sqlite3_step()] would only return a generic
58.1019 +** [SQLITE_ERROR] result code and you would have to make a second call to
58.1020 +** [sqlite3_reset()] in order to find the underlying cause of the problem.
58.1021 +** With the "v2" prepare interfaces, the underlying reason for the error is
58.1022 +** returned immediately.
58.1023 +** </li>
58.1024 +** </ol>
58.1025 +*/
58.1026 +int sqlite3_prepare(
58.1027 + sqlite3 *db, /* Database handle */
58.1028 + const char *zSql, /* SQL statement, UTF-8 encoded */
58.1029 + int nByte, /* Maximum length of zSql in bytes. */
58.1030 + sqlite3_stmt **ppStmt, /* OUT: Statement handle */
58.1031 + const char **pzTail /* OUT: Pointer to unused portion of zSql */
58.1032 +);
58.1033 +int sqlite3_prepare_v2(
58.1034 + sqlite3 *db, /* Database handle */
58.1035 + const char *zSql, /* SQL statement, UTF-8 encoded */
58.1036 + int nByte, /* Maximum length of zSql in bytes. */
58.1037 + sqlite3_stmt **ppStmt, /* OUT: Statement handle */
58.1038 + const char **pzTail /* OUT: Pointer to unused portion of zSql */
58.1039 +);
58.1040 +int sqlite3_prepare16(
58.1041 + sqlite3 *db, /* Database handle */
58.1042 + const void *zSql, /* SQL statement, UTF-16 encoded */
58.1043 + int nByte, /* Maximum length of zSql in bytes. */
58.1044 + sqlite3_stmt **ppStmt, /* OUT: Statement handle */
58.1045 + const void **pzTail /* OUT: Pointer to unused portion of zSql */
58.1046 +);
58.1047 +int sqlite3_prepare16_v2(
58.1048 + sqlite3 *db, /* Database handle */
58.1049 + const void *zSql, /* SQL statement, UTF-16 encoded */
58.1050 + int nByte, /* Maximum length of zSql in bytes. */
58.1051 + sqlite3_stmt **ppStmt, /* OUT: Statement handle */
58.1052 + const void **pzTail /* OUT: Pointer to unused portion of zSql */
58.1053 +);
58.1054 +
58.1055 +/*
58.1056 +** CAPI3REF: Dynamically Typed Value Object
58.1057 +**
58.1058 +** SQLite uses dynamic typing for the values it stores. Values can
58.1059 +** be integers, floating point values, strings, BLOBs, or NULL. When
58.1060 +** passing around values internally, each value is represented as
58.1061 +** an instance of the sqlite3_value object.
58.1062 +*/
58.1063 +typedef struct Mem sqlite3_value;
58.1064 +
58.1065 +/*
58.1066 +** CAPI3REF: SQL Function Context Object
58.1067 +**
58.1068 +** The context in which an SQL function executes is stored in an
58.1069 +** sqlite3_context object. A pointer to such an object is the
58.1070 +** first parameter to user-defined SQL functions.
58.1071 +*/
58.1072 +typedef struct sqlite3_context sqlite3_context;
58.1073 +
58.1074 +/*
58.1075 +** CAPI3REF: Binding Values To Prepared Statements
58.1076 +**
58.1077 +** In the SQL strings input to [sqlite3_prepare_v2()] and its variants,
58.1078 +** one or more literals can be replace by a parameter in one of these
58.1079 +** forms:
58.1080 +**
58.1081 +** <ul>
58.1082 +** <li> ?
58.1083 +** <li> ?NNN
58.1084 +** <li> :AAA
58.1085 +** <li> @AAA
58.1086 +** <li> $VVV
58.1087 +** </ul>
58.1088 +**
58.1089 +** In the parameter forms shown above NNN is an integer literal,
58.1090 +** AAA is an alphanumeric identifier and VVV is a variable name according
58.1091 +** to the syntax rules of the TCL programming language.
58.1092 +** The values of these parameters (also called "host parameter names")
58.1093 +** can be set using the sqlite3_bind_*() routines defined here.
58.1094 +**
58.1095 +** The first argument to the sqlite3_bind_*() routines always is a pointer
58.1096 +** to the [sqlite3_stmt] object returned from [sqlite3_prepare_v2()] or
58.1097 +** its variants. The second
58.1098 +** argument is the index of the parameter to be set. The first parameter has
58.1099 +** an index of 1. When the same named parameter is used more than once, second
58.1100 +** and subsequent
58.1101 +** occurrences have the same index as the first occurrence. The index for
58.1102 +** named parameters can be looked up using the
58.1103 +** [sqlite3_bind_parameter_name()] API if desired. The index for "?NNN"
58.1104 +** parametes is the value of NNN.
58.1105 +** The NNN value must be between 1 and the compile-time
58.1106 +** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999).
58.1107 +** See <a href="limits.html">limits.html</a> for additional information.
58.1108 +**
58.1109 +** The third argument is the value to bind to the parameter.
58.1110 +**
58.1111 +** In those
58.1112 +** routines that have a fourth argument, its value is the number of bytes
58.1113 +** in the parameter. To be clear: the value is the number of bytes in the
58.1114 +** string, not the number of characters. The number
58.1115 +** of bytes does not include the zero-terminator at the end of strings.
58.1116 +** If the fourth parameter is negative, the length of the string is
58.1117 +** number of bytes up to the first zero terminator.
58.1118 +**
58.1119 +** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
58.1120 +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
58.1121 +** text after SQLite has finished with it. If the fifth argument is the
58.1122 +** special value [SQLITE_STATIC], then the library assumes that the information
58.1123 +** is in static, unmanaged space and does not need to be freed. If the
58.1124 +** fifth argument has the value [SQLITE_TRANSIENT], then SQLite makes its
58.1125 +** own private copy of the data immediately, before the sqlite3_bind_*()
58.1126 +** routine returns.
58.1127 +**
58.1128 +** The sqlite3_bind_zeroblob() routine binds a BLOB of length n that
58.1129 +** is filled with zeros. A zeroblob uses a fixed amount of memory
58.1130 +** (just an integer to hold it size) while it is being processed.
58.1131 +** Zeroblobs are intended to serve as place-holders for BLOBs whose
58.1132 +** content is later written using
58.1133 +** [sqlite3_blob_open | increment BLOB I/O] routines.
58.1134 +**
58.1135 +** The sqlite3_bind_*() routines must be called after
58.1136 +** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
58.1137 +** before [sqlite3_step()].
58.1138 +** Bindings are not cleared by the [sqlite3_reset()] routine.
58.1139 +** Unbound parameters are interpreted as NULL.
58.1140 +**
58.1141 +** These routines return [SQLITE_OK] on success or an error code if
58.1142 +** anything goes wrong. [SQLITE_RANGE] is returned if the parameter
58.1143 +** index is out of range. [SQLITE_NOMEM] is returned if malloc fails.
58.1144 +** [SQLITE_MISUSE] is returned if these routines are called on a virtual
58.1145 +** machine that is the wrong state or which has already been finalized.
58.1146 +*/
58.1147 +int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
58.1148 +int sqlite3_bind_double(sqlite3_stmt*, int, double);
58.1149 +int sqlite3_bind_int(sqlite3_stmt*, int, int);
58.1150 +int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite_int64);
58.1151 +int sqlite3_bind_null(sqlite3_stmt*, int);
58.1152 +int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
58.1153 +int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
58.1154 +int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
58.1155 +int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
58.1156 +
58.1157 +/*
58.1158 +** CAPI3REF: Number Of Host Parameters
58.1159 +**
58.1160 +** Return the largest host parameter index in the precompiled statement given
58.1161 +** as the argument. When the host parameters are of the forms like ":AAA"
58.1162 +** or "?", then they are assigned sequential increasing numbers beginning
58.1163 +** with one, so the value returned is the number of parameters. However
58.1164 +** if the same host parameter name is used multiple times, each occurrance
58.1165 +** is given the same number, so the value returned in that case is the number
58.1166 +** of unique host parameter names. If host parameters of the form "?NNN"
58.1167 +** are used (where NNN is an integer) then there might be gaps in the
58.1168 +** numbering and the value returned by this interface is the index of the
58.1169 +** host parameter with the largest index value.
58.1170 +*/
58.1171 +int sqlite3_bind_parameter_count(sqlite3_stmt*);
58.1172 +
58.1173 +/*
58.1174 +** CAPI3REF: Name Of A Host Parameter
58.1175 +**
58.1176 +** This routine returns a pointer to the name of the n-th parameter in a
58.1177 +** [sqlite3_stmt | prepared statement].
58.1178 +** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name
58.1179 +** which is the string ":AAA" or "@AAA" or "$VVV".
58.1180 +** In other words, the initial ":" or "$" or "@"
58.1181 +** is included as part of the name.
58.1182 +** Parameters of the form "?" or "?NNN" have no name.
58.1183 +**
58.1184 +** The first bound parameter has an index of 1, not 0.
58.1185 +**
58.1186 +** If the value n is out of range or if the n-th parameter is nameless,
58.1187 +** then NULL is returned. The returned string is always in the
58.1188 +** UTF-8 encoding even if the named parameter was originally specified
58.1189 +** as UTF-16 in [sqlite3_prepare16()] or [sqlite3_prepare16_v2()].
58.1190 +*/
58.1191 +const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
58.1192 +
58.1193 +/*
58.1194 +** CAPI3REF: Index Of A Parameter With A Given Name
58.1195 +**
58.1196 +** This routine returns the index of a host parameter with the given name.
58.1197 +** The name must match exactly. If no parameter with the given name is
58.1198 +** found, return 0. Parameter names must be UTF8.
58.1199 +*/
58.1200 +int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
58.1201 +
58.1202 +/*
58.1203 +** CAPI3REF: Reset All Bindings On A Prepared Statement
58.1204 +**
58.1205 +** Contrary to the intuition of many, [sqlite3_reset()] does not
58.1206 +** reset the [sqlite3_bind_blob | bindings] on a
58.1207 +** [sqlite3_stmt | prepared statement]. Use this routine to
58.1208 +** reset all host parameters to NULL.
58.1209 +*/
58.1210 +int sqlite3_clear_bindings(sqlite3_stmt*);
58.1211 +
58.1212 +/*
58.1213 +** CAPI3REF: Number Of Columns In A Result Set
58.1214 +**
58.1215 +** Return the number of columns in the result set returned by the
58.1216 +** [sqlite3_stmt | compiled SQL statement]. This routine returns 0
58.1217 +** if pStmt is an SQL statement that does not return data (for
58.1218 +** example an UPDATE).
58.1219 +*/
58.1220 +int sqlite3_column_count(sqlite3_stmt *pStmt);
58.1221 +
58.1222 +/*
58.1223 +** CAPI3REF: Column Names In A Result Set
58.1224 +**
58.1225 +** These routines return the name assigned to a particular column
58.1226 +** in the result set of a SELECT statement. The sqlite3_column_name()
58.1227 +** interface returns a pointer to a UTF8 string and sqlite3_column_name16()
58.1228 +** returns a pointer to a UTF16 string. The first parameter is the
58.1229 +** [sqlite_stmt | prepared statement] that implements the SELECT statement.
58.1230 +** The second parameter is the column number. The left-most column is
58.1231 +** number 0.
58.1232 +**
58.1233 +** The returned string pointer is valid until either the
58.1234 +** [sqlite_stmt | prepared statement] is destroyed by [sqlite3_finalize()]
58.1235 +** or until the next call sqlite3_column_name() or sqlite3_column_name16()
58.1236 +** on the same column.
58.1237 +*/
58.1238 +const char *sqlite3_column_name(sqlite3_stmt*, int N);
58.1239 +const void *sqlite3_column_name16(sqlite3_stmt*, int N);
58.1240 +
58.1241 +/*
58.1242 +** CAPI3REF: Source Of Data In A Query Result
58.1243 +**
58.1244 +** These routines provide a means to determine what column of what
58.1245 +** table in which database a result of a SELECT statement comes from.
58.1246 +** The name of the database or table or column can be returned as
58.1247 +** either a UTF8 or UTF16 string. The _database_ routines return
58.1248 +** the database name, the _table_ routines return the table name, and
58.1249 +** the origin_ routines return the column name.
58.1250 +** The returned string is valid until
58.1251 +** the [sqlite3_stmt | prepared statement] is destroyed using
58.1252 +** [sqlite3_finalize()] or until the same information is requested
58.1253 +** again in a different encoding.
58.1254 +**
58.1255 +** The names returned are the original un-aliased names of the
58.1256 +** database, table, and column.
58.1257 +**
58.1258 +** The first argument to the following calls is a
58.1259 +** [sqlite3_stmt | compiled SQL statement].
58.1260 +** These functions return information about the Nth column returned by
58.1261 +** the statement, where N is the second function argument.
58.1262 +**
58.1263 +** If the Nth column returned by the statement is an expression
58.1264 +** or subquery and is not a column value, then all of these functions
58.1265 +** return NULL. Otherwise, they return the
58.1266 +** name of the attached database, table and column that query result
58.1267 +** column was extracted from.
58.1268 +**
58.1269 +** As with all other SQLite APIs, those postfixed with "16" return UTF-16
58.1270 +** encoded strings, the other functions return UTF-8.
58.1271 +**
58.1272 +** These APIs are only available if the library was compiled with the
58.1273 +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
58.1274 +*/
58.1275 +const char *sqlite3_column_database_name(sqlite3_stmt*,int);
58.1276 +const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
58.1277 +const char *sqlite3_column_table_name(sqlite3_stmt*,int);
58.1278 +const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
58.1279 +const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
58.1280 +const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
58.1281 +
58.1282 +/*
58.1283 +** CAPI3REF: Declared Datatype Of A Query Result
58.1284 +**
58.1285 +** The first parameter is a [sqlite3_stmt | compiled SQL statement].
58.1286 +** If this statement is a SELECT statement and the Nth column of the
58.1287 +** returned result set of that SELECT is a table column (not an
58.1288 +** expression or subquery) then the declared type of the table
58.1289 +** column is returned. If the Nth column of the result set is an
58.1290 +** expression or subquery, then a NULL pointer is returned.
58.1291 +** The returned string is always UTF-8 encoded. For example, in
58.1292 +** the database schema:
58.1293 +**
58.1294 +** CREATE TABLE t1(c1 VARIANT);
58.1295 +**
58.1296 +** And the following statement compiled:
58.1297 +**
58.1298 +** SELECT c1 + 1, c1 FROM t1;
58.1299 +**
58.1300 +** Then this routine would return the string "VARIANT" for the second
58.1301 +** result column (i==1), and a NULL pointer for the first result column
58.1302 +** (i==0).
58.1303 +**
58.1304 +** SQLite uses dynamic run-time typing. So just because a column
58.1305 +** is declared to contain a particular type does not mean that the
58.1306 +** data stored in that column is of the declared type. SQLite is
58.1307 +** strongly typed, but the typing is dynamic not static. Type
58.1308 +** is associated with individual values, not with the containers
58.1309 +** used to hold those values.
58.1310 +*/
58.1311 +const char *sqlite3_column_decltype(sqlite3_stmt *, int i);
58.1312 +const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
58.1313 +
58.1314 +/*
58.1315 +** CAPI3REF: Evaluate An SQL Statement
58.1316 +**
58.1317 +** After an [sqlite3_stmt | SQL statement] has been prepared with a call
58.1318 +** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of
58.1319 +** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()],
58.1320 +** then this function must be called one or more times to evaluate the
58.1321 +** statement.
58.1322 +**
58.1323 +** The details of the behavior of this sqlite3_step() interface depend
58.1324 +** on whether the statement was prepared using the newer "v2" interface
58.1325 +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
58.1326 +** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
58.1327 +** new "v2" interface is recommended for new applications but the legacy
58.1328 +** interface will continue to be supported.
58.1329 +**
58.1330 +** In the lagacy interface, the return value will be either [SQLITE_BUSY],
58.1331 +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
58.1332 +** With the "v2" interface, any of the other [SQLITE_OK | result code]
58.1333 +** or [SQLITE_IOERR_READ | extended result code] might be returned as
58.1334 +** well.
58.1335 +**
58.1336 +** [SQLITE_BUSY] means that the database engine was unable to acquire the
58.1337 +** database locks it needs to do its job. If the statement is a COMMIT
58.1338 +** or occurs outside of an explicit transaction, then you can retry the
58.1339 +** statement. If the statement is not a COMMIT and occurs within a
58.1340 +** explicit transaction then you should rollback the transaction before
58.1341 +** continuing.
58.1342 +**
58.1343 +** [SQLITE_DONE] means that the statement has finished executing
58.1344 +** successfully. sqlite3_step() should not be called again on this virtual
58.1345 +** machine without first calling [sqlite3_reset()] to reset the virtual
58.1346 +** machine back to its initial state.
58.1347 +**
58.1348 +** If the SQL statement being executed returns any data, then
58.1349 +** [SQLITE_ROW] is returned each time a new row of data is ready
58.1350 +** for processing by the caller. The values may be accessed using
58.1351 +** the [sqlite3_column_int | column access functions].
58.1352 +** sqlite3_step() is called again to retrieve the next row of data.
58.1353 +**
58.1354 +** [SQLITE_ERROR] means that a run-time error (such as a constraint
58.1355 +** violation) has occurred. sqlite3_step() should not be called again on
58.1356 +** the VM. More information may be found by calling [sqlite3_errmsg()].
58.1357 +** With the legacy interface, a more specific error code (example:
58.1358 +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
58.1359 +** can be obtained by calling [sqlite3_reset()] on the
58.1360 +** [sqlite_stmt | prepared statement]. In the "v2" interface,
58.1361 +** the more specific error code is returned directly by sqlite3_step().
58.1362 +**
58.1363 +** [SQLITE_MISUSE] means that the this routine was called inappropriately.
58.1364 +** Perhaps it was called on a [sqlite_stmt | prepared statement] that has
58.1365 +** already been [sqlite3_finalize | finalized] or on one that had
58.1366 +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
58.1367 +** be the case that the same database connection is being used by two or
58.1368 +** more threads at the same moment in time.
58.1369 +**
58.1370 +** <b>Goofy Interface Alert:</b>
58.1371 +** In the legacy interface,
58.1372 +** the sqlite3_step() API always returns a generic error code,
58.1373 +** [SQLITE_ERROR], following any error other than [SQLITE_BUSY]
58.1374 +** and [SQLITE_MISUSE]. You must call [sqlite3_reset()] or
58.1375 +** [sqlite3_finalize()] in order to find one of the specific
58.1376 +** [SQLITE_ERROR | result codes] that better describes the error.
58.1377 +** We admit that this is a goofy design. The problem has been fixed
58.1378 +** with the "v2" interface. If you prepare all of your SQL statements
58.1379 +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
58.1380 +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the
58.1381 +** more specific [SQLITE_ERROR | result codes] are returned directly
58.1382 +** by sqlite3_step(). The use of the "v2" interface is recommended.
58.1383 +*/
58.1384 +int sqlite3_step(sqlite3_stmt*);
58.1385 +
58.1386 +/*
58.1387 +** CAPI3REF:
58.1388 +**
58.1389 +** Return the number of values in the current row of the result set.
58.1390 +**
58.1391 +** After a call to [sqlite3_step()] that returns [SQLITE_ROW], this routine
58.1392 +** will return the same value as the [sqlite3_column_count()] function.
58.1393 +** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or
58.1394 +** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been
58.1395 +** called on the [sqlite_stmt | prepared statement] for the first time,
58.1396 +** this routine returns zero.
58.1397 +*/
58.1398 +int sqlite3_data_count(sqlite3_stmt *pStmt);
58.1399 +
58.1400 +/*
58.1401 +** CAPI3REF: Fundamental Datatypes
58.1402 +**
58.1403 +** Every value in SQLite has one of five fundamental datatypes:
58.1404 +**
58.1405 +** <ul>
58.1406 +** <li> 64-bit signed integer
58.1407 +** <li> 64-bit IEEE floating point number
58.1408 +** <li> string
58.1409 +** <li> BLOB
58.1410 +** <li> NULL
58.1411 +** </ul>
58.1412 +**
58.1413 +** These constants are codes for each of those types.
58.1414 +**
58.1415 +** Note that the SQLITE_TEXT constant was also used in SQLite version 2
58.1416 +** for a completely different meaning. Software that links against both
58.1417 +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not
58.1418 +** SQLITE_TEXT.
58.1419 +*/
58.1420 +#define SQLITE_INTEGER 1
58.1421 +#define SQLITE_FLOAT 2
58.1422 +#define SQLITE_BLOB 4
58.1423 +#define SQLITE_NULL 5
58.1424 +#ifdef SQLITE_TEXT
58.1425 +# undef SQLITE_TEXT
58.1426 +#else
58.1427 +# define SQLITE_TEXT 3
58.1428 +#endif
58.1429 +#define SQLITE3_TEXT 3
58.1430 +
58.1431 +/*
58.1432 +** CAPI3REF: Results Values From A Query
58.1433 +**
58.1434 +** These routines return information about the information
58.1435 +** in a single column of the current result row of a query. In every
58.1436 +** case the first argument is a pointer to the
58.1437 +** [sqlite3_stmt | SQL statement] that is being
58.1438 +** evaluate (the [sqlite_stmt*] that was returned from
58.1439 +** [sqlite3_prepare_v2()] or one of its variants) and
58.1440 +** the second argument is the index of the column for which information
58.1441 +** should be returned. The left-most column has an index of 0.
58.1442 +**
58.1443 +** If the SQL statement is not currently point to a valid row, or if the
58.1444 +** the column index is out of range, the result is undefined.
58.1445 +**
58.1446 +** The sqlite3_column_type() routine returns
58.1447 +** [SQLITE_INTEGER | datatype code] for the initial data type
58.1448 +** of the result column. The returned value is one of [SQLITE_INTEGER],
58.1449 +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
58.1450 +** returned by sqlite3_column_type() is only meaningful if no type
58.1451 +** conversions have occurred as described below. After a type conversion,
58.1452 +** the value returned by sqlite3_column_type() is undefined. Future
58.1453 +** versions of SQLite may change the behavior of sqlite3_column_type()
58.1454 +** following a type conversion.
58.1455 +**
58.1456 +** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
58.1457 +** routine returns the number of bytes in that BLOB or string.
58.1458 +** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
58.1459 +** the string to UTF-8 and then returns the number of bytes.
58.1460 +** If the result is a numeric value then sqlite3_column_bytes() uses
58.1461 +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
58.1462 +** the number of bytes in that string.
58.1463 +** The value returned does not include the zero terminator at the end
58.1464 +** of the string. For clarity: the value returned is the number of
58.1465 +** bytes in the string, not the number of characters.
58.1466 +**
58.1467 +** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
58.1468 +** but leaves the result in UTF-16 instead of UTF-8.
58.1469 +** The zero terminator is not included in this count.
58.1470 +**
58.1471 +** These routines attempt to convert the value where appropriate. For
58.1472 +** example, if the internal representation is FLOAT and a text result
58.1473 +** is requested, [sqlite3_snprintf()] is used internally to do the conversion
58.1474 +** automatically. The following table details the conversions that
58.1475 +** are applied:
58.1476 +**
58.1477 +** <blockquote>
58.1478 +** <table border="1">
58.1479 +** <tr><th> Internal <th> Requested <th>
58.1480 +** <tr><th> Type <th> Type <th> Conversion
58.1481 +**
58.1482 +** <tr><td> NULL <td> INTEGER <td> Result is 0
58.1483 +** <tr><td> NULL <td> FLOAT <td> Result is 0.0
58.1484 +** <tr><td> NULL <td> TEXT <td> Result is NULL pointer
58.1485 +** <tr><td> NULL <td> BLOB <td> Result is NULL pointer
58.1486 +** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
58.1487 +** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
58.1488 +** <tr><td> INTEGER <td> BLOB <td> Same as for INTEGER->TEXT
58.1489 +** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer
58.1490 +** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
58.1491 +** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT
58.1492 +** <tr><td> TEXT <td> INTEGER <td> Use atoi()
58.1493 +** <tr><td> TEXT <td> FLOAT <td> Use atof()
58.1494 +** <tr><td> TEXT <td> BLOB <td> No change
58.1495 +** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi()
58.1496 +** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof()
58.1497 +** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
58.1498 +** </table>
58.1499 +** </blockquote>
58.1500 +**
58.1501 +** The table above makes reference to standard C library functions atoi()
58.1502 +** and atof(). SQLite does not really use these functions. It has its
58.1503 +** on equavalent internal routines. The atoi() and atof() names are
58.1504 +** used in the table for brevity and because they are familiar to most
58.1505 +** C programmers.
58.1506 +**
58.1507 +** Note that when type conversions occur, pointers returned by prior
58.1508 +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
58.1509 +** sqlite3_column_text16() may be invalidated.
58.1510 +** Type conversions and pointer invalidations might occur
58.1511 +** in the following cases:
58.1512 +**
58.1513 +** <ul>
58.1514 +** <li><p> The initial content is a BLOB and sqlite3_column_text()
58.1515 +** or sqlite3_column_text16() is called. A zero-terminator might
58.1516 +** need to be added to the string.</p></li>
58.1517 +**
58.1518 +** <li><p> The initial content is UTF-8 text and sqlite3_column_bytes16() or
58.1519 +** sqlite3_column_text16() is called. The content must be converted
58.1520 +** to UTF-16.</p></li>
58.1521 +**
58.1522 +** <li><p> The initial content is UTF-16 text and sqlite3_column_bytes() or
58.1523 +** sqlite3_column_text() is called. The content must be converted
58.1524 +** to UTF-8.</p></li>
58.1525 +** </ul>
58.1526 +**
58.1527 +** Conversions between UTF-16be and UTF-16le are always done in place and do
58.1528 +** not invalidate a prior pointer, though of course the content of the buffer
58.1529 +** that the prior pointer points to will have been modified. Other kinds
58.1530 +** of conversion are done in place when it is possible, but sometime it is
58.1531 +** not possible and in those cases prior pointers are invalidated.
58.1532 +**
58.1533 +** The safest and easiest to remember policy is to invoke these routines
58.1534 +** in one of the following ways:
58.1535 +**
58.1536 +** <ul>
58.1537 +** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
58.1538 +** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
58.1539 +** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
58.1540 +** </ul>
58.1541 +**
58.1542 +** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(),
58.1543 +** or sqlite3_column_text16() first to force the result into the desired
58.1544 +** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to
58.1545 +** find the size of the result. Do not mix call to sqlite3_column_text() or
58.1546 +** sqlite3_column_blob() with calls to sqlite3_column_bytes16(). And do not
58.1547 +** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes().
58.1548 +*/
58.1549 +const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
58.1550 +int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
58.1551 +int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
58.1552 +double sqlite3_column_double(sqlite3_stmt*, int iCol);
58.1553 +int sqlite3_column_int(sqlite3_stmt*, int iCol);
58.1554 +sqlite_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
58.1555 +const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
58.1556 +const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
58.1557 +int sqlite3_column_type(sqlite3_stmt*, int iCol);
58.1558 +sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
58.1559 +
58.1560 +/*
58.1561 +** CAPI3REF: Destroy A Prepared Statement Object
58.1562 +**
58.1563 +** The sqlite3_finalize() function is called to delete a
58.1564 +** [sqlite3_stmt | compiled SQL statement]. If the statement was
58.1565 +** executed successfully, or not executed at all, then SQLITE_OK is returned.
58.1566 +** If execution of the statement failed then an
58.1567 +** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code]
58.1568 +** is returned.
58.1569 +**
58.1570 +** This routine can be called at any point during the execution of the
58.1571 +** [sqlite3_stmt | virtual machine]. If the virtual machine has not
58.1572 +** completed execution when this routine is called, that is like
58.1573 +** encountering an error or an interrupt. (See [sqlite3_interrupt()].)
58.1574 +** Incomplete updates may be rolled back and transactions cancelled,
58.1575 +** depending on the circumstances, and the
58.1576 +** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT].
58.1577 +*/
58.1578 +int sqlite3_finalize(sqlite3_stmt *pStmt);
58.1579 +
58.1580 +/*
58.1581 +** CAPI3REF: Reset A Prepared Statement Object
58.1582 +**
58.1583 +** The sqlite3_reset() function is called to reset a
58.1584 +** [sqlite_stmt | compiled SQL statement] object.
58.1585 +** back to it's initial state, ready to be re-executed.
58.1586 +** Any SQL statement variables that had values bound to them using
58.1587 +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
58.1588 +** Use [sqlite3_clear_bindings()] to reset the bindings.
58.1589 +*/
58.1590 +int sqlite3_reset(sqlite3_stmt *pStmt);
58.1591 +
58.1592 +/*
58.1593 +** CAPI3REF: Create Or Redefine SQL Functions
58.1594 +**
58.1595 +** The following two functions are used to add SQL functions or aggregates
58.1596 +** or to redefine the behavior of existing SQL functions or aggregates. The
58.1597 +** difference only between the two is that the second parameter, the
58.1598 +** name of the (scalar) function or aggregate, is encoded in UTF-8 for
58.1599 +** sqlite3_create_function() and UTF-16 for sqlite3_create_function16().
58.1600 +**
58.1601 +** The first argument is the [sqlite3 | database handle] that holds the
58.1602 +** SQL function or aggregate is to be added or redefined. If a single
58.1603 +** program uses more than one database handle internally, then SQL
58.1604 +** functions or aggregates must be added individually to each database
58.1605 +** handle with which they will be used.
58.1606 +**
58.1607 +** The second parameter is the name of the SQL function to be created
58.1608 +** or redefined.
58.1609 +** The length of the name is limited to 255 bytes, exclusive of the
58.1610 +** zero-terminator. Note that the name length limit is in bytes, not
58.1611 +** characters. Any attempt to create a function with a longer name
58.1612 +** will result in an SQLITE_ERROR error.
58.1613 +**
58.1614 +** The third parameter is the number of arguments that the SQL function or
58.1615 +** aggregate takes. If this parameter is negative, then the SQL function or
58.1616 +** aggregate may take any number of arguments.
58.1617 +**
58.1618 +** The fourth parameter, eTextRep, specifies what
58.1619 +** [SQLITE_UTF8 | text encoding] this SQL function prefers for
58.1620 +** its parameters. Any SQL function implementation should be able to work
58.1621 +** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
58.1622 +** more efficient with one encoding than another. It is allowed to
58.1623 +** invoke sqlite_create_function() or sqlite3_create_function16() multiple
58.1624 +** times with the same function but with different values of eTextRep.
58.1625 +** When multiple implementations of the same function are available, SQLite
58.1626 +** will pick the one that involves the least amount of data conversion.
58.1627 +** If there is only a single implementation which does not care what
58.1628 +** text encoding is used, then the fourth argument should be
58.1629 +** [SQLITE_ANY].
58.1630 +**
58.1631 +** The fifth parameter is an arbitrary pointer. The implementation
58.1632 +** of the function can gain access to this pointer using
58.1633 +** [sqlite_user_data()].
58.1634 +**
58.1635 +** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
58.1636 +** pointers to C-language functions that implement the SQL
58.1637 +** function or aggregate. A scalar SQL function requires an implementation of
58.1638 +** the xFunc callback only, NULL pointers should be passed as the xStep
58.1639 +** and xFinal parameters. An aggregate SQL function requires an implementation
58.1640 +** of xStep and xFinal and NULL should be passed for xFunc. To delete an
58.1641 +** existing SQL function or aggregate, pass NULL for all three function
58.1642 +** callback.
58.1643 +**
58.1644 +** It is permitted to register multiple implementations of the same
58.1645 +** functions with the same name but with either differing numbers of
58.1646 +** arguments or differing perferred text encodings. SQLite will use
58.1647 +** the implementation most closely matches the way in which the
58.1648 +** SQL function is used.
58.1649 +*/
58.1650 +int sqlite3_create_function(
58.1651 + sqlite3 *,
58.1652 + const char *zFunctionName,
58.1653 + int nArg,
58.1654 + int eTextRep,
58.1655 + void*,
58.1656 + void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
58.1657 + void (*xStep)(sqlite3_context*,int,sqlite3_value**),
58.1658 + void (*xFinal)(sqlite3_context*)
58.1659 +);
58.1660 +int sqlite3_create_function16(
58.1661 + sqlite3*,
58.1662 + const void *zFunctionName,
58.1663 + int nArg,
58.1664 + int eTextRep,
58.1665 + void*,
58.1666 + void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
58.1667 + void (*xStep)(sqlite3_context*,int,sqlite3_value**),
58.1668 + void (*xFinal)(sqlite3_context*)
58.1669 +);
58.1670 +
58.1671 +/*
58.1672 +** CAPI3REF: Text Encodings
58.1673 +**
58.1674 +** These constant define integer codes that represent the various
58.1675 +** text encodings supported by SQLite.
58.1676 +*/
58.1677 +#define SQLITE_UTF8 1
58.1678 +#define SQLITE_UTF16LE 2
58.1679 +#define SQLITE_UTF16BE 3
58.1680 +#define SQLITE_UTF16 4 /* Use native byte order */
58.1681 +#define SQLITE_ANY 5 /* sqlite3_create_function only */
58.1682 +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
58.1683 +
58.1684 +/*
58.1685 +** CAPI3REF: Obsolete Functions
58.1686 +**
58.1687 +** These functions are all now obsolete. In order to maintain
58.1688 +** backwards compatibility with older code, we continue to support
58.1689 +** these functions. However, new development projects should avoid
58.1690 +** the use of these functions. To help encourage people to avoid
58.1691 +** using these functions, we are not going to tell you want they do.
58.1692 +*/
58.1693 +int sqlite3_aggregate_count(sqlite3_context*);
58.1694 +int sqlite3_expired(sqlite3_stmt*);
58.1695 +int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
58.1696 +int sqlite3_global_recover(void);
58.1697 +
58.1698 +
58.1699 +/*
58.1700 +** CAPI3REF: Obtaining SQL Function Parameter Values
58.1701 +**
58.1702 +** The C-language implementation of SQL functions and aggregates uses
58.1703 +** this set of interface routines to access the parameter values on
58.1704 +** the function or aggregate.
58.1705 +**
58.1706 +** The xFunc (for scalar functions) or xStep (for aggregates) parameters
58.1707 +** to [sqlite3_create_function()] and [sqlite3_create_function16()]
58.1708 +** define callbacks that implement the SQL functions and aggregates.
58.1709 +** The 4th parameter to these callbacks is an array of pointers to
58.1710 +** [sqlite3_value] objects. There is one [sqlite3_value] object for
58.1711 +** each parameter to the SQL function. These routines are used to
58.1712 +** extract values from the [sqlite3_value] objects.
58.1713 +**
58.1714 +** These routines work just like the corresponding
58.1715 +** [sqlite3_column_blob | sqlite3_column_* routines] except that
58.1716 +** these routines take a single [sqlite3_value*] pointer instead
58.1717 +** of an [sqlite3_stmt*] pointer and an integer column number.
58.1718 +**
58.1719 +** The sqlite3_value_text16() interface extracts a UTF16 string
58.1720 +** in the native byte-order of the host machine. The
58.1721 +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
58.1722 +** extract UTF16 strings as big-endian and little-endian respectively.
58.1723 +**
58.1724 +** The sqlite3_value_numeric_type() interface attempts to apply
58.1725 +** numeric affinity to the value. This means that an attempt is
58.1726 +** made to convert the value to an integer or floating point. If
58.1727 +** such a conversion is possible without loss of information (in order
58.1728 +** words if the value is original a string that looks like a number)
58.1729 +** then it is done. Otherwise no conversion occurs. The
58.1730 +** [SQLITE_INTEGER | datatype] after conversion is returned.
58.1731 +**
58.1732 +** Please pay particular attention to the fact that the pointer that
58.1733 +** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or
58.1734 +** [sqlite3_value_text16()] can be invalidated by a subsequent call to
58.1735 +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite_value_text()],
58.1736 +** or [sqlite3_value_text16()].
58.1737 +*/
58.1738 +const void *sqlite3_value_blob(sqlite3_value*);
58.1739 +int sqlite3_value_bytes(sqlite3_value*);
58.1740 +int sqlite3_value_bytes16(sqlite3_value*);
58.1741 +double sqlite3_value_double(sqlite3_value*);
58.1742 +int sqlite3_value_int(sqlite3_value*);
58.1743 +sqlite_int64 sqlite3_value_int64(sqlite3_value*);
58.1744 +const unsigned char *sqlite3_value_text(sqlite3_value*);
58.1745 +const void *sqlite3_value_text16(sqlite3_value*);
58.1746 +const void *sqlite3_value_text16le(sqlite3_value*);
58.1747 +const void *sqlite3_value_text16be(sqlite3_value*);
58.1748 +int sqlite3_value_type(sqlite3_value*);
58.1749 +int sqlite3_value_numeric_type(sqlite3_value*);
58.1750 +
58.1751 +/*
58.1752 +** CAPI3REF: Obtain Aggregate Function Context
58.1753 +**
58.1754 +** The implementation of aggregate SQL functions use this routine to allocate
58.1755 +** a structure for storing their state. The first time this routine
58.1756 +** is called for a particular aggregate, a new structure of size nBytes
58.1757 +** is allocated, zeroed, and returned. On subsequent calls (for the
58.1758 +** same aggregate instance) the same buffer is returned. The implementation
58.1759 +** of the aggregate can use the returned buffer to accumulate data.
58.1760 +**
58.1761 +** The buffer allocated is freed automatically by SQLite whan the aggregate
58.1762 +** query concludes.
58.1763 +**
58.1764 +** The first parameter should be a copy of the
58.1765 +** [sqlite3_context | SQL function context] that is the first
58.1766 +** parameter to the callback routine that implements the aggregate
58.1767 +** function.
58.1768 +*/
58.1769 +void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
58.1770 +
58.1771 +/*
58.1772 +** CAPI3REF: User Data For Functions
58.1773 +**
58.1774 +** The pUserData parameter to the [sqlite3_create_function()]
58.1775 +** and [sqlite3_create_function16()] routines
58.1776 +** used to register user functions is available to
58.1777 +** the implementation of the function using this call.
58.1778 +*/
58.1779 +void *sqlite3_user_data(sqlite3_context*);
58.1780 +
58.1781 +/*
58.1782 +** CAPI3REF: Function Auxiliary Data
58.1783 +**
58.1784 +** The following two functions may be used by scalar SQL functions to
58.1785 +** associate meta-data with argument values. If the same value is passed to
58.1786 +** multiple invocations of the same SQL function during query execution, under
58.1787 +** some circumstances the associated meta-data may be preserved. This may
58.1788 +** be used, for example, to add a regular-expression matching scalar
58.1789 +** function. The compiled version of the regular expression is stored as
58.1790 +** meta-data associated with the SQL value passed as the regular expression
58.1791 +** pattern. The compiled regular expression can be reused on multiple
58.1792 +** invocations of the same function so that the original pattern string
58.1793 +** does not need to be recompiled on each invocation.
58.1794 +**
58.1795 +** The sqlite3_get_auxdata() interface returns a pointer to the meta-data
58.1796 +** associated with the Nth argument value to the current SQL function
58.1797 +** call, where N is the second parameter. If no meta-data has been set for
58.1798 +** that value, then a NULL pointer is returned.
58.1799 +**
58.1800 +** The sqlite3_set_auxdata() is used to associate meta-data with an SQL
58.1801 +** function argument. The third parameter is a pointer to the meta-data
58.1802 +** to be associated with the Nth user function argument value. The fourth
58.1803 +** parameter specifies a destructor that will be called on the meta-
58.1804 +** data pointer to release it when it is no longer required. If the
58.1805 +** destructor is NULL, it is not invoked.
58.1806 +**
58.1807 +** In practice, meta-data is preserved between function calls for
58.1808 +** expressions that are constant at compile time. This includes literal
58.1809 +** values and SQL variables.
58.1810 +*/
58.1811 +void *sqlite3_get_auxdata(sqlite3_context*, int);
58.1812 +void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*));
58.1813 +
58.1814 +
58.1815 +/*
58.1816 +** CAPI3REF: Constants Defining Special Destructor Behavior
58.1817 +**
58.1818 +** These are special value for the destructor that is passed in as the
58.1819 +** final argument to routines like [sqlite3_result_blob()]. If the destructor
58.1820 +** argument is SQLITE_STATIC, it means that the content pointer is constant
58.1821 +** and will never change. It does not need to be destroyed. The
58.1822 +** SQLITE_TRANSIENT value means that the content will likely change in
58.1823 +** the near future and that SQLite should make its own private copy of
58.1824 +** the content before returning.
58.1825 +**
58.1826 +** The typedef is necessary to work around problems in certain
58.1827 +** C++ compilers. See ticket #2191.
58.1828 +*/
58.1829 +typedef void (*sqlite3_destructor_type)(void*);
58.1830 +#define SQLITE_STATIC ((sqlite3_destructor_type)0)
58.1831 +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
58.1832 +
58.1833 +/*
58.1834 +** CAPI3REF: Setting The Result Of An SQL Function
58.1835 +**
58.1836 +** These routines are used by the xFunc or xFinal callbacks that
58.1837 +** implement SQL functions and aggregates. See
58.1838 +** [sqlite3_create_function()] and [sqlite3_create_function16()]
58.1839 +** for additional information.
58.1840 +**
58.1841 +** These functions work very much like the
58.1842 +** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used
58.1843 +** to bind values to host parameters in prepared statements.
58.1844 +** Refer to the
58.1845 +** [sqlite3_bind_blob | sqlite3_bind_* documentation] for
58.1846 +** additional information.
58.1847 +**
58.1848 +** The sqlite3_result_error() and sqlite3_result_error16() functions
58.1849 +** cause the implemented SQL function to throw an exception. The
58.1850 +** parameter to sqlite3_result_error() or sqlite3_result_error16()
58.1851 +** is the text of an error message.
58.1852 +**
58.1853 +** The sqlite3_result_toobig() cause the function implementation
58.1854 +** to throw and error indicating that a string or BLOB is to long
58.1855 +** to represent.
58.1856 +*/
58.1857 +void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
58.1858 +void sqlite3_result_double(sqlite3_context*, double);
58.1859 +void sqlite3_result_error(sqlite3_context*, const char*, int);
58.1860 +void sqlite3_result_error16(sqlite3_context*, const void*, int);
58.1861 +void sqlite3_result_error_toobig(sqlite3_context*);
58.1862 +void sqlite3_result_int(sqlite3_context*, int);
58.1863 +void sqlite3_result_int64(sqlite3_context*, sqlite_int64);
58.1864 +void sqlite3_result_null(sqlite3_context*);
58.1865 +void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
58.1866 +void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
58.1867 +void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
58.1868 +void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
58.1869 +void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
58.1870 +void sqlite3_result_zeroblob(sqlite3_context*, int n);
58.1871 +
58.1872 +/*
58.1873 +** CAPI3REF: Define New Collating Sequences
58.1874 +**
58.1875 +** These functions are used to add new collation sequences to the
58.1876 +** [sqlite3*] handle specified as the first argument.
58.1877 +**
58.1878 +** The name of the new collation sequence is specified as a UTF-8 string
58.1879 +** for sqlite3_create_collation() and sqlite3_create_collation_v2()
58.1880 +** and a UTF-16 string for sqlite3_create_collation16(). In all cases
58.1881 +** the name is passed as the second function argument.
58.1882 +**
58.1883 +** The third argument must be one of the constants [SQLITE_UTF8],
58.1884 +** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
58.1885 +** routine expects to be passed pointers to strings encoded using UTF-8,
58.1886 +** UTF-16 little-endian or UTF-16 big-endian respectively.
58.1887 +**
58.1888 +** A pointer to the user supplied routine must be passed as the fifth
58.1889 +** argument. If it is NULL, this is the same as deleting the collation
58.1890 +** sequence (so that SQLite cannot call it anymore). Each time the user
58.1891 +** supplied function is invoked, it is passed a copy of the void* passed as
58.1892 +** the fourth argument to sqlite3_create_collation() or
58.1893 +** sqlite3_create_collation16() as its first parameter.
58.1894 +**
58.1895 +** The remaining arguments to the user-supplied routine are two strings,
58.1896 +** each represented by a [length, data] pair and encoded in the encoding
58.1897 +** that was passed as the third argument when the collation sequence was
58.1898 +** registered. The user routine should return negative, zero or positive if
58.1899 +** the first string is less than, equal to, or greater than the second
58.1900 +** string. i.e. (STRING1 - STRING2).
58.1901 +**
58.1902 +** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
58.1903 +** excapt that it takes an extra argument which is a destructor for
58.1904 +** the collation. The destructor is called when the collation is
58.1905 +** destroyed and is passed a copy of the fourth parameter void* pointer
58.1906 +** of the sqlite3_create_collation_v2(). Collations are destroyed when
58.1907 +** they are overridden by later calls to the collation creation functions
58.1908 +** or when the [sqlite3*] database handle is closed using [sqlite3_close()].
58.1909 +**
58.1910 +** The sqlite3_create_collation_v2() interface is experimental and
58.1911 +** subject to change in future releases. The other collation creation
58.1912 +** functions are stable.
58.1913 +*/
58.1914 +int sqlite3_create_collation(
58.1915 + sqlite3*,
58.1916 + const char *zName,
58.1917 + int eTextRep,
58.1918 + void*,
58.1919 + int(*xCompare)(void*,int,const void*,int,const void*)
58.1920 +);
58.1921 +int sqlite3_create_collation_v2(
58.1922 + sqlite3*,
58.1923 + const char *zName,
58.1924 + int eTextRep,
58.1925 + void*,
58.1926 + int(*xCompare)(void*,int,const void*,int,const void*),
58.1927 + void(*xDestroy)(void*)
58.1928 +);
58.1929 +int sqlite3_create_collation16(
58.1930 + sqlite3*,
58.1931 + const char *zName,
58.1932 + int eTextRep,
58.1933 + void*,
58.1934 + int(*xCompare)(void*,int,const void*,int,const void*)
58.1935 +);
58.1936 +
58.1937 +/*
58.1938 +** CAPI3REF: Collation Needed Callbacks
58.1939 +**
58.1940 +** To avoid having to register all collation sequences before a database
58.1941 +** can be used, a single callback function may be registered with the
58.1942 +** database handle to be called whenever an undefined collation sequence is
58.1943 +** required.
58.1944 +**
58.1945 +** If the function is registered using the sqlite3_collation_needed() API,
58.1946 +** then it is passed the names of undefined collation sequences as strings
58.1947 +** encoded in UTF-8. If sqlite3_collation_needed16() is used, the names
58.1948 +** are passed as UTF-16 in machine native byte order. A call to either
58.1949 +** function replaces any existing callback.
58.1950 +**
58.1951 +** When the callback is invoked, the first argument passed is a copy
58.1952 +** of the second argument to sqlite3_collation_needed() or
58.1953 +** sqlite3_collation_needed16(). The second argument is the database
58.1954 +** handle. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], or
58.1955 +** [SQLITE_UTF16LE], indicating the most desirable form of the collation
58.1956 +** sequence function required. The fourth parameter is the name of the
58.1957 +** required collation sequence.
58.1958 +**
58.1959 +** The callback function should register the desired collation using
58.1960 +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
58.1961 +** [sqlite3_create_collation_v2()].
58.1962 +*/
58.1963 +int sqlite3_collation_needed(
58.1964 + sqlite3*,
58.1965 + void*,
58.1966 + void(*)(void*,sqlite3*,int eTextRep,const char*)
58.1967 +);
58.1968 +int sqlite3_collation_needed16(
58.1969 + sqlite3*,
58.1970 + void*,
58.1971 + void(*)(void*,sqlite3*,int eTextRep,const void*)
58.1972 +);
58.1973 +
58.1974 +/*
58.1975 +** Specify the key for an encrypted database. This routine should be
58.1976 +** called right after sqlite3_open().
58.1977 +**
58.1978 +** The code to implement this API is not available in the public release
58.1979 +** of SQLite.
58.1980 +*/
58.1981 +int sqlite3_key(
58.1982 + sqlite3 *db, /* Database to be rekeyed */
58.1983 + const void *pKey, int nKey /* The key */
58.1984 +);
58.1985 +
58.1986 +/*
58.1987 +** Change the key on an open database. If the current database is not
58.1988 +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
58.1989 +** database is decrypted.
58.1990 +**
58.1991 +** The code to implement this API is not available in the public release
58.1992 +** of SQLite.
58.1993 +*/
58.1994 +int sqlite3_rekey(
58.1995 + sqlite3 *db, /* Database to be rekeyed */
58.1996 + const void *pKey, int nKey /* The new key */
58.1997 +);
58.1998 +
58.1999 +/*
58.2000 +** CAPI3REF: Suspend Execution For A Short Time
58.2001 +**
58.2002 +** This function causes the current thread to suspend execution
58.2003 +** a number of milliseconds specified in its parameter.
58.2004 +**
58.2005 +** If the operating system does not support sleep requests with
58.2006 +** millisecond time resolution, then the time will be rounded up to
58.2007 +** the nearest second. The number of milliseconds of sleep actually
58.2008 +** requested from the operating system is returned.
58.2009 +*/
58.2010 +int sqlite3_sleep(int);
58.2011 +
58.2012 +/*
58.2013 +** CAPI3REF: Name Of The Folder Holding Temporary Files
58.2014 +**
58.2015 +** If this global variable is made to point to a string which is
58.2016 +** the name of a folder (a.ka. directory), then all temporary files
58.2017 +** created by SQLite will be placed in that directory. If this variable
58.2018 +** is NULL pointer, then SQLite does a search for an appropriate temporary
58.2019 +** file directory.
58.2020 +**
58.2021 +** Once [sqlite3_open()] has been called, changing this variable will
58.2022 +** invalidate the current temporary database, if any. Generally speaking,
58.2023 +** it is not safe to invoke this routine after [sqlite3_open()] has
58.2024 +** been called.
58.2025 +*/
58.2026 +extern char *sqlite3_temp_directory;
58.2027 +
58.2028 +/*
58.2029 +** CAPI3REF: Test To See If The Databse Is In Auto-Commit Mode
58.2030 +**
58.2031 +** Test to see whether or not the database connection is in autocommit
58.2032 +** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
58.2033 +** by default. Autocommit is disabled by a BEGIN statement and reenabled
58.2034 +** by the next COMMIT or ROLLBACK.
58.2035 +*/
58.2036 +int sqlite3_get_autocommit(sqlite3*);
58.2037 +
58.2038 +/*
58.2039 +** CAPI3REF: Find The Database Handle Associated With A Prepared Statement
58.2040 +**
58.2041 +** Return the [sqlite3*] database handle to which a
58.2042 +** [sqlite3_stmt | prepared statement] belongs.
58.2043 +** This is the same database handle that was
58.2044 +** the first argument to the [sqlite3_prepare_v2()] or its variants
58.2045 +** that was used to create the statement in the first place.
58.2046 +*/
58.2047 +sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
58.2048 +
58.2049 +
58.2050 +/*
58.2051 +** CAPI3REF: Commit And Rollback Notification Callbacks
58.2052 +**
58.2053 +** These routines
58.2054 +** register callback functions to be invoked whenever a transaction
58.2055 +** is committed or rolled back. The pArg argument is passed through
58.2056 +** to the callback. If the callback on a commit hook function
58.2057 +** returns non-zero, then the commit is converted into a rollback.
58.2058 +**
58.2059 +** If another function was previously registered, its pArg value is returned.
58.2060 +** Otherwise NULL is returned.
58.2061 +**
58.2062 +** Registering a NULL function disables the callback.
58.2063 +**
58.2064 +** For the purposes of this API, a transaction is said to have been
58.2065 +** rolled back if an explicit "ROLLBACK" statement is executed, or
58.2066 +** an error or constraint causes an implicit rollback to occur. The
58.2067 +** callback is not invoked if a transaction is automatically rolled
58.2068 +** back because the database connection is closed.
58.2069 +**
58.2070 +** These are experimental interfaces and are subject to change.
58.2071 +*/
58.2072 +void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
58.2073 +void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
58.2074 +
58.2075 +/*
58.2076 +** CAPI3REF: Data Change Notification Callbacks
58.2077 +**
58.2078 +** Register a callback function with the database connection identified by the
58.2079 +** first argument to be invoked whenever a row is updated, inserted or deleted.
58.2080 +** Any callback set by a previous call to this function for the same
58.2081 +** database connection is overridden.
58.2082 +**
58.2083 +** The second argument is a pointer to the function to invoke when a
58.2084 +** row is updated, inserted or deleted. The first argument to the callback is
58.2085 +** a copy of the third argument to sqlite3_update_hook(). The second callback
58.2086 +** argument is one of SQLITE_INSERT, SQLITE_DELETE or SQLITE_UPDATE, depending
58.2087 +** on the operation that caused the callback to be invoked. The third and
58.2088 +** fourth arguments to the callback contain pointers to the database and
58.2089 +** table name containing the affected row. The final callback parameter is
58.2090 +** the rowid of the row. In the case of an update, this is the rowid after
58.2091 +** the update takes place.
58.2092 +**
58.2093 +** The update hook is not invoked when internal system tables are
58.2094 +** modified (i.e. sqlite_master and sqlite_sequence).
58.2095 +**
58.2096 +** If another function was previously registered, its pArg value is returned.
58.2097 +** Otherwise NULL is returned.
58.2098 +*/
58.2099 +void *sqlite3_update_hook(
58.2100 + sqlite3*,
58.2101 + void(*)(void *,int ,char const *,char const *,sqlite_int64),
58.2102 + void*
58.2103 +);
58.2104 +
58.2105 +/*
58.2106 +** CAPI3REF: Enable Or Disable Shared Pager Cache
58.2107 +**
58.2108 +** This routine enables or disables the sharing of the database cache
58.2109 +** and schema data structures between connections to the same database.
58.2110 +** Sharing is enabled if the argument is true and disabled if the argument
58.2111 +** is false.
58.2112 +**
58.2113 +** Cache sharing is enabled and disabled on a thread-by-thread basis.
58.2114 +** Each call to this routine enables or disables cache sharing only for
58.2115 +** connections created in the same thread in which this routine is called.
58.2116 +** There is no mechanism for sharing cache between database connections
58.2117 +** running in different threads.
58.2118 +**
58.2119 +** Sharing must be disabled prior to shutting down a thread or else
58.2120 +** the thread will leak memory. Call this routine with an argument of
58.2121 +** 0 to turn off sharing. Or use the sqlite3_thread_cleanup() API.
58.2122 +**
58.2123 +** This routine must not be called when any database connections
58.2124 +** are active in the current thread. Enabling or disabling shared
58.2125 +** cache while there are active database connections will result
58.2126 +** in memory corruption.
58.2127 +**
58.2128 +** When the shared cache is enabled, the
58.2129 +** following routines must always be called from the same thread:
58.2130 +** [sqlite3_open()], [sqlite3_prepare_v2()], [sqlite3_step()],
58.2131 +** [sqlite3_reset()], [sqlite3_finalize()], and [sqlite3_close()].
58.2132 +** This is due to the fact that the shared cache makes use of
58.2133 +** thread-specific storage so that it will be available for sharing
58.2134 +** with other connections.
58.2135 +**
58.2136 +** Virtual tables cannot be used with a shared cache. When shared
58.2137 +** cache is enabled, the sqlite3_create_module() API used to register
58.2138 +** virtual tables will always return an error.
58.2139 +**
58.2140 +** This routine returns [SQLITE_OK] if shared cache was
58.2141 +** enabled or disabled successfully. An [SQLITE_ERROR | error code]
58.2142 +** is returned otherwise.
58.2143 +**
58.2144 +** Shared cache is disabled by default for backward compatibility.
58.2145 +*/
58.2146 +int sqlite3_enable_shared_cache(int);
58.2147 +
58.2148 +/*
58.2149 +** CAPI3REF: Attempt To Free Heap Memory
58.2150 +**
58.2151 +** Attempt to free N bytes of heap memory by deallocating non-essential
58.2152 +** memory allocations held by the database library (example: memory
58.2153 +** used to cache database pages to improve performance).
58.2154 +**
58.2155 +** This function is not a part of standard builds. It is only created
58.2156 +** if SQLite is compiled with the SQLITE_ENABLE_MEMORY_MANAGEMENT macro.
58.2157 +*/
58.2158 +int sqlite3_release_memory(int);
58.2159 +
58.2160 +/*
58.2161 +** CAPI3REF: Impose A Limit On Heap Size
58.2162 +**
58.2163 +** Place a "soft" limit on the amount of heap memory that may be allocated by
58.2164 +** SQLite within the current thread. If an internal allocation is requested
58.2165 +** that would exceed the specified limit, [sqlite3_release_memory()] is invoked
58.2166 +** one or more times to free up some space before the allocation is made.
58.2167 +**
58.2168 +** The limit is called "soft", because if [sqlite3_release_memory()] cannot free
58.2169 +** sufficient memory to prevent the limit from being exceeded, the memory is
58.2170 +** allocated anyway and the current operation proceeds.
58.2171 +**
58.2172 +** Prior to shutting down a thread sqlite3_soft_heap_limit() must be set to
58.2173 +** zero (the default) or else the thread will leak memory. Alternatively, use
58.2174 +** the [sqlite3_thread_cleanup()] API.
58.2175 +**
58.2176 +** A negative or zero value for N means that there is no soft heap limit and
58.2177 +** [sqlite3_release_memory()] will only be called when memory is exhaused.
58.2178 +** The default value for the soft heap limit is zero.
58.2179 +**
58.2180 +** SQLite makes a best effort to honor the soft heap limit. But if it
58.2181 +** is unable to reduce memory usage below the soft limit, execution will
58.2182 +** continue without error or notification. This is why the limit is
58.2183 +** called a "soft" limit. It is advisory only.
58.2184 +**
58.2185 +** This function is only available if the library was compiled with the
58.2186 +** SQLITE_ENABLE_MEMORY_MANAGEMENT option set.
58.2187 +** memory-management has been enabled.
58.2188 +*/
58.2189 +void sqlite3_soft_heap_limit(int);
58.2190 +
58.2191 +/*
58.2192 +** CAPI3REF: Clean Up Thread Local Storage
58.2193 +**
58.2194 +** This routine makes sure that all thread-local storage has been
58.2195 +** deallocated for the current thread.
58.2196 +**
58.2197 +** This routine is not technically necessary. All thread-local storage
58.2198 +** will be automatically deallocated once memory-management and
58.2199 +** shared-cache are disabled and the soft heap limit has been set
58.2200 +** to zero. This routine is provided as a convenience for users who
58.2201 +** want to make absolutely sure they have not forgotten something
58.2202 +** prior to killing off a thread.
58.2203 +*/
58.2204 +void sqlite3_thread_cleanup(void);
58.2205 +
58.2206 +/*
58.2207 +** CAPI3REF: Extract Metadata About A Column Of A Table
58.2208 +**
58.2209 +** This routine
58.2210 +** returns meta-data about a specific column of a specific database
58.2211 +** table accessible using the connection handle passed as the first function
58.2212 +** argument.
58.2213 +**
58.2214 +** The column is identified by the second, third and fourth parameters to
58.2215 +** this function. The second parameter is either the name of the database
58.2216 +** (i.e. "main", "temp" or an attached database) containing the specified
58.2217 +** table or NULL. If it is NULL, then all attached databases are searched
58.2218 +** for the table using the same algorithm as the database engine uses to
58.2219 +** resolve unqualified table references.
58.2220 +**
58.2221 +** The third and fourth parameters to this function are the table and column
58.2222 +** name of the desired column, respectively. Neither of these parameters
58.2223 +** may be NULL.
58.2224 +**
58.2225 +** Meta information is returned by writing to the memory locations passed as
58.2226 +** the 5th and subsequent parameters to this function. Any of these
58.2227 +** arguments may be NULL, in which case the corresponding element of meta
58.2228 +** information is ommitted.
58.2229 +**
58.2230 +** <pre>
58.2231 +** Parameter Output Type Description
58.2232 +** -----------------------------------
58.2233 +**
58.2234 +** 5th const char* Data type
58.2235 +** 6th const char* Name of the default collation sequence
58.2236 +** 7th int True if the column has a NOT NULL constraint
58.2237 +** 8th int True if the column is part of the PRIMARY KEY
58.2238 +** 9th int True if the column is AUTOINCREMENT
58.2239 +** </pre>
58.2240 +**
58.2241 +**
58.2242 +** The memory pointed to by the character pointers returned for the
58.2243 +** declaration type and collation sequence is valid only until the next
58.2244 +** call to any sqlite API function.
58.2245 +**
58.2246 +** If the specified table is actually a view, then an error is returned.
58.2247 +**
58.2248 +** If the specified column is "rowid", "oid" or "_rowid_" and an
58.2249 +** INTEGER PRIMARY KEY column has been explicitly declared, then the output
58.2250 +** parameters are set for the explicitly declared column. If there is no
58.2251 +** explicitly declared IPK column, then the output parameters are set as
58.2252 +** follows:
58.2253 +**
58.2254 +** <pre>
58.2255 +** data type: "INTEGER"
58.2256 +** collation sequence: "BINARY"
58.2257 +** not null: 0
58.2258 +** primary key: 1
58.2259 +** auto increment: 0
58.2260 +** </pre>
58.2261 +**
58.2262 +** This function may load one or more schemas from database files. If an
58.2263 +** error occurs during this process, or if the requested table or column
58.2264 +** cannot be found, an SQLITE error code is returned and an error message
58.2265 +** left in the database handle (to be retrieved using sqlite3_errmsg()).
58.2266 +**
58.2267 +** This API is only available if the library was compiled with the
58.2268 +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
58.2269 +*/
58.2270 +int sqlite3_table_column_metadata(
58.2271 + sqlite3 *db, /* Connection handle */
58.2272 + const char *zDbName, /* Database name or NULL */
58.2273 + const char *zTableName, /* Table name */
58.2274 + const char *zColumnName, /* Column name */
58.2275 + char const **pzDataType, /* OUTPUT: Declared data type */
58.2276 + char const **pzCollSeq, /* OUTPUT: Collation sequence name */
58.2277 + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
58.2278 + int *pPrimaryKey, /* OUTPUT: True if column part of PK */
58.2279 + int *pAutoinc /* OUTPUT: True if colums is auto-increment */
58.2280 +);
58.2281 +
58.2282 +/*
58.2283 +** CAPI3REF: Load An Extension
58.2284 +**
58.2285 +** Attempt to load an SQLite extension library contained in the file
58.2286 +** zFile. The entry point is zProc. zProc may be 0 in which case the
58.2287 +** name of the entry point defaults to "sqlite3_extension_init".
58.2288 +**
58.2289 +** Return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
58.2290 +**
58.2291 +** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
58.2292 +** error message text. The calling function should free this memory
58.2293 +** by calling [sqlite3_free()].
58.2294 +**
58.2295 +** Extension loading must be enabled using [sqlite3_enable_load_extension()]
58.2296 +** prior to calling this API or an error will be returned.
58.2297 +*/
58.2298 +int sqlite3_load_extension(
58.2299 + sqlite3 *db, /* Load the extension into this database connection */
58.2300 + const char *zFile, /* Name of the shared library containing extension */
58.2301 + const char *zProc, /* Entry point. Derived from zFile if 0 */
58.2302 + char **pzErrMsg /* Put error message here if not 0 */
58.2303 +);
58.2304 +
58.2305 +/*
58.2306 +** CAPI3REF: Enable Or Disable Extension Loading
58.2307 +**
58.2308 +** So as not to open security holes in older applications that are
58.2309 +** unprepared to deal with extension loading, and as a means of disabling
58.2310 +** extension loading while evaluating user-entered SQL, the following
58.2311 +** API is provided to turn the [sqlite3_load_extension()] mechanism on and
58.2312 +** off. It is off by default. See ticket #1863.
58.2313 +**
58.2314 +** Call this routine with onoff==1 to turn extension loading on
58.2315 +** and call it with onoff==0 to turn it back off again.
58.2316 +*/
58.2317 +int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
58.2318 +
58.2319 +/*
58.2320 +** CAPI3REF: Make Arrangements To Automatically Load An Extension
58.2321 +**
58.2322 +** Register an extension entry point that is automatically invoked
58.2323 +** whenever a new database connection is opened using
58.2324 +** [sqlite3_open()] or [sqlite3_open16()].
58.2325 +**
58.2326 +** This API can be invoked at program startup in order to register
58.2327 +** one or more statically linked extensions that will be available
58.2328 +** to all new database connections.
58.2329 +**
58.2330 +** Duplicate extensions are detected so calling this routine multiple
58.2331 +** times with the same extension is harmless.
58.2332 +**
58.2333 +** This routine stores a pointer to the extension in an array
58.2334 +** that is obtained from malloc(). If you run a memory leak
58.2335 +** checker on your program and it reports a leak because of this
58.2336 +** array, then invoke [sqlite3_automatic_extension_reset()] prior
58.2337 +** to shutdown to free the memory.
58.2338 +**
58.2339 +** Automatic extensions apply across all threads.
58.2340 +**
58.2341 +** This interface is experimental and is subject to change or
58.2342 +** removal in future releases of SQLite.
58.2343 +*/
58.2344 +int sqlite3_auto_extension(void *xEntryPoint);
58.2345 +
58.2346 +
58.2347 +/*
58.2348 +** CAPI3REF: Reset Automatic Extension Loading
58.2349 +**
58.2350 +** Disable all previously registered automatic extensions. This
58.2351 +** routine undoes the effect of all prior [sqlite3_automatic_extension()]
58.2352 +** calls.
58.2353 +**
58.2354 +** This call disabled automatic extensions in all threads.
58.2355 +**
58.2356 +** This interface is experimental and is subject to change or
58.2357 +** removal in future releases of SQLite.
58.2358 +*/
58.2359 +void sqlite3_reset_auto_extension(void);
58.2360 +
58.2361 +
58.2362 +/*
58.2363 +****** EXPERIMENTAL - subject to change without notice **************
58.2364 +**
58.2365 +** The interface to the virtual-table mechanism is currently considered
58.2366 +** to be experimental. The interface might change in incompatible ways.
58.2367 +** If this is a problem for you, do not use the interface at this time.
58.2368 +**
58.2369 +** When the virtual-table mechanism stablizes, we will declare the
58.2370 +** interface fixed, support it indefinitely, and remove this comment.
58.2371 +*/
58.2372 +
58.2373 +/*
58.2374 +** Structures used by the virtual table interface
58.2375 +*/
58.2376 +typedef struct sqlite3_vtab sqlite3_vtab;
58.2377 +typedef struct sqlite3_index_info sqlite3_index_info;
58.2378 +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
58.2379 +typedef struct sqlite3_module sqlite3_module;
58.2380 +
58.2381 +/*
58.2382 +** A module is a class of virtual tables. Each module is defined
58.2383 +** by an instance of the following structure. This structure consists
58.2384 +** mostly of methods for the module.
58.2385 +*/
58.2386 +struct sqlite3_module {
58.2387 + int iVersion;
58.2388 + int (*xCreate)(sqlite3*, void *pAux,
58.2389 + int argc, const char *const*argv,
58.2390 + sqlite3_vtab **ppVTab, char**);
58.2391 + int (*xConnect)(sqlite3*, void *pAux,
58.2392 + int argc, const char *const*argv,
58.2393 + sqlite3_vtab **ppVTab, char**);
58.2394 + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
58.2395 + int (*xDisconnect)(sqlite3_vtab *pVTab);
58.2396 + int (*xDestroy)(sqlite3_vtab *pVTab);
58.2397 + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
58.2398 + int (*xClose)(sqlite3_vtab_cursor*);
58.2399 + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
58.2400 + int argc, sqlite3_value **argv);
58.2401 + int (*xNext)(sqlite3_vtab_cursor*);
58.2402 + int (*xEof)(sqlite3_vtab_cursor*);
58.2403 + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
58.2404 + int (*xRowid)(sqlite3_vtab_cursor*, sqlite_int64 *pRowid);
58.2405 + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite_int64 *);
58.2406 + int (*xBegin)(sqlite3_vtab *pVTab);
58.2407 + int (*xSync)(sqlite3_vtab *pVTab);
58.2408 + int (*xCommit)(sqlite3_vtab *pVTab);
58.2409 + int (*xRollback)(sqlite3_vtab *pVTab);
58.2410 + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
58.2411 + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
58.2412 + void **ppArg);
58.2413 +
58.2414 + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
58.2415 +};
58.2416 +
58.2417 +/*
58.2418 +** The sqlite3_index_info structure and its substructures is used to
58.2419 +** pass information into and receive the reply from the xBestIndex
58.2420 +** method of an sqlite3_module. The fields under **Inputs** are the
58.2421 +** inputs to xBestIndex and are read-only. xBestIndex inserts its
58.2422 +** results into the **Outputs** fields.
58.2423 +**
58.2424 +** The aConstraint[] array records WHERE clause constraints of the
58.2425 +** form:
58.2426 +**
58.2427 +** column OP expr
58.2428 +**
58.2429 +** Where OP is =, <, <=, >, or >=. The particular operator is stored
58.2430 +** in aConstraint[].op. The index of the column is stored in
58.2431 +** aConstraint[].iColumn. aConstraint[].usable is TRUE if the
58.2432 +** expr on the right-hand side can be evaluated (and thus the constraint
58.2433 +** is usable) and false if it cannot.
58.2434 +**
58.2435 +** The optimizer automatically inverts terms of the form "expr OP column"
58.2436 +** and makes other simplificatinos to the WHERE clause in an attempt to
58.2437 +** get as many WHERE clause terms into the form shown above as possible.
58.2438 +** The aConstraint[] array only reports WHERE clause terms in the correct
58.2439 +** form that refer to the particular virtual table being queried.
58.2440 +**
58.2441 +** Information about the ORDER BY clause is stored in aOrderBy[].
58.2442 +** Each term of aOrderBy records a column of the ORDER BY clause.
58.2443 +**
58.2444 +** The xBestIndex method must fill aConstraintUsage[] with information
58.2445 +** about what parameters to pass to xFilter. If argvIndex>0 then
58.2446 +** the right-hand side of the corresponding aConstraint[] is evaluated
58.2447 +** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit
58.2448 +** is true, then the constraint is assumed to be fully handled by the
58.2449 +** virtual table and is not checked again by SQLite.
58.2450 +**
58.2451 +** The idxNum and idxPtr values are recorded and passed into xFilter.
58.2452 +** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
58.2453 +**
58.2454 +** The orderByConsumed means that output from xFilter will occur in
58.2455 +** the correct order to satisfy the ORDER BY clause so that no separate
58.2456 +** sorting step is required.
58.2457 +**
58.2458 +** The estimatedCost value is an estimate of the cost of doing the
58.2459 +** particular lookup. A full scan of a table with N entries should have
58.2460 +** a cost of N. A binary search of a table of N entries should have a
58.2461 +** cost of approximately log(N).
58.2462 +*/
58.2463 +struct sqlite3_index_info {
58.2464 + /* Inputs */
58.2465 + const int nConstraint; /* Number of entries in aConstraint */
58.2466 + const struct sqlite3_index_constraint {
58.2467 + int iColumn; /* Column on left-hand side of constraint */
58.2468 + unsigned char op; /* Constraint operator */
58.2469 + unsigned char usable; /* True if this constraint is usable */
58.2470 + int iTermOffset; /* Used internally - xBestIndex should ignore */
58.2471 + } *const aConstraint; /* Table of WHERE clause constraints */
58.2472 + const int nOrderBy; /* Number of terms in the ORDER BY clause */
58.2473 + const struct sqlite3_index_orderby {
58.2474 + int iColumn; /* Column number */
58.2475 + unsigned char desc; /* True for DESC. False for ASC. */
58.2476 + } *const aOrderBy; /* The ORDER BY clause */
58.2477 +
58.2478 + /* Outputs */
58.2479 + struct sqlite3_index_constraint_usage {
58.2480 + int argvIndex; /* if >0, constraint is part of argv to xFilter */
58.2481 + unsigned char omit; /* Do not code a test for this constraint */
58.2482 + } *const aConstraintUsage;
58.2483 + int idxNum; /* Number used to identify the index */
58.2484 + char *idxStr; /* String, possibly obtained from sqlite3_malloc */
58.2485 + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
58.2486 + int orderByConsumed; /* True if output is already ordered */
58.2487 + double estimatedCost; /* Estimated cost of using this index */
58.2488 +};
58.2489 +#define SQLITE_INDEX_CONSTRAINT_EQ 2
58.2490 +#define SQLITE_INDEX_CONSTRAINT_GT 4
58.2491 +#define SQLITE_INDEX_CONSTRAINT_LE 8
58.2492 +#define SQLITE_INDEX_CONSTRAINT_LT 16
58.2493 +#define SQLITE_INDEX_CONSTRAINT_GE 32
58.2494 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64
58.2495 +
58.2496 +/*
58.2497 +** This routine is used to register a new module name with an SQLite
58.2498 +** connection. Module names must be registered before creating new
58.2499 +** virtual tables on the module, or before using preexisting virtual
58.2500 +** tables of the module.
58.2501 +*/
58.2502 +int sqlite3_create_module(
58.2503 + sqlite3 *db, /* SQLite connection to register module with */
58.2504 + const char *zName, /* Name of the module */
58.2505 + const sqlite3_module *, /* Methods for the module */
58.2506 + void * /* Client data for xCreate/xConnect */
58.2507 +);
58.2508 +
58.2509 +/*
58.2510 +** This routine is identical to the sqlite3_create_module() method above,
58.2511 +** except that it allows a destructor function to be specified. It is
58.2512 +** even more experimental than the rest of the virtual tables API.
58.2513 +*/
58.2514 +int sqlite3_create_module_v2(
58.2515 + sqlite3 *db, /* SQLite connection to register module with */
58.2516 + const char *zName, /* Name of the module */
58.2517 + const sqlite3_module *, /* Methods for the module */
58.2518 + void *, /* Client data for xCreate/xConnect */
58.2519 + void(*xDestroy)(void*) /* Module destructor function */
58.2520 +);
58.2521 +
58.2522 +/*
58.2523 +** Every module implementation uses a subclass of the following structure
58.2524 +** to describe a particular instance of the module. Each subclass will
58.2525 +** be taylored to the specific needs of the module implementation. The
58.2526 +** purpose of this superclass is to define certain fields that are common
58.2527 +** to all module implementations.
58.2528 +**
58.2529 +** Virtual tables methods can set an error message by assigning a
58.2530 +** string obtained from sqlite3_mprintf() to zErrMsg. The method should
58.2531 +** take care that any prior string is freed by a call to sqlite3_free()
58.2532 +** prior to assigning a new string to zErrMsg. After the error message
58.2533 +** is delivered up to the client application, the string will be automatically
58.2534 +** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note
58.2535 +** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
58.2536 +** since virtual tables are commonly implemented in loadable extensions which
58.2537 +** do not have access to sqlite3MPrintf() or sqlite3Free().
58.2538 +*/
58.2539 +struct sqlite3_vtab {
58.2540 + const sqlite3_module *pModule; /* The module for this virtual table */
58.2541 + int nRef; /* Used internally */
58.2542 + char *zErrMsg; /* Error message from sqlite3_mprintf() */
58.2543 + /* Virtual table implementations will typically add additional fields */
58.2544 +};
58.2545 +
58.2546 +/* Every module implementation uses a subclass of the following structure
58.2547 +** to describe cursors that point into the virtual table and are used
58.2548 +** to loop through the virtual table. Cursors are created using the
58.2549 +** xOpen method of the module. Each module implementation will define
58.2550 +** the content of a cursor structure to suit its own needs.
58.2551 +**
58.2552 +** This superclass exists in order to define fields of the cursor that
58.2553 +** are common to all implementations.
58.2554 +*/
58.2555 +struct sqlite3_vtab_cursor {
58.2556 + sqlite3_vtab *pVtab; /* Virtual table of this cursor */
58.2557 + /* Virtual table implementations will typically add additional fields */
58.2558 +};
58.2559 +
58.2560 +/*
58.2561 +** The xCreate and xConnect methods of a module use the following API
58.2562 +** to declare the format (the names and datatypes of the columns) of
58.2563 +** the virtual tables they implement.
58.2564 +*/
58.2565 +int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
58.2566 +
58.2567 +/*
58.2568 +** Virtual tables can provide alternative implementations of functions
58.2569 +** using the xFindFunction method. But global versions of those functions
58.2570 +** must exist in order to be overloaded.
58.2571 +**
58.2572 +** This API makes sure a global version of a function with a particular
58.2573 +** name and number of parameters exists. If no such function exists
58.2574 +** before this API is called, a new function is created. The implementation
58.2575 +** of the new function always causes an exception to be thrown. So
58.2576 +** the new function is not good for anything by itself. Its only
58.2577 +** purpose is to be a place-holder function that can be overloaded
58.2578 +** by virtual tables.
58.2579 +**
58.2580 +** This API should be considered part of the virtual table interface,
58.2581 +** which is experimental and subject to change.
58.2582 +*/
58.2583 +int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
58.2584 +
58.2585 +/*
58.2586 +** The interface to the virtual-table mechanism defined above (back up
58.2587 +** to a comment remarkably similar to this one) is currently considered
58.2588 +** to be experimental. The interface might change in incompatible ways.
58.2589 +** If this is a problem for you, do not use the interface at this time.
58.2590 +**
58.2591 +** When the virtual-table mechanism stablizes, we will declare the
58.2592 +** interface fixed, support it indefinitely, and remove this comment.
58.2593 +**
58.2594 +****** EXPERIMENTAL - subject to change without notice **************
58.2595 +*/
58.2596 +
58.2597 +/*
58.2598 +** CAPI3REF: A Handle To An Open BLOB
58.2599 +**
58.2600 +** An instance of the following opaque structure is used to
58.2601 +** represent an blob-handle. A blob-handle is created by
58.2602 +** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()].
58.2603 +** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
58.2604 +** can be used to read or write small subsections of the blob.
58.2605 +** The [sqltie3_blob_size()] interface returns the size of the
58.2606 +** blob in bytes.
58.2607 +*/
58.2608 +typedef struct sqlite3_blob sqlite3_blob;
58.2609 +
58.2610 +/*
58.2611 +** CAPI3REF: Open A BLOB For Incremental I/O
58.2612 +**
58.2613 +** Open a handle to the blob located in row iRow,, column zColumn,
58.2614 +** table zTable in database zDb. i.e. the same blob that would
58.2615 +** be selected by:
58.2616 +**
58.2617 +** <pre>
58.2618 +** SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
58.2619 +** </pre>
58.2620 +**
58.2621 +** If the flags parameter is non-zero, the blob is opened for
58.2622 +** read and write access. If it is zero, the blob is opened for read
58.2623 +** access.
58.2624 +**
58.2625 +** On success, [SQLITE_OK] is returned and the new
58.2626 +** [sqlite3_blob | blob handle] is written to *ppBlob.
58.2627 +** Otherwise an error code is returned and
58.2628 +** any value written to *ppBlob should not be used by the caller.
58.2629 +** This function sets the database-handle error code and message
58.2630 +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
58.2631 +*/
58.2632 +int sqlite3_blob_open(
58.2633 + sqlite3*,
58.2634 + const char *zDb,
58.2635 + const char *zTable,
58.2636 + const char *zColumn,
58.2637 + sqlite_int64 iRow,
58.2638 + int flags,
58.2639 + sqlite3_blob **ppBlob
58.2640 +);
58.2641 +
58.2642 +/*
58.2643 +** CAPI3REF: Close A BLOB Handle
58.2644 +**
58.2645 +** Close an open [sqlite3_blob | blob handle].
58.2646 +*/
58.2647 +int sqlite3_blob_close(sqlite3_blob *);
58.2648 +
58.2649 +/*
58.2650 +** CAPI3REF: Return The Size Of An Open BLOB
58.2651 +**
58.2652 +** Return the size in bytes of the blob accessible via the open
58.2653 +** [sqlite3_blob | blob-handle] passed as an argument.
58.2654 +*/
58.2655 +int sqlite3_blob_bytes(sqlite3_blob *);
58.2656 +
58.2657 +/*
58.2658 +** CAPI3REF: Read Data From A BLOB Incrementally
58.2659 +**
58.2660 +** This function is used to read data from an open
58.2661 +** [sqlite3_blob | blob-handle] into a caller supplied buffer.
58.2662 +** n bytes of data are copied into buffer
58.2663 +** z from the open blob, starting at offset iOffset.
58.2664 +**
58.2665 +** On success, SQLITE_OK is returned. Otherwise, an
58.2666 +** [SQLITE_ERROR | SQLite error code] or an
58.2667 +** [SQLITE_IOERR_READ | extended error code] is returned.
58.2668 +*/
58.2669 +int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset);
58.2670 +
58.2671 +/*
58.2672 +** CAPI3REF: Write Data Into A BLOB Incrementally
58.2673 +**
58.2674 +** This function is used to write data into an open
58.2675 +** [sqlite3_blob | blob-handle] from a user supplied buffer.
58.2676 +** n bytes of data are copied from the buffer
58.2677 +** pointed to by z into the open blob, starting at offset iOffset.
58.2678 +**
58.2679 +** If the [sqlite3_blob | blob-handle] passed as the first argument
58.2680 +** was not opened for writing (the flags parameter to [sqlite3_blob_open()]
58.2681 +*** was zero), this function returns [SQLITE_READONLY].
58.2682 +**
58.2683 +** This function may only modify the contents of the blob, it is
58.2684 +** not possible to increase the size of a blob using this API. If
58.2685 +** offset iOffset is less than n bytes from the end of the blob,
58.2686 +** [SQLITE_ERROR] is returned and no data is written.
58.2687 +**
58.2688 +** On success, SQLITE_OK is returned. Otherwise, an
58.2689 +** [SQLITE_ERROR | SQLite error code] or an
58.2690 +** [SQLITE_IOERR_READ | extended error code] is returned.
58.2691 +*/
58.2692 +int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
58.2693 +
58.2694 +/*
58.2695 +** Undo the hack that converts floating point types to integer for
58.2696 +** builds on processors without floating point support.
58.2697 +*/
58.2698 +#ifdef SQLITE_OMIT_FLOATING_POINT
58.2699 +# undef double
58.2700 +#endif
58.2701 +
58.2702 +#ifdef __cplusplus
58.2703 +} /* End of the 'extern "C"' block */
58.2704 +#endif
58.2705 +#endif
59.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
59.2 +++ b/extensions/sqlite/sqlite-source/sqlite3ext.h Sun Jul 29 01:15:31 2007 +0000
59.3 @@ -0,0 +1,298 @@
59.4 +/*
59.5 +** 2006 June 7
59.6 +**
59.7 +** The author disclaims copyright to this source code. In place of
59.8 +** a legal notice, here is a blessing:
59.9 +**
59.10 +** May you do good and not evil.
59.11 +** May you find forgiveness for yourself and forgive others.
59.12 +** May you share freely, never taking more than you give.
59.13 +**
59.14 +*************************************************************************
59.15 +** This header file defines the SQLite interface for use by
59.16 +** shared libraries that want to be imported as extensions into
59.17 +** an SQLite instance. Shared libraries that intend to be loaded
59.18 +** as extensions by SQLite should #include this file instead of
59.19 +** sqlite3.h.
59.20 +**
59.21 +** @(#) $Id$
59.22 +*/
59.23 +#ifndef _SQLITE3EXT_H_
59.24 +#define _SQLITE3EXT_H_
59.25 +#include "sqlite3.h"
59.26 +
59.27 +typedef struct sqlite3_api_routines sqlite3_api_routines;
59.28 +
59.29 +/*
59.30 +** The following structure hold pointers to all of the SQLite API
59.31 +** routines.
59.32 +**
59.33 +** WARNING: In order to maintain backwards compatibility, add new
59.34 +** interfaces to the end of this structure only. If you insert new
59.35 +** interfaces in the middle of this structure, then older different
59.36 +** versions of SQLite will not be able to load each others shared
59.37 +** libraries!
59.38 +*/
59.39 +struct sqlite3_api_routines {
59.40 + void * (*aggregate_context)(sqlite3_context*,int nBytes);
59.41 + int (*aggregate_count)(sqlite3_context*);
59.42 + int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
59.43 + int (*bind_double)(sqlite3_stmt*,int,double);
59.44 + int (*bind_int)(sqlite3_stmt*,int,int);
59.45 + int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
59.46 + int (*bind_null)(sqlite3_stmt*,int);
59.47 + int (*bind_parameter_count)(sqlite3_stmt*);
59.48 + int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
59.49 + const char * (*bind_parameter_name)(sqlite3_stmt*,int);
59.50 + int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
59.51 + int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
59.52 + int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
59.53 + int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
59.54 + int (*busy_timeout)(sqlite3*,int ms);
59.55 + int (*changes)(sqlite3*);
59.56 + int (*close)(sqlite3*);
59.57 + int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
59.58 + int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
59.59 + const void * (*column_blob)(sqlite3_stmt*,int iCol);
59.60 + int (*column_bytes)(sqlite3_stmt*,int iCol);
59.61 + int (*column_bytes16)(sqlite3_stmt*,int iCol);
59.62 + int (*column_count)(sqlite3_stmt*pStmt);
59.63 + const char * (*column_database_name)(sqlite3_stmt*,int);
59.64 + const void * (*column_database_name16)(sqlite3_stmt*,int);
59.65 + const char * (*column_decltype)(sqlite3_stmt*,int i);
59.66 + const void * (*column_decltype16)(sqlite3_stmt*,int);
59.67 + double (*column_double)(sqlite3_stmt*,int iCol);
59.68 + int (*column_int)(sqlite3_stmt*,int iCol);
59.69 + sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
59.70 + const char * (*column_name)(sqlite3_stmt*,int);
59.71 + const void * (*column_name16)(sqlite3_stmt*,int);
59.72 + const char * (*column_origin_name)(sqlite3_stmt*,int);
59.73 + const void * (*column_origin_name16)(sqlite3_stmt*,int);
59.74 + const char * (*column_table_name)(sqlite3_stmt*,int);
59.75 + const void * (*column_table_name16)(sqlite3_stmt*,int);
59.76 + const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
59.77 + const void * (*column_text16)(sqlite3_stmt*,int iCol);
59.78 + int (*column_type)(sqlite3_stmt*,int iCol);
59.79 + sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
59.80 + void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
59.81 + int (*complete)(const char*sql);
59.82 + int (*complete16)(const void*sql);
59.83 + int (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
59.84 + int (*create_collation16)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
59.85 + int (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
59.86 + int (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
59.87 + int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
59.88 + int (*data_count)(sqlite3_stmt*pStmt);
59.89 + sqlite3 * (*db_handle)(sqlite3_stmt*);
59.90 + int (*declare_vtab)(sqlite3*,const char*);
59.91 + int (*enable_shared_cache)(int);
59.92 + int (*errcode)(sqlite3*db);
59.93 + const char * (*errmsg)(sqlite3*);
59.94 + const void * (*errmsg16)(sqlite3*);
59.95 + int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
59.96 + int (*expired)(sqlite3_stmt*);
59.97 + int (*finalize)(sqlite3_stmt*pStmt);
59.98 + void (*free)(void*);
59.99 + void (*free_table)(char**result);
59.100 + int (*get_autocommit)(sqlite3*);
59.101 + void * (*get_auxdata)(sqlite3_context*,int);
59.102 + int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
59.103 + int (*global_recover)(void);
59.104 + void (*interruptx)(sqlite3*);
59.105 + sqlite_int64 (*last_insert_rowid)(sqlite3*);
59.106 + const char * (*libversion)(void);
59.107 + int (*libversion_number)(void);
59.108 + void *(*malloc)(int);
59.109 + char * (*mprintf)(const char*,...);
59.110 + int (*open)(const char*,sqlite3**);
59.111 + int (*open16)(const void*,sqlite3**);
59.112 + int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
59.113 + int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
59.114 + void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
59.115 + void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
59.116 + void *(*realloc)(void*,int);
59.117 + int (*reset)(sqlite3_stmt*pStmt);
59.118 + void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
59.119 + void (*result_double)(sqlite3_context*,double);
59.120 + void (*result_error)(sqlite3_context*,const char*,int);
59.121 + void (*result_error16)(sqlite3_context*,const void*,int);
59.122 + void (*result_int)(sqlite3_context*,int);
59.123 + void (*result_int64)(sqlite3_context*,sqlite_int64);
59.124 + void (*result_null)(sqlite3_context*);
59.125 + void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
59.126 + void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
59.127 + void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
59.128 + void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
59.129 + void (*result_value)(sqlite3_context*,sqlite3_value*);
59.130 + void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
59.131 + int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
59.132 + void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
59.133 + char * (*snprintf)(int,char*,const char*,...);
59.134 + int (*step)(sqlite3_stmt*);
59.135 + int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
59.136 + void (*thread_cleanup)(void);
59.137 + int (*total_changes)(sqlite3*);
59.138 + void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
59.139 + int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
59.140 + void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
59.141 + void * (*user_data)(sqlite3_context*);
59.142 + const void * (*value_blob)(sqlite3_value*);
59.143 + int (*value_bytes)(sqlite3_value*);
59.144 + int (*value_bytes16)(sqlite3_value*);
59.145 + double (*value_double)(sqlite3_value*);
59.146 + int (*value_int)(sqlite3_value*);
59.147 + sqlite_int64 (*value_int64)(sqlite3_value*);
59.148 + int (*value_numeric_type)(sqlite3_value*);
59.149 + const unsigned char * (*value_text)(sqlite3_value*);
59.150 + const void * (*value_text16)(sqlite3_value*);
59.151 + const void * (*value_text16be)(sqlite3_value*);
59.152 + const void * (*value_text16le)(sqlite3_value*);
59.153 + int (*value_type)(sqlite3_value*);
59.154 + char *(*vmprintf)(const char*,va_list);
59.155 + int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
59.156 + int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
59.157 + int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
59.158 + int (*clear_bindings)(sqlite3_stmt*);
59.159 + int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
59.160 +};
59.161 +
59.162 +/*
59.163 +** The following macros redefine the API routines so that they are
59.164 +** redirected throught the global sqlite3_api structure.
59.165 +**
59.166 +** This header file is also used by the loadext.c source file
59.167 +** (part of the main SQLite library - not an extension) so that
59.168 +** it can get access to the sqlite3_api_routines structure
59.169 +** definition. But the main library does not want to redefine
59.170 +** the API. So the redefinition macros are only valid if the
59.171 +** SQLITE_CORE macros is undefined.
59.172 +*/
59.173 +#ifndef SQLITE_CORE
59.174 +#define sqlite3_aggregate_context sqlite3_api->aggregate_context
59.175 +#define sqlite3_aggregate_count sqlite3_api->aggregate_count
59.176 +#define sqlite3_bind_blob sqlite3_api->bind_blob
59.177 +#define sqlite3_bind_double sqlite3_api->bind_double
59.178 +#define sqlite3_bind_int sqlite3_api->bind_int
59.179 +#define sqlite3_bind_int64 sqlite3_api->bind_int64
59.180 +#define sqlite3_bind_null sqlite3_api->bind_null
59.181 +#define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
59.182 +#define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
59.183 +#define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
59.184 +#define sqlite3_bind_text sqlite3_api->bind_text
59.185 +#define sqlite3_bind_text16 sqlite3_api->bind_text16
59.186 +#define sqlite3_bind_value sqlite3_api->bind_value
59.187 +#define sqlite3_busy_handler sqlite3_api->busy_handler
59.188 +#define sqlite3_busy_timeout sqlite3_api->busy_timeout
59.189 +#define sqlite3_changes sqlite3_api->changes
59.190 +#define sqlite3_close sqlite3_api->close
59.191 +#define sqlite3_collation_needed sqlite3_api->collation_needed
59.192 +#define sqlite3_collation_needed16 sqlite3_api->collation_needed16
59.193 +#define sqlite3_column_blob sqlite3_api->column_blob
59.194 +#define sqlite3_column_bytes sqlite3_api->column_bytes
59.195 +#define sqlite3_column_bytes16 sqlite3_api->column_bytes16
59.196 +#define sqlite3_column_count sqlite3_api->column_count
59.197 +#define sqlite3_column_database_name sqlite3_api->column_database_name
59.198 +#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
59.199 +#define sqlite3_column_decltype sqlite3_api->column_decltype
59.200 +#define sqlite3_column_decltype16 sqlite3_api->column_decltype16
59.201 +#define sqlite3_column_double sqlite3_api->column_double
59.202 +#define sqlite3_column_int sqlite3_api->column_int
59.203 +#define sqlite3_column_int64 sqlite3_api->column_int64
59.204 +#define sqlite3_column_name sqlite3_api->column_name
59.205 +#define sqlite3_column_name16 sqlite3_api->column_name16
59.206 +#define sqlite3_column_origin_name sqlite3_api->column_origin_name
59.207 +#define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
59.208 +#define sqlite3_column_table_name sqlite3_api->column_table_name
59.209 +#define sqlite3_column_table_name16 sqlite3_api->column_table_name16
59.210 +#define sqlite3_column_text sqlite3_api->column_text
59.211 +#define sqlite3_column_text16 sqlite3_api->column_text16
59.212 +#define sqlite3_column_type sqlite3_api->column_type
59.213 +#define sqlite3_column_value sqlite3_api->column_value
59.214 +#define sqlite3_commit_hook sqlite3_api->commit_hook
59.215 +#define sqlite3_complete sqlite3_api->complete
59.216 +#define sqlite3_complete16 sqlite3_api->complete16
59.217 +#define sqlite3_create_collation sqlite3_api->create_collation
59.218 +#define sqlite3_create_collation16 sqlite3_api->create_collation16
59.219 +#define sqlite3_create_function sqlite3_api->create_function
59.220 +#define sqlite3_create_function16 sqlite3_api->create_function16
59.221 +#define sqlite3_create_module sqlite3_api->create_module
59.222 +#define sqlite3_create_module_v2 sqlite3_api->create_module_v2
59.223 +#define sqlite3_data_count sqlite3_api->data_count
59.224 +#define sqlite3_db_handle sqlite3_api->db_handle
59.225 +#define sqlite3_declare_vtab sqlite3_api->declare_vtab
59.226 +#define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
59.227 +#define sqlite3_errcode sqlite3_api->errcode
59.228 +#define sqlite3_errmsg sqlite3_api->errmsg
59.229 +#define sqlite3_errmsg16 sqlite3_api->errmsg16
59.230 +#define sqlite3_exec sqlite3_api->exec
59.231 +#define sqlite3_expired sqlite3_api->expired
59.232 +#define sqlite3_finalize sqlite3_api->finalize
59.233 +#define sqlite3_free sqlite3_api->free
59.234 +#define sqlite3_free_table sqlite3_api->free_table
59.235 +#define sqlite3_get_autocommit sqlite3_api->get_autocommit
59.236 +#define sqlite3_get_auxdata sqlite3_api->get_auxdata
59.237 +#define sqlite3_get_table sqlite3_api->get_table
59.238 +#define sqlite3_global_recover sqlite3_api->global_recover
59.239 +#define sqlite3_interrupt sqlite3_api->interruptx
59.240 +#define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
59.241 +#define sqlite3_libversion sqlite3_api->libversion
59.242 +#define sqlite3_libversion_number sqlite3_api->libversion_number
59.243 +#define sqlite3_malloc sqlite3_api->malloc
59.244 +#define sqlite3_mprintf sqlite3_api->mprintf
59.245 +#define sqlite3_open sqlite3_api->open
59.246 +#define sqlite3_open16 sqlite3_api->open16
59.247 +#define sqlite3_prepare sqlite3_api->prepare
59.248 +#define sqlite3_prepare16 sqlite3_api->prepare16
59.249 +#define sqlite3_prepare_v2 sqlite3_api->prepare_v2
59.250 +#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
59.251 +#define sqlite3_profile sqlite3_api->profile
59.252 +#define sqlite3_progress_handler sqlite3_api->progress_handler
59.253 +#define sqlite3_realloc sqlite3_api->realloc
59.254 +#define sqlite3_reset sqlite3_api->reset
59.255 +#define sqlite3_result_blob sqlite3_api->result_blob
59.256 +#define sqlite3_result_double sqlite3_api->result_double
59.257 +#define sqlite3_result_error sqlite3_api->result_error
59.258 +#define sqlite3_result_error16 sqlite3_api->result_error16
59.259 +#define sqlite3_result_int sqlite3_api->result_int
59.260 +#define sqlite3_result_int64 sqlite3_api->result_int64
59.261 +#define sqlite3_result_null sqlite3_api->result_null
59.262 +#define sqlite3_result_text sqlite3_api->result_text
59.263 +#define sqlite3_result_text16 sqlite3_api->result_text16
59.264 +#define sqlite3_result_text16be sqlite3_api->result_text16be
59.265 +#define sqlite3_result_text16le sqlite3_api->result_text16le
59.266 +#define sqlite3_result_value sqlite3_api->result_value
59.267 +#define sqlite3_rollback_hook sqlite3_api->rollback_hook
59.268 +#define sqlite3_set_authorizer sqlite3_api->set_authorizer
59.269 +#define sqlite3_set_auxdata sqlite3_api->set_auxdata
59.270 +#define sqlite3_snprintf sqlite3_api->snprintf
59.271 +#define sqlite3_step sqlite3_api->step
59.272 +#define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
59.273 +#define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
59.274 +#define sqlite3_total_changes sqlite3_api->total_changes
59.275 +#define sqlite3_trace sqlite3_api->trace
59.276 +#define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
59.277 +#define sqlite3_update_hook sqlite3_api->update_hook
59.278 +#define sqlite3_user_data sqlite3_api->user_data
59.279 +#define sqlite3_value_blob sqlite3_api->value_blob
59.280 +#define sqlite3_value_bytes sqlite3_api->value_bytes
59.281 +#define sqlite3_value_bytes16 sqlite3_api->value_bytes16
59.282 +#define sqlite3_value_double sqlite3_api->value_double
59.283 +#define sqlite3_value_int sqlite3_api->value_int
59.284 +#define sqlite3_value_int64 sqlite3_api->value_int64
59.285 +#define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
59.286 +#define sqlite3_value_text sqlite3_api->value_text
59.287 +#define sqlite3_value_text16 sqlite3_api->value_text16
59.288 +#define sqlite3_value_text16be sqlite3_api->value_text16be
59.289 +#define sqlite3_value_text16le sqlite3_api->value_text16le
59.290 +#define sqlite3_value_type sqlite3_api->value_type
59.291 +#define sqlite3_vmprintf sqlite3_api->vmprintf
59.292 +#define sqlite3_overload_function sqlite3_api->overload_function
59.293 +#define sqlite3_prepare_v2 sqlite3_api->prepare_v2
59.294 +#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
59.295 +#define sqlite3_clear_bindings sqlite3_api->clear_bindings
59.296 +#endif /* SQLITE_CORE */
59.297 +
59.298 +#define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api;
59.299 +#define SQLITE_EXTENSION_INIT2(v) sqlite3_api = v;
59.300 +
59.301 +#endif /* _SQLITE3EXT_H_ */
60.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
60.2 +++ b/extensions/sqlite/sqlite-source/sqliteInt.h Sun Jul 29 01:15:31 2007 +0000
60.3 @@ -0,0 +1,2002 @@
60.4 +/*
60.5 +** 2001 September 15
60.6 +**
60.7 +** The author disclaims copyright to this source code. In place of
60.8 +** a legal notice, here is a blessing:
60.9 +**
60.10 +** May you do good and not evil.
60.11 +** May you find forgiveness for yourself and forgive others.
60.12 +** May you share freely, never taking more than you give.
60.13 +**
60.14 +*************************************************************************
60.15 +** Internal interface definitions for SQLite.
60.16 +**
60.17 +** @(#) $Id$
60.18 +*/
60.19 +#ifndef _SQLITEINT_H_
60.20 +#define _SQLITEINT_H_
60.21 +#include "sqliteLimit.h"
60.22 +
60.23 +
60.24 +#if defined(SQLITE_TCL) || defined(TCLSH)
60.25 +# include <tcl.h>
60.26 +#endif
60.27 +
60.28 +/*
60.29 +** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
60.30 +** Setting NDEBUG makes the code smaller and run faster. So the following
60.31 +** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
60.32 +** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out
60.33 +** feature.
60.34 +*/
60.35 +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
60.36 +# define NDEBUG 1
60.37 +#endif
60.38 +
60.39 +/*
60.40 +** These #defines should enable >2GB file support on Posix if the
60.41 +** underlying operating system supports it. If the OS lacks
60.42 +** large file support, or if the OS is windows, these should be no-ops.
60.43 +**
60.44 +** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
60.45 +** on the compiler command line. This is necessary if you are compiling
60.46 +** on a recent machine (ex: RedHat 7.2) but you want your code to work
60.47 +** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
60.48 +** without this option, LFS is enable. But LFS does not exist in the kernel
60.49 +** in RedHat 6.0, so the code won't work. Hence, for maximum binary
60.50 +** portability you should omit LFS.
60.51 +**
60.52 +** Similar is true for MacOS. LFS is only supported on MacOS 9 and later.
60.53 +*/
60.54 +#ifndef SQLITE_DISABLE_LFS
60.55 +# define _LARGE_FILE 1
60.56 +# ifndef _FILE_OFFSET_BITS
60.57 +# define _FILE_OFFSET_BITS 64
60.58 +# endif
60.59 +# define _LARGEFILE_SOURCE 1
60.60 +#endif
60.61 +
60.62 +#include "sqlite3.h"
60.63 +#include "hash.h"
60.64 +#include "parse.h"
60.65 +#include <stdio.h>
60.66 +#include <stdlib.h>
60.67 +#include <string.h>
60.68 +#include <assert.h>
60.69 +#include <stddef.h>
60.70 +
60.71 +#define sqlite3_isnan(X) ((X)!=(X))
60.72 +
60.73 +/*
60.74 +** If compiling for a processor that lacks floating point support,
60.75 +** substitute integer for floating-point
60.76 +*/
60.77 +#ifdef SQLITE_OMIT_FLOATING_POINT
60.78 +# define double sqlite_int64
60.79 +# define LONGDOUBLE_TYPE sqlite_int64
60.80 +# ifndef SQLITE_BIG_DBL
60.81 +# define SQLITE_BIG_DBL (0x7fffffffffffffff)
60.82 +# endif
60.83 +# define SQLITE_OMIT_DATETIME_FUNCS 1
60.84 +# define SQLITE_OMIT_TRACE 1
60.85 +# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
60.86 +#endif
60.87 +#ifndef SQLITE_BIG_DBL
60.88 +# define SQLITE_BIG_DBL (1e99)
60.89 +#endif
60.90 +
60.91 +/*
60.92 +** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
60.93 +** afterward. Having this macro allows us to cause the C compiler
60.94 +** to omit code used by TEMP tables without messy #ifndef statements.
60.95 +*/
60.96 +#ifdef SQLITE_OMIT_TEMPDB
60.97 +#define OMIT_TEMPDB 1
60.98 +#else
60.99 +#define OMIT_TEMPDB 0
60.100 +#endif
60.101 +
60.102 +/*
60.103 +** If the following macro is set to 1, then NULL values are considered
60.104 +** distinct when determining whether or not two entries are the same
60.105 +** in a UNIQUE index. This is the way PostgreSQL, Oracle, DB2, MySQL,
60.106 +** OCELOT, and Firebird all work. The SQL92 spec explicitly says this
60.107 +** is the way things are suppose to work.
60.108 +**
60.109 +** If the following macro is set to 0, the NULLs are indistinct for
60.110 +** a UNIQUE index. In this mode, you can only have a single NULL entry
60.111 +** for a column declared UNIQUE. This is the way Informix and SQL Server
60.112 +** work.
60.113 +*/
60.114 +#define NULL_DISTINCT_FOR_UNIQUE 1
60.115 +
60.116 +/*
60.117 +** The "file format" number is an integer that is incremented whenever
60.118 +** the VDBE-level file format changes. The following macros define the
60.119 +** the default file format for new databases and the maximum file format
60.120 +** that the library can read.
60.121 +*/
60.122 +#define SQLITE_MAX_FILE_FORMAT 4
60.123 +#ifndef SQLITE_DEFAULT_FILE_FORMAT
60.124 +# define SQLITE_DEFAULT_FILE_FORMAT 1
60.125 +#endif
60.126 +
60.127 +/*
60.128 +** Provide a default value for TEMP_STORE in case it is not specified
60.129 +** on the command-line
60.130 +*/
60.131 +#ifndef TEMP_STORE
60.132 +# define TEMP_STORE 1
60.133 +#endif
60.134 +
60.135 +/*
60.136 +** GCC does not define the offsetof() macro so we'll have to do it
60.137 +** ourselves.
60.138 +*/
60.139 +#ifndef offsetof
60.140 +#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
60.141 +#endif
60.142 +
60.143 +/*
60.144 +** Check to see if this machine uses EBCDIC. (Yes, believe it or
60.145 +** not, there are still machines out there that use EBCDIC.)
60.146 +*/
60.147 +#if 'A' == '\301'
60.148 +# define SQLITE_EBCDIC 1
60.149 +#else
60.150 +# define SQLITE_ASCII 1
60.151 +#endif
60.152 +
60.153 +/*
60.154 +** Integers of known sizes. These typedefs might change for architectures
60.155 +** where the sizes very. Preprocessor macros are available so that the
60.156 +** types can be conveniently redefined at compile-type. Like this:
60.157 +**
60.158 +** cc '-DUINTPTR_TYPE=long long int' ...
60.159 +*/
60.160 +#ifndef UINT32_TYPE
60.161 +# define UINT32_TYPE unsigned int
60.162 +#endif
60.163 +#ifndef UINT16_TYPE
60.164 +# define UINT16_TYPE unsigned short int
60.165 +#endif
60.166 +#ifndef INT16_TYPE
60.167 +# define INT16_TYPE short int
60.168 +#endif
60.169 +#ifndef UINT8_TYPE
60.170 +# define UINT8_TYPE unsigned char
60.171 +#endif
60.172 +#ifndef INT8_TYPE
60.173 +# define INT8_TYPE signed char
60.174 +#endif
60.175 +#ifndef LONGDOUBLE_TYPE
60.176 +# define LONGDOUBLE_TYPE long double
60.177 +#endif
60.178 +typedef sqlite_int64 i64; /* 8-byte signed integer */
60.179 +typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
60.180 +typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
60.181 +typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
60.182 +typedef INT16_TYPE i16; /* 2-byte signed integer */
60.183 +typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
60.184 +typedef UINT8_TYPE i8; /* 1-byte signed integer */
60.185 +
60.186 +/*
60.187 +** Macros to determine whether the machine is big or little endian,
60.188 +** evaluated at runtime.
60.189 +*/
60.190 +extern const int sqlite3one;
60.191 +#if defined(i386) || defined(__i386__) || defined(_M_IX86)
60.192 +# define SQLITE_BIGENDIAN 0
60.193 +# define SQLITE_LITTLEENDIAN 1
60.194 +# define SQLITE_UTF16NATIVE SQLITE_UTF16LE
60.195 +#else
60.196 +# define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
60.197 +# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
60.198 +# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
60.199 +#endif
60.200 +
60.201 +/*
60.202 +** An instance of the following structure is used to store the busy-handler
60.203 +** callback for a given sqlite handle.
60.204 +**
60.205 +** The sqlite.busyHandler member of the sqlite struct contains the busy
60.206 +** callback for the database handle. Each pager opened via the sqlite
60.207 +** handle is passed a pointer to sqlite.busyHandler. The busy-handler
60.208 +** callback is currently invoked only from within pager.c.
60.209 +*/
60.210 +typedef struct BusyHandler BusyHandler;
60.211 +struct BusyHandler {
60.212 + int (*xFunc)(void *,int); /* The busy callback */
60.213 + void *pArg; /* First arg to busy callback */
60.214 + int nBusy; /* Incremented with each busy call */
60.215 +};
60.216 +
60.217 +/*
60.218 +** Defer sourcing vdbe.h and btree.h until after the "u8" and
60.219 +** "BusyHandler typedefs.
60.220 +*/
60.221 +#include "vdbe.h"
60.222 +#include "btree.h"
60.223 +#include "pager.h"
60.224 +
60.225 +#ifdef SQLITE_MEMDEBUG
60.226 +/*
60.227 +** The following global variables are used for testing and debugging
60.228 +** only. They only work if SQLITE_MEMDEBUG is defined.
60.229 +*/
60.230 +extern int sqlite3_nMalloc; /* Number of sqliteMalloc() calls */
60.231 +extern int sqlite3_nFree; /* Number of sqliteFree() calls */
60.232 +extern int sqlite3_iMallocFail; /* Fail sqliteMalloc() after this many calls */
60.233 +extern int sqlite3_iMallocReset; /* Set iMallocFail to this when it reaches 0 */
60.234 +
60.235 +extern void *sqlite3_pFirst; /* Pointer to linked list of allocations */
60.236 +extern int sqlite3_nMaxAlloc; /* High water mark of ThreadData.nAlloc */
60.237 +extern int sqlite3_mallocDisallowed; /* assert() in sqlite3Malloc() if set */
60.238 +extern int sqlite3_isFail; /* True if all malloc calls should fail */
60.239 +extern const char *sqlite3_zFile; /* Filename to associate debug info with */
60.240 +extern int sqlite3_iLine; /* Line number for debug info */
60.241 +
60.242 +#define ENTER_MALLOC (sqlite3_zFile = __FILE__, sqlite3_iLine = __LINE__)
60.243 +#define sqliteMalloc(x) (ENTER_MALLOC, sqlite3Malloc(x,1))
60.244 +#define sqliteMallocRaw(x) (ENTER_MALLOC, sqlite3MallocRaw(x,1))
60.245 +#define sqliteRealloc(x,y) (ENTER_MALLOC, sqlite3Realloc(x,y))
60.246 +#define sqliteStrDup(x) (ENTER_MALLOC, sqlite3StrDup(x))
60.247 +#define sqliteStrNDup(x,y) (ENTER_MALLOC, sqlite3StrNDup(x,y))
60.248 +#define sqliteReallocOrFree(x,y) (ENTER_MALLOC, sqlite3ReallocOrFree(x,y))
60.249 +
60.250 +#else
60.251 +
60.252 +#define ENTER_MALLOC 0
60.253 +#define sqliteMalloc(x) sqlite3Malloc(x,1)
60.254 +#define sqliteMallocRaw(x) sqlite3MallocRaw(x,1)
60.255 +#define sqliteRealloc(x,y) sqlite3Realloc(x,y)
60.256 +#define sqliteStrDup(x) sqlite3StrDup(x)
60.257 +#define sqliteStrNDup(x,y) sqlite3StrNDup(x,y)
60.258 +#define sqliteReallocOrFree(x,y) sqlite3ReallocOrFree(x,y)
60.259 +
60.260 +#endif
60.261 +
60.262 +/* Variable sqlite3_mallocHasFailed is set to true after a malloc()
60.263 +** failure occurs.
60.264 +**
60.265 +** The sqlite3MallocFailed() macro returns true if a malloc has failed
60.266 +** in this thread since the last call to sqlite3ApiExit(), or false
60.267 +** otherwise.
60.268 +*/
60.269 +extern int sqlite3_mallocHasFailed;
60.270 +#define sqlite3MallocFailed() (sqlite3_mallocHasFailed && sqlite3OsInMutex(1))
60.271 +
60.272 +#define sqliteFree(x) sqlite3FreeX(x)
60.273 +#define sqliteAllocSize(x) sqlite3AllocSize(x)
60.274 +
60.275 +/*
60.276 +** An instance of this structure might be allocated to store information
60.277 +** specific to a single thread.
60.278 +*/
60.279 +struct ThreadData {
60.280 + int dummy; /* So that this structure is never empty */
60.281 +
60.282 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
60.283 + int nSoftHeapLimit; /* Suggested max mem allocation. No limit if <0 */
60.284 + int nAlloc; /* Number of bytes currently allocated */
60.285 + Pager *pPager; /* Linked list of all pagers in this thread */
60.286 +#endif
60.287 +
60.288 +#ifndef SQLITE_OMIT_SHARED_CACHE
60.289 + u8 useSharedData; /* True if shared pagers and schemas are enabled */
60.290 + BtShared *pBtree; /* Linked list of all currently open BTrees */
60.291 +#endif
60.292 +};
60.293 +
60.294 +/*
60.295 +** Name of the master database table. The master database table
60.296 +** is a special table that holds the names and attributes of all
60.297 +** user tables and indices.
60.298 +*/
60.299 +#define MASTER_NAME "sqlite_master"
60.300 +#define TEMP_MASTER_NAME "sqlite_temp_master"
60.301 +
60.302 +/*
60.303 +** The root-page of the master database table.
60.304 +*/
60.305 +#define MASTER_ROOT 1
60.306 +
60.307 +/*
60.308 +** The name of the schema table.
60.309 +*/
60.310 +#define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
60.311 +
60.312 +/*
60.313 +** A convenience macro that returns the number of elements in
60.314 +** an array.
60.315 +*/
60.316 +#define ArraySize(X) (sizeof(X)/sizeof(X[0]))
60.317 +
60.318 +/*
60.319 +** Forward references to structures
60.320 +*/
60.321 +typedef struct AggInfo AggInfo;
60.322 +typedef struct AuthContext AuthContext;
60.323 +typedef struct CollSeq CollSeq;
60.324 +typedef struct Column Column;
60.325 +typedef struct Db Db;
60.326 +typedef struct Schema Schema;
60.327 +typedef struct Expr Expr;
60.328 +typedef struct ExprList ExprList;
60.329 +typedef struct FKey FKey;
60.330 +typedef struct FuncDef FuncDef;
60.331 +typedef struct IdList IdList;
60.332 +typedef struct Index Index;
60.333 +typedef struct KeyClass KeyClass;
60.334 +typedef struct KeyInfo KeyInfo;
60.335 +typedef struct Module Module;
60.336 +typedef struct NameContext NameContext;
60.337 +typedef struct Parse Parse;
60.338 +typedef struct Select Select;
60.339 +typedef struct SrcList SrcList;
60.340 +typedef struct ThreadData ThreadData;
60.341 +typedef struct Table Table;
60.342 +typedef struct TableLock TableLock;
60.343 +typedef struct Token Token;
60.344 +typedef struct TriggerStack TriggerStack;
60.345 +typedef struct TriggerStep TriggerStep;
60.346 +typedef struct Trigger Trigger;
60.347 +typedef struct WhereInfo WhereInfo;
60.348 +typedef struct WhereLevel WhereLevel;
60.349 +
60.350 +#include "os.h"
60.351 +
60.352 +/*
60.353 +** Each database file to be accessed by the system is an instance
60.354 +** of the following structure. There are normally two of these structures
60.355 +** in the sqlite.aDb[] array. aDb[0] is the main database file and
60.356 +** aDb[1] is the database file used to hold temporary tables. Additional
60.357 +** databases may be attached.
60.358 +*/
60.359 +struct Db {
60.360 + char *zName; /* Name of this database */
60.361 + Btree *pBt; /* The B*Tree structure for this database file */
60.362 + u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
60.363 + u8 safety_level; /* How aggressive at synching data to disk */
60.364 + void *pAux; /* Auxiliary data. Usually NULL */
60.365 + void (*xFreeAux)(void*); /* Routine to free pAux */
60.366 + Schema *pSchema; /* Pointer to database schema (possibly shared) */
60.367 +};
60.368 +
60.369 +/*
60.370 +** An instance of the following structure stores a database schema.
60.371 +**
60.372 +** If there are no virtual tables configured in this schema, the
60.373 +** Schema.db variable is set to NULL. After the first virtual table
60.374 +** has been added, it is set to point to the database connection
60.375 +** used to create the connection. Once a virtual table has been
60.376 +** added to the Schema structure and the Schema.db variable populated,
60.377 +** only that database connection may use the Schema to prepare
60.378 +** statements.
60.379 +*/
60.380 +struct Schema {
60.381 + int schema_cookie; /* Database schema version number for this file */
60.382 + Hash tblHash; /* All tables indexed by name */
60.383 + Hash idxHash; /* All (named) indices indexed by name */
60.384 + Hash trigHash; /* All triggers indexed by name */
60.385 + Hash aFKey; /* Foreign keys indexed by to-table */
60.386 + Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
60.387 + u8 file_format; /* Schema format version for this file */
60.388 + u8 enc; /* Text encoding used by this database */
60.389 + u16 flags; /* Flags associated with this schema */
60.390 + int cache_size; /* Number of pages to use in the cache */
60.391 +#ifndef SQLITE_OMIT_VIRTUALTABLE
60.392 + sqlite3 *db; /* "Owner" connection. See comment above */
60.393 +#endif
60.394 +};
60.395 +
60.396 +/*
60.397 +** These macros can be used to test, set, or clear bits in the
60.398 +** Db.flags field.
60.399 +*/
60.400 +#define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
60.401 +#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
60.402 +#define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
60.403 +#define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
60.404 +
60.405 +/*
60.406 +** Allowed values for the DB.flags field.
60.407 +**
60.408 +** The DB_SchemaLoaded flag is set after the database schema has been
60.409 +** read into internal hash tables.
60.410 +**
60.411 +** DB_UnresetViews means that one or more views have column names that
60.412 +** have been filled out. If the schema changes, these column names might
60.413 +** changes and so the view will need to be reset.
60.414 +*/
60.415 +#define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
60.416 +#define DB_UnresetViews 0x0002 /* Some views have defined column names */
60.417 +#define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
60.418 +
60.419 +
60.420 +/*
60.421 +** Each database is an instance of the following structure.
60.422 +**
60.423 +** The sqlite.lastRowid records the last insert rowid generated by an
60.424 +** insert statement. Inserts on views do not affect its value. Each
60.425 +** trigger has its own context, so that lastRowid can be updated inside
60.426 +** triggers as usual. The previous value will be restored once the trigger
60.427 +** exits. Upon entering a before or instead of trigger, lastRowid is no
60.428 +** longer (since after version 2.8.12) reset to -1.
60.429 +**
60.430 +** The sqlite.nChange does not count changes within triggers and keeps no
60.431 +** context. It is reset at start of sqlite3_exec.
60.432 +** The sqlite.lsChange represents the number of changes made by the last
60.433 +** insert, update, or delete statement. It remains constant throughout the
60.434 +** length of a statement and is then updated by OP_SetCounts. It keeps a
60.435 +** context stack just like lastRowid so that the count of changes
60.436 +** within a trigger is not seen outside the trigger. Changes to views do not
60.437 +** affect the value of lsChange.
60.438 +** The sqlite.csChange keeps track of the number of current changes (since
60.439 +** the last statement) and is used to update sqlite_lsChange.
60.440 +**
60.441 +** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
60.442 +** store the most recent error code and, if applicable, string. The
60.443 +** internal function sqlite3Error() is used to set these variables
60.444 +** consistently.
60.445 +*/
60.446 +struct sqlite3 {
60.447 + int nDb; /* Number of backends currently in use */
60.448 + Db *aDb; /* All backends */
60.449 + int flags; /* Miscellanous flags. See below */
60.450 + int errCode; /* Most recent error code (SQLITE_*) */
60.451 + int errMask; /* & result codes with this before returning */
60.452 + u8 autoCommit; /* The auto-commit flag. */
60.453 + u8 temp_store; /* 1: file 2: memory 0: default */
60.454 + int nTable; /* Number of tables in the database */
60.455 + CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
60.456 + i64 lastRowid; /* ROWID of most recent insert (see above) */
60.457 + i64 priorNewRowid; /* Last randomly generated ROWID */
60.458 + int magic; /* Magic number for detect library misuse */
60.459 + int nChange; /* Value returned by sqlite3_changes() */
60.460 + int nTotalChange; /* Value returned by sqlite3_total_changes() */
60.461 + struct sqlite3InitInfo { /* Information used during initialization */
60.462 + int iDb; /* When back is being initialized */
60.463 + int newTnum; /* Rootpage of table being initialized */
60.464 + u8 busy; /* TRUE if currently initializing */
60.465 + } init;
60.466 + int nExtension; /* Number of loaded extensions */
60.467 + void **aExtension; /* Array of shared libraray handles */
60.468 + struct Vdbe *pVdbe; /* List of active virtual machines */
60.469 + int activeVdbeCnt; /* Number of vdbes currently executing */
60.470 + void (*xTrace)(void*,const char*); /* Trace function */
60.471 + void *pTraceArg; /* Argument to the trace function */
60.472 + void (*xProfile)(void*,const char*,u64); /* Profiling function */
60.473 + void *pProfileArg; /* Argument to profile function */
60.474 + void *pCommitArg; /* Argument to xCommitCallback() */
60.475 + int (*xCommitCallback)(void*); /* Invoked at every commit. */
60.476 + void *pRollbackArg; /* Argument to xRollbackCallback() */
60.477 + void (*xRollbackCallback)(void*); /* Invoked at every commit. */
60.478 + void *pUpdateArg;
60.479 + void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
60.480 + void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
60.481 + void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
60.482 + void *pCollNeededArg;
60.483 + sqlite3_value *pErr; /* Most recent error message */
60.484 + char *zErrMsg; /* Most recent error message (UTF-8 encoded) */
60.485 + char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */
60.486 + union {
60.487 + int isInterrupted; /* True if sqlite3_interrupt has been called */
60.488 + double notUsed1; /* Spacer */
60.489 + } u1;
60.490 +#ifndef SQLITE_OMIT_AUTHORIZATION
60.491 + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
60.492 + /* Access authorization function */
60.493 + void *pAuthArg; /* 1st argument to the access auth function */
60.494 +#endif
60.495 +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
60.496 + int (*xProgress)(void *); /* The progress callback */
60.497 + void *pProgressArg; /* Argument to the progress callback */
60.498 + int nProgressOps; /* Number of opcodes for progress callback */
60.499 +#endif
60.500 +#ifndef SQLITE_OMIT_VIRTUALTABLE
60.501 + Hash aModule; /* populated by sqlite3_create_module() */
60.502 + Table *pVTab; /* vtab with active Connect/Create method */
60.503 + sqlite3_vtab **aVTrans; /* Virtual tables with open transactions */
60.504 + int nVTrans; /* Allocated size of aVTrans */
60.505 +#endif
60.506 + Hash aFunc; /* All functions that can be in SQL exprs */
60.507 + Hash aCollSeq; /* All collating sequences */
60.508 + BusyHandler busyHandler; /* Busy callback */
60.509 + int busyTimeout; /* Busy handler timeout, in msec */
60.510 + Db aDbStatic[2]; /* Static space for the 2 default backends */
60.511 +#ifdef SQLITE_SSE
60.512 + sqlite3_stmt *pFetch; /* Used by SSE to fetch stored statements */
60.513 +#endif
60.514 + u8 dfltLockMode; /* Default locking-mode for attached dbs */
60.515 +};
60.516 +
60.517 +/*
60.518 +** A macro to discover the encoding of a database.
60.519 +*/
60.520 +#define ENC(db) ((db)->aDb[0].pSchema->enc)
60.521 +
60.522 +/*
60.523 +** Possible values for the sqlite.flags and or Db.flags fields.
60.524 +**
60.525 +** On sqlite.flags, the SQLITE_InTrans value means that we have
60.526 +** executed a BEGIN. On Db.flags, SQLITE_InTrans means a statement
60.527 +** transaction is active on that particular database file.
60.528 +*/
60.529 +#define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
60.530 +#define SQLITE_InTrans 0x00000008 /* True if in a transaction */
60.531 +#define SQLITE_InternChanges 0x00000010 /* Uncommitted Hash table changes */
60.532 +#define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
60.533 +#define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
60.534 +#define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
60.535 + /* DELETE, or UPDATE and return */
60.536 + /* the count using a callback. */
60.537 +#define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
60.538 + /* result set is empty */
60.539 +#define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
60.540 +#define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
60.541 +#define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
60.542 +#define SQLITE_NoReadlock 0x00001000 /* Readlocks are omitted when
60.543 + ** accessing read-only databases */
60.544 +#define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
60.545 +#define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
60.546 +#define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
60.547 +#define SQLITE_FullFSync 0x00010000 /* Use full fsync on the backend */
60.548 +#define SQLITE_LoadExtension 0x00020000 /* Enable load_extension */
60.549 +
60.550 +#define SQLITE_RecoveryMode 0x00040000 /* Ignore schema errors */
60.551 +
60.552 +/*
60.553 +** Possible values for the sqlite.magic field.
60.554 +** The numbers are obtained at random and have no special meaning, other
60.555 +** than being distinct from one another.
60.556 +*/
60.557 +#define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
60.558 +#define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
60.559 +#define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
60.560 +#define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
60.561 +
60.562 +/*
60.563 +** Each SQL function is defined by an instance of the following
60.564 +** structure. A pointer to this structure is stored in the sqlite.aFunc
60.565 +** hash table. When multiple functions have the same name, the hash table
60.566 +** points to a linked list of these structures.
60.567 +*/
60.568 +struct FuncDef {
60.569 + i16 nArg; /* Number of arguments. -1 means unlimited */
60.570 + u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
60.571 + u8 needCollSeq; /* True if sqlite3GetFuncCollSeq() might be called */
60.572 + u8 flags; /* Some combination of SQLITE_FUNC_* */
60.573 + void *pUserData; /* User data parameter */
60.574 + FuncDef *pNext; /* Next function with same name */
60.575 + void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
60.576 + void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
60.577 + void (*xFinalize)(sqlite3_context*); /* Aggregate finializer */
60.578 + char zName[1]; /* SQL name of the function. MUST BE LAST */
60.579 +};
60.580 +
60.581 +/*
60.582 +** Each SQLite module (virtual table definition) is defined by an
60.583 +** instance of the following structure, stored in the sqlite3.aModule
60.584 +** hash table.
60.585 +*/
60.586 +struct Module {
60.587 + const sqlite3_module *pModule; /* Callback pointers */
60.588 + const char *zName; /* Name passed to create_module() */
60.589 + void *pAux; /* pAux passed to create_module() */
60.590 + void (*xDestroy)(void *); /* Module destructor function */
60.591 +};
60.592 +
60.593 +/*
60.594 +** Possible values for FuncDef.flags
60.595 +*/
60.596 +#define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */
60.597 +#define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */
60.598 +#define SQLITE_FUNC_EPHEM 0x04 /* Ephermeral. Delete with VDBE */
60.599 +
60.600 +/*
60.601 +** information about each column of an SQL table is held in an instance
60.602 +** of this structure.
60.603 +*/
60.604 +struct Column {
60.605 + char *zName; /* Name of this column */
60.606 + Expr *pDflt; /* Default value of this column */
60.607 + char *zType; /* Data type for this column */
60.608 + char *zColl; /* Collating sequence. If NULL, use the default */
60.609 + u8 notNull; /* True if there is a NOT NULL constraint */
60.610 + u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */
60.611 + char affinity; /* One of the SQLITE_AFF_... values */
60.612 +#ifndef SQLITE_OMIT_VIRTUALTABLE
60.613 + u8 isHidden; /* True if this column is 'hidden' */
60.614 +#endif
60.615 +};
60.616 +
60.617 +/*
60.618 +** A "Collating Sequence" is defined by an instance of the following
60.619 +** structure. Conceptually, a collating sequence consists of a name and
60.620 +** a comparison routine that defines the order of that sequence.
60.621 +**
60.622 +** There may two seperate implementations of the collation function, one
60.623 +** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
60.624 +** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
60.625 +** native byte order. When a collation sequence is invoked, SQLite selects
60.626 +** the version that will require the least expensive encoding
60.627 +** translations, if any.
60.628 +**
60.629 +** The CollSeq.pUser member variable is an extra parameter that passed in
60.630 +** as the first argument to the UTF-8 comparison function, xCmp.
60.631 +** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
60.632 +** xCmp16.
60.633 +**
60.634 +** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
60.635 +** collating sequence is undefined. Indices built on an undefined
60.636 +** collating sequence may not be read or written.
60.637 +*/
60.638 +struct CollSeq {
60.639 + char *zName; /* Name of the collating sequence, UTF-8 encoded */
60.640 + u8 enc; /* Text encoding handled by xCmp() */
60.641 + u8 type; /* One of the SQLITE_COLL_... values below */
60.642 + void *pUser; /* First argument to xCmp() */
60.643 + int (*xCmp)(void*,int, const void*, int, const void*);
60.644 + void (*xDel)(void*); /* Destructor for pUser */
60.645 +};
60.646 +
60.647 +/*
60.648 +** Allowed values of CollSeq flags:
60.649 +*/
60.650 +#define SQLITE_COLL_BINARY 1 /* The default memcmp() collating sequence */
60.651 +#define SQLITE_COLL_NOCASE 2 /* The built-in NOCASE collating sequence */
60.652 +#define SQLITE_COLL_REVERSE 3 /* The built-in REVERSE collating sequence */
60.653 +#define SQLITE_COLL_USER 0 /* Any other user-defined collating sequence */
60.654 +
60.655 +/*
60.656 +** A sort order can be either ASC or DESC.
60.657 +*/
60.658 +#define SQLITE_SO_ASC 0 /* Sort in ascending order */
60.659 +#define SQLITE_SO_DESC 1 /* Sort in ascending order */
60.660 +
60.661 +/*
60.662 +** Column affinity types.
60.663 +**
60.664 +** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
60.665 +** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
60.666 +** the speed a little by number the values consecutively.
60.667 +**
60.668 +** But rather than start with 0 or 1, we begin with 'a'. That way,
60.669 +** when multiple affinity types are concatenated into a string and
60.670 +** used as the P3 operand, they will be more readable.
60.671 +**
60.672 +** Note also that the numeric types are grouped together so that testing
60.673 +** for a numeric type is a single comparison.
60.674 +*/
60.675 +#define SQLITE_AFF_TEXT 'a'
60.676 +#define SQLITE_AFF_NONE 'b'
60.677 +#define SQLITE_AFF_NUMERIC 'c'
60.678 +#define SQLITE_AFF_INTEGER 'd'
60.679 +#define SQLITE_AFF_REAL 'e'
60.680 +
60.681 +#define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
60.682 +
60.683 +/*
60.684 +** Each SQL table is represented in memory by an instance of the
60.685 +** following structure.
60.686 +**
60.687 +** Table.zName is the name of the table. The case of the original
60.688 +** CREATE TABLE statement is stored, but case is not significant for
60.689 +** comparisons.
60.690 +**
60.691 +** Table.nCol is the number of columns in this table. Table.aCol is a
60.692 +** pointer to an array of Column structures, one for each column.
60.693 +**
60.694 +** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
60.695 +** the column that is that key. Otherwise Table.iPKey is negative. Note
60.696 +** that the datatype of the PRIMARY KEY must be INTEGER for this field to
60.697 +** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
60.698 +** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
60.699 +** is generated for each row of the table. Table.hasPrimKey is true if
60.700 +** the table has any PRIMARY KEY, INTEGER or otherwise.
60.701 +**
60.702 +** Table.tnum is the page number for the root BTree page of the table in the
60.703 +** database file. If Table.iDb is the index of the database table backend
60.704 +** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
60.705 +** holds temporary tables and indices. If Table.isEphem
60.706 +** is true, then the table is stored in a file that is automatically deleted
60.707 +** when the VDBE cursor to the table is closed. In this case Table.tnum
60.708 +** refers VDBE cursor number that holds the table open, not to the root
60.709 +** page number. Transient tables are used to hold the results of a
60.710 +** sub-query that appears instead of a real table name in the FROM clause
60.711 +** of a SELECT statement.
60.712 +*/
60.713 +struct Table {
60.714 + char *zName; /* Name of the table */
60.715 + int nCol; /* Number of columns in this table */
60.716 + Column *aCol; /* Information about each column */
60.717 + int iPKey; /* If not less then 0, use aCol[iPKey] as the primary key */
60.718 + Index *pIndex; /* List of SQL indexes on this table. */
60.719 + int tnum; /* Root BTree node for this table (see note above) */
60.720 + Select *pSelect; /* NULL for tables. Points to definition if a view. */
60.721 + int nRef; /* Number of pointers to this Table */
60.722 + Trigger *pTrigger; /* List of SQL triggers on this table */
60.723 + FKey *pFKey; /* Linked list of all foreign keys in this table */
60.724 + char *zColAff; /* String defining the affinity of each column */
60.725 +#ifndef SQLITE_OMIT_CHECK
60.726 + Expr *pCheck; /* The AND of all CHECK constraints */
60.727 +#endif
60.728 +#ifndef SQLITE_OMIT_ALTERTABLE
60.729 + int addColOffset; /* Offset in CREATE TABLE statement to add a new column */
60.730 +#endif
60.731 + u8 readOnly; /* True if this table should not be written by the user */
60.732 + u8 isEphem; /* True if created using OP_OpenEphermeral */
60.733 + u8 hasPrimKey; /* True if there exists a primary key */
60.734 + u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
60.735 + u8 autoInc; /* True if the integer primary key is autoincrement */
60.736 +#ifndef SQLITE_OMIT_VIRTUALTABLE
60.737 + u8 isVirtual; /* True if this is a virtual table */
60.738 + u8 isCommit; /* True once the CREATE TABLE has been committed */
60.739 + Module *pMod; /* Pointer to the implementation of the module */
60.740 + sqlite3_vtab *pVtab; /* Pointer to the module instance */
60.741 + int nModuleArg; /* Number of arguments to the module */
60.742 + char **azModuleArg; /* Text of all module args. [0] is module name */
60.743 +#endif
60.744 + Schema *pSchema;
60.745 +};
60.746 +
60.747 +/*
60.748 +** Test to see whether or not a table is a virtual table. This is
60.749 +** done as a macro so that it will be optimized out when virtual
60.750 +** table support is omitted from the build.
60.751 +*/
60.752 +#ifndef SQLITE_OMIT_VIRTUALTABLE
60.753 +# define IsVirtual(X) ((X)->isVirtual)
60.754 +# define IsHiddenColumn(X) ((X)->isHidden)
60.755 +#else
60.756 +# define IsVirtual(X) 0
60.757 +# define IsHiddenColumn(X) 0
60.758 +#endif
60.759 +
60.760 +/*
60.761 +** Each foreign key constraint is an instance of the following structure.
60.762 +**
60.763 +** A foreign key is associated with two tables. The "from" table is
60.764 +** the table that contains the REFERENCES clause that creates the foreign
60.765 +** key. The "to" table is the table that is named in the REFERENCES clause.
60.766 +** Consider this example:
60.767 +**
60.768 +** CREATE TABLE ex1(
60.769 +** a INTEGER PRIMARY KEY,
60.770 +** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
60.771 +** );
60.772 +**
60.773 +** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
60.774 +**
60.775 +** Each REFERENCES clause generates an instance of the following structure
60.776 +** which is attached to the from-table. The to-table need not exist when
60.777 +** the from-table is created. The existance of the to-table is not checked
60.778 +** until an attempt is made to insert data into the from-table.
60.779 +**
60.780 +** The sqlite.aFKey hash table stores pointers to this structure
60.781 +** given the name of a to-table. For each to-table, all foreign keys
60.782 +** associated with that table are on a linked list using the FKey.pNextTo
60.783 +** field.
60.784 +*/
60.785 +struct FKey {
60.786 + Table *pFrom; /* The table that constains the REFERENCES clause */
60.787 + FKey *pNextFrom; /* Next foreign key in pFrom */
60.788 + char *zTo; /* Name of table that the key points to */
60.789 + FKey *pNextTo; /* Next foreign key that points to zTo */
60.790 + int nCol; /* Number of columns in this key */
60.791 + struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
60.792 + int iFrom; /* Index of column in pFrom */
60.793 + char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
60.794 + } *aCol; /* One entry for each of nCol column s */
60.795 + u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
60.796 + u8 updateConf; /* How to resolve conflicts that occur on UPDATE */
60.797 + u8 deleteConf; /* How to resolve conflicts that occur on DELETE */
60.798 + u8 insertConf; /* How to resolve conflicts that occur on INSERT */
60.799 +};
60.800 +
60.801 +/*
60.802 +** SQLite supports many different ways to resolve a contraint
60.803 +** error. ROLLBACK processing means that a constraint violation
60.804 +** causes the operation in process to fail and for the current transaction
60.805 +** to be rolled back. ABORT processing means the operation in process
60.806 +** fails and any prior changes from that one operation are backed out,
60.807 +** but the transaction is not rolled back. FAIL processing means that
60.808 +** the operation in progress stops and returns an error code. But prior
60.809 +** changes due to the same operation are not backed out and no rollback
60.810 +** occurs. IGNORE means that the particular row that caused the constraint
60.811 +** error is not inserted or updated. Processing continues and no error
60.812 +** is returned. REPLACE means that preexisting database rows that caused
60.813 +** a UNIQUE constraint violation are removed so that the new insert or
60.814 +** update can proceed. Processing continues and no error is reported.
60.815 +**
60.816 +** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
60.817 +** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
60.818 +** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
60.819 +** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
60.820 +** referenced table row is propagated into the row that holds the
60.821 +** foreign key.
60.822 +**
60.823 +** The following symbolic values are used to record which type
60.824 +** of action to take.
60.825 +*/
60.826 +#define OE_None 0 /* There is no constraint to check */
60.827 +#define OE_Rollback 1 /* Fail the operation and rollback the transaction */
60.828 +#define OE_Abort 2 /* Back out changes but do no rollback transaction */
60.829 +#define OE_Fail 3 /* Stop the operation but leave all prior changes */
60.830 +#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
60.831 +#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
60.832 +
60.833 +#define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
60.834 +#define OE_SetNull 7 /* Set the foreign key value to NULL */
60.835 +#define OE_SetDflt 8 /* Set the foreign key value to its default */
60.836 +#define OE_Cascade 9 /* Cascade the changes */
60.837 +
60.838 +#define OE_Default 99 /* Do whatever the default action is */
60.839 +
60.840 +
60.841 +/*
60.842 +** An instance of the following structure is passed as the first
60.843 +** argument to sqlite3VdbeKeyCompare and is used to control the
60.844 +** comparison of the two index keys.
60.845 +**
60.846 +** If the KeyInfo.incrKey value is true and the comparison would
60.847 +** otherwise be equal, then return a result as if the second key
60.848 +** were larger.
60.849 +*/
60.850 +struct KeyInfo {
60.851 + u8 enc; /* Text encoding - one of the TEXT_Utf* values */
60.852 + u8 incrKey; /* Increase 2nd key by epsilon before comparison */
60.853 + int nField; /* Number of entries in aColl[] */
60.854 + u8 *aSortOrder; /* If defined an aSortOrder[i] is true, sort DESC */
60.855 + CollSeq *aColl[1]; /* Collating sequence for each term of the key */
60.856 +};
60.857 +
60.858 +/*
60.859 +** Each SQL index is represented in memory by an
60.860 +** instance of the following structure.
60.861 +**
60.862 +** The columns of the table that are to be indexed are described
60.863 +** by the aiColumn[] field of this structure. For example, suppose
60.864 +** we have the following table and index:
60.865 +**
60.866 +** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
60.867 +** CREATE INDEX Ex2 ON Ex1(c3,c1);
60.868 +**
60.869 +** In the Table structure describing Ex1, nCol==3 because there are
60.870 +** three columns in the table. In the Index structure describing
60.871 +** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
60.872 +** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
60.873 +** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
60.874 +** The second column to be indexed (c1) has an index of 0 in
60.875 +** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
60.876 +**
60.877 +** The Index.onError field determines whether or not the indexed columns
60.878 +** must be unique and what to do if they are not. When Index.onError=OE_None,
60.879 +** it means this is not a unique index. Otherwise it is a unique index
60.880 +** and the value of Index.onError indicate the which conflict resolution
60.881 +** algorithm to employ whenever an attempt is made to insert a non-unique
60.882 +** element.
60.883 +*/
60.884 +struct Index {
60.885 + char *zName; /* Name of this index */
60.886 + int nColumn; /* Number of columns in the table used by this index */
60.887 + int *aiColumn; /* Which columns are used by this index. 1st is 0 */
60.888 + unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
60.889 + Table *pTable; /* The SQL table being indexed */
60.890 + int tnum; /* Page containing root of this index in database file */
60.891 + u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
60.892 + u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */
60.893 + char *zColAff; /* String defining the affinity of each column */
60.894 + Index *pNext; /* The next index associated with the same table */
60.895 + Schema *pSchema; /* Schema containing this index */
60.896 + u8 *aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */
60.897 + char **azColl; /* Array of collation sequence names for index */
60.898 +};
60.899 +
60.900 +/*
60.901 +** Each token coming out of the lexer is an instance of
60.902 +** this structure. Tokens are also used as part of an expression.
60.903 +**
60.904 +** Note if Token.z==0 then Token.dyn and Token.n are undefined and
60.905 +** may contain random values. Do not make any assuptions about Token.dyn
60.906 +** and Token.n when Token.z==0.
60.907 +*/
60.908 +struct Token {
60.909 + const unsigned char *z; /* Text of the token. Not NULL-terminated! */
60.910 + unsigned dyn : 1; /* True for malloced memory, false for static */
60.911 + unsigned n : 31; /* Number of characters in this token */
60.912 +};
60.913 +
60.914 +/*
60.915 +** An instance of this structure contains information needed to generate
60.916 +** code for a SELECT that contains aggregate functions.
60.917 +**
60.918 +** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
60.919 +** pointer to this structure. The Expr.iColumn field is the index in
60.920 +** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
60.921 +** code for that node.
60.922 +**
60.923 +** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
60.924 +** original Select structure that describes the SELECT statement. These
60.925 +** fields do not need to be freed when deallocating the AggInfo structure.
60.926 +*/
60.927 +struct AggInfo {
60.928 + u8 directMode; /* Direct rendering mode means take data directly
60.929 + ** from source tables rather than from accumulators */
60.930 + u8 useSortingIdx; /* In direct mode, reference the sorting index rather
60.931 + ** than the source table */
60.932 + int sortingIdx; /* Cursor number of the sorting index */
60.933 + ExprList *pGroupBy; /* The group by clause */
60.934 + int nSortingColumn; /* Number of columns in the sorting index */
60.935 + struct AggInfo_col { /* For each column used in source tables */
60.936 + Table *pTab; /* Source table */
60.937 + int iTable; /* Cursor number of the source table */
60.938 + int iColumn; /* Column number within the source table */
60.939 + int iSorterColumn; /* Column number in the sorting index */
60.940 + int iMem; /* Memory location that acts as accumulator */
60.941 + Expr *pExpr; /* The original expression */
60.942 + } *aCol;
60.943 + int nColumn; /* Number of used entries in aCol[] */
60.944 + int nColumnAlloc; /* Number of slots allocated for aCol[] */
60.945 + int nAccumulator; /* Number of columns that show through to the output.
60.946 + ** Additional columns are used only as parameters to
60.947 + ** aggregate functions */
60.948 + struct AggInfo_func { /* For each aggregate function */
60.949 + Expr *pExpr; /* Expression encoding the function */
60.950 + FuncDef *pFunc; /* The aggregate function implementation */
60.951 + int iMem; /* Memory location that acts as accumulator */
60.952 + int iDistinct; /* Ephermeral table used to enforce DISTINCT */
60.953 + } *aFunc;
60.954 + int nFunc; /* Number of entries in aFunc[] */
60.955 + int nFuncAlloc; /* Number of slots allocated for aFunc[] */
60.956 +};
60.957 +
60.958 +/*
60.959 +** Each node of an expression in the parse tree is an instance
60.960 +** of this structure.
60.961 +**
60.962 +** Expr.op is the opcode. The integer parser token codes are reused
60.963 +** as opcodes here. For example, the parser defines TK_GE to be an integer
60.964 +** code representing the ">=" operator. This same integer code is reused
60.965 +** to represent the greater-than-or-equal-to operator in the expression
60.966 +** tree.
60.967 +**
60.968 +** Expr.pRight and Expr.pLeft are subexpressions. Expr.pList is a list
60.969 +** of argument if the expression is a function.
60.970 +**
60.971 +** Expr.token is the operator token for this node. For some expressions
60.972 +** that have subexpressions, Expr.token can be the complete text that gave
60.973 +** rise to the Expr. In the latter case, the token is marked as being
60.974 +** a compound token.
60.975 +**
60.976 +** An expression of the form ID or ID.ID refers to a column in a table.
60.977 +** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
60.978 +** the integer cursor number of a VDBE cursor pointing to that table and
60.979 +** Expr.iColumn is the column number for the specific column. If the
60.980 +** expression is used as a result in an aggregate SELECT, then the
60.981 +** value is also stored in the Expr.iAgg column in the aggregate so that
60.982 +** it can be accessed after all aggregates are computed.
60.983 +**
60.984 +** If the expression is a function, the Expr.iTable is an integer code
60.985 +** representing which function. If the expression is an unbound variable
60.986 +** marker (a question mark character '?' in the original SQL) then the
60.987 +** Expr.iTable holds the index number for that variable.
60.988 +**
60.989 +** If the expression is a subquery then Expr.iColumn holds an integer
60.990 +** register number containing the result of the subquery. If the
60.991 +** subquery gives a constant result, then iTable is -1. If the subquery
60.992 +** gives a different answer at different times during statement processing
60.993 +** then iTable is the address of a subroutine that computes the subquery.
60.994 +**
60.995 +** The Expr.pSelect field points to a SELECT statement. The SELECT might
60.996 +** be the right operand of an IN operator. Or, if a scalar SELECT appears
60.997 +** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
60.998 +** operand.
60.999 +**
60.1000 +** If the Expr is of type OP_Column, and the table it is selecting from
60.1001 +** is a disk table or the "old.*" pseudo-table, then pTab points to the
60.1002 +** corresponding table definition.
60.1003 +*/
60.1004 +struct Expr {
60.1005 + u8 op; /* Operation performed by this node */
60.1006 + char affinity; /* The affinity of the column or 0 if not a column */
60.1007 + u16 flags; /* Various flags. See below */
60.1008 + CollSeq *pColl; /* The collation type of the column or 0 */
60.1009 + Expr *pLeft, *pRight; /* Left and right subnodes */
60.1010 + ExprList *pList; /* A list of expressions used as function arguments
60.1011 + ** or in "<expr> IN (<expr-list)" */
60.1012 + Token token; /* An operand token */
60.1013 + Token span; /* Complete text of the expression */
60.1014 + int iTable, iColumn; /* When op==TK_COLUMN, then this expr node means the
60.1015 + ** iColumn-th field of the iTable-th table. */
60.1016 + AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
60.1017 + int iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
60.1018 + int iRightJoinTable; /* If EP_FromJoin, the right table of the join */
60.1019 + Select *pSelect; /* When the expression is a sub-select. Also the
60.1020 + ** right side of "<expr> IN (<select>)" */
60.1021 + Table *pTab; /* Table for OP_Column expressions. */
60.1022 + Schema *pSchema;
60.1023 +#if SQLITE_MAX_EXPR_DEPTH>0
60.1024 + int nHeight; /* Height of the tree headed by this node */
60.1025 +#endif
60.1026 +};
60.1027 +
60.1028 +/*
60.1029 +** The following are the meanings of bits in the Expr.flags field.
60.1030 +*/
60.1031 +#define EP_FromJoin 0x01 /* Originated in ON or USING clause of a join */
60.1032 +#define EP_Agg 0x02 /* Contains one or more aggregate functions */
60.1033 +#define EP_Resolved 0x04 /* IDs have been resolved to COLUMNs */
60.1034 +#define EP_Error 0x08 /* Expression contains one or more errors */
60.1035 +#define EP_Distinct 0x10 /* Aggregate function with DISTINCT keyword */
60.1036 +#define EP_VarSelect 0x20 /* pSelect is correlated, not constant */
60.1037 +#define EP_Dequoted 0x40 /* True if the string has been dequoted */
60.1038 +#define EP_InfixFunc 0x80 /* True for an infix function: LIKE, GLOB, etc */
60.1039 +#define EP_ExpCollate 0x100 /* Collating sequence specified explicitly */
60.1040 +
60.1041 +/*
60.1042 +** These macros can be used to test, set, or clear bits in the
60.1043 +** Expr.flags field.
60.1044 +*/
60.1045 +#define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
60.1046 +#define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
60.1047 +#define ExprSetProperty(E,P) (E)->flags|=(P)
60.1048 +#define ExprClearProperty(E,P) (E)->flags&=~(P)
60.1049 +
60.1050 +/*
60.1051 +** A list of expressions. Each expression may optionally have a
60.1052 +** name. An expr/name combination can be used in several ways, such
60.1053 +** as the list of "expr AS ID" fields following a "SELECT" or in the
60.1054 +** list of "ID = expr" items in an UPDATE. A list of expressions can
60.1055 +** also be used as the argument to a function, in which case the a.zName
60.1056 +** field is not used.
60.1057 +*/
60.1058 +struct ExprList {
60.1059 + int nExpr; /* Number of expressions on the list */
60.1060 + int nAlloc; /* Number of entries allocated below */
60.1061 + int iECursor; /* VDBE Cursor associated with this ExprList */
60.1062 + struct ExprList_item {
60.1063 + Expr *pExpr; /* The list of expressions */
60.1064 + char *zName; /* Token associated with this expression */
60.1065 + u8 sortOrder; /* 1 for DESC or 0 for ASC */
60.1066 + u8 isAgg; /* True if this is an aggregate like count(*) */
60.1067 + u8 done; /* A flag to indicate when processing is finished */
60.1068 + } *a; /* One entry for each expression */
60.1069 +};
60.1070 +
60.1071 +/*
60.1072 +** An instance of this structure can hold a simple list of identifiers,
60.1073 +** such as the list "a,b,c" in the following statements:
60.1074 +**
60.1075 +** INSERT INTO t(a,b,c) VALUES ...;
60.1076 +** CREATE INDEX idx ON t(a,b,c);
60.1077 +** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
60.1078 +**
60.1079 +** The IdList.a.idx field is used when the IdList represents the list of
60.1080 +** column names after a table name in an INSERT statement. In the statement
60.1081 +**
60.1082 +** INSERT INTO t(a,b,c) ...
60.1083 +**
60.1084 +** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
60.1085 +*/
60.1086 +struct IdList {
60.1087 + struct IdList_item {
60.1088 + char *zName; /* Name of the identifier */
60.1089 + int idx; /* Index in some Table.aCol[] of a column named zName */
60.1090 + } *a;
60.1091 + int nId; /* Number of identifiers on the list */
60.1092 + int nAlloc; /* Number of entries allocated for a[] below */
60.1093 +};
60.1094 +
60.1095 +/*
60.1096 +** The bitmask datatype defined below is used for various optimizations.
60.1097 +**
60.1098 +** Changing this from a 64-bit to a 32-bit type limits the number of
60.1099 +** tables in a join to 32 instead of 64. But it also reduces the size
60.1100 +** of the library by 738 bytes on ix86.
60.1101 +*/
60.1102 +typedef u64 Bitmask;
60.1103 +
60.1104 +/*
60.1105 +** The following structure describes the FROM clause of a SELECT statement.
60.1106 +** Each table or subquery in the FROM clause is a separate element of
60.1107 +** the SrcList.a[] array.
60.1108 +**
60.1109 +** With the addition of multiple database support, the following structure
60.1110 +** can also be used to describe a particular table such as the table that
60.1111 +** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
60.1112 +** such a table must be a simple name: ID. But in SQLite, the table can
60.1113 +** now be identified by a database name, a dot, then the table name: ID.ID.
60.1114 +**
60.1115 +** The jointype starts out showing the join type between the current table
60.1116 +** and the next table on the list. The parser builds the list this way.
60.1117 +** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
60.1118 +** jointype expresses the join between the table and the previous table.
60.1119 +*/
60.1120 +struct SrcList {
60.1121 + i16 nSrc; /* Number of tables or subqueries in the FROM clause */
60.1122 + i16 nAlloc; /* Number of entries allocated in a[] below */
60.1123 + struct SrcList_item {
60.1124 + char *zDatabase; /* Name of database holding this table */
60.1125 + char *zName; /* Name of the table */
60.1126 + char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
60.1127 + Table *pTab; /* An SQL table corresponding to zName */
60.1128 + Select *pSelect; /* A SELECT statement used in place of a table name */
60.1129 + u8 isPopulated; /* Temporary table associated with SELECT is populated */
60.1130 + u8 jointype; /* Type of join between this able and the previous */
60.1131 + int iCursor; /* The VDBE cursor number used to access this table */
60.1132 + Expr *pOn; /* The ON clause of a join */
60.1133 + IdList *pUsing; /* The USING clause of a join */
60.1134 + Bitmask colUsed; /* Bit N (1<<N) set if column N or pTab is used */
60.1135 + } a[1]; /* One entry for each identifier on the list */
60.1136 +};
60.1137 +
60.1138 +/*
60.1139 +** Permitted values of the SrcList.a.jointype field
60.1140 +*/
60.1141 +#define JT_INNER 0x0001 /* Any kind of inner or cross join */
60.1142 +#define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
60.1143 +#define JT_NATURAL 0x0004 /* True for a "natural" join */
60.1144 +#define JT_LEFT 0x0008 /* Left outer join */
60.1145 +#define JT_RIGHT 0x0010 /* Right outer join */
60.1146 +#define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
60.1147 +#define JT_ERROR 0x0040 /* unknown or unsupported join type */
60.1148 +
60.1149 +/*
60.1150 +** For each nested loop in a WHERE clause implementation, the WhereInfo
60.1151 +** structure contains a single instance of this structure. This structure
60.1152 +** is intended to be private the the where.c module and should not be
60.1153 +** access or modified by other modules.
60.1154 +**
60.1155 +** The pIdxInfo and pBestIdx fields are used to help pick the best
60.1156 +** index on a virtual table. The pIdxInfo pointer contains indexing
60.1157 +** information for the i-th table in the FROM clause before reordering.
60.1158 +** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
60.1159 +** The pBestIdx pointer is a copy of pIdxInfo for the i-th table after
60.1160 +** FROM clause ordering. This is a little confusing so I will repeat
60.1161 +** it in different words. WhereInfo.a[i].pIdxInfo is index information
60.1162 +** for WhereInfo.pTabList.a[i]. WhereInfo.a[i].pBestInfo is the
60.1163 +** index information for the i-th loop of the join. pBestInfo is always
60.1164 +** either NULL or a copy of some pIdxInfo. So for cleanup it is
60.1165 +** sufficient to free all of the pIdxInfo pointers.
60.1166 +**
60.1167 +*/
60.1168 +struct WhereLevel {
60.1169 + int iFrom; /* Which entry in the FROM clause */
60.1170 + int flags; /* Flags associated with this level */
60.1171 + int iMem; /* First memory cell used by this level */
60.1172 + int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
60.1173 + Index *pIdx; /* Index used. NULL if no index */
60.1174 + int iTabCur; /* The VDBE cursor used to access the table */
60.1175 + int iIdxCur; /* The VDBE cursor used to acesss pIdx */
60.1176 + int brk; /* Jump here to break out of the loop */
60.1177 + int nxt; /* Jump here to start the next IN combination */
60.1178 + int cont; /* Jump here to continue with the next loop cycle */
60.1179 + int top; /* First instruction of interior of the loop */
60.1180 + int op, p1, p2; /* Opcode used to terminate the loop */
60.1181 + int nEq; /* Number of == or IN constraints on this loop */
60.1182 + int nIn; /* Number of IN operators constraining this loop */
60.1183 + struct InLoop {
60.1184 + int iCur; /* The VDBE cursor used by this IN operator */
60.1185 + int topAddr; /* Top of the IN loop */
60.1186 + } *aInLoop; /* Information about each nested IN operator */
60.1187 + sqlite3_index_info *pBestIdx; /* Index information for this level */
60.1188 +
60.1189 + /* The following field is really not part of the current level. But
60.1190 + ** we need a place to cache index information for each table in the
60.1191 + ** FROM clause and the WhereLevel structure is a convenient place.
60.1192 + */
60.1193 + sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
60.1194 +};
60.1195 +
60.1196 +/*
60.1197 +** The WHERE clause processing routine has two halves. The
60.1198 +** first part does the start of the WHERE loop and the second
60.1199 +** half does the tail of the WHERE loop. An instance of
60.1200 +** this structure is returned by the first half and passed
60.1201 +** into the second half to give some continuity.
60.1202 +*/
60.1203 +struct WhereInfo {
60.1204 + Parse *pParse;
60.1205 + SrcList *pTabList; /* List of tables in the join */
60.1206 + int iTop; /* The very beginning of the WHERE loop */
60.1207 + int iContinue; /* Jump here to continue with next record */
60.1208 + int iBreak; /* Jump here to break out of the loop */
60.1209 + int nLevel; /* Number of nested loop */
60.1210 + sqlite3_index_info **apInfo; /* Array of pointers to index info structures */
60.1211 + WhereLevel a[1]; /* Information about each nest loop in the WHERE */
60.1212 +};
60.1213 +
60.1214 +/*
60.1215 +** A NameContext defines a context in which to resolve table and column
60.1216 +** names. The context consists of a list of tables (the pSrcList) field and
60.1217 +** a list of named expression (pEList). The named expression list may
60.1218 +** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
60.1219 +** to the table being operated on by INSERT, UPDATE, or DELETE. The
60.1220 +** pEList corresponds to the result set of a SELECT and is NULL for
60.1221 +** other statements.
60.1222 +**
60.1223 +** NameContexts can be nested. When resolving names, the inner-most
60.1224 +** context is searched first. If no match is found, the next outer
60.1225 +** context is checked. If there is still no match, the next context
60.1226 +** is checked. This process continues until either a match is found
60.1227 +** or all contexts are check. When a match is found, the nRef member of
60.1228 +** the context containing the match is incremented.
60.1229 +**
60.1230 +** Each subquery gets a new NameContext. The pNext field points to the
60.1231 +** NameContext in the parent query. Thus the process of scanning the
60.1232 +** NameContext list corresponds to searching through successively outer
60.1233 +** subqueries looking for a match.
60.1234 +*/
60.1235 +struct NameContext {
60.1236 + Parse *pParse; /* The parser */
60.1237 + SrcList *pSrcList; /* One or more tables used to resolve names */
60.1238 + ExprList *pEList; /* Optional list of named expressions */
60.1239 + int nRef; /* Number of names resolved by this context */
60.1240 + int nErr; /* Number of errors encountered while resolving names */
60.1241 + u8 allowAgg; /* Aggregate functions allowed here */
60.1242 + u8 hasAgg; /* True if aggregates are seen */
60.1243 + u8 isCheck; /* True if resolving names in a CHECK constraint */
60.1244 + int nDepth; /* Depth of subquery recursion. 1 for no recursion */
60.1245 + AggInfo *pAggInfo; /* Information about aggregates at this level */
60.1246 + NameContext *pNext; /* Next outer name context. NULL for outermost */
60.1247 +};
60.1248 +
60.1249 +/*
60.1250 +** An instance of the following structure contains all information
60.1251 +** needed to generate code for a single SELECT statement.
60.1252 +**
60.1253 +** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
60.1254 +** If there is a LIMIT clause, the parser sets nLimit to the value of the
60.1255 +** limit and nOffset to the value of the offset (or 0 if there is not
60.1256 +** offset). But later on, nLimit and nOffset become the memory locations
60.1257 +** in the VDBE that record the limit and offset counters.
60.1258 +**
60.1259 +** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
60.1260 +** These addresses must be stored so that we can go back and fill in
60.1261 +** the P3_KEYINFO and P2 parameters later. Neither the KeyInfo nor
60.1262 +** the number of columns in P2 can be computed at the same time
60.1263 +** as the OP_OpenEphm instruction is coded because not
60.1264 +** enough information about the compound query is known at that point.
60.1265 +** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
60.1266 +** for the result set. The KeyInfo for addrOpenTran[2] contains collating
60.1267 +** sequences for the ORDER BY clause.
60.1268 +*/
60.1269 +struct Select {
60.1270 + ExprList *pEList; /* The fields of the result */
60.1271 + u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
60.1272 + u8 isDistinct; /* True if the DISTINCT keyword is present */
60.1273 + u8 isResolved; /* True once sqlite3SelectResolve() has run. */
60.1274 + u8 isAgg; /* True if this is an aggregate query */
60.1275 + u8 usesEphm; /* True if uses an OpenEphemeral opcode */
60.1276 + u8 disallowOrderBy; /* Do not allow an ORDER BY to be attached if TRUE */
60.1277 + char affinity; /* MakeRecord with this affinity for SRT_Set */
60.1278 + SrcList *pSrc; /* The FROM clause */
60.1279 + Expr *pWhere; /* The WHERE clause */
60.1280 + ExprList *pGroupBy; /* The GROUP BY clause */
60.1281 + Expr *pHaving; /* The HAVING clause */
60.1282 + ExprList *pOrderBy; /* The ORDER BY clause */
60.1283 + Select *pPrior; /* Prior select in a compound select statement */
60.1284 + Select *pRightmost; /* Right-most select in a compound select statement */
60.1285 + Expr *pLimit; /* LIMIT expression. NULL means not used. */
60.1286 + Expr *pOffset; /* OFFSET expression. NULL means not used. */
60.1287 + int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
60.1288 + int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
60.1289 +};
60.1290 +
60.1291 +/*
60.1292 +** The results of a select can be distributed in several ways.
60.1293 +*/
60.1294 +#define SRT_Union 1 /* Store result as keys in an index */
60.1295 +#define SRT_Except 2 /* Remove result from a UNION index */
60.1296 +#define SRT_Discard 3 /* Do not save the results anywhere */
60.1297 +
60.1298 +/* The ORDER BY clause is ignored for all of the above */
60.1299 +#define IgnorableOrderby(X) (X<=SRT_Discard)
60.1300 +
60.1301 +#define SRT_Callback 4 /* Invoke a callback with each row of result */
60.1302 +#define SRT_Mem 5 /* Store result in a memory cell */
60.1303 +#define SRT_Set 6 /* Store non-null results as keys in an index */
60.1304 +#define SRT_Table 7 /* Store result as data with an automatic rowid */
60.1305 +#define SRT_EphemTab 8 /* Create transient tab and store like SRT_Table */
60.1306 +#define SRT_Subroutine 9 /* Call a subroutine to handle results */
60.1307 +#define SRT_Exists 10 /* Store 1 if the result is not empty */
60.1308 +
60.1309 +/*
60.1310 +** An SQL parser context. A copy of this structure is passed through
60.1311 +** the parser and down into all the parser action routine in order to
60.1312 +** carry around information that is global to the entire parse.
60.1313 +**
60.1314 +** The structure is divided into two parts. When the parser and code
60.1315 +** generate call themselves recursively, the first part of the structure
60.1316 +** is constant but the second part is reset at the beginning and end of
60.1317 +** each recursion.
60.1318 +**
60.1319 +** The nTableLock and aTableLock variables are only used if the shared-cache
60.1320 +** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
60.1321 +** used to store the set of table-locks required by the statement being
60.1322 +** compiled. Function sqlite3TableLock() is used to add entries to the
60.1323 +** list.
60.1324 +*/
60.1325 +struct Parse {
60.1326 + sqlite3 *db; /* The main database structure */
60.1327 + int rc; /* Return code from execution */
60.1328 + char *zErrMsg; /* An error message */
60.1329 + Vdbe *pVdbe; /* An engine for executing database bytecode */
60.1330 + u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
60.1331 + u8 nameClash; /* A permanent table name clashes with temp table name */
60.1332 + u8 checkSchema; /* Causes schema cookie check after an error */
60.1333 + u8 nested; /* Number of nested calls to the parser/code generator */
60.1334 + u8 parseError; /* True after a parsing error. Ticket #1794 */
60.1335 + int nErr; /* Number of errors seen */
60.1336 + int nTab; /* Number of previously allocated VDBE cursors */
60.1337 + int nMem; /* Number of memory cells used so far */
60.1338 + int nSet; /* Number of sets used so far */
60.1339 + int ckOffset; /* Stack offset to data used by CHECK constraints */
60.1340 + u32 writeMask; /* Start a write transaction on these databases */
60.1341 + u32 cookieMask; /* Bitmask of schema verified databases */
60.1342 + int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
60.1343 + int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
60.1344 +#ifndef SQLITE_OMIT_SHARED_CACHE
60.1345 + int nTableLock; /* Number of locks in aTableLock */
60.1346 + TableLock *aTableLock; /* Required table locks for shared-cache mode */
60.1347 +#endif
60.1348 +
60.1349 + /* Above is constant between recursions. Below is reset before and after
60.1350 + ** each recursion */
60.1351 +
60.1352 + int nVar; /* Number of '?' variables seen in the SQL so far */
60.1353 + int nVarExpr; /* Number of used slots in apVarExpr[] */
60.1354 + int nVarExprAlloc; /* Number of allocated slots in apVarExpr[] */
60.1355 + Expr **apVarExpr; /* Pointers to :aaa and $aaaa wildcard expressions */
60.1356 + u8 explain; /* True if the EXPLAIN flag is found on the query */
60.1357 + Token sErrToken; /* The token at which the error occurred */
60.1358 + Token sNameToken; /* Token with unqualified schema object name */
60.1359 + Token sLastToken; /* The last token parsed */
60.1360 + const char *zSql; /* All SQL text */
60.1361 + const char *zTail; /* All SQL text past the last semicolon parsed */
60.1362 + Table *pNewTable; /* A table being constructed by CREATE TABLE */
60.1363 + Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
60.1364 + TriggerStack *trigStack; /* Trigger actions being coded */
60.1365 + const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
60.1366 +#ifndef SQLITE_OMIT_VIRTUALTABLE
60.1367 + Token sArg; /* Complete text of a module argument */
60.1368 + u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
60.1369 + Table *pVirtualLock; /* Require virtual table lock on this table */
60.1370 +#endif
60.1371 +#if SQLITE_MAX_EXPR_DEPTH>0
60.1372 + int nHeight; /* Expression tree height of current sub-select */
60.1373 +#endif
60.1374 +};
60.1375 +
60.1376 +#ifdef SQLITE_OMIT_VIRTUALTABLE
60.1377 + #define IN_DECLARE_VTAB 0
60.1378 +#else
60.1379 + #define IN_DECLARE_VTAB (pParse->declareVtab)
60.1380 +#endif
60.1381 +
60.1382 +/*
60.1383 +** An instance of the following structure can be declared on a stack and used
60.1384 +** to save the Parse.zAuthContext value so that it can be restored later.
60.1385 +*/
60.1386 +struct AuthContext {
60.1387 + const char *zAuthContext; /* Put saved Parse.zAuthContext here */
60.1388 + Parse *pParse; /* The Parse structure */
60.1389 +};
60.1390 +
60.1391 +/*
60.1392 +** Bitfield flags for P2 value in OP_Insert and OP_Delete
60.1393 +*/
60.1394 +#define OPFLAG_NCHANGE 1 /* Set to update db->nChange */
60.1395 +#define OPFLAG_LASTROWID 2 /* Set to update db->lastRowid */
60.1396 +#define OPFLAG_ISUPDATE 4 /* This OP_Insert is an sql UPDATE */
60.1397 +#define OPFLAG_APPEND 8 /* This is likely to be an append */
60.1398 +
60.1399 +/*
60.1400 + * Each trigger present in the database schema is stored as an instance of
60.1401 + * struct Trigger.
60.1402 + *
60.1403 + * Pointers to instances of struct Trigger are stored in two ways.
60.1404 + * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
60.1405 + * database). This allows Trigger structures to be retrieved by name.
60.1406 + * 2. All triggers associated with a single table form a linked list, using the
60.1407 + * pNext member of struct Trigger. A pointer to the first element of the
60.1408 + * linked list is stored as the "pTrigger" member of the associated
60.1409 + * struct Table.
60.1410 + *
60.1411 + * The "step_list" member points to the first element of a linked list
60.1412 + * containing the SQL statements specified as the trigger program.
60.1413 + */
60.1414 +struct Trigger {
60.1415 + char *name; /* The name of the trigger */
60.1416 + char *table; /* The table or view to which the trigger applies */
60.1417 + u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
60.1418 + u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
60.1419 + Expr *pWhen; /* The WHEN clause of the expresion (may be NULL) */
60.1420 + IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
60.1421 + the <column-list> is stored here */
60.1422 + Token nameToken; /* Token containing zName. Use during parsing only */
60.1423 + Schema *pSchema; /* Schema containing the trigger */
60.1424 + Schema *pTabSchema; /* Schema containing the table */
60.1425 + TriggerStep *step_list; /* Link list of trigger program steps */
60.1426 + Trigger *pNext; /* Next trigger associated with the table */
60.1427 +};
60.1428 +
60.1429 +/*
60.1430 +** A trigger is either a BEFORE or an AFTER trigger. The following constants
60.1431 +** determine which.
60.1432 +**
60.1433 +** If there are multiple triggers, you might of some BEFORE and some AFTER.
60.1434 +** In that cases, the constants below can be ORed together.
60.1435 +*/
60.1436 +#define TRIGGER_BEFORE 1
60.1437 +#define TRIGGER_AFTER 2
60.1438 +
60.1439 +/*
60.1440 + * An instance of struct TriggerStep is used to store a single SQL statement
60.1441 + * that is a part of a trigger-program.
60.1442 + *
60.1443 + * Instances of struct TriggerStep are stored in a singly linked list (linked
60.1444 + * using the "pNext" member) referenced by the "step_list" member of the
60.1445 + * associated struct Trigger instance. The first element of the linked list is
60.1446 + * the first step of the trigger-program.
60.1447 + *
60.1448 + * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
60.1449 + * "SELECT" statement. The meanings of the other members is determined by the
60.1450 + * value of "op" as follows:
60.1451 + *
60.1452 + * (op == TK_INSERT)
60.1453 + * orconf -> stores the ON CONFLICT algorithm
60.1454 + * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
60.1455 + * this stores a pointer to the SELECT statement. Otherwise NULL.
60.1456 + * target -> A token holding the name of the table to insert into.
60.1457 + * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
60.1458 + * this stores values to be inserted. Otherwise NULL.
60.1459 + * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
60.1460 + * statement, then this stores the column-names to be
60.1461 + * inserted into.
60.1462 + *
60.1463 + * (op == TK_DELETE)
60.1464 + * target -> A token holding the name of the table to delete from.
60.1465 + * pWhere -> The WHERE clause of the DELETE statement if one is specified.
60.1466 + * Otherwise NULL.
60.1467 + *
60.1468 + * (op == TK_UPDATE)
60.1469 + * target -> A token holding the name of the table to update rows of.
60.1470 + * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
60.1471 + * Otherwise NULL.
60.1472 + * pExprList -> A list of the columns to update and the expressions to update
60.1473 + * them to. See sqlite3Update() documentation of "pChanges"
60.1474 + * argument.
60.1475 + *
60.1476 + */
60.1477 +struct TriggerStep {
60.1478 + int op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
60.1479 + int orconf; /* OE_Rollback etc. */
60.1480 + Trigger *pTrig; /* The trigger that this step is a part of */
60.1481 +
60.1482 + Select *pSelect; /* Valid for SELECT and sometimes
60.1483 + INSERT steps (when pExprList == 0) */
60.1484 + Token target; /* Valid for DELETE, UPDATE, INSERT steps */
60.1485 + Expr *pWhere; /* Valid for DELETE, UPDATE steps */
60.1486 + ExprList *pExprList; /* Valid for UPDATE statements and sometimes
60.1487 + INSERT steps (when pSelect == 0) */
60.1488 + IdList *pIdList; /* Valid for INSERT statements only */
60.1489 + TriggerStep *pNext; /* Next in the link-list */
60.1490 + TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
60.1491 +};
60.1492 +
60.1493 +/*
60.1494 + * An instance of struct TriggerStack stores information required during code
60.1495 + * generation of a single trigger program. While the trigger program is being
60.1496 + * coded, its associated TriggerStack instance is pointed to by the
60.1497 + * "pTriggerStack" member of the Parse structure.
60.1498 + *
60.1499 + * The pTab member points to the table that triggers are being coded on. The
60.1500 + * newIdx member contains the index of the vdbe cursor that points at the temp
60.1501 + * table that stores the new.* references. If new.* references are not valid
60.1502 + * for the trigger being coded (for example an ON DELETE trigger), then newIdx
60.1503 + * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
60.1504 + *
60.1505 + * The ON CONFLICT policy to be used for the trigger program steps is stored
60.1506 + * as the orconf member. If this is OE_Default, then the ON CONFLICT clause
60.1507 + * specified for individual triggers steps is used.
60.1508 + *
60.1509 + * struct TriggerStack has a "pNext" member, to allow linked lists to be
60.1510 + * constructed. When coding nested triggers (triggers fired by other triggers)
60.1511 + * each nested trigger stores its parent trigger's TriggerStack as the "pNext"
60.1512 + * pointer. Once the nested trigger has been coded, the pNext value is restored
60.1513 + * to the pTriggerStack member of the Parse stucture and coding of the parent
60.1514 + * trigger continues.
60.1515 + *
60.1516 + * Before a nested trigger is coded, the linked list pointed to by the
60.1517 + * pTriggerStack is scanned to ensure that the trigger is not about to be coded
60.1518 + * recursively. If this condition is detected, the nested trigger is not coded.
60.1519 + */
60.1520 +struct TriggerStack {
60.1521 + Table *pTab; /* Table that triggers are currently being coded on */
60.1522 + int newIdx; /* Index of vdbe cursor to "new" temp table */
60.1523 + int oldIdx; /* Index of vdbe cursor to "old" temp table */
60.1524 + int orconf; /* Current orconf policy */
60.1525 + int ignoreJump; /* where to jump to for a RAISE(IGNORE) */
60.1526 + Trigger *pTrigger; /* The trigger currently being coded */
60.1527 + TriggerStack *pNext; /* Next trigger down on the trigger stack */
60.1528 +};
60.1529 +
60.1530 +/*
60.1531 +** The following structure contains information used by the sqliteFix...
60.1532 +** routines as they walk the parse tree to make database references
60.1533 +** explicit.
60.1534 +*/
60.1535 +typedef struct DbFixer DbFixer;
60.1536 +struct DbFixer {
60.1537 + Parse *pParse; /* The parsing context. Error messages written here */
60.1538 + const char *zDb; /* Make sure all objects are contained in this database */
60.1539 + const char *zType; /* Type of the container - used for error messages */
60.1540 + const Token *pName; /* Name of the container - used for error messages */
60.1541 +};
60.1542 +
60.1543 +/*
60.1544 +** A pointer to this structure is used to communicate information
60.1545 +** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
60.1546 +*/
60.1547 +typedef struct {
60.1548 + sqlite3 *db; /* The database being initialized */
60.1549 + int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
60.1550 + char **pzErrMsg; /* Error message stored here */
60.1551 + int rc; /* Result code stored here */
60.1552 +} InitData;
60.1553 +
60.1554 +/*
60.1555 + * This global flag is set for performance testing of triggers. When it is set
60.1556 + * SQLite will perform the overhead of building new and old trigger references
60.1557 + * even when no triggers exist
60.1558 + */
60.1559 +extern int sqlite3_always_code_trigger_setup;
60.1560 +
60.1561 +/*
60.1562 +** A lookup table used by the SQLITE_READ_UTF8 macro. The definition
60.1563 +** is in utf.c.
60.1564 +*/
60.1565 +extern const unsigned char sqlite3UtfTrans1[];
60.1566 +
60.1567 +/*
60.1568 +** Macros for reading UTF8 characters.
60.1569 +**
60.1570 +** SQLITE_READ_UTF8(x,c) reads a single UTF8 value out of x and writes
60.1571 +** that value into c. The type of x must be unsigned char*. The type
60.1572 +** of c must be unsigned int.
60.1573 +**
60.1574 +** SQLITE_SKIP_UTF8(x) advances x forward by one character. The type of
60.1575 +** x must be unsigned char*.
60.1576 +**
60.1577 +** Notes On Invalid UTF-8:
60.1578 +**
60.1579 +** * These macros never allow a 7-bit character (0x00 through 0x7f) to
60.1580 +** be encoded as a multi-byte character. Any multi-byte character that
60.1581 +** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
60.1582 +**
60.1583 +** * These macros never allow a UTF16 surrogate value to be encoded.
60.1584 +** If a multi-byte character attempts to encode a value between
60.1585 +** 0xd800 and 0xe000 then it is rendered as 0xfffd.
60.1586 +**
60.1587 +** * Bytes in the range of 0x80 through 0xbf which occur as the first
60.1588 +** byte of a character are interpreted as single-byte characters
60.1589 +** and rendered as themselves even though they are technically
60.1590 +** invalid characters.
60.1591 +**
60.1592 +** * These routines accept an infinite number of different UTF8 encodings
60.1593 +** for unicode values 0x80 and greater. They do not change over-length
60.1594 +** encodings to 0xfffd as some systems recommend.
60.1595 +**
60.1596 +*/
60.1597 +#define SQLITE_READ_UTF8(zIn, c) { \
60.1598 + c = *(zIn++); \
60.1599 + if( c>=0xc0 ){ \
60.1600 + c = sqlite3UtfTrans1[c-0xc0]; \
60.1601 + while( (*zIn & 0xc0)==0x80 ){ \
60.1602 + c = (c<<6) + (0x3f & *(zIn++)); \
60.1603 + } \
60.1604 + if( c<0x80 \
60.1605 + || (c&0xFFFFF800)==0xD800 \
60.1606 + || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
60.1607 + } \
60.1608 +}
60.1609 +#define SQLITE_SKIP_UTF8(zIn) { \
60.1610 + if( (*(zIn++))>=0xc0 ){ \
60.1611 + while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
60.1612 + } \
60.1613 +}
60.1614 +
60.1615 +
60.1616 +
60.1617 +
60.1618 +/*
60.1619 +** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
60.1620 +** builds) or a function call (for debugging). If it is a function call,
60.1621 +** it allows the operator to set a breakpoint at the spot where database
60.1622 +** corruption is first detected.
60.1623 +*/
60.1624 +#ifdef SQLITE_DEBUG
60.1625 + int sqlite3Corrupt(void);
60.1626 +# define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
60.1627 +#else
60.1628 +# define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
60.1629 +#endif
60.1630 +
60.1631 +/*
60.1632 +** Internal function prototypes
60.1633 +*/
60.1634 +int sqlite3StrICmp(const char *, const char *);
60.1635 +int sqlite3StrNICmp(const char *, const char *, int);
60.1636 +int sqlite3IsNumber(const char*, int*, u8);
60.1637 +
60.1638 +void *sqlite3Malloc(int,int);
60.1639 +void *sqlite3MallocRaw(int,int);
60.1640 +void *sqlite3Realloc(void*,int);
60.1641 +char *sqlite3StrDup(const char*);
60.1642 +char *sqlite3StrNDup(const char*, int);
60.1643 +# define sqlite3CheckMemory(a,b)
60.1644 +void *sqlite3ReallocOrFree(void*,int);
60.1645 +void sqlite3FreeX(void*);
60.1646 +void *sqlite3MallocX(int);
60.1647 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
60.1648 + int sqlite3AllocSize(void *);
60.1649 +#endif
60.1650 +
60.1651 +char *sqlite3MPrintf(const char*, ...);
60.1652 +char *sqlite3VMPrintf(const char*, va_list);
60.1653 +#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
60.1654 + void sqlite3DebugPrintf(const char*, ...);
60.1655 + void *sqlite3TextToPtr(const char*);
60.1656 +#endif
60.1657 +void sqlite3SetString(char **, ...);
60.1658 +void sqlite3ErrorMsg(Parse*, const char*, ...);
60.1659 +void sqlite3ErrorClear(Parse*);
60.1660 +void sqlite3Dequote(char*);
60.1661 +void sqlite3DequoteExpr(Expr*);
60.1662 +int sqlite3KeywordCode(const unsigned char*, int);
60.1663 +int sqlite3RunParser(Parse*, const char*, char **);
60.1664 +void sqlite3FinishCoding(Parse*);
60.1665 +Expr *sqlite3Expr(int, Expr*, Expr*, const Token*);
60.1666 +Expr *sqlite3ExprOrFree(int, Expr*, Expr*, const Token*);
60.1667 +Expr *sqlite3RegisterExpr(Parse*,Token*);
60.1668 +Expr *sqlite3ExprAnd(Expr*, Expr*);
60.1669 +void sqlite3ExprSpan(Expr*,Token*,Token*);
60.1670 +Expr *sqlite3ExprFunction(ExprList*, Token*);
60.1671 +void sqlite3ExprAssignVarNumber(Parse*, Expr*);
60.1672 +void sqlite3ExprDelete(Expr*);
60.1673 +ExprList *sqlite3ExprListAppend(ExprList*,Expr*,Token*);
60.1674 +void sqlite3ExprListDelete(ExprList*);
60.1675 +int sqlite3Init(sqlite3*, char**);
60.1676 +int sqlite3InitCallback(void*, int, char**, char**);
60.1677 +void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
60.1678 +void sqlite3ResetInternalSchema(sqlite3*, int);
60.1679 +void sqlite3BeginParse(Parse*,int);
60.1680 +void sqlite3CommitInternalChanges(sqlite3*);
60.1681 +Table *sqlite3ResultSetOfSelect(Parse*,char*,Select*);
60.1682 +void sqlite3OpenMasterTable(Parse *, int);
60.1683 +void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
60.1684 +void sqlite3AddColumn(Parse*,Token*);
60.1685 +void sqlite3AddNotNull(Parse*, int);
60.1686 +void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
60.1687 +void sqlite3AddCheckConstraint(Parse*, Expr*);
60.1688 +void sqlite3AddColumnType(Parse*,Token*);
60.1689 +void sqlite3AddDefaultValue(Parse*,Expr*);
60.1690 +void sqlite3AddCollateType(Parse*, const char*, int);
60.1691 +void sqlite3EndTable(Parse*,Token*,Token*,Select*);
60.1692 +
60.1693 +void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
60.1694 +
60.1695 +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
60.1696 + int sqlite3ViewGetColumnNames(Parse*,Table*);
60.1697 +#else
60.1698 +# define sqlite3ViewGetColumnNames(A,B) 0
60.1699 +#endif
60.1700 +
60.1701 +void sqlite3DropTable(Parse*, SrcList*, int, int);
60.1702 +void sqlite3DeleteTable(Table*);
60.1703 +void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
60.1704 +void *sqlite3ArrayAllocate(void*,int,int,int*,int*,int*);
60.1705 +IdList *sqlite3IdListAppend(IdList*, Token*);
60.1706 +int sqlite3IdListIndex(IdList*,const char*);
60.1707 +SrcList *sqlite3SrcListAppend(SrcList*, Token*, Token*);
60.1708 +SrcList *sqlite3SrcListAppendFromTerm(SrcList*, Token*, Token*, Token*,
60.1709 + Select*, Expr*, IdList*);
60.1710 +void sqlite3SrcListShiftJoinType(SrcList*);
60.1711 +void sqlite3SrcListAssignCursors(Parse*, SrcList*);
60.1712 +void sqlite3IdListDelete(IdList*);
60.1713 +void sqlite3SrcListDelete(SrcList*);
60.1714 +void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
60.1715 + Token*, int, int);
60.1716 +void sqlite3DropIndex(Parse*, SrcList*, int);
60.1717 +int sqlite3Select(Parse*, Select*, int, int, Select*, int, int*, char *aff);
60.1718 +Select *sqlite3SelectNew(ExprList*,SrcList*,Expr*,ExprList*,Expr*,ExprList*,
60.1719 + int,Expr*,Expr*);
60.1720 +void sqlite3SelectDelete(Select*);
60.1721 +Table *sqlite3SrcListLookup(Parse*, SrcList*);
60.1722 +int sqlite3IsReadOnly(Parse*, Table*, int);
60.1723 +void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
60.1724 +void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
60.1725 +void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
60.1726 +WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**);
60.1727 +void sqlite3WhereEnd(WhereInfo*);
60.1728 +void sqlite3ExprCodeGetColumn(Vdbe*, Table*, int, int);
60.1729 +void sqlite3ExprCode(Parse*, Expr*);
60.1730 +void sqlite3ExprCodeAndCache(Parse*, Expr*);
60.1731 +int sqlite3ExprCodeExprList(Parse*, ExprList*);
60.1732 +void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
60.1733 +void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
60.1734 +Table *sqlite3FindTable(sqlite3*,const char*, const char*);
60.1735 +Table *sqlite3LocateTable(Parse*,const char*, const char*);
60.1736 +Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
60.1737 +void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
60.1738 +void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
60.1739 +void sqlite3Vacuum(Parse*);
60.1740 +int sqlite3RunVacuum(char**, sqlite3*);
60.1741 +char *sqlite3NameFromToken(Token*);
60.1742 +int sqlite3ExprCompare(Expr*, Expr*);
60.1743 +int sqliteFuncId(Token*);
60.1744 +int sqlite3ExprResolveNames(NameContext *, Expr *);
60.1745 +int sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
60.1746 +int sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
60.1747 +Vdbe *sqlite3GetVdbe(Parse*);
60.1748 +Expr *sqlite3CreateIdExpr(const char*);
60.1749 +void sqlite3Randomness(int, void*);
60.1750 +void sqlite3RollbackAll(sqlite3*);
60.1751 +void sqlite3CodeVerifySchema(Parse*, int);
60.1752 +void sqlite3BeginTransaction(Parse*, int);
60.1753 +void sqlite3CommitTransaction(Parse*);
60.1754 +void sqlite3RollbackTransaction(Parse*);
60.1755 +int sqlite3ExprIsConstant(Expr*);
60.1756 +int sqlite3ExprIsConstantNotJoin(Expr*);
60.1757 +int sqlite3ExprIsConstantOrFunction(Expr*);
60.1758 +int sqlite3ExprIsInteger(Expr*, int*);
60.1759 +int sqlite3IsRowid(const char*);
60.1760 +void sqlite3GenerateRowDelete(sqlite3*, Vdbe*, Table*, int, int);
60.1761 +void sqlite3GenerateRowIndexDelete(Vdbe*, Table*, int, char*);
60.1762 +void sqlite3GenerateIndexKey(Vdbe*, Index*, int);
60.1763 +void sqlite3GenerateConstraintChecks(Parse*,Table*,int,char*,int,int,int,int);
60.1764 +void sqlite3CompleteInsertion(Parse*, Table*, int, char*, int, int, int, int);
60.1765 +void sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
60.1766 +void sqlite3BeginWriteOperation(Parse*, int, int);
60.1767 +Expr *sqlite3ExprDup(Expr*);
60.1768 +void sqlite3TokenCopy(Token*, Token*);
60.1769 +ExprList *sqlite3ExprListDup(ExprList*);
60.1770 +SrcList *sqlite3SrcListDup(SrcList*);
60.1771 +IdList *sqlite3IdListDup(IdList*);
60.1772 +Select *sqlite3SelectDup(Select*);
60.1773 +FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
60.1774 +void sqlite3RegisterBuiltinFunctions(sqlite3*);
60.1775 +void sqlite3RegisterDateTimeFunctions(sqlite3*);
60.1776 +int sqlite3SafetyOn(sqlite3*);
60.1777 +int sqlite3SafetyOff(sqlite3*);
60.1778 +int sqlite3SafetyCheck(sqlite3*);
60.1779 +void sqlite3ChangeCookie(sqlite3*, Vdbe*, int);
60.1780 +
60.1781 +#ifndef SQLITE_OMIT_TRIGGER
60.1782 + void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
60.1783 + Expr*,int, int);
60.1784 + void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
60.1785 + void sqlite3DropTrigger(Parse*, SrcList*, int);
60.1786 + void sqlite3DropTriggerPtr(Parse*, Trigger*);
60.1787 + int sqlite3TriggersExist(Parse*, Table*, int, ExprList*);
60.1788 + int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int,
60.1789 + int, int);
60.1790 + void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
60.1791 + void sqlite3DeleteTriggerStep(TriggerStep*);
60.1792 + TriggerStep *sqlite3TriggerSelectStep(Select*);
60.1793 + TriggerStep *sqlite3TriggerInsertStep(Token*, IdList*, ExprList*,Select*,int);
60.1794 + TriggerStep *sqlite3TriggerUpdateStep(Token*, ExprList*, Expr*, int);
60.1795 + TriggerStep *sqlite3TriggerDeleteStep(Token*, Expr*);
60.1796 + void sqlite3DeleteTrigger(Trigger*);
60.1797 + void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
60.1798 +#else
60.1799 +# define sqlite3TriggersExist(A,B,C,D,E,F) 0
60.1800 +# define sqlite3DeleteTrigger(A)
60.1801 +# define sqlite3DropTriggerPtr(A,B)
60.1802 +# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
60.1803 +# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I) 0
60.1804 +#endif
60.1805 +
60.1806 +int sqlite3JoinType(Parse*, Token*, Token*, Token*);
60.1807 +void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
60.1808 +void sqlite3DeferForeignKey(Parse*, int);
60.1809 +#ifndef SQLITE_OMIT_AUTHORIZATION
60.1810 + void sqlite3AuthRead(Parse*,Expr*,SrcList*);
60.1811 + int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
60.1812 + void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
60.1813 + void sqlite3AuthContextPop(AuthContext*);
60.1814 +#else
60.1815 +# define sqlite3AuthRead(a,b,c)
60.1816 +# define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
60.1817 +# define sqlite3AuthContextPush(a,b,c)
60.1818 +# define sqlite3AuthContextPop(a) ((void)(a))
60.1819 +#endif
60.1820 +void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
60.1821 +void sqlite3Detach(Parse*, Expr*);
60.1822 +int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
60.1823 + int omitJournal, int nCache, Btree **ppBtree);
60.1824 +int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
60.1825 +int sqlite3FixSrcList(DbFixer*, SrcList*);
60.1826 +int sqlite3FixSelect(DbFixer*, Select*);
60.1827 +int sqlite3FixExpr(DbFixer*, Expr*);
60.1828 +int sqlite3FixExprList(DbFixer*, ExprList*);
60.1829 +int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
60.1830 +int sqlite3AtoF(const char *z, double*);
60.1831 +char *sqlite3_snprintf(int,char*,const char*,...);
60.1832 +int sqlite3GetInt32(const char *, int*);
60.1833 +int sqlite3FitsIn64Bits(const char *);
60.1834 +int sqlite3Utf16ByteLen(const void *pData, int nChar);
60.1835 +int sqlite3Utf8CharLen(const char *pData, int nByte);
60.1836 +u32 sqlite3ReadUtf8(const unsigned char *);
60.1837 +int sqlite3PutVarint(unsigned char *, u64);
60.1838 +int sqlite3GetVarint(const unsigned char *, u64 *);
60.1839 +int sqlite3GetVarint32(const unsigned char *, u32 *);
60.1840 +int sqlite3VarintLen(u64 v);
60.1841 +void sqlite3IndexAffinityStr(Vdbe *, Index *);
60.1842 +void sqlite3TableAffinityStr(Vdbe *, Table *);
60.1843 +char sqlite3CompareAffinity(Expr *pExpr, char aff2);
60.1844 +int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
60.1845 +char sqlite3ExprAffinity(Expr *pExpr);
60.1846 +int sqlite3Atoi64(const char*, i64*);
60.1847 +void sqlite3Error(sqlite3*, int, const char*,...);
60.1848 +void *sqlite3HexToBlob(const char *z);
60.1849 +int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
60.1850 +const char *sqlite3ErrStr(int);
60.1851 +int sqlite3ReadSchema(Parse *pParse);
60.1852 +CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
60.1853 +CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
60.1854 +CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
60.1855 +Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
60.1856 +int sqlite3CheckCollSeq(Parse *, CollSeq *);
60.1857 +int sqlite3CheckObjectName(Parse *, const char *);
60.1858 +void sqlite3VdbeSetChanges(sqlite3 *, int);
60.1859 +void sqlite3Utf16Substr(sqlite3_context *,int,sqlite3_value **);
60.1860 +
60.1861 +const void *sqlite3ValueText(sqlite3_value*, u8);
60.1862 +int sqlite3ValueBytes(sqlite3_value*, u8);
60.1863 +void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, void(*)(void*));
60.1864 +void sqlite3ValueFree(sqlite3_value*);
60.1865 +sqlite3_value *sqlite3ValueNew(void);
60.1866 +char *sqlite3Utf16to8(const void*, int);
60.1867 +int sqlite3ValueFromExpr(Expr *, u8, u8, sqlite3_value **);
60.1868 +void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
60.1869 +extern const unsigned char sqlite3UpperToLower[];
60.1870 +void sqlite3RootPageMoved(Db*, int, int);
60.1871 +void sqlite3Reindex(Parse*, Token*, Token*);
60.1872 +void sqlite3AlterFunctions(sqlite3*);
60.1873 +void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
60.1874 +int sqlite3GetToken(const unsigned char *, int *);
60.1875 +void sqlite3NestedParse(Parse*, const char*, ...);
60.1876 +void sqlite3ExpirePreparedStatements(sqlite3*);
60.1877 +void sqlite3CodeSubselect(Parse *, Expr *);
60.1878 +int sqlite3SelectResolve(Parse *, Select *, NameContext *);
60.1879 +void sqlite3ColumnDefault(Vdbe *, Table *, int);
60.1880 +void sqlite3AlterFinishAddColumn(Parse *, Token *);
60.1881 +void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
60.1882 +CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
60.1883 +char sqlite3AffinityType(const Token*);
60.1884 +void sqlite3Analyze(Parse*, Token*, Token*);
60.1885 +int sqlite3InvokeBusyHandler(BusyHandler*);
60.1886 +int sqlite3FindDb(sqlite3*, Token*);
60.1887 +int sqlite3AnalysisLoad(sqlite3*,int iDB);
60.1888 +void sqlite3DefaultRowEst(Index*);
60.1889 +void sqlite3RegisterLikeFunctions(sqlite3*, int);
60.1890 +int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
60.1891 +ThreadData *sqlite3ThreadData(void);
60.1892 +const ThreadData *sqlite3ThreadDataReadOnly(void);
60.1893 +void sqlite3ReleaseThreadData(void);
60.1894 +void sqlite3AttachFunctions(sqlite3 *);
60.1895 +void sqlite3MinimumFileFormat(Parse*, int, int);
60.1896 +void sqlite3SchemaFree(void *);
60.1897 +Schema *sqlite3SchemaGet(Btree *);
60.1898 +int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
60.1899 +KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
60.1900 +int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
60.1901 + void (*)(sqlite3_context*,int,sqlite3_value **),
60.1902 + void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
60.1903 +int sqlite3ApiExit(sqlite3 *db, int);
60.1904 +void sqlite3FailedMalloc(void);
60.1905 +void sqlite3AbortOtherActiveVdbes(sqlite3 *, Vdbe *);
60.1906 +int sqlite3OpenTempDatabase(Parse *);
60.1907 +
60.1908 +#ifndef SQLITE_OMIT_LOAD_EXTENSION
60.1909 + void sqlite3CloseExtensions(sqlite3*);
60.1910 + int sqlite3AutoLoadExtensions(sqlite3*);
60.1911 +#else
60.1912 +# define sqlite3CloseExtensions(X)
60.1913 +# define sqlite3AutoLoadExtensions(X) SQLITE_OK
60.1914 +#endif
60.1915 +
60.1916 +#ifndef SQLITE_OMIT_SHARED_CACHE
60.1917 + void sqlite3TableLock(Parse *, int, int, u8, const char *);
60.1918 +#else
60.1919 + #define sqlite3TableLock(v,w,x,y,z)
60.1920 +#endif
60.1921 +
60.1922 +#ifdef SQLITE_TEST
60.1923 + int sqlite3Utf8To8(unsigned char*);
60.1924 +#endif
60.1925 +
60.1926 +#ifdef SQLITE_MEMDEBUG
60.1927 + void sqlite3MallocDisallow(void);
60.1928 + void sqlite3MallocAllow(void);
60.1929 + int sqlite3TestMallocFail(void);
60.1930 +#else
60.1931 + #define sqlite3TestMallocFail() 0
60.1932 + #define sqlite3MallocDisallow()
60.1933 + #define sqlite3MallocAllow()
60.1934 +#endif
60.1935 +
60.1936 +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
60.1937 + void *sqlite3ThreadSafeMalloc(int);
60.1938 + void sqlite3ThreadSafeFree(void *);
60.1939 +#else
60.1940 + #define sqlite3ThreadSafeMalloc sqlite3MallocX
60.1941 + #define sqlite3ThreadSafeFree sqlite3FreeX
60.1942 +#endif
60.1943 +
60.1944 +#ifdef SQLITE_OMIT_VIRTUALTABLE
60.1945 +# define sqlite3VtabClear(X)
60.1946 +# define sqlite3VtabSync(X,Y) (Y)
60.1947 +# define sqlite3VtabRollback(X)
60.1948 +# define sqlite3VtabCommit(X)
60.1949 +#else
60.1950 + void sqlite3VtabClear(Table*);
60.1951 + int sqlite3VtabSync(sqlite3 *db, int rc);
60.1952 + int sqlite3VtabRollback(sqlite3 *db);
60.1953 + int sqlite3VtabCommit(sqlite3 *db);
60.1954 +#endif
60.1955 +void sqlite3VtabLock(sqlite3_vtab*);
60.1956 +void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
60.1957 +void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
60.1958 +void sqlite3VtabFinishParse(Parse*, Token*);
60.1959 +void sqlite3VtabArgInit(Parse*);
60.1960 +void sqlite3VtabArgExtend(Parse*, Token*);
60.1961 +int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
60.1962 +int sqlite3VtabCallConnect(Parse*, Table*);
60.1963 +int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
60.1964 +int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
60.1965 +FuncDef *sqlite3VtabOverloadFunction(FuncDef*, int nArg, Expr*);
60.1966 +void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
60.1967 +int sqlite3Reprepare(Vdbe*);
60.1968 +void sqlite3ExprListCheckLength(Parse*, ExprList*, int, const char*);
60.1969 +CollSeq* sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
60.1970 +
60.1971 +#if SQLITE_MAX_EXPR_DEPTH>0
60.1972 + void sqlite3ExprSetHeight(Expr *);
60.1973 + int sqlite3SelectExprHeight(Select *);
60.1974 +#else
60.1975 + #define sqlite3ExprSetHeight(x)
60.1976 +#endif
60.1977 +
60.1978 +u32 sqlite3Get2byte(const u8*);
60.1979 +u32 sqlite3Get4byte(const u8*);
60.1980 +void sqlite3Put2byte(u8*, u32);
60.1981 +void sqlite3Put4byte(u8*, u32);
60.1982 +
60.1983 +#ifdef SQLITE_SSE
60.1984 +#include "sseInt.h"
60.1985 +#endif
60.1986 +
60.1987 +#ifdef SQLITE_DEBUG
60.1988 + void sqlite3ParserTrace(FILE*, char *);
60.1989 +#endif
60.1990 +
60.1991 +/*
60.1992 +** If the SQLITE_ENABLE IOTRACE exists then the global variable
60.1993 +** sqlite3_io_trace is a pointer to a printf-like routine used to
60.1994 +** print I/O tracing messages.
60.1995 +*/
60.1996 +#ifdef SQLITE_ENABLE_IOTRACE
60.1997 +# define IOTRACE(A) if( sqlite3_io_trace ){ sqlite3_io_trace A; }
60.1998 + void sqlite3VdbeIOTraceSql(Vdbe*);
60.1999 +#else
60.2000 +# define IOTRACE(A)
60.2001 +# define sqlite3VdbeIOTraceSql(X)
60.2002 +#endif
60.2003 +extern void (*sqlite3_io_trace)(const char*,...);
60.2004 +
60.2005 +#endif
61.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
61.2 +++ b/extensions/sqlite/sqlite-source/sqliteLimit.h Sun Jul 29 01:15:31 2007 +0000
61.3 @@ -0,0 +1,158 @@
61.4 +/*
61.5 +** 2007 May 7
61.6 +**
61.7 +** The author disclaims copyright to this source code. In place of
61.8 +** a legal notice, here is a blessing:
61.9 +**
61.10 +** May you do good and not evil.
61.11 +** May you find forgiveness for yourself and forgive others.
61.12 +** May you share freely, never taking more than you give.
61.13 +**
61.14 +*************************************************************************
61.15 +**
61.16 +** This file defines various limits of what SQLite can process.
61.17 +**
61.18 +** @(#) $Id$
61.19 +*/
61.20 +
61.21 +/*
61.22 +** The maximum length of a TEXT or BLOB in bytes. This also
61.23 +** limits the size of a row in a table or index.
61.24 +**
61.25 +** The hard limit is the ability of a 32-bit signed integer
61.26 +** to count the size: 2^31-1 or 2147483647.
61.27 +*/
61.28 +#ifndef SQLITE_MAX_LENGTH
61.29 +# define SQLITE_MAX_LENGTH 1000000000
61.30 +#endif
61.31 +
61.32 +/*
61.33 +** This is the maximum number of
61.34 +**
61.35 +** * Columns in a table
61.36 +** * Columns in an index
61.37 +** * Columns in a view
61.38 +** * Terms in the SET clause of an UPDATE statement
61.39 +** * Terms in the result set of a SELECT statement
61.40 +** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
61.41 +** * Terms in the VALUES clause of an INSERT statement
61.42 +**
61.43 +** The hard upper limit here is 32676. Most database people will
61.44 +** tell you that in a well-normalized database, you usually should
61.45 +** not have more than a dozen or so columns in any table. And if
61.46 +** that is the case, there is no point in having more than a few
61.47 +** dozen values in any of the other situations described above.
61.48 +*/
61.49 +#ifndef SQLITE_MAX_COLUMN
61.50 +# define SQLITE_MAX_COLUMN 2000
61.51 +#endif
61.52 +
61.53 +/*
61.54 +** The maximum length of a single SQL statement in bytes.
61.55 +** The hard limit here is the same as SQLITE_MAX_LENGTH.
61.56 +*/
61.57 +#ifndef SQLITE_MAX_SQL_LENGTH
61.58 +# define SQLITE_MAX_SQL_LENGTH 1000000
61.59 +#endif
61.60 +
61.61 +/*
61.62 +** The maximum depth of an expression tree. This is limited to
61.63 +** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
61.64 +** want to place more severe limits on the complexity of an
61.65 +** expression. A value of 0 (the default) means do not enforce
61.66 +** any limitation on expression tree depth.
61.67 +*/
61.68 +#ifndef SQLITE_MAX_EXPR_DEPTH
61.69 +# define SQLITE_MAX_EXPR_DEPTH 1000
61.70 +#endif
61.71 +
61.72 +/*
61.73 +** The maximum number of terms in a compound SELECT statement.
61.74 +** The code generator for compound SELECT statements does one
61.75 +** level of recursion for each term. A stack overflow can result
61.76 +** if the number of terms is too large. In practice, most SQL
61.77 +** never has more than 3 or 4 terms. Use a value of 0 to disable
61.78 +** any limit on the number of terms in a compount SELECT.
61.79 +*/
61.80 +#ifndef SQLITE_MAX_COMPOUND_SELECT
61.81 +# define SQLITE_MAX_COMPOUND_SELECT 500
61.82 +#endif
61.83 +
61.84 +/*
61.85 +** The maximum number of opcodes in a VDBE program.
61.86 +** Not currently enforced.
61.87 +*/
61.88 +#ifndef SQLITE_MAX_VDBE_OP
61.89 +# define SQLITE_MAX_VDBE_OP 25000
61.90 +#endif
61.91 +
61.92 +/*
61.93 +** The maximum number of arguments to an SQL function.
61.94 +*/
61.95 +#ifndef SQLITE_MAX_FUNCTION_ARG
61.96 +# define SQLITE_MAX_FUNCTION_ARG 100
61.97 +#endif
61.98 +
61.99 +/*
61.100 +** The maximum number of in-memory pages to use for the main database
61.101 +** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
61.102 +*/
61.103 +#ifndef SQLITE_DEFAULT_CACHE_SIZE
61.104 +# define SQLITE_DEFAULT_CACHE_SIZE 2000
61.105 +#endif
61.106 +#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
61.107 +# define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
61.108 +#endif
61.109 +
61.110 +/*
61.111 +** The maximum number of attached databases. This must be at least 2
61.112 +** in order to support the main database file (0) and the file used to
61.113 +** hold temporary tables (1). And it must be less than 32 because
61.114 +** we use a bitmask of databases with a u32 in places (for example
61.115 +** the Parse.cookieMask field).
61.116 +*/
61.117 +#ifndef SQLITE_MAX_ATTACHED
61.118 +# define SQLITE_MAX_ATTACHED 10
61.119 +#endif
61.120 +
61.121 +
61.122 +/*
61.123 +** The maximum value of a ?nnn wildcard that the parser will accept.
61.124 +*/
61.125 +#ifndef SQLITE_MAX_VARIABLE_NUMBER
61.126 +# define SQLITE_MAX_VARIABLE_NUMBER 999
61.127 +#endif
61.128 +
61.129 +/*
61.130 +** The default size of a database page.
61.131 +*/
61.132 +#ifndef SQLITE_DEFAULT_PAGE_SIZE
61.133 +# define SQLITE_DEFAULT_PAGE_SIZE 1024
61.134 +#endif
61.135 +
61.136 +/* Maximum page size. The upper bound on this value is 32768. This a limit
61.137 +** imposed by the necessity of storing the value in a 2-byte unsigned integer
61.138 +** and the fact that the page size must be a power of 2.
61.139 +*/
61.140 +#ifndef SQLITE_MAX_PAGE_SIZE
61.141 +# define SQLITE_MAX_PAGE_SIZE 32768
61.142 +#endif
61.143 +
61.144 +/*
61.145 +** Maximum number of pages in one database file.
61.146 +**
61.147 +** This is really just the default value for the max_page_count pragma.
61.148 +** This value can be lowered (or raised) at run-time using that the
61.149 +** max_page_count macro.
61.150 +*/
61.151 +#ifndef SQLITE_MAX_PAGE_COUNT
61.152 +# define SQLITE_MAX_PAGE_COUNT 1073741823
61.153 +#endif
61.154 +
61.155 +/*
61.156 +** Maximum length (in bytes) of the pattern in a LIKE or GLOB
61.157 +** operator.
61.158 +*/
61.159 +#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
61.160 +# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
61.161 +#endif
62.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
62.2 +++ b/extensions/sqlite/sqlite-source/table.c Sun Jul 29 01:15:31 2007 +0000
62.3 @@ -0,0 +1,199 @@
62.4 +/*
62.5 +** 2001 September 15
62.6 +**
62.7 +** The author disclaims copyright to this source code. In place of
62.8 +** a legal notice, here is a blessing:
62.9 +**
62.10 +** May you do good and not evil.
62.11 +** May you find forgiveness for yourself and forgive others.
62.12 +** May you share freely, never taking more than you give.
62.13 +**
62.14 +*************************************************************************
62.15 +** This file contains the sqlite3_get_table() and sqlite3_free_table()
62.16 +** interface routines. These are just wrappers around the main
62.17 +** interface routine of sqlite3_exec().
62.18 +**
62.19 +** These routines are in a separate files so that they will not be linked
62.20 +** if they are not used.
62.21 +*/
62.22 +#include "sqliteInt.h"
62.23 +#include <stdlib.h>
62.24 +#include <string.h>
62.25 +
62.26 +#ifndef SQLITE_OMIT_GET_TABLE
62.27 +
62.28 +/*
62.29 +** This structure is used to pass data from sqlite3_get_table() through
62.30 +** to the callback function is uses to build the result.
62.31 +*/
62.32 +typedef struct TabResult {
62.33 + char **azResult;
62.34 + char *zErrMsg;
62.35 + int nResult;
62.36 + int nAlloc;
62.37 + int nRow;
62.38 + int nColumn;
62.39 + int nData;
62.40 + int rc;
62.41 +} TabResult;
62.42 +
62.43 +/*
62.44 +** This routine is called once for each row in the result table. Its job
62.45 +** is to fill in the TabResult structure appropriately, allocating new
62.46 +** memory as necessary.
62.47 +*/
62.48 +static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
62.49 + TabResult *p = (TabResult*)pArg;
62.50 + int need;
62.51 + int i;
62.52 + char *z;
62.53 +
62.54 + /* Make sure there is enough space in p->azResult to hold everything
62.55 + ** we need to remember from this invocation of the callback.
62.56 + */
62.57 + if( p->nRow==0 && argv!=0 ){
62.58 + need = nCol*2;
62.59 + }else{
62.60 + need = nCol;
62.61 + }
62.62 + if( p->nData + need >= p->nAlloc ){
62.63 + char **azNew;
62.64 + p->nAlloc = p->nAlloc*2 + need + 1;
62.65 + azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
62.66 + if( azNew==0 ) goto malloc_failed;
62.67 + p->azResult = azNew;
62.68 + }
62.69 +
62.70 + /* If this is the first row, then generate an extra row containing
62.71 + ** the names of all columns.
62.72 + */
62.73 + if( p->nRow==0 ){
62.74 + p->nColumn = nCol;
62.75 + for(i=0; i<nCol; i++){
62.76 + if( colv[i]==0 ){
62.77 + z = sqlite3_mprintf("");
62.78 + }else{
62.79 + z = sqlite3_mprintf("%s", colv[i]);
62.80 + }
62.81 + p->azResult[p->nData++] = z;
62.82 + }
62.83 + }else if( p->nColumn!=nCol ){
62.84 + sqlite3SetString(&p->zErrMsg,
62.85 + "sqlite3_get_table() called with two or more incompatible queries",
62.86 + (char*)0);
62.87 + p->rc = SQLITE_ERROR;
62.88 + return 1;
62.89 + }
62.90 +
62.91 + /* Copy over the row data
62.92 + */
62.93 + if( argv!=0 ){
62.94 + for(i=0; i<nCol; i++){
62.95 + if( argv[i]==0 ){
62.96 + z = 0;
62.97 + }else{
62.98 + int n = strlen(argv[i])+1;
62.99 + z = sqlite3_malloc( n );
62.100 + if( z==0 ) goto malloc_failed;
62.101 + memcpy(z, argv[i], n);
62.102 + }
62.103 + p->azResult[p->nData++] = z;
62.104 + }
62.105 + p->nRow++;
62.106 + }
62.107 + return 0;
62.108 +
62.109 +malloc_failed:
62.110 + p->rc = SQLITE_NOMEM;
62.111 + return 1;
62.112 +}
62.113 +
62.114 +/*
62.115 +** Query the database. But instead of invoking a callback for each row,
62.116 +** malloc() for space to hold the result and return the entire results
62.117 +** at the conclusion of the call.
62.118 +**
62.119 +** The result that is written to ***pazResult is held in memory obtained
62.120 +** from malloc(). But the caller cannot free this memory directly.
62.121 +** Instead, the entire table should be passed to sqlite3_free_table() when
62.122 +** the calling procedure is finished using it.
62.123 +*/
62.124 +int sqlite3_get_table(
62.125 + sqlite3 *db, /* The database on which the SQL executes */
62.126 + const char *zSql, /* The SQL to be executed */
62.127 + char ***pazResult, /* Write the result table here */
62.128 + int *pnRow, /* Write the number of rows in the result here */
62.129 + int *pnColumn, /* Write the number of columns of result here */
62.130 + char **pzErrMsg /* Write error messages here */
62.131 +){
62.132 + int rc;
62.133 + TabResult res;
62.134 + if( pazResult==0 ){ return SQLITE_ERROR; }
62.135 + *pazResult = 0;
62.136 + if( pnColumn ) *pnColumn = 0;
62.137 + if( pnRow ) *pnRow = 0;
62.138 + res.zErrMsg = 0;
62.139 + res.nResult = 0;
62.140 + res.nRow = 0;
62.141 + res.nColumn = 0;
62.142 + res.nData = 1;
62.143 + res.nAlloc = 20;
62.144 + res.rc = SQLITE_OK;
62.145 + res.azResult = sqlite3_malloc( sizeof(char*)*res.nAlloc );
62.146 + if( res.azResult==0 ) return SQLITE_NOMEM;
62.147 + res.azResult[0] = 0;
62.148 + rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
62.149 + if( res.azResult ){
62.150 + assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
62.151 + res.azResult[0] = (char*)res.nData;
62.152 + }
62.153 + if( (rc&0xff)==SQLITE_ABORT ){
62.154 + sqlite3_free_table(&res.azResult[1]);
62.155 + if( res.zErrMsg ){
62.156 + if( pzErrMsg ){
62.157 + sqlite3_free(*pzErrMsg);
62.158 + *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
62.159 + }
62.160 + sqliteFree(res.zErrMsg);
62.161 + }
62.162 + db->errCode = res.rc;
62.163 + return res.rc & db->errMask;
62.164 + }
62.165 + sqliteFree(res.zErrMsg);
62.166 + if( rc!=SQLITE_OK ){
62.167 + sqlite3_free_table(&res.azResult[1]);
62.168 + return rc & db->errMask;
62.169 + }
62.170 + if( res.nAlloc>res.nData ){
62.171 + char **azNew;
62.172 + azNew = sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) );
62.173 + if( azNew==0 ){
62.174 + sqlite3_free_table(&res.azResult[1]);
62.175 + return SQLITE_NOMEM;
62.176 + }
62.177 + res.nAlloc = res.nData+1;
62.178 + res.azResult = azNew;
62.179 + }
62.180 + *pazResult = &res.azResult[1];
62.181 + if( pnColumn ) *pnColumn = res.nColumn;
62.182 + if( pnRow ) *pnRow = res.nRow;
62.183 + return rc & db->errMask;
62.184 +}
62.185 +
62.186 +/*
62.187 +** This routine frees the space the sqlite3_get_table() malloced.
62.188 +*/
62.189 +void sqlite3_free_table(
62.190 + char **azResult /* Result returned from from sqlite3_get_table() */
62.191 +){
62.192 + if( azResult ){
62.193 + int i, n;
62.194 + azResult--;
62.195 + if( azResult==0 ) return;
62.196 + n = (int)azResult[0];
62.197 + for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
62.198 + sqlite3_free(azResult);
62.199 + }
62.200 +}
62.201 +
62.202 +#endif /* SQLITE_OMIT_GET_TABLE */
63.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
63.2 +++ b/extensions/sqlite/sqlite-source/tokenize.c Sun Jul 29 01:15:31 2007 +0000
63.3 @@ -0,0 +1,515 @@
63.4 +/*
63.5 +** 2001 September 15
63.6 +**
63.7 +** The author disclaims copyright to this source code. In place of
63.8 +** a legal notice, here is a blessing:
63.9 +**
63.10 +** May you do good and not evil.
63.11 +** May you find forgiveness for yourself and forgive others.
63.12 +** May you share freely, never taking more than you give.
63.13 +**
63.14 +*************************************************************************
63.15 +** An tokenizer for SQL
63.16 +**
63.17 +** This file contains C code that splits an SQL input string up into
63.18 +** individual tokens and sends those tokens one-by-one over to the
63.19 +** parser for analysis.
63.20 +**
63.21 +** $Id$
63.22 +*/
63.23 +#include "sqliteInt.h"
63.24 +#include "os.h"
63.25 +#include <ctype.h>
63.26 +#include <stdlib.h>
63.27 +
63.28 +/*
63.29 +** The charMap() macro maps alphabetic characters into their
63.30 +** lower-case ASCII equivalent. On ASCII machines, this is just
63.31 +** an upper-to-lower case map. On EBCDIC machines we also need
63.32 +** to adjust the encoding. Only alphabetic characters and underscores
63.33 +** need to be translated.
63.34 +*/
63.35 +#ifdef SQLITE_ASCII
63.36 +# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
63.37 +#endif
63.38 +#ifdef SQLITE_EBCDIC
63.39 +# define charMap(X) ebcdicToAscii[(unsigned char)X]
63.40 +const unsigned char ebcdicToAscii[] = {
63.41 +/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
63.42 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
63.43 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
63.44 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
63.45 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
63.46 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
63.47 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
63.48 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
63.49 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
63.50 + 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
63.51 + 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
63.52 + 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
63.53 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
63.54 + 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
63.55 + 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
63.56 + 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
63.57 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
63.58 +};
63.59 +#endif
63.60 +
63.61 +/*
63.62 +** The sqlite3KeywordCode function looks up an identifier to determine if
63.63 +** it is a keyword. If it is a keyword, the token code of that keyword is
63.64 +** returned. If the input is not a keyword, TK_ID is returned.
63.65 +**
63.66 +** The implementation of this routine was generated by a program,
63.67 +** mkkeywordhash.h, located in the tool subdirectory of the distribution.
63.68 +** The output of the mkkeywordhash.c program is written into a file
63.69 +** named keywordhash.h and then included into this source file by
63.70 +** the #include below.
63.71 +*/
63.72 +#include "keywordhash.h"
63.73 +
63.74 +
63.75 +/*
63.76 +** If X is a character that can be used in an identifier then
63.77 +** IdChar(X) will be true. Otherwise it is false.
63.78 +**
63.79 +** For ASCII, any character with the high-order bit set is
63.80 +** allowed in an identifier. For 7-bit characters,
63.81 +** sqlite3IsIdChar[X] must be 1.
63.82 +**
63.83 +** For EBCDIC, the rules are more complex but have the same
63.84 +** end result.
63.85 +**
63.86 +** Ticket #1066. the SQL standard does not allow '$' in the
63.87 +** middle of identfiers. But many SQL implementations do.
63.88 +** SQLite will allow '$' in identifiers for compatibility.
63.89 +** But the feature is undocumented.
63.90 +*/
63.91 +#ifdef SQLITE_ASCII
63.92 +const char sqlite3IsIdChar[] = {
63.93 +/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
63.94 + 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
63.95 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
63.96 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
63.97 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
63.98 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
63.99 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
63.100 +};
63.101 +#define IdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsIdChar[c-0x20]))
63.102 +#endif
63.103 +#ifdef SQLITE_EBCDIC
63.104 +const char sqlite3IsIdChar[] = {
63.105 +/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
63.106 + 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
63.107 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
63.108 + 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
63.109 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
63.110 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
63.111 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
63.112 + 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
63.113 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
63.114 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
63.115 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
63.116 + 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
63.117 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
63.118 +};
63.119 +#define IdChar(C) (((c=C)>=0x42 && sqlite3IsIdChar[c-0x40]))
63.120 +#endif
63.121 +
63.122 +
63.123 +/*
63.124 +** Return the length of the token that begins at z[0].
63.125 +** Store the token type in *tokenType before returning.
63.126 +*/
63.127 +static int getToken(const unsigned char *z, int *tokenType){
63.128 + int i, c;
63.129 + switch( *z ){
63.130 + case ' ': case '\t': case '\n': case '\f': case '\r': {
63.131 + for(i=1; isspace(z[i]); i++){}
63.132 + *tokenType = TK_SPACE;
63.133 + return i;
63.134 + }
63.135 + case '-': {
63.136 + if( z[1]=='-' ){
63.137 + for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
63.138 + *tokenType = TK_COMMENT;
63.139 + return i;
63.140 + }
63.141 + *tokenType = TK_MINUS;
63.142 + return 1;
63.143 + }
63.144 + case '(': {
63.145 + *tokenType = TK_LP;
63.146 + return 1;
63.147 + }
63.148 + case ')': {
63.149 + *tokenType = TK_RP;
63.150 + return 1;
63.151 + }
63.152 + case ';': {
63.153 + *tokenType = TK_SEMI;
63.154 + return 1;
63.155 + }
63.156 + case '+': {
63.157 + *tokenType = TK_PLUS;
63.158 + return 1;
63.159 + }
63.160 + case '*': {
63.161 + *tokenType = TK_STAR;
63.162 + return 1;
63.163 + }
63.164 + case '/': {
63.165 + if( z[1]!='*' || z[2]==0 ){
63.166 + *tokenType = TK_SLASH;
63.167 + return 1;
63.168 + }
63.169 + for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
63.170 + if( c ) i++;
63.171 + *tokenType = TK_COMMENT;
63.172 + return i;
63.173 + }
63.174 + case '%': {
63.175 + *tokenType = TK_REM;
63.176 + return 1;
63.177 + }
63.178 + case '=': {
63.179 + *tokenType = TK_EQ;
63.180 + return 1 + (z[1]=='=');
63.181 + }
63.182 + case '<': {
63.183 + if( (c=z[1])=='=' ){
63.184 + *tokenType = TK_LE;
63.185 + return 2;
63.186 + }else if( c=='>' ){
63.187 + *tokenType = TK_NE;
63.188 + return 2;
63.189 + }else if( c=='<' ){
63.190 + *tokenType = TK_LSHIFT;
63.191 + return 2;
63.192 + }else{
63.193 + *tokenType = TK_LT;
63.194 + return 1;
63.195 + }
63.196 + }
63.197 + case '>': {
63.198 + if( (c=z[1])=='=' ){
63.199 + *tokenType = TK_GE;
63.200 + return 2;
63.201 + }else if( c=='>' ){
63.202 + *tokenType = TK_RSHIFT;
63.203 + return 2;
63.204 + }else{
63.205 + *tokenType = TK_GT;
63.206 + return 1;
63.207 + }
63.208 + }
63.209 + case '!': {
63.210 + if( z[1]!='=' ){
63.211 + *tokenType = TK_ILLEGAL;
63.212 + return 2;
63.213 + }else{
63.214 + *tokenType = TK_NE;
63.215 + return 2;
63.216 + }
63.217 + }
63.218 + case '|': {
63.219 + if( z[1]!='|' ){
63.220 + *tokenType = TK_BITOR;
63.221 + return 1;
63.222 + }else{
63.223 + *tokenType = TK_CONCAT;
63.224 + return 2;
63.225 + }
63.226 + }
63.227 + case ',': {
63.228 + *tokenType = TK_COMMA;
63.229 + return 1;
63.230 + }
63.231 + case '&': {
63.232 + *tokenType = TK_BITAND;
63.233 + return 1;
63.234 + }
63.235 + case '~': {
63.236 + *tokenType = TK_BITNOT;
63.237 + return 1;
63.238 + }
63.239 + case '`':
63.240 + case '\'':
63.241 + case '"': {
63.242 + int delim = z[0];
63.243 + for(i=1; (c=z[i])!=0; i++){
63.244 + if( c==delim ){
63.245 + if( z[i+1]==delim ){
63.246 + i++;
63.247 + }else{
63.248 + break;
63.249 + }
63.250 + }
63.251 + }
63.252 + if( c ){
63.253 + *tokenType = TK_STRING;
63.254 + return i+1;
63.255 + }else{
63.256 + *tokenType = TK_ILLEGAL;
63.257 + return i;
63.258 + }
63.259 + }
63.260 + case '.': {
63.261 +#ifndef SQLITE_OMIT_FLOATING_POINT
63.262 + if( !isdigit(z[1]) )
63.263 +#endif
63.264 + {
63.265 + *tokenType = TK_DOT;
63.266 + return 1;
63.267 + }
63.268 + /* If the next character is a digit, this is a floating point
63.269 + ** number that begins with ".". Fall thru into the next case */
63.270 + }
63.271 + case '0': case '1': case '2': case '3': case '4':
63.272 + case '5': case '6': case '7': case '8': case '9': {
63.273 + *tokenType = TK_INTEGER;
63.274 + for(i=0; isdigit(z[i]); i++){}
63.275 +#ifndef SQLITE_OMIT_FLOATING_POINT
63.276 + if( z[i]=='.' ){
63.277 + i++;
63.278 + while( isdigit(z[i]) ){ i++; }
63.279 + *tokenType = TK_FLOAT;
63.280 + }
63.281 + if( (z[i]=='e' || z[i]=='E') &&
63.282 + ( isdigit(z[i+1])
63.283 + || ((z[i+1]=='+' || z[i+1]=='-') && isdigit(z[i+2]))
63.284 + )
63.285 + ){
63.286 + i += 2;
63.287 + while( isdigit(z[i]) ){ i++; }
63.288 + *tokenType = TK_FLOAT;
63.289 + }
63.290 +#endif
63.291 + while( IdChar(z[i]) ){
63.292 + *tokenType = TK_ILLEGAL;
63.293 + i++;
63.294 + }
63.295 + return i;
63.296 + }
63.297 + case '[': {
63.298 + for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
63.299 + *tokenType = TK_ID;
63.300 + return i;
63.301 + }
63.302 + case '?': {
63.303 + *tokenType = TK_VARIABLE;
63.304 + for(i=1; isdigit(z[i]); i++){}
63.305 + return i;
63.306 + }
63.307 + case '#': {
63.308 + for(i=1; isdigit(z[i]); i++){}
63.309 + if( i>1 ){
63.310 + /* Parameters of the form #NNN (where NNN is a number) are used
63.311 + ** internally by sqlite3NestedParse. */
63.312 + *tokenType = TK_REGISTER;
63.313 + return i;
63.314 + }
63.315 + /* Fall through into the next case if the '#' is not followed by
63.316 + ** a digit. Try to match #AAAA where AAAA is a parameter name. */
63.317 + }
63.318 +#ifndef SQLITE_OMIT_TCL_VARIABLE
63.319 + case '$':
63.320 +#endif
63.321 + case '@': /* For compatibility with MS SQL Server */
63.322 + case ':': {
63.323 + int n = 0;
63.324 + *tokenType = TK_VARIABLE;
63.325 + for(i=1; (c=z[i])!=0; i++){
63.326 + if( IdChar(c) ){
63.327 + n++;
63.328 +#ifndef SQLITE_OMIT_TCL_VARIABLE
63.329 + }else if( c=='(' && n>0 ){
63.330 + do{
63.331 + i++;
63.332 + }while( (c=z[i])!=0 && !isspace(c) && c!=')' );
63.333 + if( c==')' ){
63.334 + i++;
63.335 + }else{
63.336 + *tokenType = TK_ILLEGAL;
63.337 + }
63.338 + break;
63.339 + }else if( c==':' && z[i+1]==':' ){
63.340 + i++;
63.341 +#endif
63.342 + }else{
63.343 + break;
63.344 + }
63.345 + }
63.346 + if( n==0 ) *tokenType = TK_ILLEGAL;
63.347 + return i;
63.348 + }
63.349 +#ifndef SQLITE_OMIT_BLOB_LITERAL
63.350 + case 'x': case 'X': {
63.351 + if( (c=z[1])=='\'' || c=='"' ){
63.352 + int delim = c;
63.353 + *tokenType = TK_BLOB;
63.354 + for(i=2; (c=z[i])!=0; i++){
63.355 + if( c==delim ){
63.356 + if( i%2 ) *tokenType = TK_ILLEGAL;
63.357 + break;
63.358 + }
63.359 + if( !isxdigit(c) ){
63.360 + *tokenType = TK_ILLEGAL;
63.361 + return i;
63.362 + }
63.363 + }
63.364 + if( c ) i++;
63.365 + return i;
63.366 + }
63.367 + /* Otherwise fall through to the next case */
63.368 + }
63.369 +#endif
63.370 + default: {
63.371 + if( !IdChar(*z) ){
63.372 + break;
63.373 + }
63.374 + for(i=1; IdChar(z[i]); i++){}
63.375 + *tokenType = keywordCode((char*)z, i);
63.376 + return i;
63.377 + }
63.378 + }
63.379 + *tokenType = TK_ILLEGAL;
63.380 + return 1;
63.381 +}
63.382 +int sqlite3GetToken(const unsigned char *z, int *tokenType){
63.383 + return getToken(z, tokenType);
63.384 +}
63.385 +
63.386 +/*
63.387 +** The interface to the LEMON-generated parser
63.388 +*/
63.389 +void *sqlite3ParserAlloc(void*(*)(size_t));
63.390 +void sqlite3ParserFree(void*, void(*)(void*));
63.391 +void sqlite3Parser(void*, int, Token, Parse*);
63.392 +
63.393 +/*
63.394 +** Run the parser on the given SQL string. The parser structure is
63.395 +** passed in. An SQLITE_ status code is returned. If an error occurs
63.396 +** and pzErrMsg!=NULL then an error message might be written into
63.397 +** memory obtained from malloc() and *pzErrMsg made to point to that
63.398 +** error message. Or maybe not.
63.399 +*/
63.400 +int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
63.401 + int nErr = 0;
63.402 + int i;
63.403 + void *pEngine;
63.404 + int tokenType;
63.405 + int lastTokenParsed = -1;
63.406 + sqlite3 *db = pParse->db;
63.407 +
63.408 + if( db->activeVdbeCnt==0 ){
63.409 + db->u1.isInterrupted = 0;
63.410 + }
63.411 + pParse->rc = SQLITE_OK;
63.412 + i = 0;
63.413 + pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3MallocX);
63.414 + if( pEngine==0 ){
63.415 + return SQLITE_NOMEM;
63.416 + }
63.417 + assert( pParse->sLastToken.dyn==0 );
63.418 + assert( pParse->pNewTable==0 );
63.419 + assert( pParse->pNewTrigger==0 );
63.420 + assert( pParse->nVar==0 );
63.421 + assert( pParse->nVarExpr==0 );
63.422 + assert( pParse->nVarExprAlloc==0 );
63.423 + assert( pParse->apVarExpr==0 );
63.424 + pParse->zTail = pParse->zSql = zSql;
63.425 + while( !sqlite3MallocFailed() && zSql[i]!=0 ){
63.426 + assert( i>=0 );
63.427 + pParse->sLastToken.z = (u8*)&zSql[i];
63.428 + assert( pParse->sLastToken.dyn==0 );
63.429 + pParse->sLastToken.n = getToken((unsigned char*)&zSql[i],&tokenType);
63.430 + i += pParse->sLastToken.n;
63.431 + if( i>SQLITE_MAX_SQL_LENGTH ){
63.432 + pParse->rc = SQLITE_TOOBIG;
63.433 + break;
63.434 + }
63.435 + switch( tokenType ){
63.436 + case TK_SPACE:
63.437 + case TK_COMMENT: {
63.438 + if( db->u1.isInterrupted ){
63.439 + pParse->rc = SQLITE_INTERRUPT;
63.440 + sqlite3SetString(pzErrMsg, "interrupt", (char*)0);
63.441 + goto abort_parse;
63.442 + }
63.443 + break;
63.444 + }
63.445 + case TK_ILLEGAL: {
63.446 + if( pzErrMsg ){
63.447 + sqliteFree(*pzErrMsg);
63.448 + *pzErrMsg = sqlite3MPrintf("unrecognized token: \"%T\"",
63.449 + &pParse->sLastToken);
63.450 + }
63.451 + nErr++;
63.452 + goto abort_parse;
63.453 + }
63.454 + case TK_SEMI: {
63.455 + pParse->zTail = &zSql[i];
63.456 + /* Fall thru into the default case */
63.457 + }
63.458 + default: {
63.459 + sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
63.460 + lastTokenParsed = tokenType;
63.461 + if( pParse->rc!=SQLITE_OK ){
63.462 + goto abort_parse;
63.463 + }
63.464 + break;
63.465 + }
63.466 + }
63.467 + }
63.468 +abort_parse:
63.469 + if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
63.470 + if( lastTokenParsed!=TK_SEMI ){
63.471 + sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
63.472 + pParse->zTail = &zSql[i];
63.473 + }
63.474 + sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
63.475 + }
63.476 + sqlite3ParserFree(pEngine, sqlite3FreeX);
63.477 + if( sqlite3MallocFailed() ){
63.478 + pParse->rc = SQLITE_NOMEM;
63.479 + }
63.480 + if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
63.481 + sqlite3SetString(&pParse->zErrMsg, sqlite3ErrStr(pParse->rc), (char*)0);
63.482 + }
63.483 + if( pParse->zErrMsg ){
63.484 + if( pzErrMsg && *pzErrMsg==0 ){
63.485 + *pzErrMsg = pParse->zErrMsg;
63.486 + }else{
63.487 + sqliteFree(pParse->zErrMsg);
63.488 + }
63.489 + pParse->zErrMsg = 0;
63.490 + if( !nErr ) nErr++;
63.491 + }
63.492 + if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
63.493 + sqlite3VdbeDelete(pParse->pVdbe);
63.494 + pParse->pVdbe = 0;
63.495 + }
63.496 +#ifndef SQLITE_OMIT_SHARED_CACHE
63.497 + if( pParse->nested==0 ){
63.498 + sqliteFree(pParse->aTableLock);
63.499 + pParse->aTableLock = 0;
63.500 + pParse->nTableLock = 0;
63.501 + }
63.502 +#endif
63.503 +
63.504 + if( !IN_DECLARE_VTAB ){
63.505 + /* If the pParse->declareVtab flag is set, do not delete any table
63.506 + ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
63.507 + ** will take responsibility for freeing the Table structure.
63.508 + */
63.509 + sqlite3DeleteTable(pParse->pNewTable);
63.510 + }
63.511 +
63.512 + sqlite3DeleteTrigger(pParse->pNewTrigger);
63.513 + sqliteFree(pParse->apVarExpr);
63.514 + if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
63.515 + pParse->rc = SQLITE_ERROR;
63.516 + }
63.517 + return nErr;
63.518 +}
64.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
64.2 +++ b/extensions/sqlite/sqlite-source/trigger.c Sun Jul 29 01:15:31 2007 +0000
64.3 @@ -0,0 +1,828 @@
64.4 +/*
64.5 +**
64.6 +** The author disclaims copyright to this source code. In place of
64.7 +** a legal notice, here is a blessing:
64.8 +**
64.9 +** May you do good and not evil.
64.10 +** May you find forgiveness for yourself and forgive others.
64.11 +** May you share freely, never taking more than you give.
64.12 +**
64.13 +*************************************************************************
64.14 +*
64.15 +*/
64.16 +#include "sqliteInt.h"
64.17 +
64.18 +#ifndef SQLITE_OMIT_TRIGGER
64.19 +/*
64.20 +** Delete a linked list of TriggerStep structures.
64.21 +*/
64.22 +void sqlite3DeleteTriggerStep(TriggerStep *pTriggerStep){
64.23 + while( pTriggerStep ){
64.24 + TriggerStep * pTmp = pTriggerStep;
64.25 + pTriggerStep = pTriggerStep->pNext;
64.26 +
64.27 + if( pTmp->target.dyn ) sqliteFree((char*)pTmp->target.z);
64.28 + sqlite3ExprDelete(pTmp->pWhere);
64.29 + sqlite3ExprListDelete(pTmp->pExprList);
64.30 + sqlite3SelectDelete(pTmp->pSelect);
64.31 + sqlite3IdListDelete(pTmp->pIdList);
64.32 +
64.33 + sqliteFree(pTmp);
64.34 + }
64.35 +}
64.36 +
64.37 +/*
64.38 +** This is called by the parser when it sees a CREATE TRIGGER statement
64.39 +** up to the point of the BEGIN before the trigger actions. A Trigger
64.40 +** structure is generated based on the information available and stored
64.41 +** in pParse->pNewTrigger. After the trigger actions have been parsed, the
64.42 +** sqlite3FinishTrigger() function is called to complete the trigger
64.43 +** construction process.
64.44 +*/
64.45 +void sqlite3BeginTrigger(
64.46 + Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
64.47 + Token *pName1, /* The name of the trigger */
64.48 + Token *pName2, /* The name of the trigger */
64.49 + int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
64.50 + int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
64.51 + IdList *pColumns, /* column list if this is an UPDATE OF trigger */
64.52 + SrcList *pTableName,/* The name of the table/view the trigger applies to */
64.53 + Expr *pWhen, /* WHEN clause */
64.54 + int isTemp, /* True if the TEMPORARY keyword is present */
64.55 + int noErr /* Suppress errors if the trigger already exists */
64.56 +){
64.57 + Trigger *pTrigger = 0;
64.58 + Table *pTab;
64.59 + char *zName = 0; /* Name of the trigger */
64.60 + sqlite3 *db = pParse->db;
64.61 + int iDb; /* The database to store the trigger in */
64.62 + Token *pName; /* The unqualified db name */
64.63 + DbFixer sFix;
64.64 + int iTabDb;
64.65 +
64.66 + assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
64.67 + assert( pName2!=0 );
64.68 + if( isTemp ){
64.69 + /* If TEMP was specified, then the trigger name may not be qualified. */
64.70 + if( pName2->n>0 ){
64.71 + sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
64.72 + goto trigger_cleanup;
64.73 + }
64.74 + iDb = 1;
64.75 + pName = pName1;
64.76 + }else{
64.77 + /* Figure out the db that the the trigger will be created in */
64.78 + iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
64.79 + if( iDb<0 ){
64.80 + goto trigger_cleanup;
64.81 + }
64.82 + }
64.83 +
64.84 + /* If the trigger name was unqualified, and the table is a temp table,
64.85 + ** then set iDb to 1 to create the trigger in the temporary database.
64.86 + ** If sqlite3SrcListLookup() returns 0, indicating the table does not
64.87 + ** exist, the error is caught by the block below.
64.88 + */
64.89 + if( !pTableName || sqlite3MallocFailed() ){
64.90 + goto trigger_cleanup;
64.91 + }
64.92 + pTab = sqlite3SrcListLookup(pParse, pTableName);
64.93 + if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
64.94 + iDb = 1;
64.95 + }
64.96 +
64.97 + /* Ensure the table name matches database name and that the table exists */
64.98 + if( sqlite3MallocFailed() ) goto trigger_cleanup;
64.99 + assert( pTableName->nSrc==1 );
64.100 + if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
64.101 + sqlite3FixSrcList(&sFix, pTableName) ){
64.102 + goto trigger_cleanup;
64.103 + }
64.104 + pTab = sqlite3SrcListLookup(pParse, pTableName);
64.105 + if( !pTab ){
64.106 + /* The table does not exist. */
64.107 + goto trigger_cleanup;
64.108 + }
64.109 + if( IsVirtual(pTab) ){
64.110 + sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
64.111 + goto trigger_cleanup;
64.112 + }
64.113 +
64.114 + /* Check that the trigger name is not reserved and that no trigger of the
64.115 + ** specified name exists */
64.116 + zName = sqlite3NameFromToken(pName);
64.117 + if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
64.118 + goto trigger_cleanup;
64.119 + }
64.120 + if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash), zName,strlen(zName)) ){
64.121 + if( !noErr ){
64.122 + sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
64.123 + }
64.124 + goto trigger_cleanup;
64.125 + }
64.126 +
64.127 + /* Do not create a trigger on a system table */
64.128 + if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
64.129 + sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
64.130 + pParse->nErr++;
64.131 + goto trigger_cleanup;
64.132 + }
64.133 +
64.134 + /* INSTEAD of triggers are only for views and views only support INSTEAD
64.135 + ** of triggers.
64.136 + */
64.137 + if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
64.138 + sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
64.139 + (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
64.140 + goto trigger_cleanup;
64.141 + }
64.142 + if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
64.143 + sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
64.144 + " trigger on table: %S", pTableName, 0);
64.145 + goto trigger_cleanup;
64.146 + }
64.147 + iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
64.148 +
64.149 +#ifndef SQLITE_OMIT_AUTHORIZATION
64.150 + {
64.151 + int code = SQLITE_CREATE_TRIGGER;
64.152 + const char *zDb = db->aDb[iTabDb].zName;
64.153 + const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
64.154 + if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
64.155 + if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
64.156 + goto trigger_cleanup;
64.157 + }
64.158 + if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
64.159 + goto trigger_cleanup;
64.160 + }
64.161 + }
64.162 +#endif
64.163 +
64.164 + /* INSTEAD OF triggers can only appear on views and BEFORE triggers
64.165 + ** cannot appear on views. So we might as well translate every
64.166 + ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
64.167 + ** elsewhere.
64.168 + */
64.169 + if (tr_tm == TK_INSTEAD){
64.170 + tr_tm = TK_BEFORE;
64.171 + }
64.172 +
64.173 + /* Build the Trigger object */
64.174 + pTrigger = (Trigger*)sqliteMalloc(sizeof(Trigger));
64.175 + if( pTrigger==0 ) goto trigger_cleanup;
64.176 + pTrigger->name = zName;
64.177 + zName = 0;
64.178 + pTrigger->table = sqliteStrDup(pTableName->a[0].zName);
64.179 + pTrigger->pSchema = db->aDb[iDb].pSchema;
64.180 + pTrigger->pTabSchema = pTab->pSchema;
64.181 + pTrigger->op = op;
64.182 + pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
64.183 + pTrigger->pWhen = sqlite3ExprDup(pWhen);
64.184 + pTrigger->pColumns = sqlite3IdListDup(pColumns);
64.185 + sqlite3TokenCopy(&pTrigger->nameToken,pName);
64.186 + assert( pParse->pNewTrigger==0 );
64.187 + pParse->pNewTrigger = pTrigger;
64.188 +
64.189 +trigger_cleanup:
64.190 + sqliteFree(zName);
64.191 + sqlite3SrcListDelete(pTableName);
64.192 + sqlite3IdListDelete(pColumns);
64.193 + sqlite3ExprDelete(pWhen);
64.194 + if( !pParse->pNewTrigger ){
64.195 + sqlite3DeleteTrigger(pTrigger);
64.196 + }else{
64.197 + assert( pParse->pNewTrigger==pTrigger );
64.198 + }
64.199 +}
64.200 +
64.201 +/*
64.202 +** This routine is called after all of the trigger actions have been parsed
64.203 +** in order to complete the process of building the trigger.
64.204 +*/
64.205 +void sqlite3FinishTrigger(
64.206 + Parse *pParse, /* Parser context */
64.207 + TriggerStep *pStepList, /* The triggered program */
64.208 + Token *pAll /* Token that describes the complete CREATE TRIGGER */
64.209 +){
64.210 + Trigger *pTrig = 0; /* The trigger whose construction is finishing up */
64.211 + sqlite3 *db = pParse->db; /* The database */
64.212 + DbFixer sFix;
64.213 + int iDb; /* Database containing the trigger */
64.214 +
64.215 + pTrig = pParse->pNewTrigger;
64.216 + pParse->pNewTrigger = 0;
64.217 + if( pParse->nErr || !pTrig ) goto triggerfinish_cleanup;
64.218 + iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
64.219 + pTrig->step_list = pStepList;
64.220 + while( pStepList ){
64.221 + pStepList->pTrig = pTrig;
64.222 + pStepList = pStepList->pNext;
64.223 + }
64.224 + if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &pTrig->nameToken)
64.225 + && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
64.226 + goto triggerfinish_cleanup;
64.227 + }
64.228 +
64.229 + /* if we are not initializing, and this trigger is not on a TEMP table,
64.230 + ** build the sqlite_master entry
64.231 + */
64.232 + if( !db->init.busy ){
64.233 + static const VdbeOpList insertTrig[] = {
64.234 + { OP_NewRowid, 0, 0, 0 },
64.235 + { OP_String8, 0, 0, "trigger" },
64.236 + { OP_String8, 0, 0, 0 }, /* 2: trigger name */
64.237 + { OP_String8, 0, 0, 0 }, /* 3: table name */
64.238 + { OP_Integer, 0, 0, 0 },
64.239 + { OP_String8, 0, 0, "CREATE TRIGGER "},
64.240 + { OP_String8, 0, 0, 0 }, /* 6: SQL */
64.241 + { OP_Concat, 0, 0, 0 },
64.242 + { OP_MakeRecord, 5, 0, "aaada" },
64.243 + { OP_Insert, 0, 0, 0 },
64.244 + };
64.245 + int addr;
64.246 + Vdbe *v;
64.247 +
64.248 + /* Make an entry in the sqlite_master table */
64.249 + v = sqlite3GetVdbe(pParse);
64.250 + if( v==0 ) goto triggerfinish_cleanup;
64.251 + sqlite3BeginWriteOperation(pParse, 0, iDb);
64.252 + sqlite3OpenMasterTable(pParse, iDb);
64.253 + addr = sqlite3VdbeAddOpList(v, ArraySize(insertTrig), insertTrig);
64.254 + sqlite3VdbeChangeP3(v, addr+2, pTrig->name, 0);
64.255 + sqlite3VdbeChangeP3(v, addr+3, pTrig->table, 0);
64.256 + sqlite3VdbeChangeP3(v, addr+6, (char*)pAll->z, pAll->n);
64.257 + sqlite3ChangeCookie(db, v, iDb);
64.258 + sqlite3VdbeAddOp(v, OP_Close, 0, 0);
64.259 + sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
64.260 + sqlite3MPrintf("type='trigger' AND name='%q'", pTrig->name), P3_DYNAMIC);
64.261 + }
64.262 +
64.263 + if( db->init.busy ){
64.264 + int n;
64.265 + Table *pTab;
64.266 + Trigger *pDel;
64.267 + pDel = sqlite3HashInsert(&db->aDb[iDb].pSchema->trigHash,
64.268 + pTrig->name, strlen(pTrig->name), pTrig);
64.269 + if( pDel ){
64.270 + assert( sqlite3MallocFailed() && pDel==pTrig );
64.271 + goto triggerfinish_cleanup;
64.272 + }
64.273 + n = strlen(pTrig->table) + 1;
64.274 + pTab = sqlite3HashFind(&pTrig->pTabSchema->tblHash, pTrig->table, n);
64.275 + assert( pTab!=0 );
64.276 + pTrig->pNext = pTab->pTrigger;
64.277 + pTab->pTrigger = pTrig;
64.278 + pTrig = 0;
64.279 + }
64.280 +
64.281 +triggerfinish_cleanup:
64.282 + sqlite3DeleteTrigger(pTrig);
64.283 + assert( !pParse->pNewTrigger );
64.284 + sqlite3DeleteTriggerStep(pStepList);
64.285 +}
64.286 +
64.287 +/*
64.288 +** Make a copy of all components of the given trigger step. This has
64.289 +** the effect of copying all Expr.token.z values into memory obtained
64.290 +** from sqliteMalloc(). As initially created, the Expr.token.z values
64.291 +** all point to the input string that was fed to the parser. But that
64.292 +** string is ephemeral - it will go away as soon as the sqlite3_exec()
64.293 +** call that started the parser exits. This routine makes a persistent
64.294 +** copy of all the Expr.token.z strings so that the TriggerStep structure
64.295 +** will be valid even after the sqlite3_exec() call returns.
64.296 +*/
64.297 +static void sqlitePersistTriggerStep(TriggerStep *p){
64.298 + if( p->target.z ){
64.299 + p->target.z = (u8*)sqliteStrNDup((char*)p->target.z, p->target.n);
64.300 + p->target.dyn = 1;
64.301 + }
64.302 + if( p->pSelect ){
64.303 + Select *pNew = sqlite3SelectDup(p->pSelect);
64.304 + sqlite3SelectDelete(p->pSelect);
64.305 + p->pSelect = pNew;
64.306 + }
64.307 + if( p->pWhere ){
64.308 + Expr *pNew = sqlite3ExprDup(p->pWhere);
64.309 + sqlite3ExprDelete(p->pWhere);
64.310 + p->pWhere = pNew;
64.311 + }
64.312 + if( p->pExprList ){
64.313 + ExprList *pNew = sqlite3ExprListDup(p->pExprList);
64.314 + sqlite3ExprListDelete(p->pExprList);
64.315 + p->pExprList = pNew;
64.316 + }
64.317 + if( p->pIdList ){
64.318 + IdList *pNew = sqlite3IdListDup(p->pIdList);
64.319 + sqlite3IdListDelete(p->pIdList);
64.320 + p->pIdList = pNew;
64.321 + }
64.322 +}
64.323 +
64.324 +/*
64.325 +** Turn a SELECT statement (that the pSelect parameter points to) into
64.326 +** a trigger step. Return a pointer to a TriggerStep structure.
64.327 +**
64.328 +** The parser calls this routine when it finds a SELECT statement in
64.329 +** body of a TRIGGER.
64.330 +*/
64.331 +TriggerStep *sqlite3TriggerSelectStep(Select *pSelect){
64.332 + TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
64.333 + if( pTriggerStep==0 ) {
64.334 + sqlite3SelectDelete(pSelect);
64.335 + return 0;
64.336 + }
64.337 +
64.338 + pTriggerStep->op = TK_SELECT;
64.339 + pTriggerStep->pSelect = pSelect;
64.340 + pTriggerStep->orconf = OE_Default;
64.341 + sqlitePersistTriggerStep(pTriggerStep);
64.342 +
64.343 + return pTriggerStep;
64.344 +}
64.345 +
64.346 +/*
64.347 +** Build a trigger step out of an INSERT statement. Return a pointer
64.348 +** to the new trigger step.
64.349 +**
64.350 +** The parser calls this routine when it sees an INSERT inside the
64.351 +** body of a trigger.
64.352 +*/
64.353 +TriggerStep *sqlite3TriggerInsertStep(
64.354 + Token *pTableName, /* Name of the table into which we insert */
64.355 + IdList *pColumn, /* List of columns in pTableName to insert into */
64.356 + ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
64.357 + Select *pSelect, /* A SELECT statement that supplies values */
64.358 + int orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
64.359 +){
64.360 + TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
64.361 +
64.362 + assert(pEList == 0 || pSelect == 0);
64.363 + assert(pEList != 0 || pSelect != 0);
64.364 +
64.365 + if( pTriggerStep ){
64.366 + pTriggerStep->op = TK_INSERT;
64.367 + pTriggerStep->pSelect = pSelect;
64.368 + pTriggerStep->target = *pTableName;
64.369 + pTriggerStep->pIdList = pColumn;
64.370 + pTriggerStep->pExprList = pEList;
64.371 + pTriggerStep->orconf = orconf;
64.372 + sqlitePersistTriggerStep(pTriggerStep);
64.373 + }else{
64.374 + sqlite3IdListDelete(pColumn);
64.375 + sqlite3ExprListDelete(pEList);
64.376 + sqlite3SelectDup(pSelect);
64.377 + }
64.378 +
64.379 + return pTriggerStep;
64.380 +}
64.381 +
64.382 +/*
64.383 +** Construct a trigger step that implements an UPDATE statement and return
64.384 +** a pointer to that trigger step. The parser calls this routine when it
64.385 +** sees an UPDATE statement inside the body of a CREATE TRIGGER.
64.386 +*/
64.387 +TriggerStep *sqlite3TriggerUpdateStep(
64.388 + Token *pTableName, /* Name of the table to be updated */
64.389 + ExprList *pEList, /* The SET clause: list of column and new values */
64.390 + Expr *pWhere, /* The WHERE clause */
64.391 + int orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
64.392 +){
64.393 + TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
64.394 + if( pTriggerStep==0 ){
64.395 + sqlite3ExprListDelete(pEList);
64.396 + sqlite3ExprDelete(pWhere);
64.397 + return 0;
64.398 + }
64.399 +
64.400 + pTriggerStep->op = TK_UPDATE;
64.401 + pTriggerStep->target = *pTableName;
64.402 + pTriggerStep->pExprList = pEList;
64.403 + pTriggerStep->pWhere = pWhere;
64.404 + pTriggerStep->orconf = orconf;
64.405 + sqlitePersistTriggerStep(pTriggerStep);
64.406 +
64.407 + return pTriggerStep;
64.408 +}
64.409 +
64.410 +/*
64.411 +** Construct a trigger step that implements a DELETE statement and return
64.412 +** a pointer to that trigger step. The parser calls this routine when it
64.413 +** sees a DELETE statement inside the body of a CREATE TRIGGER.
64.414 +*/
64.415 +TriggerStep *sqlite3TriggerDeleteStep(Token *pTableName, Expr *pWhere){
64.416 + TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
64.417 + if( pTriggerStep==0 ){
64.418 + sqlite3ExprDelete(pWhere);
64.419 + return 0;
64.420 + }
64.421 +
64.422 + pTriggerStep->op = TK_DELETE;
64.423 + pTriggerStep->target = *pTableName;
64.424 + pTriggerStep->pWhere = pWhere;
64.425 + pTriggerStep->orconf = OE_Default;
64.426 + sqlitePersistTriggerStep(pTriggerStep);
64.427 +
64.428 + return pTriggerStep;
64.429 +}
64.430 +
64.431 +/*
64.432 +** Recursively delete a Trigger structure
64.433 +*/
64.434 +void sqlite3DeleteTrigger(Trigger *pTrigger){
64.435 + if( pTrigger==0 ) return;
64.436 + sqlite3DeleteTriggerStep(pTrigger->step_list);
64.437 + sqliteFree(pTrigger->name);
64.438 + sqliteFree(pTrigger->table);
64.439 + sqlite3ExprDelete(pTrigger->pWhen);
64.440 + sqlite3IdListDelete(pTrigger->pColumns);
64.441 + if( pTrigger->nameToken.dyn ) sqliteFree((char*)pTrigger->nameToken.z);
64.442 + sqliteFree(pTrigger);
64.443 +}
64.444 +
64.445 +/*
64.446 +** This function is called to drop a trigger from the database schema.
64.447 +**
64.448 +** This may be called directly from the parser and therefore identifies
64.449 +** the trigger by name. The sqlite3DropTriggerPtr() routine does the
64.450 +** same job as this routine except it takes a pointer to the trigger
64.451 +** instead of the trigger name.
64.452 +**/
64.453 +void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
64.454 + Trigger *pTrigger = 0;
64.455 + int i;
64.456 + const char *zDb;
64.457 + const char *zName;
64.458 + int nName;
64.459 + sqlite3 *db = pParse->db;
64.460 +
64.461 + if( sqlite3MallocFailed() ) goto drop_trigger_cleanup;
64.462 + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
64.463 + goto drop_trigger_cleanup;
64.464 + }
64.465 +
64.466 + assert( pName->nSrc==1 );
64.467 + zDb = pName->a[0].zDatabase;
64.468 + zName = pName->a[0].zName;
64.469 + nName = strlen(zName);
64.470 + for(i=OMIT_TEMPDB; i<db->nDb; i++){
64.471 + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
64.472 + if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
64.473 + pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
64.474 + if( pTrigger ) break;
64.475 + }
64.476 + if( !pTrigger ){
64.477 + if( !noErr ){
64.478 + sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
64.479 + }
64.480 + goto drop_trigger_cleanup;
64.481 + }
64.482 + sqlite3DropTriggerPtr(pParse, pTrigger);
64.483 +
64.484 +drop_trigger_cleanup:
64.485 + sqlite3SrcListDelete(pName);
64.486 +}
64.487 +
64.488 +/*
64.489 +** Return a pointer to the Table structure for the table that a trigger
64.490 +** is set on.
64.491 +*/
64.492 +static Table *tableOfTrigger(Trigger *pTrigger){
64.493 + int n = strlen(pTrigger->table) + 1;
64.494 + return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
64.495 +}
64.496 +
64.497 +
64.498 +/*
64.499 +** Drop a trigger given a pointer to that trigger.
64.500 +*/
64.501 +void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
64.502 + Table *pTable;
64.503 + Vdbe *v;
64.504 + sqlite3 *db = pParse->db;
64.505 + int iDb;
64.506 +
64.507 + iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
64.508 + assert( iDb>=0 && iDb<db->nDb );
64.509 + pTable = tableOfTrigger(pTrigger);
64.510 + assert( pTable );
64.511 + assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
64.512 +#ifndef SQLITE_OMIT_AUTHORIZATION
64.513 + {
64.514 + int code = SQLITE_DROP_TRIGGER;
64.515 + const char *zDb = db->aDb[iDb].zName;
64.516 + const char *zTab = SCHEMA_TABLE(iDb);
64.517 + if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
64.518 + if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
64.519 + sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
64.520 + return;
64.521 + }
64.522 + }
64.523 +#endif
64.524 +
64.525 + /* Generate code to destroy the database record of the trigger.
64.526 + */
64.527 + assert( pTable!=0 );
64.528 + if( (v = sqlite3GetVdbe(pParse))!=0 ){
64.529 + int base;
64.530 + static const VdbeOpList dropTrigger[] = {
64.531 + { OP_Rewind, 0, ADDR(9), 0},
64.532 + { OP_String8, 0, 0, 0}, /* 1 */
64.533 + { OP_Column, 0, 1, 0},
64.534 + { OP_Ne, 0, ADDR(8), 0},
64.535 + { OP_String8, 0, 0, "trigger"},
64.536 + { OP_Column, 0, 0, 0},
64.537 + { OP_Ne, 0, ADDR(8), 0},
64.538 + { OP_Delete, 0, 0, 0},
64.539 + { OP_Next, 0, ADDR(1), 0}, /* 8 */
64.540 + };
64.541 +
64.542 + sqlite3BeginWriteOperation(pParse, 0, iDb);
64.543 + sqlite3OpenMasterTable(pParse, iDb);
64.544 + base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
64.545 + sqlite3VdbeChangeP3(v, base+1, pTrigger->name, 0);
64.546 + sqlite3ChangeCookie(db, v, iDb);
64.547 + sqlite3VdbeAddOp(v, OP_Close, 0, 0);
64.548 + sqlite3VdbeOp3(v, OP_DropTrigger, iDb, 0, pTrigger->name, 0);
64.549 + }
64.550 +}
64.551 +
64.552 +/*
64.553 +** Remove a trigger from the hash tables of the sqlite* pointer.
64.554 +*/
64.555 +void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
64.556 + Trigger *pTrigger;
64.557 + int nName = strlen(zName);
64.558 + pTrigger = sqlite3HashInsert(&(db->aDb[iDb].pSchema->trigHash),
64.559 + zName, nName, 0);
64.560 + if( pTrigger ){
64.561 + Table *pTable = tableOfTrigger(pTrigger);
64.562 + assert( pTable!=0 );
64.563 + if( pTable->pTrigger == pTrigger ){
64.564 + pTable->pTrigger = pTrigger->pNext;
64.565 + }else{
64.566 + Trigger *cc = pTable->pTrigger;
64.567 + while( cc ){
64.568 + if( cc->pNext == pTrigger ){
64.569 + cc->pNext = cc->pNext->pNext;
64.570 + break;
64.571 + }
64.572 + cc = cc->pNext;
64.573 + }
64.574 + assert(cc);
64.575 + }
64.576 + sqlite3DeleteTrigger(pTrigger);
64.577 + db->flags |= SQLITE_InternChanges;
64.578 + }
64.579 +}
64.580 +
64.581 +/*
64.582 +** pEList is the SET clause of an UPDATE statement. Each entry
64.583 +** in pEList is of the format <id>=<expr>. If any of the entries
64.584 +** in pEList have an <id> which matches an identifier in pIdList,
64.585 +** then return TRUE. If pIdList==NULL, then it is considered a
64.586 +** wildcard that matches anything. Likewise if pEList==NULL then
64.587 +** it matches anything so always return true. Return false only
64.588 +** if there is no match.
64.589 +*/
64.590 +static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
64.591 + int e;
64.592 + if( !pIdList || !pEList ) return 1;
64.593 + for(e=0; e<pEList->nExpr; e++){
64.594 + if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
64.595 + }
64.596 + return 0;
64.597 +}
64.598 +
64.599 +/*
64.600 +** Return a bit vector to indicate what kind of triggers exist for operation
64.601 +** "op" on table pTab. If pChanges is not NULL then it is a list of columns
64.602 +** that are being updated. Triggers only match if the ON clause of the
64.603 +** trigger definition overlaps the set of columns being updated.
64.604 +**
64.605 +** The returned bit vector is some combination of TRIGGER_BEFORE and
64.606 +** TRIGGER_AFTER.
64.607 +*/
64.608 +int sqlite3TriggersExist(
64.609 + Parse *pParse, /* Used to check for recursive triggers */
64.610 + Table *pTab, /* The table the contains the triggers */
64.611 + int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
64.612 + ExprList *pChanges /* Columns that change in an UPDATE statement */
64.613 +){
64.614 + Trigger *pTrigger;
64.615 + int mask = 0;
64.616 +
64.617 + pTrigger = IsVirtual(pTab) ? 0 : pTab->pTrigger;
64.618 + while( pTrigger ){
64.619 + if( pTrigger->op==op && checkColumnOverLap(pTrigger->pColumns, pChanges) ){
64.620 + mask |= pTrigger->tr_tm;
64.621 + }
64.622 + pTrigger = pTrigger->pNext;
64.623 + }
64.624 + return mask;
64.625 +}
64.626 +
64.627 +/*
64.628 +** Convert the pStep->target token into a SrcList and return a pointer
64.629 +** to that SrcList.
64.630 +**
64.631 +** This routine adds a specific database name, if needed, to the target when
64.632 +** forming the SrcList. This prevents a trigger in one database from
64.633 +** referring to a target in another database. An exception is when the
64.634 +** trigger is in TEMP in which case it can refer to any other database it
64.635 +** wants.
64.636 +*/
64.637 +static SrcList *targetSrcList(
64.638 + Parse *pParse, /* The parsing context */
64.639 + TriggerStep *pStep /* The trigger containing the target token */
64.640 +){
64.641 + Token sDb; /* Dummy database name token */
64.642 + int iDb; /* Index of the database to use */
64.643 + SrcList *pSrc; /* SrcList to be returned */
64.644 +
64.645 + iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
64.646 + if( iDb==0 || iDb>=2 ){
64.647 + assert( iDb<pParse->db->nDb );
64.648 + sDb.z = (u8*)pParse->db->aDb[iDb].zName;
64.649 + sDb.n = strlen((char*)sDb.z);
64.650 + pSrc = sqlite3SrcListAppend(0, &sDb, &pStep->target);
64.651 + } else {
64.652 + pSrc = sqlite3SrcListAppend(0, &pStep->target, 0);
64.653 + }
64.654 + return pSrc;
64.655 +}
64.656 +
64.657 +/*
64.658 +** Generate VDBE code for zero or more statements inside the body of a
64.659 +** trigger.
64.660 +*/
64.661 +static int codeTriggerProgram(
64.662 + Parse *pParse, /* The parser context */
64.663 + TriggerStep *pStepList, /* List of statements inside the trigger body */
64.664 + int orconfin /* Conflict algorithm. (OE_Abort, etc) */
64.665 +){
64.666 + TriggerStep * pTriggerStep = pStepList;
64.667 + int orconf;
64.668 + Vdbe *v = pParse->pVdbe;
64.669 +
64.670 + assert( pTriggerStep!=0 );
64.671 + assert( v!=0 );
64.672 + sqlite3VdbeAddOp(v, OP_ContextPush, 0, 0);
64.673 + VdbeComment((v, "# begin trigger %s", pStepList->pTrig->name));
64.674 + while( pTriggerStep ){
64.675 + orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
64.676 + pParse->trigStack->orconf = orconf;
64.677 + switch( pTriggerStep->op ){
64.678 + case TK_SELECT: {
64.679 + Select *ss = sqlite3SelectDup(pTriggerStep->pSelect);
64.680 + if( ss ){
64.681 + sqlite3SelectResolve(pParse, ss, 0);
64.682 + sqlite3Select(pParse, ss, SRT_Discard, 0, 0, 0, 0, 0);
64.683 + sqlite3SelectDelete(ss);
64.684 + }
64.685 + break;
64.686 + }
64.687 + case TK_UPDATE: {
64.688 + SrcList *pSrc;
64.689 + pSrc = targetSrcList(pParse, pTriggerStep);
64.690 + sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0);
64.691 + sqlite3Update(pParse, pSrc,
64.692 + sqlite3ExprListDup(pTriggerStep->pExprList),
64.693 + sqlite3ExprDup(pTriggerStep->pWhere), orconf);
64.694 + sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0);
64.695 + break;
64.696 + }
64.697 + case TK_INSERT: {
64.698 + SrcList *pSrc;
64.699 + pSrc = targetSrcList(pParse, pTriggerStep);
64.700 + sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0);
64.701 + sqlite3Insert(pParse, pSrc,
64.702 + sqlite3ExprListDup(pTriggerStep->pExprList),
64.703 + sqlite3SelectDup(pTriggerStep->pSelect),
64.704 + sqlite3IdListDup(pTriggerStep->pIdList), orconf);
64.705 + sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0);
64.706 + break;
64.707 + }
64.708 + case TK_DELETE: {
64.709 + SrcList *pSrc;
64.710 + sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0);
64.711 + pSrc = targetSrcList(pParse, pTriggerStep);
64.712 + sqlite3DeleteFrom(pParse, pSrc, sqlite3ExprDup(pTriggerStep->pWhere));
64.713 + sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0);
64.714 + break;
64.715 + }
64.716 + default:
64.717 + assert(0);
64.718 + }
64.719 + pTriggerStep = pTriggerStep->pNext;
64.720 + }
64.721 + sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
64.722 + VdbeComment((v, "# end trigger %s", pStepList->pTrig->name));
64.723 +
64.724 + return 0;
64.725 +}
64.726 +
64.727 +/*
64.728 +** This is called to code FOR EACH ROW triggers.
64.729 +**
64.730 +** When the code that this function generates is executed, the following
64.731 +** must be true:
64.732 +**
64.733 +** 1. No cursors may be open in the main database. (But newIdx and oldIdx
64.734 +** can be indices of cursors in temporary tables. See below.)
64.735 +**
64.736 +** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
64.737 +** a temporary vdbe cursor (index newIdx) must be open and pointing at
64.738 +** a row containing values to be substituted for new.* expressions in the
64.739 +** trigger program(s).
64.740 +**
64.741 +** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
64.742 +** a temporary vdbe cursor (index oldIdx) must be open and pointing at
64.743 +** a row containing values to be substituted for old.* expressions in the
64.744 +** trigger program(s).
64.745 +**
64.746 +*/
64.747 +int sqlite3CodeRowTrigger(
64.748 + Parse *pParse, /* Parse context */
64.749 + int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
64.750 + ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
64.751 + int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
64.752 + Table *pTab, /* The table to code triggers from */
64.753 + int newIdx, /* The indice of the "new" row to access */
64.754 + int oldIdx, /* The indice of the "old" row to access */
64.755 + int orconf, /* ON CONFLICT policy */
64.756 + int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
64.757 +){
64.758 + Trigger *p;
64.759 + TriggerStack trigStackEntry;
64.760 +
64.761 + assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
64.762 + assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
64.763 +
64.764 + assert(newIdx != -1 || oldIdx != -1);
64.765 +
64.766 + for(p=pTab->pTrigger; p; p=p->pNext){
64.767 + int fire_this = 0;
64.768 +
64.769 + /* Determine whether we should code this trigger */
64.770 + if(
64.771 + p->op==op &&
64.772 + p->tr_tm==tr_tm &&
64.773 + (p->pSchema==p->pTabSchema || p->pSchema==pParse->db->aDb[1].pSchema) &&
64.774 + (op!=TK_UPDATE||!p->pColumns||checkColumnOverLap(p->pColumns,pChanges))
64.775 + ){
64.776 + TriggerStack *pS; /* Pointer to trigger-stack entry */
64.777 + for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
64.778 + if( !pS ){
64.779 + fire_this = 1;
64.780 + }
64.781 +#if 0 /* Give no warning for recursive triggers. Just do not do them */
64.782 + else{
64.783 + sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
64.784 + p->name);
64.785 + return SQLITE_ERROR;
64.786 + }
64.787 +#endif
64.788 + }
64.789 +
64.790 + if( fire_this ){
64.791 + int endTrigger;
64.792 + Expr * whenExpr;
64.793 + AuthContext sContext;
64.794 + NameContext sNC;
64.795 +
64.796 + memset(&sNC, 0, sizeof(sNC));
64.797 + sNC.pParse = pParse;
64.798 +
64.799 + /* Push an entry on to the trigger stack */
64.800 + trigStackEntry.pTrigger = p;
64.801 + trigStackEntry.newIdx = newIdx;
64.802 + trigStackEntry.oldIdx = oldIdx;
64.803 + trigStackEntry.pTab = pTab;
64.804 + trigStackEntry.pNext = pParse->trigStack;
64.805 + trigStackEntry.ignoreJump = ignoreJump;
64.806 + pParse->trigStack = &trigStackEntry;
64.807 + sqlite3AuthContextPush(pParse, &sContext, p->name);
64.808 +
64.809 + /* code the WHEN clause */
64.810 + endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
64.811 + whenExpr = sqlite3ExprDup(p->pWhen);
64.812 + if( sqlite3ExprResolveNames(&sNC, whenExpr) ){
64.813 + pParse->trigStack = trigStackEntry.pNext;
64.814 + sqlite3ExprDelete(whenExpr);
64.815 + return 1;
64.816 + }
64.817 + sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, 1);
64.818 + sqlite3ExprDelete(whenExpr);
64.819 +
64.820 + codeTriggerProgram(pParse, p->step_list, orconf);
64.821 +
64.822 + /* Pop the entry off the trigger stack */
64.823 + pParse->trigStack = trigStackEntry.pNext;
64.824 + sqlite3AuthContextPop(&sContext);
64.825 +
64.826 + sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
64.827 + }
64.828 + }
64.829 + return 0;
64.830 +}
64.831 +#endif /* !defined(SQLITE_OMIT_TRIGGER) */
65.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
65.2 +++ b/extensions/sqlite/sqlite-source/update.c Sun Jul 29 01:15:31 2007 +0000
65.3 @@ -0,0 +1,627 @@
65.4 +/*
65.5 +** 2001 September 15
65.6 +**
65.7 +** The author disclaims copyright to this source code. In place of
65.8 +** a legal notice, here is a blessing:
65.9 +**
65.10 +** May you do good and not evil.
65.11 +** May you find forgiveness for yourself and forgive others.
65.12 +** May you share freely, never taking more than you give.
65.13 +**
65.14 +*************************************************************************
65.15 +** This file contains C code routines that are called by the parser
65.16 +** to handle UPDATE statements.
65.17 +**
65.18 +** $Id$
65.19 +*/
65.20 +#include "sqliteInt.h"
65.21 +
65.22 +#ifndef SQLITE_OMIT_VIRTUALTABLE
65.23 +/* Forward declaration */
65.24 +static void updateVirtualTable(
65.25 + Parse *pParse, /* The parsing context */
65.26 + SrcList *pSrc, /* The virtual table to be modified */
65.27 + Table *pTab, /* The virtual table */
65.28 + ExprList *pChanges, /* The columns to change in the UPDATE statement */
65.29 + Expr *pRowidExpr, /* Expression used to recompute the rowid */
65.30 + int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
65.31 + Expr *pWhere /* WHERE clause of the UPDATE statement */
65.32 +);
65.33 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
65.34 +
65.35 +/*
65.36 +** The most recently coded instruction was an OP_Column to retrieve the
65.37 +** i-th column of table pTab. This routine sets the P3 parameter of the
65.38 +** OP_Column to the default value, if any.
65.39 +**
65.40 +** The default value of a column is specified by a DEFAULT clause in the
65.41 +** column definition. This was either supplied by the user when the table
65.42 +** was created, or added later to the table definition by an ALTER TABLE
65.43 +** command. If the latter, then the row-records in the table btree on disk
65.44 +** may not contain a value for the column and the default value, taken
65.45 +** from the P3 parameter of the OP_Column instruction, is returned instead.
65.46 +** If the former, then all row-records are guaranteed to include a value
65.47 +** for the column and the P3 value is not required.
65.48 +**
65.49 +** Column definitions created by an ALTER TABLE command may only have
65.50 +** literal default values specified: a number, null or a string. (If a more
65.51 +** complicated default expression value was provided, it is evaluated
65.52 +** when the ALTER TABLE is executed and one of the literal values written
65.53 +** into the sqlite_master table.)
65.54 +**
65.55 +** Therefore, the P3 parameter is only required if the default value for
65.56 +** the column is a literal number, string or null. The sqlite3ValueFromExpr()
65.57 +** function is capable of transforming these types of expressions into
65.58 +** sqlite3_value objects.
65.59 +*/
65.60 +void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
65.61 + if( pTab && !pTab->pSelect ){
65.62 + sqlite3_value *pValue;
65.63 + u8 enc = ENC(sqlite3VdbeDb(v));
65.64 + Column *pCol = &pTab->aCol[i];
65.65 + assert( i<pTab->nCol );
65.66 + sqlite3ValueFromExpr(pCol->pDflt, enc, pCol->affinity, &pValue);
65.67 + if( pValue ){
65.68 + sqlite3VdbeChangeP3(v, -1, (const char *)pValue, P3_MEM);
65.69 + }else{
65.70 + VdbeComment((v, "# %s.%s", pTab->zName, pCol->zName));
65.71 + }
65.72 + }
65.73 +}
65.74 +
65.75 +/*
65.76 +** Process an UPDATE statement.
65.77 +**
65.78 +** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
65.79 +** \_______/ \________/ \______/ \________________/
65.80 +* onError pTabList pChanges pWhere
65.81 +*/
65.82 +void sqlite3Update(
65.83 + Parse *pParse, /* The parser context */
65.84 + SrcList *pTabList, /* The table in which we should change things */
65.85 + ExprList *pChanges, /* Things to be changed */
65.86 + Expr *pWhere, /* The WHERE clause. May be null */
65.87 + int onError /* How to handle constraint errors */
65.88 +){
65.89 + int i, j; /* Loop counters */
65.90 + Table *pTab; /* The table to be updated */
65.91 + int addr = 0; /* VDBE instruction address of the start of the loop */
65.92 + WhereInfo *pWInfo; /* Information about the WHERE clause */
65.93 + Vdbe *v; /* The virtual database engine */
65.94 + Index *pIdx; /* For looping over indices */
65.95 + int nIdx; /* Number of indices that need updating */
65.96 + int nIdxTotal; /* Total number of indices */
65.97 + int iCur; /* VDBE Cursor number of pTab */
65.98 + sqlite3 *db; /* The database structure */
65.99 + Index **apIdx = 0; /* An array of indices that need updating too */
65.100 + char *aIdxUsed = 0; /* aIdxUsed[i]==1 if the i-th index is used */
65.101 + int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
65.102 + ** an expression for the i-th column of the table.
65.103 + ** aXRef[i]==-1 if the i-th column is not changed. */
65.104 + int chngRowid; /* True if the record number is being changed */
65.105 + Expr *pRowidExpr = 0; /* Expression defining the new record number */
65.106 + int openAll = 0; /* True if all indices need to be opened */
65.107 + AuthContext sContext; /* The authorization context */
65.108 + NameContext sNC; /* The name-context to resolve expressions in */
65.109 + int iDb; /* Database containing the table being updated */
65.110 + int memCnt = 0; /* Memory cell used for counting rows changed */
65.111 +
65.112 +#ifndef SQLITE_OMIT_TRIGGER
65.113 + int isView; /* Trying to update a view */
65.114 + int triggers_exist = 0; /* True if any row triggers exist */
65.115 +#endif
65.116 +
65.117 + int newIdx = -1; /* index of trigger "new" temp table */
65.118 + int oldIdx = -1; /* index of trigger "old" temp table */
65.119 +
65.120 + sContext.pParse = 0;
65.121 + if( pParse->nErr || sqlite3MallocFailed() ){
65.122 + goto update_cleanup;
65.123 + }
65.124 + db = pParse->db;
65.125 + assert( pTabList->nSrc==1 );
65.126 +
65.127 + /* Locate the table which we want to update.
65.128 + */
65.129 + pTab = sqlite3SrcListLookup(pParse, pTabList);
65.130 + if( pTab==0 ) goto update_cleanup;
65.131 + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
65.132 +
65.133 + /* Figure out if we have any triggers and if the table being
65.134 + ** updated is a view
65.135 + */
65.136 +#ifndef SQLITE_OMIT_TRIGGER
65.137 + triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges);
65.138 + isView = pTab->pSelect!=0;
65.139 +#else
65.140 +# define triggers_exist 0
65.141 +# define isView 0
65.142 +#endif
65.143 +#ifdef SQLITE_OMIT_VIEW
65.144 +# undef isView
65.145 +# define isView 0
65.146 +#endif
65.147 +
65.148 + if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
65.149 + goto update_cleanup;
65.150 + }
65.151 + if( sqlite3ViewGetColumnNames(pParse, pTab) ){
65.152 + goto update_cleanup;
65.153 + }
65.154 + aXRef = sqliteMallocRaw( sizeof(int) * pTab->nCol );
65.155 + if( aXRef==0 ) goto update_cleanup;
65.156 + for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
65.157 +
65.158 + /* If there are FOR EACH ROW triggers, allocate cursors for the
65.159 + ** special OLD and NEW tables
65.160 + */
65.161 + if( triggers_exist ){
65.162 + newIdx = pParse->nTab++;
65.163 + oldIdx = pParse->nTab++;
65.164 + }
65.165 +
65.166 + /* Allocate a cursors for the main database table and for all indices.
65.167 + ** The index cursors might not be used, but if they are used they
65.168 + ** need to occur right after the database cursor. So go ahead and
65.169 + ** allocate enough space, just in case.
65.170 + */
65.171 + pTabList->a[0].iCursor = iCur = pParse->nTab++;
65.172 + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
65.173 + pParse->nTab++;
65.174 + }
65.175 +
65.176 + /* Initialize the name-context */
65.177 + memset(&sNC, 0, sizeof(sNC));
65.178 + sNC.pParse = pParse;
65.179 + sNC.pSrcList = pTabList;
65.180 +
65.181 + /* Resolve the column names in all the expressions of the
65.182 + ** of the UPDATE statement. Also find the column index
65.183 + ** for each column to be updated in the pChanges array. For each
65.184 + ** column to be updated, make sure we have authorization to change
65.185 + ** that column.
65.186 + */
65.187 + chngRowid = 0;
65.188 + for(i=0; i<pChanges->nExpr; i++){
65.189 + if( sqlite3ExprResolveNames(&sNC, pChanges->a[i].pExpr) ){
65.190 + goto update_cleanup;
65.191 + }
65.192 + for(j=0; j<pTab->nCol; j++){
65.193 + if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
65.194 + if( j==pTab->iPKey ){
65.195 + chngRowid = 1;
65.196 + pRowidExpr = pChanges->a[i].pExpr;
65.197 + }
65.198 + aXRef[j] = i;
65.199 + break;
65.200 + }
65.201 + }
65.202 + if( j>=pTab->nCol ){
65.203 + if( sqlite3IsRowid(pChanges->a[i].zName) ){
65.204 + chngRowid = 1;
65.205 + pRowidExpr = pChanges->a[i].pExpr;
65.206 + }else{
65.207 + sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
65.208 + goto update_cleanup;
65.209 + }
65.210 + }
65.211 +#ifndef SQLITE_OMIT_AUTHORIZATION
65.212 + {
65.213 + int rc;
65.214 + rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
65.215 + pTab->aCol[j].zName, db->aDb[iDb].zName);
65.216 + if( rc==SQLITE_DENY ){
65.217 + goto update_cleanup;
65.218 + }else if( rc==SQLITE_IGNORE ){
65.219 + aXRef[j] = -1;
65.220 + }
65.221 + }
65.222 +#endif
65.223 + }
65.224 +
65.225 + /* Allocate memory for the array apIdx[] and fill it with pointers to every
65.226 + ** index that needs to be updated. Indices only need updating if their
65.227 + ** key includes one of the columns named in pChanges or if the record
65.228 + ** number of the original table entry is changing.
65.229 + */
65.230 + for(nIdx=nIdxTotal=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdxTotal++){
65.231 + if( chngRowid ){
65.232 + i = 0;
65.233 + }else {
65.234 + for(i=0; i<pIdx->nColumn; i++){
65.235 + if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
65.236 + }
65.237 + }
65.238 + if( i<pIdx->nColumn ) nIdx++;
65.239 + }
65.240 + if( nIdxTotal>0 ){
65.241 + apIdx = sqliteMallocRaw( sizeof(Index*) * nIdx + nIdxTotal );
65.242 + if( apIdx==0 ) goto update_cleanup;
65.243 + aIdxUsed = (char*)&apIdx[nIdx];
65.244 + }
65.245 + for(nIdx=j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
65.246 + if( chngRowid ){
65.247 + i = 0;
65.248 + }else{
65.249 + for(i=0; i<pIdx->nColumn; i++){
65.250 + if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
65.251 + }
65.252 + }
65.253 + if( i<pIdx->nColumn ){
65.254 + apIdx[nIdx++] = pIdx;
65.255 + aIdxUsed[j] = 1;
65.256 + }else{
65.257 + aIdxUsed[j] = 0;
65.258 + }
65.259 + }
65.260 +
65.261 + /* Begin generating code.
65.262 + */
65.263 + v = sqlite3GetVdbe(pParse);
65.264 + if( v==0 ) goto update_cleanup;
65.265 + if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
65.266 + sqlite3BeginWriteOperation(pParse, 1, iDb);
65.267 +
65.268 +#ifndef SQLITE_OMIT_VIRTUALTABLE
65.269 + /* Virtual tables must be handled separately */
65.270 + if( IsVirtual(pTab) ){
65.271 + updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
65.272 + pWhere);
65.273 + pWhere = 0;
65.274 + pTabList = 0;
65.275 + goto update_cleanup;
65.276 + }
65.277 +#endif
65.278 +
65.279 + /* Resolve the column names in all the expressions in the
65.280 + ** WHERE clause.
65.281 + */
65.282 + if( sqlite3ExprResolveNames(&sNC, pWhere) ){
65.283 + goto update_cleanup;
65.284 + }
65.285 +
65.286 + /* Start the view context
65.287 + */
65.288 + if( isView ){
65.289 + sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
65.290 + }
65.291 +
65.292 + /* If we are trying to update a view, realize that view into
65.293 + ** a ephemeral table.
65.294 + */
65.295 + if( isView ){
65.296 + Select *pView;
65.297 + pView = sqlite3SelectDup(pTab->pSelect);
65.298 + sqlite3Select(pParse, pView, SRT_EphemTab, iCur, 0, 0, 0, 0);
65.299 + sqlite3SelectDelete(pView);
65.300 + }
65.301 +
65.302 + /* Begin the database scan
65.303 + */
65.304 + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
65.305 + if( pWInfo==0 ) goto update_cleanup;
65.306 +
65.307 + /* Remember the rowid of every item to be updated.
65.308 + */
65.309 + sqlite3VdbeAddOp(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, 0);
65.310 + sqlite3VdbeAddOp(v, OP_FifoWrite, 0, 0);
65.311 +
65.312 + /* End the database scan loop.
65.313 + */
65.314 + sqlite3WhereEnd(pWInfo);
65.315 +
65.316 + /* Initialize the count of updated rows
65.317 + */
65.318 + if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
65.319 + memCnt = pParse->nMem++;
65.320 + sqlite3VdbeAddOp(v, OP_MemInt, 0, memCnt);
65.321 + }
65.322 +
65.323 + if( triggers_exist ){
65.324 + /* Create pseudo-tables for NEW and OLD
65.325 + */
65.326 + sqlite3VdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
65.327 + sqlite3VdbeAddOp(v, OP_SetNumColumns, oldIdx, pTab->nCol);
65.328 + sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
65.329 + sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
65.330 +
65.331 + /* The top of the update loop for when there are triggers.
65.332 + */
65.333 + addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, 0);
65.334 +
65.335 + if( !isView ){
65.336 + sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
65.337 + sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
65.338 + /* Open a cursor and make it point to the record that is
65.339 + ** being updated.
65.340 + */
65.341 + sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
65.342 + }
65.343 + sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
65.344 +
65.345 + /* Generate the OLD table
65.346 + */
65.347 + sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
65.348 + sqlite3VdbeAddOp(v, OP_RowData, iCur, 0);
65.349 + sqlite3VdbeAddOp(v, OP_Insert, oldIdx, 0);
65.350 +
65.351 + /* Generate the NEW table
65.352 + */
65.353 + if( chngRowid ){
65.354 + sqlite3ExprCodeAndCache(pParse, pRowidExpr);
65.355 + }else{
65.356 + sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
65.357 + }
65.358 + for(i=0; i<pTab->nCol; i++){
65.359 + if( i==pTab->iPKey ){
65.360 + sqlite3VdbeAddOp(v, OP_Null, 0, 0);
65.361 + continue;
65.362 + }
65.363 + j = aXRef[i];
65.364 + if( j<0 ){
65.365 + sqlite3VdbeAddOp(v, OP_Column, iCur, i);
65.366 + sqlite3ColumnDefault(v, pTab, i);
65.367 + }else{
65.368 + sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr);
65.369 + }
65.370 + }
65.371 + sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
65.372 + if( !isView ){
65.373 + sqlite3TableAffinityStr(v, pTab);
65.374 + }
65.375 + if( pParse->nErr ) goto update_cleanup;
65.376 + sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
65.377 + if( !isView ){
65.378 + sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
65.379 + }
65.380 +
65.381 + /* Fire the BEFORE and INSTEAD OF triggers
65.382 + */
65.383 + if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab,
65.384 + newIdx, oldIdx, onError, addr) ){
65.385 + goto update_cleanup;
65.386 + }
65.387 + }
65.388 +
65.389 + if( !isView && !IsVirtual(pTab) ){
65.390 + /*
65.391 + ** Open every index that needs updating. Note that if any
65.392 + ** index could potentially invoke a REPLACE conflict resolution
65.393 + ** action, then we need to open all indices because we might need
65.394 + ** to be deleting some records.
65.395 + */
65.396 + sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
65.397 + if( onError==OE_Replace ){
65.398 + openAll = 1;
65.399 + }else{
65.400 + openAll = 0;
65.401 + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
65.402 + if( pIdx->onError==OE_Replace ){
65.403 + openAll = 1;
65.404 + break;
65.405 + }
65.406 + }
65.407 + }
65.408 + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
65.409 + if( openAll || aIdxUsed[i] ){
65.410 + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
65.411 + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
65.412 + sqlite3VdbeOp3(v, OP_OpenWrite, iCur+i+1, pIdx->tnum,
65.413 + (char*)pKey, P3_KEYINFO_HANDOFF);
65.414 + assert( pParse->nTab>iCur+i+1 );
65.415 + }
65.416 + }
65.417 +
65.418 + /* Loop over every record that needs updating. We have to load
65.419 + ** the old data for each record to be updated because some columns
65.420 + ** might not change and we will need to copy the old value.
65.421 + ** Also, the old data is needed to delete the old index entries.
65.422 + ** So make the cursor point at the old record.
65.423 + */
65.424 + if( !triggers_exist ){
65.425 + addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, 0);
65.426 + sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
65.427 + }
65.428 + sqlite3VdbeAddOp(v, OP_NotExists, iCur, addr);
65.429 +
65.430 + /* If the record number will change, push the record number as it
65.431 + ** will be after the update. (The old record number is currently
65.432 + ** on top of the stack.)
65.433 + */
65.434 + if( chngRowid ){
65.435 + sqlite3ExprCode(pParse, pRowidExpr);
65.436 + sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
65.437 + }
65.438 +
65.439 + /* Compute new data for this record.
65.440 + */
65.441 + for(i=0; i<pTab->nCol; i++){
65.442 + if( i==pTab->iPKey ){
65.443 + sqlite3VdbeAddOp(v, OP_Null, 0, 0);
65.444 + continue;
65.445 + }
65.446 + j = aXRef[i];
65.447 + if( j<0 ){
65.448 + sqlite3VdbeAddOp(v, OP_Column, iCur, i);
65.449 + sqlite3ColumnDefault(v, pTab, i);
65.450 + }else{
65.451 + sqlite3ExprCode(pParse, pChanges->a[j].pExpr);
65.452 + }
65.453 + }
65.454 +
65.455 + /* Do constraint checks
65.456 + */
65.457 + sqlite3GenerateConstraintChecks(pParse, pTab, iCur, aIdxUsed, chngRowid, 1,
65.458 + onError, addr);
65.459 +
65.460 + /* Delete the old indices for the current record.
65.461 + */
65.462 + sqlite3GenerateRowIndexDelete(v, pTab, iCur, aIdxUsed);
65.463 +
65.464 + /* If changing the record number, delete the old record.
65.465 + */
65.466 + if( chngRowid ){
65.467 + sqlite3VdbeAddOp(v, OP_Delete, iCur, 0);
65.468 + }
65.469 +
65.470 + /* Create the new index entries and the new record.
65.471 + */
65.472 + sqlite3CompleteInsertion(pParse, pTab, iCur, aIdxUsed, chngRowid, 1, -1, 0);
65.473 + }
65.474 +
65.475 + /* Increment the row counter
65.476 + */
65.477 + if( db->flags & SQLITE_CountRows && !pParse->trigStack){
65.478 + sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt);
65.479 + }
65.480 +
65.481 + /* If there are triggers, close all the cursors after each iteration
65.482 + ** through the loop. The fire the after triggers.
65.483 + */
65.484 + if( triggers_exist ){
65.485 + if( !isView ){
65.486 + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
65.487 + if( openAll || aIdxUsed[i] )
65.488 + sqlite3VdbeAddOp(v, OP_Close, iCur+i+1, 0);
65.489 + }
65.490 + sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
65.491 + }
65.492 + if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab,
65.493 + newIdx, oldIdx, onError, addr) ){
65.494 + goto update_cleanup;
65.495 + }
65.496 + }
65.497 +
65.498 + /* Repeat the above with the next record to be updated, until
65.499 + ** all record selected by the WHERE clause have been updated.
65.500 + */
65.501 + sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
65.502 + sqlite3VdbeJumpHere(v, addr);
65.503 +
65.504 + /* Close all tables if there were no FOR EACH ROW triggers */
65.505 + if( !triggers_exist ){
65.506 + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
65.507 + if( openAll || aIdxUsed[i] ){
65.508 + sqlite3VdbeAddOp(v, OP_Close, iCur+i+1, 0);
65.509 + }
65.510 + }
65.511 + sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
65.512 + }else{
65.513 + sqlite3VdbeAddOp(v, OP_Close, newIdx, 0);
65.514 + sqlite3VdbeAddOp(v, OP_Close, oldIdx, 0);
65.515 + }
65.516 +
65.517 + /*
65.518 + ** Return the number of rows that were changed. If this routine is
65.519 + ** generating code because of a call to sqlite3NestedParse(), do not
65.520 + ** invoke the callback function.
65.521 + */
65.522 + if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){
65.523 + sqlite3VdbeAddOp(v, OP_MemLoad, memCnt, 0);
65.524 + sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
65.525 + sqlite3VdbeSetNumCols(v, 1);
65.526 + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", P3_STATIC);
65.527 + }
65.528 +
65.529 +update_cleanup:
65.530 + sqlite3AuthContextPop(&sContext);
65.531 + sqliteFree(apIdx);
65.532 + sqliteFree(aXRef);
65.533 + sqlite3SrcListDelete(pTabList);
65.534 + sqlite3ExprListDelete(pChanges);
65.535 + sqlite3ExprDelete(pWhere);
65.536 + return;
65.537 +}
65.538 +
65.539 +#ifndef SQLITE_OMIT_VIRTUALTABLE
65.540 +/*
65.541 +** Generate code for an UPDATE of a virtual table.
65.542 +**
65.543 +** The strategy is that we create an ephemerial table that contains
65.544 +** for each row to be changed:
65.545 +**
65.546 +** (A) The original rowid of that row.
65.547 +** (B) The revised rowid for the row. (note1)
65.548 +** (C) The content of every column in the row.
65.549 +**
65.550 +** Then we loop over this ephemeral table and for each row in
65.551 +** the ephermeral table call VUpdate.
65.552 +**
65.553 +** When finished, drop the ephemeral table.
65.554 +**
65.555 +** (note1) Actually, if we know in advance that (A) is always the same
65.556 +** as (B) we only store (A), then duplicate (A) when pulling
65.557 +** it out of the ephemeral table before calling VUpdate.
65.558 +*/
65.559 +static void updateVirtualTable(
65.560 + Parse *pParse, /* The parsing context */
65.561 + SrcList *pSrc, /* The virtual table to be modified */
65.562 + Table *pTab, /* The virtual table */
65.563 + ExprList *pChanges, /* The columns to change in the UPDATE statement */
65.564 + Expr *pRowid, /* Expression used to recompute the rowid */
65.565 + int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
65.566 + Expr *pWhere /* WHERE clause of the UPDATE statement */
65.567 +){
65.568 + Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
65.569 + ExprList *pEList = 0; /* The result set of the SELECT statement */
65.570 + Select *pSelect = 0; /* The SELECT statement */
65.571 + Expr *pExpr; /* Temporary expression */
65.572 + int ephemTab; /* Table holding the result of the SELECT */
65.573 + int i; /* Loop counter */
65.574 + int addr; /* Address of top of loop */
65.575 +
65.576 + /* Construct the SELECT statement that will find the new values for
65.577 + ** all updated rows.
65.578 + */
65.579 + pEList = sqlite3ExprListAppend(0, sqlite3CreateIdExpr("_rowid_"), 0);
65.580 + if( pRowid ){
65.581 + pEList = sqlite3ExprListAppend(pEList, sqlite3ExprDup(pRowid), 0);
65.582 + }
65.583 + assert( pTab->iPKey<0 );
65.584 + for(i=0; i<pTab->nCol; i++){
65.585 + if( aXRef[i]>=0 ){
65.586 + pExpr = sqlite3ExprDup(pChanges->a[aXRef[i]].pExpr);
65.587 + }else{
65.588 + pExpr = sqlite3CreateIdExpr(pTab->aCol[i].zName);
65.589 + }
65.590 + pEList = sqlite3ExprListAppend(pEList, pExpr, 0);
65.591 + }
65.592 + pSelect = sqlite3SelectNew(pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
65.593 +
65.594 + /* Create the ephemeral table into which the update results will
65.595 + ** be stored.
65.596 + */
65.597 + assert( v );
65.598 + ephemTab = pParse->nTab++;
65.599 + sqlite3VdbeAddOp(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
65.600 +
65.601 + /* fill the ephemeral table
65.602 + */
65.603 + sqlite3Select(pParse, pSelect, SRT_Table, ephemTab, 0, 0, 0, 0);
65.604 +
65.605 + /*
65.606 + ** Generate code to scan the ephemeral table and call VDelete and
65.607 + ** VInsert
65.608 + */
65.609 + sqlite3VdbeAddOp(v, OP_Rewind, ephemTab, 0);
65.610 + addr = sqlite3VdbeCurrentAddr(v);
65.611 + sqlite3VdbeAddOp(v, OP_Column, ephemTab, 0);
65.612 + if( pRowid ){
65.613 + sqlite3VdbeAddOp(v, OP_Column, ephemTab, 1);
65.614 + }else{
65.615 + sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
65.616 + }
65.617 + for(i=0; i<pTab->nCol; i++){
65.618 + sqlite3VdbeAddOp(v, OP_Column, ephemTab, i+1+(pRowid!=0));
65.619 + }
65.620 + pParse->pVirtualLock = pTab;
65.621 + sqlite3VdbeOp3(v, OP_VUpdate, 0, pTab->nCol+2,
65.622 + (const char*)pTab->pVtab, P3_VTAB);
65.623 + sqlite3VdbeAddOp(v, OP_Next, ephemTab, addr);
65.624 + sqlite3VdbeJumpHere(v, addr-1);
65.625 + sqlite3VdbeAddOp(v, OP_Close, ephemTab, 0);
65.626 +
65.627 + /* Cleanup */
65.628 + sqlite3SelectDelete(pSelect);
65.629 +}
65.630 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
66.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
66.2 +++ b/extensions/sqlite/sqlite-source/utf.c Sun Jul 29 01:15:31 2007 +0000
66.3 @@ -0,0 +1,544 @@
66.4 +/*
66.5 +** 2004 April 13
66.6 +**
66.7 +** The author disclaims copyright to this source code. In place of
66.8 +** a legal notice, here is a blessing:
66.9 +**
66.10 +** May you do good and not evil.
66.11 +** May you find forgiveness for yourself and forgive others.
66.12 +** May you share freely, never taking more than you give.
66.13 +**
66.14 +*************************************************************************
66.15 +** This file contains routines used to translate between UTF-8,
66.16 +** UTF-16, UTF-16BE, and UTF-16LE.
66.17 +**
66.18 +** $Id$
66.19 +**
66.20 +** Notes on UTF-8:
66.21 +**
66.22 +** Byte-0 Byte-1 Byte-2 Byte-3 Value
66.23 +** 0xxxxxxx 00000000 00000000 0xxxxxxx
66.24 +** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
66.25 +** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
66.26 +** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
66.27 +**
66.28 +**
66.29 +** Notes on UTF-16: (with wwww+1==uuuuu)
66.30 +**
66.31 +** Word-0 Word-1 Value
66.32 +** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
66.33 +** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
66.34 +**
66.35 +**
66.36 +** BOM or Byte Order Mark:
66.37 +** 0xff 0xfe little-endian utf-16 follows
66.38 +** 0xfe 0xff big-endian utf-16 follows
66.39 +**
66.40 +*/
66.41 +#include "sqliteInt.h"
66.42 +#include <assert.h>
66.43 +#include "vdbeInt.h"
66.44 +
66.45 +/*
66.46 +** The following constant value is used by the SQLITE_BIGENDIAN and
66.47 +** SQLITE_LITTLEENDIAN macros.
66.48 +*/
66.49 +const int sqlite3one = 1;
66.50 +
66.51 +/*
66.52 +** This lookup table is used to help decode the first byte of
66.53 +** a multi-byte UTF8 character.
66.54 +*/
66.55 +const unsigned char sqlite3UtfTrans1[] = {
66.56 + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
66.57 + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
66.58 + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
66.59 + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
66.60 + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
66.61 + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
66.62 + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
66.63 + 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
66.64 +};
66.65 +
66.66 +#define WRITE_UTF8(zOut, c) { \
66.67 + if( c<0x00080 ){ \
66.68 + *zOut++ = (c&0xFF); \
66.69 + } \
66.70 + else if( c<0x00800 ){ \
66.71 + *zOut++ = 0xC0 + ((c>>6)&0x1F); \
66.72 + *zOut++ = 0x80 + (c & 0x3F); \
66.73 + } \
66.74 + else if( c<0x10000 ){ \
66.75 + *zOut++ = 0xE0 + ((c>>12)&0x0F); \
66.76 + *zOut++ = 0x80 + ((c>>6) & 0x3F); \
66.77 + *zOut++ = 0x80 + (c & 0x3F); \
66.78 + }else{ \
66.79 + *zOut++ = 0xF0 + ((c>>18) & 0x07); \
66.80 + *zOut++ = 0x80 + ((c>>12) & 0x3F); \
66.81 + *zOut++ = 0x80 + ((c>>6) & 0x3F); \
66.82 + *zOut++ = 0x80 + (c & 0x3F); \
66.83 + } \
66.84 +}
66.85 +
66.86 +#define WRITE_UTF16LE(zOut, c) { \
66.87 + if( c<=0xFFFF ){ \
66.88 + *zOut++ = (c&0x00FF); \
66.89 + *zOut++ = ((c>>8)&0x00FF); \
66.90 + }else{ \
66.91 + *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
66.92 + *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03)); \
66.93 + *zOut++ = (c&0x00FF); \
66.94 + *zOut++ = (0x00DC + ((c>>8)&0x03)); \
66.95 + } \
66.96 +}
66.97 +
66.98 +#define WRITE_UTF16BE(zOut, c) { \
66.99 + if( c<=0xFFFF ){ \
66.100 + *zOut++ = ((c>>8)&0x00FF); \
66.101 + *zOut++ = (c&0x00FF); \
66.102 + }else{ \
66.103 + *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03)); \
66.104 + *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
66.105 + *zOut++ = (0x00DC + ((c>>8)&0x03)); \
66.106 + *zOut++ = (c&0x00FF); \
66.107 + } \
66.108 +}
66.109 +
66.110 +#define READ_UTF16LE(zIn, c){ \
66.111 + c = (*zIn++); \
66.112 + c += ((*zIn++)<<8); \
66.113 + if( c>=0xD800 && c<0xE000 ){ \
66.114 + int c2 = (*zIn++); \
66.115 + c2 += ((*zIn++)<<8); \
66.116 + c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
66.117 + if( (c & 0xFFFF0000)==0 ) c = 0xFFFD; \
66.118 + } \
66.119 +}
66.120 +
66.121 +#define READ_UTF16BE(zIn, c){ \
66.122 + c = ((*zIn++)<<8); \
66.123 + c += (*zIn++); \
66.124 + if( c>=0xD800 && c<0xE000 ){ \
66.125 + int c2 = ((*zIn++)<<8); \
66.126 + c2 += (*zIn++); \
66.127 + c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
66.128 + if( (c & 0xFFFF0000)==0 ) c = 0xFFFD; \
66.129 + } \
66.130 +}
66.131 +
66.132 +/*
66.133 +** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
66.134 +** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
66.135 +*/
66.136 +/* #define TRANSLATE_TRACE 1 */
66.137 +
66.138 +#ifndef SQLITE_OMIT_UTF16
66.139 +/*
66.140 +** This routine transforms the internal text encoding used by pMem to
66.141 +** desiredEnc. It is an error if the string is already of the desired
66.142 +** encoding, or if *pMem does not contain a string value.
66.143 +*/
66.144 +int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
66.145 + unsigned char zShort[NBFS]; /* Temporary short output buffer */
66.146 + int len; /* Maximum length of output string in bytes */
66.147 + unsigned char *zOut; /* Output buffer */
66.148 + unsigned char *zIn; /* Input iterator */
66.149 + unsigned char *zTerm; /* End of input */
66.150 + unsigned char *z; /* Output iterator */
66.151 + unsigned int c;
66.152 +
66.153 + assert( pMem->flags&MEM_Str );
66.154 + assert( pMem->enc!=desiredEnc );
66.155 + assert( pMem->enc!=0 );
66.156 + assert( pMem->n>=0 );
66.157 +
66.158 +#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
66.159 + {
66.160 + char zBuf[100];
66.161 + sqlite3VdbeMemPrettyPrint(pMem, zBuf);
66.162 + fprintf(stderr, "INPUT: %s\n", zBuf);
66.163 + }
66.164 +#endif
66.165 +
66.166 + /* If the translation is between UTF-16 little and big endian, then
66.167 + ** all that is required is to swap the byte order. This case is handled
66.168 + ** differently from the others.
66.169 + */
66.170 + if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
66.171 + u8 temp;
66.172 + int rc;
66.173 + rc = sqlite3VdbeMemMakeWriteable(pMem);
66.174 + if( rc!=SQLITE_OK ){
66.175 + assert( rc==SQLITE_NOMEM );
66.176 + return SQLITE_NOMEM;
66.177 + }
66.178 + zIn = (u8*)pMem->z;
66.179 + zTerm = &zIn[pMem->n];
66.180 + while( zIn<zTerm ){
66.181 + temp = *zIn;
66.182 + *zIn = *(zIn+1);
66.183 + zIn++;
66.184 + *zIn++ = temp;
66.185 + }
66.186 + pMem->enc = desiredEnc;
66.187 + goto translate_out;
66.188 + }
66.189 +
66.190 + /* Set len to the maximum number of bytes required in the output buffer. */
66.191 + if( desiredEnc==SQLITE_UTF8 ){
66.192 + /* When converting from UTF-16, the maximum growth results from
66.193 + ** translating a 2-byte character to a 4-byte UTF-8 character.
66.194 + ** A single byte is required for the output string
66.195 + ** nul-terminator.
66.196 + */
66.197 + len = pMem->n * 2 + 1;
66.198 + }else{
66.199 + /* When converting from UTF-8 to UTF-16 the maximum growth is caused
66.200 + ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
66.201 + ** character. Two bytes are required in the output buffer for the
66.202 + ** nul-terminator.
66.203 + */
66.204 + len = pMem->n * 2 + 2;
66.205 + }
66.206 +
66.207 + /* Set zIn to point at the start of the input buffer and zTerm to point 1
66.208 + ** byte past the end.
66.209 + **
66.210 + ** Variable zOut is set to point at the output buffer. This may be space
66.211 + ** obtained from malloc(), or Mem.zShort, if it large enough and not in
66.212 + ** use, or the zShort array on the stack (see above).
66.213 + */
66.214 + zIn = (u8*)pMem->z;
66.215 + zTerm = &zIn[pMem->n];
66.216 + if( len>NBFS ){
66.217 + zOut = sqliteMallocRaw(len);
66.218 + if( !zOut ) return SQLITE_NOMEM;
66.219 + }else{
66.220 + zOut = zShort;
66.221 + }
66.222 + z = zOut;
66.223 +
66.224 + if( pMem->enc==SQLITE_UTF8 ){
66.225 + unsigned int iExtra = 0xD800;
66.226 +
66.227 + if( 0==(pMem->flags&MEM_Term) && zTerm>zIn && (zTerm[-1]&0x80) ){
66.228 + /* This UTF8 string is not nul-terminated, and the last byte is
66.229 + ** not a character in the ascii range (codpoints 0..127). This
66.230 + ** means the SQLITE_READ_UTF8() macro might read past the end
66.231 + ** of the allocated buffer.
66.232 + **
66.233 + ** There are four possibilities:
66.234 + **
66.235 + ** 1. The last byte is the first byte of a non-ASCII character,
66.236 + **
66.237 + ** 2. The final N bytes of the input string are continuation bytes
66.238 + ** and immediately preceding them is the first byte of a
66.239 + ** non-ASCII character.
66.240 + **
66.241 + ** 3. The final N bytes of the input string are continuation bytes
66.242 + ** and immediately preceding them is a byte that encodes a
66.243 + ** character in the ASCII range.
66.244 + **
66.245 + ** 4. The entire string consists of continuation characters.
66.246 + **
66.247 + ** Cases (3) and (4) require no special handling. The SQLITE_READ_UTF8()
66.248 + ** macro will not overread the buffer in these cases.
66.249 + */
66.250 + unsigned char *zExtra = &zTerm[-1];
66.251 + while( zExtra>zIn && (zExtra[0]&0xC0)==0x80 ){
66.252 + zExtra--;
66.253 + }
66.254 +
66.255 + if( (zExtra[0]&0xC0)==0xC0 ){
66.256 + /* Make a copy of the last character encoding in the input string.
66.257 + ** Then make sure it is nul-terminated and use SQLITE_READ_UTF8()
66.258 + ** to decode the codepoint. Store the codepoint in variable iExtra,
66.259 + ** it will be appended to the output string later.
66.260 + */
66.261 + unsigned char *zFree = 0;
66.262 + unsigned char zBuf[16];
66.263 + int nExtra = (pMem->n+zIn-zExtra);
66.264 + zTerm = zExtra;
66.265 + if( nExtra>15 ){
66.266 + zExtra = sqliteMallocRaw(nExtra+1);
66.267 + if( !zExtra ){
66.268 + return SQLITE_NOMEM;
66.269 + }
66.270 + zFree = zExtra;
66.271 + }else{
66.272 + zExtra = zBuf;
66.273 + }
66.274 + memcpy(zExtra, zTerm, nExtra);
66.275 + zExtra[nExtra] = '\0';
66.276 + SQLITE_READ_UTF8(zExtra, iExtra);
66.277 + sqliteFree(zFree);
66.278 + }
66.279 + }
66.280 +
66.281 + if( desiredEnc==SQLITE_UTF16LE ){
66.282 + /* UTF-8 -> UTF-16 Little-endian */
66.283 + while( zIn<zTerm ){
66.284 + SQLITE_READ_UTF8(zIn, c);
66.285 + WRITE_UTF16LE(z, c);
66.286 + }
66.287 + if( iExtra!=0xD800 ){
66.288 + WRITE_UTF16LE(z, iExtra);
66.289 + }
66.290 + }else{
66.291 + assert( desiredEnc==SQLITE_UTF16BE );
66.292 + /* UTF-8 -> UTF-16 Big-endian */
66.293 + while( zIn<zTerm ){
66.294 + SQLITE_READ_UTF8(zIn, c);
66.295 + WRITE_UTF16BE(z, c);
66.296 + }
66.297 + if( iExtra!=0xD800 ){
66.298 + WRITE_UTF16BE(z, iExtra);
66.299 + }
66.300 + }
66.301 + pMem->n = z - zOut;
66.302 + *z++ = 0;
66.303 + }else{
66.304 + assert( desiredEnc==SQLITE_UTF8 );
66.305 + if( pMem->enc==SQLITE_UTF16LE ){
66.306 + /* UTF-16 Little-endian -> UTF-8 */
66.307 + while( zIn<zTerm ){
66.308 + READ_UTF16LE(zIn, c);
66.309 + WRITE_UTF8(z, c);
66.310 + }
66.311 + }else{
66.312 + /* UTF-16 Little-endian -> UTF-8 */
66.313 + while( zIn<zTerm ){
66.314 + READ_UTF16BE(zIn, c);
66.315 + WRITE_UTF8(z, c);
66.316 + }
66.317 + }
66.318 + pMem->n = z - zOut;
66.319 + }
66.320 + *z = 0;
66.321 + assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
66.322 +
66.323 + sqlite3VdbeMemRelease(pMem);
66.324 + pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
66.325 + pMem->enc = desiredEnc;
66.326 + if( zOut==zShort ){
66.327 + memcpy(pMem->zShort, zOut, len);
66.328 + zOut = (u8*)pMem->zShort;
66.329 + pMem->flags |= (MEM_Term|MEM_Short);
66.330 + }else{
66.331 + pMem->flags |= (MEM_Term|MEM_Dyn);
66.332 + }
66.333 + pMem->z = (char*)zOut;
66.334 +
66.335 +translate_out:
66.336 +#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
66.337 + {
66.338 + char zBuf[100];
66.339 + sqlite3VdbeMemPrettyPrint(pMem, zBuf);
66.340 + fprintf(stderr, "OUTPUT: %s\n", zBuf);
66.341 + }
66.342 +#endif
66.343 + return SQLITE_OK;
66.344 +}
66.345 +
66.346 +/*
66.347 +** This routine checks for a byte-order mark at the beginning of the
66.348 +** UTF-16 string stored in *pMem. If one is present, it is removed and
66.349 +** the encoding of the Mem adjusted. This routine does not do any
66.350 +** byte-swapping, it just sets Mem.enc appropriately.
66.351 +**
66.352 +** The allocation (static, dynamic etc.) and encoding of the Mem may be
66.353 +** changed by this function.
66.354 +*/
66.355 +int sqlite3VdbeMemHandleBom(Mem *pMem){
66.356 + int rc = SQLITE_OK;
66.357 + u8 bom = 0;
66.358 +
66.359 + if( pMem->n<0 || pMem->n>1 ){
66.360 + u8 b1 = *(u8 *)pMem->z;
66.361 + u8 b2 = *(((u8 *)pMem->z) + 1);
66.362 + if( b1==0xFE && b2==0xFF ){
66.363 + bom = SQLITE_UTF16BE;
66.364 + }
66.365 + if( b1==0xFF && b2==0xFE ){
66.366 + bom = SQLITE_UTF16LE;
66.367 + }
66.368 + }
66.369 +
66.370 + if( bom ){
66.371 + /* This function is called as soon as a string is stored in a Mem*,
66.372 + ** from within sqlite3VdbeMemSetStr(). At that point it is not possible
66.373 + ** for the string to be stored in Mem.zShort, or for it to be stored
66.374 + ** in dynamic memory with no destructor.
66.375 + */
66.376 + assert( !(pMem->flags&MEM_Short) );
66.377 + assert( !(pMem->flags&MEM_Dyn) || pMem->xDel );
66.378 + if( pMem->flags & MEM_Dyn ){
66.379 + void (*xDel)(void*) = pMem->xDel;
66.380 + char *z = pMem->z;
66.381 + pMem->z = 0;
66.382 + pMem->xDel = 0;
66.383 + rc = sqlite3VdbeMemSetStr(pMem, &z[2], pMem->n-2, bom, SQLITE_TRANSIENT);
66.384 + xDel(z);
66.385 + }else{
66.386 + rc = sqlite3VdbeMemSetStr(pMem, &pMem->z[2], pMem->n-2, bom,
66.387 + SQLITE_TRANSIENT);
66.388 + }
66.389 + }
66.390 + return rc;
66.391 +}
66.392 +#endif /* SQLITE_OMIT_UTF16 */
66.393 +
66.394 +/*
66.395 +** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
66.396 +** return the number of unicode characters in pZ up to (but not including)
66.397 +** the first 0x00 byte. If nByte is not less than zero, return the
66.398 +** number of unicode characters in the first nByte of pZ (or up to
66.399 +** the first 0x00, whichever comes first).
66.400 +*/
66.401 +int sqlite3Utf8CharLen(const char *zIn, int nByte){
66.402 + int r = 0;
66.403 + const u8 *z = (const u8*)zIn;
66.404 + const u8 *zTerm;
66.405 + if( nByte>=0 ){
66.406 + zTerm = &z[nByte];
66.407 + }else{
66.408 + zTerm = (const u8*)(-1);
66.409 + }
66.410 + assert( z<=zTerm );
66.411 + while( *z!=0 && z<zTerm ){
66.412 + SQLITE_SKIP_UTF8(z);
66.413 + r++;
66.414 + }
66.415 + return r;
66.416 +}
66.417 +
66.418 +#ifndef SQLITE_OMIT_UTF16
66.419 +/*
66.420 +** Convert a UTF-16 string in the native encoding into a UTF-8 string.
66.421 +** Memory to hold the UTF-8 string is obtained from malloc and must be
66.422 +** freed by the calling function.
66.423 +**
66.424 +** NULL is returned if there is an allocation error.
66.425 +*/
66.426 +char *sqlite3Utf16to8(const void *z, int nByte){
66.427 + Mem m;
66.428 + memset(&m, 0, sizeof(m));
66.429 + sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
66.430 + sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
66.431 + assert( (m.flags & MEM_Term)!=0 || sqlite3MallocFailed() );
66.432 + assert( (m.flags & MEM_Str)!=0 || sqlite3MallocFailed() );
66.433 + return (m.flags & MEM_Dyn)!=0 ? m.z : sqliteStrDup(m.z);
66.434 +}
66.435 +
66.436 +/*
66.437 +** pZ is a UTF-16 encoded unicode string. If nChar is less than zero,
66.438 +** return the number of bytes up to (but not including), the first pair
66.439 +** of consecutive 0x00 bytes in pZ. If nChar is not less than zero,
66.440 +** then return the number of bytes in the first nChar unicode characters
66.441 +** in pZ (or up until the first pair of 0x00 bytes, whichever comes first).
66.442 +*/
66.443 +int sqlite3Utf16ByteLen(const void *zIn, int nChar){
66.444 + unsigned int c = 1;
66.445 + char const *z = zIn;
66.446 + int n = 0;
66.447 + if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
66.448 + /* Using an "if (SQLITE_UTF16NATIVE==SQLITE_UTF16BE)" construct here
66.449 + ** and in other parts of this file means that at one branch will
66.450 + ** not be covered by coverage testing on any single host. But coverage
66.451 + ** will be complete if the tests are run on both a little-endian and
66.452 + ** big-endian host. Because both the UTF16NATIVE and SQLITE_UTF16BE
66.453 + ** macros are constant at compile time the compiler can determine
66.454 + ** which branch will be followed. It is therefore assumed that no runtime
66.455 + ** penalty is paid for this "if" statement.
66.456 + */
66.457 + while( c && ((nChar<0) || n<nChar) ){
66.458 + READ_UTF16BE(z, c);
66.459 + n++;
66.460 + }
66.461 + }else{
66.462 + while( c && ((nChar<0) || n<nChar) ){
66.463 + READ_UTF16LE(z, c);
66.464 + n++;
66.465 + }
66.466 + }
66.467 + return (z-(char const *)zIn)-((c==0)?2:0);
66.468 +}
66.469 +
66.470 +#if defined(SQLITE_TEST)
66.471 +/*
66.472 +** Translate UTF-8 to UTF-8.
66.473 +**
66.474 +** This has the effect of making sure that the string is well-formed
66.475 +** UTF-8. Miscoded characters are removed.
66.476 +**
66.477 +** The translation is done in-place (since it is impossible for the
66.478 +** correct UTF-8 encoding to be longer than a malformed encoding).
66.479 +*/
66.480 +int sqlite3Utf8To8(unsigned char *zIn){
66.481 + unsigned char *zOut = zIn;
66.482 + unsigned char *zStart = zIn;
66.483 + int c;
66.484 +
66.485 + while(1){
66.486 + SQLITE_READ_UTF8(zIn, c);
66.487 + if( c==0 ) break;
66.488 + if( c!=0xfffd ){
66.489 + WRITE_UTF8(zOut, c);
66.490 + }
66.491 + }
66.492 + *zOut = 0;
66.493 + return zOut - zStart;
66.494 +}
66.495 +#endif
66.496 +
66.497 +#if defined(SQLITE_TEST)
66.498 +/*
66.499 +** This routine is called from the TCL test function "translate_selftest".
66.500 +** It checks that the primitives for serializing and deserializing
66.501 +** characters in each encoding are inverses of each other.
66.502 +*/
66.503 +void sqlite3UtfSelfTest(){
66.504 + unsigned int i, t;
66.505 + unsigned char zBuf[20];
66.506 + unsigned char *z;
66.507 + int n;
66.508 + unsigned int c;
66.509 +
66.510 + for(i=0; i<0x00110000; i++){
66.511 + z = zBuf;
66.512 + WRITE_UTF8(z, i);
66.513 + n = z-zBuf;
66.514 + z[0] = 0;
66.515 + z = zBuf;
66.516 + SQLITE_READ_UTF8(z, c);
66.517 + t = i;
66.518 + if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
66.519 + if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
66.520 + assert( c==t );
66.521 + assert( (z-zBuf)==n );
66.522 + }
66.523 + for(i=0; i<0x00110000; i++){
66.524 + if( i>=0xD800 && i<0xE000 ) continue;
66.525 + z = zBuf;
66.526 + WRITE_UTF16LE(z, i);
66.527 + n = z-zBuf;
66.528 + z[0] = 0;
66.529 + z = zBuf;
66.530 + READ_UTF16LE(z, c);
66.531 + assert( c==i );
66.532 + assert( (z-zBuf)==n );
66.533 + }
66.534 + for(i=0; i<0x00110000; i++){
66.535 + if( i>=0xD800 && i<0xE000 ) continue;
66.536 + z = zBuf;
66.537 + WRITE_UTF16BE(z, i);
66.538 + n = z-zBuf;
66.539 + z[0] = 0;
66.540 + z = zBuf;
66.541 + READ_UTF16BE(z, c);
66.542 + assert( c==i );
66.543 + assert( (z-zBuf)==n );
66.544 + }
66.545 +}
66.546 +#endif /* SQLITE_TEST */
66.547 +#endif /* SQLITE_OMIT_UTF16 */
67.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
67.2 +++ b/extensions/sqlite/sqlite-source/util.c Sun Jul 29 01:15:31 2007 +0000
67.3 @@ -0,0 +1,732 @@
67.4 +/*
67.5 +** 2001 September 15
67.6 +**
67.7 +** The author disclaims copyright to this source code. In place of
67.8 +** a legal notice, here is a blessing:
67.9 +**
67.10 +** May you do good and not evil.
67.11 +** May you find forgiveness for yourself and forgive others.
67.12 +** May you share freely, never taking more than you give.
67.13 +**
67.14 +*************************************************************************
67.15 +** Utility functions used throughout sqlite.
67.16 +**
67.17 +** This file contains functions for allocating memory, comparing
67.18 +** strings, and stuff like that.
67.19 +**
67.20 +** $Id$
67.21 +*/
67.22 +#include "sqliteInt.h"
67.23 +#include "os.h"
67.24 +#include <stdarg.h>
67.25 +#include <ctype.h>
67.26 +
67.27 +
67.28 +/*
67.29 +** Set the most recent error code and error string for the sqlite
67.30 +** handle "db". The error code is set to "err_code".
67.31 +**
67.32 +** If it is not NULL, string zFormat specifies the format of the
67.33 +** error string in the style of the printf functions: The following
67.34 +** format characters are allowed:
67.35 +**
67.36 +** %s Insert a string
67.37 +** %z A string that should be freed after use
67.38 +** %d Insert an integer
67.39 +** %T Insert a token
67.40 +** %S Insert the first element of a SrcList
67.41 +**
67.42 +** zFormat and any string tokens that follow it are assumed to be
67.43 +** encoded in UTF-8.
67.44 +**
67.45 +** To clear the most recent error for sqlite handle "db", sqlite3Error
67.46 +** should be called with err_code set to SQLITE_OK and zFormat set
67.47 +** to NULL.
67.48 +*/
67.49 +void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
67.50 + if( db && (db->pErr || (db->pErr = sqlite3ValueNew())!=0) ){
67.51 + db->errCode = err_code;
67.52 + if( zFormat ){
67.53 + char *z;
67.54 + va_list ap;
67.55 + va_start(ap, zFormat);
67.56 + z = sqlite3VMPrintf(zFormat, ap);
67.57 + va_end(ap);
67.58 + sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, sqlite3FreeX);
67.59 + }else{
67.60 + sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
67.61 + }
67.62 + }
67.63 +}
67.64 +
67.65 +/*
67.66 +** Add an error message to pParse->zErrMsg and increment pParse->nErr.
67.67 +** The following formatting characters are allowed:
67.68 +**
67.69 +** %s Insert a string
67.70 +** %z A string that should be freed after use
67.71 +** %d Insert an integer
67.72 +** %T Insert a token
67.73 +** %S Insert the first element of a SrcList
67.74 +**
67.75 +** This function should be used to report any error that occurs whilst
67.76 +** compiling an SQL statement (i.e. within sqlite3_prepare()). The
67.77 +** last thing the sqlite3_prepare() function does is copy the error
67.78 +** stored by this function into the database handle using sqlite3Error().
67.79 +** Function sqlite3Error() should be used during statement execution
67.80 +** (sqlite3_step() etc.).
67.81 +*/
67.82 +void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
67.83 + va_list ap;
67.84 + pParse->nErr++;
67.85 + sqliteFree(pParse->zErrMsg);
67.86 + va_start(ap, zFormat);
67.87 + pParse->zErrMsg = sqlite3VMPrintf(zFormat, ap);
67.88 + va_end(ap);
67.89 + if( pParse->rc==SQLITE_OK ){
67.90 + pParse->rc = SQLITE_ERROR;
67.91 + }
67.92 +}
67.93 +
67.94 +/*
67.95 +** Clear the error message in pParse, if any
67.96 +*/
67.97 +void sqlite3ErrorClear(Parse *pParse){
67.98 + sqliteFree(pParse->zErrMsg);
67.99 + pParse->zErrMsg = 0;
67.100 + pParse->nErr = 0;
67.101 +}
67.102 +
67.103 +/*
67.104 +** Convert an SQL-style quoted string into a normal string by removing
67.105 +** the quote characters. The conversion is done in-place. If the
67.106 +** input does not begin with a quote character, then this routine
67.107 +** is a no-op.
67.108 +**
67.109 +** 2002-Feb-14: This routine is extended to remove MS-Access style
67.110 +** brackets from around identifers. For example: "[a-b-c]" becomes
67.111 +** "a-b-c".
67.112 +*/
67.113 +void sqlite3Dequote(char *z){
67.114 + int quote;
67.115 + int i, j;
67.116 + if( z==0 ) return;
67.117 + quote = z[0];
67.118 + switch( quote ){
67.119 + case '\'': break;
67.120 + case '"': break;
67.121 + case '`': break; /* For MySQL compatibility */
67.122 + case '[': quote = ']'; break; /* For MS SqlServer compatibility */
67.123 + default: return;
67.124 + }
67.125 + for(i=1, j=0; z[i]; i++){
67.126 + if( z[i]==quote ){
67.127 + if( z[i+1]==quote ){
67.128 + z[j++] = quote;
67.129 + i++;
67.130 + }else{
67.131 + z[j++] = 0;
67.132 + break;
67.133 + }
67.134 + }else{
67.135 + z[j++] = z[i];
67.136 + }
67.137 + }
67.138 +}
67.139 +
67.140 +/* An array to map all upper-case characters into their corresponding
67.141 +** lower-case character.
67.142 +*/
67.143 +const unsigned char sqlite3UpperToLower[] = {
67.144 +#ifdef SQLITE_ASCII
67.145 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
67.146 + 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
67.147 + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
67.148 + 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
67.149 + 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
67.150 + 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
67.151 + 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
67.152 + 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
67.153 + 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
67.154 + 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
67.155 + 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
67.156 + 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
67.157 + 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
67.158 + 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
67.159 + 252,253,254,255
67.160 +#endif
67.161 +#ifdef SQLITE_EBCDIC
67.162 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
67.163 + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
67.164 + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
67.165 + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
67.166 + 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
67.167 + 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
67.168 + 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
67.169 + 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
67.170 + 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
67.171 + 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
67.172 + 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
67.173 + 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
67.174 + 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
67.175 + 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
67.176 + 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
67.177 + 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
67.178 +#endif
67.179 +};
67.180 +#define UpperToLower sqlite3UpperToLower
67.181 +
67.182 +/*
67.183 +** Some systems have stricmp(). Others have strcasecmp(). Because
67.184 +** there is no consistency, we will define our own.
67.185 +*/
67.186 +int sqlite3StrICmp(const char *zLeft, const char *zRight){
67.187 + register unsigned char *a, *b;
67.188 + a = (unsigned char *)zLeft;
67.189 + b = (unsigned char *)zRight;
67.190 + while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
67.191 + return UpperToLower[*a] - UpperToLower[*b];
67.192 +}
67.193 +int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
67.194 + register unsigned char *a, *b;
67.195 + a = (unsigned char *)zLeft;
67.196 + b = (unsigned char *)zRight;
67.197 + while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
67.198 + return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
67.199 +}
67.200 +
67.201 +/*
67.202 +** Return TRUE if z is a pure numeric string. Return FALSE if the
67.203 +** string contains any character which is not part of a number. If
67.204 +** the string is numeric and contains the '.' character, set *realnum
67.205 +** to TRUE (otherwise FALSE).
67.206 +**
67.207 +** An empty string is considered non-numeric.
67.208 +*/
67.209 +int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
67.210 + int incr = (enc==SQLITE_UTF8?1:2);
67.211 + if( enc==SQLITE_UTF16BE ) z++;
67.212 + if( *z=='-' || *z=='+' ) z += incr;
67.213 + if( !isdigit(*(u8*)z) ){
67.214 + return 0;
67.215 + }
67.216 + z += incr;
67.217 + if( realnum ) *realnum = 0;
67.218 + while( isdigit(*(u8*)z) ){ z += incr; }
67.219 + if( *z=='.' ){
67.220 + z += incr;
67.221 + if( !isdigit(*(u8*)z) ) return 0;
67.222 + while( isdigit(*(u8*)z) ){ z += incr; }
67.223 + if( realnum ) *realnum = 1;
67.224 + }
67.225 + if( *z=='e' || *z=='E' ){
67.226 + z += incr;
67.227 + if( *z=='+' || *z=='-' ) z += incr;
67.228 + if( !isdigit(*(u8*)z) ) return 0;
67.229 + while( isdigit(*(u8*)z) ){ z += incr; }
67.230 + if( realnum ) *realnum = 1;
67.231 + }
67.232 + return *z==0;
67.233 +}
67.234 +
67.235 +/*
67.236 +** The string z[] is an ascii representation of a real number.
67.237 +** Convert this string to a double.
67.238 +**
67.239 +** This routine assumes that z[] really is a valid number. If it
67.240 +** is not, the result is undefined.
67.241 +**
67.242 +** This routine is used instead of the library atof() function because
67.243 +** the library atof() might want to use "," as the decimal point instead
67.244 +** of "." depending on how locale is set. But that would cause problems
67.245 +** for SQL. So this routine always uses "." regardless of locale.
67.246 +*/
67.247 +int sqlite3AtoF(const char *z, double *pResult){
67.248 +#ifndef SQLITE_OMIT_FLOATING_POINT
67.249 + int sign = 1;
67.250 + const char *zBegin = z;
67.251 + LONGDOUBLE_TYPE v1 = 0.0;
67.252 + while( isspace(*(u8*)z) ) z++;
67.253 + if( *z=='-' ){
67.254 + sign = -1;
67.255 + z++;
67.256 + }else if( *z=='+' ){
67.257 + z++;
67.258 + }
67.259 + while( isdigit(*(u8*)z) ){
67.260 + v1 = v1*10.0 + (*z - '0');
67.261 + z++;
67.262 + }
67.263 + if( *z=='.' ){
67.264 + LONGDOUBLE_TYPE divisor = 1.0;
67.265 + z++;
67.266 + while( isdigit(*(u8*)z) ){
67.267 + v1 = v1*10.0 + (*z - '0');
67.268 + divisor *= 10.0;
67.269 + z++;
67.270 + }
67.271 + v1 /= divisor;
67.272 + }
67.273 + if( *z=='e' || *z=='E' ){
67.274 + int esign = 1;
67.275 + int eval = 0;
67.276 + LONGDOUBLE_TYPE scale = 1.0;
67.277 + z++;
67.278 + if( *z=='-' ){
67.279 + esign = -1;
67.280 + z++;
67.281 + }else if( *z=='+' ){
67.282 + z++;
67.283 + }
67.284 + while( isdigit(*(u8*)z) ){
67.285 + eval = eval*10 + *z - '0';
67.286 + z++;
67.287 + }
67.288 + while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
67.289 + while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
67.290 + while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
67.291 + while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
67.292 + if( esign<0 ){
67.293 + v1 /= scale;
67.294 + }else{
67.295 + v1 *= scale;
67.296 + }
67.297 + }
67.298 + *pResult = sign<0 ? -v1 : v1;
67.299 + return z - zBegin;
67.300 +#else
67.301 + return sqlite3Atoi64(z, pResult);
67.302 +#endif /* SQLITE_OMIT_FLOATING_POINT */
67.303 +}
67.304 +
67.305 +/*
67.306 +** Compare the 19-character string zNum against the text representation
67.307 +** value 2^63: 9223372036854775808. Return negative, zero, or positive
67.308 +** if zNum is less than, equal to, or greater than the string.
67.309 +**
67.310 +** Unlike memcmp() this routine is guaranteed to return the difference
67.311 +** in the values of the last digit if the only difference is in the
67.312 +** last digit. So, for example,
67.313 +**
67.314 +** compare2pow63("9223372036854775800")
67.315 +**
67.316 +** will return -8.
67.317 +*/
67.318 +static int compare2pow63(const char *zNum){
67.319 + int c;
67.320 + c = memcmp(zNum,"922337203685477580",18);
67.321 + if( c==0 ){
67.322 + c = zNum[18] - '8';
67.323 + }
67.324 + return c;
67.325 +}
67.326 +
67.327 +
67.328 +/*
67.329 +** Return TRUE if zNum is a 64-bit signed integer and write
67.330 +** the value of the integer into *pNum. If zNum is not an integer
67.331 +** or is an integer that is too large to be expressed with 64 bits,
67.332 +** then return false.
67.333 +**
67.334 +** When this routine was originally written it dealt with only
67.335 +** 32-bit numbers. At that time, it was much faster than the
67.336 +** atoi() library routine in RedHat 7.2.
67.337 +*/
67.338 +int sqlite3Atoi64(const char *zNum, i64 *pNum){
67.339 + i64 v = 0;
67.340 + int neg;
67.341 + int i, c;
67.342 + while( isspace(*(u8*)zNum) ) zNum++;
67.343 + if( *zNum=='-' ){
67.344 + neg = 1;
67.345 + zNum++;
67.346 + }else if( *zNum=='+' ){
67.347 + neg = 0;
67.348 + zNum++;
67.349 + }else{
67.350 + neg = 0;
67.351 + }
67.352 + while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
67.353 + for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
67.354 + v = v*10 + c - '0';
67.355 + }
67.356 + *pNum = neg ? -v : v;
67.357 + if( c!=0 || i==0 || i>19 ){
67.358 + /* zNum is empty or contains non-numeric text or is longer
67.359 + ** than 19 digits (thus guaranting that it is too large) */
67.360 + return 0;
67.361 + }else if( i<19 ){
67.362 + /* Less than 19 digits, so we know that it fits in 64 bits */
67.363 + return 1;
67.364 + }else{
67.365 + /* 19-digit numbers must be no larger than 9223372036854775807 if positive
67.366 + ** or 9223372036854775808 if negative. Note that 9223372036854665808
67.367 + ** is 2^63. */
67.368 + return compare2pow63(zNum)<neg;
67.369 + }
67.370 +}
67.371 +
67.372 +/*
67.373 +** The string zNum represents an integer. There might be some other
67.374 +** information following the integer too, but that part is ignored.
67.375 +** If the integer that the prefix of zNum represents will fit in a
67.376 +** 64-bit signed integer, return TRUE. Otherwise return FALSE.
67.377 +**
67.378 +** This routine returns FALSE for the string -9223372036854775808 even that
67.379 +** that number will, in theory fit in a 64-bit integer. Positive
67.380 +** 9223373036854775808 will not fit in 64 bits. So it seems safer to return
67.381 +** false.
67.382 +*/
67.383 +int sqlite3FitsIn64Bits(const char *zNum){
67.384 + int i, c;
67.385 + int neg = 0;
67.386 + if( *zNum=='-' ){
67.387 + neg = 1;
67.388 + zNum++;
67.389 + }else if( *zNum=='+' ){
67.390 + zNum++;
67.391 + }
67.392 + while( *zNum=='0' ){
67.393 + zNum++; /* Skip leading zeros. Ticket #2454 */
67.394 + }
67.395 + for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
67.396 + if( i<19 ){
67.397 + /* Guaranteed to fit if less than 19 digits */
67.398 + return 1;
67.399 + }else if( i>19 ){
67.400 + /* Guaranteed to be too big if greater than 19 digits */
67.401 + return 0;
67.402 + }else{
67.403 + /* Compare against 2^63. */
67.404 + return compare2pow63(zNum)<neg;
67.405 + }
67.406 +}
67.407 +
67.408 +/*
67.409 +** If zNum represents an integer that will fit in 32-bits, then set
67.410 +** *pValue to that integer and return true. Otherwise return false.
67.411 +**
67.412 +** Any non-numeric characters that following zNum are ignored.
67.413 +** This is different from sqlite3Atoi64() which requires the
67.414 +** input number to be zero-terminated.
67.415 +*/
67.416 +int sqlite3GetInt32(const char *zNum, int *pValue){
67.417 + sqlite_int64 v = 0;
67.418 + int i, c;
67.419 + int neg = 0;
67.420 + if( zNum[0]=='-' ){
67.421 + neg = 1;
67.422 + zNum++;
67.423 + }else if( zNum[0]=='+' ){
67.424 + zNum++;
67.425 + }
67.426 + while( zNum[0]=='0' ) zNum++;
67.427 + for(i=0; i<10 && (c = zNum[i] - '0')>=0 && c<=9; i++){
67.428 + v = v*10 + c;
67.429 + }
67.430 + if( i>9 ){
67.431 + return 0;
67.432 + }
67.433 + if( v-neg>2147483647 ){
67.434 + return 0;
67.435 + }
67.436 + if( neg ){
67.437 + v = -v;
67.438 + }
67.439 + *pValue = (int)v;
67.440 + return 1;
67.441 +}
67.442 +
67.443 +/*
67.444 +** Check to make sure we have a valid db pointer. This test is not
67.445 +** foolproof but it does provide some measure of protection against
67.446 +** misuse of the interface such as passing in db pointers that are
67.447 +** NULL or which have been previously closed. If this routine returns
67.448 +** TRUE it means that the db pointer is invalid and should not be
67.449 +** dereferenced for any reason. The calling function should invoke
67.450 +** SQLITE_MISUSE immediately.
67.451 +*/
67.452 +int sqlite3SafetyCheck(sqlite3 *db){
67.453 + int magic;
67.454 + if( db==0 ) return 1;
67.455 + magic = db->magic;
67.456 + if( magic!=SQLITE_MAGIC_CLOSED &&
67.457 + magic!=SQLITE_MAGIC_OPEN &&
67.458 + magic!=SQLITE_MAGIC_BUSY ) return 1;
67.459 + return 0;
67.460 +}
67.461 +
67.462 +/*
67.463 +** The variable-length integer encoding is as follows:
67.464 +**
67.465 +** KEY:
67.466 +** A = 0xxxxxxx 7 bits of data and one flag bit
67.467 +** B = 1xxxxxxx 7 bits of data and one flag bit
67.468 +** C = xxxxxxxx 8 bits of data
67.469 +**
67.470 +** 7 bits - A
67.471 +** 14 bits - BA
67.472 +** 21 bits - BBA
67.473 +** 28 bits - BBBA
67.474 +** 35 bits - BBBBA
67.475 +** 42 bits - BBBBBA
67.476 +** 49 bits - BBBBBBA
67.477 +** 56 bits - BBBBBBBA
67.478 +** 64 bits - BBBBBBBBC
67.479 +*/
67.480 +
67.481 +/*
67.482 +** Write a 64-bit variable-length integer to memory starting at p[0].
67.483 +** The length of data write will be between 1 and 9 bytes. The number
67.484 +** of bytes written is returned.
67.485 +**
67.486 +** A variable-length integer consists of the lower 7 bits of each byte
67.487 +** for all bytes that have the 8th bit set and one byte with the 8th
67.488 +** bit clear. Except, if we get to the 9th byte, it stores the full
67.489 +** 8 bits and is the last byte.
67.490 +*/
67.491 +int sqlite3PutVarint(unsigned char *p, u64 v){
67.492 + int i, j, n;
67.493 + u8 buf[10];
67.494 + if( v & (((u64)0xff000000)<<32) ){
67.495 + p[8] = v;
67.496 + v >>= 8;
67.497 + for(i=7; i>=0; i--){
67.498 + p[i] = (v & 0x7f) | 0x80;
67.499 + v >>= 7;
67.500 + }
67.501 + return 9;
67.502 + }
67.503 + n = 0;
67.504 + do{
67.505 + buf[n++] = (v & 0x7f) | 0x80;
67.506 + v >>= 7;
67.507 + }while( v!=0 );
67.508 + buf[0] &= 0x7f;
67.509 + assert( n<=9 );
67.510 + for(i=0, j=n-1; j>=0; j--, i++){
67.511 + p[i] = buf[j];
67.512 + }
67.513 + return n;
67.514 +}
67.515 +
67.516 +/*
67.517 +** Read a 64-bit variable-length integer from memory starting at p[0].
67.518 +** Return the number of bytes read. The value is stored in *v.
67.519 +*/
67.520 +int sqlite3GetVarint(const unsigned char *p, u64 *v){
67.521 + u32 x;
67.522 + u64 x64;
67.523 + int n;
67.524 + unsigned char c;
67.525 + if( ((c = p[0]) & 0x80)==0 ){
67.526 + *v = c;
67.527 + return 1;
67.528 + }
67.529 + x = c & 0x7f;
67.530 + if( ((c = p[1]) & 0x80)==0 ){
67.531 + *v = (x<<7) | c;
67.532 + return 2;
67.533 + }
67.534 + x = (x<<7) | (c&0x7f);
67.535 + if( ((c = p[2]) & 0x80)==0 ){
67.536 + *v = (x<<7) | c;
67.537 + return 3;
67.538 + }
67.539 + x = (x<<7) | (c&0x7f);
67.540 + if( ((c = p[3]) & 0x80)==0 ){
67.541 + *v = (x<<7) | c;
67.542 + return 4;
67.543 + }
67.544 + x64 = (x<<7) | (c&0x7f);
67.545 + n = 4;
67.546 + do{
67.547 + c = p[n++];
67.548 + if( n==9 ){
67.549 + x64 = (x64<<8) | c;
67.550 + break;
67.551 + }
67.552 + x64 = (x64<<7) | (c&0x7f);
67.553 + }while( (c & 0x80)!=0 );
67.554 + *v = x64;
67.555 + return n;
67.556 +}
67.557 +
67.558 +/*
67.559 +** Read a 32-bit variable-length integer from memory starting at p[0].
67.560 +** Return the number of bytes read. The value is stored in *v.
67.561 +*/
67.562 +int sqlite3GetVarint32(const unsigned char *p, u32 *v){
67.563 + u32 x;
67.564 + int n;
67.565 + unsigned char c;
67.566 + if( ((signed char*)p)[0]>=0 ){
67.567 + *v = p[0];
67.568 + return 1;
67.569 + }
67.570 + x = p[0] & 0x7f;
67.571 + if( ((signed char*)p)[1]>=0 ){
67.572 + *v = (x<<7) | p[1];
67.573 + return 2;
67.574 + }
67.575 + x = (x<<7) | (p[1] & 0x7f);
67.576 + n = 2;
67.577 + do{
67.578 + x = (x<<7) | ((c = p[n++])&0x7f);
67.579 + }while( (c & 0x80)!=0 && n<9 );
67.580 + *v = x;
67.581 + return n;
67.582 +}
67.583 +
67.584 +/*
67.585 +** Return the number of bytes that will be needed to store the given
67.586 +** 64-bit integer.
67.587 +*/
67.588 +int sqlite3VarintLen(u64 v){
67.589 + int i = 0;
67.590 + do{
67.591 + i++;
67.592 + v >>= 7;
67.593 + }while( v!=0 && i<9 );
67.594 + return i;
67.595 +}
67.596 +
67.597 +
67.598 +/*
67.599 +** Read or write a four-byte big-endian integer value.
67.600 +*/
67.601 +u32 sqlite3Get4byte(const u8 *p){
67.602 + return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
67.603 +}
67.604 +void sqlite3Put4byte(unsigned char *p, u32 v){
67.605 + p[0] = v>>24;
67.606 + p[1] = v>>16;
67.607 + p[2] = v>>8;
67.608 + p[3] = v;
67.609 +}
67.610 +
67.611 +
67.612 +
67.613 +#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC) \
67.614 + || defined(SQLITE_TEST)
67.615 +/*
67.616 +** Translate a single byte of Hex into an integer.
67.617 +*/
67.618 +static int hexToInt(int h){
67.619 + if( h>='0' && h<='9' ){
67.620 + return h - '0';
67.621 + }else if( h>='a' && h<='f' ){
67.622 + return h - 'a' + 10;
67.623 + }else{
67.624 + assert( h>='A' && h<='F' );
67.625 + return h - 'A' + 10;
67.626 + }
67.627 +}
67.628 +#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC || SQLITE_TEST */
67.629 +
67.630 +#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
67.631 +/*
67.632 +** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
67.633 +** value. Return a pointer to its binary value. Space to hold the
67.634 +** binary value has been obtained from malloc and must be freed by
67.635 +** the calling routine.
67.636 +*/
67.637 +void *sqlite3HexToBlob(const char *z){
67.638 + char *zBlob;
67.639 + int i;
67.640 + int n = strlen(z);
67.641 + if( n%2 ) return 0;
67.642 +
67.643 + zBlob = (char *)sqliteMalloc(n/2);
67.644 + if( zBlob ){
67.645 + for(i=0; i<n; i+=2){
67.646 + zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
67.647 + }
67.648 + }
67.649 + return zBlob;
67.650 +}
67.651 +#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
67.652 +
67.653 +
67.654 +/*
67.655 +** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
67.656 +** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
67.657 +** when this routine is called.
67.658 +**
67.659 +** This routine is called when entering an SQLite API. The SQLITE_MAGIC_OPEN
67.660 +** value indicates that the database connection passed into the API is
67.661 +** open and is not being used by another thread. By changing the value
67.662 +** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
67.663 +** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
67.664 +** when the API exits.
67.665 +**
67.666 +** This routine is a attempt to detect if two threads use the
67.667 +** same sqlite* pointer at the same time. There is a race
67.668 +** condition so it is possible that the error is not detected.
67.669 +** But usually the problem will be seen. The result will be an
67.670 +** error which can be used to debug the application that is
67.671 +** using SQLite incorrectly.
67.672 +**
67.673 +** Ticket #202: If db->magic is not a valid open value, take care not
67.674 +** to modify the db structure at all. It could be that db is a stale
67.675 +** pointer. In other words, it could be that there has been a prior
67.676 +** call to sqlite3_close(db) and db has been deallocated. And we do
67.677 +** not want to write into deallocated memory.
67.678 +*/
67.679 +int sqlite3SafetyOn(sqlite3 *db){
67.680 + if( db->magic==SQLITE_MAGIC_OPEN ){
67.681 + db->magic = SQLITE_MAGIC_BUSY;
67.682 + return 0;
67.683 + }else if( db->magic==SQLITE_MAGIC_BUSY ){
67.684 + db->magic = SQLITE_MAGIC_ERROR;
67.685 + db->u1.isInterrupted = 1;
67.686 + }
67.687 + return 1;
67.688 +}
67.689 +
67.690 +/*
67.691 +** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
67.692 +** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
67.693 +** when this routine is called.
67.694 +*/
67.695 +int sqlite3SafetyOff(sqlite3 *db){
67.696 + if( db->magic==SQLITE_MAGIC_BUSY ){
67.697 + db->magic = SQLITE_MAGIC_OPEN;
67.698 + return 0;
67.699 + }else {
67.700 + db->magic = SQLITE_MAGIC_ERROR;
67.701 + db->u1.isInterrupted = 1;
67.702 + return 1;
67.703 + }
67.704 +}
67.705 +
67.706 +/*
67.707 +** Return a pointer to the ThreadData associated with the calling thread.
67.708 +*/
67.709 +ThreadData *sqlite3ThreadData(){
67.710 + ThreadData *p = (ThreadData*)sqlite3OsThreadSpecificData(1);
67.711 + if( !p ){
67.712 + sqlite3FailedMalloc();
67.713 + }
67.714 + return p;
67.715 +}
67.716 +
67.717 +/*
67.718 +** Return a pointer to the ThreadData associated with the calling thread.
67.719 +** If no ThreadData has been allocated to this thread yet, return a pointer
67.720 +** to a substitute ThreadData structure that is all zeros.
67.721 +*/
67.722 +const ThreadData *sqlite3ThreadDataReadOnly(){
67.723 + static const ThreadData zeroData = {0}; /* Initializer to silence warnings
67.724 + ** from broken compilers */
67.725 + const ThreadData *pTd = sqlite3OsThreadSpecificData(0);
67.726 + return pTd ? pTd : &zeroData;
67.727 +}
67.728 +
67.729 +/*
67.730 +** Check to see if the ThreadData for this thread is all zero. If it
67.731 +** is, then deallocate it.
67.732 +*/
67.733 +void sqlite3ReleaseThreadData(){
67.734 + sqlite3OsThreadSpecificData(-1);
67.735 +}
68.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
68.2 +++ b/extensions/sqlite/sqlite-source/vacuum.c Sun Jul 29 01:15:31 2007 +0000
68.3 @@ -0,0 +1,262 @@
68.4 +/*
68.5 +** 2003 April 6
68.6 +**
68.7 +** The author disclaims copyright to this source code. In place of
68.8 +** a legal notice, here is a blessing:
68.9 +**
68.10 +** May you do good and not evil.
68.11 +** May you find forgiveness for yourself and forgive others.
68.12 +** May you share freely, never taking more than you give.
68.13 +**
68.14 +*************************************************************************
68.15 +** This file contains code used to implement the VACUUM command.
68.16 +**
68.17 +** Most of the code in this file may be omitted by defining the
68.18 +** SQLITE_OMIT_VACUUM macro.
68.19 +**
68.20 +** $Id$
68.21 +*/
68.22 +#include "sqliteInt.h"
68.23 +#include "vdbeInt.h"
68.24 +#include "os.h"
68.25 +
68.26 +#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
68.27 +/*
68.28 +** Execute zSql on database db. Return an error code.
68.29 +*/
68.30 +static int execSql(sqlite3 *db, const char *zSql){
68.31 + sqlite3_stmt *pStmt;
68.32 + if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
68.33 + return sqlite3_errcode(db);
68.34 + }
68.35 + while( SQLITE_ROW==sqlite3_step(pStmt) ){}
68.36 + return sqlite3_finalize(pStmt);
68.37 +}
68.38 +
68.39 +/*
68.40 +** Execute zSql on database db. The statement returns exactly
68.41 +** one column. Execute this as SQL on the same database.
68.42 +*/
68.43 +static int execExecSql(sqlite3 *db, const char *zSql){
68.44 + sqlite3_stmt *pStmt;
68.45 + int rc;
68.46 +
68.47 + rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
68.48 + if( rc!=SQLITE_OK ) return rc;
68.49 +
68.50 + while( SQLITE_ROW==sqlite3_step(pStmt) ){
68.51 + rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
68.52 + if( rc!=SQLITE_OK ){
68.53 + sqlite3_finalize(pStmt);
68.54 + return rc;
68.55 + }
68.56 + }
68.57 +
68.58 + return sqlite3_finalize(pStmt);
68.59 +}
68.60 +
68.61 +/*
68.62 +** The non-standard VACUUM command is used to clean up the database,
68.63 +** collapse free space, etc. It is modelled after the VACUUM command
68.64 +** in PostgreSQL.
68.65 +**
68.66 +** In version 1.0.x of SQLite, the VACUUM command would call
68.67 +** gdbm_reorganize() on all the database tables. But beginning
68.68 +** with 2.0.0, SQLite no longer uses GDBM so this command has
68.69 +** become a no-op.
68.70 +*/
68.71 +void sqlite3Vacuum(Parse *pParse){
68.72 + Vdbe *v = sqlite3GetVdbe(pParse);
68.73 + if( v ){
68.74 + sqlite3VdbeAddOp(v, OP_Vacuum, 0, 0);
68.75 + }
68.76 + return;
68.77 +}
68.78 +
68.79 +/*
68.80 +** This routine implements the OP_Vacuum opcode of the VDBE.
68.81 +*/
68.82 +int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
68.83 + int rc = SQLITE_OK; /* Return code from service routines */
68.84 + Btree *pMain; /* The database being vacuumed */
68.85 + Btree *pTemp; /* The temporary database we vacuum into */
68.86 + char *zSql = 0; /* SQL statements */
68.87 + int saved_flags; /* Saved value of the db->flags */
68.88 + Db *pDb = 0; /* Database to detach at end of vacuum */
68.89 +
68.90 + /* Save the current value of the write-schema flag before setting it. */
68.91 + saved_flags = db->flags;
68.92 + db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
68.93 +
68.94 + if( !db->autoCommit ){
68.95 + sqlite3SetString(pzErrMsg, "cannot VACUUM from within a transaction",
68.96 + (char*)0);
68.97 + rc = SQLITE_ERROR;
68.98 + goto end_of_vacuum;
68.99 + }
68.100 + pMain = db->aDb[0].pBt;
68.101 +
68.102 + /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
68.103 + ** can be set to 'off' for this file, as it is not recovered if a crash
68.104 + ** occurs anyway. The integrity of the database is maintained by a
68.105 + ** (possibly synchronous) transaction opened on the main database before
68.106 + ** sqlite3BtreeCopyFile() is called.
68.107 + **
68.108 + ** An optimisation would be to use a non-journaled pager.
68.109 + */
68.110 + zSql = "ATTACH '' AS vacuum_db;";
68.111 + rc = execSql(db, zSql);
68.112 + if( rc!=SQLITE_OK ) goto end_of_vacuum;
68.113 + pDb = &db->aDb[db->nDb-1];
68.114 + assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
68.115 + pTemp = db->aDb[db->nDb-1].pBt;
68.116 + sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain),
68.117 + sqlite3BtreeGetReserve(pMain));
68.118 + if( sqlite3MallocFailed() ){
68.119 + rc = SQLITE_NOMEM;
68.120 + goto end_of_vacuum;
68.121 + }
68.122 + assert( sqlite3BtreeGetPageSize(pTemp)==sqlite3BtreeGetPageSize(pMain) );
68.123 + rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
68.124 + if( rc!=SQLITE_OK ){
68.125 + goto end_of_vacuum;
68.126 + }
68.127 +
68.128 +#ifndef SQLITE_OMIT_AUTOVACUUM
68.129 + sqlite3BtreeSetAutoVacuum(pTemp, sqlite3BtreeGetAutoVacuum(pMain));
68.130 +#endif
68.131 +
68.132 + /* Begin a transaction */
68.133 + rc = execSql(db, "BEGIN EXCLUSIVE;");
68.134 + if( rc!=SQLITE_OK ) goto end_of_vacuum;
68.135 +
68.136 + /* Query the schema of the main database. Create a mirror schema
68.137 + ** in the temporary database.
68.138 + */
68.139 + rc = execExecSql(db,
68.140 + "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14,100000000) "
68.141 + " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
68.142 + " AND rootpage>0"
68.143 + );
68.144 + if( rc!=SQLITE_OK ) goto end_of_vacuum;
68.145 + rc = execExecSql(db,
68.146 + "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14,100000000)"
68.147 + " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
68.148 + if( rc!=SQLITE_OK ) goto end_of_vacuum;
68.149 + rc = execExecSql(db,
68.150 + "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21,100000000) "
68.151 + " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
68.152 + if( rc!=SQLITE_OK ) goto end_of_vacuum;
68.153 +
68.154 + /* Loop through the tables in the main database. For each, do
68.155 + ** an "INSERT INTO vacuum_db.xxx SELECT * FROM xxx;" to copy
68.156 + ** the contents to the temporary database.
68.157 + */
68.158 + rc = execExecSql(db,
68.159 + "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
68.160 + "|| ' SELECT * FROM ' || quote(name) || ';'"
68.161 + "FROM sqlite_master "
68.162 + "WHERE type = 'table' AND name!='sqlite_sequence' "
68.163 + " AND rootpage>0"
68.164 +
68.165 + );
68.166 + if( rc!=SQLITE_OK ) goto end_of_vacuum;
68.167 +
68.168 + /* Copy over the sequence table
68.169 + */
68.170 + rc = execExecSql(db,
68.171 + "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
68.172 + "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
68.173 + );
68.174 + if( rc!=SQLITE_OK ) goto end_of_vacuum;
68.175 + rc = execExecSql(db,
68.176 + "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
68.177 + "|| ' SELECT * FROM ' || quote(name) || ';' "
68.178 + "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
68.179 + );
68.180 + if( rc!=SQLITE_OK ) goto end_of_vacuum;
68.181 +
68.182 +
68.183 + /* Copy the triggers, views, and virtual tables from the main database
68.184 + ** over to the temporary database. None of these objects has any
68.185 + ** associated storage, so all we have to do is copy their entries
68.186 + ** from the SQLITE_MASTER table.
68.187 + */
68.188 + rc = execSql(db,
68.189 + "INSERT INTO vacuum_db.sqlite_master "
68.190 + " SELECT type, name, tbl_name, rootpage, sql"
68.191 + " FROM sqlite_master"
68.192 + " WHERE type='view' OR type='trigger'"
68.193 + " OR (type='table' AND rootpage=0)"
68.194 + );
68.195 + if( rc ) goto end_of_vacuum;
68.196 +
68.197 + /* At this point, unless the main db was completely empty, there is now a
68.198 + ** transaction open on the vacuum database, but not on the main database.
68.199 + ** Open a btree level transaction on the main database. This allows a
68.200 + ** call to sqlite3BtreeCopyFile(). The main database btree level
68.201 + ** transaction is then committed, so the SQL level never knows it was
68.202 + ** opened for writing. This way, the SQL transaction used to create the
68.203 + ** temporary database never needs to be committed.
68.204 + */
68.205 + if( rc==SQLITE_OK ){
68.206 + u32 meta;
68.207 + int i;
68.208 +
68.209 + /* This array determines which meta meta values are preserved in the
68.210 + ** vacuum. Even entries are the meta value number and odd entries
68.211 + ** are an increment to apply to the meta value after the vacuum.
68.212 + ** The increment is used to increase the schema cookie so that other
68.213 + ** connections to the same database will know to reread the schema.
68.214 + */
68.215 + static const unsigned char aCopy[] = {
68.216 + 1, 1, /* Add one to the old schema cookie */
68.217 + 3, 0, /* Preserve the default page cache size */
68.218 + 5, 0, /* Preserve the default text encoding */
68.219 + 6, 0, /* Preserve the user version */
68.220 + };
68.221 +
68.222 + assert( 1==sqlite3BtreeIsInTrans(pTemp) );
68.223 + assert( 1==sqlite3BtreeIsInTrans(pMain) );
68.224 +
68.225 + /* Copy Btree meta values */
68.226 + for(i=0; i<sizeof(aCopy)/sizeof(aCopy[0]); i+=2){
68.227 + rc = sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
68.228 + if( rc!=SQLITE_OK ) goto end_of_vacuum;
68.229 + rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
68.230 + if( rc!=SQLITE_OK ) goto end_of_vacuum;
68.231 + }
68.232 +
68.233 + rc = sqlite3BtreeCopyFile(pMain, pTemp);
68.234 + if( rc!=SQLITE_OK ) goto end_of_vacuum;
68.235 + rc = sqlite3BtreeCommit(pTemp);
68.236 + if( rc!=SQLITE_OK ) goto end_of_vacuum;
68.237 + rc = sqlite3BtreeCommit(pMain);
68.238 + }
68.239 +
68.240 +end_of_vacuum:
68.241 + /* Restore the original value of db->flags */
68.242 + db->flags = saved_flags;
68.243 +
68.244 + /* Currently there is an SQL level transaction open on the vacuum
68.245 + ** database. No locks are held on any other files (since the main file
68.246 + ** was committed at the btree level). So it safe to end the transaction
68.247 + ** by manually setting the autoCommit flag to true and detaching the
68.248 + ** vacuum database. The vacuum_db journal file is deleted when the pager
68.249 + ** is closed by the DETACH.
68.250 + */
68.251 + db->autoCommit = 1;
68.252 +
68.253 + if( pDb ){
68.254 + sqlite3MallocDisallow();
68.255 + sqlite3BtreeClose(pDb->pBt);
68.256 + sqlite3MallocAllow();
68.257 + pDb->pBt = 0;
68.258 + pDb->pSchema = 0;
68.259 + }
68.260 +
68.261 + sqlite3ResetInternalSchema(db, 0);
68.262 +
68.263 + return rc;
68.264 +}
68.265 +#endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
69.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
69.2 +++ b/extensions/sqlite/sqlite-source/vdbe.c Sun Jul 29 01:15:31 2007 +0000
69.3 @@ -0,0 +1,5225 @@
69.4 +/*
69.5 +** 2001 September 15
69.6 +**
69.7 +** The author disclaims copyright to this source code. In place of
69.8 +** a legal notice, here is a blessing:
69.9 +**
69.10 +** May you do good and not evil.
69.11 +** May you find forgiveness for yourself and forgive others.
69.12 +** May you share freely, never taking more than you give.
69.13 +**
69.14 +*************************************************************************
69.15 +** The code in this file implements execution method of the
69.16 +** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
69.17 +** handles housekeeping details such as creating and deleting
69.18 +** VDBE instances. This file is solely interested in executing
69.19 +** the VDBE program.
69.20 +**
69.21 +** In the external interface, an "sqlite3_stmt*" is an opaque pointer
69.22 +** to a VDBE.
69.23 +**
69.24 +** The SQL parser generates a program which is then executed by
69.25 +** the VDBE to do the work of the SQL statement. VDBE programs are
69.26 +** similar in form to assembly language. The program consists of
69.27 +** a linear sequence of operations. Each operation has an opcode
69.28 +** and 3 operands. Operands P1 and P2 are integers. Operand P3
69.29 +** is a null-terminated string. The P2 operand must be non-negative.
69.30 +** Opcodes will typically ignore one or more operands. Many opcodes
69.31 +** ignore all three operands.
69.32 +**
69.33 +** Computation results are stored on a stack. Each entry on the
69.34 +** stack is either an integer, a null-terminated string, a floating point
69.35 +** number, or the SQL "NULL" value. An inplicit conversion from one
69.36 +** type to the other occurs as necessary.
69.37 +**
69.38 +** Most of the code in this file is taken up by the sqlite3VdbeExec()
69.39 +** function which does the work of interpreting a VDBE program.
69.40 +** But other routines are also provided to help in building up
69.41 +** a program instruction by instruction.
69.42 +**
69.43 +** Various scripts scan this source file in order to generate HTML
69.44 +** documentation, headers files, or other derived files. The formatting
69.45 +** of the code in this file is, therefore, important. See other comments
69.46 +** in this file for details. If in doubt, do not deviate from existing
69.47 +** commenting and indentation practices when changing or adding code.
69.48 +**
69.49 +** $Id$
69.50 +*/
69.51 +#include "sqliteInt.h"
69.52 +#include "os.h"
69.53 +#include <ctype.h>
69.54 +#include <math.h>
69.55 +#include "vdbeInt.h"
69.56 +
69.57 +/*
69.58 +** The following global variable is incremented every time a cursor
69.59 +** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes. The test
69.60 +** procedures use this information to make sure that indices are
69.61 +** working correctly. This variable has no function other than to
69.62 +** help verify the correct operation of the library.
69.63 +*/
69.64 +#ifdef SQLITE_TEST
69.65 +int sqlite3_search_count = 0;
69.66 +#endif
69.67 +
69.68 +/*
69.69 +** When this global variable is positive, it gets decremented once before
69.70 +** each instruction in the VDBE. When reaches zero, the u1.isInterrupted
69.71 +** field of the sqlite3 structure is set in order to simulate and interrupt.
69.72 +**
69.73 +** This facility is used for testing purposes only. It does not function
69.74 +** in an ordinary build.
69.75 +*/
69.76 +#ifdef SQLITE_TEST
69.77 +int sqlite3_interrupt_count = 0;
69.78 +#endif
69.79 +
69.80 +/*
69.81 +** The next global variable is incremented each type the OP_Sort opcode
69.82 +** is executed. The test procedures use this information to make sure that
69.83 +** sorting is occurring or not occuring at appropriate times. This variable
69.84 +** has no function other than to help verify the correct operation of the
69.85 +** library.
69.86 +*/
69.87 +#ifdef SQLITE_TEST
69.88 +int sqlite3_sort_count = 0;
69.89 +#endif
69.90 +
69.91 +/*
69.92 +** The next global variable records the size of the largest MEM_Blob
69.93 +** or MEM_Str that has appeared on the VDBE stack. The test procedures
69.94 +** use this information to make sure that the zero-blob functionality
69.95 +** is working correctly. This variable has no function other than to
69.96 +** help verify the correct operation of the library.
69.97 +*/
69.98 +#ifdef SQLITE_TEST
69.99 +int sqlite3_max_blobsize = 0;
69.100 +#endif
69.101 +
69.102 +/*
69.103 +** Release the memory associated with the given stack level. This
69.104 +** leaves the Mem.flags field in an inconsistent state.
69.105 +*/
69.106 +#define Release(P) if((P)->flags&MEM_Dyn){ sqlite3VdbeMemRelease(P); }
69.107 +
69.108 +/*
69.109 +** Convert the given stack entity into a string if it isn't one
69.110 +** already. Return non-zero if a malloc() fails.
69.111 +*/
69.112 +#define Stringify(P, enc) \
69.113 + if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
69.114 + { goto no_mem; }
69.115 +
69.116 +/*
69.117 +** Convert the given stack entity into a string that has been obtained
69.118 +** from sqliteMalloc(). This is different from Stringify() above in that
69.119 +** Stringify() will use the NBFS bytes of static string space if the string
69.120 +** will fit but this routine always mallocs for space.
69.121 +** Return non-zero if we run out of memory.
69.122 +*/
69.123 +#define Dynamicify(P,enc) sqlite3VdbeMemDynamicify(P)
69.124 +
69.125 +/*
69.126 +** The header of a record consists of a sequence variable-length integers.
69.127 +** These integers are almost always small and are encoded as a single byte.
69.128 +** The following macro takes advantage this fact to provide a fast decode
69.129 +** of the integers in a record header. It is faster for the common case
69.130 +** where the integer is a single byte. It is a little slower when the
69.131 +** integer is two or more bytes. But overall it is faster.
69.132 +**
69.133 +** The following expressions are equivalent:
69.134 +**
69.135 +** x = sqlite3GetVarint32( A, &B );
69.136 +**
69.137 +** x = GetVarint( A, B );
69.138 +**
69.139 +*/
69.140 +#define GetVarint(A,B) ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
69.141 +
69.142 +/*
69.143 +** An ephemeral string value (signified by the MEM_Ephem flag) contains
69.144 +** a pointer to a dynamically allocated string where some other entity
69.145 +** is responsible for deallocating that string. Because the stack entry
69.146 +** does not control the string, it might be deleted without the stack
69.147 +** entry knowing it.
69.148 +**
69.149 +** This routine converts an ephemeral string into a dynamically allocated
69.150 +** string that the stack entry itself controls. In other words, it
69.151 +** converts an MEM_Ephem string into an MEM_Dyn string.
69.152 +*/
69.153 +#define Deephemeralize(P) \
69.154 + if( ((P)->flags&MEM_Ephem)!=0 \
69.155 + && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
69.156 +
69.157 +/*
69.158 +** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
69.159 +** P if required.
69.160 +*/
69.161 +#define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
69.162 +
69.163 +/*
69.164 +** Argument pMem points at a memory cell that will be passed to a
69.165 +** user-defined function or returned to the user as the result of a query.
69.166 +** The second argument, 'db_enc' is the text encoding used by the vdbe for
69.167 +** stack variables. This routine sets the pMem->enc and pMem->type
69.168 +** variables used by the sqlite3_value_*() routines.
69.169 +*/
69.170 +#define storeTypeInfo(A,B) _storeTypeInfo(A)
69.171 +static void _storeTypeInfo(Mem *pMem){
69.172 + int flags = pMem->flags;
69.173 + if( flags & MEM_Null ){
69.174 + pMem->type = SQLITE_NULL;
69.175 + }
69.176 + else if( flags & MEM_Int ){
69.177 + pMem->type = SQLITE_INTEGER;
69.178 + }
69.179 + else if( flags & MEM_Real ){
69.180 + pMem->type = SQLITE_FLOAT;
69.181 + }
69.182 + else if( flags & MEM_Str ){
69.183 + pMem->type = SQLITE_TEXT;
69.184 + }else{
69.185 + pMem->type = SQLITE_BLOB;
69.186 + }
69.187 +}
69.188 +
69.189 +/*
69.190 +** Pop the stack N times.
69.191 +*/
69.192 +static void popStack(Mem **ppTos, int N){
69.193 + Mem *pTos = *ppTos;
69.194 + while( N>0 ){
69.195 + N--;
69.196 + Release(pTos);
69.197 + pTos--;
69.198 + }
69.199 + *ppTos = pTos;
69.200 +}
69.201 +
69.202 +/*
69.203 +** Allocate cursor number iCur. Return a pointer to it. Return NULL
69.204 +** if we run out of memory.
69.205 +*/
69.206 +static Cursor *allocateCursor(Vdbe *p, int iCur, int iDb){
69.207 + Cursor *pCx;
69.208 + assert( iCur<p->nCursor );
69.209 + if( p->apCsr[iCur] ){
69.210 + sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
69.211 + }
69.212 + p->apCsr[iCur] = pCx = sqliteMalloc( sizeof(Cursor) );
69.213 + if( pCx ){
69.214 + pCx->iDb = iDb;
69.215 + }
69.216 + return pCx;
69.217 +}
69.218 +
69.219 +/*
69.220 +** Try to convert a value into a numeric representation if we can
69.221 +** do so without loss of information. In other words, if the string
69.222 +** looks like a number, convert it into a number. If it does not
69.223 +** look like a number, leave it alone.
69.224 +*/
69.225 +static void applyNumericAffinity(Mem *pRec){
69.226 + if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
69.227 + int realnum;
69.228 + sqlite3VdbeMemNulTerminate(pRec);
69.229 + if( (pRec->flags&MEM_Str)
69.230 + && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
69.231 + i64 value;
69.232 + sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
69.233 + if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
69.234 + sqlite3VdbeMemRelease(pRec);
69.235 + pRec->u.i = value;
69.236 + pRec->flags = MEM_Int;
69.237 + }else{
69.238 + sqlite3VdbeMemRealify(pRec);
69.239 + }
69.240 + }
69.241 + }
69.242 +}
69.243 +
69.244 +/*
69.245 +** Processing is determine by the affinity parameter:
69.246 +**
69.247 +** SQLITE_AFF_INTEGER:
69.248 +** SQLITE_AFF_REAL:
69.249 +** SQLITE_AFF_NUMERIC:
69.250 +** Try to convert pRec to an integer representation or a
69.251 +** floating-point representation if an integer representation
69.252 +** is not possible. Note that the integer representation is
69.253 +** always preferred, even if the affinity is REAL, because
69.254 +** an integer representation is more space efficient on disk.
69.255 +**
69.256 +** SQLITE_AFF_TEXT:
69.257 +** Convert pRec to a text representation.
69.258 +**
69.259 +** SQLITE_AFF_NONE:
69.260 +** No-op. pRec is unchanged.
69.261 +*/
69.262 +static void applyAffinity(Mem *pRec, char affinity, u8 enc){
69.263 + if( affinity==SQLITE_AFF_TEXT ){
69.264 + /* Only attempt the conversion to TEXT if there is an integer or real
69.265 + ** representation (blob and NULL do not get converted) but no string
69.266 + ** representation.
69.267 + */
69.268 + if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
69.269 + sqlite3VdbeMemStringify(pRec, enc);
69.270 + }
69.271 + pRec->flags &= ~(MEM_Real|MEM_Int);
69.272 + }else if( affinity!=SQLITE_AFF_NONE ){
69.273 + assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
69.274 + || affinity==SQLITE_AFF_NUMERIC );
69.275 + applyNumericAffinity(pRec);
69.276 + if( pRec->flags & MEM_Real ){
69.277 + sqlite3VdbeIntegerAffinity(pRec);
69.278 + }
69.279 + }
69.280 +}
69.281 +
69.282 +/*
69.283 +** Try to convert the type of a function argument or a result column
69.284 +** into a numeric representation. Use either INTEGER or REAL whichever
69.285 +** is appropriate. But only do the conversion if it is possible without
69.286 +** loss of information and return the revised type of the argument.
69.287 +**
69.288 +** This is an EXPERIMENTAL api and is subject to change or removal.
69.289 +*/
69.290 +int sqlite3_value_numeric_type(sqlite3_value *pVal){
69.291 + Mem *pMem = (Mem*)pVal;
69.292 + applyNumericAffinity(pMem);
69.293 + storeTypeInfo(pMem, 0);
69.294 + return pMem->type;
69.295 +}
69.296 +
69.297 +/*
69.298 +** Exported version of applyAffinity(). This one works on sqlite3_value*,
69.299 +** not the internal Mem* type.
69.300 +*/
69.301 +void sqlite3ValueApplyAffinity(sqlite3_value *pVal, u8 affinity, u8 enc){
69.302 + applyAffinity((Mem *)pVal, affinity, enc);
69.303 +}
69.304 +
69.305 +#ifdef SQLITE_DEBUG
69.306 +/*
69.307 +** Write a nice string representation of the contents of cell pMem
69.308 +** into buffer zBuf, length nBuf.
69.309 +*/
69.310 +void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
69.311 + char *zCsr = zBuf;
69.312 + int f = pMem->flags;
69.313 +
69.314 + static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
69.315 +
69.316 + if( f&MEM_Blob ){
69.317 + int i;
69.318 + char c;
69.319 + if( f & MEM_Dyn ){
69.320 + c = 'z';
69.321 + assert( (f & (MEM_Static|MEM_Ephem))==0 );
69.322 + }else if( f & MEM_Static ){
69.323 + c = 't';
69.324 + assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
69.325 + }else if( f & MEM_Ephem ){
69.326 + c = 'e';
69.327 + assert( (f & (MEM_Static|MEM_Dyn))==0 );
69.328 + }else{
69.329 + c = 's';
69.330 + }
69.331 +
69.332 + sqlite3_snprintf(100, zCsr, "%c", c);
69.333 + zCsr += strlen(zCsr);
69.334 + sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
69.335 + zCsr += strlen(zCsr);
69.336 + for(i=0; i<16 && i<pMem->n; i++){
69.337 + sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
69.338 + zCsr += strlen(zCsr);
69.339 + }
69.340 + for(i=0; i<16 && i<pMem->n; i++){
69.341 + char z = pMem->z[i];
69.342 + if( z<32 || z>126 ) *zCsr++ = '.';
69.343 + else *zCsr++ = z;
69.344 + }
69.345 +
69.346 + sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
69.347 + zCsr += strlen(zCsr);
69.348 + if( f & MEM_Zero ){
69.349 + sqlite3_snprintf(100, zCsr,"+%lldz",pMem->u.i);
69.350 + zCsr += strlen(zCsr);
69.351 + }
69.352 + *zCsr = '\0';
69.353 + }else if( f & MEM_Str ){
69.354 + int j, k;
69.355 + zBuf[0] = ' ';
69.356 + if( f & MEM_Dyn ){
69.357 + zBuf[1] = 'z';
69.358 + assert( (f & (MEM_Static|MEM_Ephem))==0 );
69.359 + }else if( f & MEM_Static ){
69.360 + zBuf[1] = 't';
69.361 + assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
69.362 + }else if( f & MEM_Ephem ){
69.363 + zBuf[1] = 'e';
69.364 + assert( (f & (MEM_Static|MEM_Dyn))==0 );
69.365 + }else{
69.366 + zBuf[1] = 's';
69.367 + }
69.368 + k = 2;
69.369 + sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
69.370 + k += strlen(&zBuf[k]);
69.371 + zBuf[k++] = '[';
69.372 + for(j=0; j<15 && j<pMem->n; j++){
69.373 + u8 c = pMem->z[j];
69.374 + if( c>=0x20 && c<0x7f ){
69.375 + zBuf[k++] = c;
69.376 + }else{
69.377 + zBuf[k++] = '.';
69.378 + }
69.379 + }
69.380 + zBuf[k++] = ']';
69.381 + sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
69.382 + k += strlen(&zBuf[k]);
69.383 + zBuf[k++] = 0;
69.384 + }
69.385 +}
69.386 +#endif
69.387 +
69.388 +
69.389 +#ifdef VDBE_PROFILE
69.390 +/*
69.391 +** The following routine only works on pentium-class processors.
69.392 +** It uses the RDTSC opcode to read the cycle count value out of the
69.393 +** processor and returns that value. This can be used for high-res
69.394 +** profiling.
69.395 +*/
69.396 +__inline__ unsigned long long int hwtime(void){
69.397 + unsigned long long int x;
69.398 + __asm__("rdtsc\n\t"
69.399 + "mov %%edx, %%ecx\n\t"
69.400 + :"=A" (x));
69.401 + return x;
69.402 +}
69.403 +#endif
69.404 +
69.405 +/*
69.406 +** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
69.407 +** sqlite3_interrupt() routine has been called. If it has been, then
69.408 +** processing of the VDBE program is interrupted.
69.409 +**
69.410 +** This macro added to every instruction that does a jump in order to
69.411 +** implement a loop. This test used to be on every single instruction,
69.412 +** but that meant we more testing that we needed. By only testing the
69.413 +** flag on jump instructions, we get a (small) speed improvement.
69.414 +*/
69.415 +#define CHECK_FOR_INTERRUPT \
69.416 + if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
69.417 +
69.418 +
69.419 +/*
69.420 +** Execute as much of a VDBE program as we can then return.
69.421 +**
69.422 +** sqlite3VdbeMakeReady() must be called before this routine in order to
69.423 +** close the program with a final OP_Halt and to set up the callbacks
69.424 +** and the error message pointer.
69.425 +**
69.426 +** Whenever a row or result data is available, this routine will either
69.427 +** invoke the result callback (if there is one) or return with
69.428 +** SQLITE_ROW.
69.429 +**
69.430 +** If an attempt is made to open a locked database, then this routine
69.431 +** will either invoke the busy callback (if there is one) or it will
69.432 +** return SQLITE_BUSY.
69.433 +**
69.434 +** If an error occurs, an error message is written to memory obtained
69.435 +** from sqliteMalloc() and p->zErrMsg is made to point to that memory.
69.436 +** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
69.437 +**
69.438 +** If the callback ever returns non-zero, then the program exits
69.439 +** immediately. There will be no error message but the p->rc field is
69.440 +** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
69.441 +**
69.442 +** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
69.443 +** routine to return SQLITE_ERROR.
69.444 +**
69.445 +** Other fatal errors return SQLITE_ERROR.
69.446 +**
69.447 +** After this routine has finished, sqlite3VdbeFinalize() should be
69.448 +** used to clean up the mess that was left behind.
69.449 +*/
69.450 +int sqlite3VdbeExec(
69.451 + Vdbe *p /* The VDBE */
69.452 +){
69.453 + int pc; /* The program counter */
69.454 + Op *pOp; /* Current operation */
69.455 + int rc = SQLITE_OK; /* Value to return */
69.456 + sqlite3 *db = p->db; /* The database */
69.457 + u8 encoding = ENC(db); /* The database encoding */
69.458 + Mem *pTos; /* Top entry in the operand stack */
69.459 +#ifdef VDBE_PROFILE
69.460 + unsigned long long start; /* CPU clock count at start of opcode */
69.461 + int origPc; /* Program counter at start of opcode */
69.462 +#endif
69.463 +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
69.464 + int nProgressOps = 0; /* Opcodes executed since progress callback. */
69.465 +#endif
69.466 +#ifndef NDEBUG
69.467 + Mem *pStackLimit;
69.468 +#endif
69.469 +
69.470 + if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
69.471 + assert( db->magic==SQLITE_MAGIC_BUSY );
69.472 + pTos = p->pTos;
69.473 + if( p->rc==SQLITE_NOMEM ){
69.474 + /* This happens if a malloc() inside a call to sqlite3_column_text() or
69.475 + ** sqlite3_column_text16() failed. */
69.476 + goto no_mem;
69.477 + }
69.478 + assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
69.479 + p->rc = SQLITE_OK;
69.480 + assert( p->explain==0 );
69.481 + if( p->popStack ){
69.482 + popStack(&pTos, p->popStack);
69.483 + p->popStack = 0;
69.484 + }
69.485 + p->resOnStack = 0;
69.486 + db->busyHandler.nBusy = 0;
69.487 + CHECK_FOR_INTERRUPT;
69.488 + sqlite3VdbeIOTraceSql(p);
69.489 +#ifdef SQLITE_DEBUG
69.490 + if( (p->db->flags & SQLITE_VdbeListing)!=0
69.491 + || sqlite3OsFileExists("vdbe_explain")
69.492 + ){
69.493 + int i;
69.494 + printf("VDBE Program Listing:\n");
69.495 + sqlite3VdbePrintSql(p);
69.496 + for(i=0; i<p->nOp; i++){
69.497 + sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
69.498 + }
69.499 + }
69.500 + if( sqlite3OsFileExists("vdbe_trace") ){
69.501 + p->trace = stdout;
69.502 + }
69.503 +#endif
69.504 + for(pc=p->pc; rc==SQLITE_OK; pc++){
69.505 + assert( pc>=0 && pc<p->nOp );
69.506 + assert( pTos<=&p->aStack[pc] );
69.507 + if( sqlite3MallocFailed() ) goto no_mem;
69.508 +#ifdef VDBE_PROFILE
69.509 + origPc = pc;
69.510 + start = hwtime();
69.511 +#endif
69.512 + pOp = &p->aOp[pc];
69.513 +
69.514 + /* Only allow tracing if SQLITE_DEBUG is defined.
69.515 + */
69.516 +#ifdef SQLITE_DEBUG
69.517 + if( p->trace ){
69.518 + if( pc==0 ){
69.519 + printf("VDBE Execution Trace:\n");
69.520 + sqlite3VdbePrintSql(p);
69.521 + }
69.522 + sqlite3VdbePrintOp(p->trace, pc, pOp);
69.523 + }
69.524 + if( p->trace==0 && pc==0 && sqlite3OsFileExists("vdbe_sqltrace") ){
69.525 + sqlite3VdbePrintSql(p);
69.526 + }
69.527 +#endif
69.528 +
69.529 +
69.530 + /* Check to see if we need to simulate an interrupt. This only happens
69.531 + ** if we have a special test build.
69.532 + */
69.533 +#ifdef SQLITE_TEST
69.534 + if( sqlite3_interrupt_count>0 ){
69.535 + sqlite3_interrupt_count--;
69.536 + if( sqlite3_interrupt_count==0 ){
69.537 + sqlite3_interrupt(db);
69.538 + }
69.539 + }
69.540 +#endif
69.541 +
69.542 +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
69.543 + /* Call the progress callback if it is configured and the required number
69.544 + ** of VDBE ops have been executed (either since this invocation of
69.545 + ** sqlite3VdbeExec() or since last time the progress callback was called).
69.546 + ** If the progress callback returns non-zero, exit the virtual machine with
69.547 + ** a return code SQLITE_ABORT.
69.548 + */
69.549 + if( db->xProgress ){
69.550 + if( db->nProgressOps==nProgressOps ){
69.551 + int prc;
69.552 + if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
69.553 + prc =db->xProgress(db->pProgressArg);
69.554 + if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
69.555 + if( prc!=0 ){
69.556 + rc = SQLITE_INTERRUPT;
69.557 + goto vdbe_halt;
69.558 + }
69.559 + nProgressOps = 0;
69.560 + }
69.561 + nProgressOps++;
69.562 + }
69.563 +#endif
69.564 +
69.565 +#ifndef NDEBUG
69.566 + /* This is to check that the return value of static function
69.567 + ** opcodeNoPush() (see vdbeaux.c) returns values that match the
69.568 + ** implementation of the virtual machine in this file. If
69.569 + ** opcodeNoPush() returns non-zero, then the stack is guarenteed
69.570 + ** not to grow when the opcode is executed. If it returns zero, then
69.571 + ** the stack may grow by at most 1.
69.572 + **
69.573 + ** The global wrapper function sqlite3VdbeOpcodeUsesStack() is not
69.574 + ** available if NDEBUG is defined at build time.
69.575 + */
69.576 + pStackLimit = pTos;
69.577 + if( !sqlite3VdbeOpcodeNoPush(pOp->opcode) ){
69.578 + pStackLimit++;
69.579 + }
69.580 +#endif
69.581 +
69.582 + switch( pOp->opcode ){
69.583 +
69.584 +/*****************************************************************************
69.585 +** What follows is a massive switch statement where each case implements a
69.586 +** separate instruction in the virtual machine. If we follow the usual
69.587 +** indentation conventions, each case should be indented by 6 spaces. But
69.588 +** that is a lot of wasted space on the left margin. So the code within
69.589 +** the switch statement will break with convention and be flush-left. Another
69.590 +** big comment (similar to this one) will mark the point in the code where
69.591 +** we transition back to normal indentation.
69.592 +**
69.593 +** The formatting of each case is important. The makefile for SQLite
69.594 +** generates two C files "opcodes.h" and "opcodes.c" by scanning this
69.595 +** file looking for lines that begin with "case OP_". The opcodes.h files
69.596 +** will be filled with #defines that give unique integer values to each
69.597 +** opcode and the opcodes.c file is filled with an array of strings where
69.598 +** each string is the symbolic name for the corresponding opcode. If the
69.599 +** case statement is followed by a comment of the form "/# same as ... #/"
69.600 +** that comment is used to determine the particular value of the opcode.
69.601 +**
69.602 +** If a comment on the same line as the "case OP_" construction contains
69.603 +** the word "no-push", then the opcode is guarenteed not to grow the
69.604 +** vdbe stack when it is executed. See function opcode() in
69.605 +** vdbeaux.c for details.
69.606 +**
69.607 +** Documentation about VDBE opcodes is generated by scanning this file
69.608 +** for lines of that contain "Opcode:". That line and all subsequent
69.609 +** comment lines are used in the generation of the opcode.html documentation
69.610 +** file.
69.611 +**
69.612 +** SUMMARY:
69.613 +**
69.614 +** Formatting is important to scripts that scan this file.
69.615 +** Do not deviate from the formatting style currently in use.
69.616 +**
69.617 +*****************************************************************************/
69.618 +
69.619 +/* Opcode: Goto * P2 *
69.620 +**
69.621 +** An unconditional jump to address P2.
69.622 +** The next instruction executed will be
69.623 +** the one at index P2 from the beginning of
69.624 +** the program.
69.625 +*/
69.626 +case OP_Goto: { /* no-push */
69.627 + CHECK_FOR_INTERRUPT;
69.628 + pc = pOp->p2 - 1;
69.629 + break;
69.630 +}
69.631 +
69.632 +/* Opcode: Gosub * P2 *
69.633 +**
69.634 +** Push the current address plus 1 onto the return address stack
69.635 +** and then jump to address P2.
69.636 +**
69.637 +** The return address stack is of limited depth. If too many
69.638 +** OP_Gosub operations occur without intervening OP_Returns, then
69.639 +** the return address stack will fill up and processing will abort
69.640 +** with a fatal error.
69.641 +*/
69.642 +case OP_Gosub: { /* no-push */
69.643 + assert( p->returnDepth<sizeof(p->returnStack)/sizeof(p->returnStack[0]) );
69.644 + p->returnStack[p->returnDepth++] = pc+1;
69.645 + pc = pOp->p2 - 1;
69.646 + break;
69.647 +}
69.648 +
69.649 +/* Opcode: Return * * *
69.650 +**
69.651 +** Jump immediately to the next instruction after the last unreturned
69.652 +** OP_Gosub. If an OP_Return has occurred for all OP_Gosubs, then
69.653 +** processing aborts with a fatal error.
69.654 +*/
69.655 +case OP_Return: { /* no-push */
69.656 + assert( p->returnDepth>0 );
69.657 + p->returnDepth--;
69.658 + pc = p->returnStack[p->returnDepth] - 1;
69.659 + break;
69.660 +}
69.661 +
69.662 +/* Opcode: Halt P1 P2 P3
69.663 +**
69.664 +** Exit immediately. All open cursors, Fifos, etc are closed
69.665 +** automatically.
69.666 +**
69.667 +** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
69.668 +** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
69.669 +** For errors, it can be some other value. If P1!=0 then P2 will determine
69.670 +** whether or not to rollback the current transaction. Do not rollback
69.671 +** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
69.672 +** then back out all changes that have occurred during this execution of the
69.673 +** VDBE, but do not rollback the transaction.
69.674 +**
69.675 +** If P3 is not null then it is an error message string.
69.676 +**
69.677 +** There is an implied "Halt 0 0 0" instruction inserted at the very end of
69.678 +** every program. So a jump past the last instruction of the program
69.679 +** is the same as executing Halt.
69.680 +*/
69.681 +case OP_Halt: { /* no-push */
69.682 + p->pTos = pTos;
69.683 + p->rc = pOp->p1;
69.684 + p->pc = pc;
69.685 + p->errorAction = pOp->p2;
69.686 + if( pOp->p3 ){
69.687 + sqlite3SetString(&p->zErrMsg, pOp->p3, (char*)0);
69.688 + }
69.689 + rc = sqlite3VdbeHalt(p);
69.690 + assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
69.691 + if( rc==SQLITE_BUSY ){
69.692 + p->rc = SQLITE_BUSY;
69.693 + return SQLITE_BUSY;
69.694 + }
69.695 + return p->rc ? SQLITE_ERROR : SQLITE_DONE;
69.696 +}
69.697 +
69.698 +/* Opcode: Integer P1 * *
69.699 +**
69.700 +** The 32-bit integer value P1 is pushed onto the stack.
69.701 +*/
69.702 +case OP_Integer: {
69.703 + pTos++;
69.704 + pTos->flags = MEM_Int;
69.705 + pTos->u.i = pOp->p1;
69.706 + break;
69.707 +}
69.708 +
69.709 +/* Opcode: Int64 * * P3
69.710 +**
69.711 +** P3 is a string representation of an integer. Convert that integer
69.712 +** to a 64-bit value and push it onto the stack.
69.713 +*/
69.714 +case OP_Int64: {
69.715 + pTos++;
69.716 + assert( pOp->p3!=0 );
69.717 + pTos->flags = MEM_Str|MEM_Static|MEM_Term;
69.718 + pTos->z = pOp->p3;
69.719 + pTos->n = strlen(pTos->z);
69.720 + pTos->enc = SQLITE_UTF8;
69.721 + pTos->u.i = sqlite3VdbeIntValue(pTos);
69.722 + pTos->flags |= MEM_Int;
69.723 + break;
69.724 +}
69.725 +
69.726 +/* Opcode: Real * * P3
69.727 +**
69.728 +** The string value P3 is converted to a real and pushed on to the stack.
69.729 +*/
69.730 +case OP_Real: { /* same as TK_FLOAT, */
69.731 + pTos++;
69.732 + pTos->flags = MEM_Str|MEM_Static|MEM_Term;
69.733 + pTos->z = pOp->p3;
69.734 + pTos->n = strlen(pTos->z);
69.735 + pTos->enc = SQLITE_UTF8;
69.736 + pTos->r = sqlite3VdbeRealValue(pTos);
69.737 + pTos->flags |= MEM_Real;
69.738 + sqlite3VdbeChangeEncoding(pTos, encoding);
69.739 + break;
69.740 +}
69.741 +
69.742 +/* Opcode: String8 * * P3
69.743 +**
69.744 +** P3 points to a nul terminated UTF-8 string. This opcode is transformed
69.745 +** into an OP_String before it is executed for the first time.
69.746 +*/
69.747 +case OP_String8: { /* same as TK_STRING */
69.748 + assert( pOp->p3!=0 );
69.749 + pOp->opcode = OP_String;
69.750 + pOp->p1 = strlen(pOp->p3);
69.751 + assert( SQLITE_MAX_SQL_LENGTH < SQLITE_MAX_LENGTH );
69.752 + assert( pOp->p1 < SQLITE_MAX_LENGTH );
69.753 +
69.754 +#ifndef SQLITE_OMIT_UTF16
69.755 + if( encoding!=SQLITE_UTF8 ){
69.756 + pTos++;
69.757 + sqlite3VdbeMemSetStr(pTos, pOp->p3, -1, SQLITE_UTF8, SQLITE_STATIC);
69.758 + if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pTos, encoding) ) goto no_mem;
69.759 + if( SQLITE_OK!=sqlite3VdbeMemDynamicify(pTos) ) goto no_mem;
69.760 + pTos->flags &= ~(MEM_Dyn);
69.761 + pTos->flags |= MEM_Static;
69.762 + if( pOp->p3type==P3_DYNAMIC ){
69.763 + sqliteFree(pOp->p3);
69.764 + }
69.765 + pOp->p3type = P3_DYNAMIC;
69.766 + pOp->p3 = pTos->z;
69.767 + pOp->p1 = pTos->n;
69.768 + assert( pOp->p1 < SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
69.769 + break;
69.770 + }
69.771 +#endif
69.772 + /* Otherwise fall through to the next case, OP_String */
69.773 +}
69.774 +
69.775 +/* Opcode: String P1 * P3
69.776 +**
69.777 +** The string value P3 of length P1 (bytes) is pushed onto the stack.
69.778 +*/
69.779 +case OP_String: {
69.780 + assert( pOp->p1 < SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
69.781 + pTos++;
69.782 + assert( pOp->p3!=0 );
69.783 + pTos->flags = MEM_Str|MEM_Static|MEM_Term;
69.784 + pTos->z = pOp->p3;
69.785 + pTos->n = pOp->p1;
69.786 + pTos->enc = encoding;
69.787 + break;
69.788 +}
69.789 +
69.790 +/* Opcode: Null * * *
69.791 +**
69.792 +** Push a NULL onto the stack.
69.793 +*/
69.794 +case OP_Null: {
69.795 + pTos++;
69.796 + pTos->flags = MEM_Null;
69.797 + pTos->n = 0;
69.798 + break;
69.799 +}
69.800 +
69.801 +
69.802 +#ifndef SQLITE_OMIT_BLOB_LITERAL
69.803 +/* Opcode: HexBlob * * P3
69.804 +**
69.805 +** P3 is an UTF-8 SQL hex encoding of a blob. The blob is pushed onto the
69.806 +** vdbe stack.
69.807 +**
69.808 +** The first time this instruction executes, in transforms itself into a
69.809 +** 'Blob' opcode with a binary blob as P3.
69.810 +*/
69.811 +case OP_HexBlob: { /* same as TK_BLOB */
69.812 + pOp->opcode = OP_Blob;
69.813 + pOp->p1 = strlen(pOp->p3)/2;
69.814 + assert( SQLITE_MAX_SQL_LENGTH < SQLITE_MAX_LENGTH );
69.815 + assert( pOp->p1 < SQLITE_MAX_LENGTH );
69.816 + if( pOp->p1 ){
69.817 + char *zBlob = sqlite3HexToBlob(pOp->p3);
69.818 + if( !zBlob ) goto no_mem;
69.819 + if( pOp->p3type==P3_DYNAMIC ){
69.820 + sqliteFree(pOp->p3);
69.821 + }
69.822 + pOp->p3 = zBlob;
69.823 + pOp->p3type = P3_DYNAMIC;
69.824 + }else{
69.825 + if( pOp->p3type==P3_DYNAMIC ){
69.826 + sqliteFree(pOp->p3);
69.827 + }
69.828 + pOp->p3type = P3_STATIC;
69.829 + pOp->p3 = "";
69.830 + }
69.831 +
69.832 + /* Fall through to the next case, OP_Blob. */
69.833 +}
69.834 +
69.835 +/* Opcode: Blob P1 * P3
69.836 +**
69.837 +** P3 points to a blob of data P1 bytes long. Push this
69.838 +** value onto the stack. This instruction is not coded directly
69.839 +** by the compiler. Instead, the compiler layer specifies
69.840 +** an OP_HexBlob opcode, with the hex string representation of
69.841 +** the blob as P3. This opcode is transformed to an OP_Blob
69.842 +** the first time it is executed.
69.843 +*/
69.844 +case OP_Blob: {
69.845 + pTos++;
69.846 + assert( pOp->p1 < SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
69.847 + sqlite3VdbeMemSetStr(pTos, pOp->p3, pOp->p1, 0, 0);
69.848 + pTos->enc = encoding;
69.849 + break;
69.850 +}
69.851 +#endif /* SQLITE_OMIT_BLOB_LITERAL */
69.852 +
69.853 +/* Opcode: Variable P1 * *
69.854 +**
69.855 +** Push the value of variable P1 onto the stack. A variable is
69.856 +** an unknown in the original SQL string as handed to sqlite3_compile().
69.857 +** Any occurance of the '?' character in the original SQL is considered
69.858 +** a variable. Variables in the SQL string are number from left to
69.859 +** right beginning with 1. The values of variables are set using the
69.860 +** sqlite3_bind() API.
69.861 +*/
69.862 +case OP_Variable: {
69.863 + int j = pOp->p1 - 1;
69.864 + Mem *pVar;
69.865 + assert( j>=0 && j<p->nVar );
69.866 +
69.867 + pVar = &p->aVar[j];
69.868 + if( sqlite3VdbeMemTooBig(pVar) ){
69.869 + goto too_big;
69.870 + }
69.871 + pTos++;
69.872 + sqlite3VdbeMemShallowCopy(pTos, &p->aVar[j], MEM_Static);
69.873 + break;
69.874 +}
69.875 +
69.876 +/* Opcode: Pop P1 * *
69.877 +**
69.878 +** P1 elements are popped off of the top of stack and discarded.
69.879 +*/
69.880 +case OP_Pop: { /* no-push */
69.881 + assert( pOp->p1>=0 );
69.882 + popStack(&pTos, pOp->p1);
69.883 + assert( pTos>=&p->aStack[-1] );
69.884 + break;
69.885 +}
69.886 +
69.887 +/* Opcode: Dup P1 P2 *
69.888 +**
69.889 +** A copy of the P1-th element of the stack
69.890 +** is made and pushed onto the top of the stack.
69.891 +** The top of the stack is element 0. So the
69.892 +** instruction "Dup 0 0 0" will make a copy of the
69.893 +** top of the stack.
69.894 +**
69.895 +** If the content of the P1-th element is a dynamically
69.896 +** allocated string, then a new copy of that string
69.897 +** is made if P2==0. If P2!=0, then just a pointer
69.898 +** to the string is copied.
69.899 +**
69.900 +** Also see the Pull instruction.
69.901 +*/
69.902 +case OP_Dup: {
69.903 + Mem *pFrom = &pTos[-pOp->p1];
69.904 + assert( pFrom<=pTos && pFrom>=p->aStack );
69.905 + pTos++;
69.906 + sqlite3VdbeMemShallowCopy(pTos, pFrom, MEM_Ephem);
69.907 + if( pOp->p2 ){
69.908 + Deephemeralize(pTos);
69.909 + }
69.910 + break;
69.911 +}
69.912 +
69.913 +/* Opcode: Pull P1 * *
69.914 +**
69.915 +** The P1-th element is removed from its current location on
69.916 +** the stack and pushed back on top of the stack. The
69.917 +** top of the stack is element 0, so "Pull 0 0 0" is
69.918 +** a no-op. "Pull 1 0 0" swaps the top two elements of
69.919 +** the stack.
69.920 +**
69.921 +** See also the Dup instruction.
69.922 +*/
69.923 +case OP_Pull: { /* no-push */
69.924 + Mem *pFrom = &pTos[-pOp->p1];
69.925 + int i;
69.926 + Mem ts;
69.927 +
69.928 + ts = *pFrom;
69.929 + Deephemeralize(pTos);
69.930 + for(i=0; i<pOp->p1; i++, pFrom++){
69.931 + Deephemeralize(&pFrom[1]);
69.932 + assert( (pFrom[1].flags & MEM_Ephem)==0 );
69.933 + *pFrom = pFrom[1];
69.934 + if( pFrom->flags & MEM_Short ){
69.935 + assert( pFrom->flags & (MEM_Str|MEM_Blob) );
69.936 + assert( pFrom->z==pFrom[1].zShort );
69.937 + pFrom->z = pFrom->zShort;
69.938 + }
69.939 + }
69.940 + *pTos = ts;
69.941 + if( pTos->flags & MEM_Short ){
69.942 + assert( pTos->flags & (MEM_Str|MEM_Blob) );
69.943 + assert( pTos->z==pTos[-pOp->p1].zShort );
69.944 + pTos->z = pTos->zShort;
69.945 + }
69.946 + break;
69.947 +}
69.948 +
69.949 +/* Opcode: Push P1 * *
69.950 +**
69.951 +** Overwrite the value of the P1-th element down on the
69.952 +** stack (P1==0 is the top of the stack) with the value
69.953 +** of the top of the stack. Then pop the top of the stack.
69.954 +*/
69.955 +case OP_Push: { /* no-push */
69.956 + Mem *pTo = &pTos[-pOp->p1];
69.957 +
69.958 + assert( pTo>=p->aStack );
69.959 + sqlite3VdbeMemMove(pTo, pTos);
69.960 + pTos--;
69.961 + break;
69.962 +}
69.963 +
69.964 +/* Opcode: Callback P1 * *
69.965 +**
69.966 +** The top P1 values on the stack represent a single result row from
69.967 +** a query. This opcode causes the sqlite3_step() call to terminate
69.968 +** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
69.969 +** structure to provide access to the top P1 values as the result
69.970 +** row. When the sqlite3_step() function is run again, the top P1
69.971 +** values will be automatically popped from the stack before the next
69.972 +** instruction executes.
69.973 +*/
69.974 +case OP_Callback: { /* no-push */
69.975 + Mem *pMem;
69.976 + Mem *pFirstColumn;
69.977 + assert( p->nResColumn==pOp->p1 );
69.978 +
69.979 + /* Data in the pager might be moved or changed out from under us
69.980 + ** in between the return from this sqlite3_step() call and the
69.981 + ** next call to sqlite3_step(). So deephermeralize everything on
69.982 + ** the stack. Note that ephemeral data is never stored in memory
69.983 + ** cells so we do not have to worry about them.
69.984 + */
69.985 + pFirstColumn = &pTos[0-pOp->p1];
69.986 + for(pMem = p->aStack; pMem<pFirstColumn; pMem++){
69.987 + Deephemeralize(pMem);
69.988 + }
69.989 +
69.990 + /* Invalidate all ephemeral cursor row caches */
69.991 + p->cacheCtr = (p->cacheCtr + 2)|1;
69.992 +
69.993 + /* Make sure the results of the current row are \000 terminated
69.994 + ** and have an assigned type. The results are deephemeralized as
69.995 + ** as side effect.
69.996 + */
69.997 + for(; pMem<=pTos; pMem++ ){
69.998 + sqlite3VdbeMemNulTerminate(pMem);
69.999 + storeTypeInfo(pMem, encoding);
69.1000 + }
69.1001 +
69.1002 + /* Set up the statement structure so that it will pop the current
69.1003 + ** results from the stack when the statement returns.
69.1004 + */
69.1005 + p->resOnStack = 1;
69.1006 + p->nCallback++;
69.1007 + p->popStack = pOp->p1;
69.1008 + p->pc = pc + 1;
69.1009 + p->pTos = pTos;
69.1010 + return SQLITE_ROW;
69.1011 +}
69.1012 +
69.1013 +/* Opcode: Concat P1 P2 *
69.1014 +**
69.1015 +** Look at the first P1+2 elements of the stack. Append them all
69.1016 +** together with the lowest element first. The original P1+2 elements
69.1017 +** are popped from the stack if P2==0 and retained if P2==1. If
69.1018 +** any element of the stack is NULL, then the result is NULL.
69.1019 +**
69.1020 +** When P1==1, this routine makes a copy of the top stack element
69.1021 +** into memory obtained from sqliteMalloc().
69.1022 +*/
69.1023 +case OP_Concat: { /* same as TK_CONCAT */
69.1024 + char *zNew;
69.1025 + i64 nByte;
69.1026 + int nField;
69.1027 + int i, j;
69.1028 + Mem *pTerm;
69.1029 +
69.1030 + /* Loop through the stack elements to see how long the result will be. */
69.1031 + nField = pOp->p1 + 2;
69.1032 + pTerm = &pTos[1-nField];
69.1033 + nByte = 0;
69.1034 + for(i=0; i<nField; i++, pTerm++){
69.1035 + assert( pOp->p2==0 || (pTerm->flags&MEM_Str) );
69.1036 + if( pTerm->flags&MEM_Null ){
69.1037 + nByte = -1;
69.1038 + break;
69.1039 + }
69.1040 + ExpandBlob(pTerm);
69.1041 + Stringify(pTerm, encoding);
69.1042 + nByte += pTerm->n;
69.1043 + }
69.1044 +
69.1045 + if( nByte<0 ){
69.1046 + /* If nByte is less than zero, then there is a NULL value on the stack.
69.1047 + ** In this case just pop the values off the stack (if required) and
69.1048 + ** push on a NULL.
69.1049 + */
69.1050 + if( pOp->p2==0 ){
69.1051 + popStack(&pTos, nField);
69.1052 + }
69.1053 + pTos++;
69.1054 + pTos->flags = MEM_Null;
69.1055 + }else{
69.1056 + /* Otherwise malloc() space for the result and concatenate all the
69.1057 + ** stack values.
69.1058 + */
69.1059 + if( nByte+2>SQLITE_MAX_LENGTH ){
69.1060 + goto too_big;
69.1061 + }
69.1062 + zNew = sqliteMallocRaw( nByte+2 );
69.1063 + if( zNew==0 ) goto no_mem;
69.1064 + j = 0;
69.1065 + pTerm = &pTos[1-nField];
69.1066 + for(i=j=0; i<nField; i++, pTerm++){
69.1067 + int n = pTerm->n;
69.1068 + assert( pTerm->flags & (MEM_Str|MEM_Blob) );
69.1069 + memcpy(&zNew[j], pTerm->z, n);
69.1070 + j += n;
69.1071 + }
69.1072 + zNew[j] = 0;
69.1073 + zNew[j+1] = 0;
69.1074 + assert( j==nByte );
69.1075 +
69.1076 + if( pOp->p2==0 ){
69.1077 + popStack(&pTos, nField);
69.1078 + }
69.1079 + pTos++;
69.1080 + pTos->n = j;
69.1081 + pTos->flags = MEM_Str|MEM_Dyn|MEM_Term;
69.1082 + pTos->xDel = 0;
69.1083 + pTos->enc = encoding;
69.1084 + pTos->z = zNew;
69.1085 + }
69.1086 + break;
69.1087 +}
69.1088 +
69.1089 +/* Opcode: Add * * *
69.1090 +**
69.1091 +** Pop the top two elements from the stack, add them together,
69.1092 +** and push the result back onto the stack. If either element
69.1093 +** is a string then it is converted to a double using the atof()
69.1094 +** function before the addition.
69.1095 +** If either operand is NULL, the result is NULL.
69.1096 +*/
69.1097 +/* Opcode: Multiply * * *
69.1098 +**
69.1099 +** Pop the top two elements from the stack, multiply them together,
69.1100 +** and push the result back onto the stack. If either element
69.1101 +** is a string then it is converted to a double using the atof()
69.1102 +** function before the multiplication.
69.1103 +** If either operand is NULL, the result is NULL.
69.1104 +*/
69.1105 +/* Opcode: Subtract * * *
69.1106 +**
69.1107 +** Pop the top two elements from the stack, subtract the
69.1108 +** first (what was on top of the stack) from the second (the
69.1109 +** next on stack)
69.1110 +** and push the result back onto the stack. If either element
69.1111 +** is a string then it is converted to a double using the atof()
69.1112 +** function before the subtraction.
69.1113 +** If either operand is NULL, the result is NULL.
69.1114 +*/
69.1115 +/* Opcode: Divide * * *
69.1116 +**
69.1117 +** Pop the top two elements from the stack, divide the
69.1118 +** first (what was on top of the stack) from the second (the
69.1119 +** next on stack)
69.1120 +** and push the result back onto the stack. If either element
69.1121 +** is a string then it is converted to a double using the atof()
69.1122 +** function before the division. Division by zero returns NULL.
69.1123 +** If either operand is NULL, the result is NULL.
69.1124 +*/
69.1125 +/* Opcode: Remainder * * *
69.1126 +**
69.1127 +** Pop the top two elements from the stack, divide the
69.1128 +** first (what was on top of the stack) from the second (the
69.1129 +** next on stack)
69.1130 +** and push the remainder after division onto the stack. If either element
69.1131 +** is a string then it is converted to a double using the atof()
69.1132 +** function before the division. Division by zero returns NULL.
69.1133 +** If either operand is NULL, the result is NULL.
69.1134 +*/
69.1135 +case OP_Add: /* same as TK_PLUS, no-push */
69.1136 +case OP_Subtract: /* same as TK_MINUS, no-push */
69.1137 +case OP_Multiply: /* same as TK_STAR, no-push */
69.1138 +case OP_Divide: /* same as TK_SLASH, no-push */
69.1139 +case OP_Remainder: { /* same as TK_REM, no-push */
69.1140 + Mem *pNos = &pTos[-1];
69.1141 + int flags;
69.1142 + assert( pNos>=p->aStack );
69.1143 + flags = pTos->flags | pNos->flags;
69.1144 + if( (flags & MEM_Null)!=0 ){
69.1145 + Release(pTos);
69.1146 + pTos--;
69.1147 + Release(pTos);
69.1148 + pTos->flags = MEM_Null;
69.1149 + }else if( (pTos->flags & pNos->flags & MEM_Int)==MEM_Int ){
69.1150 + i64 a, b;
69.1151 + a = pTos->u.i;
69.1152 + b = pNos->u.i;
69.1153 + switch( pOp->opcode ){
69.1154 + case OP_Add: b += a; break;
69.1155 + case OP_Subtract: b -= a; break;
69.1156 + case OP_Multiply: b *= a; break;
69.1157 + case OP_Divide: {
69.1158 + if( a==0 ) goto divide_by_zero;
69.1159 + /* Dividing the largest possible negative 64-bit integer (1<<63) by
69.1160 + ** -1 returns an integer to large to store in a 64-bit data-type. On
69.1161 + ** some architectures, the value overflows to (1<<63). On others,
69.1162 + ** a SIGFPE is issued. The following statement normalizes this
69.1163 + ** behaviour so that all architectures behave as if integer
69.1164 + ** overflow occured.
69.1165 + */
69.1166 + if( a==-1 && b==(((i64)1)<<63) ) a = 1;
69.1167 + b /= a;
69.1168 + break;
69.1169 + }
69.1170 + default: {
69.1171 + if( a==0 ) goto divide_by_zero;
69.1172 + if( a==-1 ) a = 1;
69.1173 + b %= a;
69.1174 + break;
69.1175 + }
69.1176 + }
69.1177 + Release(pTos);
69.1178 + pTos--;
69.1179 + Release(pTos);
69.1180 + pTos->u.i = b;
69.1181 + pTos->flags = MEM_Int;
69.1182 + }else{
69.1183 + double a, b;
69.1184 + a = sqlite3VdbeRealValue(pTos);
69.1185 + b = sqlite3VdbeRealValue(pNos);
69.1186 + switch( pOp->opcode ){
69.1187 + case OP_Add: b += a; break;
69.1188 + case OP_Subtract: b -= a; break;
69.1189 + case OP_Multiply: b *= a; break;
69.1190 + case OP_Divide: {
69.1191 + if( a==0.0 ) goto divide_by_zero;
69.1192 + b /= a;
69.1193 + break;
69.1194 + }
69.1195 + default: {
69.1196 + i64 ia = (i64)a;
69.1197 + i64 ib = (i64)b;
69.1198 + if( ia==0 ) goto divide_by_zero;
69.1199 + if( ia==-1 ) ia = 1;
69.1200 + b = ib % ia;
69.1201 + break;
69.1202 + }
69.1203 + }
69.1204 + if( sqlite3_isnan(b) ){
69.1205 + goto divide_by_zero;
69.1206 + }
69.1207 + Release(pTos);
69.1208 + pTos--;
69.1209 + Release(pTos);
69.1210 + pTos->r = b;
69.1211 + pTos->flags = MEM_Real;
69.1212 + if( (flags & MEM_Real)==0 ){
69.1213 + sqlite3VdbeIntegerAffinity(pTos);
69.1214 + }
69.1215 + }
69.1216 + break;
69.1217 +
69.1218 +divide_by_zero:
69.1219 + Release(pTos);
69.1220 + pTos--;
69.1221 + Release(pTos);
69.1222 + pTos->flags = MEM_Null;
69.1223 + break;
69.1224 +}
69.1225 +
69.1226 +/* Opcode: CollSeq * * P3
69.1227 +**
69.1228 +** P3 is a pointer to a CollSeq struct. If the next call to a user function
69.1229 +** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
69.1230 +** be returned. This is used by the built-in min(), max() and nullif()
69.1231 +** functions.
69.1232 +**
69.1233 +** The interface used by the implementation of the aforementioned functions
69.1234 +** to retrieve the collation sequence set by this opcode is not available
69.1235 +** publicly, only to user functions defined in func.c.
69.1236 +*/
69.1237 +case OP_CollSeq: { /* no-push */
69.1238 + assert( pOp->p3type==P3_COLLSEQ );
69.1239 + break;
69.1240 +}
69.1241 +
69.1242 +/* Opcode: Function P1 P2 P3
69.1243 +**
69.1244 +** Invoke a user function (P3 is a pointer to a Function structure that
69.1245 +** defines the function) with P2 arguments taken from the stack. Pop all
69.1246 +** arguments from the stack and push back the result.
69.1247 +**
69.1248 +** P1 is a 32-bit bitmask indicating whether or not each argument to the
69.1249 +** function was determined to be constant at compile time. If the first
69.1250 +** argument was constant then bit 0 of P1 is set. This is used to determine
69.1251 +** whether meta data associated with a user function argument using the
69.1252 +** sqlite3_set_auxdata() API may be safely retained until the next
69.1253 +** invocation of this opcode.
69.1254 +**
69.1255 +** See also: AggStep and AggFinal
69.1256 +*/
69.1257 +case OP_Function: {
69.1258 + int i;
69.1259 + Mem *pArg;
69.1260 + sqlite3_context ctx;
69.1261 + sqlite3_value **apVal;
69.1262 + int n = pOp->p2;
69.1263 +
69.1264 + apVal = p->apArg;
69.1265 + assert( apVal || n==0 );
69.1266 +
69.1267 + pArg = &pTos[1-n];
69.1268 + for(i=0; i<n; i++, pArg++){
69.1269 + apVal[i] = pArg;
69.1270 + storeTypeInfo(pArg, encoding);
69.1271 + }
69.1272 +
69.1273 + assert( pOp->p3type==P3_FUNCDEF || pOp->p3type==P3_VDBEFUNC );
69.1274 + if( pOp->p3type==P3_FUNCDEF ){
69.1275 + ctx.pFunc = (FuncDef*)pOp->p3;
69.1276 + ctx.pVdbeFunc = 0;
69.1277 + }else{
69.1278 + ctx.pVdbeFunc = (VdbeFunc*)pOp->p3;
69.1279 + ctx.pFunc = ctx.pVdbeFunc->pFunc;
69.1280 + }
69.1281 +
69.1282 + ctx.s.flags = MEM_Null;
69.1283 + ctx.s.z = 0;
69.1284 + ctx.s.xDel = 0;
69.1285 + ctx.isError = 0;
69.1286 + if( ctx.pFunc->needCollSeq ){
69.1287 + assert( pOp>p->aOp );
69.1288 + assert( pOp[-1].p3type==P3_COLLSEQ );
69.1289 + assert( pOp[-1].opcode==OP_CollSeq );
69.1290 + ctx.pColl = (CollSeq *)pOp[-1].p3;
69.1291 + }
69.1292 + if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
69.1293 + (*ctx.pFunc->xFunc)(&ctx, n, apVal);
69.1294 + if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
69.1295 + if( sqlite3MallocFailed() ) goto no_mem;
69.1296 + popStack(&pTos, n);
69.1297 +
69.1298 + /* If any auxilary data functions have been called by this user function,
69.1299 + ** immediately call the destructor for any non-static values.
69.1300 + */
69.1301 + if( ctx.pVdbeFunc ){
69.1302 + sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
69.1303 + pOp->p3 = (char *)ctx.pVdbeFunc;
69.1304 + pOp->p3type = P3_VDBEFUNC;
69.1305 + }
69.1306 +
69.1307 + /* If the function returned an error, throw an exception */
69.1308 + if( ctx.isError ){
69.1309 + sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
69.1310 + rc = SQLITE_ERROR;
69.1311 + }
69.1312 +
69.1313 + /* Copy the result of the function to the top of the stack */
69.1314 + sqlite3VdbeChangeEncoding(&ctx.s, encoding);
69.1315 + pTos++;
69.1316 + pTos->flags = 0;
69.1317 + sqlite3VdbeMemMove(pTos, &ctx.s);
69.1318 + if( sqlite3VdbeMemTooBig(pTos) ){
69.1319 + goto too_big;
69.1320 + }
69.1321 + break;
69.1322 +}
69.1323 +
69.1324 +/* Opcode: BitAnd * * *
69.1325 +**
69.1326 +** Pop the top two elements from the stack. Convert both elements
69.1327 +** to integers. Push back onto the stack the bit-wise AND of the
69.1328 +** two elements.
69.1329 +** If either operand is NULL, the result is NULL.
69.1330 +*/
69.1331 +/* Opcode: BitOr * * *
69.1332 +**
69.1333 +** Pop the top two elements from the stack. Convert both elements
69.1334 +** to integers. Push back onto the stack the bit-wise OR of the
69.1335 +** two elements.
69.1336 +** If either operand is NULL, the result is NULL.
69.1337 +*/
69.1338 +/* Opcode: ShiftLeft * * *
69.1339 +**
69.1340 +** Pop the top two elements from the stack. Convert both elements
69.1341 +** to integers. Push back onto the stack the second element shifted
69.1342 +** left by N bits where N is the top element on the stack.
69.1343 +** If either operand is NULL, the result is NULL.
69.1344 +*/
69.1345 +/* Opcode: ShiftRight * * *
69.1346 +**
69.1347 +** Pop the top two elements from the stack. Convert both elements
69.1348 +** to integers. Push back onto the stack the second element shifted
69.1349 +** right by N bits where N is the top element on the stack.
69.1350 +** If either operand is NULL, the result is NULL.
69.1351 +*/
69.1352 +case OP_BitAnd: /* same as TK_BITAND, no-push */
69.1353 +case OP_BitOr: /* same as TK_BITOR, no-push */
69.1354 +case OP_ShiftLeft: /* same as TK_LSHIFT, no-push */
69.1355 +case OP_ShiftRight: { /* same as TK_RSHIFT, no-push */
69.1356 + Mem *pNos = &pTos[-1];
69.1357 + i64 a, b;
69.1358 +
69.1359 + assert( pNos>=p->aStack );
69.1360 + if( (pTos->flags | pNos->flags) & MEM_Null ){
69.1361 + popStack(&pTos, 2);
69.1362 + pTos++;
69.1363 + pTos->flags = MEM_Null;
69.1364 + break;
69.1365 + }
69.1366 + a = sqlite3VdbeIntValue(pNos);
69.1367 + b = sqlite3VdbeIntValue(pTos);
69.1368 + switch( pOp->opcode ){
69.1369 + case OP_BitAnd: a &= b; break;
69.1370 + case OP_BitOr: a |= b; break;
69.1371 + case OP_ShiftLeft: a <<= b; break;
69.1372 + case OP_ShiftRight: a >>= b; break;
69.1373 + default: /* CANT HAPPEN */ break;
69.1374 + }
69.1375 + Release(pTos);
69.1376 + pTos--;
69.1377 + Release(pTos);
69.1378 + pTos->u.i = a;
69.1379 + pTos->flags = MEM_Int;
69.1380 + break;
69.1381 +}
69.1382 +
69.1383 +/* Opcode: AddImm P1 * *
69.1384 +**
69.1385 +** Add the value P1 to whatever is on top of the stack. The result
69.1386 +** is always an integer.
69.1387 +**
69.1388 +** To force the top of the stack to be an integer, just add 0.
69.1389 +*/
69.1390 +case OP_AddImm: { /* no-push */
69.1391 + assert( pTos>=p->aStack );
69.1392 + sqlite3VdbeMemIntegerify(pTos);
69.1393 + pTos->u.i += pOp->p1;
69.1394 + break;
69.1395 +}
69.1396 +
69.1397 +/* Opcode: ForceInt P1 P2 *
69.1398 +**
69.1399 +** Convert the top of the stack into an integer. If the current top of
69.1400 +** the stack is not numeric (meaning that is is a NULL or a string that
69.1401 +** does not look like an integer or floating point number) then pop the
69.1402 +** stack and jump to P2. If the top of the stack is numeric then
69.1403 +** convert it into the least integer that is greater than or equal to its
69.1404 +** current value if P1==0, or to the least integer that is strictly
69.1405 +** greater than its current value if P1==1.
69.1406 +*/
69.1407 +case OP_ForceInt: { /* no-push */
69.1408 + i64 v;
69.1409 + assert( pTos>=p->aStack );
69.1410 + applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
69.1411 + if( (pTos->flags & (MEM_Int|MEM_Real))==0 ){
69.1412 + Release(pTos);
69.1413 + pTos--;
69.1414 + pc = pOp->p2 - 1;
69.1415 + break;
69.1416 + }
69.1417 + if( pTos->flags & MEM_Int ){
69.1418 + v = pTos->u.i + (pOp->p1!=0);
69.1419 + }else{
69.1420 + /* FIX ME: should this not be assert( pTos->flags & MEM_Real ) ??? */
69.1421 + sqlite3VdbeMemRealify(pTos);
69.1422 + v = (int)pTos->r;
69.1423 + if( pTos->r>(double)v ) v++;
69.1424 + if( pOp->p1 && pTos->r==(double)v ) v++;
69.1425 + }
69.1426 + Release(pTos);
69.1427 + pTos->u.i = v;
69.1428 + pTos->flags = MEM_Int;
69.1429 + break;
69.1430 +}
69.1431 +
69.1432 +/* Opcode: MustBeInt P1 P2 *
69.1433 +**
69.1434 +** Force the top of the stack to be an integer. If the top of the
69.1435 +** stack is not an integer and cannot be converted into an integer
69.1436 +** with out data loss, then jump immediately to P2, or if P2==0
69.1437 +** raise an SQLITE_MISMATCH exception.
69.1438 +**
69.1439 +** If the top of the stack is not an integer and P2 is not zero and
69.1440 +** P1 is 1, then the stack is popped. In all other cases, the depth
69.1441 +** of the stack is unchanged.
69.1442 +*/
69.1443 +case OP_MustBeInt: { /* no-push */
69.1444 + assert( pTos>=p->aStack );
69.1445 + applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
69.1446 + if( (pTos->flags & MEM_Int)==0 ){
69.1447 + if( pOp->p2==0 ){
69.1448 + rc = SQLITE_MISMATCH;
69.1449 + goto abort_due_to_error;
69.1450 + }else{
69.1451 + if( pOp->p1 ) popStack(&pTos, 1);
69.1452 + pc = pOp->p2 - 1;
69.1453 + }
69.1454 + }else{
69.1455 + Release(pTos);
69.1456 + pTos->flags = MEM_Int;
69.1457 + }
69.1458 + break;
69.1459 +}
69.1460 +
69.1461 +/* Opcode: RealAffinity * * *
69.1462 +**
69.1463 +** If the top of the stack is an integer, convert it to a real value.
69.1464 +**
69.1465 +** This opcode is used when extracting information from a column that
69.1466 +** has REAL affinity. Such column values may still be stored as
69.1467 +** integers, for space efficiency, but after extraction we want them
69.1468 +** to have only a real value.
69.1469 +*/
69.1470 +case OP_RealAffinity: { /* no-push */
69.1471 + assert( pTos>=p->aStack );
69.1472 + if( pTos->flags & MEM_Int ){
69.1473 + sqlite3VdbeMemRealify(pTos);
69.1474 + }
69.1475 + break;
69.1476 +}
69.1477 +
69.1478 +#ifndef SQLITE_OMIT_CAST
69.1479 +/* Opcode: ToText * * *
69.1480 +**
69.1481 +** Force the value on the top of the stack to be text.
69.1482 +** If the value is numeric, convert it to a string using the
69.1483 +** equivalent of printf(). Blob values are unchanged and
69.1484 +** are afterwards simply interpreted as text.
69.1485 +**
69.1486 +** A NULL value is not changed by this routine. It remains NULL.
69.1487 +*/
69.1488 +case OP_ToText: { /* same as TK_TO_TEXT, no-push */
69.1489 + assert( pTos>=p->aStack );
69.1490 + if( pTos->flags & MEM_Null ) break;
69.1491 + assert( MEM_Str==(MEM_Blob>>3) );
69.1492 + pTos->flags |= (pTos->flags&MEM_Blob)>>3;
69.1493 + applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
69.1494 + rc = ExpandBlob(pTos);
69.1495 + assert( pTos->flags & MEM_Str );
69.1496 + pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Blob);
69.1497 + break;
69.1498 +}
69.1499 +
69.1500 +/* Opcode: ToBlob * * *
69.1501 +**
69.1502 +** Force the value on the top of the stack to be a BLOB.
69.1503 +** If the value is numeric, convert it to a string first.
69.1504 +** Strings are simply reinterpreted as blobs with no change
69.1505 +** to the underlying data.
69.1506 +**
69.1507 +** A NULL value is not changed by this routine. It remains NULL.
69.1508 +*/
69.1509 +case OP_ToBlob: { /* same as TK_TO_BLOB, no-push */
69.1510 + assert( pTos>=p->aStack );
69.1511 + if( pTos->flags & MEM_Null ) break;
69.1512 + if( (pTos->flags & MEM_Blob)==0 ){
69.1513 + applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
69.1514 + assert( pTos->flags & MEM_Str );
69.1515 + pTos->flags |= MEM_Blob;
69.1516 + }
69.1517 + pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Str);
69.1518 + break;
69.1519 +}
69.1520 +
69.1521 +/* Opcode: ToNumeric * * *
69.1522 +**
69.1523 +** Force the value on the top of the stack to be numeric (either an
69.1524 +** integer or a floating-point number.)
69.1525 +** If the value is text or blob, try to convert it to an using the
69.1526 +** equivalent of atoi() or atof() and store 0 if no such conversion
69.1527 +** is possible.
69.1528 +**
69.1529 +** A NULL value is not changed by this routine. It remains NULL.
69.1530 +*/
69.1531 +case OP_ToNumeric: { /* same as TK_TO_NUMERIC, no-push */
69.1532 + assert( pTos>=p->aStack );
69.1533 + if( (pTos->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
69.1534 + sqlite3VdbeMemNumerify(pTos);
69.1535 + }
69.1536 + break;
69.1537 +}
69.1538 +#endif /* SQLITE_OMIT_CAST */
69.1539 +
69.1540 +/* Opcode: ToInt * * *
69.1541 +**
69.1542 +** Force the value on the top of the stack to be an integer. If
69.1543 +** The value is currently a real number, drop its fractional part.
69.1544 +** If the value is text or blob, try to convert it to an integer using the
69.1545 +** equivalent of atoi() and store 0 if no such conversion is possible.
69.1546 +**
69.1547 +** A NULL value is not changed by this routine. It remains NULL.
69.1548 +*/
69.1549 +case OP_ToInt: { /* same as TK_TO_INT, no-push */
69.1550 + assert( pTos>=p->aStack );
69.1551 + if( (pTos->flags & MEM_Null)==0 ){
69.1552 + sqlite3VdbeMemIntegerify(pTos);
69.1553 + }
69.1554 + break;
69.1555 +}
69.1556 +
69.1557 +#ifndef SQLITE_OMIT_CAST
69.1558 +/* Opcode: ToReal * * *
69.1559 +**
69.1560 +** Force the value on the top of the stack to be a floating point number.
69.1561 +** If The value is currently an integer, convert it.
69.1562 +** If the value is text or blob, try to convert it to an integer using the
69.1563 +** equivalent of atoi() and store 0 if no such conversion is possible.
69.1564 +**
69.1565 +** A NULL value is not changed by this routine. It remains NULL.
69.1566 +*/
69.1567 +case OP_ToReal: { /* same as TK_TO_REAL, no-push */
69.1568 + assert( pTos>=p->aStack );
69.1569 + if( (pTos->flags & MEM_Null)==0 ){
69.1570 + sqlite3VdbeMemRealify(pTos);
69.1571 + }
69.1572 + break;
69.1573 +}
69.1574 +#endif /* SQLITE_OMIT_CAST */
69.1575 +
69.1576 +/* Opcode: Eq P1 P2 P3
69.1577 +**
69.1578 +** Pop the top two elements from the stack. If they are equal, then
69.1579 +** jump to instruction P2. Otherwise, continue to the next instruction.
69.1580 +**
69.1581 +** If the 0x100 bit of P1 is true and either operand is NULL then take the
69.1582 +** jump. If the 0x100 bit of P1 is clear then fall thru if either operand
69.1583 +** is NULL.
69.1584 +**
69.1585 +** If the 0x200 bit of P1 is set and either operand is NULL then
69.1586 +** both operands are converted to integers prior to comparison.
69.1587 +** NULL operands are converted to zero and non-NULL operands are
69.1588 +** converted to 1. Thus, for example, with 0x200 set, NULL==NULL is true
69.1589 +** whereas it would normally be NULL. Similarly, NULL==123 is false when
69.1590 +** 0x200 is set but is NULL when the 0x200 bit of P1 is clear.
69.1591 +**
69.1592 +** The least significant byte of P1 (mask 0xff) must be an affinity character -
69.1593 +** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
69.1594 +** to coerce both values
69.1595 +** according to the affinity before the comparison is made. If the byte is
69.1596 +** 0x00, then numeric affinity is used.
69.1597 +**
69.1598 +** Once any conversions have taken place, and neither value is NULL,
69.1599 +** the values are compared. If both values are blobs, or both are text,
69.1600 +** then memcmp() is used to determine the results of the comparison. If
69.1601 +** both values are numeric, then a numeric comparison is used. If the
69.1602 +** two values are of different types, then they are inequal.
69.1603 +**
69.1604 +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
69.1605 +** stack if the jump would have been taken, or a 0 if not. Push a
69.1606 +** NULL if either operand was NULL.
69.1607 +**
69.1608 +** If P3 is not NULL it is a pointer to a collating sequence (a CollSeq
69.1609 +** structure) that defines how to compare text.
69.1610 +*/
69.1611 +/* Opcode: Ne P1 P2 P3
69.1612 +**
69.1613 +** This works just like the Eq opcode except that the jump is taken if
69.1614 +** the operands from the stack are not equal. See the Eq opcode for
69.1615 +** additional information.
69.1616 +*/
69.1617 +/* Opcode: Lt P1 P2 P3
69.1618 +**
69.1619 +** This works just like the Eq opcode except that the jump is taken if
69.1620 +** the 2nd element down on the stack is less than the top of the stack.
69.1621 +** See the Eq opcode for additional information.
69.1622 +*/
69.1623 +/* Opcode: Le P1 P2 P3
69.1624 +**
69.1625 +** This works just like the Eq opcode except that the jump is taken if
69.1626 +** the 2nd element down on the stack is less than or equal to the
69.1627 +** top of the stack. See the Eq opcode for additional information.
69.1628 +*/
69.1629 +/* Opcode: Gt P1 P2 P3
69.1630 +**
69.1631 +** This works just like the Eq opcode except that the jump is taken if
69.1632 +** the 2nd element down on the stack is greater than the top of the stack.
69.1633 +** See the Eq opcode for additional information.
69.1634 +*/
69.1635 +/* Opcode: Ge P1 P2 P3
69.1636 +**
69.1637 +** This works just like the Eq opcode except that the jump is taken if
69.1638 +** the 2nd element down on the stack is greater than or equal to the
69.1639 +** top of the stack. See the Eq opcode for additional information.
69.1640 +*/
69.1641 +case OP_Eq: /* same as TK_EQ, no-push */
69.1642 +case OP_Ne: /* same as TK_NE, no-push */
69.1643 +case OP_Lt: /* same as TK_LT, no-push */
69.1644 +case OP_Le: /* same as TK_LE, no-push */
69.1645 +case OP_Gt: /* same as TK_GT, no-push */
69.1646 +case OP_Ge: { /* same as TK_GE, no-push */
69.1647 + Mem *pNos;
69.1648 + int flags;
69.1649 + int res;
69.1650 + char affinity;
69.1651 +
69.1652 + pNos = &pTos[-1];
69.1653 + flags = pTos->flags|pNos->flags;
69.1654 +
69.1655 + /* If either value is a NULL P2 is not zero, take the jump if the least
69.1656 + ** significant byte of P1 is true. If P2 is zero, then push a NULL onto
69.1657 + ** the stack.
69.1658 + */
69.1659 + if( flags&MEM_Null ){
69.1660 + if( (pOp->p1 & 0x200)!=0 ){
69.1661 + /* The 0x200 bit of P1 means, roughly "do not treat NULL as the
69.1662 + ** magic SQL value it normally is - treat it as if it were another
69.1663 + ** integer".
69.1664 + **
69.1665 + ** With 0x200 set, if either operand is NULL then both operands
69.1666 + ** are converted to integers prior to being passed down into the
69.1667 + ** normal comparison logic below. NULL operands are converted to
69.1668 + ** zero and non-NULL operands are converted to 1. Thus, for example,
69.1669 + ** with 0x200 set, NULL==NULL is true whereas it would normally
69.1670 + ** be NULL. Similarly, NULL!=123 is true.
69.1671 + */
69.1672 + sqlite3VdbeMemSetInt64(pTos, (pTos->flags & MEM_Null)==0);
69.1673 + sqlite3VdbeMemSetInt64(pNos, (pNos->flags & MEM_Null)==0);
69.1674 + }else{
69.1675 + /* If the 0x200 bit of P1 is clear and either operand is NULL then
69.1676 + ** the result is always NULL. The jump is taken if the 0x100 bit
69.1677 + ** of P1 is set.
69.1678 + */
69.1679 + popStack(&pTos, 2);
69.1680 + if( pOp->p2 ){
69.1681 + if( pOp->p1 & 0x100 ){
69.1682 + pc = pOp->p2-1;
69.1683 + }
69.1684 + }else{
69.1685 + pTos++;
69.1686 + pTos->flags = MEM_Null;
69.1687 + }
69.1688 + break;
69.1689 + }
69.1690 + }
69.1691 +
69.1692 + affinity = pOp->p1 & 0xFF;
69.1693 + if( affinity ){
69.1694 + applyAffinity(pNos, affinity, encoding);
69.1695 + applyAffinity(pTos, affinity, encoding);
69.1696 + }
69.1697 +
69.1698 + assert( pOp->p3type==P3_COLLSEQ || pOp->p3==0 );
69.1699 + ExpandBlob(pNos);
69.1700 + ExpandBlob(pTos);
69.1701 + res = sqlite3MemCompare(pNos, pTos, (CollSeq*)pOp->p3);
69.1702 + switch( pOp->opcode ){
69.1703 + case OP_Eq: res = res==0; break;
69.1704 + case OP_Ne: res = res!=0; break;
69.1705 + case OP_Lt: res = res<0; break;
69.1706 + case OP_Le: res = res<=0; break;
69.1707 + case OP_Gt: res = res>0; break;
69.1708 + default: res = res>=0; break;
69.1709 + }
69.1710 +
69.1711 + popStack(&pTos, 2);
69.1712 + if( pOp->p2 ){
69.1713 + if( res ){
69.1714 + pc = pOp->p2-1;
69.1715 + }
69.1716 + }else{
69.1717 + pTos++;
69.1718 + pTos->flags = MEM_Int;
69.1719 + pTos->u.i = res;
69.1720 + }
69.1721 + break;
69.1722 +}
69.1723 +
69.1724 +/* Opcode: And * * *
69.1725 +**
69.1726 +** Pop two values off the stack. Take the logical AND of the
69.1727 +** two values and push the resulting boolean value back onto the
69.1728 +** stack.
69.1729 +*/
69.1730 +/* Opcode: Or * * *
69.1731 +**
69.1732 +** Pop two values off the stack. Take the logical OR of the
69.1733 +** two values and push the resulting boolean value back onto the
69.1734 +** stack.
69.1735 +*/
69.1736 +case OP_And: /* same as TK_AND, no-push */
69.1737 +case OP_Or: { /* same as TK_OR, no-push */
69.1738 + Mem *pNos = &pTos[-1];
69.1739 + int v1, v2; /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */
69.1740 +
69.1741 + assert( pNos>=p->aStack );
69.1742 + if( pTos->flags & MEM_Null ){
69.1743 + v1 = 2;
69.1744 + }else{
69.1745 + sqlite3VdbeMemIntegerify(pTos);
69.1746 + v1 = pTos->u.i==0;
69.1747 + }
69.1748 + if( pNos->flags & MEM_Null ){
69.1749 + v2 = 2;
69.1750 + }else{
69.1751 + sqlite3VdbeMemIntegerify(pNos);
69.1752 + v2 = pNos->u.i==0;
69.1753 + }
69.1754 + if( pOp->opcode==OP_And ){
69.1755 + static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
69.1756 + v1 = and_logic[v1*3+v2];
69.1757 + }else{
69.1758 + static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
69.1759 + v1 = or_logic[v1*3+v2];
69.1760 + }
69.1761 + popStack(&pTos, 2);
69.1762 + pTos++;
69.1763 + if( v1==2 ){
69.1764 + pTos->flags = MEM_Null;
69.1765 + }else{
69.1766 + pTos->u.i = v1==0;
69.1767 + pTos->flags = MEM_Int;
69.1768 + }
69.1769 + break;
69.1770 +}
69.1771 +
69.1772 +/* Opcode: Negative * * *
69.1773 +**
69.1774 +** Treat the top of the stack as a numeric quantity. Replace it
69.1775 +** with its additive inverse. If the top of the stack is NULL
69.1776 +** its value is unchanged.
69.1777 +*/
69.1778 +/* Opcode: AbsValue * * *
69.1779 +**
69.1780 +** Treat the top of the stack as a numeric quantity. Replace it
69.1781 +** with its absolute value. If the top of the stack is NULL
69.1782 +** its value is unchanged.
69.1783 +*/
69.1784 +case OP_Negative: /* same as TK_UMINUS, no-push */
69.1785 +case OP_AbsValue: {
69.1786 + assert( pTos>=p->aStack );
69.1787 + if( (pTos->flags & (MEM_Real|MEM_Int|MEM_Null))==0 ){
69.1788 + sqlite3VdbeMemNumerify(pTos);
69.1789 + }
69.1790 + if( pTos->flags & MEM_Real ){
69.1791 + Release(pTos);
69.1792 + if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
69.1793 + pTos->r = -pTos->r;
69.1794 + }
69.1795 + pTos->flags = MEM_Real;
69.1796 + }else if( pTos->flags & MEM_Int ){
69.1797 + Release(pTos);
69.1798 + if( pOp->opcode==OP_Negative || pTos->u.i<0 ){
69.1799 + pTos->u.i = -pTos->u.i;
69.1800 + }
69.1801 + pTos->flags = MEM_Int;
69.1802 + }
69.1803 + break;
69.1804 +}
69.1805 +
69.1806 +/* Opcode: Not * * *
69.1807 +**
69.1808 +** Interpret the top of the stack as a boolean value. Replace it
69.1809 +** with its complement. If the top of the stack is NULL its value
69.1810 +** is unchanged.
69.1811 +*/
69.1812 +case OP_Not: { /* same as TK_NOT, no-push */
69.1813 + assert( pTos>=p->aStack );
69.1814 + if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */
69.1815 + sqlite3VdbeMemIntegerify(pTos);
69.1816 + assert( (pTos->flags & MEM_Dyn)==0 );
69.1817 + pTos->u.i = !pTos->u.i;
69.1818 + pTos->flags = MEM_Int;
69.1819 + break;
69.1820 +}
69.1821 +
69.1822 +/* Opcode: BitNot * * *
69.1823 +**
69.1824 +** Interpret the top of the stack as an value. Replace it
69.1825 +** with its ones-complement. If the top of the stack is NULL its
69.1826 +** value is unchanged.
69.1827 +*/
69.1828 +case OP_BitNot: { /* same as TK_BITNOT, no-push */
69.1829 + assert( pTos>=p->aStack );
69.1830 + if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */
69.1831 + sqlite3VdbeMemIntegerify(pTos);
69.1832 + assert( (pTos->flags & MEM_Dyn)==0 );
69.1833 + pTos->u.i = ~pTos->u.i;
69.1834 + pTos->flags = MEM_Int;
69.1835 + break;
69.1836 +}
69.1837 +
69.1838 +/* Opcode: Noop * * *
69.1839 +**
69.1840 +** Do nothing. This instruction is often useful as a jump
69.1841 +** destination.
69.1842 +*/
69.1843 +/*
69.1844 +** The magic Explain opcode are only inserted when explain==2 (which
69.1845 +** is to say when the EXPLAIN QUERY PLAN syntax is used.)
69.1846 +** This opcode records information from the optimizer. It is the
69.1847 +** the same as a no-op. This opcodesnever appears in a real VM program.
69.1848 +*/
69.1849 +case OP_Explain:
69.1850 +case OP_Noop: { /* no-push */
69.1851 + break;
69.1852 +}
69.1853 +
69.1854 +/* Opcode: If P1 P2 *
69.1855 +**
69.1856 +** Pop a single boolean from the stack. If the boolean popped is
69.1857 +** true, then jump to p2. Otherwise continue to the next instruction.
69.1858 +** An integer is false if zero and true otherwise. A string is
69.1859 +** false if it has zero length and true otherwise.
69.1860 +**
69.1861 +** If the value popped of the stack is NULL, then take the jump if P1
69.1862 +** is true and fall through if P1 is false.
69.1863 +*/
69.1864 +/* Opcode: IfNot P1 P2 *
69.1865 +**
69.1866 +** Pop a single boolean from the stack. If the boolean popped is
69.1867 +** false, then jump to p2. Otherwise continue to the next instruction.
69.1868 +** An integer is false if zero and true otherwise. A string is
69.1869 +** false if it has zero length and true otherwise.
69.1870 +**
69.1871 +** If the value popped of the stack is NULL, then take the jump if P1
69.1872 +** is true and fall through if P1 is false.
69.1873 +*/
69.1874 +case OP_If: /* no-push */
69.1875 +case OP_IfNot: { /* no-push */
69.1876 + int c;
69.1877 + assert( pTos>=p->aStack );
69.1878 + if( pTos->flags & MEM_Null ){
69.1879 + c = pOp->p1;
69.1880 + }else{
69.1881 +#ifdef SQLITE_OMIT_FLOATING_POINT
69.1882 + c = sqlite3VdbeIntValue(pTos);
69.1883 +#else
69.1884 + c = sqlite3VdbeRealValue(pTos)!=0.0;
69.1885 +#endif
69.1886 + if( pOp->opcode==OP_IfNot ) c = !c;
69.1887 + }
69.1888 + Release(pTos);
69.1889 + pTos--;
69.1890 + if( c ) pc = pOp->p2-1;
69.1891 + break;
69.1892 +}
69.1893 +
69.1894 +/* Opcode: IsNull P1 P2 *
69.1895 +**
69.1896 +** Check the top of the stack and jump to P2 if the top of the stack
69.1897 +** is NULL. If P1 is positive, then pop P1 elements from the stack
69.1898 +** regardless of whether or not the jump is taken. If P1 is negative,
69.1899 +** pop -P1 elements from the stack only if the jump is taken and leave
69.1900 +** the stack unchanged if the jump is not taken.
69.1901 +*/
69.1902 +case OP_IsNull: { /* same as TK_ISNULL, no-push */
69.1903 + if( pTos->flags & MEM_Null ){
69.1904 + pc = pOp->p2-1;
69.1905 + if( pOp->p1<0 ){
69.1906 + popStack(&pTos, -pOp->p1);
69.1907 + }
69.1908 + }
69.1909 + if( pOp->p1>0 ){
69.1910 + popStack(&pTos, pOp->p1);
69.1911 + }
69.1912 + break;
69.1913 +}
69.1914 +
69.1915 +/* Opcode: NotNull P1 P2 *
69.1916 +**
69.1917 +** Jump to P2 if the top abs(P1) values on the stack are all not NULL.
69.1918 +** Regardless of whether or not the jump is taken, pop the stack
69.1919 +** P1 times if P1 is greater than zero. But if P1 is negative,
69.1920 +** leave the stack unchanged.
69.1921 +*/
69.1922 +case OP_NotNull: { /* same as TK_NOTNULL, no-push */
69.1923 + int i, cnt;
69.1924 + cnt = pOp->p1;
69.1925 + if( cnt<0 ) cnt = -cnt;
69.1926 + assert( &pTos[1-cnt] >= p->aStack );
69.1927 + for(i=0; i<cnt && (pTos[1+i-cnt].flags & MEM_Null)==0; i++){}
69.1928 + if( i>=cnt ) pc = pOp->p2-1;
69.1929 + if( pOp->p1>0 ) popStack(&pTos, cnt);
69.1930 + break;
69.1931 +}
69.1932 +
69.1933 +/* Opcode: SetNumColumns P1 P2 *
69.1934 +**
69.1935 +** Before the OP_Column opcode can be executed on a cursor, this
69.1936 +** opcode must be called to set the number of fields in the table.
69.1937 +**
69.1938 +** This opcode sets the number of columns for cursor P1 to P2.
69.1939 +**
69.1940 +** If OP_KeyAsData is to be applied to cursor P1, it must be executed
69.1941 +** before this op-code.
69.1942 +*/
69.1943 +case OP_SetNumColumns: { /* no-push */
69.1944 + Cursor *pC;
69.1945 + assert( (pOp->p1)<p->nCursor );
69.1946 + assert( p->apCsr[pOp->p1]!=0 );
69.1947 + pC = p->apCsr[pOp->p1];
69.1948 + pC->nField = pOp->p2;
69.1949 + break;
69.1950 +}
69.1951 +
69.1952 +/* Opcode: Column P1 P2 P3
69.1953 +**
69.1954 +** Interpret the data that cursor P1 points to as a structure built using
69.1955 +** the MakeRecord instruction. (See the MakeRecord opcode for additional
69.1956 +** information about the format of the data.) Push onto the stack the value
69.1957 +** of the P2-th column contained in the data. If there are less that (P2+1)
69.1958 +** values in the record, push a NULL onto the stack.
69.1959 +**
69.1960 +** If the KeyAsData opcode has previously executed on this cursor, then the
69.1961 +** field might be extracted from the key rather than the data.
69.1962 +**
69.1963 +** If the column contains fewer than P2 fields, then push a NULL. Or
69.1964 +** if P3 is of type P3_MEM, then push the P3 value. The P3 value will
69.1965 +** be default value for a column that has been added using the ALTER TABLE
69.1966 +** ADD COLUMN command. If P3 is an ordinary string, just push a NULL.
69.1967 +** When P3 is a string it is really just a comment describing the value
69.1968 +** to be pushed, not a default value.
69.1969 +*/
69.1970 +case OP_Column: {
69.1971 + u32 payloadSize; /* Number of bytes in the record */
69.1972 + int p1 = pOp->p1; /* P1 value of the opcode */
69.1973 + int p2 = pOp->p2; /* column number to retrieve */
69.1974 + Cursor *pC = 0; /* The VDBE cursor */
69.1975 + char *zRec; /* Pointer to complete record-data */
69.1976 + BtCursor *pCrsr; /* The BTree cursor */
69.1977 + u32 *aType; /* aType[i] holds the numeric type of the i-th column */
69.1978 + u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
69.1979 + u32 nField; /* number of fields in the record */
69.1980 + int len; /* The length of the serialized data for the column */
69.1981 + int i; /* Loop counter */
69.1982 + char *zData; /* Part of the record being decoded */
69.1983 + Mem sMem; /* For storing the record being decoded */
69.1984 +
69.1985 + sMem.flags = 0;
69.1986 + assert( p1<p->nCursor );
69.1987 + pTos++;
69.1988 + pTos->flags = MEM_Null;
69.1989 +
69.1990 + /* This block sets the variable payloadSize to be the total number of
69.1991 + ** bytes in the record.
69.1992 + **
69.1993 + ** zRec is set to be the complete text of the record if it is available.
69.1994 + ** The complete record text is always available for pseudo-tables
69.1995 + ** If the record is stored in a cursor, the complete record text
69.1996 + ** might be available in the pC->aRow cache. Or it might not be.
69.1997 + ** If the data is unavailable, zRec is set to NULL.
69.1998 + **
69.1999 + ** We also compute the number of columns in the record. For cursors,
69.2000 + ** the number of columns is stored in the Cursor.nField element. For
69.2001 + ** records on the stack, the next entry down on the stack is an integer
69.2002 + ** which is the number of records.
69.2003 + */
69.2004 + pC = p->apCsr[p1];
69.2005 +#ifndef SQLITE_OMIT_VIRTUALTABLE
69.2006 + assert( pC->pVtabCursor==0 );
69.2007 +#endif
69.2008 + assert( pC!=0 );
69.2009 + if( pC->pCursor!=0 ){
69.2010 + /* The record is stored in a B-Tree */
69.2011 + rc = sqlite3VdbeCursorMoveto(pC);
69.2012 + if( rc ) goto abort_due_to_error;
69.2013 + zRec = 0;
69.2014 + pCrsr = pC->pCursor;
69.2015 + if( pC->nullRow ){
69.2016 + payloadSize = 0;
69.2017 + }else if( pC->cacheStatus==p->cacheCtr ){
69.2018 + payloadSize = pC->payloadSize;
69.2019 + zRec = (char*)pC->aRow;
69.2020 + }else if( pC->isIndex ){
69.2021 + i64 payloadSize64;
69.2022 + sqlite3BtreeKeySize(pCrsr, &payloadSize64);
69.2023 + payloadSize = payloadSize64;
69.2024 + }else{
69.2025 + sqlite3BtreeDataSize(pCrsr, &payloadSize);
69.2026 + }
69.2027 + nField = pC->nField;
69.2028 + }else if( pC->pseudoTable ){
69.2029 + /* The record is the sole entry of a pseudo-table */
69.2030 + payloadSize = pC->nData;
69.2031 + zRec = pC->pData;
69.2032 + pC->cacheStatus = CACHE_STALE;
69.2033 + assert( payloadSize==0 || zRec!=0 );
69.2034 + nField = pC->nField;
69.2035 + pCrsr = 0;
69.2036 + }else{
69.2037 + zRec = 0;
69.2038 + payloadSize = 0;
69.2039 + pCrsr = 0;
69.2040 + nField = 0;
69.2041 + }
69.2042 +
69.2043 + /* If payloadSize is 0, then just push a NULL onto the stack. */
69.2044 + if( payloadSize==0 ){
69.2045 + assert( pTos->flags==MEM_Null );
69.2046 + break;
69.2047 + }
69.2048 + if( payloadSize>SQLITE_MAX_LENGTH ){
69.2049 + goto too_big;
69.2050 + }
69.2051 +
69.2052 + assert( p2<nField );
69.2053 +
69.2054 + /* Read and parse the table header. Store the results of the parse
69.2055 + ** into the record header cache fields of the cursor.
69.2056 + */
69.2057 + if( pC && pC->cacheStatus==p->cacheCtr ){
69.2058 + aType = pC->aType;
69.2059 + aOffset = pC->aOffset;
69.2060 + }else{
69.2061 + u8 *zIdx; /* Index into header */
69.2062 + u8 *zEndHdr; /* Pointer to first byte after the header */
69.2063 + u32 offset; /* Offset into the data */
69.2064 + int szHdrSz; /* Size of the header size field at start of record */
69.2065 + int avail; /* Number of bytes of available data */
69.2066 +
69.2067 + aType = pC->aType;
69.2068 + if( aType==0 ){
69.2069 + pC->aType = aType = sqliteMallocRaw( 2*nField*sizeof(aType) );
69.2070 + }
69.2071 + if( aType==0 ){
69.2072 + goto no_mem;
69.2073 + }
69.2074 + pC->aOffset = aOffset = &aType[nField];
69.2075 + pC->payloadSize = payloadSize;
69.2076 + pC->cacheStatus = p->cacheCtr;
69.2077 +
69.2078 + /* Figure out how many bytes are in the header */
69.2079 + if( zRec ){
69.2080 + zData = zRec;
69.2081 + }else{
69.2082 + if( pC->isIndex ){
69.2083 + zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
69.2084 + }else{
69.2085 + zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
69.2086 + }
69.2087 + /* If KeyFetch()/DataFetch() managed to get the entire payload,
69.2088 + ** save the payload in the pC->aRow cache. That will save us from
69.2089 + ** having to make additional calls to fetch the content portion of
69.2090 + ** the record.
69.2091 + */
69.2092 + if( avail>=payloadSize ){
69.2093 + zRec = zData;
69.2094 + pC->aRow = (u8*)zData;
69.2095 + }else{
69.2096 + pC->aRow = 0;
69.2097 + }
69.2098 + }
69.2099 + /* The following assert is true in all cases accept when
69.2100 + ** the database file has been corrupted externally.
69.2101 + ** assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
69.2102 + szHdrSz = GetVarint((u8*)zData, offset);
69.2103 +
69.2104 + /* The KeyFetch() or DataFetch() above are fast and will get the entire
69.2105 + ** record header in most cases. But they will fail to get the complete
69.2106 + ** record header if the record header does not fit on a single page
69.2107 + ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
69.2108 + ** acquire the complete header text.
69.2109 + */
69.2110 + if( !zRec && avail<offset ){
69.2111 + rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
69.2112 + if( rc!=SQLITE_OK ){
69.2113 + goto op_column_out;
69.2114 + }
69.2115 + zData = sMem.z;
69.2116 + }
69.2117 + zEndHdr = (u8 *)&zData[offset];
69.2118 + zIdx = (u8 *)&zData[szHdrSz];
69.2119 +
69.2120 + /* Scan the header and use it to fill in the aType[] and aOffset[]
69.2121 + ** arrays. aType[i] will contain the type integer for the i-th
69.2122 + ** column and aOffset[i] will contain the offset from the beginning
69.2123 + ** of the record to the start of the data for the i-th column
69.2124 + */
69.2125 + for(i=0; i<nField; i++){
69.2126 + if( zIdx<zEndHdr ){
69.2127 + aOffset[i] = offset;
69.2128 + zIdx += GetVarint(zIdx, aType[i]);
69.2129 + offset += sqlite3VdbeSerialTypeLen(aType[i]);
69.2130 + }else{
69.2131 + /* If i is less that nField, then there are less fields in this
69.2132 + ** record than SetNumColumns indicated there are columns in the
69.2133 + ** table. Set the offset for any extra columns not present in
69.2134 + ** the record to 0. This tells code below to push a NULL onto the
69.2135 + ** stack instead of deserializing a value from the record.
69.2136 + */
69.2137 + aOffset[i] = 0;
69.2138 + }
69.2139 + }
69.2140 + Release(&sMem);
69.2141 + sMem.flags = MEM_Null;
69.2142 +
69.2143 + /* If we have read more header data than was contained in the header,
69.2144 + ** or if the end of the last field appears to be past the end of the
69.2145 + ** record, then we must be dealing with a corrupt database.
69.2146 + */
69.2147 + if( zIdx>zEndHdr || offset>payloadSize ){
69.2148 + rc = SQLITE_CORRUPT_BKPT;
69.2149 + goto op_column_out;
69.2150 + }
69.2151 + }
69.2152 +
69.2153 + /* Get the column information. If aOffset[p2] is non-zero, then
69.2154 + ** deserialize the value from the record. If aOffset[p2] is zero,
69.2155 + ** then there are not enough fields in the record to satisfy the
69.2156 + ** request. In this case, set the value NULL or to P3 if P3 is
69.2157 + ** a pointer to a Mem object.
69.2158 + */
69.2159 + if( aOffset[p2] ){
69.2160 + assert( rc==SQLITE_OK );
69.2161 + if( zRec ){
69.2162 + zData = &zRec[aOffset[p2]];
69.2163 + }else{
69.2164 + len = sqlite3VdbeSerialTypeLen(aType[p2]);
69.2165 + rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex,&sMem);
69.2166 + if( rc!=SQLITE_OK ){
69.2167 + goto op_column_out;
69.2168 + }
69.2169 + zData = sMem.z;
69.2170 + }
69.2171 + sqlite3VdbeSerialGet((u8*)zData, aType[p2], pTos);
69.2172 + pTos->enc = encoding;
69.2173 + }else{
69.2174 + if( pOp->p3type==P3_MEM ){
69.2175 + sqlite3VdbeMemShallowCopy(pTos, (Mem *)(pOp->p3), MEM_Static);
69.2176 + }else{
69.2177 + pTos->flags = MEM_Null;
69.2178 + }
69.2179 + }
69.2180 +
69.2181 + /* If we dynamically allocated space to hold the data (in the
69.2182 + ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
69.2183 + ** dynamically allocated space over to the pTos structure.
69.2184 + ** This prevents a memory copy.
69.2185 + */
69.2186 + if( (sMem.flags & MEM_Dyn)!=0 ){
69.2187 + assert( pTos->flags & MEM_Ephem );
69.2188 + assert( pTos->flags & (MEM_Str|MEM_Blob) );
69.2189 + assert( pTos->z==sMem.z );
69.2190 + assert( sMem.flags & MEM_Term );
69.2191 + pTos->flags &= ~MEM_Ephem;
69.2192 + pTos->flags |= MEM_Dyn|MEM_Term;
69.2193 + }
69.2194 +
69.2195 + /* pTos->z might be pointing to sMem.zShort[]. Fix that so that we
69.2196 + ** can abandon sMem */
69.2197 + rc = sqlite3VdbeMemMakeWriteable(pTos);
69.2198 +
69.2199 +op_column_out:
69.2200 + break;
69.2201 +}
69.2202 +
69.2203 +/* Opcode: MakeRecord P1 P2 P3
69.2204 +**
69.2205 +** Convert the top abs(P1) entries of the stack into a single entry
69.2206 +** suitable for use as a data record in a database table or as a key
69.2207 +** in an index. The details of the format are irrelavant as long as
69.2208 +** the OP_Column opcode can decode the record later and as long as the
69.2209 +** sqlite3VdbeRecordCompare function will correctly compare two encoded
69.2210 +** records. Refer to source code comments for the details of the record
69.2211 +** format.
69.2212 +**
69.2213 +** The original stack entries are popped from the stack if P1>0 but
69.2214 +** remain on the stack if P1<0.
69.2215 +**
69.2216 +** If P2 is not zero and one or more of the entries are NULL, then jump
69.2217 +** to the address given by P2. This feature can be used to skip a
69.2218 +** uniqueness test on indices.
69.2219 +**
69.2220 +** P3 may be a string that is P1 characters long. The nth character of the
69.2221 +** string indicates the column affinity that should be used for the nth
69.2222 +** field of the index key (i.e. the first character of P3 corresponds to the
69.2223 +** lowest element on the stack).
69.2224 +**
69.2225 +** The mapping from character to affinity is given by the SQLITE_AFF_
69.2226 +** macros defined in sqliteInt.h.
69.2227 +**
69.2228 +** If P3 is NULL then all index fields have the affinity NONE.
69.2229 +**
69.2230 +** See also OP_MakeIdxRec
69.2231 +*/
69.2232 +/* Opcode: MakeIdxRec P1 P2 P3
69.2233 +**
69.2234 +** This opcode works just OP_MakeRecord except that it reads an extra
69.2235 +** integer from the stack (thus reading a total of abs(P1+1) entries)
69.2236 +** and appends that extra integer to the end of the record as a varint.
69.2237 +** This results in an index key.
69.2238 +*/
69.2239 +case OP_MakeIdxRec:
69.2240 +case OP_MakeRecord: {
69.2241 + /* Assuming the record contains N fields, the record format looks
69.2242 + ** like this:
69.2243 + **
69.2244 + ** ------------------------------------------------------------------------
69.2245 + ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
69.2246 + ** ------------------------------------------------------------------------
69.2247 + **
69.2248 + ** Data(0) is taken from the lowest element of the stack and data(N-1) is
69.2249 + ** the top of the stack.
69.2250 + **
69.2251 + ** Each type field is a varint representing the serial type of the
69.2252 + ** corresponding data element (see sqlite3VdbeSerialType()). The
69.2253 + ** hdr-size field is also a varint which is the offset from the beginning
69.2254 + ** of the record to data0.
69.2255 + */
69.2256 + u8 *zNewRecord; /* A buffer to hold the data for the new record */
69.2257 + Mem *pRec; /* The new record */
69.2258 + Mem *pRowid = 0; /* Rowid appended to the new record */
69.2259 + u64 nData = 0; /* Number of bytes of data space */
69.2260 + int nHdr = 0; /* Number of bytes of header space */
69.2261 + u64 nByte = 0; /* Data space required for this record */
69.2262 + int nZero = 0; /* Number of zero bytes at the end of the record */
69.2263 + int nVarint; /* Number of bytes in a varint */
69.2264 + u32 serial_type; /* Type field */
69.2265 + int containsNull = 0; /* True if any of the data fields are NULL */
69.2266 + Mem *pData0; /* Bottom of the stack */
69.2267 + int leaveOnStack; /* If true, leave the entries on the stack */
69.2268 + int nField; /* Number of fields in the record */
69.2269 + int jumpIfNull; /* Jump here if non-zero and any entries are NULL. */
69.2270 + int addRowid; /* True to append a rowid column at the end */
69.2271 + char *zAffinity; /* The affinity string for the record */
69.2272 + int file_format; /* File format to use for encoding */
69.2273 + int i; /* Space used in zNewRecord[] */
69.2274 + char zTemp[NBFS]; /* Space to hold small records */
69.2275 +
69.2276 + leaveOnStack = ((pOp->p1<0)?1:0);
69.2277 + nField = pOp->p1 * (leaveOnStack?-1:1);
69.2278 + jumpIfNull = pOp->p2;
69.2279 + addRowid = pOp->opcode==OP_MakeIdxRec;
69.2280 + zAffinity = pOp->p3;
69.2281 +
69.2282 + pData0 = &pTos[1-nField];
69.2283 + assert( pData0>=p->aStack );
69.2284 + containsNull = 0;
69.2285 + file_format = p->minWriteFileFormat;
69.2286 +
69.2287 + /* Loop through the elements that will make up the record to figure
69.2288 + ** out how much space is required for the new record.
69.2289 + */
69.2290 + for(pRec=pData0; pRec<=pTos; pRec++){
69.2291 + int len;
69.2292 + if( zAffinity ){
69.2293 + applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
69.2294 + }
69.2295 + if( pRec->flags&MEM_Null ){
69.2296 + containsNull = 1;
69.2297 + }
69.2298 + if( pRec->flags&MEM_Zero && pRec->n>0 ){
69.2299 + ExpandBlob(pRec);
69.2300 + }
69.2301 + serial_type = sqlite3VdbeSerialType(pRec, file_format);
69.2302 + len = sqlite3VdbeSerialTypeLen(serial_type);
69.2303 + nData += len;
69.2304 + nHdr += sqlite3VarintLen(serial_type);
69.2305 + if( pRec->flags & MEM_Zero ){
69.2306 + /* Only pure zero-filled BLOBs can be input to this Opcode.
69.2307 + ** We do not allow blobs with a prefix and a zero-filled tail. */
69.2308 + nZero += pRec->u.i;
69.2309 + }else if( len ){
69.2310 + nZero = 0;
69.2311 + }
69.2312 + }
69.2313 +
69.2314 + /* If we have to append a varint rowid to this record, set pRowid
69.2315 + ** to the value of the rowid and increase nByte by the amount of space
69.2316 + ** required to store it.
69.2317 + */
69.2318 + if( addRowid ){
69.2319 + pRowid = &pTos[0-nField];
69.2320 + assert( pRowid>=p->aStack );
69.2321 + sqlite3VdbeMemIntegerify(pRowid);
69.2322 + serial_type = sqlite3VdbeSerialType(pRowid, 0);
69.2323 + nData += sqlite3VdbeSerialTypeLen(serial_type);
69.2324 + nHdr += sqlite3VarintLen(serial_type);
69.2325 + nZero = 0;
69.2326 + }
69.2327 +
69.2328 + /* Add the initial header varint and total the size */
69.2329 + nHdr += nVarint = sqlite3VarintLen(nHdr);
69.2330 + if( nVarint<sqlite3VarintLen(nHdr) ){
69.2331 + nHdr++;
69.2332 + }
69.2333 + nByte = nHdr+nData-nZero;
69.2334 + if( nByte>SQLITE_MAX_LENGTH ){
69.2335 + goto too_big;
69.2336 + }
69.2337 +
69.2338 + /* Allocate space for the new record. */
69.2339 + if( nByte>sizeof(zTemp) ){
69.2340 + zNewRecord = sqliteMallocRaw(nByte);
69.2341 + if( !zNewRecord ){
69.2342 + goto no_mem;
69.2343 + }
69.2344 + }else{
69.2345 + zNewRecord = (u8*)zTemp;
69.2346 + }
69.2347 +
69.2348 + /* Write the record */
69.2349 + i = sqlite3PutVarint(zNewRecord, nHdr);
69.2350 + for(pRec=pData0; pRec<=pTos; pRec++){
69.2351 + serial_type = sqlite3VdbeSerialType(pRec, file_format);
69.2352 + i += sqlite3PutVarint(&zNewRecord[i], serial_type); /* serial type */
69.2353 + }
69.2354 + if( addRowid ){
69.2355 + i += sqlite3PutVarint(&zNewRecord[i], sqlite3VdbeSerialType(pRowid, 0));
69.2356 + }
69.2357 + for(pRec=pData0; pRec<=pTos; pRec++){ /* serial data */
69.2358 + i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format);
69.2359 + }
69.2360 + if( addRowid ){
69.2361 + i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRowid, 0);
69.2362 + }
69.2363 + assert( i==nByte );
69.2364 +
69.2365 + /* Pop entries off the stack if required. Push the new record on. */
69.2366 + if( !leaveOnStack ){
69.2367 + popStack(&pTos, nField+addRowid);
69.2368 + }
69.2369 + pTos++;
69.2370 + pTos->n = nByte;
69.2371 + if( nByte<=sizeof(zTemp) ){
69.2372 + assert( zNewRecord==(unsigned char *)zTemp );
69.2373 + pTos->z = pTos->zShort;
69.2374 + memcpy(pTos->zShort, zTemp, nByte);
69.2375 + pTos->flags = MEM_Blob | MEM_Short;
69.2376 + }else{
69.2377 + assert( zNewRecord!=(unsigned char *)zTemp );
69.2378 + pTos->z = (char*)zNewRecord;
69.2379 + pTos->flags = MEM_Blob | MEM_Dyn;
69.2380 + pTos->xDel = 0;
69.2381 + }
69.2382 + if( nZero ){
69.2383 + pTos->u.i = nZero;
69.2384 + pTos->flags |= MEM_Zero;
69.2385 + }
69.2386 + pTos->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
69.2387 +
69.2388 + /* If a NULL was encountered and jumpIfNull is non-zero, take the jump. */
69.2389 + if( jumpIfNull && containsNull ){
69.2390 + pc = jumpIfNull - 1;
69.2391 + }
69.2392 + break;
69.2393 +}
69.2394 +
69.2395 +/* Opcode: Statement P1 * *
69.2396 +**
69.2397 +** Begin an individual statement transaction which is part of a larger
69.2398 +** BEGIN..COMMIT transaction. This is needed so that the statement
69.2399 +** can be rolled back after an error without having to roll back the
69.2400 +** entire transaction. The statement transaction will automatically
69.2401 +** commit when the VDBE halts.
69.2402 +**
69.2403 +** The statement is begun on the database file with index P1. The main
69.2404 +** database file has an index of 0 and the file used for temporary tables
69.2405 +** has an index of 1.
69.2406 +*/
69.2407 +case OP_Statement: { /* no-push */
69.2408 + int i = pOp->p1;
69.2409 + Btree *pBt;
69.2410 + if( i>=0 && i<db->nDb && (pBt = db->aDb[i].pBt)!=0 && !(db->autoCommit) ){
69.2411 + assert( sqlite3BtreeIsInTrans(pBt) );
69.2412 + if( !sqlite3BtreeIsInStmt(pBt) ){
69.2413 + rc = sqlite3BtreeBeginStmt(pBt);
69.2414 + p->openedStatement = 1;
69.2415 + }
69.2416 + }
69.2417 + break;
69.2418 +}
69.2419 +
69.2420 +/* Opcode: AutoCommit P1 P2 *
69.2421 +**
69.2422 +** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
69.2423 +** back any currently active btree transactions. If there are any active
69.2424 +** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
69.2425 +**
69.2426 +** This instruction causes the VM to halt.
69.2427 +*/
69.2428 +case OP_AutoCommit: { /* no-push */
69.2429 + u8 i = pOp->p1;
69.2430 + u8 rollback = pOp->p2;
69.2431 +
69.2432 + assert( i==1 || i==0 );
69.2433 + assert( i==1 || rollback==0 );
69.2434 +
69.2435 + assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */
69.2436 +
69.2437 + if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
69.2438 + /* If this instruction implements a COMMIT or ROLLBACK, other VMs are
69.2439 + ** still running, and a transaction is active, return an error indicating
69.2440 + ** that the other VMs must complete first.
69.2441 + */
69.2442 + sqlite3SetString(&p->zErrMsg, "cannot ", rollback?"rollback":"commit",
69.2443 + " transaction - SQL statements in progress", (char*)0);
69.2444 + rc = SQLITE_ERROR;
69.2445 + }else if( i!=db->autoCommit ){
69.2446 + if( pOp->p2 ){
69.2447 + assert( i==1 );
69.2448 + sqlite3RollbackAll(db);
69.2449 + db->autoCommit = 1;
69.2450 + }else{
69.2451 + db->autoCommit = i;
69.2452 + if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
69.2453 + p->pTos = pTos;
69.2454 + p->pc = pc;
69.2455 + db->autoCommit = 1-i;
69.2456 + p->rc = SQLITE_BUSY;
69.2457 + return SQLITE_BUSY;
69.2458 + }
69.2459 + }
69.2460 + if( p->rc==SQLITE_OK ){
69.2461 + return SQLITE_DONE;
69.2462 + }else{
69.2463 + return SQLITE_ERROR;
69.2464 + }
69.2465 + }else{
69.2466 + sqlite3SetString(&p->zErrMsg,
69.2467 + (!i)?"cannot start a transaction within a transaction":(
69.2468 + (rollback)?"cannot rollback - no transaction is active":
69.2469 + "cannot commit - no transaction is active"), (char*)0);
69.2470 +
69.2471 + rc = SQLITE_ERROR;
69.2472 + }
69.2473 + break;
69.2474 +}
69.2475 +
69.2476 +/* Opcode: Transaction P1 P2 *
69.2477 +**
69.2478 +** Begin a transaction. The transaction ends when a Commit or Rollback
69.2479 +** opcode is encountered. Depending on the ON CONFLICT setting, the
69.2480 +** transaction might also be rolled back if an error is encountered.
69.2481 +**
69.2482 +** P1 is the index of the database file on which the transaction is
69.2483 +** started. Index 0 is the main database file and index 1 is the
69.2484 +** file used for temporary tables.
69.2485 +**
69.2486 +** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
69.2487 +** obtained on the database file when a write-transaction is started. No
69.2488 +** other process can start another write transaction while this transaction is
69.2489 +** underway. Starting a write transaction also creates a rollback journal. A
69.2490 +** write transaction must be started before any changes can be made to the
69.2491 +** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
69.2492 +** on the file.
69.2493 +**
69.2494 +** If P2 is zero, then a read-lock is obtained on the database file.
69.2495 +*/
69.2496 +case OP_Transaction: { /* no-push */
69.2497 + int i = pOp->p1;
69.2498 + Btree *pBt;
69.2499 +
69.2500 + assert( i>=0 && i<db->nDb );
69.2501 + pBt = db->aDb[i].pBt;
69.2502 +
69.2503 + if( pBt ){
69.2504 + rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
69.2505 + if( rc==SQLITE_BUSY ){
69.2506 + p->pc = pc;
69.2507 + p->rc = SQLITE_BUSY;
69.2508 + p->pTos = pTos;
69.2509 + return SQLITE_BUSY;
69.2510 + }
69.2511 + if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
69.2512 + goto abort_due_to_error;
69.2513 + }
69.2514 + }
69.2515 + break;
69.2516 +}
69.2517 +
69.2518 +/* Opcode: ReadCookie P1 P2 *
69.2519 +**
69.2520 +** Read cookie number P2 from database P1 and push it onto the stack.
69.2521 +** P2==0 is the schema version. P2==1 is the database format.
69.2522 +** P2==2 is the recommended pager cache size, and so forth. P1==0 is
69.2523 +** the main database file and P1==1 is the database file used to store
69.2524 +** temporary tables.
69.2525 +**
69.2526 +** If P1 is negative, then this is a request to read the size of a
69.2527 +** databases free-list. P2 must be set to 1 in this case. The actual
69.2528 +** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
69.2529 +** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
69.2530 +**
69.2531 +** There must be a read-lock on the database (either a transaction
69.2532 +** must be started or there must be an open cursor) before
69.2533 +** executing this instruction.
69.2534 +*/
69.2535 +case OP_ReadCookie: {
69.2536 + int iMeta;
69.2537 + int iDb = pOp->p1;
69.2538 + int iCookie = pOp->p2;
69.2539 +
69.2540 + assert( pOp->p2<SQLITE_N_BTREE_META );
69.2541 + if( iDb<0 ){
69.2542 + iDb = (-1*(iDb+1));
69.2543 + iCookie *= -1;
69.2544 + }
69.2545 + assert( iDb>=0 && iDb<db->nDb );
69.2546 + assert( db->aDb[iDb].pBt!=0 );
69.2547 + /* The indexing of meta values at the schema layer is off by one from
69.2548 + ** the indexing in the btree layer. The btree considers meta[0] to
69.2549 + ** be the number of free pages in the database (a read-only value)
69.2550 + ** and meta[1] to be the schema cookie. The schema layer considers
69.2551 + ** meta[1] to be the schema cookie. So we have to shift the index
69.2552 + ** by one in the following statement.
69.2553 + */
69.2554 + rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
69.2555 + pTos++;
69.2556 + pTos->u.i = iMeta;
69.2557 + pTos->flags = MEM_Int;
69.2558 + break;
69.2559 +}
69.2560 +
69.2561 +/* Opcode: SetCookie P1 P2 *
69.2562 +**
69.2563 +** Write the top of the stack into cookie number P2 of database P1.
69.2564 +** P2==0 is the schema version. P2==1 is the database format.
69.2565 +** P2==2 is the recommended pager cache size, and so forth. P1==0 is
69.2566 +** the main database file and P1==1 is the database file used to store
69.2567 +** temporary tables.
69.2568 +**
69.2569 +** A transaction must be started before executing this opcode.
69.2570 +*/
69.2571 +case OP_SetCookie: { /* no-push */
69.2572 + Db *pDb;
69.2573 + assert( pOp->p2<SQLITE_N_BTREE_META );
69.2574 + assert( pOp->p1>=0 && pOp->p1<db->nDb );
69.2575 + pDb = &db->aDb[pOp->p1];
69.2576 + assert( pDb->pBt!=0 );
69.2577 + assert( pTos>=p->aStack );
69.2578 + sqlite3VdbeMemIntegerify(pTos);
69.2579 + /* See note about index shifting on OP_ReadCookie */
69.2580 + rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pTos->u.i);
69.2581 + if( pOp->p2==0 ){
69.2582 + /* When the schema cookie changes, record the new cookie internally */
69.2583 + pDb->pSchema->schema_cookie = pTos->u.i;
69.2584 + db->flags |= SQLITE_InternChanges;
69.2585 + }else if( pOp->p2==1 ){
69.2586 + /* Record changes in the file format */
69.2587 + pDb->pSchema->file_format = pTos->u.i;
69.2588 + }
69.2589 + assert( (pTos->flags & MEM_Dyn)==0 );
69.2590 + pTos--;
69.2591 + if( pOp->p1==1 ){
69.2592 + /* Invalidate all prepared statements whenever the TEMP database
69.2593 + ** schema is changed. Ticket #1644 */
69.2594 + sqlite3ExpirePreparedStatements(db);
69.2595 + }
69.2596 + break;
69.2597 +}
69.2598 +
69.2599 +/* Opcode: VerifyCookie P1 P2 *
69.2600 +**
69.2601 +** Check the value of global database parameter number 0 (the
69.2602 +** schema version) and make sure it is equal to P2.
69.2603 +** P1 is the database number which is 0 for the main database file
69.2604 +** and 1 for the file holding temporary tables and some higher number
69.2605 +** for auxiliary databases.
69.2606 +**
69.2607 +** The cookie changes its value whenever the database schema changes.
69.2608 +** This operation is used to detect when that the cookie has changed
69.2609 +** and that the current process needs to reread the schema.
69.2610 +**
69.2611 +** Either a transaction needs to have been started or an OP_Open needs
69.2612 +** to be executed (to establish a read lock) before this opcode is
69.2613 +** invoked.
69.2614 +*/
69.2615 +case OP_VerifyCookie: { /* no-push */
69.2616 + int iMeta;
69.2617 + Btree *pBt;
69.2618 + assert( pOp->p1>=0 && pOp->p1<db->nDb );
69.2619 + pBt = db->aDb[pOp->p1].pBt;
69.2620 + if( pBt ){
69.2621 + rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
69.2622 + }else{
69.2623 + rc = SQLITE_OK;
69.2624 + iMeta = 0;
69.2625 + }
69.2626 + if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
69.2627 + sqlite3SetString(&p->zErrMsg, "database schema has changed", (char*)0);
69.2628 + /* If the schema-cookie from the database file matches the cookie
69.2629 + ** stored with the in-memory representation of the schema, do
69.2630 + ** not reload the schema from the database file.
69.2631 + **
69.2632 + ** If virtual-tables are in use, this is not just an optimisation.
69.2633 + ** Often, v-tables store their data in other SQLite tables, which
69.2634 + ** are queried from within xNext() and other v-table methods using
69.2635 + ** prepared queries. If such a query is out-of-date, we do not want to
69.2636 + ** discard the database schema, as the user code implementing the
69.2637 + ** v-table would have to be ready for the sqlite3_vtab structure itself
69.2638 + ** to be invalidated whenever sqlite3_step() is called from within
69.2639 + ** a v-table method.
69.2640 + */
69.2641 + if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
69.2642 + sqlite3ResetInternalSchema(db, pOp->p1);
69.2643 + }
69.2644 +
69.2645 + sqlite3ExpirePreparedStatements(db);
69.2646 + rc = SQLITE_SCHEMA;
69.2647 + }
69.2648 + break;
69.2649 +}
69.2650 +
69.2651 +/* Opcode: OpenRead P1 P2 P3
69.2652 +**
69.2653 +** Open a read-only cursor for the database table whose root page is
69.2654 +** P2 in a database file. The database file is determined by an
69.2655 +** integer from the top of the stack. 0 means the main database and
69.2656 +** 1 means the database used for temporary tables. Give the new
69.2657 +** cursor an identifier of P1. The P1 values need not be contiguous
69.2658 +** but all P1 values should be small integers. It is an error for
69.2659 +** P1 to be negative.
69.2660 +**
69.2661 +** If P2==0 then take the root page number from the next of the stack.
69.2662 +**
69.2663 +** There will be a read lock on the database whenever there is an
69.2664 +** open cursor. If the database was unlocked prior to this instruction
69.2665 +** then a read lock is acquired as part of this instruction. A read
69.2666 +** lock allows other processes to read the database but prohibits
69.2667 +** any other process from modifying the database. The read lock is
69.2668 +** released when all cursors are closed. If this instruction attempts
69.2669 +** to get a read lock but fails, the script terminates with an
69.2670 +** SQLITE_BUSY error code.
69.2671 +**
69.2672 +** The P3 value is a pointer to a KeyInfo structure that defines the
69.2673 +** content and collating sequence of indices. P3 is NULL for cursors
69.2674 +** that are not pointing to indices.
69.2675 +**
69.2676 +** See also OpenWrite.
69.2677 +*/
69.2678 +/* Opcode: OpenWrite P1 P2 P3
69.2679 +**
69.2680 +** Open a read/write cursor named P1 on the table or index whose root
69.2681 +** page is P2. If P2==0 then take the root page number from the stack.
69.2682 +**
69.2683 +** The P3 value is a pointer to a KeyInfo structure that defines the
69.2684 +** content and collating sequence of indices. P3 is NULL for cursors
69.2685 +** that are not pointing to indices.
69.2686 +**
69.2687 +** This instruction works just like OpenRead except that it opens the cursor
69.2688 +** in read/write mode. For a given table, there can be one or more read-only
69.2689 +** cursors or a single read/write cursor but not both.
69.2690 +**
69.2691 +** See also OpenRead.
69.2692 +*/
69.2693 +case OP_OpenRead: /* no-push */
69.2694 +case OP_OpenWrite: { /* no-push */
69.2695 + int i = pOp->p1;
69.2696 + int p2 = pOp->p2;
69.2697 + int wrFlag;
69.2698 + Btree *pX;
69.2699 + int iDb;
69.2700 + Cursor *pCur;
69.2701 + Db *pDb;
69.2702 +
69.2703 + assert( pTos>=p->aStack );
69.2704 + sqlite3VdbeMemIntegerify(pTos);
69.2705 + iDb = pTos->u.i;
69.2706 + assert( (pTos->flags & MEM_Dyn)==0 );
69.2707 + pTos--;
69.2708 + assert( iDb>=0 && iDb<db->nDb );
69.2709 + pDb = &db->aDb[iDb];
69.2710 + pX = pDb->pBt;
69.2711 + assert( pX!=0 );
69.2712 + if( pOp->opcode==OP_OpenWrite ){
69.2713 + wrFlag = 1;
69.2714 + if( pDb->pSchema->file_format < p->minWriteFileFormat ){
69.2715 + p->minWriteFileFormat = pDb->pSchema->file_format;
69.2716 + }
69.2717 + }else{
69.2718 + wrFlag = 0;
69.2719 + }
69.2720 + if( p2<=0 ){
69.2721 + assert( pTos>=p->aStack );
69.2722 + sqlite3VdbeMemIntegerify(pTos);
69.2723 + p2 = pTos->u.i;
69.2724 + assert( (pTos->flags & MEM_Dyn)==0 );
69.2725 + pTos--;
69.2726 + assert( p2>=2 );
69.2727 + }
69.2728 + assert( i>=0 );
69.2729 + pCur = allocateCursor(p, i, iDb);
69.2730 + if( pCur==0 ) goto no_mem;
69.2731 + pCur->nullRow = 1;
69.2732 + if( pX==0 ) break;
69.2733 + /* We always provide a key comparison function. If the table being
69.2734 + ** opened is of type INTKEY, the comparision function will be ignored. */
69.2735 + rc = sqlite3BtreeCursor(pX, p2, wrFlag,
69.2736 + sqlite3VdbeRecordCompare, pOp->p3,
69.2737 + &pCur->pCursor);
69.2738 + if( pOp->p3type==P3_KEYINFO ){
69.2739 + pCur->pKeyInfo = (KeyInfo*)pOp->p3;
69.2740 + pCur->pIncrKey = &pCur->pKeyInfo->incrKey;
69.2741 + pCur->pKeyInfo->enc = ENC(p->db);
69.2742 + }else{
69.2743 + pCur->pKeyInfo = 0;
69.2744 + pCur->pIncrKey = &pCur->bogusIncrKey;
69.2745 + }
69.2746 + switch( rc ){
69.2747 + case SQLITE_BUSY: {
69.2748 + p->pc = pc;
69.2749 + p->rc = SQLITE_BUSY;
69.2750 + p->pTos = &pTos[1 + (pOp->p2<=0)]; /* Operands must remain on stack */
69.2751 + return SQLITE_BUSY;
69.2752 + }
69.2753 + case SQLITE_OK: {
69.2754 + int flags = sqlite3BtreeFlags(pCur->pCursor);
69.2755 + /* Sanity checking. Only the lower four bits of the flags byte should
69.2756 + ** be used. Bit 3 (mask 0x08) is unpreditable. The lower 3 bits
69.2757 + ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
69.2758 + ** 2 (zerodata for indices). If these conditions are not met it can
69.2759 + ** only mean that we are dealing with a corrupt database file
69.2760 + */
69.2761 + if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
69.2762 + rc = SQLITE_CORRUPT_BKPT;
69.2763 + goto abort_due_to_error;
69.2764 + }
69.2765 + pCur->isTable = (flags & BTREE_INTKEY)!=0;
69.2766 + pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
69.2767 + /* If P3==0 it means we are expected to open a table. If P3!=0 then
69.2768 + ** we expect to be opening an index. If this is not what happened,
69.2769 + ** then the database is corrupt
69.2770 + */
69.2771 + if( (pCur->isTable && pOp->p3type==P3_KEYINFO)
69.2772 + || (pCur->isIndex && pOp->p3type!=P3_KEYINFO) ){
69.2773 + rc = SQLITE_CORRUPT_BKPT;
69.2774 + goto abort_due_to_error;
69.2775 + }
69.2776 + break;
69.2777 + }
69.2778 + case SQLITE_EMPTY: {
69.2779 + pCur->isTable = pOp->p3type!=P3_KEYINFO;
69.2780 + pCur->isIndex = !pCur->isTable;
69.2781 + rc = SQLITE_OK;
69.2782 + break;
69.2783 + }
69.2784 + default: {
69.2785 + goto abort_due_to_error;
69.2786 + }
69.2787 + }
69.2788 + break;
69.2789 +}
69.2790 +
69.2791 +/* Opcode: OpenEphemeral P1 P2 P3
69.2792 +**
69.2793 +** Open a new cursor P1 to a transient table.
69.2794 +** The cursor is always opened read/write even if
69.2795 +** the main database is read-only. The transient or virtual
69.2796 +** table is deleted automatically when the cursor is closed.
69.2797 +**
69.2798 +** P2 is the number of columns in the virtual table.
69.2799 +** The cursor points to a BTree table if P3==0 and to a BTree index
69.2800 +** if P3 is not 0. If P3 is not NULL, it points to a KeyInfo structure
69.2801 +** that defines the format of keys in the index.
69.2802 +**
69.2803 +** This opcode was once called OpenTemp. But that created
69.2804 +** confusion because the term "temp table", might refer either
69.2805 +** to a TEMP table at the SQL level, or to a table opened by
69.2806 +** this opcode. Then this opcode was call OpenVirtual. But
69.2807 +** that created confusion with the whole virtual-table idea.
69.2808 +*/
69.2809 +case OP_OpenEphemeral: { /* no-push */
69.2810 + int i = pOp->p1;
69.2811 + Cursor *pCx;
69.2812 + assert( i>=0 );
69.2813 + pCx = allocateCursor(p, i, -1);
69.2814 + if( pCx==0 ) goto no_mem;
69.2815 + pCx->nullRow = 1;
69.2816 + rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, &pCx->pBt);
69.2817 + if( rc==SQLITE_OK ){
69.2818 + rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
69.2819 + }
69.2820 + if( rc==SQLITE_OK ){
69.2821 + /* If a transient index is required, create it by calling
69.2822 + ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
69.2823 + ** opening it. If a transient table is required, just use the
69.2824 + ** automatically created table with root-page 1 (an INTKEY table).
69.2825 + */
69.2826 + if( pOp->p3 ){
69.2827 + int pgno;
69.2828 + assert( pOp->p3type==P3_KEYINFO );
69.2829 + rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA);
69.2830 + if( rc==SQLITE_OK ){
69.2831 + assert( pgno==MASTER_ROOT+1 );
69.2832 + rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, sqlite3VdbeRecordCompare,
69.2833 + pOp->p3, &pCx->pCursor);
69.2834 + pCx->pKeyInfo = (KeyInfo*)pOp->p3;
69.2835 + pCx->pKeyInfo->enc = ENC(p->db);
69.2836 + pCx->pIncrKey = &pCx->pKeyInfo->incrKey;
69.2837 + }
69.2838 + pCx->isTable = 0;
69.2839 + }else{
69.2840 + rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, 0, &pCx->pCursor);
69.2841 + pCx->isTable = 1;
69.2842 + pCx->pIncrKey = &pCx->bogusIncrKey;
69.2843 + }
69.2844 + }
69.2845 + pCx->nField = pOp->p2;
69.2846 + pCx->isIndex = !pCx->isTable;
69.2847 + break;
69.2848 +}
69.2849 +
69.2850 +/* Opcode: OpenPseudo P1 * *
69.2851 +**
69.2852 +** Open a new cursor that points to a fake table that contains a single
69.2853 +** row of data. Any attempt to write a second row of data causes the
69.2854 +** first row to be deleted. All data is deleted when the cursor is
69.2855 +** closed.
69.2856 +**
69.2857 +** A pseudo-table created by this opcode is useful for holding the
69.2858 +** NEW or OLD tables in a trigger. Also used to hold the a single
69.2859 +** row output from the sorter so that the row can be decomposed into
69.2860 +** individual columns using the OP_Column opcode.
69.2861 +*/
69.2862 +case OP_OpenPseudo: { /* no-push */
69.2863 + int i = pOp->p1;
69.2864 + Cursor *pCx;
69.2865 + assert( i>=0 );
69.2866 + pCx = allocateCursor(p, i, -1);
69.2867 + if( pCx==0 ) goto no_mem;
69.2868 + pCx->nullRow = 1;
69.2869 + pCx->pseudoTable = 1;
69.2870 + pCx->pIncrKey = &pCx->bogusIncrKey;
69.2871 + pCx->isTable = 1;
69.2872 + pCx->isIndex = 0;
69.2873 + break;
69.2874 +}
69.2875 +
69.2876 +/* Opcode: Close P1 * *
69.2877 +**
69.2878 +** Close a cursor previously opened as P1. If P1 is not
69.2879 +** currently open, this instruction is a no-op.
69.2880 +*/
69.2881 +case OP_Close: { /* no-push */
69.2882 + int i = pOp->p1;
69.2883 + if( i>=0 && i<p->nCursor ){
69.2884 + sqlite3VdbeFreeCursor(p, p->apCsr[i]);
69.2885 + p->apCsr[i] = 0;
69.2886 + }
69.2887 + break;
69.2888 +}
69.2889 +
69.2890 +/* Opcode: MoveGe P1 P2 *
69.2891 +**
69.2892 +** Pop the top of the stack and use its value as a key. Reposition
69.2893 +** cursor P1 so that it points to the smallest entry that is greater
69.2894 +** than or equal to the key that was popped ffrom the stack.
69.2895 +** If there are no records greater than or equal to the key and P2
69.2896 +** is not zero, then jump to P2.
69.2897 +**
69.2898 +** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
69.2899 +*/
69.2900 +/* Opcode: MoveGt P1 P2 *
69.2901 +**
69.2902 +** Pop the top of the stack and use its value as a key. Reposition
69.2903 +** cursor P1 so that it points to the smallest entry that is greater
69.2904 +** than the key from the stack.
69.2905 +** If there are no records greater than the key and P2 is not zero,
69.2906 +** then jump to P2.
69.2907 +**
69.2908 +** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
69.2909 +*/
69.2910 +/* Opcode: MoveLt P1 P2 *
69.2911 +**
69.2912 +** Pop the top of the stack and use its value as a key. Reposition
69.2913 +** cursor P1 so that it points to the largest entry that is less
69.2914 +** than the key from the stack.
69.2915 +** If there are no records less than the key and P2 is not zero,
69.2916 +** then jump to P2.
69.2917 +**
69.2918 +** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
69.2919 +*/
69.2920 +/* Opcode: MoveLe P1 P2 *
69.2921 +**
69.2922 +** Pop the top of the stack and use its value as a key. Reposition
69.2923 +** cursor P1 so that it points to the largest entry that is less than
69.2924 +** or equal to the key that was popped from the stack.
69.2925 +** If there are no records less than or eqal to the key and P2 is not zero,
69.2926 +** then jump to P2.
69.2927 +**
69.2928 +** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
69.2929 +*/
69.2930 +case OP_MoveLt: /* no-push */
69.2931 +case OP_MoveLe: /* no-push */
69.2932 +case OP_MoveGe: /* no-push */
69.2933 +case OP_MoveGt: { /* no-push */
69.2934 + int i = pOp->p1;
69.2935 + Cursor *pC;
69.2936 +
69.2937 + assert( pTos>=p->aStack );
69.2938 + assert( i>=0 && i<p->nCursor );
69.2939 + pC = p->apCsr[i];
69.2940 + assert( pC!=0 );
69.2941 + if( pC->pCursor!=0 ){
69.2942 + int res, oc;
69.2943 + oc = pOp->opcode;
69.2944 + pC->nullRow = 0;
69.2945 + *pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe;
69.2946 + if( pC->isTable ){
69.2947 + i64 iKey;
69.2948 + sqlite3VdbeMemIntegerify(pTos);
69.2949 + iKey = intToKey(pTos->u.i);
69.2950 + if( pOp->p2==0 && pOp->opcode==OP_MoveGe ){
69.2951 + pC->movetoTarget = iKey;
69.2952 + pC->deferredMoveto = 1;
69.2953 + assert( (pTos->flags & MEM_Dyn)==0 );
69.2954 + pTos--;
69.2955 + break;
69.2956 + }
69.2957 + rc = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)iKey, 0, &res);
69.2958 + if( rc!=SQLITE_OK ){
69.2959 + goto abort_due_to_error;
69.2960 + }
69.2961 + pC->lastRowid = pTos->u.i;
69.2962 + pC->rowidIsValid = res==0;
69.2963 + }else{
69.2964 + assert( pTos->flags & MEM_Blob );
69.2965 + ExpandBlob(pTos);
69.2966 + rc = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res);
69.2967 + if( rc!=SQLITE_OK ){
69.2968 + goto abort_due_to_error;
69.2969 + }
69.2970 + pC->rowidIsValid = 0;
69.2971 + }
69.2972 + pC->deferredMoveto = 0;
69.2973 + pC->cacheStatus = CACHE_STALE;
69.2974 + *pC->pIncrKey = 0;
69.2975 +#ifdef SQLITE_TEST
69.2976 + sqlite3_search_count++;
69.2977 +#endif
69.2978 + if( oc==OP_MoveGe || oc==OP_MoveGt ){
69.2979 + if( res<0 ){
69.2980 + rc = sqlite3BtreeNext(pC->pCursor, &res);
69.2981 + if( rc!=SQLITE_OK ) goto abort_due_to_error;
69.2982 + pC->rowidIsValid = 0;
69.2983 + }else{
69.2984 + res = 0;
69.2985 + }
69.2986 + }else{
69.2987 + assert( oc==OP_MoveLt || oc==OP_MoveLe );
69.2988 + if( res>=0 ){
69.2989 + rc = sqlite3BtreePrevious(pC->pCursor, &res);
69.2990 + if( rc!=SQLITE_OK ) goto abort_due_to_error;
69.2991 + pC->rowidIsValid = 0;
69.2992 + }else{
69.2993 + /* res might be negative because the table is empty. Check to
69.2994 + ** see if this is the case.
69.2995 + */
69.2996 + res = sqlite3BtreeEof(pC->pCursor);
69.2997 + }
69.2998 + }
69.2999 + if( res ){
69.3000 + if( pOp->p2>0 ){
69.3001 + pc = pOp->p2 - 1;
69.3002 + }else{
69.3003 + pC->nullRow = 1;
69.3004 + }
69.3005 + }
69.3006 + }
69.3007 + Release(pTos);
69.3008 + pTos--;
69.3009 + break;
69.3010 +}
69.3011 +
69.3012 +/* Opcode: Distinct P1 P2 *
69.3013 +**
69.3014 +** Use the top of the stack as a record created using MakeRecord. P1 is a
69.3015 +** cursor on a table that declared as an index. If that table contains an
69.3016 +** entry that matches the top of the stack fall thru. If the top of the stack
69.3017 +** matches no entry in P1 then jump to P2.
69.3018 +**
69.3019 +** The cursor is left pointing at the matching entry if it exists. The
69.3020 +** record on the top of the stack is not popped.
69.3021 +**
69.3022 +** This instruction is similar to NotFound except that this operation
69.3023 +** does not pop the key from the stack.
69.3024 +**
69.3025 +** The instruction is used to implement the DISTINCT operator on SELECT
69.3026 +** statements. The P1 table is not a true index but rather a record of
69.3027 +** all results that have produced so far.
69.3028 +**
69.3029 +** See also: Found, NotFound, MoveTo, IsUnique, NotExists
69.3030 +*/
69.3031 +/* Opcode: Found P1 P2 *
69.3032 +**
69.3033 +** Top of the stack holds a blob constructed by MakeRecord. P1 is an index.
69.3034 +** If an entry that matches the top of the stack exists in P1 then
69.3035 +** jump to P2. If the top of the stack does not match any entry in P1
69.3036 +** then fall thru. The P1 cursor is left pointing at the matching entry
69.3037 +** if it exists. The blob is popped off the top of the stack.
69.3038 +**
69.3039 +** This instruction is used to implement the IN operator where the
69.3040 +** left-hand side is a SELECT statement. P1 is not a true index but
69.3041 +** is instead a temporary index that holds the results of the SELECT
69.3042 +** statement. This instruction just checks to see if the left-hand side
69.3043 +** of the IN operator (stored on the top of the stack) exists in the
69.3044 +** result of the SELECT statement.
69.3045 +**
69.3046 +** See also: Distinct, NotFound, MoveTo, IsUnique, NotExists
69.3047 +*/
69.3048 +/* Opcode: NotFound P1 P2 *
69.3049 +**
69.3050 +** The top of the stack holds a blob constructed by MakeRecord. P1 is
69.3051 +** an index. If no entry exists in P1 that matches the blob then jump
69.3052 +** to P2. If an entry does existing, fall through. The cursor is left
69.3053 +** pointing to the entry that matches. The blob is popped from the stack.
69.3054 +**
69.3055 +** The difference between this operation and Distinct is that
69.3056 +** Distinct does not pop the key from the stack.
69.3057 +**
69.3058 +** See also: Distinct, Found, MoveTo, NotExists, IsUnique
69.3059 +*/
69.3060 +case OP_Distinct: /* no-push */
69.3061 +case OP_NotFound: /* no-push */
69.3062 +case OP_Found: { /* no-push */
69.3063 + int i = pOp->p1;
69.3064 + int alreadyExists = 0;
69.3065 + Cursor *pC;
69.3066 + assert( pTos>=p->aStack );
69.3067 + assert( i>=0 && i<p->nCursor );
69.3068 + assert( p->apCsr[i]!=0 );
69.3069 + if( (pC = p->apCsr[i])->pCursor!=0 ){
69.3070 + int res, rx;
69.3071 + assert( pC->isTable==0 );
69.3072 + assert( pTos->flags & MEM_Blob );
69.3073 + Stringify(pTos, encoding);
69.3074 + rx = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res);
69.3075 + alreadyExists = rx==SQLITE_OK && res==0;
69.3076 + pC->deferredMoveto = 0;
69.3077 + pC->cacheStatus = CACHE_STALE;
69.3078 + }
69.3079 + if( pOp->opcode==OP_Found ){
69.3080 + if( alreadyExists ) pc = pOp->p2 - 1;
69.3081 + }else{
69.3082 + if( !alreadyExists ) pc = pOp->p2 - 1;
69.3083 + }
69.3084 + if( pOp->opcode!=OP_Distinct ){
69.3085 + Release(pTos);
69.3086 + pTos--;
69.3087 + }
69.3088 + break;
69.3089 +}
69.3090 +
69.3091 +/* Opcode: IsUnique P1 P2 *
69.3092 +**
69.3093 +** The top of the stack is an integer record number. Call this
69.3094 +** record number R. The next on the stack is an index key created
69.3095 +** using MakeIdxRec. Call it K. This instruction pops R from the
69.3096 +** stack but it leaves K unchanged.
69.3097 +**
69.3098 +** P1 is an index. So it has no data and its key consists of a
69.3099 +** record generated by OP_MakeRecord where the last field is the
69.3100 +** rowid of the entry that the index refers to.
69.3101 +**
69.3102 +** This instruction asks if there is an entry in P1 where the
69.3103 +** fields matches K but the rowid is different from R.
69.3104 +** If there is no such entry, then there is an immediate
69.3105 +** jump to P2. If any entry does exist where the index string
69.3106 +** matches K but the record number is not R, then the record
69.3107 +** number for that entry is pushed onto the stack and control
69.3108 +** falls through to the next instruction.
69.3109 +**
69.3110 +** See also: Distinct, NotFound, NotExists, Found
69.3111 +*/
69.3112 +case OP_IsUnique: { /* no-push */
69.3113 + int i = pOp->p1;
69.3114 + Mem *pNos = &pTos[-1];
69.3115 + Cursor *pCx;
69.3116 + BtCursor *pCrsr;
69.3117 + i64 R;
69.3118 +
69.3119 + /* Pop the value R off the top of the stack
69.3120 + */
69.3121 + assert( pNos>=p->aStack );
69.3122 + sqlite3VdbeMemIntegerify(pTos);
69.3123 + R = pTos->u.i;
69.3124 + assert( (pTos->flags & MEM_Dyn)==0 );
69.3125 + pTos--;
69.3126 + assert( i>=0 && i<p->nCursor );
69.3127 + pCx = p->apCsr[i];
69.3128 + assert( pCx!=0 );
69.3129 + pCrsr = pCx->pCursor;
69.3130 + if( pCrsr!=0 ){
69.3131 + int res;
69.3132 + i64 v; /* The record number on the P1 entry that matches K */
69.3133 + char *zKey; /* The value of K */
69.3134 + int nKey; /* Number of bytes in K */
69.3135 + int len; /* Number of bytes in K without the rowid at the end */
69.3136 + int szRowid; /* Size of the rowid column at the end of zKey */
69.3137 +
69.3138 + /* Make sure K is a string and make zKey point to K
69.3139 + */
69.3140 + assert( pNos->flags & MEM_Blob );
69.3141 + Stringify(pNos, encoding);
69.3142 + zKey = pNos->z;
69.3143 + nKey = pNos->n;
69.3144 +
69.3145 + szRowid = sqlite3VdbeIdxRowidLen((u8*)zKey);
69.3146 + len = nKey-szRowid;
69.3147 +
69.3148 + /* Search for an entry in P1 where all but the last four bytes match K.
69.3149 + ** If there is no such entry, jump immediately to P2.
69.3150 + */
69.3151 + assert( pCx->deferredMoveto==0 );
69.3152 + pCx->cacheStatus = CACHE_STALE;
69.3153 + rc = sqlite3BtreeMoveto(pCrsr, zKey, len, 0, &res);
69.3154 + if( rc!=SQLITE_OK ){
69.3155 + goto abort_due_to_error;
69.3156 + }
69.3157 + if( res<0 ){
69.3158 + rc = sqlite3BtreeNext(pCrsr, &res);
69.3159 + if( res ){
69.3160 + pc = pOp->p2 - 1;
69.3161 + break;
69.3162 + }
69.3163 + }
69.3164 + rc = sqlite3VdbeIdxKeyCompare(pCx, len, (u8*)zKey, &res);
69.3165 + if( rc!=SQLITE_OK ) goto abort_due_to_error;
69.3166 + if( res>0 ){
69.3167 + pc = pOp->p2 - 1;
69.3168 + break;
69.3169 + }
69.3170 +
69.3171 + /* At this point, pCrsr is pointing to an entry in P1 where all but
69.3172 + ** the final entry (the rowid) matches K. Check to see if the
69.3173 + ** final rowid column is different from R. If it equals R then jump
69.3174 + ** immediately to P2.
69.3175 + */
69.3176 + rc = sqlite3VdbeIdxRowid(pCrsr, &v);
69.3177 + if( rc!=SQLITE_OK ){
69.3178 + goto abort_due_to_error;
69.3179 + }
69.3180 + if( v==R ){
69.3181 + pc = pOp->p2 - 1;
69.3182 + break;
69.3183 + }
69.3184 +
69.3185 + /* The final varint of the key is different from R. Push it onto
69.3186 + ** the stack. (The record number of an entry that violates a UNIQUE
69.3187 + ** constraint.)
69.3188 + */
69.3189 + pTos++;
69.3190 + pTos->u.i = v;
69.3191 + pTos->flags = MEM_Int;
69.3192 + }
69.3193 + break;
69.3194 +}
69.3195 +
69.3196 +/* Opcode: NotExists P1 P2 *
69.3197 +**
69.3198 +** Use the top of the stack as a integer key. If a record with that key
69.3199 +** does not exist in table of P1, then jump to P2. If the record
69.3200 +** does exist, then fall thru. The cursor is left pointing to the
69.3201 +** record if it exists. The integer key is popped from the stack.
69.3202 +**
69.3203 +** The difference between this operation and NotFound is that this
69.3204 +** operation assumes the key is an integer and that P1 is a table whereas
69.3205 +** NotFound assumes key is a blob constructed from MakeRecord and
69.3206 +** P1 is an index.
69.3207 +**
69.3208 +** See also: Distinct, Found, MoveTo, NotFound, IsUnique
69.3209 +*/
69.3210 +case OP_NotExists: { /* no-push */
69.3211 + int i = pOp->p1;
69.3212 + Cursor *pC;
69.3213 + BtCursor *pCrsr;
69.3214 + assert( pTos>=p->aStack );
69.3215 + assert( i>=0 && i<p->nCursor );
69.3216 + assert( p->apCsr[i]!=0 );
69.3217 + if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
69.3218 + int res;
69.3219 + u64 iKey;
69.3220 + assert( pTos->flags & MEM_Int );
69.3221 + assert( p->apCsr[i]->isTable );
69.3222 + iKey = intToKey(pTos->u.i);
69.3223 + rc = sqlite3BtreeMoveto(pCrsr, 0, iKey, 0,&res);
69.3224 + pC->lastRowid = pTos->u.i;
69.3225 + pC->rowidIsValid = res==0;
69.3226 + pC->nullRow = 0;
69.3227 + pC->cacheStatus = CACHE_STALE;
69.3228 + /* res might be uninitialized if rc!=SQLITE_OK. But if rc!=SQLITE_OK
69.3229 + ** processing is about to abort so we really do not care whether or not
69.3230 + ** the following jump is taken. (In other words, do not stress over
69.3231 + ** the error that valgrind sometimes shows on the next statement when
69.3232 + ** running ioerr.test and similar failure-recovery test scripts.) */
69.3233 + if( res!=0 ){
69.3234 + pc = pOp->p2 - 1;
69.3235 + pC->rowidIsValid = 0;
69.3236 + }
69.3237 + }
69.3238 + Release(pTos);
69.3239 + pTos--;
69.3240 + break;
69.3241 +}
69.3242 +
69.3243 +/* Opcode: Sequence P1 * *
69.3244 +**
69.3245 +** Push an integer onto the stack which is the next available
69.3246 +** sequence number for cursor P1. The sequence number on the
69.3247 +** cursor is incremented after the push.
69.3248 +*/
69.3249 +case OP_Sequence: {
69.3250 + int i = pOp->p1;
69.3251 + assert( pTos>=p->aStack );
69.3252 + assert( i>=0 && i<p->nCursor );
69.3253 + assert( p->apCsr[i]!=0 );
69.3254 + pTos++;
69.3255 + pTos->u.i = p->apCsr[i]->seqCount++;
69.3256 + pTos->flags = MEM_Int;
69.3257 + break;
69.3258 +}
69.3259 +
69.3260 +
69.3261 +/* Opcode: NewRowid P1 P2 *
69.3262 +**
69.3263 +** Get a new integer record number (a.k.a "rowid") used as the key to a table.
69.3264 +** The record number is not previously used as a key in the database
69.3265 +** table that cursor P1 points to. The new record number is pushed
69.3266 +** onto the stack.
69.3267 +**
69.3268 +** If P2>0 then P2 is a memory cell that holds the largest previously
69.3269 +** generated record number. No new record numbers are allowed to be less
69.3270 +** than this value. When this value reaches its maximum, a SQLITE_FULL
69.3271 +** error is generated. The P2 memory cell is updated with the generated
69.3272 +** record number. This P2 mechanism is used to help implement the
69.3273 +** AUTOINCREMENT feature.
69.3274 +*/
69.3275 +case OP_NewRowid: {
69.3276 + int i = pOp->p1;
69.3277 + i64 v = 0;
69.3278 + Cursor *pC;
69.3279 + assert( i>=0 && i<p->nCursor );
69.3280 + assert( p->apCsr[i]!=0 );
69.3281 + if( (pC = p->apCsr[i])->pCursor==0 ){
69.3282 + /* The zero initialization above is all that is needed */
69.3283 + }else{
69.3284 + /* The next rowid or record number (different terms for the same
69.3285 + ** thing) is obtained in a two-step algorithm.
69.3286 + **
69.3287 + ** First we attempt to find the largest existing rowid and add one
69.3288 + ** to that. But if the largest existing rowid is already the maximum
69.3289 + ** positive integer, we have to fall through to the second
69.3290 + ** probabilistic algorithm
69.3291 + **
69.3292 + ** The second algorithm is to select a rowid at random and see if
69.3293 + ** it already exists in the table. If it does not exist, we have
69.3294 + ** succeeded. If the random rowid does exist, we select a new one
69.3295 + ** and try again, up to 1000 times.
69.3296 + **
69.3297 + ** For a table with less than 2 billion entries, the probability
69.3298 + ** of not finding a unused rowid is about 1.0e-300. This is a
69.3299 + ** non-zero probability, but it is still vanishingly small and should
69.3300 + ** never cause a problem. You are much, much more likely to have a
69.3301 + ** hardware failure than for this algorithm to fail.
69.3302 + **
69.3303 + ** The analysis in the previous paragraph assumes that you have a good
69.3304 + ** source of random numbers. Is a library function like lrand48()
69.3305 + ** good enough? Maybe. Maybe not. It's hard to know whether there
69.3306 + ** might be subtle bugs is some implementations of lrand48() that
69.3307 + ** could cause problems. To avoid uncertainty, SQLite uses its own
69.3308 + ** random number generator based on the RC4 algorithm.
69.3309 + **
69.3310 + ** To promote locality of reference for repetitive inserts, the
69.3311 + ** first few attempts at chosing a random rowid pick values just a little
69.3312 + ** larger than the previous rowid. This has been shown experimentally
69.3313 + ** to double the speed of the COPY operation.
69.3314 + */
69.3315 + int res, rx=SQLITE_OK, cnt;
69.3316 + i64 x;
69.3317 + cnt = 0;
69.3318 + if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
69.3319 + BTREE_INTKEY ){
69.3320 + rc = SQLITE_CORRUPT_BKPT;
69.3321 + goto abort_due_to_error;
69.3322 + }
69.3323 + assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
69.3324 + assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
69.3325 +
69.3326 +#ifdef SQLITE_32BIT_ROWID
69.3327 +# define MAX_ROWID 0x7fffffff
69.3328 +#else
69.3329 + /* Some compilers complain about constants of the form 0x7fffffffffffffff.
69.3330 + ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
69.3331 + ** to provide the constant while making all compilers happy.
69.3332 + */
69.3333 +# define MAX_ROWID ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
69.3334 +#endif
69.3335 +
69.3336 + if( !pC->useRandomRowid ){
69.3337 + if( pC->nextRowidValid ){
69.3338 + v = pC->nextRowid;
69.3339 + }else{
69.3340 + rc = sqlite3BtreeLast(pC->pCursor, &res);
69.3341 + if( rc!=SQLITE_OK ){
69.3342 + goto abort_due_to_error;
69.3343 + }
69.3344 + if( res ){
69.3345 + v = 1;
69.3346 + }else{
69.3347 + sqlite3BtreeKeySize(pC->pCursor, &v);
69.3348 + v = keyToInt(v);
69.3349 + if( v==MAX_ROWID ){
69.3350 + pC->useRandomRowid = 1;
69.3351 + }else{
69.3352 + v++;
69.3353 + }
69.3354 + }
69.3355 + }
69.3356 +
69.3357 +#ifndef SQLITE_OMIT_AUTOINCREMENT
69.3358 + if( pOp->p2 ){
69.3359 + Mem *pMem;
69.3360 + assert( pOp->p2>0 && pOp->p2<p->nMem ); /* P2 is a valid memory cell */
69.3361 + pMem = &p->aMem[pOp->p2];
69.3362 + sqlite3VdbeMemIntegerify(pMem);
69.3363 + assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P2) holds an integer */
69.3364 + if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
69.3365 + rc = SQLITE_FULL;
69.3366 + goto abort_due_to_error;
69.3367 + }
69.3368 + if( v<pMem->u.i+1 ){
69.3369 + v = pMem->u.i + 1;
69.3370 + }
69.3371 + pMem->u.i = v;
69.3372 + }
69.3373 +#endif
69.3374 +
69.3375 + if( v<MAX_ROWID ){
69.3376 + pC->nextRowidValid = 1;
69.3377 + pC->nextRowid = v+1;
69.3378 + }else{
69.3379 + pC->nextRowidValid = 0;
69.3380 + }
69.3381 + }
69.3382 + if( pC->useRandomRowid ){
69.3383 + assert( pOp->p2==0 ); /* SQLITE_FULL must have occurred prior to this */
69.3384 + v = db->priorNewRowid;
69.3385 + cnt = 0;
69.3386 + do{
69.3387 + if( v==0 || cnt>2 ){
69.3388 + sqlite3Randomness(sizeof(v), &v);
69.3389 + if( cnt<5 ) v &= 0xffffff;
69.3390 + }else{
69.3391 + unsigned char r;
69.3392 + sqlite3Randomness(1, &r);
69.3393 + v += r + 1;
69.3394 + }
69.3395 + if( v==0 ) continue;
69.3396 + x = intToKey(v);
69.3397 + rx = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)x, 0, &res);
69.3398 + cnt++;
69.3399 + }while( cnt<1000 && rx==SQLITE_OK && res==0 );
69.3400 + db->priorNewRowid = v;
69.3401 + if( rx==SQLITE_OK && res==0 ){
69.3402 + rc = SQLITE_FULL;
69.3403 + goto abort_due_to_error;
69.3404 + }
69.3405 + }
69.3406 + pC->rowidIsValid = 0;
69.3407 + pC->deferredMoveto = 0;
69.3408 + pC->cacheStatus = CACHE_STALE;
69.3409 + }
69.3410 + pTos++;
69.3411 + pTos->u.i = v;
69.3412 + pTos->flags = MEM_Int;
69.3413 + break;
69.3414 +}
69.3415 +
69.3416 +/* Opcode: Insert P1 P2 P3
69.3417 +**
69.3418 +** Write an entry into the table of cursor P1. A new entry is
69.3419 +** created if it doesn't already exist or the data for an existing
69.3420 +** entry is overwritten. The data is the value on the top of the
69.3421 +** stack. The key is the next value down on the stack. The key must
69.3422 +** be an integer. The stack is popped twice by this instruction.
69.3423 +**
69.3424 +** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
69.3425 +** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P2 is set,
69.3426 +** then rowid is stored for subsequent return by the
69.3427 +** sqlite3_last_insert_rowid() function (otherwise it's unmodified).
69.3428 +**
69.3429 +** Parameter P3 may point to a string containing the table-name, or
69.3430 +** may be NULL. If it is not NULL, then the update-hook
69.3431 +** (sqlite3.xUpdateCallback) is invoked following a successful insert.
69.3432 +**
69.3433 +** This instruction only works on tables. The equivalent instruction
69.3434 +** for indices is OP_IdxInsert.
69.3435 +*/
69.3436 +case OP_Insert: { /* no-push */
69.3437 + Mem *pNos = &pTos[-1];
69.3438 + int i = pOp->p1;
69.3439 + Cursor *pC;
69.3440 + assert( pNos>=p->aStack );
69.3441 + assert( i>=0 && i<p->nCursor );
69.3442 + assert( p->apCsr[i]!=0 );
69.3443 + if( ((pC = p->apCsr[i])->pCursor!=0 || pC->pseudoTable) ){
69.3444 + i64 iKey; /* The integer ROWID or key for the record to be inserted */
69.3445 +
69.3446 + assert( pNos->flags & MEM_Int );
69.3447 + assert( pC->isTable );
69.3448 + iKey = intToKey(pNos->u.i);
69.3449 +
69.3450 + if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
69.3451 + if( pOp->p2 & OPFLAG_LASTROWID ) db->lastRowid = pNos->u.i;
69.3452 + if( pC->nextRowidValid && pNos->u.i>=pC->nextRowid ){
69.3453 + pC->nextRowidValid = 0;
69.3454 + }
69.3455 + if( pTos->flags & MEM_Null ){
69.3456 + pTos->z = 0;
69.3457 + pTos->n = 0;
69.3458 + }else{
69.3459 + assert( pTos->flags & (MEM_Blob|MEM_Str) );
69.3460 + }
69.3461 + if( pC->pseudoTable ){
69.3462 + sqliteFree(pC->pData);
69.3463 + pC->iKey = iKey;
69.3464 + pC->nData = pTos->n;
69.3465 + if( pTos->flags & MEM_Dyn ){
69.3466 + pC->pData = pTos->z;
69.3467 + pTos->flags = MEM_Null;
69.3468 + }else{
69.3469 + pC->pData = sqliteMallocRaw( pC->nData+2 );
69.3470 + if( !pC->pData ) goto no_mem;
69.3471 + memcpy(pC->pData, pTos->z, pC->nData);
69.3472 + pC->pData[pC->nData] = 0;
69.3473 + pC->pData[pC->nData+1] = 0;
69.3474 + }
69.3475 + pC->nullRow = 0;
69.3476 + }else{
69.3477 + int nZero;
69.3478 + if( pTos->flags & MEM_Zero ){
69.3479 + nZero = pTos->u.i;
69.3480 + }else{
69.3481 + nZero = 0;
69.3482 + }
69.3483 + rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
69.3484 + pTos->z, pTos->n, nZero,
69.3485 + pOp->p2 & OPFLAG_APPEND);
69.3486 + }
69.3487 +
69.3488 + pC->rowidIsValid = 0;
69.3489 + pC->deferredMoveto = 0;
69.3490 + pC->cacheStatus = CACHE_STALE;
69.3491 +
69.3492 + /* Invoke the update-hook if required. */
69.3493 + if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
69.3494 + const char *zDb = db->aDb[pC->iDb].zName;
69.3495 + const char *zTbl = pOp->p3;
69.3496 + int op = ((pOp->p2 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
69.3497 + assert( pC->isTable );
69.3498 + db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
69.3499 + assert( pC->iDb>=0 );
69.3500 + }
69.3501 + }
69.3502 + popStack(&pTos, 2);
69.3503 +
69.3504 + break;
69.3505 +}
69.3506 +
69.3507 +/* Opcode: Delete P1 P2 P3
69.3508 +**
69.3509 +** Delete the record at which the P1 cursor is currently pointing.
69.3510 +**
69.3511 +** The cursor will be left pointing at either the next or the previous
69.3512 +** record in the table. If it is left pointing at the next record, then
69.3513 +** the next Next instruction will be a no-op. Hence it is OK to delete
69.3514 +** a record from within an Next loop.
69.3515 +**
69.3516 +** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
69.3517 +** incremented (otherwise not).
69.3518 +**
69.3519 +** If P1 is a pseudo-table, then this instruction is a no-op.
69.3520 +*/
69.3521 +case OP_Delete: { /* no-push */
69.3522 + int i = pOp->p1;
69.3523 + Cursor *pC;
69.3524 + assert( i>=0 && i<p->nCursor );
69.3525 + pC = p->apCsr[i];
69.3526 + assert( pC!=0 );
69.3527 + if( pC->pCursor!=0 ){
69.3528 + i64 iKey;
69.3529 +
69.3530 + /* If the update-hook will be invoked, set iKey to the rowid of the
69.3531 + ** row being deleted.
69.3532 + */
69.3533 + if( db->xUpdateCallback && pOp->p3 ){
69.3534 + assert( pC->isTable );
69.3535 + if( pC->rowidIsValid ){
69.3536 + iKey = pC->lastRowid;
69.3537 + }else{
69.3538 + rc = sqlite3BtreeKeySize(pC->pCursor, &iKey);
69.3539 + if( rc ){
69.3540 + goto abort_due_to_error;
69.3541 + }
69.3542 + iKey = keyToInt(iKey);
69.3543 + }
69.3544 + }
69.3545 +
69.3546 + rc = sqlite3VdbeCursorMoveto(pC);
69.3547 + if( rc ) goto abort_due_to_error;
69.3548 + rc = sqlite3BtreeDelete(pC->pCursor);
69.3549 + pC->nextRowidValid = 0;
69.3550 + pC->cacheStatus = CACHE_STALE;
69.3551 +
69.3552 + /* Invoke the update-hook if required. */
69.3553 + if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
69.3554 + const char *zDb = db->aDb[pC->iDb].zName;
69.3555 + const char *zTbl = pOp->p3;
69.3556 + db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
69.3557 + assert( pC->iDb>=0 );
69.3558 + }
69.3559 + }
69.3560 + if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
69.3561 + break;
69.3562 +}
69.3563 +
69.3564 +/* Opcode: ResetCount P1 * *
69.3565 +**
69.3566 +** This opcode resets the VMs internal change counter to 0. If P1 is true,
69.3567 +** then the value of the change counter is copied to the database handle
69.3568 +** change counter (returned by subsequent calls to sqlite3_changes())
69.3569 +** before it is reset. This is used by trigger programs.
69.3570 +*/
69.3571 +case OP_ResetCount: { /* no-push */
69.3572 + if( pOp->p1 ){
69.3573 + sqlite3VdbeSetChanges(db, p->nChange);
69.3574 + }
69.3575 + p->nChange = 0;
69.3576 + break;
69.3577 +}
69.3578 +
69.3579 +/* Opcode: RowData P1 * *
69.3580 +**
69.3581 +** Push onto the stack the complete row data for cursor P1.
69.3582 +** There is no interpretation of the data. It is just copied
69.3583 +** onto the stack exactly as it is found in the database file.
69.3584 +**
69.3585 +** If the cursor is not pointing to a valid row, a NULL is pushed
69.3586 +** onto the stack.
69.3587 +*/
69.3588 +/* Opcode: RowKey P1 * *
69.3589 +**
69.3590 +** Push onto the stack the complete row key for cursor P1.
69.3591 +** There is no interpretation of the key. It is just copied
69.3592 +** onto the stack exactly as it is found in the database file.
69.3593 +**
69.3594 +** If the cursor is not pointing to a valid row, a NULL is pushed
69.3595 +** onto the stack.
69.3596 +*/
69.3597 +case OP_RowKey:
69.3598 +case OP_RowData: {
69.3599 + int i = pOp->p1;
69.3600 + Cursor *pC;
69.3601 + u32 n;
69.3602 +
69.3603 + /* Note that RowKey and RowData are really exactly the same instruction */
69.3604 + pTos++;
69.3605 + assert( i>=0 && i<p->nCursor );
69.3606 + pC = p->apCsr[i];
69.3607 + assert( pC->isTable || pOp->opcode==OP_RowKey );
69.3608 + assert( pC->isIndex || pOp->opcode==OP_RowData );
69.3609 + assert( pC!=0 );
69.3610 + if( pC->nullRow ){
69.3611 + pTos->flags = MEM_Null;
69.3612 + }else if( pC->pCursor!=0 ){
69.3613 + BtCursor *pCrsr = pC->pCursor;
69.3614 + rc = sqlite3VdbeCursorMoveto(pC);
69.3615 + if( rc ) goto abort_due_to_error;
69.3616 + if( pC->nullRow ){
69.3617 + pTos->flags = MEM_Null;
69.3618 + break;
69.3619 + }else if( pC->isIndex ){
69.3620 + i64 n64;
69.3621 + assert( !pC->isTable );
69.3622 + sqlite3BtreeKeySize(pCrsr, &n64);
69.3623 + if( n64>SQLITE_MAX_LENGTH ){
69.3624 + goto too_big;
69.3625 + }
69.3626 + n = n64;
69.3627 + }else{
69.3628 + sqlite3BtreeDataSize(pCrsr, &n);
69.3629 + }
69.3630 + if( n>SQLITE_MAX_LENGTH ){
69.3631 + goto too_big;
69.3632 + }
69.3633 + pTos->n = n;
69.3634 + if( n<=NBFS ){
69.3635 + pTos->flags = MEM_Blob | MEM_Short;
69.3636 + pTos->z = pTos->zShort;
69.3637 + }else{
69.3638 + char *z = sqliteMallocRaw( n );
69.3639 + if( z==0 ) goto no_mem;
69.3640 + pTos->flags = MEM_Blob | MEM_Dyn;
69.3641 + pTos->xDel = 0;
69.3642 + pTos->z = z;
69.3643 + }
69.3644 + if( pC->isIndex ){
69.3645 + rc = sqlite3BtreeKey(pCrsr, 0, n, pTos->z);
69.3646 + }else{
69.3647 + rc = sqlite3BtreeData(pCrsr, 0, n, pTos->z);
69.3648 + }
69.3649 + }else if( pC->pseudoTable ){
69.3650 + pTos->n = pC->nData;
69.3651 + assert( pC->nData<=SQLITE_MAX_LENGTH );
69.3652 + pTos->z = pC->pData;
69.3653 + pTos->flags = MEM_Blob|MEM_Ephem;
69.3654 + }else{
69.3655 + pTos->flags = MEM_Null;
69.3656 + }
69.3657 + pTos->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
69.3658 + break;
69.3659 +}
69.3660 +
69.3661 +/* Opcode: Rowid P1 * *
69.3662 +**
69.3663 +** Push onto the stack an integer which is the key of the table entry that
69.3664 +** P1 is currently point to.
69.3665 +*/
69.3666 +case OP_Rowid: {
69.3667 + int i = pOp->p1;
69.3668 + Cursor *pC;
69.3669 + i64 v;
69.3670 +
69.3671 + assert( i>=0 && i<p->nCursor );
69.3672 + pC = p->apCsr[i];
69.3673 + assert( pC!=0 );
69.3674 + rc = sqlite3VdbeCursorMoveto(pC);
69.3675 + if( rc ) goto abort_due_to_error;
69.3676 + pTos++;
69.3677 + if( pC->rowidIsValid ){
69.3678 + v = pC->lastRowid;
69.3679 + }else if( pC->pseudoTable ){
69.3680 + v = keyToInt(pC->iKey);
69.3681 + }else if( pC->nullRow || pC->pCursor==0 ){
69.3682 + pTos->flags = MEM_Null;
69.3683 + break;
69.3684 + }else{
69.3685 + assert( pC->pCursor!=0 );
69.3686 + sqlite3BtreeKeySize(pC->pCursor, &v);
69.3687 + v = keyToInt(v);
69.3688 + }
69.3689 + pTos->u.i = v;
69.3690 + pTos->flags = MEM_Int;
69.3691 + break;
69.3692 +}
69.3693 +
69.3694 +/* Opcode: NullRow P1 * *
69.3695 +**
69.3696 +** Move the cursor P1 to a null row. Any OP_Column operations
69.3697 +** that occur while the cursor is on the null row will always push
69.3698 +** a NULL onto the stack.
69.3699 +*/
69.3700 +case OP_NullRow: { /* no-push */
69.3701 + int i = pOp->p1;
69.3702 + Cursor *pC;
69.3703 +
69.3704 + assert( i>=0 && i<p->nCursor );
69.3705 + pC = p->apCsr[i];
69.3706 + assert( pC!=0 );
69.3707 + pC->nullRow = 1;
69.3708 + pC->rowidIsValid = 0;
69.3709 + break;
69.3710 +}
69.3711 +
69.3712 +/* Opcode: Last P1 P2 *
69.3713 +**
69.3714 +** The next use of the Rowid or Column or Next instruction for P1
69.3715 +** will refer to the last entry in the database table or index.
69.3716 +** If the table or index is empty and P2>0, then jump immediately to P2.
69.3717 +** If P2 is 0 or if the table or index is not empty, fall through
69.3718 +** to the following instruction.
69.3719 +*/
69.3720 +case OP_Last: { /* no-push */
69.3721 + int i = pOp->p1;
69.3722 + Cursor *pC;
69.3723 + BtCursor *pCrsr;
69.3724 +
69.3725 + assert( i>=0 && i<p->nCursor );
69.3726 + pC = p->apCsr[i];
69.3727 + assert( pC!=0 );
69.3728 + if( (pCrsr = pC->pCursor)!=0 ){
69.3729 + int res;
69.3730 + rc = sqlite3BtreeLast(pCrsr, &res);
69.3731 + pC->nullRow = res;
69.3732 + pC->deferredMoveto = 0;
69.3733 + pC->cacheStatus = CACHE_STALE;
69.3734 + if( res && pOp->p2>0 ){
69.3735 + pc = pOp->p2 - 1;
69.3736 + }
69.3737 + }else{
69.3738 + pC->nullRow = 0;
69.3739 + }
69.3740 + break;
69.3741 +}
69.3742 +
69.3743 +
69.3744 +/* Opcode: Sort P1 P2 *
69.3745 +**
69.3746 +** This opcode does exactly the same thing as OP_Rewind except that
69.3747 +** it increments an undocumented global variable used for testing.
69.3748 +**
69.3749 +** Sorting is accomplished by writing records into a sorting index,
69.3750 +** then rewinding that index and playing it back from beginning to
69.3751 +** end. We use the OP_Sort opcode instead of OP_Rewind to do the
69.3752 +** rewinding so that the global variable will be incremented and
69.3753 +** regression tests can determine whether or not the optimizer is
69.3754 +** correctly optimizing out sorts.
69.3755 +*/
69.3756 +case OP_Sort: { /* no-push */
69.3757 +#ifdef SQLITE_TEST
69.3758 + sqlite3_sort_count++;
69.3759 + sqlite3_search_count--;
69.3760 +#endif
69.3761 + /* Fall through into OP_Rewind */
69.3762 +}
69.3763 +/* Opcode: Rewind P1 P2 *
69.3764 +**
69.3765 +** The next use of the Rowid or Column or Next instruction for P1
69.3766 +** will refer to the first entry in the database table or index.
69.3767 +** If the table or index is empty and P2>0, then jump immediately to P2.
69.3768 +** If P2 is 0 or if the table or index is not empty, fall through
69.3769 +** to the following instruction.
69.3770 +*/
69.3771 +case OP_Rewind: { /* no-push */
69.3772 + int i = pOp->p1;
69.3773 + Cursor *pC;
69.3774 + BtCursor *pCrsr;
69.3775 + int res;
69.3776 +
69.3777 + assert( i>=0 && i<p->nCursor );
69.3778 + pC = p->apCsr[i];
69.3779 + assert( pC!=0 );
69.3780 + if( (pCrsr = pC->pCursor)!=0 ){
69.3781 + rc = sqlite3BtreeFirst(pCrsr, &res);
69.3782 + pC->atFirst = res==0;
69.3783 + pC->deferredMoveto = 0;
69.3784 + pC->cacheStatus = CACHE_STALE;
69.3785 + }else{
69.3786 + res = 1;
69.3787 + }
69.3788 + pC->nullRow = res;
69.3789 + if( res && pOp->p2>0 ){
69.3790 + pc = pOp->p2 - 1;
69.3791 + }
69.3792 + break;
69.3793 +}
69.3794 +
69.3795 +/* Opcode: Next P1 P2 *
69.3796 +**
69.3797 +** Advance cursor P1 so that it points to the next key/data pair in its
69.3798 +** table or index. If there are no more key/value pairs then fall through
69.3799 +** to the following instruction. But if the cursor advance was successful,
69.3800 +** jump immediately to P2.
69.3801 +**
69.3802 +** See also: Prev
69.3803 +*/
69.3804 +/* Opcode: Prev P1 P2 *
69.3805 +**
69.3806 +** Back up cursor P1 so that it points to the previous key/data pair in its
69.3807 +** table or index. If there is no previous key/value pairs then fall through
69.3808 +** to the following instruction. But if the cursor backup was successful,
69.3809 +** jump immediately to P2.
69.3810 +*/
69.3811 +case OP_Prev: /* no-push */
69.3812 +case OP_Next: { /* no-push */
69.3813 + Cursor *pC;
69.3814 + BtCursor *pCrsr;
69.3815 +
69.3816 + CHECK_FOR_INTERRUPT;
69.3817 + assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69.3818 + pC = p->apCsr[pOp->p1];
69.3819 + if( pC==0 ){
69.3820 + break; /* See ticket #2273 */
69.3821 + }
69.3822 + if( (pCrsr = pC->pCursor)!=0 ){
69.3823 + int res;
69.3824 + if( pC->nullRow ){
69.3825 + res = 1;
69.3826 + }else{
69.3827 + assert( pC->deferredMoveto==0 );
69.3828 + rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
69.3829 + sqlite3BtreePrevious(pCrsr, &res);
69.3830 + pC->nullRow = res;
69.3831 + pC->cacheStatus = CACHE_STALE;
69.3832 + }
69.3833 + if( res==0 ){
69.3834 + pc = pOp->p2 - 1;
69.3835 +#ifdef SQLITE_TEST
69.3836 + sqlite3_search_count++;
69.3837 +#endif
69.3838 + }
69.3839 + }else{
69.3840 + pC->nullRow = 1;
69.3841 + }
69.3842 + pC->rowidIsValid = 0;
69.3843 + break;
69.3844 +}
69.3845 +
69.3846 +/* Opcode: IdxInsert P1 P2 *
69.3847 +**
69.3848 +** The top of the stack holds a SQL index key made using either the
69.3849 +** MakeIdxRec or MakeRecord instructions. This opcode writes that key
69.3850 +** into the index P1. Data for the entry is nil.
69.3851 +**
69.3852 +** P2 is a flag that provides a hint to the b-tree layer that this
69.3853 +** insert is likely to be an append.
69.3854 +**
69.3855 +** This instruction only works for indices. The equivalent instruction
69.3856 +** for tables is OP_Insert.
69.3857 +*/
69.3858 +case OP_IdxInsert: { /* no-push */
69.3859 + int i = pOp->p1;
69.3860 + Cursor *pC;
69.3861 + BtCursor *pCrsr;
69.3862 + assert( pTos>=p->aStack );
69.3863 + assert( i>=0 && i<p->nCursor );
69.3864 + assert( p->apCsr[i]!=0 );
69.3865 + assert( pTos->flags & MEM_Blob );
69.3866 + if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
69.3867 + assert( pC->isTable==0 );
69.3868 + rc = ExpandBlob(pTos);
69.3869 + if( rc==SQLITE_OK ){
69.3870 + int nKey = pTos->n;
69.3871 + const char *zKey = pTos->z;
69.3872 + rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p2);
69.3873 + assert( pC->deferredMoveto==0 );
69.3874 + pC->cacheStatus = CACHE_STALE;
69.3875 + }
69.3876 + }
69.3877 + Release(pTos);
69.3878 + pTos--;
69.3879 + break;
69.3880 +}
69.3881 +
69.3882 +/* Opcode: IdxDelete P1 * *
69.3883 +**
69.3884 +** The top of the stack is an index key built using the either the
69.3885 +** MakeIdxRec or MakeRecord opcodes.
69.3886 +** This opcode removes that entry from the index.
69.3887 +*/
69.3888 +case OP_IdxDelete: { /* no-push */
69.3889 + int i = pOp->p1;
69.3890 + Cursor *pC;
69.3891 + BtCursor *pCrsr;
69.3892 + assert( pTos>=p->aStack );
69.3893 + assert( pTos->flags & MEM_Blob );
69.3894 + assert( i>=0 && i<p->nCursor );
69.3895 + assert( p->apCsr[i]!=0 );
69.3896 + if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
69.3897 + int res;
69.3898 + rc = sqlite3BtreeMoveto(pCrsr, pTos->z, pTos->n, 0, &res);
69.3899 + if( rc==SQLITE_OK && res==0 ){
69.3900 + rc = sqlite3BtreeDelete(pCrsr);
69.3901 + }
69.3902 + assert( pC->deferredMoveto==0 );
69.3903 + pC->cacheStatus = CACHE_STALE;
69.3904 + }
69.3905 + Release(pTos);
69.3906 + pTos--;
69.3907 + break;
69.3908 +}
69.3909 +
69.3910 +/* Opcode: IdxRowid P1 * *
69.3911 +**
69.3912 +** Push onto the stack an integer which is the last entry in the record at
69.3913 +** the end of the index key pointed to by cursor P1. This integer should be
69.3914 +** the rowid of the table entry to which this index entry points.
69.3915 +**
69.3916 +** See also: Rowid, MakeIdxRec.
69.3917 +*/
69.3918 +case OP_IdxRowid: {
69.3919 + int i = pOp->p1;
69.3920 + BtCursor *pCrsr;
69.3921 + Cursor *pC;
69.3922 +
69.3923 + assert( i>=0 && i<p->nCursor );
69.3924 + assert( p->apCsr[i]!=0 );
69.3925 + pTos++;
69.3926 + pTos->flags = MEM_Null;
69.3927 + if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
69.3928 + i64 rowid;
69.3929 +
69.3930 + assert( pC->deferredMoveto==0 );
69.3931 + assert( pC->isTable==0 );
69.3932 + if( pC->nullRow ){
69.3933 + pTos->flags = MEM_Null;
69.3934 + }else{
69.3935 + rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
69.3936 + if( rc!=SQLITE_OK ){
69.3937 + goto abort_due_to_error;
69.3938 + }
69.3939 + pTos->flags = MEM_Int;
69.3940 + pTos->u.i = rowid;
69.3941 + }
69.3942 + }
69.3943 + break;
69.3944 +}
69.3945 +
69.3946 +/* Opcode: IdxGT P1 P2 *
69.3947 +**
69.3948 +** The top of the stack is an index entry that omits the ROWID. Compare
69.3949 +** the top of stack against the index that P1 is currently pointing to.
69.3950 +** Ignore the ROWID on the P1 index.
69.3951 +**
69.3952 +** The top of the stack might have fewer columns that P1.
69.3953 +**
69.3954 +** If the P1 index entry is greater than the top of the stack
69.3955 +** then jump to P2. Otherwise fall through to the next instruction.
69.3956 +** In either case, the stack is popped once.
69.3957 +*/
69.3958 +/* Opcode: IdxGE P1 P2 P3
69.3959 +**
69.3960 +** The top of the stack is an index entry that omits the ROWID. Compare
69.3961 +** the top of stack against the index that P1 is currently pointing to.
69.3962 +** Ignore the ROWID on the P1 index.
69.3963 +**
69.3964 +** If the P1 index entry is greater than or equal to the top of the stack
69.3965 +** then jump to P2. Otherwise fall through to the next instruction.
69.3966 +** In either case, the stack is popped once.
69.3967 +**
69.3968 +** If P3 is the "+" string (or any other non-NULL string) then the
69.3969 +** index taken from the top of the stack is temporarily increased by
69.3970 +** an epsilon prior to the comparison. This make the opcode work
69.3971 +** like IdxGT except that if the key from the stack is a prefix of
69.3972 +** the key in the cursor, the result is false whereas it would be
69.3973 +** true with IdxGT.
69.3974 +*/
69.3975 +/* Opcode: IdxLT P1 P2 P3
69.3976 +**
69.3977 +** The top of the stack is an index entry that omits the ROWID. Compare
69.3978 +** the top of stack against the index that P1 is currently pointing to.
69.3979 +** Ignore the ROWID on the P1 index.
69.3980 +**
69.3981 +** If the P1 index entry is less than the top of the stack
69.3982 +** then jump to P2. Otherwise fall through to the next instruction.
69.3983 +** In either case, the stack is popped once.
69.3984 +**
69.3985 +** If P3 is the "+" string (or any other non-NULL string) then the
69.3986 +** index taken from the top of the stack is temporarily increased by
69.3987 +** an epsilon prior to the comparison. This makes the opcode work
69.3988 +** like IdxLE.
69.3989 +*/
69.3990 +case OP_IdxLT: /* no-push */
69.3991 +case OP_IdxGT: /* no-push */
69.3992 +case OP_IdxGE: { /* no-push */
69.3993 + int i= pOp->p1;
69.3994 + Cursor *pC;
69.3995 +
69.3996 + assert( i>=0 && i<p->nCursor );
69.3997 + assert( p->apCsr[i]!=0 );
69.3998 + assert( pTos>=p->aStack );
69.3999 + if( (pC = p->apCsr[i])->pCursor!=0 ){
69.4000 + int res;
69.4001 +
69.4002 + assert( pTos->flags & MEM_Blob ); /* Created using OP_MakeRecord */
69.4003 + assert( pC->deferredMoveto==0 );
69.4004 + ExpandBlob(pTos);
69.4005 + *pC->pIncrKey = pOp->p3!=0;
69.4006 + assert( pOp->p3==0 || pOp->opcode!=OP_IdxGT );
69.4007 + rc = sqlite3VdbeIdxKeyCompare(pC, pTos->n, (u8*)pTos->z, &res);
69.4008 + *pC->pIncrKey = 0;
69.4009 + if( rc!=SQLITE_OK ){
69.4010 + break;
69.4011 + }
69.4012 + if( pOp->opcode==OP_IdxLT ){
69.4013 + res = -res;
69.4014 + }else if( pOp->opcode==OP_IdxGE ){
69.4015 + res++;
69.4016 + }
69.4017 + if( res>0 ){
69.4018 + pc = pOp->p2 - 1 ;
69.4019 + }
69.4020 + }
69.4021 + Release(pTos);
69.4022 + pTos--;
69.4023 + break;
69.4024 +}
69.4025 +
69.4026 +/* Opcode: Destroy P1 P2 *
69.4027 +**
69.4028 +** Delete an entire database table or index whose root page in the database
69.4029 +** file is given by P1.
69.4030 +**
69.4031 +** The table being destroyed is in the main database file if P2==0. If
69.4032 +** P2==1 then the table to be clear is in the auxiliary database file
69.4033 +** that is used to store tables create using CREATE TEMPORARY TABLE.
69.4034 +**
69.4035 +** If AUTOVACUUM is enabled then it is possible that another root page
69.4036 +** might be moved into the newly deleted root page in order to keep all
69.4037 +** root pages contiguous at the beginning of the database. The former
69.4038 +** value of the root page that moved - its value before the move occurred -
69.4039 +** is pushed onto the stack. If no page movement was required (because
69.4040 +** the table being dropped was already the last one in the database) then
69.4041 +** a zero is pushed onto the stack. If AUTOVACUUM is disabled
69.4042 +** then a zero is pushed onto the stack.
69.4043 +**
69.4044 +** See also: Clear
69.4045 +*/
69.4046 +case OP_Destroy: {
69.4047 + int iMoved;
69.4048 + int iCnt;
69.4049 +#ifndef SQLITE_OMIT_VIRTUALTABLE
69.4050 + Vdbe *pVdbe;
69.4051 + iCnt = 0;
69.4052 + for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
69.4053 + if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
69.4054 + iCnt++;
69.4055 + }
69.4056 + }
69.4057 +#else
69.4058 + iCnt = db->activeVdbeCnt;
69.4059 +#endif
69.4060 + if( iCnt>1 ){
69.4061 + rc = SQLITE_LOCKED;
69.4062 + }else{
69.4063 + assert( iCnt==1 );
69.4064 + rc = sqlite3BtreeDropTable(db->aDb[pOp->p2].pBt, pOp->p1, &iMoved);
69.4065 + pTos++;
69.4066 + pTos->flags = MEM_Int;
69.4067 + pTos->u.i = iMoved;
69.4068 +#ifndef SQLITE_OMIT_AUTOVACUUM
69.4069 + if( rc==SQLITE_OK && iMoved!=0 ){
69.4070 + sqlite3RootPageMoved(&db->aDb[pOp->p2], iMoved, pOp->p1);
69.4071 + }
69.4072 +#endif
69.4073 + }
69.4074 + break;
69.4075 +}
69.4076 +
69.4077 +/* Opcode: Clear P1 P2 *
69.4078 +**
69.4079 +** Delete all contents of the database table or index whose root page
69.4080 +** in the database file is given by P1. But, unlike Destroy, do not
69.4081 +** remove the table or index from the database file.
69.4082 +**
69.4083 +** The table being clear is in the main database file if P2==0. If
69.4084 +** P2==1 then the table to be clear is in the auxiliary database file
69.4085 +** that is used to store tables create using CREATE TEMPORARY TABLE.
69.4086 +**
69.4087 +** See also: Destroy
69.4088 +*/
69.4089 +case OP_Clear: { /* no-push */
69.4090 +
69.4091 + /* For consistency with the way other features of SQLite operate
69.4092 + ** with a truncate, we will also skip the update callback.
69.4093 + */
69.4094 +#if 0
69.4095 + Btree *pBt = db->aDb[pOp->p2].pBt;
69.4096 + if( db->xUpdateCallback && pOp->p3 ){
69.4097 + const char *zDb = db->aDb[pOp->p2].zName;
69.4098 + const char *zTbl = pOp->p3;
69.4099 + BtCursor *pCur = 0;
69.4100 + int fin = 0;
69.4101 +
69.4102 + rc = sqlite3BtreeCursor(pBt, pOp->p1, 0, 0, 0, &pCur);
69.4103 + if( rc!=SQLITE_OK ){
69.4104 + goto abort_due_to_error;
69.4105 + }
69.4106 + for(
69.4107 + rc=sqlite3BtreeFirst(pCur, &fin);
69.4108 + rc==SQLITE_OK && !fin;
69.4109 + rc=sqlite3BtreeNext(pCur, &fin)
69.4110 + ){
69.4111 + i64 iKey;
69.4112 + rc = sqlite3BtreeKeySize(pCur, &iKey);
69.4113 + if( rc ){
69.4114 + break;
69.4115 + }
69.4116 + iKey = keyToInt(iKey);
69.4117 + db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
69.4118 + }
69.4119 + sqlite3BtreeCloseCursor(pCur);
69.4120 + if( rc!=SQLITE_OK ){
69.4121 + goto abort_due_to_error;
69.4122 + }
69.4123 + }
69.4124 +#endif
69.4125 + rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
69.4126 + break;
69.4127 +}
69.4128 +
69.4129 +/* Opcode: CreateTable P1 * *
69.4130 +**
69.4131 +** Allocate a new table in the main database file if P2==0 or in the
69.4132 +** auxiliary database file if P2==1. Push the page number
69.4133 +** for the root page of the new table onto the stack.
69.4134 +**
69.4135 +** The difference between a table and an index is this: A table must
69.4136 +** have a 4-byte integer key and can have arbitrary data. An index
69.4137 +** has an arbitrary key but no data.
69.4138 +**
69.4139 +** See also: CreateIndex
69.4140 +*/
69.4141 +/* Opcode: CreateIndex P1 * *
69.4142 +**
69.4143 +** Allocate a new index in the main database file if P2==0 or in the
69.4144 +** auxiliary database file if P2==1. Push the page number of the
69.4145 +** root page of the new index onto the stack.
69.4146 +**
69.4147 +** See documentation on OP_CreateTable for additional information.
69.4148 +*/
69.4149 +case OP_CreateIndex:
69.4150 +case OP_CreateTable: {
69.4151 + int pgno;
69.4152 + int flags;
69.4153 + Db *pDb;
69.4154 + assert( pOp->p1>=0 && pOp->p1<db->nDb );
69.4155 + pDb = &db->aDb[pOp->p1];
69.4156 + assert( pDb->pBt!=0 );
69.4157 + if( pOp->opcode==OP_CreateTable ){
69.4158 + /* flags = BTREE_INTKEY; */
69.4159 + flags = BTREE_LEAFDATA|BTREE_INTKEY;
69.4160 + }else{
69.4161 + flags = BTREE_ZERODATA;
69.4162 + }
69.4163 + rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
69.4164 + pTos++;
69.4165 + if( rc==SQLITE_OK ){
69.4166 + pTos->u.i = pgno;
69.4167 + pTos->flags = MEM_Int;
69.4168 + }else{
69.4169 + pTos->flags = MEM_Null;
69.4170 + }
69.4171 + break;
69.4172 +}
69.4173 +
69.4174 +/* Opcode: ParseSchema P1 P2 P3
69.4175 +**
69.4176 +** Read and parse all entries from the SQLITE_MASTER table of database P1
69.4177 +** that match the WHERE clause P3. P2 is the "force" flag. Always do
69.4178 +** the parsing if P2 is true. If P2 is false, then this routine is a
69.4179 +** no-op if the schema is not currently loaded. In other words, if P2
69.4180 +** is false, the SQLITE_MASTER table is only parsed if the rest of the
69.4181 +** schema is already loaded into the symbol table.
69.4182 +**
69.4183 +** This opcode invokes the parser to create a new virtual machine,
69.4184 +** then runs the new virtual machine. It is thus a reentrant opcode.
69.4185 +*/
69.4186 +case OP_ParseSchema: { /* no-push */
69.4187 + char *zSql;
69.4188 + int iDb = pOp->p1;
69.4189 + const char *zMaster;
69.4190 + InitData initData;
69.4191 +
69.4192 + assert( iDb>=0 && iDb<db->nDb );
69.4193 + if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
69.4194 + break;
69.4195 + }
69.4196 + zMaster = SCHEMA_TABLE(iDb);
69.4197 + initData.db = db;
69.4198 + initData.iDb = pOp->p1;
69.4199 + initData.pzErrMsg = &p->zErrMsg;
69.4200 + zSql = sqlite3MPrintf(
69.4201 + "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
69.4202 + db->aDb[iDb].zName, zMaster, pOp->p3);
69.4203 + if( zSql==0 ) goto no_mem;
69.4204 + sqlite3SafetyOff(db);
69.4205 + assert( db->init.busy==0 );
69.4206 + db->init.busy = 1;
69.4207 + assert( !sqlite3MallocFailed() );
69.4208 + rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
69.4209 + if( rc==SQLITE_ABORT ) rc = initData.rc;
69.4210 + sqliteFree(zSql);
69.4211 + db->init.busy = 0;
69.4212 + sqlite3SafetyOn(db);
69.4213 + if( rc==SQLITE_NOMEM ){
69.4214 + sqlite3FailedMalloc();
69.4215 + goto no_mem;
69.4216 + }
69.4217 + break;
69.4218 +}
69.4219 +
69.4220 +#if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
69.4221 +/* Opcode: LoadAnalysis P1 * *
69.4222 +**
69.4223 +** Read the sqlite_stat1 table for database P1 and load the content
69.4224 +** of that table into the internal index hash table. This will cause
69.4225 +** the analysis to be used when preparing all subsequent queries.
69.4226 +*/
69.4227 +case OP_LoadAnalysis: { /* no-push */
69.4228 + int iDb = pOp->p1;
69.4229 + assert( iDb>=0 && iDb<db->nDb );
69.4230 + rc = sqlite3AnalysisLoad(db, iDb);
69.4231 + break;
69.4232 +}
69.4233 +#endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER) */
69.4234 +
69.4235 +/* Opcode: DropTable P1 * P3
69.4236 +**
69.4237 +** Remove the internal (in-memory) data structures that describe
69.4238 +** the table named P3 in database P1. This is called after a table
69.4239 +** is dropped in order to keep the internal representation of the
69.4240 +** schema consistent with what is on disk.
69.4241 +*/
69.4242 +case OP_DropTable: { /* no-push */
69.4243 + sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p3);
69.4244 + break;
69.4245 +}
69.4246 +
69.4247 +/* Opcode: DropIndex P1 * P3
69.4248 +**
69.4249 +** Remove the internal (in-memory) data structures that describe
69.4250 +** the index named P3 in database P1. This is called after an index
69.4251 +** is dropped in order to keep the internal representation of the
69.4252 +** schema consistent with what is on disk.
69.4253 +*/
69.4254 +case OP_DropIndex: { /* no-push */
69.4255 + sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p3);
69.4256 + break;
69.4257 +}
69.4258 +
69.4259 +/* Opcode: DropTrigger P1 * P3
69.4260 +**
69.4261 +** Remove the internal (in-memory) data structures that describe
69.4262 +** the trigger named P3 in database P1. This is called after a trigger
69.4263 +** is dropped in order to keep the internal representation of the
69.4264 +** schema consistent with what is on disk.
69.4265 +*/
69.4266 +case OP_DropTrigger: { /* no-push */
69.4267 + sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p3);
69.4268 + break;
69.4269 +}
69.4270 +
69.4271 +
69.4272 +#ifndef SQLITE_OMIT_INTEGRITY_CHECK
69.4273 +/* Opcode: IntegrityCk P1 P2 *
69.4274 +**
69.4275 +** Do an analysis of the currently open database. Push onto the
69.4276 +** stack the text of an error message describing any problems.
69.4277 +** If no problems are found, push a NULL onto the stack.
69.4278 +**
69.4279 +** P1 is the address of a memory cell that contains the maximum
69.4280 +** number of allowed errors. At most mem[P1] errors will be reported.
69.4281 +** In other words, the analysis stops as soon as mem[P1] errors are
69.4282 +** seen. Mem[P1] is updated with the number of errors remaining.
69.4283 +**
69.4284 +** The root page numbers of all tables in the database are integer
69.4285 +** values on the stack. This opcode pulls as many integers as it
69.4286 +** can off of the stack and uses those numbers as the root pages.
69.4287 +**
69.4288 +** If P2 is not zero, the check is done on the auxiliary database
69.4289 +** file, not the main database file.
69.4290 +**
69.4291 +** This opcode is used to implement the integrity_check pragma.
69.4292 +*/
69.4293 +case OP_IntegrityCk: {
69.4294 + int nRoot;
69.4295 + int *aRoot;
69.4296 + int j;
69.4297 + int nErr;
69.4298 + char *z;
69.4299 + Mem *pnErr;
69.4300 +
69.4301 + for(nRoot=0; &pTos[-nRoot]>=p->aStack; nRoot++){
69.4302 + if( (pTos[-nRoot].flags & MEM_Int)==0 ) break;
69.4303 + }
69.4304 + assert( nRoot>0 );
69.4305 + aRoot = sqliteMallocRaw( sizeof(int*)*(nRoot+1) );
69.4306 + if( aRoot==0 ) goto no_mem;
69.4307 + j = pOp->p1;
69.4308 + assert( j>=0 && j<p->nMem );
69.4309 + pnErr = &p->aMem[j];
69.4310 + assert( (pnErr->flags & MEM_Int)!=0 );
69.4311 + for(j=0; j<nRoot; j++){
69.4312 + aRoot[j] = pTos[-j].u.i;
69.4313 + }
69.4314 + aRoot[j] = 0;
69.4315 + popStack(&pTos, nRoot);
69.4316 + pTos++;
69.4317 + z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot,
69.4318 + pnErr->u.i, &nErr);
69.4319 + pnErr->u.i -= nErr;
69.4320 + if( nErr==0 ){
69.4321 + assert( z==0 );
69.4322 + pTos->flags = MEM_Null;
69.4323 + }else{
69.4324 + pTos->z = z;
69.4325 + pTos->n = strlen(z);
69.4326 + pTos->flags = MEM_Str | MEM_Dyn | MEM_Term;
69.4327 + pTos->xDel = 0;
69.4328 + }
69.4329 + pTos->enc = SQLITE_UTF8;
69.4330 + sqlite3VdbeChangeEncoding(pTos, encoding);
69.4331 + sqliteFree(aRoot);
69.4332 + break;
69.4333 +}
69.4334 +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
69.4335 +
69.4336 +/* Opcode: FifoWrite * * *
69.4337 +**
69.4338 +** Write the integer on the top of the stack
69.4339 +** into the Fifo.
69.4340 +*/
69.4341 +case OP_FifoWrite: { /* no-push */
69.4342 + assert( pTos>=p->aStack );
69.4343 + sqlite3VdbeMemIntegerify(pTos);
69.4344 + sqlite3VdbeFifoPush(&p->sFifo, pTos->u.i);
69.4345 + assert( (pTos->flags & MEM_Dyn)==0 );
69.4346 + pTos--;
69.4347 + break;
69.4348 +}
69.4349 +
69.4350 +/* Opcode: FifoRead * P2 *
69.4351 +**
69.4352 +** Attempt to read a single integer from the Fifo
69.4353 +** and push it onto the stack. If the Fifo is empty
69.4354 +** push nothing but instead jump to P2.
69.4355 +*/
69.4356 +case OP_FifoRead: {
69.4357 + i64 v;
69.4358 + CHECK_FOR_INTERRUPT;
69.4359 + if( sqlite3VdbeFifoPop(&p->sFifo, &v)==SQLITE_DONE ){
69.4360 + pc = pOp->p2 - 1;
69.4361 + }else{
69.4362 + pTos++;
69.4363 + pTos->u.i = v;
69.4364 + pTos->flags = MEM_Int;
69.4365 + }
69.4366 + break;
69.4367 +}
69.4368 +
69.4369 +#ifndef SQLITE_OMIT_TRIGGER
69.4370 +/* Opcode: ContextPush * * *
69.4371 +**
69.4372 +** Save the current Vdbe context such that it can be restored by a ContextPop
69.4373 +** opcode. The context stores the last insert row id, the last statement change
69.4374 +** count, and the current statement change count.
69.4375 +*/
69.4376 +case OP_ContextPush: { /* no-push */
69.4377 + int i = p->contextStackTop++;
69.4378 + Context *pContext;
69.4379 +
69.4380 + assert( i>=0 );
69.4381 + /* FIX ME: This should be allocated as part of the vdbe at compile-time */
69.4382 + if( i>=p->contextStackDepth ){
69.4383 + p->contextStackDepth = i+1;
69.4384 + p->contextStack = sqliteReallocOrFree(p->contextStack,
69.4385 + sizeof(Context)*(i+1));
69.4386 + if( p->contextStack==0 ) goto no_mem;
69.4387 + }
69.4388 + pContext = &p->contextStack[i];
69.4389 + pContext->lastRowid = db->lastRowid;
69.4390 + pContext->nChange = p->nChange;
69.4391 + pContext->sFifo = p->sFifo;
69.4392 + sqlite3VdbeFifoInit(&p->sFifo);
69.4393 + break;
69.4394 +}
69.4395 +
69.4396 +/* Opcode: ContextPop * * *
69.4397 +**
69.4398 +** Restore the Vdbe context to the state it was in when contextPush was last
69.4399 +** executed. The context stores the last insert row id, the last statement
69.4400 +** change count, and the current statement change count.
69.4401 +*/
69.4402 +case OP_ContextPop: { /* no-push */
69.4403 + Context *pContext = &p->contextStack[--p->contextStackTop];
69.4404 + assert( p->contextStackTop>=0 );
69.4405 + db->lastRowid = pContext->lastRowid;
69.4406 + p->nChange = pContext->nChange;
69.4407 + sqlite3VdbeFifoClear(&p->sFifo);
69.4408 + p->sFifo = pContext->sFifo;
69.4409 + break;
69.4410 +}
69.4411 +#endif /* #ifndef SQLITE_OMIT_TRIGGER */
69.4412 +
69.4413 +/* Opcode: MemStore P1 P2 *
69.4414 +**
69.4415 +** Write the top of the stack into memory location P1.
69.4416 +** P1 should be a small integer since space is allocated
69.4417 +** for all memory locations between 0 and P1 inclusive.
69.4418 +**
69.4419 +** After the data is stored in the memory location, the
69.4420 +** stack is popped once if P2 is 1. If P2 is zero, then
69.4421 +** the original data remains on the stack.
69.4422 +*/
69.4423 +case OP_MemStore: { /* no-push */
69.4424 + assert( pTos>=p->aStack );
69.4425 + assert( pOp->p1>=0 && pOp->p1<p->nMem );
69.4426 + rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], pTos);
69.4427 + pTos--;
69.4428 +
69.4429 + /* If P2 is 0 then fall thru to the next opcode, OP_MemLoad, that will
69.4430 + ** restore the top of the stack to its original value.
69.4431 + */
69.4432 + if( pOp->p2 ){
69.4433 + break;
69.4434 + }
69.4435 +}
69.4436 +/* Opcode: MemLoad P1 * *
69.4437 +**
69.4438 +** Push a copy of the value in memory location P1 onto the stack.
69.4439 +**
69.4440 +** If the value is a string, then the value pushed is a pointer to
69.4441 +** the string that is stored in the memory location. If the memory
69.4442 +** location is subsequently changed (using OP_MemStore) then the
69.4443 +** value pushed onto the stack will change too.
69.4444 +*/
69.4445 +case OP_MemLoad: {
69.4446 + int i = pOp->p1;
69.4447 + assert( i>=0 && i<p->nMem );
69.4448 + pTos++;
69.4449 + sqlite3VdbeMemShallowCopy(pTos, &p->aMem[i], MEM_Ephem);
69.4450 + break;
69.4451 +}
69.4452 +
69.4453 +#ifndef SQLITE_OMIT_AUTOINCREMENT
69.4454 +/* Opcode: MemMax P1 * *
69.4455 +**
69.4456 +** Set the value of memory cell P1 to the maximum of its current value
69.4457 +** and the value on the top of the stack. The stack is unchanged.
69.4458 +**
69.4459 +** This instruction throws an error if the memory cell is not initially
69.4460 +** an integer.
69.4461 +*/
69.4462 +case OP_MemMax: { /* no-push */
69.4463 + int i = pOp->p1;
69.4464 + Mem *pMem;
69.4465 + assert( pTos>=p->aStack );
69.4466 + assert( i>=0 && i<p->nMem );
69.4467 + pMem = &p->aMem[i];
69.4468 + sqlite3VdbeMemIntegerify(pMem);
69.4469 + sqlite3VdbeMemIntegerify(pTos);
69.4470 + if( pMem->u.i<pTos->u.i){
69.4471 + pMem->u.i = pTos->u.i;
69.4472 + }
69.4473 + break;
69.4474 +}
69.4475 +#endif /* SQLITE_OMIT_AUTOINCREMENT */
69.4476 +
69.4477 +/* Opcode: MemIncr P1 P2 *
69.4478 +**
69.4479 +** Increment the integer valued memory cell P2 by the value in P1.
69.4480 +**
69.4481 +** It is illegal to use this instruction on a memory cell that does
69.4482 +** not contain an integer. An assertion fault will result if you try.
69.4483 +*/
69.4484 +case OP_MemIncr: { /* no-push */
69.4485 + int i = pOp->p2;
69.4486 + Mem *pMem;
69.4487 + assert( i>=0 && i<p->nMem );
69.4488 + pMem = &p->aMem[i];
69.4489 + assert( pMem->flags==MEM_Int );
69.4490 + pMem->u.i += pOp->p1;
69.4491 + break;
69.4492 +}
69.4493 +
69.4494 +/* Opcode: IfMemPos P1 P2 *
69.4495 +**
69.4496 +** If the value of memory cell P1 is 1 or greater, jump to P2.
69.4497 +**
69.4498 +** It is illegal to use this instruction on a memory cell that does
69.4499 +** not contain an integer. An assertion fault will result if you try.
69.4500 +*/
69.4501 +case OP_IfMemPos: { /* no-push */
69.4502 + int i = pOp->p1;
69.4503 + Mem *pMem;
69.4504 + assert( i>=0 && i<p->nMem );
69.4505 + pMem = &p->aMem[i];
69.4506 + assert( pMem->flags==MEM_Int );
69.4507 + if( pMem->u.i>0 ){
69.4508 + pc = pOp->p2 - 1;
69.4509 + }
69.4510 + break;
69.4511 +}
69.4512 +
69.4513 +/* Opcode: IfMemNeg P1 P2 *
69.4514 +**
69.4515 +** If the value of memory cell P1 is less than zero, jump to P2.
69.4516 +**
69.4517 +** It is illegal to use this instruction on a memory cell that does
69.4518 +** not contain an integer. An assertion fault will result if you try.
69.4519 +*/
69.4520 +case OP_IfMemNeg: { /* no-push */
69.4521 + int i = pOp->p1;
69.4522 + Mem *pMem;
69.4523 + assert( i>=0 && i<p->nMem );
69.4524 + pMem = &p->aMem[i];
69.4525 + assert( pMem->flags==MEM_Int );
69.4526 + if( pMem->u.i<0 ){
69.4527 + pc = pOp->p2 - 1;
69.4528 + }
69.4529 + break;
69.4530 +}
69.4531 +
69.4532 +/* Opcode: IfMemZero P1 P2 *
69.4533 +**
69.4534 +** If the value of memory cell P1 is exactly 0, jump to P2.
69.4535 +**
69.4536 +** It is illegal to use this instruction on a memory cell that does
69.4537 +** not contain an integer. An assertion fault will result if you try.
69.4538 +*/
69.4539 +case OP_IfMemZero: { /* no-push */
69.4540 + int i = pOp->p1;
69.4541 + Mem *pMem;
69.4542 + assert( i>=0 && i<p->nMem );
69.4543 + pMem = &p->aMem[i];
69.4544 + assert( pMem->flags==MEM_Int );
69.4545 + if( pMem->u.i==0 ){
69.4546 + pc = pOp->p2 - 1;
69.4547 + }
69.4548 + break;
69.4549 +}
69.4550 +
69.4551 +/* Opcode: MemNull P1 * *
69.4552 +**
69.4553 +** Store a NULL in memory cell P1
69.4554 +*/
69.4555 +case OP_MemNull: {
69.4556 + assert( pOp->p1>=0 && pOp->p1<p->nMem );
69.4557 + sqlite3VdbeMemSetNull(&p->aMem[pOp->p1]);
69.4558 + break;
69.4559 +}
69.4560 +
69.4561 +/* Opcode: MemInt P1 P2 *
69.4562 +**
69.4563 +** Store the integer value P1 in memory cell P2.
69.4564 +*/
69.4565 +case OP_MemInt: {
69.4566 + assert( pOp->p2>=0 && pOp->p2<p->nMem );
69.4567 + sqlite3VdbeMemSetInt64(&p->aMem[pOp->p2], pOp->p1);
69.4568 + break;
69.4569 +}
69.4570 +
69.4571 +/* Opcode: MemMove P1 P2 *
69.4572 +**
69.4573 +** Move the content of memory cell P2 over to memory cell P1.
69.4574 +** Any prior content of P1 is erased. Memory cell P2 is left
69.4575 +** containing a NULL.
69.4576 +*/
69.4577 +case OP_MemMove: {
69.4578 + assert( pOp->p1>=0 && pOp->p1<p->nMem );
69.4579 + assert( pOp->p2>=0 && pOp->p2<p->nMem );
69.4580 + rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], &p->aMem[pOp->p2]);
69.4581 + break;
69.4582 +}
69.4583 +
69.4584 +/* Opcode: AggStep P1 P2 P3
69.4585 +**
69.4586 +** Execute the step function for an aggregate. The
69.4587 +** function has P2 arguments. P3 is a pointer to the FuncDef
69.4588 +** structure that specifies the function. Use memory location
69.4589 +** P1 as the accumulator.
69.4590 +**
69.4591 +** The P2 arguments are popped from the stack.
69.4592 +*/
69.4593 +case OP_AggStep: { /* no-push */
69.4594 + int n = pOp->p2;
69.4595 + int i;
69.4596 + Mem *pMem, *pRec;
69.4597 + sqlite3_context ctx;
69.4598 + sqlite3_value **apVal;
69.4599 +
69.4600 + assert( n>=0 );
69.4601 + pRec = &pTos[1-n];
69.4602 + assert( pRec>=p->aStack );
69.4603 + apVal = p->apArg;
69.4604 + assert( apVal || n==0 );
69.4605 + for(i=0; i<n; i++, pRec++){
69.4606 + apVal[i] = pRec;
69.4607 + storeTypeInfo(pRec, encoding);
69.4608 + }
69.4609 + ctx.pFunc = (FuncDef*)pOp->p3;
69.4610 + assert( pOp->p1>=0 && pOp->p1<p->nMem );
69.4611 + ctx.pMem = pMem = &p->aMem[pOp->p1];
69.4612 + pMem->n++;
69.4613 + ctx.s.flags = MEM_Null;
69.4614 + ctx.s.z = 0;
69.4615 + ctx.s.xDel = 0;
69.4616 + ctx.isError = 0;
69.4617 + ctx.pColl = 0;
69.4618 + if( ctx.pFunc->needCollSeq ){
69.4619 + assert( pOp>p->aOp );
69.4620 + assert( pOp[-1].p3type==P3_COLLSEQ );
69.4621 + assert( pOp[-1].opcode==OP_CollSeq );
69.4622 + ctx.pColl = (CollSeq *)pOp[-1].p3;
69.4623 + }
69.4624 + (ctx.pFunc->xStep)(&ctx, n, apVal);
69.4625 + popStack(&pTos, n);
69.4626 + if( ctx.isError ){
69.4627 + sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
69.4628 + rc = SQLITE_ERROR;
69.4629 + }
69.4630 + sqlite3VdbeMemRelease(&ctx.s);
69.4631 + break;
69.4632 +}
69.4633 +
69.4634 +/* Opcode: AggFinal P1 P2 P3
69.4635 +**
69.4636 +** Execute the finalizer function for an aggregate. P1 is
69.4637 +** the memory location that is the accumulator for the aggregate.
69.4638 +**
69.4639 +** P2 is the number of arguments that the step function takes and
69.4640 +** P3 is a pointer to the FuncDef for this function. The P2
69.4641 +** argument is not used by this opcode. It is only there to disambiguate
69.4642 +** functions that can take varying numbers of arguments. The
69.4643 +** P3 argument is only needed for the degenerate case where
69.4644 +** the step function was not previously called.
69.4645 +*/
69.4646 +case OP_AggFinal: { /* no-push */
69.4647 + Mem *pMem;
69.4648 + assert( pOp->p1>=0 && pOp->p1<p->nMem );
69.4649 + pMem = &p->aMem[pOp->p1];
69.4650 + assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
69.4651 + rc = sqlite3VdbeMemFinalize(pMem, (FuncDef*)pOp->p3);
69.4652 + if( rc==SQLITE_ERROR ){
69.4653 + sqlite3SetString(&p->zErrMsg, sqlite3_value_text(pMem), (char*)0);
69.4654 + }
69.4655 + if( sqlite3VdbeMemTooBig(pMem) ){
69.4656 + goto too_big;
69.4657 + }
69.4658 + break;
69.4659 +}
69.4660 +
69.4661 +
69.4662 +#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
69.4663 +/* Opcode: Vacuum * * *
69.4664 +**
69.4665 +** Vacuum the entire database. This opcode will cause other virtual
69.4666 +** machines to be created and run. It may not be called from within
69.4667 +** a transaction.
69.4668 +*/
69.4669 +case OP_Vacuum: { /* no-push */
69.4670 + if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
69.4671 + rc = sqlite3RunVacuum(&p->zErrMsg, db);
69.4672 + if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
69.4673 + break;
69.4674 +}
69.4675 +#endif
69.4676 +
69.4677 +#if !defined(SQLITE_OMIT_AUTOVACUUM)
69.4678 +/* Opcode: IncrVacuum P1 P2 *
69.4679 +**
69.4680 +** Perform a single step of the incremental vacuum procedure on
69.4681 +** the P1 database. If the vacuum has finished, jump to instruction
69.4682 +** P2. Otherwise, fall through to the next instruction.
69.4683 +*/
69.4684 +case OP_IncrVacuum: { /* no-push */
69.4685 + Btree *pBt;
69.4686 +
69.4687 + assert( pOp->p1>=0 && pOp->p1<db->nDb );
69.4688 + pBt = db->aDb[pOp->p1].pBt;
69.4689 + rc = sqlite3BtreeIncrVacuum(pBt);
69.4690 + if( rc==SQLITE_DONE ){
69.4691 + pc = pOp->p2 - 1;
69.4692 + rc = SQLITE_OK;
69.4693 + }
69.4694 + break;
69.4695 +}
69.4696 +#endif
69.4697 +
69.4698 +/* Opcode: Expire P1 * *
69.4699 +**
69.4700 +** Cause precompiled statements to become expired. An expired statement
69.4701 +** fails with an error code of SQLITE_SCHEMA if it is ever executed
69.4702 +** (via sqlite3_step()).
69.4703 +**
69.4704 +** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
69.4705 +** then only the currently executing statement is affected.
69.4706 +*/
69.4707 +case OP_Expire: { /* no-push */
69.4708 + if( !pOp->p1 ){
69.4709 + sqlite3ExpirePreparedStatements(db);
69.4710 + }else{
69.4711 + p->expired = 1;
69.4712 + }
69.4713 + break;
69.4714 +}
69.4715 +
69.4716 +#ifndef SQLITE_OMIT_SHARED_CACHE
69.4717 +/* Opcode: TableLock P1 P2 P3
69.4718 +**
69.4719 +** Obtain a lock on a particular table. This instruction is only used when
69.4720 +** the shared-cache feature is enabled.
69.4721 +**
69.4722 +** If P1 is not negative, then it is the index of the database
69.4723 +** in sqlite3.aDb[] and a read-lock is required. If P1 is negative, a
69.4724 +** write-lock is required. In this case the index of the database is the
69.4725 +** absolute value of P1 minus one (iDb = abs(P1) - 1;) and a write-lock is
69.4726 +** required.
69.4727 +**
69.4728 +** P2 contains the root-page of the table to lock.
69.4729 +**
69.4730 +** P3 contains a pointer to the name of the table being locked. This is only
69.4731 +** used to generate an error message if the lock cannot be obtained.
69.4732 +*/
69.4733 +case OP_TableLock: { /* no-push */
69.4734 + int p1 = pOp->p1;
69.4735 + u8 isWriteLock = (p1<0);
69.4736 + if( isWriteLock ){
69.4737 + p1 = (-1*p1)-1;
69.4738 + }
69.4739 + rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
69.4740 + if( rc==SQLITE_LOCKED ){
69.4741 + const char *z = (const char *)pOp->p3;
69.4742 + sqlite3SetString(&p->zErrMsg, "database table is locked: ", z, (char*)0);
69.4743 + }
69.4744 + break;
69.4745 +}
69.4746 +#endif /* SQLITE_OMIT_SHARED_CACHE */
69.4747 +
69.4748 +#ifndef SQLITE_OMIT_VIRTUALTABLE
69.4749 +/* Opcode: VBegin * * P3
69.4750 +**
69.4751 +** P3 a pointer to an sqlite3_vtab structure. Call the xBegin method
69.4752 +** for that table.
69.4753 +*/
69.4754 +case OP_VBegin: { /* no-push */
69.4755 + rc = sqlite3VtabBegin(db, (sqlite3_vtab *)pOp->p3);
69.4756 + break;
69.4757 +}
69.4758 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
69.4759 +
69.4760 +#ifndef SQLITE_OMIT_VIRTUALTABLE
69.4761 +/* Opcode: VCreate P1 * P3
69.4762 +**
69.4763 +** P3 is the name of a virtual table in database P1. Call the xCreate method
69.4764 +** for that table.
69.4765 +*/
69.4766 +case OP_VCreate: { /* no-push */
69.4767 + rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p3, &p->zErrMsg);
69.4768 + break;
69.4769 +}
69.4770 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
69.4771 +
69.4772 +#ifndef SQLITE_OMIT_VIRTUALTABLE
69.4773 +/* Opcode: VDestroy P1 * P3
69.4774 +**
69.4775 +** P3 is the name of a virtual table in database P1. Call the xDestroy method
69.4776 +** of that table.
69.4777 +*/
69.4778 +case OP_VDestroy: { /* no-push */
69.4779 + p->inVtabMethod = 2;
69.4780 + rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p3);
69.4781 + p->inVtabMethod = 0;
69.4782 + break;
69.4783 +}
69.4784 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
69.4785 +
69.4786 +#ifndef SQLITE_OMIT_VIRTUALTABLE
69.4787 +/* Opcode: VOpen P1 * P3
69.4788 +**
69.4789 +** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
69.4790 +** P1 is a cursor number. This opcode opens a cursor to the virtual
69.4791 +** table and stores that cursor in P1.
69.4792 +*/
69.4793 +case OP_VOpen: { /* no-push */
69.4794 + Cursor *pCur = 0;
69.4795 + sqlite3_vtab_cursor *pVtabCursor = 0;
69.4796 +
69.4797 + sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
69.4798 + sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
69.4799 +
69.4800 + assert(pVtab && pModule);
69.4801 + if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
69.4802 + rc = pModule->xOpen(pVtab, &pVtabCursor);
69.4803 + if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
69.4804 + if( SQLITE_OK==rc ){
69.4805 + /* Initialise sqlite3_vtab_cursor base class */
69.4806 + pVtabCursor->pVtab = pVtab;
69.4807 +
69.4808 + /* Initialise vdbe cursor object */
69.4809 + pCur = allocateCursor(p, pOp->p1, -1);
69.4810 + if( pCur ){
69.4811 + pCur->pVtabCursor = pVtabCursor;
69.4812 + pCur->pModule = pVtabCursor->pVtab->pModule;
69.4813 + }else{
69.4814 + pModule->xClose(pVtabCursor);
69.4815 + }
69.4816 + }
69.4817 + break;
69.4818 +}
69.4819 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
69.4820 +
69.4821 +#ifndef SQLITE_OMIT_VIRTUALTABLE
69.4822 +/* Opcode: VFilter P1 P2 P3
69.4823 +**
69.4824 +** P1 is a cursor opened using VOpen. P2 is an address to jump to if
69.4825 +** the filtered result set is empty.
69.4826 +**
69.4827 +** P3 is either NULL or a string that was generated by the xBestIndex
69.4828 +** method of the module. The interpretation of the P3 string is left
69.4829 +** to the module implementation.
69.4830 +**
69.4831 +** This opcode invokes the xFilter method on the virtual table specified
69.4832 +** by P1. The integer query plan parameter to xFilter is the top of the
69.4833 +** stack. Next down on the stack is the argc parameter. Beneath the
69.4834 +** next of stack are argc additional parameters which are passed to
69.4835 +** xFilter as argv. The topmost parameter (i.e. 3rd element popped from
69.4836 +** the stack) becomes argv[argc-1] when passed to xFilter.
69.4837 +**
69.4838 +** The integer query plan parameter, argc, and all argv stack values
69.4839 +** are popped from the stack before this instruction completes.
69.4840 +**
69.4841 +** A jump is made to P2 if the result set after filtering would be
69.4842 +** empty.
69.4843 +*/
69.4844 +case OP_VFilter: { /* no-push */
69.4845 + int nArg;
69.4846 +
69.4847 + const sqlite3_module *pModule;
69.4848 +
69.4849 + Cursor *pCur = p->apCsr[pOp->p1];
69.4850 + assert( pCur->pVtabCursor );
69.4851 + pModule = pCur->pVtabCursor->pVtab->pModule;
69.4852 +
69.4853 + /* Grab the index number and argc parameters off the top of the stack. */
69.4854 + assert( (&pTos[-1])>=p->aStack );
69.4855 + assert( (pTos[0].flags&MEM_Int)!=0 && pTos[-1].flags==MEM_Int );
69.4856 + nArg = pTos[-1].u.i;
69.4857 +
69.4858 + /* Invoke the xFilter method */
69.4859 + {
69.4860 + int res = 0;
69.4861 + int i;
69.4862 + Mem **apArg = p->apArg;
69.4863 + for(i = 0; i<nArg; i++){
69.4864 + apArg[i] = &pTos[i+1-2-nArg];
69.4865 + storeTypeInfo(apArg[i], 0);
69.4866 + }
69.4867 +
69.4868 + if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
69.4869 + p->inVtabMethod = 1;
69.4870 + rc = pModule->xFilter(pCur->pVtabCursor, pTos->u.i, pOp->p3, nArg, apArg);
69.4871 + p->inVtabMethod = 0;
69.4872 + if( rc==SQLITE_OK ){
69.4873 + res = pModule->xEof(pCur->pVtabCursor);
69.4874 + }
69.4875 + if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
69.4876 +
69.4877 + if( res ){
69.4878 + pc = pOp->p2 - 1;
69.4879 + }
69.4880 + }
69.4881 +
69.4882 + /* Pop the index number, argc value and parameters off the stack */
69.4883 + popStack(&pTos, 2+nArg);
69.4884 + break;
69.4885 +}
69.4886 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
69.4887 +
69.4888 +#ifndef SQLITE_OMIT_VIRTUALTABLE
69.4889 +/* Opcode: VRowid P1 * *
69.4890 +**
69.4891 +** Push an integer onto the stack which is the rowid of
69.4892 +** the virtual-table that the P1 cursor is pointing to.
69.4893 +*/
69.4894 +case OP_VRowid: {
69.4895 + const sqlite3_module *pModule;
69.4896 +
69.4897 + Cursor *pCur = p->apCsr[pOp->p1];
69.4898 + assert( pCur->pVtabCursor );
69.4899 + pModule = pCur->pVtabCursor->pVtab->pModule;
69.4900 + if( pModule->xRowid==0 ){
69.4901 + sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xRowid", 0);
69.4902 + rc = SQLITE_ERROR;
69.4903 + } else {
69.4904 + sqlite_int64 iRow;
69.4905 +
69.4906 + if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
69.4907 + rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
69.4908 + if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
69.4909 +
69.4910 + pTos++;
69.4911 + pTos->flags = MEM_Int;
69.4912 + pTos->u.i = iRow;
69.4913 + }
69.4914 +
69.4915 + break;
69.4916 +}
69.4917 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
69.4918 +
69.4919 +#ifndef SQLITE_OMIT_VIRTUALTABLE
69.4920 +/* Opcode: VColumn P1 P2 *
69.4921 +**
69.4922 +** Push onto the stack the value of the P2-th column of
69.4923 +** the row of the virtual-table that the P1 cursor is pointing to.
69.4924 +*/
69.4925 +case OP_VColumn: {
69.4926 + const sqlite3_module *pModule;
69.4927 +
69.4928 + Cursor *pCur = p->apCsr[pOp->p1];
69.4929 + assert( pCur->pVtabCursor );
69.4930 + pModule = pCur->pVtabCursor->pVtab->pModule;
69.4931 + if( pModule->xColumn==0 ){
69.4932 + sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xColumn", 0);
69.4933 + rc = SQLITE_ERROR;
69.4934 + } else {
69.4935 + sqlite3_context sContext;
69.4936 + memset(&sContext, 0, sizeof(sContext));
69.4937 + sContext.s.flags = MEM_Null;
69.4938 + if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
69.4939 + rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
69.4940 +
69.4941 + /* Copy the result of the function to the top of the stack. We
69.4942 + ** do this regardless of whether or not an error occured to ensure any
69.4943 + ** dynamic allocation in sContext.s (a Mem struct) is released.
69.4944 + */
69.4945 + sqlite3VdbeChangeEncoding(&sContext.s, encoding);
69.4946 + pTos++;
69.4947 + pTos->flags = 0;
69.4948 + sqlite3VdbeMemMove(pTos, &sContext.s);
69.4949 +
69.4950 + if( sqlite3SafetyOn(db) ){
69.4951 + goto abort_due_to_misuse;
69.4952 + }
69.4953 + if( sqlite3VdbeMemTooBig(pTos) ){
69.4954 + goto too_big;
69.4955 + }
69.4956 + }
69.4957 +
69.4958 + break;
69.4959 +}
69.4960 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
69.4961 +
69.4962 +#ifndef SQLITE_OMIT_VIRTUALTABLE
69.4963 +/* Opcode: VNext P1 P2 *
69.4964 +**
69.4965 +** Advance virtual table P1 to the next row in its result set and
69.4966 +** jump to instruction P2. Or, if the virtual table has reached
69.4967 +** the end of its result set, then fall through to the next instruction.
69.4968 +*/
69.4969 +case OP_VNext: { /* no-push */
69.4970 + const sqlite3_module *pModule;
69.4971 + int res = 0;
69.4972 +
69.4973 + Cursor *pCur = p->apCsr[pOp->p1];
69.4974 + assert( pCur->pVtabCursor );
69.4975 + pModule = pCur->pVtabCursor->pVtab->pModule;
69.4976 + if( pModule->xNext==0 ){
69.4977 + sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xNext", 0);
69.4978 + rc = SQLITE_ERROR;
69.4979 + } else {
69.4980 + /* Invoke the xNext() method of the module. There is no way for the
69.4981 + ** underlying implementation to return an error if one occurs during
69.4982 + ** xNext(). Instead, if an error occurs, true is returned (indicating that
69.4983 + ** data is available) and the error code returned when xColumn or
69.4984 + ** some other method is next invoked on the save virtual table cursor.
69.4985 + */
69.4986 + if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
69.4987 + p->inVtabMethod = 1;
69.4988 + rc = pModule->xNext(pCur->pVtabCursor);
69.4989 + p->inVtabMethod = 0;
69.4990 + if( rc==SQLITE_OK ){
69.4991 + res = pModule->xEof(pCur->pVtabCursor);
69.4992 + }
69.4993 + if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
69.4994 +
69.4995 + if( !res ){
69.4996 + /* If there is data, jump to P2 */
69.4997 + pc = pOp->p2 - 1;
69.4998 + }
69.4999 + }
69.5000 +
69.5001 + break;
69.5002 +}
69.5003 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
69.5004 +
69.5005 +#ifndef SQLITE_OMIT_VIRTUALTABLE
69.5006 +/* Opcode: VRename * * P3
69.5007 +**
69.5008 +** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
69.5009 +** This opcode invokes the corresponding xRename method. The value
69.5010 +** on the top of the stack is popped and passed as the zName argument
69.5011 +** to the xRename method.
69.5012 +*/
69.5013 +case OP_VRename: { /* no-push */
69.5014 + sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
69.5015 + assert( pVtab->pModule->xRename );
69.5016 +
69.5017 + Stringify(pTos, encoding);
69.5018 +
69.5019 + if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
69.5020 + sqlite3VtabLock(pVtab);
69.5021 + rc = pVtab->pModule->xRename(pVtab, pTos->z);
69.5022 + sqlite3VtabUnlock(db, pVtab);
69.5023 + if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
69.5024 +
69.5025 + popStack(&pTos, 1);
69.5026 + break;
69.5027 +}
69.5028 +#endif
69.5029 +
69.5030 +#ifndef SQLITE_OMIT_VIRTUALTABLE
69.5031 +/* Opcode: VUpdate P1 P2 P3
69.5032 +**
69.5033 +** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
69.5034 +** This opcode invokes the corresponding xUpdate method. P2 values
69.5035 +** are taken from the stack to pass to the xUpdate invocation. The
69.5036 +** value on the top of the stack corresponds to the p2th element
69.5037 +** of the argv array passed to xUpdate.
69.5038 +**
69.5039 +** The xUpdate method will do a DELETE or an INSERT or both.
69.5040 +** The argv[0] element (which corresponds to the P2-th element down
69.5041 +** on the stack) is the rowid of a row to delete. If argv[0] is
69.5042 +** NULL then no deletion occurs. The argv[1] element is the rowid
69.5043 +** of the new row. This can be NULL to have the virtual table
69.5044 +** select the new rowid for itself. The higher elements in the
69.5045 +** stack are the values of columns in the new row.
69.5046 +**
69.5047 +** If P2==1 then no insert is performed. argv[0] is the rowid of
69.5048 +** a row to delete.
69.5049 +**
69.5050 +** P1 is a boolean flag. If it is set to true and the xUpdate call
69.5051 +** is successful, then the value returned by sqlite3_last_insert_rowid()
69.5052 +** is set to the value of the rowid for the row just inserted.
69.5053 +*/
69.5054 +case OP_VUpdate: { /* no-push */
69.5055 + sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
69.5056 + sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
69.5057 + int nArg = pOp->p2;
69.5058 + assert( pOp->p3type==P3_VTAB );
69.5059 + if( pModule->xUpdate==0 ){
69.5060 + sqlite3SetString(&p->zErrMsg, "read-only table", 0);
69.5061 + rc = SQLITE_ERROR;
69.5062 + }else{
69.5063 + int i;
69.5064 + sqlite_int64 rowid;
69.5065 + Mem **apArg = p->apArg;
69.5066 + Mem *pX = &pTos[1-nArg];
69.5067 + for(i = 0; i<nArg; i++, pX++){
69.5068 + storeTypeInfo(pX, 0);
69.5069 + apArg[i] = pX;
69.5070 + }
69.5071 + if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
69.5072 + sqlite3VtabLock(pVtab);
69.5073 + rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
69.5074 + sqlite3VtabUnlock(db, pVtab);
69.5075 + if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
69.5076 + if( pOp->p1 && rc==SQLITE_OK ){
69.5077 + assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
69.5078 + db->lastRowid = rowid;
69.5079 + }
69.5080 + }
69.5081 + popStack(&pTos, nArg);
69.5082 + break;
69.5083 +}
69.5084 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
69.5085 +
69.5086 +/* An other opcode is illegal...
69.5087 +*/
69.5088 +default: {
69.5089 + assert( 0 );
69.5090 + break;
69.5091 +}
69.5092 +
69.5093 +/*****************************************************************************
69.5094 +** The cases of the switch statement above this line should all be indented
69.5095 +** by 6 spaces. But the left-most 6 spaces have been removed to improve the
69.5096 +** readability. From this point on down, the normal indentation rules are
69.5097 +** restored.
69.5098 +*****************************************************************************/
69.5099 + }
69.5100 +
69.5101 + /* Make sure the stack limit was not exceeded */
69.5102 + assert( pTos<=pStackLimit );
69.5103 +
69.5104 +#ifdef VDBE_PROFILE
69.5105 + {
69.5106 + long long elapse = hwtime() - start;
69.5107 + pOp->cycles += elapse;
69.5108 + pOp->cnt++;
69.5109 +#if 0
69.5110 + fprintf(stdout, "%10lld ", elapse);
69.5111 + sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
69.5112 +#endif
69.5113 + }
69.5114 +#endif
69.5115 +
69.5116 +#ifdef SQLITE_TEST
69.5117 + /* Keep track of the size of the largest BLOB or STR that has appeared
69.5118 + ** on the top of the VDBE stack.
69.5119 + */
69.5120 + if( pTos>=p->aStack && (pTos->flags & (MEM_Blob|MEM_Str))!=0
69.5121 + && pTos->n>sqlite3_max_blobsize ){
69.5122 + sqlite3_max_blobsize = pTos->n;
69.5123 + }
69.5124 +#endif
69.5125 +
69.5126 + /* The following code adds nothing to the actual functionality
69.5127 + ** of the program. It is only here for testing and debugging.
69.5128 + ** On the other hand, it does burn CPU cycles every time through
69.5129 + ** the evaluator loop. So we can leave it out when NDEBUG is defined.
69.5130 + */
69.5131 +#ifndef NDEBUG
69.5132 + /* Sanity checking on the top element of the stack. If the previous
69.5133 + ** instruction was VNoChange, then the flags field of the top
69.5134 + ** of the stack is set to 0. This is technically invalid for a memory
69.5135 + ** cell, so avoid calling MemSanity() in this case.
69.5136 + */
69.5137 + if( pTos>=p->aStack && pTos->flags ){
69.5138 + sqlite3VdbeMemSanity(pTos);
69.5139 + assert( !sqlite3VdbeMemTooBig(pTos) );
69.5140 + }
69.5141 + assert( pc>=-1 && pc<p->nOp );
69.5142 +
69.5143 +#ifdef SQLITE_DEBUG
69.5144 + /* Code for tracing the vdbe stack. */
69.5145 + if( p->trace && pTos>=p->aStack ){
69.5146 + int i;
69.5147 + fprintf(p->trace, "Stack:");
69.5148 + for(i=0; i>-5 && &pTos[i]>=p->aStack; i--){
69.5149 + if( pTos[i].flags & MEM_Null ){
69.5150 + fprintf(p->trace, " NULL");
69.5151 + }else if( (pTos[i].flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
69.5152 + fprintf(p->trace, " si:%lld", pTos[i].u.i);
69.5153 + }else if( pTos[i].flags & MEM_Int ){
69.5154 + fprintf(p->trace, " i:%lld", pTos[i].u.i);
69.5155 + }else if( pTos[i].flags & MEM_Real ){
69.5156 + fprintf(p->trace, " r:%g", pTos[i].r);
69.5157 + }else{
69.5158 + char zBuf[200];
69.5159 + sqlite3VdbeMemPrettyPrint(&pTos[i], zBuf);
69.5160 + fprintf(p->trace, " ");
69.5161 + fprintf(p->trace, "%s", zBuf);
69.5162 + }
69.5163 + }
69.5164 + if( rc!=0 ) fprintf(p->trace," rc=%d",rc);
69.5165 + fprintf(p->trace,"\n");
69.5166 + }
69.5167 +#endif /* SQLITE_DEBUG */
69.5168 +#endif /* NDEBUG */
69.5169 + } /* The end of the for(;;) loop the loops through opcodes */
69.5170 +
69.5171 + /* If we reach this point, it means that execution is finished.
69.5172 + */
69.5173 +vdbe_halt:
69.5174 + if( rc ){
69.5175 + p->rc = rc;
69.5176 + rc = SQLITE_ERROR;
69.5177 + }else{
69.5178 + rc = SQLITE_DONE;
69.5179 + }
69.5180 + sqlite3VdbeHalt(p);
69.5181 + p->pTos = pTos;
69.5182 + return rc;
69.5183 +
69.5184 + /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
69.5185 + ** is encountered.
69.5186 + */
69.5187 +too_big:
69.5188 + sqlite3SetString(&p->zErrMsg, "string or blob too big", (char*)0);
69.5189 + rc = SQLITE_TOOBIG;
69.5190 + goto vdbe_halt;
69.5191 +
69.5192 + /* Jump to here if a malloc() fails.
69.5193 + */
69.5194 +no_mem:
69.5195 + sqlite3SetString(&p->zErrMsg, "out of memory", (char*)0);
69.5196 + rc = SQLITE_NOMEM;
69.5197 + goto vdbe_halt;
69.5198 +
69.5199 + /* Jump to here for an SQLITE_MISUSE error.
69.5200 + */
69.5201 +abort_due_to_misuse:
69.5202 + rc = SQLITE_MISUSE;
69.5203 + /* Fall thru into abort_due_to_error */
69.5204 +
69.5205 + /* Jump to here for any other kind of fatal error. The "rc" variable
69.5206 + ** should hold the error number.
69.5207 + */
69.5208 +abort_due_to_error:
69.5209 + if( p->zErrMsg==0 ){
69.5210 + if( sqlite3MallocFailed() ) rc = SQLITE_NOMEM;
69.5211 + sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
69.5212 + }
69.5213 + goto vdbe_halt;
69.5214 +
69.5215 + /* Jump to here if the sqlite3_interrupt() API sets the interrupt
69.5216 + ** flag.
69.5217 + */
69.5218 +abort_due_to_interrupt:
69.5219 + assert( db->u1.isInterrupted );
69.5220 + if( db->magic!=SQLITE_MAGIC_BUSY ){
69.5221 + rc = SQLITE_MISUSE;
69.5222 + }else{
69.5223 + rc = SQLITE_INTERRUPT;
69.5224 + }
69.5225 + p->rc = rc;
69.5226 + sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
69.5227 + goto vdbe_halt;
69.5228 +}
70.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
70.2 +++ b/extensions/sqlite/sqlite-source/vdbe.h Sun Jul 29 01:15:31 2007 +0000
70.3 @@ -0,0 +1,150 @@
70.4 +/*
70.5 +** 2001 September 15
70.6 +**
70.7 +** The author disclaims copyright to this source code. In place of
70.8 +** a legal notice, here is a blessing:
70.9 +**
70.10 +** May you do good and not evil.
70.11 +** May you find forgiveness for yourself and forgive others.
70.12 +** May you share freely, never taking more than you give.
70.13 +**
70.14 +*************************************************************************
70.15 +** Header file for the Virtual DataBase Engine (VDBE)
70.16 +**
70.17 +** This header defines the interface to the virtual database engine
70.18 +** or VDBE. The VDBE implements an abstract machine that runs a
70.19 +** simple program to access and modify the underlying database.
70.20 +**
70.21 +** $Id$
70.22 +*/
70.23 +#ifndef _SQLITE_VDBE_H_
70.24 +#define _SQLITE_VDBE_H_
70.25 +#include <stdio.h>
70.26 +
70.27 +/*
70.28 +** A single VDBE is an opaque structure named "Vdbe". Only routines
70.29 +** in the source file sqliteVdbe.c are allowed to see the insides
70.30 +** of this structure.
70.31 +*/
70.32 +typedef struct Vdbe Vdbe;
70.33 +
70.34 +/*
70.35 +** A single instruction of the virtual machine has an opcode
70.36 +** and as many as three operands. The instruction is recorded
70.37 +** as an instance of the following structure:
70.38 +*/
70.39 +struct VdbeOp {
70.40 + u8 opcode; /* What operation to perform */
70.41 + int p1; /* First operand */
70.42 + int p2; /* Second parameter (often the jump destination) */
70.43 + char *p3; /* Third parameter */
70.44 + int p3type; /* One of the P3_xxx constants defined below */
70.45 +#ifdef VDBE_PROFILE
70.46 + int cnt; /* Number of times this instruction was executed */
70.47 + long long cycles; /* Total time spend executing this instruction */
70.48 +#endif
70.49 +};
70.50 +typedef struct VdbeOp VdbeOp;
70.51 +
70.52 +/*
70.53 +** A smaller version of VdbeOp used for the VdbeAddOpList() function because
70.54 +** it takes up less space.
70.55 +*/
70.56 +struct VdbeOpList {
70.57 + u8 opcode; /* What operation to perform */
70.58 + signed char p1; /* First operand */
70.59 + short int p2; /* Second parameter (often the jump destination) */
70.60 + char *p3; /* Third parameter */
70.61 +};
70.62 +typedef struct VdbeOpList VdbeOpList;
70.63 +
70.64 +/*
70.65 +** Allowed values of VdbeOp.p3type
70.66 +*/
70.67 +#define P3_NOTUSED 0 /* The P3 parameter is not used */
70.68 +#define P3_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
70.69 +#define P3_STATIC (-2) /* Pointer to a static string */
70.70 +#define P3_COLLSEQ (-4) /* P3 is a pointer to a CollSeq structure */
70.71 +#define P3_FUNCDEF (-5) /* P3 is a pointer to a FuncDef structure */
70.72 +#define P3_KEYINFO (-6) /* P3 is a pointer to a KeyInfo structure */
70.73 +#define P3_VDBEFUNC (-7) /* P3 is a pointer to a VdbeFunc structure */
70.74 +#define P3_MEM (-8) /* P3 is a pointer to a Mem* structure */
70.75 +#define P3_TRANSIENT (-9) /* P3 is a pointer to a transient string */
70.76 +#define P3_VTAB (-10) /* P3 is a pointer to an sqlite3_vtab structure */
70.77 +#define P3_MPRINTF (-11) /* P3 is a string obtained from sqlite3_mprintf() */
70.78 +
70.79 +/* When adding a P3 argument using P3_KEYINFO, a copy of the KeyInfo structure
70.80 +** is made. That copy is freed when the Vdbe is finalized. But if the
70.81 +** argument is P3_KEYINFO_HANDOFF, the passed in pointer is used. It still
70.82 +** gets freed when the Vdbe is finalized so it still should be obtained
70.83 +** from a single sqliteMalloc(). But no copy is made and the calling
70.84 +** function should *not* try to free the KeyInfo.
70.85 +*/
70.86 +#define P3_KEYINFO_HANDOFF (-9)
70.87 +
70.88 +/*
70.89 +** The Vdbe.aColName array contains 5n Mem structures, where n is the
70.90 +** number of columns of data returned by the statement.
70.91 +*/
70.92 +#define COLNAME_NAME 0
70.93 +#define COLNAME_DECLTYPE 1
70.94 +#define COLNAME_DATABASE 2
70.95 +#define COLNAME_TABLE 3
70.96 +#define COLNAME_COLUMN 4
70.97 +#define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
70.98 +
70.99 +/*
70.100 +** The following macro converts a relative address in the p2 field
70.101 +** of a VdbeOp structure into a negative number so that
70.102 +** sqlite3VdbeAddOpList() knows that the address is relative. Calling
70.103 +** the macro again restores the address.
70.104 +*/
70.105 +#define ADDR(X) (-1-(X))
70.106 +
70.107 +/*
70.108 +** The makefile scans the vdbe.c source file and creates the "opcodes.h"
70.109 +** header file that defines a number for each opcode used by the VDBE.
70.110 +*/
70.111 +#include "opcodes.h"
70.112 +
70.113 +/*
70.114 +** Prototypes for the VDBE interface. See comments on the implementation
70.115 +** for a description of what each of these routines does.
70.116 +*/
70.117 +Vdbe *sqlite3VdbeCreate(sqlite3*);
70.118 +int sqlite3VdbeAddOp(Vdbe*,int,int,int);
70.119 +int sqlite3VdbeOp3(Vdbe*,int,int,int,const char *zP3,int);
70.120 +int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
70.121 +void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
70.122 +void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
70.123 +void sqlite3VdbeJumpHere(Vdbe*, int addr);
70.124 +void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
70.125 +void sqlite3VdbeChangeP3(Vdbe*, int addr, const char *zP1, int N);
70.126 +VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
70.127 +int sqlite3VdbeMakeLabel(Vdbe*);
70.128 +void sqlite3VdbeDelete(Vdbe*);
70.129 +void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
70.130 +int sqlite3VdbeFinalize(Vdbe*);
70.131 +void sqlite3VdbeResolveLabel(Vdbe*, int);
70.132 +int sqlite3VdbeCurrentAddr(Vdbe*);
70.133 +#ifdef SQLITE_DEBUG
70.134 + void sqlite3VdbeTrace(Vdbe*,FILE*);
70.135 +#endif
70.136 +void sqlite3VdbeResetStepResult(Vdbe*);
70.137 +int sqlite3VdbeReset(Vdbe*);
70.138 +void sqlite3VdbeSetNumCols(Vdbe*,int);
70.139 +int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, int);
70.140 +void sqlite3VdbeCountChanges(Vdbe*);
70.141 +sqlite3 *sqlite3VdbeDb(Vdbe*);
70.142 +void sqlite3VdbeSetSql(Vdbe*, const char *z, int n);
70.143 +const char *sqlite3VdbeGetSql(Vdbe*);
70.144 +void sqlite3VdbeSwap(Vdbe*,Vdbe*);
70.145 +
70.146 +#ifndef NDEBUG
70.147 + void sqlite3VdbeComment(Vdbe*, const char*, ...);
70.148 +# define VdbeComment(X) sqlite3VdbeComment X
70.149 +#else
70.150 +# define VdbeComment(X)
70.151 +#endif
70.152 +
70.153 +#endif
71.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
71.2 +++ b/extensions/sqlite/sqlite-source/vdbeInt.h Sun Jul 29 01:15:31 2007 +0000
71.3 @@ -0,0 +1,429 @@
71.4 +/*
71.5 +** 2003 September 6
71.6 +**
71.7 +** The author disclaims copyright to this source code. In place of
71.8 +** a legal notice, here is a blessing:
71.9 +**
71.10 +** May you do good and not evil.
71.11 +** May you find forgiveness for yourself and forgive others.
71.12 +** May you share freely, never taking more than you give.
71.13 +**
71.14 +*************************************************************************
71.15 +** This is the header file for information that is private to the
71.16 +** VDBE. This information used to all be at the top of the single
71.17 +** source code file "vdbe.c". When that file became too big (over
71.18 +** 6000 lines long) it was split up into several smaller files and
71.19 +** this header information was factored out.
71.20 +*/
71.21 +#ifndef _VDBEINT_H_
71.22 +#define _VDBEINT_H_
71.23 +
71.24 +/*
71.25 +** intToKey() and keyToInt() used to transform the rowid. But with
71.26 +** the latest versions of the design they are no-ops.
71.27 +*/
71.28 +#define keyToInt(X) (X)
71.29 +#define intToKey(X) (X)
71.30 +
71.31 +/*
71.32 +** The makefile scans the vdbe.c source file and creates the following
71.33 +** array of string constants which are the names of all VDBE opcodes. This
71.34 +** array is defined in a separate source code file named opcode.c which is
71.35 +** automatically generated by the makefile.
71.36 +*/
71.37 +extern const char *const sqlite3OpcodeNames[];
71.38 +
71.39 +/*
71.40 +** SQL is translated into a sequence of instructions to be
71.41 +** executed by a virtual machine. Each instruction is an instance
71.42 +** of the following structure.
71.43 +*/
71.44 +typedef struct VdbeOp Op;
71.45 +
71.46 +/*
71.47 +** Boolean values
71.48 +*/
71.49 +typedef unsigned char Bool;
71.50 +
71.51 +/*
71.52 +** A cursor is a pointer into a single BTree within a database file.
71.53 +** The cursor can seek to a BTree entry with a particular key, or
71.54 +** loop over all entries of the Btree. You can also insert new BTree
71.55 +** entries or retrieve the key or data from the entry that the cursor
71.56 +** is currently pointing to.
71.57 +**
71.58 +** Every cursor that the virtual machine has open is represented by an
71.59 +** instance of the following structure.
71.60 +**
71.61 +** If the Cursor.isTriggerRow flag is set it means that this cursor is
71.62 +** really a single row that represents the NEW or OLD pseudo-table of
71.63 +** a row trigger. The data for the row is stored in Cursor.pData and
71.64 +** the rowid is in Cursor.iKey.
71.65 +*/
71.66 +struct Cursor {
71.67 + BtCursor *pCursor; /* The cursor structure of the backend */
71.68 + int iDb; /* Index of cursor database in db->aDb[] (or -1) */
71.69 + i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
71.70 + i64 nextRowid; /* Next rowid returned by OP_NewRowid */
71.71 + Bool zeroed; /* True if zeroed out and ready for reuse */
71.72 + Bool rowidIsValid; /* True if lastRowid is valid */
71.73 + Bool atFirst; /* True if pointing to first entry */
71.74 + Bool useRandomRowid; /* Generate new record numbers semi-randomly */
71.75 + Bool nullRow; /* True if pointing to a row with no data */
71.76 + Bool nextRowidValid; /* True if the nextRowid field is valid */
71.77 + Bool pseudoTable; /* This is a NEW or OLD pseudo-tables of a trigger */
71.78 + Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
71.79 + Bool isTable; /* True if a table requiring integer keys */
71.80 + Bool isIndex; /* True if an index containing keys only - no data */
71.81 + u8 bogusIncrKey; /* Something for pIncrKey to point to if pKeyInfo==0 */
71.82 + i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
71.83 + Btree *pBt; /* Separate file holding temporary table */
71.84 + int nData; /* Number of bytes in pData */
71.85 + char *pData; /* Data for a NEW or OLD pseudo-table */
71.86 + i64 iKey; /* Key for the NEW or OLD pseudo-table row */
71.87 + u8 *pIncrKey; /* Pointer to pKeyInfo->incrKey */
71.88 + KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
71.89 + int nField; /* Number of fields in the header */
71.90 + i64 seqCount; /* Sequence counter */
71.91 + sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
71.92 + const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
71.93 +
71.94 + /* Cached information about the header for the data record that the
71.95 + ** cursor is currently pointing to. Only valid if cacheValid is true.
71.96 + ** aRow might point to (ephemeral) data for the current row, or it might
71.97 + ** be NULL.
71.98 + */
71.99 + int cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
71.100 + int payloadSize; /* Total number of bytes in the record */
71.101 + u32 *aType; /* Type values for all entries in the record */
71.102 + u32 *aOffset; /* Cached offsets to the start of each columns data */
71.103 + u8 *aRow; /* Data for the current row, if all on one page */
71.104 +};
71.105 +typedef struct Cursor Cursor;
71.106 +
71.107 +/*
71.108 +** Number of bytes of string storage space available to each stack
71.109 +** layer without having to malloc. NBFS is short for Number of Bytes
71.110 +** For Strings.
71.111 +*/
71.112 +#define NBFS 32
71.113 +
71.114 +/*
71.115 +** A value for Cursor.cacheValid that means the cache is always invalid.
71.116 +*/
71.117 +#define CACHE_STALE 0
71.118 +
71.119 +/*
71.120 +** Internally, the vdbe manipulates nearly all SQL values as Mem
71.121 +** structures. Each Mem struct may cache multiple representations (string,
71.122 +** integer etc.) of the same value. A value (and therefore Mem structure)
71.123 +** has the following properties:
71.124 +**
71.125 +** Each value has a manifest type. The manifest type of the value stored
71.126 +** in a Mem struct is returned by the MemType(Mem*) macro. The type is
71.127 +** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
71.128 +** SQLITE_BLOB.
71.129 +*/
71.130 +struct Mem {
71.131 + union {
71.132 + i64 i; /* Integer value. Or FuncDef* when flags==MEM_Agg */
71.133 + FuncDef *pDef; /* Used only when flags==MEM_Agg */
71.134 + } u;
71.135 + double r; /* Real value */
71.136 + char *z; /* String or BLOB value */
71.137 + int n; /* Number of characters in string value, including '\0' */
71.138 + u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
71.139 + u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
71.140 + u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
71.141 + void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
71.142 + char zShort[NBFS]; /* Space for short strings */
71.143 +};
71.144 +typedef struct Mem Mem;
71.145 +
71.146 +/* One or more of the following flags are set to indicate the validOK
71.147 +** representations of the value stored in the Mem struct.
71.148 +**
71.149 +** If the MEM_Null flag is set, then the value is an SQL NULL value.
71.150 +** No other flags may be set in this case.
71.151 +**
71.152 +** If the MEM_Str flag is set then Mem.z points at a string representation.
71.153 +** Usually this is encoded in the same unicode encoding as the main
71.154 +** database (see below for exceptions). If the MEM_Term flag is also
71.155 +** set, then the string is nul terminated. The MEM_Int and MEM_Real
71.156 +** flags may coexist with the MEM_Str flag.
71.157 +**
71.158 +** Multiple of these values can appear in Mem.flags. But only one
71.159 +** at a time can appear in Mem.type.
71.160 +*/
71.161 +#define MEM_Null 0x0001 /* Value is NULL */
71.162 +#define MEM_Str 0x0002 /* Value is a string */
71.163 +#define MEM_Int 0x0004 /* Value is an integer */
71.164 +#define MEM_Real 0x0008 /* Value is a real number */
71.165 +#define MEM_Blob 0x0010 /* Value is a BLOB */
71.166 +
71.167 +/* Whenever Mem contains a valid string or blob representation, one of
71.168 +** the following flags must be set to determine the memory management
71.169 +** policy for Mem.z. The MEM_Term flag tells us whether or not the
71.170 +** string is \000 or \u0000 terminated
71.171 +*/
71.172 +#define MEM_Term 0x0020 /* String rep is nul terminated */
71.173 +#define MEM_Dyn 0x0040 /* Need to call sqliteFree() on Mem.z */
71.174 +#define MEM_Static 0x0080 /* Mem.z points to a static string */
71.175 +#define MEM_Ephem 0x0100 /* Mem.z points to an ephemeral string */
71.176 +#define MEM_Short 0x0200 /* Mem.z points to Mem.zShort */
71.177 +#define MEM_Agg 0x0400 /* Mem.z points to an agg function context */
71.178 +#define MEM_Zero 0x0800 /* Mem.i contains count of 0s appended to blob */
71.179 +
71.180 +#ifdef SQLITE_OMIT_INCRBLOB
71.181 + #undef MEM_Zero
71.182 + #define MEM_Zero 0x0000
71.183 +#endif
71.184 +
71.185 +
71.186 +/* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
71.187 +** additional information about auxiliary information bound to arguments
71.188 +** of the function. This is used to implement the sqlite3_get_auxdata()
71.189 +** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
71.190 +** that can be associated with a constant argument to a function. This
71.191 +** allows functions such as "regexp" to compile their constant regular
71.192 +** expression argument once and reused the compiled code for multiple
71.193 +** invocations.
71.194 +*/
71.195 +struct VdbeFunc {
71.196 + FuncDef *pFunc; /* The definition of the function */
71.197 + int nAux; /* Number of entries allocated for apAux[] */
71.198 + struct AuxData {
71.199 + void *pAux; /* Aux data for the i-th argument */
71.200 + void (*xDelete)(void *); /* Destructor for the aux data */
71.201 + } apAux[1]; /* One slot for each function argument */
71.202 +};
71.203 +typedef struct VdbeFunc VdbeFunc;
71.204 +
71.205 +/*
71.206 +** The "context" argument for a installable function. A pointer to an
71.207 +** instance of this structure is the first argument to the routines used
71.208 +** implement the SQL functions.
71.209 +**
71.210 +** There is a typedef for this structure in sqlite.h. So all routines,
71.211 +** even the public interface to SQLite, can use a pointer to this structure.
71.212 +** But this file is the only place where the internal details of this
71.213 +** structure are known.
71.214 +**
71.215 +** This structure is defined inside of vdbeInt.h because it uses substructures
71.216 +** (Mem) which are only defined there.
71.217 +*/
71.218 +struct sqlite3_context {
71.219 + FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
71.220 + VdbeFunc *pVdbeFunc; /* Auxilary data, if created. */
71.221 + Mem s; /* The return value is stored here */
71.222 + Mem *pMem; /* Memory cell used to store aggregate context */
71.223 + u8 isError; /* Set to true for an error */
71.224 + CollSeq *pColl; /* Collating sequence */
71.225 +};
71.226 +
71.227 +/*
71.228 +** A Set structure is used for quick testing to see if a value
71.229 +** is part of a small set. Sets are used to implement code like
71.230 +** this:
71.231 +** x.y IN ('hi','hoo','hum')
71.232 +*/
71.233 +typedef struct Set Set;
71.234 +struct Set {
71.235 + Hash hash; /* A set is just a hash table */
71.236 + HashElem *prev; /* Previously accessed hash elemen */
71.237 +};
71.238 +
71.239 +/*
71.240 +** A FifoPage structure holds a single page of valves. Pages are arranged
71.241 +** in a list.
71.242 +*/
71.243 +typedef struct FifoPage FifoPage;
71.244 +struct FifoPage {
71.245 + int nSlot; /* Number of entries aSlot[] */
71.246 + int iWrite; /* Push the next value into this entry in aSlot[] */
71.247 + int iRead; /* Read the next value from this entry in aSlot[] */
71.248 + FifoPage *pNext; /* Next page in the fifo */
71.249 + i64 aSlot[1]; /* One or more slots for rowid values */
71.250 +};
71.251 +
71.252 +/*
71.253 +** The Fifo structure is typedef-ed in vdbeInt.h. But the implementation
71.254 +** of that structure is private to this file.
71.255 +**
71.256 +** The Fifo structure describes the entire fifo.
71.257 +*/
71.258 +typedef struct Fifo Fifo;
71.259 +struct Fifo {
71.260 + int nEntry; /* Total number of entries */
71.261 + FifoPage *pFirst; /* First page on the list */
71.262 + FifoPage *pLast; /* Last page on the list */
71.263 +};
71.264 +
71.265 +/*
71.266 +** A Context stores the last insert rowid, the last statement change count,
71.267 +** and the current statement change count (i.e. changes since last statement).
71.268 +** The current keylist is also stored in the context.
71.269 +** Elements of Context structure type make up the ContextStack, which is
71.270 +** updated by the ContextPush and ContextPop opcodes (used by triggers).
71.271 +** The context is pushed before executing a trigger a popped when the
71.272 +** trigger finishes.
71.273 +*/
71.274 +typedef struct Context Context;
71.275 +struct Context {
71.276 + i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
71.277 + int nChange; /* Statement changes (Vdbe.nChanges) */
71.278 + Fifo sFifo; /* Records that will participate in a DELETE or UPDATE */
71.279 +};
71.280 +
71.281 +/*
71.282 +** An instance of the virtual machine. This structure contains the complete
71.283 +** state of the virtual machine.
71.284 +**
71.285 +** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
71.286 +** is really a pointer to an instance of this structure.
71.287 +**
71.288 +** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
71.289 +** any virtual table method invocations made by the vdbe program. It is
71.290 +** set to 2 for xDestroy method calls and 1 for all other methods. This
71.291 +** variable is used for two purposes: to allow xDestroy methods to execute
71.292 +** "DROP TABLE" statements and to prevent some nasty side effects of
71.293 +** malloc failure when SQLite is invoked recursively by a virtual table
71.294 +** method function.
71.295 +*/
71.296 +struct Vdbe {
71.297 + sqlite3 *db; /* The whole database */
71.298 + Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
71.299 + int nOp; /* Number of instructions in the program */
71.300 + int nOpAlloc; /* Number of slots allocated for aOp[] */
71.301 + Op *aOp; /* Space to hold the virtual machine's program */
71.302 + int nLabel; /* Number of labels used */
71.303 + int nLabelAlloc; /* Number of slots allocated in aLabel[] */
71.304 + int *aLabel; /* Space to hold the labels */
71.305 + Mem *aStack; /* The operand stack, except string values */
71.306 + Mem *pTos; /* Top entry in the operand stack */
71.307 + Mem **apArg; /* Arguments to currently executing user function */
71.308 + Mem *aColName; /* Column names to return */
71.309 + int nCursor; /* Number of slots in apCsr[] */
71.310 + Cursor **apCsr; /* One element of this array for each open cursor */
71.311 + int nVar; /* Number of entries in aVar[] */
71.312 + Mem *aVar; /* Values for the OP_Variable opcode. */
71.313 + char **azVar; /* Name of variables */
71.314 + int okVar; /* True if azVar[] has been initialized */
71.315 + int magic; /* Magic number for sanity checking */
71.316 + int nMem; /* Number of memory locations currently allocated */
71.317 + Mem *aMem; /* The memory locations */
71.318 + int nCallback; /* Number of callbacks invoked so far */
71.319 + int cacheCtr; /* Cursor row cache generation counter */
71.320 + Fifo sFifo; /* A list of ROWIDs */
71.321 + int contextStackTop; /* Index of top element in the context stack */
71.322 + int contextStackDepth; /* The size of the "context" stack */
71.323 + Context *contextStack; /* Stack used by opcodes ContextPush & ContextPop*/
71.324 + int pc; /* The program counter */
71.325 + int rc; /* Value to return */
71.326 + unsigned uniqueCnt; /* Used by OP_MakeRecord when P2!=0 */
71.327 + int errorAction; /* Recovery action to do in case of an error */
71.328 + int inTempTrans; /* True if temp database is transactioned */
71.329 + int returnStack[100]; /* Return address stack for OP_Gosub & OP_Return */
71.330 + int returnDepth; /* Next unused element in returnStack[] */
71.331 + int nResColumn; /* Number of columns in one row of the result set */
71.332 + char **azResColumn; /* Values for one row of result */
71.333 + int popStack; /* Pop the stack this much on entry to VdbeExec() */
71.334 + char *zErrMsg; /* Error message written here */
71.335 + u8 resOnStack; /* True if there are result values on the stack */
71.336 + u8 explain; /* True if EXPLAIN present on SQL command */
71.337 + u8 changeCntOn; /* True to update the change-counter */
71.338 + u8 aborted; /* True if ROLLBACK in another VM causes an abort */
71.339 + u8 expired; /* True if the VM needs to be recompiled */
71.340 + u8 minWriteFileFormat; /* Minimum file format for writable database files */
71.341 + u8 inVtabMethod; /* See comments above */
71.342 + int nChange; /* Number of db changes made since last reset */
71.343 + i64 startTime; /* Time when query started - used for profiling */
71.344 + int nSql; /* Number of bytes in zSql */
71.345 + char *zSql; /* Text of the SQL statement that generated this */
71.346 +#ifdef SQLITE_DEBUG
71.347 + FILE *trace; /* Write an execution trace here, if not NULL */
71.348 +#endif
71.349 + int openedStatement; /* True if this VM has opened a statement journal */
71.350 +#ifdef SQLITE_SSE
71.351 + int fetchId; /* Statement number used by sqlite3_fetch_statement */
71.352 + int lru; /* Counter used for LRU cache replacement */
71.353 +#endif
71.354 +};
71.355 +
71.356 +/*
71.357 +** The following are allowed values for Vdbe.magic
71.358 +*/
71.359 +#define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
71.360 +#define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
71.361 +#define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
71.362 +#define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
71.363 +
71.364 +/*
71.365 +** Function prototypes
71.366 +*/
71.367 +void sqlite3VdbeFreeCursor(Vdbe *, Cursor*);
71.368 +void sqliteVdbePopStack(Vdbe*,int);
71.369 +int sqlite3VdbeCursorMoveto(Cursor*);
71.370 +#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
71.371 +void sqlite3VdbePrintOp(FILE*, int, Op*);
71.372 +#endif
71.373 +int sqlite3VdbeSerialTypeLen(u32);
71.374 +u32 sqlite3VdbeSerialType(Mem*, int);
71.375 +int sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
71.376 +int sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
71.377 +void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
71.378 +
71.379 +int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
71.380 +int sqlite3VdbeIdxKeyCompare(Cursor*, int , const unsigned char*, int*);
71.381 +int sqlite3VdbeIdxRowid(BtCursor *, i64 *);
71.382 +int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
71.383 +int sqlite3VdbeRecordCompare(void*,int,const void*,int, const void*);
71.384 +int sqlite3VdbeIdxRowidLen(const u8*);
71.385 +int sqlite3VdbeExec(Vdbe*);
71.386 +int sqlite3VdbeList(Vdbe*);
71.387 +int sqlite3VdbeHalt(Vdbe*);
71.388 +int sqlite3VdbeChangeEncoding(Mem *, int);
71.389 +int sqlite3VdbeMemTooBig(Mem*);
71.390 +int sqlite3VdbeMemCopy(Mem*, const Mem*);
71.391 +void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
71.392 +int sqlite3VdbeMemMove(Mem*, Mem*);
71.393 +int sqlite3VdbeMemNulTerminate(Mem*);
71.394 +int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
71.395 +void sqlite3VdbeMemSetInt64(Mem*, i64);
71.396 +void sqlite3VdbeMemSetDouble(Mem*, double);
71.397 +void sqlite3VdbeMemSetNull(Mem*);
71.398 +void sqlite3VdbeMemSetZeroBlob(Mem*,int);
71.399 +int sqlite3VdbeMemMakeWriteable(Mem*);
71.400 +int sqlite3VdbeMemDynamicify(Mem*);
71.401 +int sqlite3VdbeMemStringify(Mem*, int);
71.402 +i64 sqlite3VdbeIntValue(Mem*);
71.403 +int sqlite3VdbeMemIntegerify(Mem*);
71.404 +double sqlite3VdbeRealValue(Mem*);
71.405 +void sqlite3VdbeIntegerAffinity(Mem*);
71.406 +int sqlite3VdbeMemRealify(Mem*);
71.407 +int sqlite3VdbeMemNumerify(Mem*);
71.408 +int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
71.409 +void sqlite3VdbeMemRelease(Mem *p);
71.410 +int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
71.411 +#ifndef NDEBUG
71.412 + void sqlite3VdbeMemSanity(Mem*);
71.413 + int sqlite3VdbeOpcodeNoPush(u8);
71.414 +#endif
71.415 +int sqlite3VdbeMemTranslate(Mem*, u8);
71.416 +#ifdef SQLITE_DEBUG
71.417 + void sqlite3VdbePrintSql(Vdbe*);
71.418 + void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
71.419 +#endif
71.420 +int sqlite3VdbeMemHandleBom(Mem *pMem);
71.421 +void sqlite3VdbeFifoInit(Fifo*);
71.422 +int sqlite3VdbeFifoPush(Fifo*, i64);
71.423 +int sqlite3VdbeFifoPop(Fifo*, i64*);
71.424 +void sqlite3VdbeFifoClear(Fifo*);
71.425 +
71.426 +#ifndef SQLITE_OMIT_INCRBLOB
71.427 + int sqlite3VdbeMemExpandBlob(Mem *);
71.428 +#else
71.429 + #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
71.430 +#endif
71.431 +
71.432 +#endif /* !defined(_VDBEINT_H_) */
72.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
72.2 +++ b/extensions/sqlite/sqlite-source/vdbeapi.c Sun Jul 29 01:15:31 2007 +0000
72.3 @@ -0,0 +1,914 @@
72.4 +/*
72.5 +** 2004 May 26
72.6 +**
72.7 +** The author disclaims copyright to this source code. In place of
72.8 +** a legal notice, here is a blessing:
72.9 +**
72.10 +** May you do good and not evil.
72.11 +** May you find forgiveness for yourself and forgive others.
72.12 +** May you share freely, never taking more than you give.
72.13 +**
72.14 +*************************************************************************
72.15 +**
72.16 +** This file contains code use to implement APIs that are part of the
72.17 +** VDBE.
72.18 +*/
72.19 +#include "sqliteInt.h"
72.20 +#include "vdbeInt.h"
72.21 +#include "os.h"
72.22 +
72.23 +/*
72.24 +** Return TRUE (non-zero) of the statement supplied as an argument needs
72.25 +** to be recompiled. A statement needs to be recompiled whenever the
72.26 +** execution environment changes in a way that would alter the program
72.27 +** that sqlite3_prepare() generates. For example, if new functions or
72.28 +** collating sequences are registered or if an authorizer function is
72.29 +** added or changed.
72.30 +*/
72.31 +int sqlite3_expired(sqlite3_stmt *pStmt){
72.32 + Vdbe *p = (Vdbe*)pStmt;
72.33 + return p==0 || p->expired;
72.34 +}
72.35 +
72.36 +/**************************** sqlite3_value_ *******************************
72.37 +** The following routines extract information from a Mem or sqlite3_value
72.38 +** structure.
72.39 +*/
72.40 +const void *sqlite3_value_blob(sqlite3_value *pVal){
72.41 + Mem *p = (Mem*)pVal;
72.42 + if( p->flags & (MEM_Blob|MEM_Str) ){
72.43 + sqlite3VdbeMemExpandBlob(p);
72.44 + p->flags &= ~MEM_Str;
72.45 + p->flags |= MEM_Blob;
72.46 + return p->z;
72.47 + }else{
72.48 + return sqlite3_value_text(pVal);
72.49 + }
72.50 +}
72.51 +int sqlite3_value_bytes(sqlite3_value *pVal){
72.52 + return sqlite3ValueBytes(pVal, SQLITE_UTF8);
72.53 +}
72.54 +int sqlite3_value_bytes16(sqlite3_value *pVal){
72.55 + return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
72.56 +}
72.57 +double sqlite3_value_double(sqlite3_value *pVal){
72.58 + return sqlite3VdbeRealValue((Mem*)pVal);
72.59 +}
72.60 +int sqlite3_value_int(sqlite3_value *pVal){
72.61 + return sqlite3VdbeIntValue((Mem*)pVal);
72.62 +}
72.63 +sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
72.64 + return sqlite3VdbeIntValue((Mem*)pVal);
72.65 +}
72.66 +const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
72.67 + return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
72.68 +}
72.69 +#ifndef SQLITE_OMIT_UTF16
72.70 +const void *sqlite3_value_text16(sqlite3_value* pVal){
72.71 + return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
72.72 +}
72.73 +const void *sqlite3_value_text16be(sqlite3_value *pVal){
72.74 + return sqlite3ValueText(pVal, SQLITE_UTF16BE);
72.75 +}
72.76 +const void *sqlite3_value_text16le(sqlite3_value *pVal){
72.77 + return sqlite3ValueText(pVal, SQLITE_UTF16LE);
72.78 +}
72.79 +#endif /* SQLITE_OMIT_UTF16 */
72.80 +int sqlite3_value_type(sqlite3_value* pVal){
72.81 + return pVal->type;
72.82 +}
72.83 +/* sqlite3_value_numeric_type() defined in vdbe.c */
72.84 +
72.85 +/**************************** sqlite3_result_ *******************************
72.86 +** The following routines are used by user-defined functions to specify
72.87 +** the function result.
72.88 +*/
72.89 +void sqlite3_result_blob(
72.90 + sqlite3_context *pCtx,
72.91 + const void *z,
72.92 + int n,
72.93 + void (*xDel)(void *)
72.94 +){
72.95 + assert( n>=0 );
72.96 + sqlite3VdbeMemSetStr(&pCtx->s, z, n, 0, xDel);
72.97 +}
72.98 +void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
72.99 + sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
72.100 +}
72.101 +void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
72.102 + pCtx->isError = 1;
72.103 + sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
72.104 +}
72.105 +#ifndef SQLITE_OMIT_UTF16
72.106 +void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
72.107 + pCtx->isError = 1;
72.108 + sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
72.109 +}
72.110 +#endif
72.111 +void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
72.112 + sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
72.113 +}
72.114 +void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
72.115 + sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
72.116 +}
72.117 +void sqlite3_result_null(sqlite3_context *pCtx){
72.118 + sqlite3VdbeMemSetNull(&pCtx->s);
72.119 +}
72.120 +void sqlite3_result_text(
72.121 + sqlite3_context *pCtx,
72.122 + const char *z,
72.123 + int n,
72.124 + void (*xDel)(void *)
72.125 +){
72.126 + sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, xDel);
72.127 +}
72.128 +#ifndef SQLITE_OMIT_UTF16
72.129 +void sqlite3_result_text16(
72.130 + sqlite3_context *pCtx,
72.131 + const void *z,
72.132 + int n,
72.133 + void (*xDel)(void *)
72.134 +){
72.135 + sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, xDel);
72.136 +}
72.137 +void sqlite3_result_text16be(
72.138 + sqlite3_context *pCtx,
72.139 + const void *z,
72.140 + int n,
72.141 + void (*xDel)(void *)
72.142 +){
72.143 + sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16BE, xDel);
72.144 +}
72.145 +void sqlite3_result_text16le(
72.146 + sqlite3_context *pCtx,
72.147 + const void *z,
72.148 + int n,
72.149 + void (*xDel)(void *)
72.150 +){
72.151 + sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16LE, xDel);
72.152 +}
72.153 +#endif /* SQLITE_OMIT_UTF16 */
72.154 +void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
72.155 + sqlite3VdbeMemCopy(&pCtx->s, pValue);
72.156 +}
72.157 +void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
72.158 + sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
72.159 +}
72.160 +
72.161 +/* Force an SQLITE_TOOBIG error. */
72.162 +void sqlite3_result_error_toobig(sqlite3_context *pCtx){
72.163 + sqlite3VdbeMemSetZeroBlob(&pCtx->s, SQLITE_MAX_LENGTH+1);
72.164 +}
72.165 +
72.166 +
72.167 +/*
72.168 +** Execute the statement pStmt, either until a row of data is ready, the
72.169 +** statement is completely executed or an error occurs.
72.170 +**
72.171 +** This routine implements the bulk of the logic behind the sqlite_step()
72.172 +** API. The only thing omitted is the automatic recompile if a
72.173 +** schema change has occurred. That detail is handled by the
72.174 +** outer sqlite3_step() wrapper procedure.
72.175 +*/
72.176 +static int sqlite3Step(Vdbe *p){
72.177 + sqlite3 *db;
72.178 + int rc;
72.179 +
72.180 + /* Assert that malloc() has not failed */
72.181 + assert( !sqlite3MallocFailed() );
72.182 +
72.183 + if( p==0 || p->magic!=VDBE_MAGIC_RUN ){
72.184 + return SQLITE_MISUSE;
72.185 + }
72.186 + if( p->aborted ){
72.187 + return SQLITE_ABORT;
72.188 + }
72.189 + if( p->pc<=0 && p->expired ){
72.190 + if( p->rc==SQLITE_OK ){
72.191 + p->rc = SQLITE_SCHEMA;
72.192 + }
72.193 + rc = SQLITE_ERROR;
72.194 + goto end_of_step;
72.195 + }
72.196 + db = p->db;
72.197 + if( sqlite3SafetyOn(db) ){
72.198 + p->rc = SQLITE_MISUSE;
72.199 + return SQLITE_MISUSE;
72.200 + }
72.201 + if( p->pc<0 ){
72.202 + /* If there are no other statements currently running, then
72.203 + ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
72.204 + ** from interrupting a statement that has not yet started.
72.205 + */
72.206 + if( db->activeVdbeCnt==0 ){
72.207 + db->u1.isInterrupted = 0;
72.208 + }
72.209 +
72.210 +#ifndef SQLITE_OMIT_TRACE
72.211 + /* Invoke the trace callback if there is one
72.212 + */
72.213 + if( db->xTrace && !db->init.busy ){
72.214 + assert( p->nOp>0 );
72.215 + assert( p->aOp[p->nOp-1].opcode==OP_Noop );
72.216 + assert( p->aOp[p->nOp-1].p3!=0 );
72.217 + assert( p->aOp[p->nOp-1].p3type==P3_DYNAMIC );
72.218 + sqlite3SafetyOff(db);
72.219 + db->xTrace(db->pTraceArg, p->aOp[p->nOp-1].p3);
72.220 + if( sqlite3SafetyOn(db) ){
72.221 + p->rc = SQLITE_MISUSE;
72.222 + return SQLITE_MISUSE;
72.223 + }
72.224 + }
72.225 + if( db->xProfile && !db->init.busy ){
72.226 + double rNow;
72.227 + sqlite3OsCurrentTime(&rNow);
72.228 + p->startTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0;
72.229 + }
72.230 +#endif
72.231 +
72.232 + /* Print a copy of SQL as it is executed if the SQL_TRACE pragma is turned
72.233 + ** on in debugging mode.
72.234 + */
72.235 +#ifdef SQLITE_DEBUG
72.236 + if( (db->flags & SQLITE_SqlTrace)!=0 ){
72.237 + sqlite3DebugPrintf("SQL-trace: %s\n", p->aOp[p->nOp-1].p3);
72.238 + }
72.239 +#endif /* SQLITE_DEBUG */
72.240 +
72.241 + db->activeVdbeCnt++;
72.242 + p->pc = 0;
72.243 + }
72.244 +#ifndef SQLITE_OMIT_EXPLAIN
72.245 + if( p->explain ){
72.246 + rc = sqlite3VdbeList(p);
72.247 + }else
72.248 +#endif /* SQLITE_OMIT_EXPLAIN */
72.249 + {
72.250 + rc = sqlite3VdbeExec(p);
72.251 + }
72.252 +
72.253 + if( sqlite3SafetyOff(db) ){
72.254 + rc = SQLITE_MISUSE;
72.255 + }
72.256 +
72.257 +#ifndef SQLITE_OMIT_TRACE
72.258 + /* Invoke the profile callback if there is one
72.259 + */
72.260 + if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy ){
72.261 + double rNow;
72.262 + u64 elapseTime;
72.263 +
72.264 + sqlite3OsCurrentTime(&rNow);
72.265 + elapseTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0 - p->startTime;
72.266 + assert( p->nOp>0 );
72.267 + assert( p->aOp[p->nOp-1].opcode==OP_Noop );
72.268 + assert( p->aOp[p->nOp-1].p3!=0 );
72.269 + assert( p->aOp[p->nOp-1].p3type==P3_DYNAMIC );
72.270 + db->xProfile(db->pProfileArg, p->aOp[p->nOp-1].p3, elapseTime);
72.271 + }
72.272 +#endif
72.273 +
72.274 + sqlite3Error(p->db, rc, 0);
72.275 + p->rc = sqlite3ApiExit(p->db, p->rc);
72.276 +end_of_step:
72.277 + assert( (rc&0xff)==rc );
72.278 + if( p->zSql && (rc&0xff)<SQLITE_ROW ){
72.279 + /* This behavior occurs if sqlite3_prepare_v2() was used to build
72.280 + ** the prepared statement. Return error codes directly */
72.281 + sqlite3Error(p->db, p->rc, 0);
72.282 + return p->rc;
72.283 + }else{
72.284 + /* This is for legacy sqlite3_prepare() builds and when the code
72.285 + ** is SQLITE_ROW or SQLITE_DONE */
72.286 + return rc;
72.287 + }
72.288 +}
72.289 +
72.290 +/*
72.291 +** This is the top-level implementation of sqlite3_step(). Call
72.292 +** sqlite3Step() to do most of the work. If a schema error occurs,
72.293 +** call sqlite3Reprepare() and try again.
72.294 +*/
72.295 +#ifdef SQLITE_OMIT_PARSER
72.296 +int sqlite3_step(sqlite3_stmt *pStmt){
72.297 + return sqlite3Step((Vdbe*)pStmt);
72.298 +}
72.299 +#else
72.300 +int sqlite3_step(sqlite3_stmt *pStmt){
72.301 + int cnt = 0;
72.302 + int rc;
72.303 + Vdbe *v = (Vdbe*)pStmt;
72.304 + while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
72.305 + && cnt++ < 5
72.306 + && sqlite3Reprepare(v) ){
72.307 + sqlite3_reset(pStmt);
72.308 + v->expired = 0;
72.309 + }
72.310 + return rc;
72.311 +}
72.312 +#endif
72.313 +
72.314 +/*
72.315 +** Extract the user data from a sqlite3_context structure and return a
72.316 +** pointer to it.
72.317 +*/
72.318 +void *sqlite3_user_data(sqlite3_context *p){
72.319 + assert( p && p->pFunc );
72.320 + return p->pFunc->pUserData;
72.321 +}
72.322 +
72.323 +/*
72.324 +** The following is the implementation of an SQL function that always
72.325 +** fails with an error message stating that the function is used in the
72.326 +** wrong context. The sqlite3_overload_function() API might construct
72.327 +** SQL function that use this routine so that the functions will exist
72.328 +** for name resolution but are actually overloaded by the xFindFunction
72.329 +** method of virtual tables.
72.330 +*/
72.331 +void sqlite3InvalidFunction(
72.332 + sqlite3_context *context, /* The function calling context */
72.333 + int argc, /* Number of arguments to the function */
72.334 + sqlite3_value **argv /* Value of each argument */
72.335 +){
72.336 + const char *zName = context->pFunc->zName;
72.337 + char *zErr;
72.338 + zErr = sqlite3MPrintf(
72.339 + "unable to use function %s in the requested context", zName);
72.340 + sqlite3_result_error(context, zErr, -1);
72.341 + sqliteFree(zErr);
72.342 +}
72.343 +
72.344 +/*
72.345 +** Allocate or return the aggregate context for a user function. A new
72.346 +** context is allocated on the first call. Subsequent calls return the
72.347 +** same context that was returned on prior calls.
72.348 +*/
72.349 +void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
72.350 + Mem *pMem = p->pMem;
72.351 + assert( p && p->pFunc && p->pFunc->xStep );
72.352 + if( (pMem->flags & MEM_Agg)==0 ){
72.353 + if( nByte==0 ){
72.354 + assert( pMem->flags==MEM_Null );
72.355 + pMem->z = 0;
72.356 + }else{
72.357 + pMem->flags = MEM_Agg;
72.358 + pMem->xDel = sqlite3FreeX;
72.359 + pMem->u.pDef = p->pFunc;
72.360 + if( nByte<=NBFS ){
72.361 + pMem->z = pMem->zShort;
72.362 + memset(pMem->z, 0, nByte);
72.363 + }else{
72.364 + pMem->z = sqliteMalloc( nByte );
72.365 + }
72.366 + }
72.367 + }
72.368 + return (void*)pMem->z;
72.369 +}
72.370 +
72.371 +/*
72.372 +** Return the auxilary data pointer, if any, for the iArg'th argument to
72.373 +** the user-function defined by pCtx.
72.374 +*/
72.375 +void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
72.376 + VdbeFunc *pVdbeFunc = pCtx->pVdbeFunc;
72.377 + if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
72.378 + return 0;
72.379 + }
72.380 + return pVdbeFunc->apAux[iArg].pAux;
72.381 +}
72.382 +
72.383 +/*
72.384 +** Set the auxilary data pointer and delete function, for the iArg'th
72.385 +** argument to the user-function defined by pCtx. Any previous value is
72.386 +** deleted by calling the delete function specified when it was set.
72.387 +*/
72.388 +void sqlite3_set_auxdata(
72.389 + sqlite3_context *pCtx,
72.390 + int iArg,
72.391 + void *pAux,
72.392 + void (*xDelete)(void*)
72.393 +){
72.394 + struct AuxData *pAuxData;
72.395 + VdbeFunc *pVdbeFunc;
72.396 + if( iArg<0 ) return;
72.397 +
72.398 + pVdbeFunc = pCtx->pVdbeFunc;
72.399 + if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
72.400 + int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
72.401 + pVdbeFunc = sqliteRealloc(pVdbeFunc, nMalloc);
72.402 + if( !pVdbeFunc ) return;
72.403 + pCtx->pVdbeFunc = pVdbeFunc;
72.404 + memset(&pVdbeFunc->apAux[pVdbeFunc->nAux], 0,
72.405 + sizeof(struct AuxData)*(iArg+1-pVdbeFunc->nAux));
72.406 + pVdbeFunc->nAux = iArg+1;
72.407 + pVdbeFunc->pFunc = pCtx->pFunc;
72.408 + }
72.409 +
72.410 + pAuxData = &pVdbeFunc->apAux[iArg];
72.411 + if( pAuxData->pAux && pAuxData->xDelete ){
72.412 + pAuxData->xDelete(pAuxData->pAux);
72.413 + }
72.414 + pAuxData->pAux = pAux;
72.415 + pAuxData->xDelete = xDelete;
72.416 +}
72.417 +
72.418 +/*
72.419 +** Return the number of times the Step function of a aggregate has been
72.420 +** called.
72.421 +**
72.422 +** This function is deprecated. Do not use it for new code. It is
72.423 +** provide only to avoid breaking legacy code. New aggregate function
72.424 +** implementations should keep their own counts within their aggregate
72.425 +** context.
72.426 +*/
72.427 +int sqlite3_aggregate_count(sqlite3_context *p){
72.428 + assert( p && p->pFunc && p->pFunc->xStep );
72.429 + return p->pMem->n;
72.430 +}
72.431 +
72.432 +/*
72.433 +** Return the number of columns in the result set for the statement pStmt.
72.434 +*/
72.435 +int sqlite3_column_count(sqlite3_stmt *pStmt){
72.436 + Vdbe *pVm = (Vdbe *)pStmt;
72.437 + return pVm ? pVm->nResColumn : 0;
72.438 +}
72.439 +
72.440 +/*
72.441 +** Return the number of values available from the current row of the
72.442 +** currently executing statement pStmt.
72.443 +*/
72.444 +int sqlite3_data_count(sqlite3_stmt *pStmt){
72.445 + Vdbe *pVm = (Vdbe *)pStmt;
72.446 + if( pVm==0 || !pVm->resOnStack ) return 0;
72.447 + return pVm->nResColumn;
72.448 +}
72.449 +
72.450 +
72.451 +/*
72.452 +** Check to see if column iCol of the given statement is valid. If
72.453 +** it is, return a pointer to the Mem for the value of that column.
72.454 +** If iCol is not valid, return a pointer to a Mem which has a value
72.455 +** of NULL.
72.456 +*/
72.457 +static Mem *columnMem(sqlite3_stmt *pStmt, int i){
72.458 + Vdbe *pVm = (Vdbe *)pStmt;
72.459 + int vals = sqlite3_data_count(pStmt);
72.460 + if( pVm==0 || pVm->resOnStack==0 || i>=pVm->nResColumn || i<0 ){
72.461 + static const Mem nullMem = {{0}, 0.0, "", 0, MEM_Null, SQLITE_NULL };
72.462 + sqlite3Error(pVm->db, SQLITE_RANGE, 0);
72.463 + return (Mem*)&nullMem;
72.464 + }
72.465 + return &pVm->pTos[(1-vals)+i];
72.466 +}
72.467 +
72.468 +/*
72.469 +** This function is called after invoking an sqlite3_value_XXX function on a
72.470 +** column value (i.e. a value returned by evaluating an SQL expression in the
72.471 +** select list of a SELECT statement) that may cause a malloc() failure. If
72.472 +** malloc() has failed, the threads mallocFailed flag is cleared and the result
72.473 +** code of statement pStmt set to SQLITE_NOMEM.
72.474 +**
72.475 +** Specificly, this is called from within:
72.476 +**
72.477 +** sqlite3_column_int()
72.478 +** sqlite3_column_int64()
72.479 +** sqlite3_column_text()
72.480 +** sqlite3_column_text16()
72.481 +** sqlite3_column_real()
72.482 +** sqlite3_column_bytes()
72.483 +** sqlite3_column_bytes16()
72.484 +**
72.485 +** But not for sqlite3_column_blob(), which never calls malloc().
72.486 +*/
72.487 +static void columnMallocFailure(sqlite3_stmt *pStmt)
72.488 +{
72.489 + /* If malloc() failed during an encoding conversion within an
72.490 + ** sqlite3_column_XXX API, then set the return code of the statement to
72.491 + ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
72.492 + ** and _finalize() will return NOMEM.
72.493 + */
72.494 + Vdbe *p = (Vdbe *)pStmt;
72.495 + p->rc = sqlite3ApiExit(0, p->rc);
72.496 +}
72.497 +
72.498 +/**************************** sqlite3_column_ *******************************
72.499 +** The following routines are used to access elements of the current row
72.500 +** in the result set.
72.501 +*/
72.502 +const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
72.503 + const void *val;
72.504 + val = sqlite3_value_blob( columnMem(pStmt,i) );
72.505 + /* Even though there is no encoding conversion, value_blob() might
72.506 + ** need to call malloc() to expand the result of a zeroblob()
72.507 + ** expression.
72.508 + */
72.509 + columnMallocFailure(pStmt);
72.510 + return val;
72.511 +}
72.512 +int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
72.513 + int val = sqlite3_value_bytes( columnMem(pStmt,i) );
72.514 + columnMallocFailure(pStmt);
72.515 + return val;
72.516 +}
72.517 +int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
72.518 + int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
72.519 + columnMallocFailure(pStmt);
72.520 + return val;
72.521 +}
72.522 +double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
72.523 + double val = sqlite3_value_double( columnMem(pStmt,i) );
72.524 + columnMallocFailure(pStmt);
72.525 + return val;
72.526 +}
72.527 +int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
72.528 + int val = sqlite3_value_int( columnMem(pStmt,i) );
72.529 + columnMallocFailure(pStmt);
72.530 + return val;
72.531 +}
72.532 +sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
72.533 + sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
72.534 + columnMallocFailure(pStmt);
72.535 + return val;
72.536 +}
72.537 +const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
72.538 + const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
72.539 + columnMallocFailure(pStmt);
72.540 + return val;
72.541 +}
72.542 +sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
72.543 + return columnMem(pStmt, i);
72.544 +}
72.545 +#ifndef SQLITE_OMIT_UTF16
72.546 +const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
72.547 + const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
72.548 + columnMallocFailure(pStmt);
72.549 + return val;
72.550 +}
72.551 +#endif /* SQLITE_OMIT_UTF16 */
72.552 +int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
72.553 + return sqlite3_value_type( columnMem(pStmt,i) );
72.554 +}
72.555 +
72.556 +/* The following function is experimental and subject to change or
72.557 +** removal */
72.558 +/*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
72.559 +** return sqlite3_value_numeric_type( columnMem(pStmt,i) );
72.560 +**}
72.561 +*/
72.562 +
72.563 +/*
72.564 +** Convert the N-th element of pStmt->pColName[] into a string using
72.565 +** xFunc() then return that string. If N is out of range, return 0.
72.566 +**
72.567 +** There are up to 5 names for each column. useType determines which
72.568 +** name is returned. Here are the names:
72.569 +**
72.570 +** 0 The column name as it should be displayed for output
72.571 +** 1 The datatype name for the column
72.572 +** 2 The name of the database that the column derives from
72.573 +** 3 The name of the table that the column derives from
72.574 +** 4 The name of the table column that the result column derives from
72.575 +**
72.576 +** If the result is not a simple column reference (if it is an expression
72.577 +** or a constant) then useTypes 2, 3, and 4 return NULL.
72.578 +*/
72.579 +static const void *columnName(
72.580 + sqlite3_stmt *pStmt,
72.581 + int N,
72.582 + const void *(*xFunc)(Mem*),
72.583 + int useType
72.584 +){
72.585 + const void *ret;
72.586 + Vdbe *p = (Vdbe *)pStmt;
72.587 + int n = sqlite3_column_count(pStmt);
72.588 +
72.589 + if( p==0 || N>=n || N<0 ){
72.590 + return 0;
72.591 + }
72.592 + N += useType*n;
72.593 + ret = xFunc(&p->aColName[N]);
72.594 +
72.595 + /* A malloc may have failed inside of the xFunc() call. If this is the case,
72.596 + ** clear the mallocFailed flag and return NULL.
72.597 + */
72.598 + sqlite3ApiExit(0, 0);
72.599 + return ret;
72.600 +}
72.601 +
72.602 +/*
72.603 +** Return the name of the Nth column of the result set returned by SQL
72.604 +** statement pStmt.
72.605 +*/
72.606 +const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
72.607 + return columnName(
72.608 + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
72.609 +}
72.610 +#ifndef SQLITE_OMIT_UTF16
72.611 +const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
72.612 + return columnName(
72.613 + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
72.614 +}
72.615 +#endif
72.616 +
72.617 +/*
72.618 +** Return the column declaration type (if applicable) of the 'i'th column
72.619 +** of the result set of SQL statement pStmt.
72.620 +*/
72.621 +const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
72.622 + return columnName(
72.623 + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
72.624 +}
72.625 +#ifndef SQLITE_OMIT_UTF16
72.626 +const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
72.627 + return columnName(
72.628 + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
72.629 +}
72.630 +#endif /* SQLITE_OMIT_UTF16 */
72.631 +
72.632 +#ifdef SQLITE_ENABLE_COLUMN_METADATA
72.633 +/*
72.634 +** Return the name of the database from which a result column derives.
72.635 +** NULL is returned if the result column is an expression or constant or
72.636 +** anything else which is not an unabiguous reference to a database column.
72.637 +*/
72.638 +const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
72.639 + return columnName(
72.640 + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
72.641 +}
72.642 +#ifndef SQLITE_OMIT_UTF16
72.643 +const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
72.644 + return columnName(
72.645 + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
72.646 +}
72.647 +#endif /* SQLITE_OMIT_UTF16 */
72.648 +
72.649 +/*
72.650 +** Return the name of the table from which a result column derives.
72.651 +** NULL is returned if the result column is an expression or constant or
72.652 +** anything else which is not an unabiguous reference to a database column.
72.653 +*/
72.654 +const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
72.655 + return columnName(
72.656 + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
72.657 +}
72.658 +#ifndef SQLITE_OMIT_UTF16
72.659 +const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
72.660 + return columnName(
72.661 + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
72.662 +}
72.663 +#endif /* SQLITE_OMIT_UTF16 */
72.664 +
72.665 +/*
72.666 +** Return the name of the table column from which a result column derives.
72.667 +** NULL is returned if the result column is an expression or constant or
72.668 +** anything else which is not an unabiguous reference to a database column.
72.669 +*/
72.670 +const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
72.671 + return columnName(
72.672 + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
72.673 +}
72.674 +#ifndef SQLITE_OMIT_UTF16
72.675 +const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
72.676 + return columnName(
72.677 + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
72.678 +}
72.679 +#endif /* SQLITE_OMIT_UTF16 */
72.680 +#endif /* SQLITE_ENABLE_COLUMN_METADATA */
72.681 +
72.682 +
72.683 +/******************************* sqlite3_bind_ ***************************
72.684 +**
72.685 +** Routines used to attach values to wildcards in a compiled SQL statement.
72.686 +*/
72.687 +/*
72.688 +** Unbind the value bound to variable i in virtual machine p. This is the
72.689 +** the same as binding a NULL value to the column. If the "i" parameter is
72.690 +** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
72.691 +**
72.692 +** The error code stored in database p->db is overwritten with the return
72.693 +** value in any case.
72.694 +*/
72.695 +static int vdbeUnbind(Vdbe *p, int i){
72.696 + Mem *pVar;
72.697 + if( p==0 || p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
72.698 + if( p ) sqlite3Error(p->db, SQLITE_MISUSE, 0);
72.699 + return SQLITE_MISUSE;
72.700 + }
72.701 + if( i<1 || i>p->nVar ){
72.702 + sqlite3Error(p->db, SQLITE_RANGE, 0);
72.703 + return SQLITE_RANGE;
72.704 + }
72.705 + i--;
72.706 + pVar = &p->aVar[i];
72.707 + sqlite3VdbeMemRelease(pVar);
72.708 + pVar->flags = MEM_Null;
72.709 + sqlite3Error(p->db, SQLITE_OK, 0);
72.710 + return SQLITE_OK;
72.711 +}
72.712 +
72.713 +/*
72.714 +** Bind a text or BLOB value.
72.715 +*/
72.716 +static int bindText(
72.717 + sqlite3_stmt *pStmt,
72.718 + int i,
72.719 + const void *zData,
72.720 + int nData,
72.721 + void (*xDel)(void*),
72.722 + int encoding
72.723 +){
72.724 + Vdbe *p = (Vdbe *)pStmt;
72.725 + Mem *pVar;
72.726 + int rc;
72.727 +
72.728 + rc = vdbeUnbind(p, i);
72.729 + if( rc || zData==0 ){
72.730 + return rc;
72.731 + }
72.732 + pVar = &p->aVar[i-1];
72.733 + rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
72.734 + if( rc==SQLITE_OK && encoding!=0 ){
72.735 + rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
72.736 + }
72.737 +
72.738 + sqlite3Error(((Vdbe *)pStmt)->db, rc, 0);
72.739 + return sqlite3ApiExit(((Vdbe *)pStmt)->db, rc);
72.740 +}
72.741 +
72.742 +
72.743 +/*
72.744 +** Bind a blob value to an SQL statement variable.
72.745 +*/
72.746 +int sqlite3_bind_blob(
72.747 + sqlite3_stmt *pStmt,
72.748 + int i,
72.749 + const void *zData,
72.750 + int nData,
72.751 + void (*xDel)(void*)
72.752 +){
72.753 + return bindText(pStmt, i, zData, nData, xDel, 0);
72.754 +}
72.755 +int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
72.756 + int rc;
72.757 + Vdbe *p = (Vdbe *)pStmt;
72.758 + rc = vdbeUnbind(p, i);
72.759 + if( rc==SQLITE_OK ){
72.760 + sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
72.761 + }
72.762 + return rc;
72.763 +}
72.764 +int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
72.765 + return sqlite3_bind_int64(p, i, (i64)iValue);
72.766 +}
72.767 +int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
72.768 + int rc;
72.769 + Vdbe *p = (Vdbe *)pStmt;
72.770 + rc = vdbeUnbind(p, i);
72.771 + if( rc==SQLITE_OK ){
72.772 + sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
72.773 + }
72.774 + return rc;
72.775 +}
72.776 +int sqlite3_bind_null(sqlite3_stmt* p, int i){
72.777 + return vdbeUnbind((Vdbe *)p, i);
72.778 +}
72.779 +int sqlite3_bind_text(
72.780 + sqlite3_stmt *pStmt,
72.781 + int i,
72.782 + const char *zData,
72.783 + int nData,
72.784 + void (*xDel)(void*)
72.785 +){
72.786 + return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
72.787 +}
72.788 +#ifndef SQLITE_OMIT_UTF16
72.789 +int sqlite3_bind_text16(
72.790 + sqlite3_stmt *pStmt,
72.791 + int i,
72.792 + const void *zData,
72.793 + int nData,
72.794 + void (*xDel)(void*)
72.795 +){
72.796 + return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
72.797 +}
72.798 +#endif /* SQLITE_OMIT_UTF16 */
72.799 +int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
72.800 + int rc;
72.801 + Vdbe *p = (Vdbe *)pStmt;
72.802 + rc = vdbeUnbind(p, i);
72.803 + if( rc==SQLITE_OK ){
72.804 + sqlite3VdbeMemCopy(&p->aVar[i-1], pValue);
72.805 + }
72.806 + return rc;
72.807 +}
72.808 +int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
72.809 + int rc;
72.810 + Vdbe *p = (Vdbe *)pStmt;
72.811 + rc = vdbeUnbind(p, i);
72.812 + if( rc==SQLITE_OK ){
72.813 + sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
72.814 + }
72.815 + return rc;
72.816 +}
72.817 +
72.818 +/*
72.819 +** Return the number of wildcards that can be potentially bound to.
72.820 +** This routine is added to support DBD::SQLite.
72.821 +*/
72.822 +int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
72.823 + Vdbe *p = (Vdbe*)pStmt;
72.824 + return p ? p->nVar : 0;
72.825 +}
72.826 +
72.827 +/*
72.828 +** Create a mapping from variable numbers to variable names
72.829 +** in the Vdbe.azVar[] array, if such a mapping does not already
72.830 +** exist.
72.831 +*/
72.832 +static void createVarMap(Vdbe *p){
72.833 + if( !p->okVar ){
72.834 + int j;
72.835 + Op *pOp;
72.836 + for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
72.837 + if( pOp->opcode==OP_Variable ){
72.838 + assert( pOp->p1>0 && pOp->p1<=p->nVar );
72.839 + p->azVar[pOp->p1-1] = pOp->p3;
72.840 + }
72.841 + }
72.842 + p->okVar = 1;
72.843 + }
72.844 +}
72.845 +
72.846 +/*
72.847 +** Return the name of a wildcard parameter. Return NULL if the index
72.848 +** is out of range or if the wildcard is unnamed.
72.849 +**
72.850 +** The result is always UTF-8.
72.851 +*/
72.852 +const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
72.853 + Vdbe *p = (Vdbe*)pStmt;
72.854 + if( p==0 || i<1 || i>p->nVar ){
72.855 + return 0;
72.856 + }
72.857 + createVarMap(p);
72.858 + return p->azVar[i-1];
72.859 +}
72.860 +
72.861 +/*
72.862 +** Given a wildcard parameter name, return the index of the variable
72.863 +** with that name. If there is no variable with the given name,
72.864 +** return 0.
72.865 +*/
72.866 +int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
72.867 + Vdbe *p = (Vdbe*)pStmt;
72.868 + int i;
72.869 + if( p==0 ){
72.870 + return 0;
72.871 + }
72.872 + createVarMap(p);
72.873 + if( zName ){
72.874 + for(i=0; i<p->nVar; i++){
72.875 + const char *z = p->azVar[i];
72.876 + if( z && strcmp(z,zName)==0 ){
72.877 + return i+1;
72.878 + }
72.879 + }
72.880 + }
72.881 + return 0;
72.882 +}
72.883 +
72.884 +/*
72.885 +** Transfer all bindings from the first statement over to the second.
72.886 +** If the two statements contain a different number of bindings, then
72.887 +** an SQLITE_ERROR is returned.
72.888 +*/
72.889 +int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
72.890 + Vdbe *pFrom = (Vdbe*)pFromStmt;
72.891 + Vdbe *pTo = (Vdbe*)pToStmt;
72.892 + int i, rc = SQLITE_OK;
72.893 + if( (pFrom->magic!=VDBE_MAGIC_RUN && pFrom->magic!=VDBE_MAGIC_HALT)
72.894 + || (pTo->magic!=VDBE_MAGIC_RUN && pTo->magic!=VDBE_MAGIC_HALT) ){
72.895 + return SQLITE_MISUSE;
72.896 + }
72.897 + if( pFrom->nVar!=pTo->nVar ){
72.898 + return SQLITE_ERROR;
72.899 + }
72.900 + for(i=0; rc==SQLITE_OK && i<pFrom->nVar; i++){
72.901 + sqlite3MallocDisallow();
72.902 + rc = sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
72.903 + sqlite3MallocAllow();
72.904 + }
72.905 + assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
72.906 + return rc;
72.907 +}
72.908 +
72.909 +/*
72.910 +** Return the sqlite3* database handle to which the prepared statement given
72.911 +** in the argument belongs. This is the same database handle that was
72.912 +** the first argument to the sqlite3_prepare() that was used to create
72.913 +** the statement in the first place.
72.914 +*/
72.915 +sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
72.916 + return pStmt ? ((Vdbe*)pStmt)->db : 0;
72.917 +}
73.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
73.2 +++ b/extensions/sqlite/sqlite-source/vdbeaux.c Sun Jul 29 01:15:31 2007 +0000
73.3 @@ -0,0 +1,2215 @@
73.4 +/*
73.5 +** 2003 September 6
73.6 +**
73.7 +** The author disclaims copyright to this source code. In place of
73.8 +** a legal notice, here is a blessing:
73.9 +**
73.10 +** May you do good and not evil.
73.11 +** May you find forgiveness for yourself and forgive others.
73.12 +** May you share freely, never taking more than you give.
73.13 +**
73.14 +*************************************************************************
73.15 +** This file contains code used for creating, destroying, and populating
73.16 +** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
73.17 +** to version 2.8.7, all this code was combined into the vdbe.c source file.
73.18 +** But that file was getting too big so this subroutines were split out.
73.19 +*/
73.20 +#include "sqliteInt.h"
73.21 +#include "os.h"
73.22 +#include <ctype.h>
73.23 +#include "vdbeInt.h"
73.24 +
73.25 +
73.26 +/*
73.27 +** When debugging the code generator in a symbolic debugger, one can
73.28 +** set the sqlite3_vdbe_addop_trace to 1 and all opcodes will be printed
73.29 +** as they are added to the instruction stream.
73.30 +*/
73.31 +#ifdef SQLITE_DEBUG
73.32 +int sqlite3_vdbe_addop_trace = 0;
73.33 +#endif
73.34 +
73.35 +
73.36 +/*
73.37 +** Create a new virtual database engine.
73.38 +*/
73.39 +Vdbe *sqlite3VdbeCreate(sqlite3 *db){
73.40 + Vdbe *p;
73.41 + p = sqliteMalloc( sizeof(Vdbe) );
73.42 + if( p==0 ) return 0;
73.43 + p->db = db;
73.44 + if( db->pVdbe ){
73.45 + db->pVdbe->pPrev = p;
73.46 + }
73.47 + p->pNext = db->pVdbe;
73.48 + p->pPrev = 0;
73.49 + db->pVdbe = p;
73.50 + p->magic = VDBE_MAGIC_INIT;
73.51 + return p;
73.52 +}
73.53 +
73.54 +/*
73.55 +** Remember the SQL string for a prepared statement.
73.56 +*/
73.57 +void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
73.58 + if( p==0 ) return;
73.59 + assert( p->zSql==0 );
73.60 + p->zSql = sqlite3StrNDup(z, n);
73.61 +}
73.62 +
73.63 +/*
73.64 +** Return the SQL associated with a prepared statement
73.65 +*/
73.66 +const char *sqlite3VdbeGetSql(Vdbe *p){
73.67 + return p->zSql;
73.68 +}
73.69 +
73.70 +/*
73.71 +** Swap all content between two VDBE structures.
73.72 +*/
73.73 +void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
73.74 + Vdbe tmp, *pTmp;
73.75 + char *zTmp;
73.76 + int nTmp;
73.77 + tmp = *pA;
73.78 + *pA = *pB;
73.79 + *pB = tmp;
73.80 + pTmp = pA->pNext;
73.81 + pA->pNext = pB->pNext;
73.82 + pB->pNext = pTmp;
73.83 + pTmp = pA->pPrev;
73.84 + pA->pPrev = pB->pPrev;
73.85 + pB->pPrev = pTmp;
73.86 + zTmp = pA->zSql;
73.87 + pA->zSql = pB->zSql;
73.88 + pB->zSql = zTmp;
73.89 + nTmp = pA->nSql;
73.90 + pA->nSql = pB->nSql;
73.91 + pB->nSql = nTmp;
73.92 +}
73.93 +
73.94 +#ifdef SQLITE_DEBUG
73.95 +/*
73.96 +** Turn tracing on or off
73.97 +*/
73.98 +void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
73.99 + p->trace = trace;
73.100 +}
73.101 +#endif
73.102 +
73.103 +/*
73.104 +** Resize the Vdbe.aOp array so that it contains at least N
73.105 +** elements. If the Vdbe is in VDBE_MAGIC_RUN state, then
73.106 +** the Vdbe.aOp array will be sized to contain exactly N
73.107 +** elements. Vdbe.nOpAlloc is set to reflect the new size of
73.108 +** the array.
73.109 +**
73.110 +** If an out-of-memory error occurs while resizing the array,
73.111 +** Vdbe.aOp and Vdbe.nOpAlloc remain unchanged (this is so that
73.112 +** any opcodes already allocated can be correctly deallocated
73.113 +** along with the rest of the Vdbe).
73.114 +*/
73.115 +static void resizeOpArray(Vdbe *p, int N){
73.116 + int runMode = p->magic==VDBE_MAGIC_RUN;
73.117 + if( runMode || p->nOpAlloc<N ){
73.118 + VdbeOp *pNew;
73.119 + int nNew = N + 100*(!runMode);
73.120 + int oldSize = p->nOpAlloc;
73.121 + pNew = sqliteRealloc(p->aOp, nNew*sizeof(Op));
73.122 + if( pNew ){
73.123 + p->nOpAlloc = nNew;
73.124 + p->aOp = pNew;
73.125 + if( nNew>oldSize ){
73.126 + memset(&p->aOp[oldSize], 0, (nNew-oldSize)*sizeof(Op));
73.127 + }
73.128 + }
73.129 + }
73.130 +}
73.131 +
73.132 +/*
73.133 +** Add a new instruction to the list of instructions current in the
73.134 +** VDBE. Return the address of the new instruction.
73.135 +**
73.136 +** Parameters:
73.137 +**
73.138 +** p Pointer to the VDBE
73.139 +**
73.140 +** op The opcode for this instruction
73.141 +**
73.142 +** p1, p2 First two of the three possible operands.
73.143 +**
73.144 +** Use the sqlite3VdbeResolveLabel() function to fix an address and
73.145 +** the sqlite3VdbeChangeP3() function to change the value of the P3
73.146 +** operand.
73.147 +*/
73.148 +int sqlite3VdbeAddOp(Vdbe *p, int op, int p1, int p2){
73.149 + int i;
73.150 + VdbeOp *pOp;
73.151 +
73.152 + i = p->nOp;
73.153 + assert( p->magic==VDBE_MAGIC_INIT );
73.154 + if( p->nOpAlloc<=i ){
73.155 + resizeOpArray(p, i+1);
73.156 + if( sqlite3MallocFailed() ){
73.157 + return 0;
73.158 + }
73.159 + }
73.160 + p->nOp++;
73.161 + pOp = &p->aOp[i];
73.162 + pOp->opcode = op;
73.163 + pOp->p1 = p1;
73.164 + pOp->p2 = p2;
73.165 + pOp->p3 = 0;
73.166 + pOp->p3type = P3_NOTUSED;
73.167 + p->expired = 0;
73.168 +#ifdef SQLITE_DEBUG
73.169 + if( sqlite3_vdbe_addop_trace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
73.170 +#endif
73.171 + return i;
73.172 +}
73.173 +
73.174 +/*
73.175 +** Add an opcode that includes the p3 value.
73.176 +*/
73.177 +int sqlite3VdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3,int p3type){
73.178 + int addr = sqlite3VdbeAddOp(p, op, p1, p2);
73.179 + sqlite3VdbeChangeP3(p, addr, zP3, p3type);
73.180 + return addr;
73.181 +}
73.182 +
73.183 +/*
73.184 +** Create a new symbolic label for an instruction that has yet to be
73.185 +** coded. The symbolic label is really just a negative number. The
73.186 +** label can be used as the P2 value of an operation. Later, when
73.187 +** the label is resolved to a specific address, the VDBE will scan
73.188 +** through its operation list and change all values of P2 which match
73.189 +** the label into the resolved address.
73.190 +**
73.191 +** The VDBE knows that a P2 value is a label because labels are
73.192 +** always negative and P2 values are suppose to be non-negative.
73.193 +** Hence, a negative P2 value is a label that has yet to be resolved.
73.194 +**
73.195 +** Zero is returned if a malloc() fails.
73.196 +*/
73.197 +int sqlite3VdbeMakeLabel(Vdbe *p){
73.198 + int i;
73.199 + i = p->nLabel++;
73.200 + assert( p->magic==VDBE_MAGIC_INIT );
73.201 + if( i>=p->nLabelAlloc ){
73.202 + p->nLabelAlloc = p->nLabelAlloc*2 + 10;
73.203 + p->aLabel = sqliteReallocOrFree(p->aLabel,
73.204 + p->nLabelAlloc*sizeof(p->aLabel[0]));
73.205 + }
73.206 + if( p->aLabel ){
73.207 + p->aLabel[i] = -1;
73.208 + }
73.209 + return -1-i;
73.210 +}
73.211 +
73.212 +/*
73.213 +** Resolve label "x" to be the address of the next instruction to
73.214 +** be inserted. The parameter "x" must have been obtained from
73.215 +** a prior call to sqlite3VdbeMakeLabel().
73.216 +*/
73.217 +void sqlite3VdbeResolveLabel(Vdbe *p, int x){
73.218 + int j = -1-x;
73.219 + assert( p->magic==VDBE_MAGIC_INIT );
73.220 + assert( j>=0 && j<p->nLabel );
73.221 + if( p->aLabel ){
73.222 + p->aLabel[j] = p->nOp;
73.223 + }
73.224 +}
73.225 +
73.226 +/*
73.227 +** Return non-zero if opcode 'op' is guarenteed not to push more values
73.228 +** onto the VDBE stack than it pops off.
73.229 +*/
73.230 +static int opcodeNoPush(u8 op){
73.231 + /* The 10 NOPUSH_MASK_n constants are defined in the automatically
73.232 + ** generated header file opcodes.h. Each is a 16-bit bitmask, one
73.233 + ** bit corresponding to each opcode implemented by the virtual
73.234 + ** machine in vdbe.c. The bit is true if the word "no-push" appears
73.235 + ** in a comment on the same line as the "case OP_XXX:" in
73.236 + ** sqlite3VdbeExec() in vdbe.c.
73.237 + **
73.238 + ** If the bit is true, then the corresponding opcode is guarenteed not
73.239 + ** to grow the stack when it is executed. Otherwise, it may grow the
73.240 + ** stack by at most one entry.
73.241 + **
73.242 + ** NOPUSH_MASK_0 corresponds to opcodes 0 to 15. NOPUSH_MASK_1 contains
73.243 + ** one bit for opcodes 16 to 31, and so on.
73.244 + **
73.245 + ** 16-bit bitmasks (rather than 32-bit) are specified in opcodes.h
73.246 + ** because the file is generated by an awk program. Awk manipulates
73.247 + ** all numbers as floating-point and we don't want to risk a rounding
73.248 + ** error if someone builds with an awk that uses (for example) 32-bit
73.249 + ** IEEE floats.
73.250 + */
73.251 + static const u32 masks[5] = {
73.252 + NOPUSH_MASK_0 + (((unsigned)NOPUSH_MASK_1)<<16),
73.253 + NOPUSH_MASK_2 + (((unsigned)NOPUSH_MASK_3)<<16),
73.254 + NOPUSH_MASK_4 + (((unsigned)NOPUSH_MASK_5)<<16),
73.255 + NOPUSH_MASK_6 + (((unsigned)NOPUSH_MASK_7)<<16),
73.256 + NOPUSH_MASK_8 + (((unsigned)NOPUSH_MASK_9)<<16)
73.257 + };
73.258 + assert( op<32*5 );
73.259 + return (masks[op>>5] & (1<<(op&0x1F)));
73.260 +}
73.261 +
73.262 +#ifndef NDEBUG
73.263 +int sqlite3VdbeOpcodeNoPush(u8 op){
73.264 + return opcodeNoPush(op);
73.265 +}
73.266 +#endif
73.267 +
73.268 +/*
73.269 +** Loop through the program looking for P2 values that are negative.
73.270 +** Each such value is a label. Resolve the label by setting the P2
73.271 +** value to its correct non-zero value.
73.272 +**
73.273 +** This routine is called once after all opcodes have been inserted.
73.274 +**
73.275 +** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
73.276 +** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
73.277 +** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
73.278 +**
73.279 +** The integer *pMaxStack is set to the maximum number of vdbe stack
73.280 +** entries that static analysis reveals this program might need.
73.281 +**
73.282 +** This routine also does the following optimization: It scans for
73.283 +** Halt instructions where P1==SQLITE_CONSTRAINT or P2==OE_Abort or for
73.284 +** IdxInsert instructions where P2!=0. If no such instruction is
73.285 +** found, then every Statement instruction is changed to a Noop. In
73.286 +** this way, we avoid creating the statement journal file unnecessarily.
73.287 +*/
73.288 +static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs, int *pMaxStack){
73.289 + int i;
73.290 + int nMaxArgs = 0;
73.291 + int nMaxStack = p->nOp;
73.292 + Op *pOp;
73.293 + int *aLabel = p->aLabel;
73.294 + int doesStatementRollback = 0;
73.295 + int hasStatementBegin = 0;
73.296 + for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
73.297 + u8 opcode = pOp->opcode;
73.298 +
73.299 + if( opcode==OP_Function || opcode==OP_AggStep
73.300 +#ifndef SQLITE_OMIT_VIRTUALTABLE
73.301 + || opcode==OP_VUpdate
73.302 +#endif
73.303 + ){
73.304 + if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
73.305 + }
73.306 + if( opcode==OP_Halt ){
73.307 + if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
73.308 + doesStatementRollback = 1;
73.309 + }
73.310 + }else if( opcode==OP_Statement ){
73.311 + hasStatementBegin = 1;
73.312 +#ifndef SQLITE_OMIT_VIRTUALTABLE
73.313 + }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
73.314 + doesStatementRollback = 1;
73.315 + }else if( opcode==OP_VFilter ){
73.316 + int n;
73.317 + assert( p->nOp - i >= 3 );
73.318 + assert( pOp[-2].opcode==OP_Integer );
73.319 + n = pOp[-2].p1;
73.320 + if( n>nMaxArgs ) nMaxArgs = n;
73.321 +#endif
73.322 + }
73.323 + if( opcodeNoPush(opcode) ){
73.324 + nMaxStack--;
73.325 + }
73.326 +
73.327 + if( pOp->p2>=0 ) continue;
73.328 + assert( -1-pOp->p2<p->nLabel );
73.329 + pOp->p2 = aLabel[-1-pOp->p2];
73.330 + }
73.331 + sqliteFree(p->aLabel);
73.332 + p->aLabel = 0;
73.333 +
73.334 + *pMaxFuncArgs = nMaxArgs;
73.335 + *pMaxStack = nMaxStack;
73.336 +
73.337 + /* If we never rollback a statement transaction, then statement
73.338 + ** transactions are not needed. So change every OP_Statement
73.339 + ** opcode into an OP_Noop. This avoid a call to sqlite3OsOpenExclusive()
73.340 + ** which can be expensive on some platforms.
73.341 + */
73.342 + if( hasStatementBegin && !doesStatementRollback ){
73.343 + for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
73.344 + if( pOp->opcode==OP_Statement ){
73.345 + pOp->opcode = OP_Noop;
73.346 + }
73.347 + }
73.348 + }
73.349 +}
73.350 +
73.351 +/*
73.352 +** Return the address of the next instruction to be inserted.
73.353 +*/
73.354 +int sqlite3VdbeCurrentAddr(Vdbe *p){
73.355 + assert( p->magic==VDBE_MAGIC_INIT );
73.356 + return p->nOp;
73.357 +}
73.358 +
73.359 +/*
73.360 +** Add a whole list of operations to the operation stack. Return the
73.361 +** address of the first operation added.
73.362 +*/
73.363 +int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
73.364 + int addr;
73.365 + assert( p->magic==VDBE_MAGIC_INIT );
73.366 + resizeOpArray(p, p->nOp + nOp);
73.367 + if( sqlite3MallocFailed() ){
73.368 + return 0;
73.369 + }
73.370 + addr = p->nOp;
73.371 + if( nOp>0 ){
73.372 + int i;
73.373 + VdbeOpList const *pIn = aOp;
73.374 + for(i=0; i<nOp; i++, pIn++){
73.375 + int p2 = pIn->p2;
73.376 + VdbeOp *pOut = &p->aOp[i+addr];
73.377 + pOut->opcode = pIn->opcode;
73.378 + pOut->p1 = pIn->p1;
73.379 + pOut->p2 = p2<0 ? addr + ADDR(p2) : p2;
73.380 + pOut->p3 = pIn->p3;
73.381 + pOut->p3type = pIn->p3 ? P3_STATIC : P3_NOTUSED;
73.382 +#ifdef SQLITE_DEBUG
73.383 + if( sqlite3_vdbe_addop_trace ){
73.384 + sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
73.385 + }
73.386 +#endif
73.387 + }
73.388 + p->nOp += nOp;
73.389 + }
73.390 + return addr;
73.391 +}
73.392 +
73.393 +/*
73.394 +** Change the value of the P1 operand for a specific instruction.
73.395 +** This routine is useful when a large program is loaded from a
73.396 +** static array using sqlite3VdbeAddOpList but we want to make a
73.397 +** few minor changes to the program.
73.398 +*/
73.399 +void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
73.400 + assert( p==0 || p->magic==VDBE_MAGIC_INIT );
73.401 + if( p && addr>=0 && p->nOp>addr && p->aOp ){
73.402 + p->aOp[addr].p1 = val;
73.403 + }
73.404 +}
73.405 +
73.406 +/*
73.407 +** Change the value of the P2 operand for a specific instruction.
73.408 +** This routine is useful for setting a jump destination.
73.409 +*/
73.410 +void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
73.411 + assert( val>=0 );
73.412 + assert( p==0 || p->magic==VDBE_MAGIC_INIT );
73.413 + if( p && addr>=0 && p->nOp>addr && p->aOp ){
73.414 + p->aOp[addr].p2 = val;
73.415 + }
73.416 +}
73.417 +
73.418 +/*
73.419 +** Change the P2 operand of instruction addr so that it points to
73.420 +** the address of the next instruction to be coded.
73.421 +*/
73.422 +void sqlite3VdbeJumpHere(Vdbe *p, int addr){
73.423 + sqlite3VdbeChangeP2(p, addr, p->nOp);
73.424 +}
73.425 +
73.426 +
73.427 +/*
73.428 +** If the input FuncDef structure is ephemeral, then free it. If
73.429 +** the FuncDef is not ephermal, then do nothing.
73.430 +*/
73.431 +static void freeEphemeralFunction(FuncDef *pDef){
73.432 + if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
73.433 + sqliteFree(pDef);
73.434 + }
73.435 +}
73.436 +
73.437 +/*
73.438 +** Delete a P3 value if necessary.
73.439 +*/
73.440 +static void freeP3(int p3type, void *p3){
73.441 + if( p3 ){
73.442 + switch( p3type ){
73.443 + case P3_DYNAMIC:
73.444 + case P3_KEYINFO:
73.445 + case P3_KEYINFO_HANDOFF: {
73.446 + sqliteFree(p3);
73.447 + break;
73.448 + }
73.449 + case P3_MPRINTF: {
73.450 + sqlite3_free(p3);
73.451 + break;
73.452 + }
73.453 + case P3_VDBEFUNC: {
73.454 + VdbeFunc *pVdbeFunc = (VdbeFunc *)p3;
73.455 + freeEphemeralFunction(pVdbeFunc->pFunc);
73.456 + sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
73.457 + sqliteFree(pVdbeFunc);
73.458 + break;
73.459 + }
73.460 + case P3_FUNCDEF: {
73.461 + freeEphemeralFunction((FuncDef*)p3);
73.462 + break;
73.463 + }
73.464 + case P3_MEM: {
73.465 + sqlite3ValueFree((sqlite3_value*)p3);
73.466 + break;
73.467 + }
73.468 + }
73.469 + }
73.470 +}
73.471 +
73.472 +
73.473 +/*
73.474 +** Change N opcodes starting at addr to No-ops.
73.475 +*/
73.476 +void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
73.477 + if( p && p->aOp ){
73.478 + VdbeOp *pOp = &p->aOp[addr];
73.479 + while( N-- ){
73.480 + freeP3(pOp->p3type, pOp->p3);
73.481 + memset(pOp, 0, sizeof(pOp[0]));
73.482 + pOp->opcode = OP_Noop;
73.483 + pOp++;
73.484 + }
73.485 + }
73.486 +}
73.487 +
73.488 +/*
73.489 +** Change the value of the P3 operand for a specific instruction.
73.490 +** This routine is useful when a large program is loaded from a
73.491 +** static array using sqlite3VdbeAddOpList but we want to make a
73.492 +** few minor changes to the program.
73.493 +**
73.494 +** If n>=0 then the P3 operand is dynamic, meaning that a copy of
73.495 +** the string is made into memory obtained from sqliteMalloc().
73.496 +** A value of n==0 means copy bytes of zP3 up to and including the
73.497 +** first null byte. If n>0 then copy n+1 bytes of zP3.
73.498 +**
73.499 +** If n==P3_KEYINFO it means that zP3 is a pointer to a KeyInfo structure.
73.500 +** A copy is made of the KeyInfo structure into memory obtained from
73.501 +** sqliteMalloc, to be freed when the Vdbe is finalized.
73.502 +** n==P3_KEYINFO_HANDOFF indicates that zP3 points to a KeyInfo structure
73.503 +** stored in memory that the caller has obtained from sqliteMalloc. The
73.504 +** caller should not free the allocation, it will be freed when the Vdbe is
73.505 +** finalized.
73.506 +**
73.507 +** Other values of n (P3_STATIC, P3_COLLSEQ etc.) indicate that zP3 points
73.508 +** to a string or structure that is guaranteed to exist for the lifetime of
73.509 +** the Vdbe. In these cases we can just copy the pointer.
73.510 +**
73.511 +** If addr<0 then change P3 on the most recently inserted instruction.
73.512 +*/
73.513 +void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
73.514 + Op *pOp;
73.515 + assert( p==0 || p->magic==VDBE_MAGIC_INIT );
73.516 + if( p==0 || p->aOp==0 || sqlite3MallocFailed() ){
73.517 + if (n != P3_KEYINFO) {
73.518 + freeP3(n, (void*)*(char**)&zP3);
73.519 + }
73.520 + return;
73.521 + }
73.522 + if( addr<0 || addr>=p->nOp ){
73.523 + addr = p->nOp - 1;
73.524 + if( addr<0 ) return;
73.525 + }
73.526 + pOp = &p->aOp[addr];
73.527 + freeP3(pOp->p3type, pOp->p3);
73.528 + pOp->p3 = 0;
73.529 + if( zP3==0 ){
73.530 + pOp->p3 = 0;
73.531 + pOp->p3type = P3_NOTUSED;
73.532 + }else if( n==P3_KEYINFO ){
73.533 + KeyInfo *pKeyInfo;
73.534 + int nField, nByte;
73.535 +
73.536 + nField = ((KeyInfo*)zP3)->nField;
73.537 + nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
73.538 + pKeyInfo = sqliteMallocRaw( nByte );
73.539 + pOp->p3 = (char*)pKeyInfo;
73.540 + if( pKeyInfo ){
73.541 + unsigned char *aSortOrder;
73.542 + memcpy(pKeyInfo, zP3, nByte);
73.543 + aSortOrder = pKeyInfo->aSortOrder;
73.544 + if( aSortOrder ){
73.545 + pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
73.546 + memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
73.547 + }
73.548 + pOp->p3type = P3_KEYINFO;
73.549 + }else{
73.550 + pOp->p3type = P3_NOTUSED;
73.551 + }
73.552 + }else if( n==P3_KEYINFO_HANDOFF ){
73.553 + pOp->p3 = (char*)zP3;
73.554 + pOp->p3type = P3_KEYINFO;
73.555 + }else if( n<0 ){
73.556 + pOp->p3 = (char*)zP3;
73.557 + pOp->p3type = n;
73.558 + }else{
73.559 + if( n==0 ) n = strlen(zP3);
73.560 + pOp->p3 = sqliteStrNDup(zP3, n);
73.561 + pOp->p3type = P3_DYNAMIC;
73.562 + }
73.563 +}
73.564 +
73.565 +#ifndef NDEBUG
73.566 +/*
73.567 +** Replace the P3 field of the most recently coded instruction with
73.568 +** comment text.
73.569 +*/
73.570 +void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
73.571 + va_list ap;
73.572 + assert( p->nOp>0 || p->aOp==0 );
73.573 + assert( p->aOp==0 || p->aOp[p->nOp-1].p3==0 || sqlite3MallocFailed() );
73.574 + va_start(ap, zFormat);
73.575 + sqlite3VdbeChangeP3(p, -1, sqlite3VMPrintf(zFormat, ap), P3_DYNAMIC);
73.576 + va_end(ap);
73.577 +}
73.578 +#endif
73.579 +
73.580 +/*
73.581 +** Return the opcode for a given address.
73.582 +*/
73.583 +VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
73.584 + assert( p->magic==VDBE_MAGIC_INIT );
73.585 + assert( (addr>=0 && addr<p->nOp) || sqlite3MallocFailed() );
73.586 + return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
73.587 +}
73.588 +
73.589 +#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
73.590 + || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
73.591 +/*
73.592 +** Compute a string that describes the P3 parameter for an opcode.
73.593 +** Use zTemp for any required temporary buffer space.
73.594 +*/
73.595 +static char *displayP3(Op *pOp, char *zTemp, int nTemp){
73.596 + char *zP3;
73.597 + assert( nTemp>=20 );
73.598 + switch( pOp->p3type ){
73.599 + case P3_KEYINFO: {
73.600 + int i, j;
73.601 + KeyInfo *pKeyInfo = (KeyInfo*)pOp->p3;
73.602 + sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
73.603 + i = strlen(zTemp);
73.604 + for(j=0; j<pKeyInfo->nField; j++){
73.605 + CollSeq *pColl = pKeyInfo->aColl[j];
73.606 + if( pColl ){
73.607 + int n = strlen(pColl->zName);
73.608 + if( i+n>nTemp-6 ){
73.609 + memcpy(&zTemp[i],",...",4);
73.610 + break;
73.611 + }
73.612 + zTemp[i++] = ',';
73.613 + if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
73.614 + zTemp[i++] = '-';
73.615 + }
73.616 + memcpy(&zTemp[i], pColl->zName,n+1);
73.617 + i += n;
73.618 + }else if( i+4<nTemp-6 ){
73.619 + memcpy(&zTemp[i],",nil",4);
73.620 + i += 4;
73.621 + }
73.622 + }
73.623 + zTemp[i++] = ')';
73.624 + zTemp[i] = 0;
73.625 + assert( i<nTemp );
73.626 + zP3 = zTemp;
73.627 + break;
73.628 + }
73.629 + case P3_COLLSEQ: {
73.630 + CollSeq *pColl = (CollSeq*)pOp->p3;
73.631 + sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
73.632 + zP3 = zTemp;
73.633 + break;
73.634 + }
73.635 + case P3_FUNCDEF: {
73.636 + FuncDef *pDef = (FuncDef*)pOp->p3;
73.637 + sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
73.638 + zP3 = zTemp;
73.639 + break;
73.640 + }
73.641 +#ifndef SQLITE_OMIT_VIRTUALTABLE
73.642 + case P3_VTAB: {
73.643 + sqlite3_vtab *pVtab = (sqlite3_vtab*)pOp->p3;
73.644 + sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
73.645 + zP3 = zTemp;
73.646 + break;
73.647 + }
73.648 +#endif
73.649 + default: {
73.650 + zP3 = pOp->p3;
73.651 + if( zP3==0 || pOp->opcode==OP_Noop ){
73.652 + zP3 = "";
73.653 + }
73.654 + }
73.655 + }
73.656 + assert( zP3!=0 );
73.657 + return zP3;
73.658 +}
73.659 +#endif
73.660 +
73.661 +
73.662 +#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
73.663 +/*
73.664 +** Print a single opcode. This routine is used for debugging only.
73.665 +*/
73.666 +void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
73.667 + char *zP3;
73.668 + char zPtr[50];
73.669 + static const char *zFormat1 = "%4d %-13s %4d %4d %s\n";
73.670 + if( pOut==0 ) pOut = stdout;
73.671 + zP3 = displayP3(pOp, zPtr, sizeof(zPtr));
73.672 + fprintf(pOut, zFormat1,
73.673 + pc, sqlite3OpcodeNames[pOp->opcode], pOp->p1, pOp->p2, zP3);
73.674 + fflush(pOut);
73.675 +}
73.676 +#endif
73.677 +
73.678 +/*
73.679 +** Release an array of N Mem elements
73.680 +*/
73.681 +static void releaseMemArray(Mem *p, int N){
73.682 + if( p ){
73.683 + while( N-->0 ){
73.684 + sqlite3VdbeMemRelease(p++);
73.685 + }
73.686 + }
73.687 +}
73.688 +
73.689 +#ifndef SQLITE_OMIT_EXPLAIN
73.690 +/*
73.691 +** Give a listing of the program in the virtual machine.
73.692 +**
73.693 +** The interface is the same as sqlite3VdbeExec(). But instead of
73.694 +** running the code, it invokes the callback once for each instruction.
73.695 +** This feature is used to implement "EXPLAIN".
73.696 +*/
73.697 +int sqlite3VdbeList(
73.698 + Vdbe *p /* The VDBE */
73.699 +){
73.700 + sqlite3 *db = p->db;
73.701 + int i;
73.702 + int rc = SQLITE_OK;
73.703 +
73.704 + assert( p->explain );
73.705 + if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
73.706 + assert( db->magic==SQLITE_MAGIC_BUSY );
73.707 + assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
73.708 +
73.709 + /* Even though this opcode does not put dynamic strings onto the
73.710 + ** the stack, they may become dynamic if the user calls
73.711 + ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
73.712 + */
73.713 + if( p->pTos==&p->aStack[4] ){
73.714 + releaseMemArray(p->aStack, 5);
73.715 + }
73.716 + p->resOnStack = 0;
73.717 +
73.718 + do{
73.719 + i = p->pc++;
73.720 + }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
73.721 + if( i>=p->nOp ){
73.722 + p->rc = SQLITE_OK;
73.723 + rc = SQLITE_DONE;
73.724 + }else if( db->u1.isInterrupted ){
73.725 + p->rc = SQLITE_INTERRUPT;
73.726 + rc = SQLITE_ERROR;
73.727 + sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(p->rc), (char*)0);
73.728 + }else{
73.729 + Op *pOp = &p->aOp[i];
73.730 + Mem *pMem = p->aStack;
73.731 + pMem->flags = MEM_Int;
73.732 + pMem->type = SQLITE_INTEGER;
73.733 + pMem->u.i = i; /* Program counter */
73.734 + pMem++;
73.735 +
73.736 + pMem->flags = MEM_Static|MEM_Str|MEM_Term;
73.737 + pMem->z = (char*)sqlite3OpcodeNames[pOp->opcode]; /* Opcode */
73.738 + assert( pMem->z!=0 );
73.739 + pMem->n = strlen(pMem->z);
73.740 + pMem->type = SQLITE_TEXT;
73.741 + pMem->enc = SQLITE_UTF8;
73.742 + pMem++;
73.743 +
73.744 + pMem->flags = MEM_Int;
73.745 + pMem->u.i = pOp->p1; /* P1 */
73.746 + pMem->type = SQLITE_INTEGER;
73.747 + pMem++;
73.748 +
73.749 + pMem->flags = MEM_Int;
73.750 + pMem->u.i = pOp->p2; /* P2 */
73.751 + pMem->type = SQLITE_INTEGER;
73.752 + pMem++;
73.753 +
73.754 + pMem->flags = MEM_Ephem|MEM_Str|MEM_Term; /* P3 */
73.755 + pMem->z = displayP3(pOp, pMem->zShort, sizeof(pMem->zShort));
73.756 + assert( pMem->z!=0 );
73.757 + pMem->n = strlen(pMem->z);
73.758 + pMem->type = SQLITE_TEXT;
73.759 + pMem->enc = SQLITE_UTF8;
73.760 +
73.761 + p->nResColumn = 5 - 2*(p->explain-1);
73.762 + p->pTos = pMem;
73.763 + p->rc = SQLITE_OK;
73.764 + p->resOnStack = 1;
73.765 + rc = SQLITE_ROW;
73.766 + }
73.767 + return rc;
73.768 +}
73.769 +#endif /* SQLITE_OMIT_EXPLAIN */
73.770 +
73.771 +#ifdef SQLITE_DEBUG
73.772 +/*
73.773 +** Print the SQL that was used to generate a VDBE program.
73.774 +*/
73.775 +void sqlite3VdbePrintSql(Vdbe *p){
73.776 + int nOp = p->nOp;
73.777 + VdbeOp *pOp;
73.778 + if( nOp<1 ) return;
73.779 + pOp = &p->aOp[nOp-1];
73.780 + if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
73.781 + const char *z = pOp->p3;
73.782 + while( isspace(*(u8*)z) ) z++;
73.783 + printf("SQL: [%s]\n", z);
73.784 + }
73.785 +}
73.786 +#endif
73.787 +
73.788 +#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
73.789 +/*
73.790 +** Print an IOTRACE message showing SQL content.
73.791 +*/
73.792 +void sqlite3VdbeIOTraceSql(Vdbe *p){
73.793 + int nOp = p->nOp;
73.794 + VdbeOp *pOp;
73.795 + if( sqlite3_io_trace==0 ) return;
73.796 + if( nOp<1 ) return;
73.797 + pOp = &p->aOp[nOp-1];
73.798 + if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
73.799 + char *z = sqlite3StrDup(pOp->p3);
73.800 + int i, j;
73.801 + for(i=0; isspace((unsigned char)z[i]); i++){}
73.802 + for(j=0; z[i]; i++){
73.803 + if( isspace((unsigned char)z[i]) ){
73.804 + if( z[i-1]!=' ' ){
73.805 + z[j++] = ' ';
73.806 + }
73.807 + }else{
73.808 + z[j++] = z[i];
73.809 + }
73.810 + }
73.811 + z[j] = 0;
73.812 + sqlite3_io_trace("SQL %s\n", z);
73.813 + sqliteFree(z);
73.814 + }
73.815 +}
73.816 +#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
73.817 +
73.818 +
73.819 +/*
73.820 +** Prepare a virtual machine for execution. This involves things such
73.821 +** as allocating stack space and initializing the program counter.
73.822 +** After the VDBE has be prepped, it can be executed by one or more
73.823 +** calls to sqlite3VdbeExec().
73.824 +**
73.825 +** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
73.826 +** VDBE_MAGIC_RUN.
73.827 +*/
73.828 +void sqlite3VdbeMakeReady(
73.829 + Vdbe *p, /* The VDBE */
73.830 + int nVar, /* Number of '?' see in the SQL statement */
73.831 + int nMem, /* Number of memory cells to allocate */
73.832 + int nCursor, /* Number of cursors to allocate */
73.833 + int isExplain /* True if the EXPLAIN keywords is present */
73.834 +){
73.835 + int n;
73.836 +
73.837 + assert( p!=0 );
73.838 + assert( p->magic==VDBE_MAGIC_INIT );
73.839 +
73.840 + /* There should be at least one opcode.
73.841 + */
73.842 + assert( p->nOp>0 );
73.843 +
73.844 + /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
73.845 + * is because the call to resizeOpArray() below may shrink the
73.846 + * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN
73.847 + * state.
73.848 + */
73.849 + p->magic = VDBE_MAGIC_RUN;
73.850 +
73.851 + /* No instruction ever pushes more than a single element onto the
73.852 + ** stack. And the stack never grows on successive executions of the
73.853 + ** same loop. So the total number of instructions is an upper bound
73.854 + ** on the maximum stack depth required. (Added later:) The
73.855 + ** resolveP2Values() call computes a tighter upper bound on the
73.856 + ** stack size.
73.857 + **
73.858 + ** Allocation all the stack space we will ever need.
73.859 + */
73.860 + if( p->aStack==0 ){
73.861 + int nArg; /* Maximum number of args passed to a user function. */
73.862 + int nStack; /* Maximum number of stack entries required */
73.863 + resolveP2Values(p, &nArg, &nStack);
73.864 + resizeOpArray(p, p->nOp);
73.865 + assert( nVar>=0 );
73.866 + assert( nStack<p->nOp );
73.867 + if( isExplain ){
73.868 + nStack = 10;
73.869 + }
73.870 + p->aStack = sqliteMalloc(
73.871 + nStack*sizeof(p->aStack[0]) /* aStack */
73.872 + + nArg*sizeof(Mem*) /* apArg */
73.873 + + nVar*sizeof(Mem) /* aVar */
73.874 + + nVar*sizeof(char*) /* azVar */
73.875 + + nMem*sizeof(Mem) /* aMem */
73.876 + + nCursor*sizeof(Cursor*) /* apCsr */
73.877 + );
73.878 + if( !sqlite3MallocFailed() ){
73.879 + p->aMem = &p->aStack[nStack];
73.880 + p->nMem = nMem;
73.881 + p->aVar = &p->aMem[nMem];
73.882 + p->nVar = nVar;
73.883 + p->okVar = 0;
73.884 + p->apArg = (Mem**)&p->aVar[nVar];
73.885 + p->azVar = (char**)&p->apArg[nArg];
73.886 + p->apCsr = (Cursor**)&p->azVar[nVar];
73.887 + p->nCursor = nCursor;
73.888 + for(n=0; n<nVar; n++){
73.889 + p->aVar[n].flags = MEM_Null;
73.890 + }
73.891 + }
73.892 + }
73.893 + for(n=0; n<p->nMem; n++){
73.894 + p->aMem[n].flags = MEM_Null;
73.895 + }
73.896 +
73.897 + p->pTos = &p->aStack[-1];
73.898 + p->pc = -1;
73.899 + p->rc = SQLITE_OK;
73.900 + p->uniqueCnt = 0;
73.901 + p->returnDepth = 0;
73.902 + p->errorAction = OE_Abort;
73.903 + p->popStack = 0;
73.904 + p->explain |= isExplain;
73.905 + p->magic = VDBE_MAGIC_RUN;
73.906 + p->nChange = 0;
73.907 + p->cacheCtr = 1;
73.908 + p->minWriteFileFormat = 255;
73.909 + p->openedStatement = 0;
73.910 +#ifdef VDBE_PROFILE
73.911 + {
73.912 + int i;
73.913 + for(i=0; i<p->nOp; i++){
73.914 + p->aOp[i].cnt = 0;
73.915 + p->aOp[i].cycles = 0;
73.916 + }
73.917 + }
73.918 +#endif
73.919 +}
73.920 +
73.921 +/*
73.922 +** Close a cursor and release all the resources that cursor happens
73.923 +** to hold.
73.924 +*/
73.925 +void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
73.926 + if( pCx==0 ){
73.927 + return;
73.928 + }
73.929 + if( pCx->pCursor ){
73.930 + sqlite3BtreeCloseCursor(pCx->pCursor);
73.931 + }
73.932 + if( pCx->pBt ){
73.933 + sqlite3BtreeClose(pCx->pBt);
73.934 + }
73.935 +#ifndef SQLITE_OMIT_VIRTUALTABLE
73.936 + if( pCx->pVtabCursor ){
73.937 + sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
73.938 + const sqlite3_module *pModule = pCx->pModule;
73.939 + p->inVtabMethod = 1;
73.940 + sqlite3SafetyOff(p->db);
73.941 + pModule->xClose(pVtabCursor);
73.942 + sqlite3SafetyOn(p->db);
73.943 + p->inVtabMethod = 0;
73.944 + }
73.945 +#endif
73.946 + sqliteFree(pCx->pData);
73.947 + sqliteFree(pCx->aType);
73.948 + sqliteFree(pCx);
73.949 +}
73.950 +
73.951 +/*
73.952 +** Close all cursors
73.953 +*/
73.954 +static void closeAllCursors(Vdbe *p){
73.955 + int i;
73.956 + if( p->apCsr==0 ) return;
73.957 + for(i=0; i<p->nCursor; i++){
73.958 + if( !p->inVtabMethod || (p->apCsr[i] && !p->apCsr[i]->pVtabCursor) ){
73.959 + sqlite3VdbeFreeCursor(p, p->apCsr[i]);
73.960 + p->apCsr[i] = 0;
73.961 + }
73.962 + }
73.963 +}
73.964 +
73.965 +/*
73.966 +** Clean up the VM after execution.
73.967 +**
73.968 +** This routine will automatically close any cursors, lists, and/or
73.969 +** sorters that were left open. It also deletes the values of
73.970 +** variables in the aVar[] array.
73.971 +*/
73.972 +static void Cleanup(Vdbe *p){
73.973 + int i;
73.974 + if( p->aStack ){
73.975 + releaseMemArray(p->aStack, 1 + (p->pTos - p->aStack));
73.976 + p->pTos = &p->aStack[-1];
73.977 + }
73.978 + closeAllCursors(p);
73.979 + releaseMemArray(p->aMem, p->nMem);
73.980 + sqlite3VdbeFifoClear(&p->sFifo);
73.981 + if( p->contextStack ){
73.982 + for(i=0; i<p->contextStackTop; i++){
73.983 + sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
73.984 + }
73.985 + sqliteFree(p->contextStack);
73.986 + }
73.987 + p->contextStack = 0;
73.988 + p->contextStackDepth = 0;
73.989 + p->contextStackTop = 0;
73.990 + sqliteFree(p->zErrMsg);
73.991 + p->zErrMsg = 0;
73.992 + p->resOnStack = 0;
73.993 +}
73.994 +
73.995 +/*
73.996 +** Set the number of result columns that will be returned by this SQL
73.997 +** statement. This is now set at compile time, rather than during
73.998 +** execution of the vdbe program so that sqlite3_column_count() can
73.999 +** be called on an SQL statement before sqlite3_step().
73.1000 +*/
73.1001 +void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
73.1002 + Mem *pColName;
73.1003 + int n;
73.1004 + releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
73.1005 + sqliteFree(p->aColName);
73.1006 + n = nResColumn*COLNAME_N;
73.1007 + p->nResColumn = nResColumn;
73.1008 + p->aColName = pColName = (Mem*)sqliteMalloc( sizeof(Mem)*n );
73.1009 + if( p->aColName==0 ) return;
73.1010 + while( n-- > 0 ){
73.1011 + (pColName++)->flags = MEM_Null;
73.1012 + }
73.1013 +}
73.1014 +
73.1015 +/*
73.1016 +** Set the name of the idx'th column to be returned by the SQL statement.
73.1017 +** zName must be a pointer to a nul terminated string.
73.1018 +**
73.1019 +** This call must be made after a call to sqlite3VdbeSetNumCols().
73.1020 +**
73.1021 +** If N==P3_STATIC it means that zName is a pointer to a constant static
73.1022 +** string and we can just copy the pointer. If it is P3_DYNAMIC, then
73.1023 +** the string is freed using sqliteFree() when the vdbe is finished with
73.1024 +** it. Otherwise, N bytes of zName are copied.
73.1025 +*/
73.1026 +int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
73.1027 + int rc;
73.1028 + Mem *pColName;
73.1029 + assert( idx<p->nResColumn );
73.1030 + assert( var<COLNAME_N );
73.1031 + if( sqlite3MallocFailed() ) return SQLITE_NOMEM;
73.1032 + assert( p->aColName!=0 );
73.1033 + pColName = &(p->aColName[idx+var*p->nResColumn]);
73.1034 + if( N==P3_DYNAMIC || N==P3_STATIC ){
73.1035 + rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
73.1036 + }else{
73.1037 + rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
73.1038 + }
73.1039 + if( rc==SQLITE_OK && N==P3_DYNAMIC ){
73.1040 + pColName->flags = (pColName->flags&(~MEM_Static))|MEM_Dyn;
73.1041 + pColName->xDel = 0;
73.1042 + }
73.1043 + return rc;
73.1044 +}
73.1045 +
73.1046 +/*
73.1047 +** A read or write transaction may or may not be active on database handle
73.1048 +** db. If a transaction is active, commit it. If there is a
73.1049 +** write-transaction spanning more than one database file, this routine
73.1050 +** takes care of the master journal trickery.
73.1051 +*/
73.1052 +static int vdbeCommit(sqlite3 *db){
73.1053 + int i;
73.1054 + int nTrans = 0; /* Number of databases with an active write-transaction */
73.1055 + int rc = SQLITE_OK;
73.1056 + int needXcommit = 0;
73.1057 +
73.1058 + /* Before doing anything else, call the xSync() callback for any
73.1059 + ** virtual module tables written in this transaction. This has to
73.1060 + ** be done before determining whether a master journal file is
73.1061 + ** required, as an xSync() callback may add an attached database
73.1062 + ** to the transaction.
73.1063 + */
73.1064 + rc = sqlite3VtabSync(db, rc);
73.1065 + if( rc!=SQLITE_OK ){
73.1066 + return rc;
73.1067 + }
73.1068 +
73.1069 + /* This loop determines (a) if the commit hook should be invoked and
73.1070 + ** (b) how many database files have open write transactions, not
73.1071 + ** including the temp database. (b) is important because if more than
73.1072 + ** one database file has an open write transaction, a master journal
73.1073 + ** file is required for an atomic commit.
73.1074 + */
73.1075 + for(i=0; i<db->nDb; i++){
73.1076 + Btree *pBt = db->aDb[i].pBt;
73.1077 + if( pBt && sqlite3BtreeIsInTrans(pBt) ){
73.1078 + needXcommit = 1;
73.1079 + if( i!=1 ) nTrans++;
73.1080 + }
73.1081 + }
73.1082 +
73.1083 + /* If there are any write-transactions at all, invoke the commit hook */
73.1084 + if( needXcommit && db->xCommitCallback ){
73.1085 + sqlite3SafetyOff(db);
73.1086 + rc = db->xCommitCallback(db->pCommitArg);
73.1087 + sqlite3SafetyOn(db);
73.1088 + if( rc ){
73.1089 + return SQLITE_CONSTRAINT;
73.1090 + }
73.1091 + }
73.1092 +
73.1093 + /* The simple case - no more than one database file (not counting the
73.1094 + ** TEMP database) has a transaction active. There is no need for the
73.1095 + ** master-journal.
73.1096 + **
73.1097 + ** If the return value of sqlite3BtreeGetFilename() is a zero length
73.1098 + ** string, it means the main database is :memory:. In that case we do
73.1099 + ** not support atomic multi-file commits, so use the simple case then
73.1100 + ** too.
73.1101 + */
73.1102 + if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
73.1103 + for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
73.1104 + Btree *pBt = db->aDb[i].pBt;
73.1105 + if( pBt ){
73.1106 + rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
73.1107 + }
73.1108 + }
73.1109 +
73.1110 + /* Do the commit only if all databases successfully complete phase 1.
73.1111 + ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
73.1112 + ** IO error while deleting or truncating a journal file. It is unlikely,
73.1113 + ** but could happen. In this case abandon processing and return the error.
73.1114 + */
73.1115 + for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
73.1116 + Btree *pBt = db->aDb[i].pBt;
73.1117 + if( pBt ){
73.1118 + rc = sqlite3BtreeCommitPhaseTwo(pBt);
73.1119 + }
73.1120 + }
73.1121 + if( rc==SQLITE_OK ){
73.1122 + sqlite3VtabCommit(db);
73.1123 + }
73.1124 + }
73.1125 +
73.1126 + /* The complex case - There is a multi-file write-transaction active.
73.1127 + ** This requires a master journal file to ensure the transaction is
73.1128 + ** committed atomicly.
73.1129 + */
73.1130 +#ifndef SQLITE_OMIT_DISKIO
73.1131 + else{
73.1132 + int needSync = 0;
73.1133 + char *zMaster = 0; /* File-name for the master journal */
73.1134 + char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
73.1135 + OsFile *master = 0;
73.1136 +
73.1137 + /* Select a master journal file name */
73.1138 + do {
73.1139 + u32 random;
73.1140 + sqliteFree(zMaster);
73.1141 + sqlite3Randomness(sizeof(random), &random);
73.1142 + zMaster = sqlite3MPrintf("%s-mj%08X", zMainFile, random&0x7fffffff);
73.1143 + if( !zMaster ){
73.1144 + return SQLITE_NOMEM;
73.1145 + }
73.1146 + }while( sqlite3OsFileExists(zMaster) );
73.1147 +
73.1148 + /* Open the master journal. */
73.1149 + rc = sqlite3OsOpenExclusive(zMaster, &master, 0);
73.1150 + if( rc!=SQLITE_OK ){
73.1151 + sqliteFree(zMaster);
73.1152 + return rc;
73.1153 + }
73.1154 +
73.1155 + /* Write the name of each database file in the transaction into the new
73.1156 + ** master journal file. If an error occurs at this point close
73.1157 + ** and delete the master journal file. All the individual journal files
73.1158 + ** still have 'null' as the master journal pointer, so they will roll
73.1159 + ** back independently if a failure occurs.
73.1160 + */
73.1161 + for(i=0; i<db->nDb; i++){
73.1162 + Btree *pBt = db->aDb[i].pBt;
73.1163 + if( i==1 ) continue; /* Ignore the TEMP database */
73.1164 + if( pBt && sqlite3BtreeIsInTrans(pBt) ){
73.1165 + char const *zFile = sqlite3BtreeGetJournalname(pBt);
73.1166 + if( zFile[0]==0 ) continue; /* Ignore :memory: databases */
73.1167 + if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
73.1168 + needSync = 1;
73.1169 + }
73.1170 + rc = sqlite3OsWrite(master, zFile, strlen(zFile)+1);
73.1171 + if( rc!=SQLITE_OK ){
73.1172 + sqlite3OsClose(&master);
73.1173 + sqlite3OsDelete(zMaster);
73.1174 + sqliteFree(zMaster);
73.1175 + return rc;
73.1176 + }
73.1177 + }
73.1178 + }
73.1179 +
73.1180 +
73.1181 + /* Sync the master journal file. Before doing this, open the directory
73.1182 + ** the master journal file is store in so that it gets synced too.
73.1183 + */
73.1184 + zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
73.1185 + rc = sqlite3OsOpenDirectory(master, zMainFile);
73.1186 + if( rc!=SQLITE_OK ||
73.1187 + (needSync && (rc=sqlite3OsSync(master,0))!=SQLITE_OK) ){
73.1188 + sqlite3OsClose(&master);
73.1189 + sqlite3OsDelete(zMaster);
73.1190 + sqliteFree(zMaster);
73.1191 + return rc;
73.1192 + }
73.1193 +
73.1194 + /* Sync all the db files involved in the transaction. The same call
73.1195 + ** sets the master journal pointer in each individual journal. If
73.1196 + ** an error occurs here, do not delete the master journal file.
73.1197 + **
73.1198 + ** If the error occurs during the first call to
73.1199 + ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
73.1200 + ** master journal file will be orphaned. But we cannot delete it,
73.1201 + ** in case the master journal file name was written into the journal
73.1202 + ** file before the failure occured.
73.1203 + */
73.1204 + for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
73.1205 + Btree *pBt = db->aDb[i].pBt;
73.1206 + if( pBt && sqlite3BtreeIsInTrans(pBt) ){
73.1207 + rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
73.1208 + }
73.1209 + }
73.1210 + sqlite3OsClose(&master);
73.1211 + if( rc!=SQLITE_OK ){
73.1212 + sqliteFree(zMaster);
73.1213 + return rc;
73.1214 + }
73.1215 +
73.1216 + /* Delete the master journal file. This commits the transaction. After
73.1217 + ** doing this the directory is synced again before any individual
73.1218 + ** transaction files are deleted.
73.1219 + */
73.1220 + rc = sqlite3OsDelete(zMaster);
73.1221 + sqliteFree(zMaster);
73.1222 + zMaster = 0;
73.1223 + if( rc ){
73.1224 + return rc;
73.1225 + }
73.1226 + rc = sqlite3OsSyncDirectory(zMainFile);
73.1227 + if( rc!=SQLITE_OK ){
73.1228 + /* This is not good. The master journal file has been deleted, but
73.1229 + ** the directory sync failed. There is no completely safe course of
73.1230 + ** action from here. The individual journals contain the name of the
73.1231 + ** master journal file, but there is no way of knowing if that
73.1232 + ** master journal exists now or if it will exist after the operating
73.1233 + ** system crash that may follow the fsync() failure.
73.1234 + */
73.1235 + return rc;
73.1236 + }
73.1237 +
73.1238 + /* All files and directories have already been synced, so the following
73.1239 + ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
73.1240 + ** deleting or truncating journals. If something goes wrong while
73.1241 + ** this is happening we don't really care. The integrity of the
73.1242 + ** transaction is already guaranteed, but some stray 'cold' journals
73.1243 + ** may be lying around. Returning an error code won't help matters.
73.1244 + */
73.1245 + disable_simulated_io_errors();
73.1246 + for(i=0; i<db->nDb; i++){
73.1247 + Btree *pBt = db->aDb[i].pBt;
73.1248 + if( pBt ){
73.1249 + sqlite3BtreeCommitPhaseTwo(pBt);
73.1250 + }
73.1251 + }
73.1252 + enable_simulated_io_errors();
73.1253 +
73.1254 + sqlite3VtabCommit(db);
73.1255 + }
73.1256 +#endif
73.1257 +
73.1258 + return rc;
73.1259 +}
73.1260 +
73.1261 +/*
73.1262 +** This routine checks that the sqlite3.activeVdbeCnt count variable
73.1263 +** matches the number of vdbe's in the list sqlite3.pVdbe that are
73.1264 +** currently active. An assertion fails if the two counts do not match.
73.1265 +** This is an internal self-check only - it is not an essential processing
73.1266 +** step.
73.1267 +**
73.1268 +** This is a no-op if NDEBUG is defined.
73.1269 +*/
73.1270 +#ifndef NDEBUG
73.1271 +static void checkActiveVdbeCnt(sqlite3 *db){
73.1272 + Vdbe *p;
73.1273 + int cnt = 0;
73.1274 + p = db->pVdbe;
73.1275 + while( p ){
73.1276 + if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
73.1277 + cnt++;
73.1278 + }
73.1279 + p = p->pNext;
73.1280 + }
73.1281 + assert( cnt==db->activeVdbeCnt );
73.1282 +}
73.1283 +#else
73.1284 +#define checkActiveVdbeCnt(x)
73.1285 +#endif
73.1286 +
73.1287 +/*
73.1288 +** Find every active VM other than pVdbe and change its status to
73.1289 +** aborted. This happens when one VM causes a rollback due to an
73.1290 +** ON CONFLICT ROLLBACK clause (for example). The other VMs must be
73.1291 +** aborted so that they do not have data rolled out from underneath
73.1292 +** them leading to a segfault.
73.1293 +*/
73.1294 +void sqlite3AbortOtherActiveVdbes(sqlite3 *db, Vdbe *pExcept){
73.1295 + Vdbe *pOther;
73.1296 + for(pOther=db->pVdbe; pOther; pOther=pOther->pNext){
73.1297 + if( pOther==pExcept ) continue;
73.1298 + if( pOther->magic!=VDBE_MAGIC_RUN || pOther->pc<0 ) continue;
73.1299 + checkActiveVdbeCnt(db);
73.1300 + closeAllCursors(pOther);
73.1301 + checkActiveVdbeCnt(db);
73.1302 + pOther->aborted = 1;
73.1303 + }
73.1304 +}
73.1305 +
73.1306 +/*
73.1307 +** This routine is called the when a VDBE tries to halt. If the VDBE
73.1308 +** has made changes and is in autocommit mode, then commit those
73.1309 +** changes. If a rollback is needed, then do the rollback.
73.1310 +**
73.1311 +** This routine is the only way to move the state of a VM from
73.1312 +** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.
73.1313 +**
73.1314 +** Return an error code. If the commit could not complete because of
73.1315 +** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
73.1316 +** means the close did not happen and needs to be repeated.
73.1317 +*/
73.1318 +int sqlite3VdbeHalt(Vdbe *p){
73.1319 + sqlite3 *db = p->db;
73.1320 + int i;
73.1321 + int (*xFunc)(Btree *pBt) = 0; /* Function to call on each btree backend */
73.1322 + int isSpecialError; /* Set to true if SQLITE_NOMEM or IOERR */
73.1323 +
73.1324 + /* This function contains the logic that determines if a statement or
73.1325 + ** transaction will be committed or rolled back as a result of the
73.1326 + ** execution of this virtual machine.
73.1327 + **
73.1328 + ** Special errors:
73.1329 + **
73.1330 + ** If an SQLITE_NOMEM error has occured in a statement that writes to
73.1331 + ** the database, then either a statement or transaction must be rolled
73.1332 + ** back to ensure the tree-structures are in a consistent state. A
73.1333 + ** statement transaction is rolled back if one is open, otherwise the
73.1334 + ** entire transaction must be rolled back.
73.1335 + **
73.1336 + ** If an SQLITE_IOERR error has occured in a statement that writes to
73.1337 + ** the database, then the entire transaction must be rolled back. The
73.1338 + ** I/O error may have caused garbage to be written to the journal
73.1339 + ** file. Were the transaction to continue and eventually be rolled
73.1340 + ** back that garbage might end up in the database file.
73.1341 + **
73.1342 + ** In both of the above cases, the Vdbe.errorAction variable is
73.1343 + ** ignored. If the sqlite3.autoCommit flag is false and a transaction
73.1344 + ** is rolled back, it will be set to true.
73.1345 + **
73.1346 + ** Other errors:
73.1347 + **
73.1348 + ** No error:
73.1349 + **
73.1350 + */
73.1351 +
73.1352 + if( sqlite3MallocFailed() ){
73.1353 + p->rc = SQLITE_NOMEM;
73.1354 + }
73.1355 + if( p->magic!=VDBE_MAGIC_RUN ){
73.1356 + /* Already halted. Nothing to do. */
73.1357 + assert( p->magic==VDBE_MAGIC_HALT );
73.1358 +#ifndef SQLITE_OMIT_VIRTUALTABLE
73.1359 + closeAllCursors(p);
73.1360 +#endif
73.1361 + return SQLITE_OK;
73.1362 + }
73.1363 + closeAllCursors(p);
73.1364 + checkActiveVdbeCnt(db);
73.1365 +
73.1366 + /* No commit or rollback needed if the program never started */
73.1367 + if( p->pc>=0 ){
73.1368 + int mrc; /* Primary error code from p->rc */
73.1369 + /* Check for one of the special errors - SQLITE_NOMEM or SQLITE_IOERR */
73.1370 + mrc = p->rc & 0xff;
73.1371 + isSpecialError = (
73.1372 + (mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR || mrc==SQLITE_INTERRUPT)?1:0);
73.1373 + if( isSpecialError ){
73.1374 + /* This loop does static analysis of the query to see which of the
73.1375 + ** following three categories it falls into:
73.1376 + **
73.1377 + ** Read-only
73.1378 + ** Query with statement journal
73.1379 + ** Query without statement journal
73.1380 + **
73.1381 + ** We could do something more elegant than this static analysis (i.e.
73.1382 + ** store the type of query as part of the compliation phase), but
73.1383 + ** handling malloc() or IO failure is a fairly obscure edge case so
73.1384 + ** this is probably easier. Todo: Might be an opportunity to reduce
73.1385 + ** code size a very small amount though...
73.1386 + */
73.1387 + int isReadOnly = 1;
73.1388 + int isStatement = 0;
73.1389 + assert(p->aOp || p->nOp==0);
73.1390 + for(i=0; i<p->nOp; i++){
73.1391 + switch( p->aOp[i].opcode ){
73.1392 + case OP_Transaction:
73.1393 + /* This is a bit strange. If we hit a malloc() or IO error and
73.1394 + ** the statement did not open a statement transaction, we will
73.1395 + ** rollback any active transaction and abort all other active
73.1396 + ** statements. Or, if this is an SQLITE_INTERRUPT error, we
73.1397 + ** will only rollback if the interrupted statement was a write.
73.1398 + **
73.1399 + ** It could be argued that read-only statements should never
73.1400 + ** rollback anything. But careful analysis is required before
73.1401 + ** making this change
73.1402 + */
73.1403 + if( p->aOp[i].p2 || mrc!=SQLITE_INTERRUPT ){
73.1404 + isReadOnly = 0;
73.1405 + }
73.1406 + break;
73.1407 + case OP_Statement:
73.1408 + isStatement = 1;
73.1409 + break;
73.1410 + }
73.1411 + }
73.1412 +
73.1413 + /* If the query was read-only, we need do no rollback at all. Otherwise,
73.1414 + ** proceed with the special handling.
73.1415 + */
73.1416 + if( !isReadOnly ){
73.1417 + if( p->rc==SQLITE_IOERR_BLOCKED && isStatement ){
73.1418 + xFunc = sqlite3BtreeRollbackStmt;
73.1419 + p->rc = SQLITE_BUSY;
73.1420 + } else if( p->rc==SQLITE_NOMEM && isStatement ){
73.1421 + xFunc = sqlite3BtreeRollbackStmt;
73.1422 + }else{
73.1423 + /* We are forced to roll back the active transaction. Before doing
73.1424 + ** so, abort any other statements this handle currently has active.
73.1425 + */
73.1426 + sqlite3AbortOtherActiveVdbes(db, p);
73.1427 + sqlite3RollbackAll(db);
73.1428 + db->autoCommit = 1;
73.1429 + }
73.1430 + }
73.1431 + }
73.1432 +
73.1433 + /* If the auto-commit flag is set and this is the only active vdbe, then
73.1434 + ** we do either a commit or rollback of the current transaction.
73.1435 + **
73.1436 + ** Note: This block also runs if one of the special errors handled
73.1437 + ** above has occured.
73.1438 + */
73.1439 + if( db->autoCommit && db->activeVdbeCnt==1 ){
73.1440 + if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
73.1441 + /* The auto-commit flag is true, and the vdbe program was
73.1442 + ** successful or hit an 'OR FAIL' constraint. This means a commit
73.1443 + ** is required.
73.1444 + */
73.1445 + int rc = vdbeCommit(db);
73.1446 + if( rc==SQLITE_BUSY ){
73.1447 + return SQLITE_BUSY;
73.1448 + }else if( rc!=SQLITE_OK ){
73.1449 + p->rc = rc;
73.1450 + sqlite3RollbackAll(db);
73.1451 + }else{
73.1452 + sqlite3CommitInternalChanges(db);
73.1453 + }
73.1454 + }else{
73.1455 + sqlite3RollbackAll(db);
73.1456 + }
73.1457 + }else if( !xFunc ){
73.1458 + if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
73.1459 + if( p->openedStatement ){
73.1460 + xFunc = sqlite3BtreeCommitStmt;
73.1461 + }
73.1462 + }else if( p->errorAction==OE_Abort ){
73.1463 + xFunc = sqlite3BtreeRollbackStmt;
73.1464 + }else{
73.1465 + sqlite3AbortOtherActiveVdbes(db, p);
73.1466 + sqlite3RollbackAll(db);
73.1467 + db->autoCommit = 1;
73.1468 + }
73.1469 + }
73.1470 +
73.1471 + /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
73.1472 + ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
73.1473 + ** and the return code is still SQLITE_OK, set the return code to the new
73.1474 + ** error value.
73.1475 + */
73.1476 + assert(!xFunc ||
73.1477 + xFunc==sqlite3BtreeCommitStmt ||
73.1478 + xFunc==sqlite3BtreeRollbackStmt
73.1479 + );
73.1480 + for(i=0; xFunc && i<db->nDb; i++){
73.1481 + int rc;
73.1482 + Btree *pBt = db->aDb[i].pBt;
73.1483 + if( pBt ){
73.1484 + rc = xFunc(pBt);
73.1485 + if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
73.1486 + p->rc = rc;
73.1487 + sqlite3SetString(&p->zErrMsg, 0);
73.1488 + }
73.1489 + }
73.1490 + }
73.1491 +
73.1492 + /* If this was an INSERT, UPDATE or DELETE and the statement was committed,
73.1493 + ** set the change counter.
73.1494 + */
73.1495 + if( p->changeCntOn && p->pc>=0 ){
73.1496 + if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
73.1497 + sqlite3VdbeSetChanges(db, p->nChange);
73.1498 + }else{
73.1499 + sqlite3VdbeSetChanges(db, 0);
73.1500 + }
73.1501 + p->nChange = 0;
73.1502 + }
73.1503 +
73.1504 + /* Rollback or commit any schema changes that occurred. */
73.1505 + if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
73.1506 + sqlite3ResetInternalSchema(db, 0);
73.1507 + db->flags = (db->flags | SQLITE_InternChanges);
73.1508 + }
73.1509 + }
73.1510 +
73.1511 + /* We have successfully halted and closed the VM. Record this fact. */
73.1512 + if( p->pc>=0 ){
73.1513 + db->activeVdbeCnt--;
73.1514 + }
73.1515 + p->magic = VDBE_MAGIC_HALT;
73.1516 + checkActiveVdbeCnt(db);
73.1517 +
73.1518 + return SQLITE_OK;
73.1519 +}
73.1520 +
73.1521 +/*
73.1522 +** Each VDBE holds the result of the most recent sqlite3_step() call
73.1523 +** in p->rc. This routine sets that result back to SQLITE_OK.
73.1524 +*/
73.1525 +void sqlite3VdbeResetStepResult(Vdbe *p){
73.1526 + p->rc = SQLITE_OK;
73.1527 +}
73.1528 +
73.1529 +/*
73.1530 +** Clean up a VDBE after execution but do not delete the VDBE just yet.
73.1531 +** Write any error messages into *pzErrMsg. Return the result code.
73.1532 +**
73.1533 +** After this routine is run, the VDBE should be ready to be executed
73.1534 +** again.
73.1535 +**
73.1536 +** To look at it another way, this routine resets the state of the
73.1537 +** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
73.1538 +** VDBE_MAGIC_INIT.
73.1539 +*/
73.1540 +int sqlite3VdbeReset(Vdbe *p){
73.1541 + sqlite3 *db;
73.1542 + db = p->db;
73.1543 +
73.1544 + /* If the VM did not run to completion or if it encountered an
73.1545 + ** error, then it might not have been halted properly. So halt
73.1546 + ** it now.
73.1547 + */
73.1548 + sqlite3SafetyOn(db);
73.1549 + sqlite3VdbeHalt(p);
73.1550 + sqlite3SafetyOff(db);
73.1551 +
73.1552 + /* If the VDBE has be run even partially, then transfer the error code
73.1553 + ** and error message from the VDBE into the main database structure. But
73.1554 + ** if the VDBE has just been set to run but has not actually executed any
73.1555 + ** instructions yet, leave the main database error information unchanged.
73.1556 + */
73.1557 + if( p->pc>=0 ){
73.1558 + if( p->zErrMsg ){
73.1559 + sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, sqlite3FreeX);
73.1560 + db->errCode = p->rc;
73.1561 + p->zErrMsg = 0;
73.1562 + }else if( p->rc ){
73.1563 + sqlite3Error(db, p->rc, 0);
73.1564 + }else{
73.1565 + sqlite3Error(db, SQLITE_OK, 0);
73.1566 + }
73.1567 + }else if( p->rc && p->expired ){
73.1568 + /* The expired flag was set on the VDBE before the first call
73.1569 + ** to sqlite3_step(). For consistency (since sqlite3_step() was
73.1570 + ** called), set the database error in this case as well.
73.1571 + */
73.1572 + sqlite3Error(db, p->rc, 0);
73.1573 + }
73.1574 +
73.1575 + /* Reclaim all memory used by the VDBE
73.1576 + */
73.1577 + Cleanup(p);
73.1578 +
73.1579 + /* Save profiling information from this VDBE run.
73.1580 + */
73.1581 + assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || !p->aStack );
73.1582 +#ifdef VDBE_PROFILE
73.1583 + {
73.1584 + FILE *out = fopen("vdbe_profile.out", "a");
73.1585 + if( out ){
73.1586 + int i;
73.1587 + fprintf(out, "---- ");
73.1588 + for(i=0; i<p->nOp; i++){
73.1589 + fprintf(out, "%02x", p->aOp[i].opcode);
73.1590 + }
73.1591 + fprintf(out, "\n");
73.1592 + for(i=0; i<p->nOp; i++){
73.1593 + fprintf(out, "%6d %10lld %8lld ",
73.1594 + p->aOp[i].cnt,
73.1595 + p->aOp[i].cycles,
73.1596 + p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
73.1597 + );
73.1598 + sqlite3VdbePrintOp(out, i, &p->aOp[i]);
73.1599 + }
73.1600 + fclose(out);
73.1601 + }
73.1602 + }
73.1603 +#endif
73.1604 + p->magic = VDBE_MAGIC_INIT;
73.1605 + p->aborted = 0;
73.1606 + if( p->rc==SQLITE_SCHEMA ){
73.1607 + sqlite3ResetInternalSchema(db, 0);
73.1608 + }
73.1609 + return p->rc & db->errMask;
73.1610 +}
73.1611 +
73.1612 +/*
73.1613 +** Clean up and delete a VDBE after execution. Return an integer which is
73.1614 +** the result code. Write any error message text into *pzErrMsg.
73.1615 +*/
73.1616 +int sqlite3VdbeFinalize(Vdbe *p){
73.1617 + int rc = SQLITE_OK;
73.1618 + if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
73.1619 + rc = sqlite3VdbeReset(p);
73.1620 + assert( (rc & p->db->errMask)==rc );
73.1621 + }else if( p->magic!=VDBE_MAGIC_INIT ){
73.1622 + return SQLITE_MISUSE;
73.1623 + }
73.1624 + sqlite3VdbeDelete(p);
73.1625 + return rc;
73.1626 +}
73.1627 +
73.1628 +/*
73.1629 +** Call the destructor for each auxdata entry in pVdbeFunc for which
73.1630 +** the corresponding bit in mask is clear. Auxdata entries beyond 31
73.1631 +** are always destroyed. To destroy all auxdata entries, call this
73.1632 +** routine with mask==0.
73.1633 +*/
73.1634 +void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
73.1635 + int i;
73.1636 + for(i=0; i<pVdbeFunc->nAux; i++){
73.1637 + struct AuxData *pAux = &pVdbeFunc->apAux[i];
73.1638 + if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
73.1639 + if( pAux->xDelete ){
73.1640 + pAux->xDelete(pAux->pAux);
73.1641 + }
73.1642 + pAux->pAux = 0;
73.1643 + }
73.1644 + }
73.1645 +}
73.1646 +
73.1647 +/*
73.1648 +** Delete an entire VDBE.
73.1649 +*/
73.1650 +void sqlite3VdbeDelete(Vdbe *p){
73.1651 + int i;
73.1652 + if( p==0 ) return;
73.1653 + Cleanup(p);
73.1654 + if( p->pPrev ){
73.1655 + p->pPrev->pNext = p->pNext;
73.1656 + }else{
73.1657 + assert( p->db->pVdbe==p );
73.1658 + p->db->pVdbe = p->pNext;
73.1659 + }
73.1660 + if( p->pNext ){
73.1661 + p->pNext->pPrev = p->pPrev;
73.1662 + }
73.1663 + if( p->aOp ){
73.1664 + for(i=0; i<p->nOp; i++){
73.1665 + Op *pOp = &p->aOp[i];
73.1666 + freeP3(pOp->p3type, pOp->p3);
73.1667 + }
73.1668 + sqliteFree(p->aOp);
73.1669 + }
73.1670 + releaseMemArray(p->aVar, p->nVar);
73.1671 + sqliteFree(p->aLabel);
73.1672 + sqliteFree(p->aStack);
73.1673 + releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
73.1674 + sqliteFree(p->aColName);
73.1675 + sqliteFree(p->zSql);
73.1676 + p->magic = VDBE_MAGIC_DEAD;
73.1677 + sqliteFree(p);
73.1678 +}
73.1679 +
73.1680 +/*
73.1681 +** If a MoveTo operation is pending on the given cursor, then do that
73.1682 +** MoveTo now. Return an error code. If no MoveTo is pending, this
73.1683 +** routine does nothing and returns SQLITE_OK.
73.1684 +*/
73.1685 +int sqlite3VdbeCursorMoveto(Cursor *p){
73.1686 + if( p->deferredMoveto ){
73.1687 + int res, rc;
73.1688 +#ifdef SQLITE_TEST
73.1689 + extern int sqlite3_search_count;
73.1690 +#endif
73.1691 + assert( p->isTable );
73.1692 + rc = sqlite3BtreeMoveto(p->pCursor, 0, p->movetoTarget, 0, &res);
73.1693 + if( rc ) return rc;
73.1694 + *p->pIncrKey = 0;
73.1695 + p->lastRowid = keyToInt(p->movetoTarget);
73.1696 + p->rowidIsValid = res==0;
73.1697 + if( res<0 ){
73.1698 + rc = sqlite3BtreeNext(p->pCursor, &res);
73.1699 + if( rc ) return rc;
73.1700 + }
73.1701 +#ifdef SQLITE_TEST
73.1702 + sqlite3_search_count++;
73.1703 +#endif
73.1704 + p->deferredMoveto = 0;
73.1705 + p->cacheStatus = CACHE_STALE;
73.1706 + }
73.1707 + return SQLITE_OK;
73.1708 +}
73.1709 +
73.1710 +/*
73.1711 +** The following functions:
73.1712 +**
73.1713 +** sqlite3VdbeSerialType()
73.1714 +** sqlite3VdbeSerialTypeLen()
73.1715 +** sqlite3VdbeSerialRead()
73.1716 +** sqlite3VdbeSerialLen()
73.1717 +** sqlite3VdbeSerialWrite()
73.1718 +**
73.1719 +** encapsulate the code that serializes values for storage in SQLite
73.1720 +** data and index records. Each serialized value consists of a
73.1721 +** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
73.1722 +** integer, stored as a varint.
73.1723 +**
73.1724 +** In an SQLite index record, the serial type is stored directly before
73.1725 +** the blob of data that it corresponds to. In a table record, all serial
73.1726 +** types are stored at the start of the record, and the blobs of data at
73.1727 +** the end. Hence these functions allow the caller to handle the
73.1728 +** serial-type and data blob seperately.
73.1729 +**
73.1730 +** The following table describes the various storage classes for data:
73.1731 +**
73.1732 +** serial type bytes of data type
73.1733 +** -------------- --------------- ---------------
73.1734 +** 0 0 NULL
73.1735 +** 1 1 signed integer
73.1736 +** 2 2 signed integer
73.1737 +** 3 3 signed integer
73.1738 +** 4 4 signed integer
73.1739 +** 5 6 signed integer
73.1740 +** 6 8 signed integer
73.1741 +** 7 8 IEEE float
73.1742 +** 8 0 Integer constant 0
73.1743 +** 9 0 Integer constant 1
73.1744 +** 10,11 reserved for expansion
73.1745 +** N>=12 and even (N-12)/2 BLOB
73.1746 +** N>=13 and odd (N-13)/2 text
73.1747 +**
73.1748 +** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
73.1749 +** of SQLite will not understand those serial types.
73.1750 +*/
73.1751 +
73.1752 +/*
73.1753 +** Return the serial-type for the value stored in pMem.
73.1754 +*/
73.1755 +u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
73.1756 + int flags = pMem->flags;
73.1757 + int n;
73.1758 +
73.1759 + if( flags&MEM_Null ){
73.1760 + return 0;
73.1761 + }
73.1762 + if( flags&MEM_Int ){
73.1763 + /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
73.1764 +# define MAX_6BYTE ((((i64)0x00001000)<<32)-1)
73.1765 + i64 i = pMem->u.i;
73.1766 + u64 u;
73.1767 + if( file_format>=4 && (i&1)==i ){
73.1768 + return 8+i;
73.1769 + }
73.1770 + u = i<0 ? -i : i;
73.1771 + if( u<=127 ) return 1;
73.1772 + if( u<=32767 ) return 2;
73.1773 + if( u<=8388607 ) return 3;
73.1774 + if( u<=2147483647 ) return 4;
73.1775 + if( u<=MAX_6BYTE ) return 5;
73.1776 + return 6;
73.1777 + }
73.1778 + if( flags&MEM_Real ){
73.1779 + return 7;
73.1780 + }
73.1781 + assert( flags&(MEM_Str|MEM_Blob) );
73.1782 + n = pMem->n;
73.1783 + if( flags & MEM_Zero ){
73.1784 + n += pMem->u.i;
73.1785 + }
73.1786 + assert( n>=0 );
73.1787 + return ((n*2) + 12 + ((flags&MEM_Str)!=0));
73.1788 +}
73.1789 +
73.1790 +/*
73.1791 +** Return the length of the data corresponding to the supplied serial-type.
73.1792 +*/
73.1793 +int sqlite3VdbeSerialTypeLen(u32 serial_type){
73.1794 + if( serial_type>=12 ){
73.1795 + return (serial_type-12)/2;
73.1796 + }else{
73.1797 + static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
73.1798 + return aSize[serial_type];
73.1799 + }
73.1800 +}
73.1801 +
73.1802 +/*
73.1803 +** If we are on an architecture with mixed-endian floating
73.1804 +** points (ex: ARM7) then swap the lower 4 bytes with the
73.1805 +** upper 4 bytes. Return the result.
73.1806 +**
73.1807 +** For most architectures, this is a no-op.
73.1808 +**
73.1809 +** (later): It is reported to me that the mixed-endian problem
73.1810 +** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
73.1811 +** that early versions of GCC stored the two words of a 64-bit
73.1812 +** float in the wrong order. And that error has been propagated
73.1813 +** ever since. The blame is not necessarily with GCC, though.
73.1814 +** GCC might have just copying the problem from a prior compiler.
73.1815 +** I am also told that newer versions of GCC that follow a different
73.1816 +** ABI get the byte order right.
73.1817 +**
73.1818 +** Developers using SQLite on an ARM7 should compile and run their
73.1819 +** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
73.1820 +** enabled, some asserts below will ensure that the byte order of
73.1821 +** floating point values is correct.
73.1822 +*/
73.1823 +#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
73.1824 +static double floatSwap(double in){
73.1825 + union {
73.1826 + double r;
73.1827 + u32 i[2];
73.1828 + } u;
73.1829 + u32 t;
73.1830 +
73.1831 + u.r = in;
73.1832 + t = u.i[0];
73.1833 + u.i[0] = u.i[1];
73.1834 + u.i[1] = t;
73.1835 + return u.r;
73.1836 +}
73.1837 +# define swapMixedEndianFloat(X) X = floatSwap(X)
73.1838 +#else
73.1839 +# define swapMixedEndianFloat(X)
73.1840 +#endif
73.1841 +
73.1842 +/*
73.1843 +** Write the serialized data blob for the value stored in pMem into
73.1844 +** buf. It is assumed that the caller has allocated sufficient space.
73.1845 +** Return the number of bytes written.
73.1846 +**
73.1847 +** nBuf is the amount of space left in buf[]. nBuf must always be
73.1848 +** large enough to hold the entire field. Except, if the field is
73.1849 +** a blob with a zero-filled tail, then buf[] might be just the right
73.1850 +** size to hold everything except for the zero-filled tail. If buf[]
73.1851 +** is only big enough to hold the non-zero prefix, then only write that
73.1852 +** prefix into buf[]. But if buf[] is large enough to hold both the
73.1853 +** prefix and the tail then write the prefix and set the tail to all
73.1854 +** zeros.
73.1855 +**
73.1856 +** Return the number of bytes actually written into buf[]. The number
73.1857 +** of bytes in the zero-filled tail is included in the return value only
73.1858 +** if those bytes were zeroed in buf[].
73.1859 +*/
73.1860 +int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
73.1861 + u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
73.1862 + int len;
73.1863 +
73.1864 + /* Integer and Real */
73.1865 + if( serial_type<=7 && serial_type>0 ){
73.1866 + u64 v;
73.1867 + int i;
73.1868 + if( serial_type==7 ){
73.1869 + assert( sizeof(v)==sizeof(pMem->r) );
73.1870 + swapMixedEndianFloat(pMem->r);
73.1871 + memcpy(&v, &pMem->r, sizeof(v));
73.1872 + }else{
73.1873 + v = pMem->u.i;
73.1874 + }
73.1875 + len = i = sqlite3VdbeSerialTypeLen(serial_type);
73.1876 + assert( len<=nBuf );
73.1877 + while( i-- ){
73.1878 + buf[i] = (v&0xFF);
73.1879 + v >>= 8;
73.1880 + }
73.1881 + return len;
73.1882 + }
73.1883 +
73.1884 + /* String or blob */
73.1885 + if( serial_type>=12 ){
73.1886 + assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.i:0)
73.1887 + == sqlite3VdbeSerialTypeLen(serial_type) );
73.1888 + assert( pMem->n<=nBuf );
73.1889 + len = pMem->n;
73.1890 + memcpy(buf, pMem->z, len);
73.1891 + if( pMem->flags & MEM_Zero ){
73.1892 + len += pMem->u.i;
73.1893 + if( len>nBuf ){
73.1894 + len = nBuf;
73.1895 + }
73.1896 + memset(&buf[pMem->n], 0, len-pMem->n);
73.1897 + }
73.1898 + return len;
73.1899 + }
73.1900 +
73.1901 + /* NULL or constants 0 or 1 */
73.1902 + return 0;
73.1903 +}
73.1904 +
73.1905 +/*
73.1906 +** Deserialize the data blob pointed to by buf as serial type serial_type
73.1907 +** and store the result in pMem. Return the number of bytes read.
73.1908 +*/
73.1909 +int sqlite3VdbeSerialGet(
73.1910 + const unsigned char *buf, /* Buffer to deserialize from */
73.1911 + u32 serial_type, /* Serial type to deserialize */
73.1912 + Mem *pMem /* Memory cell to write value into */
73.1913 +){
73.1914 + switch( serial_type ){
73.1915 + case 10: /* Reserved for future use */
73.1916 + case 11: /* Reserved for future use */
73.1917 + case 0: { /* NULL */
73.1918 + pMem->flags = MEM_Null;
73.1919 + break;
73.1920 + }
73.1921 + case 1: { /* 1-byte signed integer */
73.1922 + pMem->u.i = (signed char)buf[0];
73.1923 + pMem->flags = MEM_Int;
73.1924 + return 1;
73.1925 + }
73.1926 + case 2: { /* 2-byte signed integer */
73.1927 + pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
73.1928 + pMem->flags = MEM_Int;
73.1929 + return 2;
73.1930 + }
73.1931 + case 3: { /* 3-byte signed integer */
73.1932 + pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
73.1933 + pMem->flags = MEM_Int;
73.1934 + return 3;
73.1935 + }
73.1936 + case 4: { /* 4-byte signed integer */
73.1937 + pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
73.1938 + pMem->flags = MEM_Int;
73.1939 + return 4;
73.1940 + }
73.1941 + case 5: { /* 6-byte signed integer */
73.1942 + u64 x = (((signed char)buf[0])<<8) | buf[1];
73.1943 + u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
73.1944 + x = (x<<32) | y;
73.1945 + pMem->u.i = *(i64*)&x;
73.1946 + pMem->flags = MEM_Int;
73.1947 + return 6;
73.1948 + }
73.1949 + case 6: /* 8-byte signed integer */
73.1950 + case 7: { /* IEEE floating point */
73.1951 + u64 x;
73.1952 + u32 y;
73.1953 +#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
73.1954 + /* Verify that integers and floating point values use the same
73.1955 + ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
73.1956 + ** defined that 64-bit floating point values really are mixed
73.1957 + ** endian.
73.1958 + */
73.1959 + static const u64 t1 = ((u64)0x3ff00000)<<32;
73.1960 + static const double r1 = 1.0;
73.1961 + double r2 = r1;
73.1962 + swapMixedEndianFloat(r2);
73.1963 + assert( sizeof(r2)==sizeof(t1) && memcmp(&r2, &t1, sizeof(r1))==0 );
73.1964 +#endif
73.1965 +
73.1966 + x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
73.1967 + y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
73.1968 + x = (x<<32) | y;
73.1969 + if( serial_type==6 ){
73.1970 + pMem->u.i = *(i64*)&x;
73.1971 + pMem->flags = MEM_Int;
73.1972 + }else{
73.1973 + assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
73.1974 + memcpy(&pMem->r, &x, sizeof(x));
73.1975 + swapMixedEndianFloat(pMem->r);
73.1976 + pMem->flags = MEM_Real;
73.1977 + }
73.1978 + return 8;
73.1979 + }
73.1980 + case 8: /* Integer 0 */
73.1981 + case 9: { /* Integer 1 */
73.1982 + pMem->u.i = serial_type-8;
73.1983 + pMem->flags = MEM_Int;
73.1984 + return 0;
73.1985 + }
73.1986 + default: {
73.1987 + int len = (serial_type-12)/2;
73.1988 + pMem->z = (char *)buf;
73.1989 + pMem->n = len;
73.1990 + pMem->xDel = 0;
73.1991 + if( serial_type&0x01 ){
73.1992 + pMem->flags = MEM_Str | MEM_Ephem;
73.1993 + }else{
73.1994 + pMem->flags = MEM_Blob | MEM_Ephem;
73.1995 + }
73.1996 + return len;
73.1997 + }
73.1998 + }
73.1999 + return 0;
73.2000 +}
73.2001 +
73.2002 +/*
73.2003 +** The header of a record consists of a sequence variable-length integers.
73.2004 +** These integers are almost always small and are encoded as a single byte.
73.2005 +** The following macro takes advantage this fact to provide a fast decode
73.2006 +** of the integers in a record header. It is faster for the common case
73.2007 +** where the integer is a single byte. It is a little slower when the
73.2008 +** integer is two or more bytes. But overall it is faster.
73.2009 +**
73.2010 +** The following expressions are equivalent:
73.2011 +**
73.2012 +** x = sqlite3GetVarint32( A, &B );
73.2013 +**
73.2014 +** x = GetVarint( A, B );
73.2015 +**
73.2016 +*/
73.2017 +#define GetVarint(A,B) ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
73.2018 +
73.2019 +/*
73.2020 +** This function compares the two table rows or index records specified by
73.2021 +** {nKey1, pKey1} and {nKey2, pKey2}, returning a negative, zero
73.2022 +** or positive integer if {nKey1, pKey1} is less than, equal to or
73.2023 +** greater than {nKey2, pKey2}. Both Key1 and Key2 must be byte strings
73.2024 +** composed by the OP_MakeRecord opcode of the VDBE.
73.2025 +*/
73.2026 +int sqlite3VdbeRecordCompare(
73.2027 + void *userData,
73.2028 + int nKey1, const void *pKey1,
73.2029 + int nKey2, const void *pKey2
73.2030 +){
73.2031 + KeyInfo *pKeyInfo = (KeyInfo*)userData;
73.2032 + u32 d1, d2; /* Offset into aKey[] of next data element */
73.2033 + u32 idx1, idx2; /* Offset into aKey[] of next header element */
73.2034 + u32 szHdr1, szHdr2; /* Number of bytes in header */
73.2035 + int i = 0;
73.2036 + int nField;
73.2037 + int rc = 0;
73.2038 + const unsigned char *aKey1 = (const unsigned char *)pKey1;
73.2039 + const unsigned char *aKey2 = (const unsigned char *)pKey2;
73.2040 +
73.2041 + Mem mem1;
73.2042 + Mem mem2;
73.2043 + mem1.enc = pKeyInfo->enc;
73.2044 + mem2.enc = pKeyInfo->enc;
73.2045 +
73.2046 + idx1 = GetVarint(aKey1, szHdr1);
73.2047 + d1 = szHdr1;
73.2048 + idx2 = GetVarint(aKey2, szHdr2);
73.2049 + d2 = szHdr2;
73.2050 + nField = pKeyInfo->nField;
73.2051 + while( idx1<szHdr1 && idx2<szHdr2 ){
73.2052 + u32 serial_type1;
73.2053 + u32 serial_type2;
73.2054 +
73.2055 + /* Read the serial types for the next element in each key. */
73.2056 + idx1 += GetVarint( aKey1+idx1, serial_type1 );
73.2057 + if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
73.2058 + idx2 += GetVarint( aKey2+idx2, serial_type2 );
73.2059 + if( d2>=nKey2 && sqlite3VdbeSerialTypeLen(serial_type2)>0 ) break;
73.2060 +
73.2061 + /* Extract the values to be compared.
73.2062 + */
73.2063 + d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
73.2064 + d2 += sqlite3VdbeSerialGet(&aKey2[d2], serial_type2, &mem2);
73.2065 +
73.2066 + /* Do the comparison
73.2067 + */
73.2068 + rc = sqlite3MemCompare(&mem1, &mem2, i<nField ? pKeyInfo->aColl[i] : 0);
73.2069 + if( mem1.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem1);
73.2070 + if( mem2.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem2);
73.2071 + if( rc!=0 ){
73.2072 + break;
73.2073 + }
73.2074 + i++;
73.2075 + }
73.2076 +
73.2077 + /* One of the keys ran out of fields, but all the fields up to that point
73.2078 + ** were equal. If the incrKey flag is true, then the second key is
73.2079 + ** treated as larger.
73.2080 + */
73.2081 + if( rc==0 ){
73.2082 + if( pKeyInfo->incrKey ){
73.2083 + rc = -1;
73.2084 + }else if( d1<nKey1 ){
73.2085 + rc = 1;
73.2086 + }else if( d2<nKey2 ){
73.2087 + rc = -1;
73.2088 + }
73.2089 + }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
73.2090 + && pKeyInfo->aSortOrder[i] ){
73.2091 + rc = -rc;
73.2092 + }
73.2093 +
73.2094 + return rc;
73.2095 +}
73.2096 +
73.2097 +/*
73.2098 +** The argument is an index entry composed using the OP_MakeRecord opcode.
73.2099 +** The last entry in this record should be an integer (specifically
73.2100 +** an integer rowid). This routine returns the number of bytes in
73.2101 +** that integer.
73.2102 +*/
73.2103 +int sqlite3VdbeIdxRowidLen(const u8 *aKey){
73.2104 + u32 szHdr; /* Size of the header */
73.2105 + u32 typeRowid; /* Serial type of the rowid */
73.2106 +
73.2107 + sqlite3GetVarint32(aKey, &szHdr);
73.2108 + sqlite3GetVarint32(&aKey[szHdr-1], &typeRowid);
73.2109 + return sqlite3VdbeSerialTypeLen(typeRowid);
73.2110 +}
73.2111 +
73.2112 +
73.2113 +/*
73.2114 +** pCur points at an index entry created using the OP_MakeRecord opcode.
73.2115 +** Read the rowid (the last field in the record) and store it in *rowid.
73.2116 +** Return SQLITE_OK if everything works, or an error code otherwise.
73.2117 +*/
73.2118 +int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
73.2119 + i64 nCellKey = 0;
73.2120 + int rc;
73.2121 + u32 szHdr; /* Size of the header */
73.2122 + u32 typeRowid; /* Serial type of the rowid */
73.2123 + u32 lenRowid; /* Size of the rowid */
73.2124 + Mem m, v;
73.2125 +
73.2126 + sqlite3BtreeKeySize(pCur, &nCellKey);
73.2127 + if( nCellKey<=0 ){
73.2128 + return SQLITE_CORRUPT_BKPT;
73.2129 + }
73.2130 + rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
73.2131 + if( rc ){
73.2132 + return rc;
73.2133 + }
73.2134 + sqlite3GetVarint32((u8*)m.z, &szHdr);
73.2135 + sqlite3GetVarint32((u8*)&m.z[szHdr-1], &typeRowid);
73.2136 + lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
73.2137 + sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
73.2138 + *rowid = v.u.i;
73.2139 + sqlite3VdbeMemRelease(&m);
73.2140 + return SQLITE_OK;
73.2141 +}
73.2142 +
73.2143 +/*
73.2144 +** Compare the key of the index entry that cursor pC is point to against
73.2145 +** the key string in pKey (of length nKey). Write into *pRes a number
73.2146 +** that is negative, zero, or positive if pC is less than, equal to,
73.2147 +** or greater than pKey. Return SQLITE_OK on success.
73.2148 +**
73.2149 +** pKey is either created without a rowid or is truncated so that it
73.2150 +** omits the rowid at the end. The rowid at the end of the index entry
73.2151 +** is ignored as well.
73.2152 +*/
73.2153 +int sqlite3VdbeIdxKeyCompare(
73.2154 + Cursor *pC, /* The cursor to compare against */
73.2155 + int nKey, const u8 *pKey, /* The key to compare */
73.2156 + int *res /* Write the comparison result here */
73.2157 +){
73.2158 + i64 nCellKey = 0;
73.2159 + int rc;
73.2160 + BtCursor *pCur = pC->pCursor;
73.2161 + int lenRowid;
73.2162 + Mem m;
73.2163 +
73.2164 + sqlite3BtreeKeySize(pCur, &nCellKey);
73.2165 + if( nCellKey<=0 ){
73.2166 + *res = 0;
73.2167 + return SQLITE_OK;
73.2168 + }
73.2169 + rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
73.2170 + if( rc ){
73.2171 + return rc;
73.2172 + }
73.2173 + lenRowid = sqlite3VdbeIdxRowidLen((u8*)m.z);
73.2174 + *res = sqlite3VdbeRecordCompare(pC->pKeyInfo, m.n-lenRowid, m.z, nKey, pKey);
73.2175 + sqlite3VdbeMemRelease(&m);
73.2176 + return SQLITE_OK;
73.2177 +}
73.2178 +
73.2179 +/*
73.2180 +** This routine sets the value to be returned by subsequent calls to
73.2181 +** sqlite3_changes() on the database handle 'db'.
73.2182 +*/
73.2183 +void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
73.2184 + db->nChange = nChange;
73.2185 + db->nTotalChange += nChange;
73.2186 +}
73.2187 +
73.2188 +/*
73.2189 +** Set a flag in the vdbe to update the change counter when it is finalised
73.2190 +** or reset.
73.2191 +*/
73.2192 +void sqlite3VdbeCountChanges(Vdbe *v){
73.2193 + v->changeCntOn = 1;
73.2194 +}
73.2195 +
73.2196 +/*
73.2197 +** Mark every prepared statement associated with a database connection
73.2198 +** as expired.
73.2199 +**
73.2200 +** An expired statement means that recompilation of the statement is
73.2201 +** recommend. Statements expire when things happen that make their
73.2202 +** programs obsolete. Removing user-defined functions or collating
73.2203 +** sequences, or changing an authorization function are the types of
73.2204 +** things that make prepared statements obsolete.
73.2205 +*/
73.2206 +void sqlite3ExpirePreparedStatements(sqlite3 *db){
73.2207 + Vdbe *p;
73.2208 + for(p = db->pVdbe; p; p=p->pNext){
73.2209 + p->expired = 1;
73.2210 + }
73.2211 +}
73.2212 +
73.2213 +/*
73.2214 +** Return the database associated with the Vdbe.
73.2215 +*/
73.2216 +sqlite3 *sqlite3VdbeDb(Vdbe *v){
73.2217 + return v->db;
73.2218 +}
74.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
74.2 +++ b/extensions/sqlite/sqlite-source/vdbeblob.c Sun Jul 29 01:15:31 2007 +0000
74.3 @@ -0,0 +1,310 @@
74.4 +/*
74.5 +** 2007 May 1
74.6 +**
74.7 +** The author disclaims copyright to this source code. In place of
74.8 +** a legal notice, here is a blessing:
74.9 +**
74.10 +** May you do good and not evil.
74.11 +** May you find forgiveness for yourself and forgive others.
74.12 +** May you share freely, never taking more than you give.
74.13 +**
74.14 +*************************************************************************
74.15 +**
74.16 +** This file contains code used to implement incremental BLOB I/O.
74.17 +**
74.18 +** $Id$
74.19 +*/
74.20 +
74.21 +#include "sqliteInt.h"
74.22 +#include "vdbeInt.h"
74.23 +
74.24 +#ifndef SQLITE_OMIT_INCRBLOB
74.25 +
74.26 +/*
74.27 +** Valid sqlite3_blob* handles point to Incrblob structures.
74.28 +*/
74.29 +typedef struct Incrblob Incrblob;
74.30 +struct Incrblob {
74.31 + int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
74.32 + int nByte; /* Size of open blob, in bytes */
74.33 + int iOffset; /* Byte offset of blob in cursor data */
74.34 + BtCursor *pCsr; /* Cursor pointing at blob row */
74.35 + sqlite3_stmt *pStmt; /* Statement holding cursor open */
74.36 +};
74.37 +
74.38 +/*
74.39 +** Open a blob handle.
74.40 +*/
74.41 +int sqlite3_blob_open(
74.42 + sqlite3* db, /* The database connection */
74.43 + const char *zDb, /* The attached database containing the blob */
74.44 + const char *zTable, /* The table containing the blob */
74.45 + const char *zColumn, /* The column containing the blob */
74.46 + sqlite_int64 iRow, /* The row containing the glob */
74.47 + int flags, /* True -> read/write access, false -> read-only */
74.48 + sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
74.49 +){
74.50 + int nAttempt = 0;
74.51 + int iCol; /* Index of zColumn in row-record */
74.52 +
74.53 + /* This VDBE program seeks a btree cursor to the identified
74.54 + ** db/table/row entry. The reason for using a vdbe program instead
74.55 + ** of writing code to use the b-tree layer directly is that the
74.56 + ** vdbe program will take advantage of the various transaction,
74.57 + ** locking and error handling infrastructure built into the vdbe.
74.58 + **
74.59 + ** After seeking the cursor, the vdbe executes an OP_Callback.
74.60 + ** Code external to the Vdbe then "borrows" the b-tree cursor and
74.61 + ** uses it to implement the blob_read(), blob_write() and
74.62 + ** blob_bytes() functions.
74.63 + **
74.64 + ** The sqlite3_blob_close() function finalizes the vdbe program,
74.65 + ** which closes the b-tree cursor and (possibly) commits the
74.66 + ** transaction.
74.67 + */
74.68 + static const VdbeOpList openBlob[] = {
74.69 + {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
74.70 + {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
74.71 + {OP_Integer, 0, 0, 0}, /* 2: Database number */
74.72 +
74.73 + /* One of the following two instructions is replaced by an
74.74 + ** OP_Noop before exection.
74.75 + */
74.76 + {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
74.77 + {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
74.78 + {OP_SetNumColumns, 0, 0, 0}, /* 5: Num cols for cursor */
74.79 +
74.80 + {OP_Variable, 1, 0, 0}, /* 6: Push the rowid to the stack */
74.81 + {OP_NotExists, 0, 10, 0}, /* 7: Seek the cursor */
74.82 + {OP_Column, 0, 0, 0}, /* 8 */
74.83 + {OP_Callback, 0, 0, 0}, /* 9 */
74.84 + {OP_Close, 0, 0, 0}, /* 10 */
74.85 + {OP_Halt, 0, 0, 0}, /* 11 */
74.86 + };
74.87 +
74.88 + Vdbe *v = 0;
74.89 + int rc = SQLITE_OK;
74.90 + char zErr[128];
74.91 +
74.92 + zErr[0] = 0;
74.93 + do {
74.94 + Parse sParse;
74.95 + Table *pTab;
74.96 +
74.97 + memset(&sParse, 0, sizeof(Parse));
74.98 + sParse.db = db;
74.99 +
74.100 + rc = sqlite3SafetyOn(db);
74.101 + if( rc!=SQLITE_OK ){
74.102 + return rc;
74.103 + }
74.104 +
74.105 + pTab = sqlite3LocateTable(&sParse, zTable, zDb);
74.106 + if( !pTab ){
74.107 + if( sParse.zErrMsg ){
74.108 + sqlite3_snprintf(sizeof(zErr), zErr, "%s", sParse.zErrMsg);
74.109 + }
74.110 + sqliteFree(sParse.zErrMsg);
74.111 + rc = SQLITE_ERROR;
74.112 + sqlite3SafetyOff(db);
74.113 + goto blob_open_out;
74.114 + }
74.115 +
74.116 + /* Now search pTab for the exact column. */
74.117 + for(iCol=0; iCol < pTab->nCol; iCol++) {
74.118 + if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
74.119 + break;
74.120 + }
74.121 + }
74.122 + if( iCol==pTab->nCol ){
74.123 + sqlite3_snprintf(sizeof(zErr), zErr, "no such column: \"%s\"", zColumn);
74.124 + rc = SQLITE_ERROR;
74.125 + sqlite3SafetyOff(db);
74.126 + goto blob_open_out;
74.127 + }
74.128 +
74.129 + /* If the value is being opened for writing, check that the
74.130 + ** column is not indexed. It is against the rules to open an
74.131 + ** indexed column for writing.
74.132 + */
74.133 + if( flags ){
74.134 + Index *pIdx;
74.135 + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
74.136 + int j;
74.137 + for(j=0; j<pIdx->nColumn; j++){
74.138 + if( pIdx->aiColumn[j]==iCol ){
74.139 + sqlite3_snprintf(sizeof(zErr), zErr,
74.140 + "cannot open indexed column for writing");
74.141 + rc = SQLITE_ERROR;
74.142 + sqlite3SafetyOff(db);
74.143 + goto blob_open_out;
74.144 + }
74.145 + }
74.146 + }
74.147 + }
74.148 +
74.149 + v = sqlite3VdbeCreate(db);
74.150 + if( v ){
74.151 + int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74.152 + sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
74.153 +
74.154 + /* Configure the OP_Transaction */
74.155 + sqlite3VdbeChangeP1(v, 0, iDb);
74.156 + sqlite3VdbeChangeP2(v, 0, (flags ? 1 : 0));
74.157 +
74.158 + /* Configure the OP_VerifyCookie */
74.159 + sqlite3VdbeChangeP1(v, 1, iDb);
74.160 + sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
74.161 +
74.162 + /* Configure the db number pushed onto the stack */
74.163 + sqlite3VdbeChangeP1(v, 2, iDb);
74.164 +
74.165 + /* Remove either the OP_OpenWrite or OpenRead. Set the P2
74.166 + ** parameter of the other to pTab->tnum.
74.167 + */
74.168 + sqlite3VdbeChangeToNoop(v, (flags ? 3 : 4), 1);
74.169 + sqlite3VdbeChangeP2(v, (flags ? 4 : 3), pTab->tnum);
74.170 +
74.171 + /* Configure the OP_SetNumColumns. Configure the cursor to
74.172 + ** think that the table has one more column than it really
74.173 + ** does. An OP_Column to retrieve this imaginary column will
74.174 + ** always return an SQL NULL. This is useful because it means
74.175 + ** we can invoke OP_Column to fill in the vdbe cursors type
74.176 + ** and offset cache without causing any IO.
74.177 + */
74.178 + sqlite3VdbeChangeP2(v, 5, pTab->nCol+1);
74.179 + if( !sqlite3MallocFailed() ){
74.180 + sqlite3VdbeMakeReady(v, 1, 0, 1, 0);
74.181 + }
74.182 + }
74.183 +
74.184 + rc = sqlite3SafetyOff(db);
74.185 + if( rc!=SQLITE_OK || sqlite3MallocFailed() ){
74.186 + goto blob_open_out;
74.187 + }
74.188 +
74.189 + sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
74.190 + rc = sqlite3_step((sqlite3_stmt *)v);
74.191 + if( rc!=SQLITE_ROW ){
74.192 + nAttempt++;
74.193 + rc = sqlite3_finalize((sqlite3_stmt *)v);
74.194 + sqlite3_snprintf(sizeof(zErr), zErr, sqlite3_errmsg(db));
74.195 + v = 0;
74.196 + }
74.197 + } while( nAttempt<5 && rc==SQLITE_SCHEMA );
74.198 +
74.199 + if( rc==SQLITE_ROW ){
74.200 + /* The row-record has been opened successfully. Check that the
74.201 + ** column in question contains text or a blob. If it contains
74.202 + ** text, it is up to the caller to get the encoding right.
74.203 + */
74.204 + Incrblob *pBlob;
74.205 + u32 type = v->apCsr[0]->aType[iCol];
74.206 +
74.207 + if( type<12 ){
74.208 + sqlite3_snprintf(sizeof(zErr), zErr, "cannot open value of type %s",
74.209 + type==0?"null": type==7?"real": "integer"
74.210 + );
74.211 + rc = SQLITE_ERROR;
74.212 + goto blob_open_out;
74.213 + }
74.214 + pBlob = (Incrblob *)sqliteMalloc(sizeof(Incrblob));
74.215 + if( sqlite3MallocFailed() ){
74.216 + sqliteFree(pBlob);
74.217 + goto blob_open_out;
74.218 + }
74.219 + pBlob->flags = flags;
74.220 + pBlob->pCsr = v->apCsr[0]->pCursor;
74.221 + sqlite3BtreeCacheOverflow(pBlob->pCsr);
74.222 + pBlob->pStmt = (sqlite3_stmt *)v;
74.223 + pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
74.224 + pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
74.225 + *ppBlob = (sqlite3_blob *)pBlob;
74.226 + rc = SQLITE_OK;
74.227 + }else if( rc==SQLITE_OK ){
74.228 + sqlite3_snprintf(sizeof(zErr), zErr, "no such rowid: %lld", iRow);
74.229 + rc = SQLITE_ERROR;
74.230 + }
74.231 +
74.232 +blob_open_out:
74.233 + zErr[sizeof(zErr)-1] = '\0';
74.234 + if( rc!=SQLITE_OK || sqlite3MallocFailed() ){
74.235 + sqlite3_finalize((sqlite3_stmt *)v);
74.236 + }
74.237 + sqlite3Error(db, rc, (rc==SQLITE_OK?0:zErr));
74.238 + return sqlite3ApiExit(db, rc);
74.239 +}
74.240 +
74.241 +/*
74.242 +** Close a blob handle that was previously created using
74.243 +** sqlite3_blob_open().
74.244 +*/
74.245 +int sqlite3_blob_close(sqlite3_blob *pBlob){
74.246 + Incrblob *p = (Incrblob *)pBlob;
74.247 + sqlite3_stmt *pStmt = p->pStmt;
74.248 + sqliteFree(p);
74.249 + return sqlite3_finalize(pStmt);
74.250 +}
74.251 +
74.252 +
74.253 +static int blobReadWrite(
74.254 + sqlite3_blob *pBlob,
74.255 + void *z,
74.256 + int n,
74.257 + int iOffset,
74.258 + int (*xCall)(BtCursor*, u32, u32, void*)
74.259 +){
74.260 + int rc;
74.261 + Incrblob *p = (Incrblob *)pBlob;
74.262 + Vdbe *v = (Vdbe *)(p->pStmt);
74.263 + sqlite3 *db;
74.264 +
74.265 + /* If there is no statement handle, then the blob-handle has
74.266 + ** already been invalidated. Return SQLITE_ABORT in this case.
74.267 + */
74.268 + if( !v ) return SQLITE_ABORT;
74.269 +
74.270 + /* Request is out of range. Return a transient error. */
74.271 + if( (iOffset+n)>p->nByte ){
74.272 + return SQLITE_ERROR;
74.273 + }
74.274 +
74.275 + /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
74.276 + ** returned, clean-up the statement handle.
74.277 + */
74.278 + db = v->db;
74.279 + rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
74.280 + if( rc==SQLITE_ABORT ){
74.281 + sqlite3VdbeFinalize(v);
74.282 + p->pStmt = 0;
74.283 + }else{
74.284 + db->errCode = rc;
74.285 + v->rc = rc;
74.286 + }
74.287 +
74.288 + return sqlite3ApiExit(db, rc);
74.289 +}
74.290 +
74.291 +/*
74.292 +** Read data from a blob handle.
74.293 +*/
74.294 +int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
74.295 + return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
74.296 +}
74.297 +
74.298 +/*
74.299 +** Write data to a blob handle.
74.300 +*/
74.301 +int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
74.302 + return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
74.303 +}
74.304 +
74.305 +/*
74.306 +** Query a blob handle for the size of the data.
74.307 +*/
74.308 +int sqlite3_blob_bytes(sqlite3_blob *pBlob){
74.309 + Incrblob *p = (Incrblob *)pBlob;
74.310 + return p->nByte;
74.311 +}
74.312 +
74.313 +#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
75.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
75.2 +++ b/extensions/sqlite/sqlite-source/vdbefifo.c Sun Jul 29 01:15:31 2007 +0000
75.3 @@ -0,0 +1,114 @@
75.4 +/*
75.5 +** 2005 June 16
75.6 +**
75.7 +** The author disclaims copyright to this source code. In place of
75.8 +** a legal notice, here is a blessing:
75.9 +**
75.10 +** May you do good and not evil.
75.11 +** May you find forgiveness for yourself and forgive others.
75.12 +** May you share freely, never taking more than you give.
75.13 +**
75.14 +*************************************************************************
75.15 +** This file implements a FIFO queue of rowids used for processing
75.16 +** UPDATE and DELETE statements.
75.17 +*/
75.18 +#include "sqliteInt.h"
75.19 +#include "vdbeInt.h"
75.20 +
75.21 +/*
75.22 +** Allocate a new FifoPage and return a pointer to it. Return NULL if
75.23 +** we run out of memory. Leave space on the page for nEntry entries.
75.24 +*/
75.25 +static FifoPage *allocateFifoPage(int nEntry){
75.26 + FifoPage *pPage;
75.27 + if( nEntry>32767 ){
75.28 + nEntry = 32767;
75.29 + }
75.30 + pPage = sqliteMallocRaw( sizeof(FifoPage) + sizeof(i64)*(nEntry-1) );
75.31 + if( pPage ){
75.32 + pPage->nSlot = nEntry;
75.33 + pPage->iWrite = 0;
75.34 + pPage->iRead = 0;
75.35 + pPage->pNext = 0;
75.36 + }
75.37 + return pPage;
75.38 +}
75.39 +
75.40 +/*
75.41 +** Initialize a Fifo structure.
75.42 +*/
75.43 +void sqlite3VdbeFifoInit(Fifo *pFifo){
75.44 + memset(pFifo, 0, sizeof(*pFifo));
75.45 +}
75.46 +
75.47 +/*
75.48 +** Push a single 64-bit integer value into the Fifo. Return SQLITE_OK
75.49 +** normally. SQLITE_NOMEM is returned if we are unable to allocate
75.50 +** memory.
75.51 +*/
75.52 +int sqlite3VdbeFifoPush(Fifo *pFifo, i64 val){
75.53 + FifoPage *pPage;
75.54 + pPage = pFifo->pLast;
75.55 + if( pPage==0 ){
75.56 + pPage = pFifo->pLast = pFifo->pFirst = allocateFifoPage(20);
75.57 + if( pPage==0 ){
75.58 + return SQLITE_NOMEM;
75.59 + }
75.60 + }else if( pPage->iWrite>=pPage->nSlot ){
75.61 + pPage->pNext = allocateFifoPage(pFifo->nEntry);
75.62 + if( pPage->pNext==0 ){
75.63 + return SQLITE_NOMEM;
75.64 + }
75.65 + pPage = pFifo->pLast = pPage->pNext;
75.66 + }
75.67 + pPage->aSlot[pPage->iWrite++] = val;
75.68 + pFifo->nEntry++;
75.69 + return SQLITE_OK;
75.70 +}
75.71 +
75.72 +/*
75.73 +** Extract a single 64-bit integer value from the Fifo. The integer
75.74 +** extracted is the one least recently inserted. If the Fifo is empty
75.75 +** return SQLITE_DONE.
75.76 +*/
75.77 +int sqlite3VdbeFifoPop(Fifo *pFifo, i64 *pVal){
75.78 + FifoPage *pPage;
75.79 + if( pFifo->nEntry==0 ){
75.80 + return SQLITE_DONE;
75.81 + }
75.82 + assert( pFifo->nEntry>0 );
75.83 + pPage = pFifo->pFirst;
75.84 + assert( pPage!=0 );
75.85 + assert( pPage->iWrite>pPage->iRead );
75.86 + assert( pPage->iWrite<=pPage->nSlot );
75.87 + assert( pPage->iRead<pPage->nSlot );
75.88 + assert( pPage->iRead>=0 );
75.89 + *pVal = pPage->aSlot[pPage->iRead++];
75.90 + pFifo->nEntry--;
75.91 + if( pPage->iRead>=pPage->iWrite ){
75.92 + pFifo->pFirst = pPage->pNext;
75.93 + sqliteFree(pPage);
75.94 + if( pFifo->nEntry==0 ){
75.95 + assert( pFifo->pLast==pPage );
75.96 + pFifo->pLast = 0;
75.97 + }else{
75.98 + assert( pFifo->pFirst!=0 );
75.99 + }
75.100 + }else{
75.101 + assert( pFifo->nEntry>0 );
75.102 + }
75.103 + return SQLITE_OK;
75.104 +}
75.105 +
75.106 +/*
75.107 +** Delete all information from a Fifo object. Free all memory held
75.108 +** by the Fifo.
75.109 +*/
75.110 +void sqlite3VdbeFifoClear(Fifo *pFifo){
75.111 + FifoPage *pPage, *pNextPage;
75.112 + for(pPage=pFifo->pFirst; pPage; pPage=pNextPage){
75.113 + pNextPage = pPage->pNext;
75.114 + sqliteFree(pPage);
75.115 + }
75.116 + sqlite3VdbeFifoInit(pFifo);
75.117 +}
76.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
76.2 +++ b/extensions/sqlite/sqlite-source/vdbemem.c Sun Jul 29 01:15:31 2007 +0000
76.3 @@ -0,0 +1,991 @@
76.4 +/*
76.5 +** 2004 May 26
76.6 +**
76.7 +** The author disclaims copyright to this source code. In place of
76.8 +** a legal notice, here is a blessing:
76.9 +**
76.10 +** May you do good and not evil.
76.11 +** May you find forgiveness for yourself and forgive others.
76.12 +** May you share freely, never taking more than you give.
76.13 +**
76.14 +*************************************************************************
76.15 +**
76.16 +** This file contains code use to manipulate "Mem" structure. A "Mem"
76.17 +** stores a single value in the VDBE. Mem is an opaque structure visible
76.18 +** only within the VDBE. Interface routines refer to a Mem using the
76.19 +** name sqlite_value
76.20 +*/
76.21 +#include "sqliteInt.h"
76.22 +#include "os.h"
76.23 +#include <math.h>
76.24 +#include <ctype.h>
76.25 +#include "vdbeInt.h"
76.26 +
76.27 +/*
76.28 +** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
76.29 +** P if required.
76.30 +*/
76.31 +#define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
76.32 +
76.33 +/*
76.34 +** If pMem is an object with a valid string representation, this routine
76.35 +** ensures the internal encoding for the string representation is
76.36 +** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
76.37 +**
76.38 +** If pMem is not a string object, or the encoding of the string
76.39 +** representation is already stored using the requested encoding, then this
76.40 +** routine is a no-op.
76.41 +**
76.42 +** SQLITE_OK is returned if the conversion is successful (or not required).
76.43 +** SQLITE_NOMEM may be returned if a malloc() fails during conversion
76.44 +** between formats.
76.45 +*/
76.46 +int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
76.47 + int rc;
76.48 + if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
76.49 + return SQLITE_OK;
76.50 + }
76.51 +#ifdef SQLITE_OMIT_UTF16
76.52 + return SQLITE_ERROR;
76.53 +#else
76.54 +
76.55 +
76.56 + /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
76.57 + ** then the encoding of the value may not have changed.
76.58 + */
76.59 + rc = sqlite3VdbeMemTranslate(pMem, desiredEnc);
76.60 + assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
76.61 + assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
76.62 + assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
76.63 + return rc;
76.64 +#endif
76.65 +}
76.66 +
76.67 +/*
76.68 +** Make the given Mem object MEM_Dyn.
76.69 +**
76.70 +** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
76.71 +*/
76.72 +int sqlite3VdbeMemDynamicify(Mem *pMem){
76.73 + int n;
76.74 + u8 *z;
76.75 + expandBlob(pMem);
76.76 + if( (pMem->flags & (MEM_Ephem|MEM_Static|MEM_Short))==0 ){
76.77 + return SQLITE_OK;
76.78 + }
76.79 + assert( (pMem->flags & MEM_Dyn)==0 );
76.80 + n = pMem->n;
76.81 + assert( pMem->flags & (MEM_Str|MEM_Blob) );
76.82 + z = sqliteMallocRaw( n+2 );
76.83 + if( z==0 ){
76.84 + return SQLITE_NOMEM;
76.85 + }
76.86 + pMem->flags |= MEM_Dyn|MEM_Term;
76.87 + pMem->xDel = 0;
76.88 + memcpy(z, pMem->z, n );
76.89 + z[n] = 0;
76.90 + z[n+1] = 0;
76.91 + pMem->z = (char*)z;
76.92 + pMem->flags &= ~(MEM_Ephem|MEM_Static|MEM_Short);
76.93 + return SQLITE_OK;
76.94 +}
76.95 +
76.96 +/*
76.97 +** If the given Mem* has a zero-filled tail, turn it into an ordinary
76.98 +** blob stored in dynamically allocated space.
76.99 +*/
76.100 +#ifndef SQLITE_OMIT_INCRBLOB
76.101 +int sqlite3VdbeMemExpandBlob(Mem *pMem){
76.102 + if( pMem->flags & MEM_Zero ){
76.103 + char *pNew;
76.104 + int nByte;
76.105 + assert( (pMem->flags & MEM_Blob)!=0 );
76.106 + nByte = pMem->n + pMem->u.i;
76.107 + if( nByte<=0 ) nByte = 1;
76.108 + pNew = sqliteMalloc(nByte);
76.109 + if( pNew==0 ){
76.110 + return SQLITE_NOMEM;
76.111 + }
76.112 + memcpy(pNew, pMem->z, pMem->n);
76.113 + memset(&pNew[pMem->n], 0, pMem->u.i);
76.114 + sqlite3VdbeMemRelease(pMem);
76.115 + pMem->z = pNew;
76.116 + pMem->n += pMem->u.i;
76.117 + pMem->u.i = 0;
76.118 + pMem->flags &= ~(MEM_Zero|MEM_Static|MEM_Ephem|MEM_Short|MEM_Term);
76.119 + pMem->flags |= MEM_Dyn;
76.120 + }
76.121 + return SQLITE_OK;
76.122 +}
76.123 +#endif
76.124 +
76.125 +
76.126 +/*
76.127 +** Make the given Mem object either MEM_Short or MEM_Dyn so that bytes
76.128 +** of the Mem.z[] array can be modified.
76.129 +**
76.130 +** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
76.131 +*/
76.132 +int sqlite3VdbeMemMakeWriteable(Mem *pMem){
76.133 + int n;
76.134 + u8 *z;
76.135 + expandBlob(pMem);
76.136 + if( (pMem->flags & (MEM_Ephem|MEM_Static))==0 ){
76.137 + return SQLITE_OK;
76.138 + }
76.139 + assert( (pMem->flags & MEM_Dyn)==0 );
76.140 + assert( pMem->flags & (MEM_Str|MEM_Blob) );
76.141 + if( (n = pMem->n)+2<sizeof(pMem->zShort) ){
76.142 + z = (u8*)pMem->zShort;
76.143 + pMem->flags |= MEM_Short|MEM_Term;
76.144 + }else{
76.145 + z = sqliteMallocRaw( n+2 );
76.146 + if( z==0 ){
76.147 + return SQLITE_NOMEM;
76.148 + }
76.149 + pMem->flags |= MEM_Dyn|MEM_Term;
76.150 + pMem->xDel = 0;
76.151 + }
76.152 + memcpy(z, pMem->z, n );
76.153 + z[n] = 0;
76.154 + z[n+1] = 0;
76.155 + pMem->z = (char*)z;
76.156 + pMem->flags &= ~(MEM_Ephem|MEM_Static);
76.157 + assert(0==(1&(int)pMem->z));
76.158 + return SQLITE_OK;
76.159 +}
76.160 +
76.161 +/*
76.162 +** Make sure the given Mem is \u0000 terminated.
76.163 +*/
76.164 +int sqlite3VdbeMemNulTerminate(Mem *pMem){
76.165 + if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
76.166 + return SQLITE_OK; /* Nothing to do */
76.167 + }
76.168 + if( pMem->flags & (MEM_Static|MEM_Ephem) ){
76.169 + return sqlite3VdbeMemMakeWriteable(pMem);
76.170 + }else{
76.171 + char *z;
76.172 + sqlite3VdbeMemExpandBlob(pMem);
76.173 + z = sqliteMalloc(pMem->n+2);
76.174 +
76.175 + if( !z ) return SQLITE_NOMEM;
76.176 + memcpy(z, pMem->z, pMem->n);
76.177 + z[pMem->n] = 0;
76.178 + z[pMem->n+1] = 0;
76.179 + if( pMem->xDel ){
76.180 + pMem->xDel(pMem->z);
76.181 + }else{
76.182 + sqliteFree(pMem->z);
76.183 + }
76.184 + pMem->xDel = 0;
76.185 + pMem->z = z;
76.186 + pMem->flags |= MEM_Term;
76.187 + }
76.188 + return SQLITE_OK;
76.189 +}
76.190 +
76.191 +/*
76.192 +** Add MEM_Str to the set of representations for the given Mem. Numbers
76.193 +** are converted using sqlite3_snprintf(). Converting a BLOB to a string
76.194 +** is a no-op.
76.195 +**
76.196 +** Existing representations MEM_Int and MEM_Real are *not* invalidated.
76.197 +**
76.198 +** A MEM_Null value will never be passed to this function. This function is
76.199 +** used for converting values to text for returning to the user (i.e. via
76.200 +** sqlite3_value_text()), or for ensuring that values to be used as btree
76.201 +** keys are strings. In the former case a NULL pointer is returned the
76.202 +** user and the later is an internal programming error.
76.203 +*/
76.204 +int sqlite3VdbeMemStringify(Mem *pMem, int enc){
76.205 + int rc = SQLITE_OK;
76.206 + int fg = pMem->flags;
76.207 + char *z = pMem->zShort;
76.208 +
76.209 + assert( !(fg&MEM_Zero) );
76.210 + assert( !(fg&(MEM_Str|MEM_Blob)) );
76.211 + assert( fg&(MEM_Int|MEM_Real) );
76.212 +
76.213 + /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
76.214 + ** string representation of the value. Then, if the required encoding
76.215 + ** is UTF-16le or UTF-16be do a translation.
76.216 + **
76.217 + ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
76.218 + */
76.219 + if( fg & MEM_Int ){
76.220 + sqlite3_snprintf(NBFS, z, "%lld", pMem->u.i);
76.221 + }else{
76.222 + assert( fg & MEM_Real );
76.223 + sqlite3_snprintf(NBFS, z, "%!.15g", pMem->r);
76.224 + }
76.225 + pMem->n = strlen(z);
76.226 + pMem->z = z;
76.227 + pMem->enc = SQLITE_UTF8;
76.228 + pMem->flags |= MEM_Str | MEM_Short | MEM_Term;
76.229 + sqlite3VdbeChangeEncoding(pMem, enc);
76.230 + return rc;
76.231 +}
76.232 +
76.233 +/*
76.234 +** Memory cell pMem contains the context of an aggregate function.
76.235 +** This routine calls the finalize method for that function. The
76.236 +** result of the aggregate is stored back into pMem.
76.237 +**
76.238 +** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
76.239 +** otherwise.
76.240 +*/
76.241 +int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
76.242 + int rc = SQLITE_OK;
76.243 + if( pFunc && pFunc->xFinalize ){
76.244 + sqlite3_context ctx;
76.245 + assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
76.246 + ctx.s.flags = MEM_Null;
76.247 + ctx.s.z = pMem->zShort;
76.248 + ctx.pMem = pMem;
76.249 + ctx.pFunc = pFunc;
76.250 + ctx.isError = 0;
76.251 + pFunc->xFinalize(&ctx);
76.252 + if( pMem->z && pMem->z!=pMem->zShort ){
76.253 + sqliteFree( pMem->z );
76.254 + }
76.255 + *pMem = ctx.s;
76.256 + if( pMem->flags & MEM_Short ){
76.257 + pMem->z = pMem->zShort;
76.258 + }
76.259 + if( ctx.isError ){
76.260 + rc = SQLITE_ERROR;
76.261 + }
76.262 + }
76.263 + return rc;
76.264 +}
76.265 +
76.266 +/*
76.267 +** Release any memory held by the Mem. This may leave the Mem in an
76.268 +** inconsistent state, for example with (Mem.z==0) and
76.269 +** (Mem.type==SQLITE_TEXT).
76.270 +*/
76.271 +void sqlite3VdbeMemRelease(Mem *p){
76.272 + if( p->flags & (MEM_Dyn|MEM_Agg) ){
76.273 + if( p->xDel ){
76.274 + if( p->flags & MEM_Agg ){
76.275 + sqlite3VdbeMemFinalize(p, p->u.pDef);
76.276 + assert( (p->flags & MEM_Agg)==0 );
76.277 + sqlite3VdbeMemRelease(p);
76.278 + }else{
76.279 + p->xDel((void *)p->z);
76.280 + }
76.281 + }else{
76.282 + sqliteFree(p->z);
76.283 + }
76.284 + p->z = 0;
76.285 + p->xDel = 0;
76.286 + }
76.287 +}
76.288 +
76.289 +/*
76.290 +** Return some kind of integer value which is the best we can do
76.291 +** at representing the value that *pMem describes as an integer.
76.292 +** If pMem is an integer, then the value is exact. If pMem is
76.293 +** a floating-point then the value returned is the integer part.
76.294 +** If pMem is a string or blob, then we make an attempt to convert
76.295 +** it into a integer and return that. If pMem is NULL, return 0.
76.296 +**
76.297 +** If pMem is a string, its encoding might be changed.
76.298 +*/
76.299 +i64 sqlite3VdbeIntValue(Mem *pMem){
76.300 + int flags = pMem->flags;
76.301 + if( flags & MEM_Int ){
76.302 + return pMem->u.i;
76.303 + }else if( flags & MEM_Real ){
76.304 + return (i64)pMem->r;
76.305 + }else if( flags & (MEM_Str|MEM_Blob) ){
76.306 + i64 value;
76.307 + pMem->flags |= MEM_Str;
76.308 + if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
76.309 + || sqlite3VdbeMemNulTerminate(pMem) ){
76.310 + return 0;
76.311 + }
76.312 + assert( pMem->z );
76.313 + sqlite3Atoi64(pMem->z, &value);
76.314 + return value;
76.315 + }else{
76.316 + return 0;
76.317 + }
76.318 +}
76.319 +
76.320 +/*
76.321 +** Return the best representation of pMem that we can get into a
76.322 +** double. If pMem is already a double or an integer, return its
76.323 +** value. If it is a string or blob, try to convert it to a double.
76.324 +** If it is a NULL, return 0.0.
76.325 +*/
76.326 +double sqlite3VdbeRealValue(Mem *pMem){
76.327 + if( pMem->flags & MEM_Real ){
76.328 + return pMem->r;
76.329 + }else if( pMem->flags & MEM_Int ){
76.330 + return (double)pMem->u.i;
76.331 + }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
76.332 + double val = 0.0;
76.333 + pMem->flags |= MEM_Str;
76.334 + if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
76.335 + || sqlite3VdbeMemNulTerminate(pMem) ){
76.336 + return 0.0;
76.337 + }
76.338 + assert( pMem->z );
76.339 + sqlite3AtoF(pMem->z, &val);
76.340 + return val;
76.341 + }else{
76.342 + return 0.0;
76.343 + }
76.344 +}
76.345 +
76.346 +/*
76.347 +** The MEM structure is already a MEM_Real. Try to also make it a
76.348 +** MEM_Int if we can.
76.349 +*/
76.350 +void sqlite3VdbeIntegerAffinity(Mem *pMem){
76.351 + assert( pMem->flags & MEM_Real );
76.352 + pMem->u.i = pMem->r;
76.353 + if( ((double)pMem->u.i)==pMem->r ){
76.354 + pMem->flags |= MEM_Int;
76.355 + }
76.356 +}
76.357 +
76.358 +/*
76.359 +** Convert pMem to type integer. Invalidate any prior representations.
76.360 +*/
76.361 +int sqlite3VdbeMemIntegerify(Mem *pMem){
76.362 + pMem->u.i = sqlite3VdbeIntValue(pMem);
76.363 + sqlite3VdbeMemRelease(pMem);
76.364 + pMem->flags = MEM_Int;
76.365 + return SQLITE_OK;
76.366 +}
76.367 +
76.368 +/*
76.369 +** Convert pMem so that it is of type MEM_Real.
76.370 +** Invalidate any prior representations.
76.371 +*/
76.372 +int sqlite3VdbeMemRealify(Mem *pMem){
76.373 + pMem->r = sqlite3VdbeRealValue(pMem);
76.374 + sqlite3VdbeMemRelease(pMem);
76.375 + pMem->flags = MEM_Real;
76.376 + return SQLITE_OK;
76.377 +}
76.378 +
76.379 +/*
76.380 +** Convert pMem so that it has types MEM_Real or MEM_Int or both.
76.381 +** Invalidate any prior representations.
76.382 +*/
76.383 +int sqlite3VdbeMemNumerify(Mem *pMem){
76.384 + double r1, r2;
76.385 + i64 i;
76.386 + assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
76.387 + assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
76.388 + r1 = sqlite3VdbeRealValue(pMem);
76.389 + i = (i64)r1;
76.390 + r2 = (double)i;
76.391 + if( r1==r2 ){
76.392 + sqlite3VdbeMemIntegerify(pMem);
76.393 + }else{
76.394 + pMem->r = r1;
76.395 + pMem->flags = MEM_Real;
76.396 + sqlite3VdbeMemRelease(pMem);
76.397 + }
76.398 + return SQLITE_OK;
76.399 +}
76.400 +
76.401 +/*
76.402 +** Delete any previous value and set the value stored in *pMem to NULL.
76.403 +*/
76.404 +void sqlite3VdbeMemSetNull(Mem *pMem){
76.405 + sqlite3VdbeMemRelease(pMem);
76.406 + pMem->flags = MEM_Null;
76.407 + pMem->type = SQLITE_NULL;
76.408 + pMem->n = 0;
76.409 +}
76.410 +
76.411 +/*
76.412 +** Delete any previous value and set the value to be a BLOB of length
76.413 +** n containing all zeros.
76.414 +*/
76.415 +void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
76.416 + sqlite3VdbeMemRelease(pMem);
76.417 + pMem->flags = MEM_Blob|MEM_Zero|MEM_Short;
76.418 + pMem->type = SQLITE_BLOB;
76.419 + pMem->n = 0;
76.420 + if( n<0 ) n = 0;
76.421 + pMem->u.i = n;
76.422 + pMem->z = pMem->zShort;
76.423 + pMem->enc = SQLITE_UTF8;
76.424 +}
76.425 +
76.426 +/*
76.427 +** Delete any previous value and set the value stored in *pMem to val,
76.428 +** manifest type INTEGER.
76.429 +*/
76.430 +void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
76.431 + sqlite3VdbeMemRelease(pMem);
76.432 + pMem->u.i = val;
76.433 + pMem->flags = MEM_Int;
76.434 + pMem->type = SQLITE_INTEGER;
76.435 +}
76.436 +
76.437 +/*
76.438 +** Delete any previous value and set the value stored in *pMem to val,
76.439 +** manifest type REAL.
76.440 +*/
76.441 +void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
76.442 + if( sqlite3_isnan(val) ){
76.443 + sqlite3VdbeMemSetNull(pMem);
76.444 + }else{
76.445 + sqlite3VdbeMemRelease(pMem);
76.446 + pMem->r = val;
76.447 + pMem->flags = MEM_Real;
76.448 + pMem->type = SQLITE_FLOAT;
76.449 + }
76.450 +}
76.451 +
76.452 +/*
76.453 +** Return true if the Mem object contains a TEXT or BLOB that is
76.454 +** too large - whose size exceeds SQLITE_MAX_LENGTH.
76.455 +*/
76.456 +int sqlite3VdbeMemTooBig(Mem *p){
76.457 + if( p->flags & (MEM_Str|MEM_Blob) ){
76.458 + int n = p->n;
76.459 + if( p->flags & MEM_Zero ){
76.460 + n += p->u.i;
76.461 + }
76.462 + return n>SQLITE_MAX_LENGTH;
76.463 + }
76.464 + return 0;
76.465 +}
76.466 +
76.467 +/*
76.468 +** Make an shallow copy of pFrom into pTo. Prior contents of
76.469 +** pTo are overwritten. The pFrom->z field is not duplicated. If
76.470 +** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
76.471 +** and flags gets srcType (either MEM_Ephem or MEM_Static).
76.472 +*/
76.473 +void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
76.474 + memcpy(pTo, pFrom, sizeof(*pFrom)-sizeof(pFrom->zShort));
76.475 + pTo->xDel = 0;
76.476 + if( pTo->flags & (MEM_Str|MEM_Blob) ){
76.477 + pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Short|MEM_Ephem);
76.478 + assert( srcType==MEM_Ephem || srcType==MEM_Static );
76.479 + pTo->flags |= srcType;
76.480 + }
76.481 +}
76.482 +
76.483 +/*
76.484 +** Make a full copy of pFrom into pTo. Prior contents of pTo are
76.485 +** freed before the copy is made.
76.486 +*/
76.487 +int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
76.488 + int rc;
76.489 + if( pTo->flags & MEM_Dyn ){
76.490 + sqlite3VdbeMemRelease(pTo);
76.491 + }
76.492 + sqlite3VdbeMemShallowCopy(pTo, pFrom, MEM_Ephem);
76.493 + if( pTo->flags & MEM_Ephem ){
76.494 + rc = sqlite3VdbeMemMakeWriteable(pTo);
76.495 + }else{
76.496 + rc = SQLITE_OK;
76.497 + }
76.498 + return rc;
76.499 +}
76.500 +
76.501 +/*
76.502 +** Transfer the contents of pFrom to pTo. Any existing value in pTo is
76.503 +** freed. If pFrom contains ephemeral data, a copy is made.
76.504 +**
76.505 +** pFrom contains an SQL NULL when this routine returns. SQLITE_NOMEM
76.506 +** might be returned if pFrom held ephemeral data and we were unable
76.507 +** to allocate enough space to make a copy.
76.508 +*/
76.509 +int sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
76.510 + int rc;
76.511 + if( pTo->flags & MEM_Dyn ){
76.512 + sqlite3VdbeMemRelease(pTo);
76.513 + }
76.514 + memcpy(pTo, pFrom, sizeof(Mem));
76.515 + if( pFrom->flags & MEM_Short ){
76.516 + pTo->z = pTo->zShort;
76.517 + }
76.518 + pFrom->flags = MEM_Null;
76.519 + pFrom->xDel = 0;
76.520 + if( pTo->flags & MEM_Ephem ){
76.521 + rc = sqlite3VdbeMemMakeWriteable(pTo);
76.522 + }else{
76.523 + rc = SQLITE_OK;
76.524 + }
76.525 + return rc;
76.526 +}
76.527 +
76.528 +/*
76.529 +** Change the value of a Mem to be a string or a BLOB.
76.530 +*/
76.531 +int sqlite3VdbeMemSetStr(
76.532 + Mem *pMem, /* Memory cell to set to string value */
76.533 + const char *z, /* String pointer */
76.534 + int n, /* Bytes in string, or negative */
76.535 + u8 enc, /* Encoding of z. 0 for BLOBs */
76.536 + void (*xDel)(void*) /* Destructor function */
76.537 +){
76.538 + sqlite3VdbeMemRelease(pMem);
76.539 + if( !z ){
76.540 + pMem->flags = MEM_Null;
76.541 + pMem->type = SQLITE_NULL;
76.542 + return SQLITE_OK;
76.543 + }
76.544 +
76.545 + pMem->z = (char *)z;
76.546 + if( xDel==SQLITE_STATIC ){
76.547 + pMem->flags = MEM_Static;
76.548 + }else if( xDel==SQLITE_TRANSIENT ){
76.549 + pMem->flags = MEM_Ephem;
76.550 + }else{
76.551 + pMem->flags = MEM_Dyn;
76.552 + pMem->xDel = xDel;
76.553 + }
76.554 +
76.555 + pMem->enc = enc;
76.556 + pMem->type = enc==0 ? SQLITE_BLOB : SQLITE_TEXT;
76.557 + pMem->n = n;
76.558 +
76.559 + assert( enc==0 || enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE
76.560 + || enc==SQLITE_UTF16BE );
76.561 + switch( enc ){
76.562 + case 0:
76.563 + pMem->flags |= MEM_Blob;
76.564 + pMem->enc = SQLITE_UTF8;
76.565 + break;
76.566 +
76.567 + case SQLITE_UTF8:
76.568 + pMem->flags |= MEM_Str;
76.569 + if( n<0 ){
76.570 + pMem->n = strlen(z);
76.571 + pMem->flags |= MEM_Term;
76.572 + }
76.573 + break;
76.574 +
76.575 +#ifndef SQLITE_OMIT_UTF16
76.576 + case SQLITE_UTF16LE:
76.577 + case SQLITE_UTF16BE:
76.578 + pMem->flags |= MEM_Str;
76.579 + if( pMem->n<0 ){
76.580 + pMem->n = sqlite3Utf16ByteLen(pMem->z,-1);
76.581 + pMem->flags |= MEM_Term;
76.582 + }
76.583 + if( sqlite3VdbeMemHandleBom(pMem) ){
76.584 + return SQLITE_NOMEM;
76.585 + }
76.586 +#endif /* SQLITE_OMIT_UTF16 */
76.587 + }
76.588 + if( pMem->flags&MEM_Ephem ){
76.589 + return sqlite3VdbeMemMakeWriteable(pMem);
76.590 + }
76.591 + return SQLITE_OK;
76.592 +}
76.593 +
76.594 +/*
76.595 +** Compare the values contained by the two memory cells, returning
76.596 +** negative, zero or positive if pMem1 is less than, equal to, or greater
76.597 +** than pMem2. Sorting order is NULL's first, followed by numbers (integers
76.598 +** and reals) sorted numerically, followed by text ordered by the collating
76.599 +** sequence pColl and finally blob's ordered by memcmp().
76.600 +**
76.601 +** Two NULL values are considered equal by this function.
76.602 +*/
76.603 +int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
76.604 + int rc;
76.605 + int f1, f2;
76.606 + int combined_flags;
76.607 +
76.608 + /* Interchange pMem1 and pMem2 if the collating sequence specifies
76.609 + ** DESC order.
76.610 + */
76.611 + f1 = pMem1->flags;
76.612 + f2 = pMem2->flags;
76.613 + combined_flags = f1|f2;
76.614 +
76.615 + /* If one value is NULL, it is less than the other. If both values
76.616 + ** are NULL, return 0.
76.617 + */
76.618 + if( combined_flags&MEM_Null ){
76.619 + return (f2&MEM_Null) - (f1&MEM_Null);
76.620 + }
76.621 +
76.622 + /* If one value is a number and the other is not, the number is less.
76.623 + ** If both are numbers, compare as reals if one is a real, or as integers
76.624 + ** if both values are integers.
76.625 + */
76.626 + if( combined_flags&(MEM_Int|MEM_Real) ){
76.627 + if( !(f1&(MEM_Int|MEM_Real)) ){
76.628 + return 1;
76.629 + }
76.630 + if( !(f2&(MEM_Int|MEM_Real)) ){
76.631 + return -1;
76.632 + }
76.633 + if( (f1 & f2 & MEM_Int)==0 ){
76.634 + double r1, r2;
76.635 + if( (f1&MEM_Real)==0 ){
76.636 + r1 = pMem1->u.i;
76.637 + }else{
76.638 + r1 = pMem1->r;
76.639 + }
76.640 + if( (f2&MEM_Real)==0 ){
76.641 + r2 = pMem2->u.i;
76.642 + }else{
76.643 + r2 = pMem2->r;
76.644 + }
76.645 + if( r1<r2 ) return -1;
76.646 + if( r1>r2 ) return 1;
76.647 + return 0;
76.648 + }else{
76.649 + assert( f1&MEM_Int );
76.650 + assert( f2&MEM_Int );
76.651 + if( pMem1->u.i < pMem2->u.i ) return -1;
76.652 + if( pMem1->u.i > pMem2->u.i ) return 1;
76.653 + return 0;
76.654 + }
76.655 + }
76.656 +
76.657 + /* If one value is a string and the other is a blob, the string is less.
76.658 + ** If both are strings, compare using the collating functions.
76.659 + */
76.660 + if( combined_flags&MEM_Str ){
76.661 + if( (f1 & MEM_Str)==0 ){
76.662 + return 1;
76.663 + }
76.664 + if( (f2 & MEM_Str)==0 ){
76.665 + return -1;
76.666 + }
76.667 +
76.668 + assert( pMem1->enc==pMem2->enc );
76.669 + assert( pMem1->enc==SQLITE_UTF8 ||
76.670 + pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
76.671 +
76.672 + /* The collation sequence must be defined at this point, even if
76.673 + ** the user deletes the collation sequence after the vdbe program is
76.674 + ** compiled (this was not always the case).
76.675 + */
76.676 + assert( !pColl || pColl->xCmp );
76.677 +
76.678 + if( pColl ){
76.679 + if( pMem1->enc==pColl->enc ){
76.680 + /* The strings are already in the correct encoding. Call the
76.681 + ** comparison function directly */
76.682 + return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
76.683 + }else{
76.684 + u8 origEnc = pMem1->enc;
76.685 + const void *v1, *v2;
76.686 + int n1, n2;
76.687 + /* Convert the strings into the encoding that the comparison
76.688 + ** function expects */
76.689 + v1 = sqlite3ValueText((sqlite3_value*)pMem1, pColl->enc);
76.690 + n1 = v1==0 ? 0 : pMem1->n;
76.691 + assert( n1==sqlite3ValueBytes((sqlite3_value*)pMem1, pColl->enc) );
76.692 + v2 = sqlite3ValueText((sqlite3_value*)pMem2, pColl->enc);
76.693 + n2 = v2==0 ? 0 : pMem2->n;
76.694 + assert( n2==sqlite3ValueBytes((sqlite3_value*)pMem2, pColl->enc) );
76.695 + /* Do the comparison */
76.696 + rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
76.697 + /* Convert the strings back into the database encoding */
76.698 + sqlite3ValueText((sqlite3_value*)pMem1, origEnc);
76.699 + sqlite3ValueText((sqlite3_value*)pMem2, origEnc);
76.700 + return rc;
76.701 + }
76.702 + }
76.703 + /* If a NULL pointer was passed as the collate function, fall through
76.704 + ** to the blob case and use memcmp(). */
76.705 + }
76.706 +
76.707 + /* Both values must be blobs. Compare using memcmp(). */
76.708 + rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
76.709 + if( rc==0 ){
76.710 + rc = pMem1->n - pMem2->n;
76.711 + }
76.712 + return rc;
76.713 +}
76.714 +
76.715 +/*
76.716 +** Move data out of a btree key or data field and into a Mem structure.
76.717 +** The data or key is taken from the entry that pCur is currently pointing
76.718 +** to. offset and amt determine what portion of the data or key to retrieve.
76.719 +** key is true to get the key or false to get data. The result is written
76.720 +** into the pMem element.
76.721 +**
76.722 +** The pMem structure is assumed to be uninitialized. Any prior content
76.723 +** is overwritten without being freed.
76.724 +**
76.725 +** If this routine fails for any reason (malloc returns NULL or unable
76.726 +** to read from the disk) then the pMem is left in an inconsistent state.
76.727 +*/
76.728 +int sqlite3VdbeMemFromBtree(
76.729 + BtCursor *pCur, /* Cursor pointing at record to retrieve. */
76.730 + int offset, /* Offset from the start of data to return bytes from. */
76.731 + int amt, /* Number of bytes to return. */
76.732 + int key, /* If true, retrieve from the btree key, not data. */
76.733 + Mem *pMem /* OUT: Return data in this Mem structure. */
76.734 +){
76.735 + char *zData; /* Data from the btree layer */
76.736 + int available = 0; /* Number of bytes available on the local btree page */
76.737 +
76.738 + if( key ){
76.739 + zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
76.740 + }else{
76.741 + zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
76.742 + }
76.743 + assert( zData!=0 );
76.744 +
76.745 + pMem->n = amt;
76.746 + if( offset+amt<=available ){
76.747 + pMem->z = &zData[offset];
76.748 + pMem->flags = MEM_Blob|MEM_Ephem;
76.749 + }else{
76.750 + int rc;
76.751 + if( amt>NBFS-2 ){
76.752 + zData = (char *)sqliteMallocRaw(amt+2);
76.753 + if( !zData ){
76.754 + return SQLITE_NOMEM;
76.755 + }
76.756 + pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
76.757 + pMem->xDel = 0;
76.758 + }else{
76.759 + zData = &(pMem->zShort[0]);
76.760 + pMem->flags = MEM_Blob|MEM_Short|MEM_Term;
76.761 + }
76.762 + pMem->z = zData;
76.763 + pMem->enc = 0;
76.764 + pMem->type = SQLITE_BLOB;
76.765 +
76.766 + if( key ){
76.767 + rc = sqlite3BtreeKey(pCur, offset, amt, zData);
76.768 + }else{
76.769 + rc = sqlite3BtreeData(pCur, offset, amt, zData);
76.770 + }
76.771 + zData[amt] = 0;
76.772 + zData[amt+1] = 0;
76.773 + if( rc!=SQLITE_OK ){
76.774 + if( amt>NBFS-2 ){
76.775 + assert( zData!=pMem->zShort );
76.776 + assert( pMem->flags & MEM_Dyn );
76.777 + sqliteFree(zData);
76.778 + } else {
76.779 + assert( zData==pMem->zShort );
76.780 + assert( pMem->flags & MEM_Short );
76.781 + }
76.782 + return rc;
76.783 + }
76.784 + }
76.785 +
76.786 + return SQLITE_OK;
76.787 +}
76.788 +
76.789 +#ifndef NDEBUG
76.790 +/*
76.791 +** Perform various checks on the memory cell pMem. An assert() will
76.792 +** fail if pMem is internally inconsistent.
76.793 +*/
76.794 +void sqlite3VdbeMemSanity(Mem *pMem){
76.795 + int flags = pMem->flags;
76.796 + assert( flags!=0 ); /* Must define some type */
76.797 + if( flags & (MEM_Str|MEM_Blob) ){
76.798 + int x = flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
76.799 + assert( x!=0 ); /* Strings must define a string subtype */
76.800 + assert( (x & (x-1))==0 ); /* Only one string subtype can be defined */
76.801 + assert( pMem->z!=0 ); /* Strings must have a value */
76.802 + /* Mem.z points to Mem.zShort iff the subtype is MEM_Short */
76.803 + assert( (x & MEM_Short)==0 || pMem->z==pMem->zShort );
76.804 + assert( (x & MEM_Short)!=0 || pMem->z!=pMem->zShort );
76.805 + /* No destructor unless there is MEM_Dyn */
76.806 + assert( pMem->xDel==0 || (pMem->flags & MEM_Dyn)!=0 );
76.807 +
76.808 + if( (flags & MEM_Str) ){
76.809 + assert( pMem->enc==SQLITE_UTF8 ||
76.810 + pMem->enc==SQLITE_UTF16BE ||
76.811 + pMem->enc==SQLITE_UTF16LE
76.812 + );
76.813 + /* If the string is UTF-8 encoded and nul terminated, then pMem->n
76.814 + ** must be the length of the string. (Later:) If the database file
76.815 + ** has been corrupted, '\000' characters might have been inserted
76.816 + ** into the middle of the string. In that case, the strlen() might
76.817 + ** be less.
76.818 + */
76.819 + if( pMem->enc==SQLITE_UTF8 && (flags & MEM_Term) ){
76.820 + assert( strlen(pMem->z)<=pMem->n );
76.821 + assert( pMem->z[pMem->n]==0 );
76.822 + }
76.823 + }
76.824 + }else{
76.825 + /* Cannot define a string subtype for non-string objects */
76.826 + assert( (pMem->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short))==0 );
76.827 + assert( pMem->xDel==0 );
76.828 + }
76.829 + /* MEM_Null excludes all other types */
76.830 + assert( (pMem->flags&(MEM_Str|MEM_Int|MEM_Real|MEM_Blob))==0
76.831 + || (pMem->flags&MEM_Null)==0 );
76.832 + /* If the MEM is both real and integer, the values are equal */
76.833 + assert( (pMem->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real)
76.834 + || pMem->r==pMem->u.i );
76.835 +}
76.836 +#endif
76.837 +
76.838 +/* This function is only available internally, it is not part of the
76.839 +** external API. It works in a similar way to sqlite3_value_text(),
76.840 +** except the data returned is in the encoding specified by the second
76.841 +** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
76.842 +** SQLITE_UTF8.
76.843 +**
76.844 +** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
76.845 +** If that is the case, then the result must be aligned on an even byte
76.846 +** boundary.
76.847 +*/
76.848 +const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
76.849 + if( !pVal ) return 0;
76.850 + assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
76.851 +
76.852 + if( pVal->flags&MEM_Null ){
76.853 + return 0;
76.854 + }
76.855 + assert( (MEM_Blob>>3) == MEM_Str );
76.856 + pVal->flags |= (pVal->flags & MEM_Blob)>>3;
76.857 + expandBlob(pVal);
76.858 + if( pVal->flags&MEM_Str ){
76.859 + sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
76.860 + if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&(int)pVal->z) ){
76.861 + assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
76.862 + if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
76.863 + return 0;
76.864 + }
76.865 + }
76.866 + sqlite3VdbeMemNulTerminate(pVal);
76.867 + }else{
76.868 + assert( (pVal->flags&MEM_Blob)==0 );
76.869 + sqlite3VdbeMemStringify(pVal, enc);
76.870 + assert( 0==(1&(int)pVal->z) );
76.871 + }
76.872 + assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || sqlite3MallocFailed() );
76.873 + if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
76.874 + return pVal->z;
76.875 + }else{
76.876 + return 0;
76.877 + }
76.878 +}
76.879 +
76.880 +/*
76.881 +** Create a new sqlite3_value object.
76.882 +*/
76.883 +sqlite3_value *sqlite3ValueNew(void){
76.884 + Mem *p = sqliteMalloc(sizeof(*p));
76.885 + if( p ){
76.886 + p->flags = MEM_Null;
76.887 + p->type = SQLITE_NULL;
76.888 + }
76.889 + return p;
76.890 +}
76.891 +
76.892 +/*
76.893 +** Create a new sqlite3_value object, containing the value of pExpr.
76.894 +**
76.895 +** This only works for very simple expressions that consist of one constant
76.896 +** token (i.e. "5", "5.1", "NULL", "'a string'"). If the expression can
76.897 +** be converted directly into a value, then the value is allocated and
76.898 +** a pointer written to *ppVal. The caller is responsible for deallocating
76.899 +** the value by passing it to sqlite3ValueFree() later on. If the expression
76.900 +** cannot be converted to a value, then *ppVal is set to NULL.
76.901 +*/
76.902 +int sqlite3ValueFromExpr(
76.903 + Expr *pExpr,
76.904 + u8 enc,
76.905 + u8 affinity,
76.906 + sqlite3_value **ppVal
76.907 +){
76.908 + int op;
76.909 + char *zVal = 0;
76.910 + sqlite3_value *pVal = 0;
76.911 +
76.912 + if( !pExpr ){
76.913 + *ppVal = 0;
76.914 + return SQLITE_OK;
76.915 + }
76.916 + op = pExpr->op;
76.917 +
76.918 + if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
76.919 + zVal = sqliteStrNDup((char*)pExpr->token.z, pExpr->token.n);
76.920 + pVal = sqlite3ValueNew();
76.921 + if( !zVal || !pVal ) goto no_mem;
76.922 + sqlite3Dequote(zVal);
76.923 + sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, sqlite3FreeX);
76.924 + if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
76.925 + sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, enc);
76.926 + }else{
76.927 + sqlite3ValueApplyAffinity(pVal, affinity, enc);
76.928 + }
76.929 + }else if( op==TK_UMINUS ) {
76.930 + if( SQLITE_OK==sqlite3ValueFromExpr(pExpr->pLeft, enc, affinity, &pVal) ){
76.931 + pVal->u.i = -1 * pVal->u.i;
76.932 + pVal->r = -1.0 * pVal->r;
76.933 + }
76.934 + }
76.935 +#ifndef SQLITE_OMIT_BLOB_LITERAL
76.936 + else if( op==TK_BLOB ){
76.937 + int nVal;
76.938 + pVal = sqlite3ValueNew();
76.939 + zVal = sqliteStrNDup((char*)pExpr->token.z+1, pExpr->token.n-1);
76.940 + if( !zVal || !pVal ) goto no_mem;
76.941 + sqlite3Dequote(zVal);
76.942 + nVal = strlen(zVal)/2;
76.943 + sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(zVal), nVal, 0, sqlite3FreeX);
76.944 + sqliteFree(zVal);
76.945 + }
76.946 +#endif
76.947 +
76.948 + *ppVal = pVal;
76.949 + return SQLITE_OK;
76.950 +
76.951 +no_mem:
76.952 + sqliteFree(zVal);
76.953 + sqlite3ValueFree(pVal);
76.954 + *ppVal = 0;
76.955 + return SQLITE_NOMEM;
76.956 +}
76.957 +
76.958 +/*
76.959 +** Change the string value of an sqlite3_value object
76.960 +*/
76.961 +void sqlite3ValueSetStr(
76.962 + sqlite3_value *v,
76.963 + int n,
76.964 + const void *z,
76.965 + u8 enc,
76.966 + void (*xDel)(void*)
76.967 +){
76.968 + if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
76.969 +}
76.970 +
76.971 +/*
76.972 +** Free an sqlite3_value object
76.973 +*/
76.974 +void sqlite3ValueFree(sqlite3_value *v){
76.975 + if( !v ) return;
76.976 + sqlite3ValueSetStr(v, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
76.977 + sqliteFree(v);
76.978 +}
76.979 +
76.980 +/*
76.981 +** Return the number of bytes in the sqlite3_value object assuming
76.982 +** that it uses the encoding "enc"
76.983 +*/
76.984 +int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
76.985 + Mem *p = (Mem*)pVal;
76.986 + if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
76.987 + if( p->flags & MEM_Zero ){
76.988 + return (int)(p->n+p->u.i);
76.989 + }else{
76.990 + return p->n;
76.991 + }
76.992 + }
76.993 + return 0;
76.994 +}
77.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
77.2 +++ b/extensions/sqlite/sqlite-source/vtab.c Sun Jul 29 01:15:31 2007 +0000
77.3 @@ -0,0 +1,781 @@
77.4 +/*
77.5 +** 2006 June 10
77.6 +**
77.7 +** The author disclaims copyright to this source code. In place of
77.8 +** a legal notice, here is a blessing:
77.9 +**
77.10 +** May you do good and not evil.
77.11 +** May you find forgiveness for yourself and forgive others.
77.12 +** May you share freely, never taking more than you give.
77.13 +**
77.14 +*************************************************************************
77.15 +** This file contains code used to help implement virtual tables.
77.16 +**
77.17 +** $Id$
77.18 +*/
77.19 +#ifndef SQLITE_OMIT_VIRTUALTABLE
77.20 +#include "sqliteInt.h"
77.21 +
77.22 +static int createModule(
77.23 + sqlite3 *db, /* Database in which module is registered */
77.24 + const char *zName, /* Name assigned to this module */
77.25 + const sqlite3_module *pModule, /* The definition of the module */
77.26 + void *pAux, /* Context pointer for xCreate/xConnect */
77.27 + void (*xDestroy)(void *) /* Module destructor function */
77.28 +) {
77.29 + int nName = strlen(zName);
77.30 + Module *pMod = (Module *)sqliteMallocRaw(sizeof(Module) + nName + 1);
77.31 + if( pMod ){
77.32 + char *zCopy = (char *)(&pMod[1]);
77.33 + memcpy(zCopy, zName, nName+1);
77.34 + pMod->zName = zCopy;
77.35 + pMod->pModule = pModule;
77.36 + pMod->pAux = pAux;
77.37 + pMod->xDestroy = xDestroy;
77.38 + pMod = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
77.39 + if( pMod && pMod->xDestroy ){
77.40 + pMod->xDestroy(pMod->pAux);
77.41 + }
77.42 + sqliteFree(pMod);
77.43 + sqlite3ResetInternalSchema(db, 0);
77.44 + }
77.45 + return sqlite3ApiExit(db, SQLITE_OK);
77.46 +}
77.47 +
77.48 +
77.49 +/*
77.50 +** External API function used to create a new virtual-table module.
77.51 +*/
77.52 +int sqlite3_create_module(
77.53 + sqlite3 *db, /* Database in which module is registered */
77.54 + const char *zName, /* Name assigned to this module */
77.55 + const sqlite3_module *pModule, /* The definition of the module */
77.56 + void *pAux /* Context pointer for xCreate/xConnect */
77.57 +){
77.58 + return createModule(db, zName, pModule, pAux, 0);
77.59 +}
77.60 +
77.61 +/*
77.62 +** External API function used to create a new virtual-table module.
77.63 +*/
77.64 +int sqlite3_create_module_v2(
77.65 + sqlite3 *db, /* Database in which module is registered */
77.66 + const char *zName, /* Name assigned to this module */
77.67 + const sqlite3_module *pModule, /* The definition of the module */
77.68 + void *pAux, /* Context pointer for xCreate/xConnect */
77.69 + void (*xDestroy)(void *) /* Module destructor function */
77.70 +){
77.71 + return createModule(db, zName, pModule, pAux, xDestroy);
77.72 +}
77.73 +
77.74 +/*
77.75 +** Lock the virtual table so that it cannot be disconnected.
77.76 +** Locks nest. Every lock should have a corresponding unlock.
77.77 +** If an unlock is omitted, resources leaks will occur.
77.78 +**
77.79 +** If a disconnect is attempted while a virtual table is locked,
77.80 +** the disconnect is deferred until all locks have been removed.
77.81 +*/
77.82 +void sqlite3VtabLock(sqlite3_vtab *pVtab){
77.83 + pVtab->nRef++;
77.84 +}
77.85 +
77.86 +/*
77.87 +** Unlock a virtual table. When the last lock is removed,
77.88 +** disconnect the virtual table.
77.89 +*/
77.90 +void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){
77.91 + pVtab->nRef--;
77.92 + assert(db);
77.93 + assert(!sqlite3SafetyCheck(db));
77.94 + if( pVtab->nRef==0 ){
77.95 + if( db->magic==SQLITE_MAGIC_BUSY ){
77.96 + sqlite3SafetyOff(db);
77.97 + pVtab->pModule->xDisconnect(pVtab);
77.98 + sqlite3SafetyOn(db);
77.99 + } else {
77.100 + pVtab->pModule->xDisconnect(pVtab);
77.101 + }
77.102 + }
77.103 +}
77.104 +
77.105 +/*
77.106 +** Clear any and all virtual-table information from the Table record.
77.107 +** This routine is called, for example, just before deleting the Table
77.108 +** record.
77.109 +*/
77.110 +void sqlite3VtabClear(Table *p){
77.111 + sqlite3_vtab *pVtab = p->pVtab;
77.112 + if( pVtab ){
77.113 + assert( p->pMod && p->pMod->pModule );
77.114 + sqlite3VtabUnlock(p->pSchema->db, pVtab);
77.115 + p->pVtab = 0;
77.116 + }
77.117 + if( p->azModuleArg ){
77.118 + int i;
77.119 + for(i=0; i<p->nModuleArg; i++){
77.120 + sqliteFree(p->azModuleArg[i]);
77.121 + }
77.122 + sqliteFree(p->azModuleArg);
77.123 + }
77.124 +}
77.125 +
77.126 +/*
77.127 +** Add a new module argument to pTable->azModuleArg[].
77.128 +** The string is not copied - the pointer is stored. The
77.129 +** string will be freed automatically when the table is
77.130 +** deleted.
77.131 +*/
77.132 +static void addModuleArgument(Table *pTable, char *zArg){
77.133 + int i = pTable->nModuleArg++;
77.134 + int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
77.135 + char **azModuleArg;
77.136 + azModuleArg = sqliteRealloc(pTable->azModuleArg, nBytes);
77.137 + if( azModuleArg==0 ){
77.138 + int j;
77.139 + for(j=0; j<i; j++){
77.140 + sqliteFree(pTable->azModuleArg[j]);
77.141 + }
77.142 + sqliteFree(zArg);
77.143 + sqliteFree(pTable->azModuleArg);
77.144 + pTable->nModuleArg = 0;
77.145 + }else{
77.146 + azModuleArg[i] = zArg;
77.147 + azModuleArg[i+1] = 0;
77.148 + }
77.149 + pTable->azModuleArg = azModuleArg;
77.150 +}
77.151 +
77.152 +/*
77.153 +** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
77.154 +** statement. The module name has been parsed, but the optional list
77.155 +** of parameters that follow the module name are still pending.
77.156 +*/
77.157 +void sqlite3VtabBeginParse(
77.158 + Parse *pParse, /* Parsing context */
77.159 + Token *pName1, /* Name of new table, or database name */
77.160 + Token *pName2, /* Name of new table or NULL */
77.161 + Token *pModuleName /* Name of the module for the virtual table */
77.162 +){
77.163 + int iDb; /* The database the table is being created in */
77.164 + Table *pTable; /* The new virtual table */
77.165 +
77.166 +#ifndef SQLITE_OMIT_SHARED_CACHE
77.167 + if( sqlite3ThreadDataReadOnly()->useSharedData ){
77.168 + sqlite3ErrorMsg(pParse, "Cannot use virtual tables in shared-cache mode");
77.169 + return;
77.170 + }
77.171 +#endif
77.172 +
77.173 + sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
77.174 + pTable = pParse->pNewTable;
77.175 + if( pTable==0 || pParse->nErr ) return;
77.176 + assert( 0==pTable->pIndex );
77.177 +
77.178 + iDb = sqlite3SchemaToIndex(pParse->db, pTable->pSchema);
77.179 + assert( iDb>=0 );
77.180 +
77.181 + pTable->isVirtual = 1;
77.182 + pTable->nModuleArg = 0;
77.183 + addModuleArgument(pTable, sqlite3NameFromToken(pModuleName));
77.184 + addModuleArgument(pTable, sqlite3StrDup(pParse->db->aDb[iDb].zName));
77.185 + addModuleArgument(pTable, sqlite3StrDup(pTable->zName));
77.186 + pParse->sNameToken.n = pModuleName->z + pModuleName->n - pName1->z;
77.187 +
77.188 +#ifndef SQLITE_OMIT_AUTHORIZATION
77.189 + /* Creating a virtual table invokes the authorization callback twice.
77.190 + ** The first invocation, to obtain permission to INSERT a row into the
77.191 + ** sqlite_master table, has already been made by sqlite3StartTable().
77.192 + ** The second call, to obtain permission to create the table, is made now.
77.193 + */
77.194 + if( pTable->azModuleArg ){
77.195 + sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
77.196 + pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
77.197 + }
77.198 +#endif
77.199 +}
77.200 +
77.201 +/*
77.202 +** This routine takes the module argument that has been accumulating
77.203 +** in pParse->zArg[] and appends it to the list of arguments on the
77.204 +** virtual table currently under construction in pParse->pTable.
77.205 +*/
77.206 +static void addArgumentToVtab(Parse *pParse){
77.207 + if( pParse->sArg.z && pParse->pNewTable ){
77.208 + const char *z = (const char*)pParse->sArg.z;
77.209 + int n = pParse->sArg.n;
77.210 + addModuleArgument(pParse->pNewTable, sqliteStrNDup(z, n));
77.211 + }
77.212 +}
77.213 +
77.214 +/*
77.215 +** The parser calls this routine after the CREATE VIRTUAL TABLE statement
77.216 +** has been completely parsed.
77.217 +*/
77.218 +void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
77.219 + Table *pTab; /* The table being constructed */
77.220 + sqlite3 *db; /* The database connection */
77.221 + char *zModule; /* The module name of the table: USING modulename */
77.222 + Module *pMod = 0;
77.223 +
77.224 + addArgumentToVtab(pParse);
77.225 + pParse->sArg.z = 0;
77.226 +
77.227 + /* Lookup the module name. */
77.228 + pTab = pParse->pNewTable;
77.229 + if( pTab==0 ) return;
77.230 + db = pParse->db;
77.231 + if( pTab->nModuleArg<1 ) return;
77.232 + zModule = pTab->azModuleArg[0];
77.233 + pMod = (Module *)sqlite3HashFind(&db->aModule, zModule, strlen(zModule));
77.234 + pTab->pMod = pMod;
77.235 +
77.236 + /* If the CREATE VIRTUAL TABLE statement is being entered for the
77.237 + ** first time (in other words if the virtual table is actually being
77.238 + ** created now instead of just being read out of sqlite_master) then
77.239 + ** do additional initialization work and store the statement text
77.240 + ** in the sqlite_master table.
77.241 + */
77.242 + if( !db->init.busy ){
77.243 + char *zStmt;
77.244 + char *zWhere;
77.245 + int iDb;
77.246 + Vdbe *v;
77.247 +
77.248 + /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
77.249 + if( pEnd ){
77.250 + pParse->sNameToken.n = pEnd->z - pParse->sNameToken.z + pEnd->n;
77.251 + }
77.252 + zStmt = sqlite3MPrintf("CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
77.253 +
77.254 + /* A slot for the record has already been allocated in the
77.255 + ** SQLITE_MASTER table. We just need to update that slot with all
77.256 + ** the information we've collected.
77.257 + **
77.258 + ** The top of the stack is the rootpage allocated by sqlite3StartTable().
77.259 + ** This value is always 0 and is ignored, a virtual table does not have a
77.260 + ** rootpage. The next entry on the stack is the rowid of the record
77.261 + ** in the sqlite_master table.
77.262 + */
77.263 + iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
77.264 + sqlite3NestedParse(pParse,
77.265 + "UPDATE %Q.%s "
77.266 + "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
77.267 + "WHERE rowid=#1",
77.268 + db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
77.269 + pTab->zName,
77.270 + pTab->zName,
77.271 + zStmt
77.272 + );
77.273 + sqliteFree(zStmt);
77.274 + v = sqlite3GetVdbe(pParse);
77.275 + sqlite3ChangeCookie(db, v, iDb);
77.276 +
77.277 + sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
77.278 + zWhere = sqlite3MPrintf("name='%q'", pTab->zName);
77.279 + sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 1, zWhere, P3_DYNAMIC);
77.280 + sqlite3VdbeOp3(v, OP_VCreate, iDb, 0, pTab->zName, strlen(pTab->zName) + 1);
77.281 + }
77.282 +
77.283 + /* If we are rereading the sqlite_master table create the in-memory
77.284 + ** record of the table. If the module has already been registered,
77.285 + ** also call the xConnect method here.
77.286 + */
77.287 + else {
77.288 + Table *pOld;
77.289 + Schema *pSchema = pTab->pSchema;
77.290 + const char *zName = pTab->zName;
77.291 + int nName = strlen(zName) + 1;
77.292 + pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
77.293 + if( pOld ){
77.294 + assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
77.295 + return;
77.296 + }
77.297 + pSchema->db = pParse->db;
77.298 + pParse->pNewTable = 0;
77.299 + }
77.300 +}
77.301 +
77.302 +/*
77.303 +** The parser calls this routine when it sees the first token
77.304 +** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
77.305 +*/
77.306 +void sqlite3VtabArgInit(Parse *pParse){
77.307 + addArgumentToVtab(pParse);
77.308 + pParse->sArg.z = 0;
77.309 + pParse->sArg.n = 0;
77.310 +}
77.311 +
77.312 +/*
77.313 +** The parser calls this routine for each token after the first token
77.314 +** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
77.315 +*/
77.316 +void sqlite3VtabArgExtend(Parse *pParse, Token *p){
77.317 + Token *pArg = &pParse->sArg;
77.318 + if( pArg->z==0 ){
77.319 + pArg->z = p->z;
77.320 + pArg->n = p->n;
77.321 + }else{
77.322 + assert(pArg->z < p->z);
77.323 + pArg->n = (p->z + p->n - pArg->z);
77.324 + }
77.325 +}
77.326 +
77.327 +/*
77.328 +** Invoke a virtual table constructor (either xCreate or xConnect). The
77.329 +** pointer to the function to invoke is passed as the fourth parameter
77.330 +** to this procedure.
77.331 +*/
77.332 +static int vtabCallConstructor(
77.333 + sqlite3 *db,
77.334 + Table *pTab,
77.335 + Module *pMod,
77.336 + int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
77.337 + char **pzErr
77.338 +){
77.339 + int rc;
77.340 + int rc2;
77.341 + sqlite3_vtab *pVtab;
77.342 + const char *const*azArg = (const char *const*)pTab->azModuleArg;
77.343 + int nArg = pTab->nModuleArg;
77.344 + char *zErr = 0;
77.345 + char *zModuleName = sqlite3MPrintf("%s", pTab->zName);
77.346 +
77.347 + if( !zModuleName ){
77.348 + return SQLITE_NOMEM;
77.349 + }
77.350 +
77.351 + assert( !db->pVTab );
77.352 + assert( xConstruct );
77.353 +
77.354 + db->pVTab = pTab;
77.355 + rc = sqlite3SafetyOff(db);
77.356 + assert( rc==SQLITE_OK );
77.357 + rc = xConstruct(db, pMod->pAux, nArg, azArg, &pTab->pVtab, &zErr);
77.358 + rc2 = sqlite3SafetyOn(db);
77.359 + pVtab = pTab->pVtab;
77.360 + if( rc==SQLITE_OK && pVtab ){
77.361 + pVtab->pModule = pMod->pModule;
77.362 + pVtab->nRef = 1;
77.363 + }
77.364 +
77.365 + if( SQLITE_OK!=rc ){
77.366 + if( zErr==0 ){
77.367 + *pzErr = sqlite3MPrintf("vtable constructor failed: %s", zModuleName);
77.368 + }else {
77.369 + *pzErr = sqlite3MPrintf("%s", zErr);
77.370 + sqlite3_free(zErr);
77.371 + }
77.372 + }else if( db->pVTab ){
77.373 + const char *zFormat = "vtable constructor did not declare schema: %s";
77.374 + *pzErr = sqlite3MPrintf(zFormat, pTab->zName);
77.375 + rc = SQLITE_ERROR;
77.376 + }
77.377 + if( rc==SQLITE_OK ){
77.378 + rc = rc2;
77.379 + }
77.380 + db->pVTab = 0;
77.381 + sqliteFree(zModuleName);
77.382 +
77.383 + /* If everything went according to plan, loop through the columns
77.384 + ** of the table to see if any of them contain the token "hidden".
77.385 + ** If so, set the Column.isHidden flag and remove the token from
77.386 + ** the type string.
77.387 + */
77.388 + if( rc==SQLITE_OK ){
77.389 + int iCol;
77.390 + for(iCol=0; iCol<pTab->nCol; iCol++){
77.391 + char *zType = pTab->aCol[iCol].zType;
77.392 + int nType;
77.393 + int i = 0;
77.394 + if( !zType ) continue;
77.395 + nType = strlen(zType);
77.396 + if( sqlite3StrNICmp("hidden", zType, 6) || (zType[6] && zType[6]!=' ') ){
77.397 + for(i=0; i<nType; i++){
77.398 + if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
77.399 + && (zType[i+7]=='\0' || zType[i+7]==' ')
77.400 + ){
77.401 + i++;
77.402 + break;
77.403 + }
77.404 + }
77.405 + }
77.406 + if( i<nType ){
77.407 + int j;
77.408 + int nDel = 6 + (zType[i+6] ? 1 : 0);
77.409 + for(j=i; (j+nDel)<=nType; j++){
77.410 + zType[j] = zType[j+nDel];
77.411 + }
77.412 + if( zType[i]=='\0' && i>0 ){
77.413 + assert(zType[i-1]==' ');
77.414 + zType[i-1] = '\0';
77.415 + }
77.416 + pTab->aCol[iCol].isHidden = 1;
77.417 + }
77.418 + }
77.419 + }
77.420 + return rc;
77.421 +}
77.422 +
77.423 +/*
77.424 +** This function is invoked by the parser to call the xConnect() method
77.425 +** of the virtual table pTab. If an error occurs, an error code is returned
77.426 +** and an error left in pParse.
77.427 +**
77.428 +** This call is a no-op if table pTab is not a virtual table.
77.429 +*/
77.430 +int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
77.431 + Module *pMod;
77.432 + int rc = SQLITE_OK;
77.433 +
77.434 + if( !pTab || !pTab->isVirtual || pTab->pVtab ){
77.435 + return SQLITE_OK;
77.436 + }
77.437 +
77.438 + pMod = pTab->pMod;
77.439 + if( !pMod ){
77.440 + const char *zModule = pTab->azModuleArg[0];
77.441 + sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
77.442 + rc = SQLITE_ERROR;
77.443 + } else {
77.444 + char *zErr = 0;
77.445 + sqlite3 *db = pParse->db;
77.446 + rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
77.447 + if( rc!=SQLITE_OK ){
77.448 + sqlite3ErrorMsg(pParse, "%s", zErr);
77.449 + }
77.450 + sqliteFree(zErr);
77.451 + }
77.452 +
77.453 + return rc;
77.454 +}
77.455 +
77.456 +/*
77.457 +** Add the virtual table pVtab to the array sqlite3.aVTrans[].
77.458 +*/
77.459 +static int addToVTrans(sqlite3 *db, sqlite3_vtab *pVtab){
77.460 + const int ARRAY_INCR = 5;
77.461 +
77.462 + /* Grow the sqlite3.aVTrans array if required */
77.463 + if( (db->nVTrans%ARRAY_INCR)==0 ){
77.464 + sqlite3_vtab **aVTrans;
77.465 + int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
77.466 + aVTrans = sqliteRealloc((void *)db->aVTrans, nBytes);
77.467 + if( !aVTrans ){
77.468 + return SQLITE_NOMEM;
77.469 + }
77.470 + memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
77.471 + db->aVTrans = aVTrans;
77.472 + }
77.473 +
77.474 + /* Add pVtab to the end of sqlite3.aVTrans */
77.475 + db->aVTrans[db->nVTrans++] = pVtab;
77.476 + sqlite3VtabLock(pVtab);
77.477 + return SQLITE_OK;
77.478 +}
77.479 +
77.480 +/*
77.481 +** This function is invoked by the vdbe to call the xCreate method
77.482 +** of the virtual table named zTab in database iDb.
77.483 +**
77.484 +** If an error occurs, *pzErr is set to point an an English language
77.485 +** description of the error and an SQLITE_XXX error code is returned.
77.486 +** In this case the caller must call sqliteFree() on *pzErr.
77.487 +*/
77.488 +int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
77.489 + int rc = SQLITE_OK;
77.490 + Table *pTab;
77.491 + Module *pMod;
77.492 + const char *zModule;
77.493 +
77.494 + pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
77.495 + assert(pTab && pTab->isVirtual && !pTab->pVtab);
77.496 + pMod = pTab->pMod;
77.497 + zModule = pTab->azModuleArg[0];
77.498 +
77.499 + /* If the module has been registered and includes a Create method,
77.500 + ** invoke it now. If the module has not been registered, return an
77.501 + ** error. Otherwise, do nothing.
77.502 + */
77.503 + if( !pMod ){
77.504 + *pzErr = sqlite3MPrintf("no such module: %s", zModule);
77.505 + rc = SQLITE_ERROR;
77.506 + }else{
77.507 + rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
77.508 + }
77.509 +
77.510 + if( rc==SQLITE_OK && pTab->pVtab ){
77.511 + rc = addToVTrans(db, pTab->pVtab);
77.512 + }
77.513 +
77.514 + return rc;
77.515 +}
77.516 +
77.517 +/*
77.518 +** This function is used to set the schema of a virtual table. It is only
77.519 +** valid to call this function from within the xCreate() or xConnect() of a
77.520 +** virtual table module.
77.521 +*/
77.522 +int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
77.523 + Parse sParse;
77.524 +
77.525 + int rc = SQLITE_OK;
77.526 + Table *pTab = db->pVTab;
77.527 + char *zErr = 0;
77.528 +
77.529 + if( !pTab ){
77.530 + sqlite3Error(db, SQLITE_MISUSE, 0);
77.531 + return SQLITE_MISUSE;
77.532 + }
77.533 + assert(pTab->isVirtual && pTab->nCol==0 && pTab->aCol==0);
77.534 +
77.535 + memset(&sParse, 0, sizeof(Parse));
77.536 + sParse.declareVtab = 1;
77.537 + sParse.db = db;
77.538 +
77.539 + if(
77.540 + SQLITE_OK == sqlite3RunParser(&sParse, zCreateTable, &zErr) &&
77.541 + sParse.pNewTable &&
77.542 + !sParse.pNewTable->pSelect &&
77.543 + !sParse.pNewTable->isVirtual
77.544 + ){
77.545 + pTab->aCol = sParse.pNewTable->aCol;
77.546 + pTab->nCol = sParse.pNewTable->nCol;
77.547 + sParse.pNewTable->nCol = 0;
77.548 + sParse.pNewTable->aCol = 0;
77.549 + db->pVTab = 0;
77.550 + } else {
77.551 + sqlite3Error(db, SQLITE_ERROR, zErr);
77.552 + sqliteFree(zErr);
77.553 + rc = SQLITE_ERROR;
77.554 + }
77.555 + sParse.declareVtab = 0;
77.556 +
77.557 + sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
77.558 + sqlite3DeleteTable(sParse.pNewTable);
77.559 + sParse.pNewTable = 0;
77.560 +
77.561 + assert( (rc&0xff)==rc );
77.562 + return sqlite3ApiExit(db, rc);
77.563 +}
77.564 +
77.565 +/*
77.566 +** This function is invoked by the vdbe to call the xDestroy method
77.567 +** of the virtual table named zTab in database iDb. This occurs
77.568 +** when a DROP TABLE is mentioned.
77.569 +**
77.570 +** This call is a no-op if zTab is not a virtual table.
77.571 +*/
77.572 +int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab)
77.573 +{
77.574 + int rc = SQLITE_OK;
77.575 + Table *pTab;
77.576 +
77.577 + pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
77.578 + assert(pTab);
77.579 + if( pTab->pVtab ){
77.580 + int (*xDestroy)(sqlite3_vtab *pVTab) = pTab->pMod->pModule->xDestroy;
77.581 + rc = sqlite3SafetyOff(db);
77.582 + assert( rc==SQLITE_OK );
77.583 + if( xDestroy ){
77.584 + rc = xDestroy(pTab->pVtab);
77.585 + }
77.586 + sqlite3SafetyOn(db);
77.587 + if( rc==SQLITE_OK ){
77.588 + pTab->pVtab = 0;
77.589 + }
77.590 + }
77.591 +
77.592 + return rc;
77.593 +}
77.594 +
77.595 +/*
77.596 +** This function invokes either the xRollback or xCommit method
77.597 +** of each of the virtual tables in the sqlite3.aVTrans array. The method
77.598 +** called is identified by the second argument, "offset", which is
77.599 +** the offset of the method to call in the sqlite3_module structure.
77.600 +**
77.601 +** The array is cleared after invoking the callbacks.
77.602 +*/
77.603 +static void callFinaliser(sqlite3 *db, int offset){
77.604 + int i;
77.605 + if( db->aVTrans ){
77.606 + for(i=0; i<db->nVTrans && db->aVTrans[i]; i++){
77.607 + sqlite3_vtab *pVtab = db->aVTrans[i];
77.608 + int (*x)(sqlite3_vtab *);
77.609 + x = *(int (**)(sqlite3_vtab *))((char *)pVtab->pModule + offset);
77.610 + if( x ) x(pVtab);
77.611 + sqlite3VtabUnlock(db, pVtab);
77.612 + }
77.613 + sqliteFree(db->aVTrans);
77.614 + db->nVTrans = 0;
77.615 + db->aVTrans = 0;
77.616 + }
77.617 +}
77.618 +
77.619 +/*
77.620 +** If argument rc2 is not SQLITE_OK, then return it and do nothing.
77.621 +** Otherwise, invoke the xSync method of all virtual tables in the
77.622 +** sqlite3.aVTrans array. Return the error code for the first error
77.623 +** that occurs, or SQLITE_OK if all xSync operations are successful.
77.624 +*/
77.625 +int sqlite3VtabSync(sqlite3 *db, int rc2){
77.626 + int i;
77.627 + int rc = SQLITE_OK;
77.628 + int rcsafety;
77.629 + sqlite3_vtab **aVTrans = db->aVTrans;
77.630 + if( rc2!=SQLITE_OK ) return rc2;
77.631 +
77.632 + rc = sqlite3SafetyOff(db);
77.633 + db->aVTrans = 0;
77.634 + for(i=0; rc==SQLITE_OK && i<db->nVTrans && aVTrans[i]; i++){
77.635 + sqlite3_vtab *pVtab = aVTrans[i];
77.636 + int (*x)(sqlite3_vtab *);
77.637 + x = pVtab->pModule->xSync;
77.638 + if( x ){
77.639 + rc = x(pVtab);
77.640 + }
77.641 + }
77.642 + db->aVTrans = aVTrans;
77.643 + rcsafety = sqlite3SafetyOn(db);
77.644 +
77.645 + if( rc==SQLITE_OK ){
77.646 + rc = rcsafety;
77.647 + }
77.648 + return rc;
77.649 +}
77.650 +
77.651 +/*
77.652 +** Invoke the xRollback method of all virtual tables in the
77.653 +** sqlite3.aVTrans array. Then clear the array itself.
77.654 +*/
77.655 +int sqlite3VtabRollback(sqlite3 *db){
77.656 + callFinaliser(db, (int)(&((sqlite3_module *)0)->xRollback));
77.657 + return SQLITE_OK;
77.658 +}
77.659 +
77.660 +/*
77.661 +** Invoke the xCommit method of all virtual tables in the
77.662 +** sqlite3.aVTrans array. Then clear the array itself.
77.663 +*/
77.664 +int sqlite3VtabCommit(sqlite3 *db){
77.665 + callFinaliser(db, (int)(&((sqlite3_module *)0)->xCommit));
77.666 + return SQLITE_OK;
77.667 +}
77.668 +
77.669 +/*
77.670 +** If the virtual table pVtab supports the transaction interface
77.671 +** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
77.672 +** not currently open, invoke the xBegin method now.
77.673 +**
77.674 +** If the xBegin call is successful, place the sqlite3_vtab pointer
77.675 +** in the sqlite3.aVTrans array.
77.676 +*/
77.677 +int sqlite3VtabBegin(sqlite3 *db, sqlite3_vtab *pVtab){
77.678 + int rc = SQLITE_OK;
77.679 + const sqlite3_module *pModule;
77.680 +
77.681 + /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
77.682 + ** than zero, then this function is being called from within a
77.683 + ** virtual module xSync() callback. It is illegal to write to
77.684 + ** virtual module tables in this case, so return SQLITE_LOCKED.
77.685 + */
77.686 + if( 0==db->aVTrans && db->nVTrans>0 ){
77.687 + return SQLITE_LOCKED;
77.688 + }
77.689 + if( !pVtab ){
77.690 + return SQLITE_OK;
77.691 + }
77.692 + pModule = pVtab->pModule;
77.693 +
77.694 + if( pModule->xBegin ){
77.695 + int i;
77.696 +
77.697 +
77.698 + /* If pVtab is already in the aVTrans array, return early */
77.699 + for(i=0; (i<db->nVTrans) && 0!=db->aVTrans[i]; i++){
77.700 + if( db->aVTrans[i]==pVtab ){
77.701 + return SQLITE_OK;
77.702 + }
77.703 + }
77.704 +
77.705 + /* Invoke the xBegin method */
77.706 + rc = pModule->xBegin(pVtab);
77.707 + if( rc!=SQLITE_OK ){
77.708 + return rc;
77.709 + }
77.710 +
77.711 + rc = addToVTrans(db, pVtab);
77.712 + }
77.713 + return rc;
77.714 +}
77.715 +
77.716 +/*
77.717 +** The first parameter (pDef) is a function implementation. The
77.718 +** second parameter (pExpr) is the first argument to this function.
77.719 +** If pExpr is a column in a virtual table, then let the virtual
77.720 +** table implementation have an opportunity to overload the function.
77.721 +**
77.722 +** This routine is used to allow virtual table implementations to
77.723 +** overload MATCH, LIKE, GLOB, and REGEXP operators.
77.724 +**
77.725 +** Return either the pDef argument (indicating no change) or a
77.726 +** new FuncDef structure that is marked as ephemeral using the
77.727 +** SQLITE_FUNC_EPHEM flag.
77.728 +*/
77.729 +FuncDef *sqlite3VtabOverloadFunction(
77.730 + FuncDef *pDef, /* Function to possibly overload */
77.731 + int nArg, /* Number of arguments to the function */
77.732 + Expr *pExpr /* First argument to the function */
77.733 +){
77.734 + Table *pTab;
77.735 + sqlite3_vtab *pVtab;
77.736 + sqlite3_module *pMod;
77.737 + void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
77.738 + void *pArg;
77.739 + FuncDef *pNew;
77.740 + int rc;
77.741 + char *zLowerName;
77.742 + unsigned char *z;
77.743 +
77.744 +
77.745 + /* Check to see the left operand is a column in a virtual table */
77.746 + if( pExpr==0 ) return pDef;
77.747 + if( pExpr->op!=TK_COLUMN ) return pDef;
77.748 + pTab = pExpr->pTab;
77.749 + if( pTab==0 ) return pDef;
77.750 + if( !pTab->isVirtual ) return pDef;
77.751 + pVtab = pTab->pVtab;
77.752 + assert( pVtab!=0 );
77.753 + assert( pVtab->pModule!=0 );
77.754 + pMod = (sqlite3_module *)pVtab->pModule;
77.755 + if( pMod->xFindFunction==0 ) return pDef;
77.756 +
77.757 + /* Call the xFuncFunction method on the virtual table implementation
77.758 + ** to see if the implementation wants to overload this function
77.759 + */
77.760 + zLowerName = sqlite3StrDup(pDef->zName);
77.761 + for(z=(unsigned char*)zLowerName; *z; z++){
77.762 + *z = sqlite3UpperToLower[*z];
77.763 + }
77.764 + rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
77.765 + sqliteFree(zLowerName);
77.766 + if( rc==0 ){
77.767 + return pDef;
77.768 + }
77.769 +
77.770 + /* Create a new ephemeral function definition for the overloaded
77.771 + ** function */
77.772 + pNew = sqliteMalloc( sizeof(*pNew) + strlen(pDef->zName) );
77.773 + if( pNew==0 ){
77.774 + return pDef;
77.775 + }
77.776 + *pNew = *pDef;
77.777 + memcpy(pNew->zName, pDef->zName, strlen(pDef->zName)+1);
77.778 + pNew->xFunc = xFunc;
77.779 + pNew->pUserData = pArg;
77.780 + pNew->flags |= SQLITE_FUNC_EPHEM;
77.781 + return pNew;
77.782 +}
77.783 +
77.784 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
78.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
78.2 +++ b/extensions/sqlite/sqlite-source/where.c Sun Jul 29 01:15:31 2007 +0000
78.3 @@ -0,0 +1,2757 @@
78.4 +/*
78.5 +** 2001 September 15
78.6 +**
78.7 +** The author disclaims copyright to this source code. In place of
78.8 +** a legal notice, here is a blessing:
78.9 +**
78.10 +** May you do good and not evil.
78.11 +** May you find forgiveness for yourself and forgive others.
78.12 +** May you share freely, never taking more than you give.
78.13 +**
78.14 +*************************************************************************
78.15 +** This module contains C code that generates VDBE code used to process
78.16 +** the WHERE clause of SQL statements. This module is reponsible for
78.17 +** generating the code that loops through a table looking for applicable
78.18 +** rows. Indices are selected and used to speed the search when doing
78.19 +** so is applicable. Because this module is responsible for selecting
78.20 +** indices, you might also think of this module as the "query optimizer".
78.21 +**
78.22 +** $Id$
78.23 +*/
78.24 +#include "sqliteInt.h"
78.25 +
78.26 +/*
78.27 +** The number of bits in a Bitmask. "BMS" means "BitMask Size".
78.28 +*/
78.29 +#define BMS (sizeof(Bitmask)*8)
78.30 +
78.31 +/*
78.32 +** Trace output macros
78.33 +*/
78.34 +#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
78.35 +int sqlite3_where_trace = 0;
78.36 +# define WHERETRACE(X) if(sqlite3_where_trace) sqlite3DebugPrintf X
78.37 +#else
78.38 +# define WHERETRACE(X)
78.39 +#endif
78.40 +
78.41 +/* Forward reference
78.42 +*/
78.43 +typedef struct WhereClause WhereClause;
78.44 +typedef struct ExprMaskSet ExprMaskSet;
78.45 +
78.46 +/*
78.47 +** The query generator uses an array of instances of this structure to
78.48 +** help it analyze the subexpressions of the WHERE clause. Each WHERE
78.49 +** clause subexpression is separated from the others by an AND operator.
78.50 +**
78.51 +** All WhereTerms are collected into a single WhereClause structure.
78.52 +** The following identity holds:
78.53 +**
78.54 +** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
78.55 +**
78.56 +** When a term is of the form:
78.57 +**
78.58 +** X <op> <expr>
78.59 +**
78.60 +** where X is a column name and <op> is one of certain operators,
78.61 +** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
78.62 +** cursor number and column number for X. WhereTerm.operator records
78.63 +** the <op> using a bitmask encoding defined by WO_xxx below. The
78.64 +** use of a bitmask encoding for the operator allows us to search
78.65 +** quickly for terms that match any of several different operators.
78.66 +**
78.67 +** prereqRight and prereqAll record sets of cursor numbers,
78.68 +** but they do so indirectly. A single ExprMaskSet structure translates
78.69 +** cursor number into bits and the translated bit is stored in the prereq
78.70 +** fields. The translation is used in order to maximize the number of
78.71 +** bits that will fit in a Bitmask. The VDBE cursor numbers might be
78.72 +** spread out over the non-negative integers. For example, the cursor
78.73 +** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The ExprMaskSet
78.74 +** translates these sparse cursor numbers into consecutive integers
78.75 +** beginning with 0 in order to make the best possible use of the available
78.76 +** bits in the Bitmask. So, in the example above, the cursor numbers
78.77 +** would be mapped into integers 0 through 7.
78.78 +*/
78.79 +typedef struct WhereTerm WhereTerm;
78.80 +struct WhereTerm {
78.81 + Expr *pExpr; /* Pointer to the subexpression */
78.82 + i16 iParent; /* Disable pWC->a[iParent] when this term disabled */
78.83 + i16 leftCursor; /* Cursor number of X in "X <op> <expr>" */
78.84 + i16 leftColumn; /* Column number of X in "X <op> <expr>" */
78.85 + u16 eOperator; /* A WO_xx value describing <op> */
78.86 + u8 flags; /* Bit flags. See below */
78.87 + u8 nChild; /* Number of children that must disable us */
78.88 + WhereClause *pWC; /* The clause this term is part of */
78.89 + Bitmask prereqRight; /* Bitmask of tables used by pRight */
78.90 + Bitmask prereqAll; /* Bitmask of tables referenced by p */
78.91 +};
78.92 +
78.93 +/*
78.94 +** Allowed values of WhereTerm.flags
78.95 +*/
78.96 +#define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(pExpr) */
78.97 +#define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
78.98 +#define TERM_CODED 0x04 /* This term is already coded */
78.99 +#define TERM_COPIED 0x08 /* Has a child */
78.100 +#define TERM_OR_OK 0x10 /* Used during OR-clause processing */
78.101 +
78.102 +/*
78.103 +** An instance of the following structure holds all information about a
78.104 +** WHERE clause. Mostly this is a container for one or more WhereTerms.
78.105 +*/
78.106 +struct WhereClause {
78.107 + Parse *pParse; /* The parser context */
78.108 + ExprMaskSet *pMaskSet; /* Mapping of table indices to bitmasks */
78.109 + int nTerm; /* Number of terms */
78.110 + int nSlot; /* Number of entries in a[] */
78.111 + WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
78.112 + WhereTerm aStatic[10]; /* Initial static space for a[] */
78.113 +};
78.114 +
78.115 +/*
78.116 +** An instance of the following structure keeps track of a mapping
78.117 +** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
78.118 +**
78.119 +** The VDBE cursor numbers are small integers contained in
78.120 +** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
78.121 +** clause, the cursor numbers might not begin with 0 and they might
78.122 +** contain gaps in the numbering sequence. But we want to make maximum
78.123 +** use of the bits in our bitmasks. This structure provides a mapping
78.124 +** from the sparse cursor numbers into consecutive integers beginning
78.125 +** with 0.
78.126 +**
78.127 +** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
78.128 +** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
78.129 +**
78.130 +** For example, if the WHERE clause expression used these VDBE
78.131 +** cursors: 4, 5, 8, 29, 57, 73. Then the ExprMaskSet structure
78.132 +** would map those cursor numbers into bits 0 through 5.
78.133 +**
78.134 +** Note that the mapping is not necessarily ordered. In the example
78.135 +** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
78.136 +** 57->5, 73->4. Or one of 719 other combinations might be used. It
78.137 +** does not really matter. What is important is that sparse cursor
78.138 +** numbers all get mapped into bit numbers that begin with 0 and contain
78.139 +** no gaps.
78.140 +*/
78.141 +struct ExprMaskSet {
78.142 + int n; /* Number of assigned cursor values */
78.143 + int ix[sizeof(Bitmask)*8]; /* Cursor assigned to each bit */
78.144 +};
78.145 +
78.146 +
78.147 +/*
78.148 +** Bitmasks for the operators that indices are able to exploit. An
78.149 +** OR-ed combination of these values can be used when searching for
78.150 +** terms in the where clause.
78.151 +*/
78.152 +#define WO_IN 1
78.153 +#define WO_EQ 2
78.154 +#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
78.155 +#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
78.156 +#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
78.157 +#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
78.158 +#define WO_MATCH 64
78.159 +#define WO_ISNULL 128
78.160 +
78.161 +/*
78.162 +** Value for flags returned by bestIndex().
78.163 +**
78.164 +** The least significant byte is reserved as a mask for WO_ values above.
78.165 +** The WhereLevel.flags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
78.166 +** But if the table is the right table of a left join, WhereLevel.flags
78.167 +** is set to WO_IN|WO_EQ. The WhereLevel.flags field can then be used as
78.168 +** the "op" parameter to findTerm when we are resolving equality constraints.
78.169 +** ISNULL constraints will then not be used on the right table of a left
78.170 +** join. Tickets #2177 and #2189.
78.171 +*/
78.172 +#define WHERE_ROWID_EQ 0x000100 /* rowid=EXPR or rowid IN (...) */
78.173 +#define WHERE_ROWID_RANGE 0x000200 /* rowid<EXPR and/or rowid>EXPR */
78.174 +#define WHERE_COLUMN_EQ 0x001000 /* x=EXPR or x IN (...) */
78.175 +#define WHERE_COLUMN_RANGE 0x002000 /* x<EXPR and/or x>EXPR */
78.176 +#define WHERE_COLUMN_IN 0x004000 /* x IN (...) */
78.177 +#define WHERE_TOP_LIMIT 0x010000 /* x<EXPR or x<=EXPR constraint */
78.178 +#define WHERE_BTM_LIMIT 0x020000 /* x>EXPR or x>=EXPR constraint */
78.179 +#define WHERE_IDX_ONLY 0x080000 /* Use index only - omit table */
78.180 +#define WHERE_ORDERBY 0x100000 /* Output will appear in correct order */
78.181 +#define WHERE_REVERSE 0x200000 /* Scan in reverse order */
78.182 +#define WHERE_UNIQUE 0x400000 /* Selects no more than one row */
78.183 +#define WHERE_VIRTUALTABLE 0x800000 /* Use virtual-table processing */
78.184 +
78.185 +/*
78.186 +** Initialize a preallocated WhereClause structure.
78.187 +*/
78.188 +static void whereClauseInit(
78.189 + WhereClause *pWC, /* The WhereClause to be initialized */
78.190 + Parse *pParse, /* The parsing context */
78.191 + ExprMaskSet *pMaskSet /* Mapping from table indices to bitmasks */
78.192 +){
78.193 + pWC->pParse = pParse;
78.194 + pWC->pMaskSet = pMaskSet;
78.195 + pWC->nTerm = 0;
78.196 + pWC->nSlot = ArraySize(pWC->aStatic);
78.197 + pWC->a = pWC->aStatic;
78.198 +}
78.199 +
78.200 +/*
78.201 +** Deallocate a WhereClause structure. The WhereClause structure
78.202 +** itself is not freed. This routine is the inverse of whereClauseInit().
78.203 +*/
78.204 +static void whereClauseClear(WhereClause *pWC){
78.205 + int i;
78.206 + WhereTerm *a;
78.207 + for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
78.208 + if( a->flags & TERM_DYNAMIC ){
78.209 + sqlite3ExprDelete(a->pExpr);
78.210 + }
78.211 + }
78.212 + if( pWC->a!=pWC->aStatic ){
78.213 + sqliteFree(pWC->a);
78.214 + }
78.215 +}
78.216 +
78.217 +/*
78.218 +** Add a new entries to the WhereClause structure. Increase the allocated
78.219 +** space as necessary.
78.220 +**
78.221 +** If the flags argument includes TERM_DYNAMIC, then responsibility
78.222 +** for freeing the expression p is assumed by the WhereClause object.
78.223 +**
78.224 +** WARNING: This routine might reallocate the space used to store
78.225 +** WhereTerms. All pointers to WhereTerms should be invalided after
78.226 +** calling this routine. Such pointers may be reinitialized by referencing
78.227 +** the pWC->a[] array.
78.228 +*/
78.229 +static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
78.230 + WhereTerm *pTerm;
78.231 + int idx;
78.232 + if( pWC->nTerm>=pWC->nSlot ){
78.233 + WhereTerm *pOld = pWC->a;
78.234 + pWC->a = sqliteMalloc( sizeof(pWC->a[0])*pWC->nSlot*2 );
78.235 + if( pWC->a==0 ){
78.236 + if( flags & TERM_DYNAMIC ){
78.237 + sqlite3ExprDelete(p);
78.238 + }
78.239 + return 0;
78.240 + }
78.241 + memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
78.242 + if( pOld!=pWC->aStatic ){
78.243 + sqliteFree(pOld);
78.244 + }
78.245 + pWC->nSlot *= 2;
78.246 + }
78.247 + pTerm = &pWC->a[idx = pWC->nTerm];
78.248 + pWC->nTerm++;
78.249 + pTerm->pExpr = p;
78.250 + pTerm->flags = flags;
78.251 + pTerm->pWC = pWC;
78.252 + pTerm->iParent = -1;
78.253 + return idx;
78.254 +}
78.255 +
78.256 +/*
78.257 +** This routine identifies subexpressions in the WHERE clause where
78.258 +** each subexpression is separated by the AND operator or some other
78.259 +** operator specified in the op parameter. The WhereClause structure
78.260 +** is filled with pointers to subexpressions. For example:
78.261 +**
78.262 +** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
78.263 +** \________/ \_______________/ \________________/
78.264 +** slot[0] slot[1] slot[2]
78.265 +**
78.266 +** The original WHERE clause in pExpr is unaltered. All this routine
78.267 +** does is make slot[] entries point to substructure within pExpr.
78.268 +**
78.269 +** In the previous sentence and in the diagram, "slot[]" refers to
78.270 +** the WhereClause.a[] array. This array grows as needed to contain
78.271 +** all terms of the WHERE clause.
78.272 +*/
78.273 +static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
78.274 + if( pExpr==0 ) return;
78.275 + if( pExpr->op!=op ){
78.276 + whereClauseInsert(pWC, pExpr, 0);
78.277 + }else{
78.278 + whereSplit(pWC, pExpr->pLeft, op);
78.279 + whereSplit(pWC, pExpr->pRight, op);
78.280 + }
78.281 +}
78.282 +
78.283 +/*
78.284 +** Initialize an expression mask set
78.285 +*/
78.286 +#define initMaskSet(P) memset(P, 0, sizeof(*P))
78.287 +
78.288 +/*
78.289 +** Return the bitmask for the given cursor number. Return 0 if
78.290 +** iCursor is not in the set.
78.291 +*/
78.292 +static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
78.293 + int i;
78.294 + for(i=0; i<pMaskSet->n; i++){
78.295 + if( pMaskSet->ix[i]==iCursor ){
78.296 + return ((Bitmask)1)<<i;
78.297 + }
78.298 + }
78.299 + return 0;
78.300 +}
78.301 +
78.302 +/*
78.303 +** Create a new mask for cursor iCursor.
78.304 +**
78.305 +** There is one cursor per table in the FROM clause. The number of
78.306 +** tables in the FROM clause is limited by a test early in the
78.307 +** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
78.308 +** array will never overflow.
78.309 +*/
78.310 +static void createMask(ExprMaskSet *pMaskSet, int iCursor){
78.311 + assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
78.312 + pMaskSet->ix[pMaskSet->n++] = iCursor;
78.313 +}
78.314 +
78.315 +/*
78.316 +** This routine walks (recursively) an expression tree and generates
78.317 +** a bitmask indicating which tables are used in that expression
78.318 +** tree.
78.319 +**
78.320 +** In order for this routine to work, the calling function must have
78.321 +** previously invoked sqlite3ExprResolveNames() on the expression. See
78.322 +** the header comment on that routine for additional information.
78.323 +** The sqlite3ExprResolveNames() routines looks for column names and
78.324 +** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
78.325 +** the VDBE cursor number of the table. This routine just has to
78.326 +** translate the cursor numbers into bitmask values and OR all
78.327 +** the bitmasks together.
78.328 +*/
78.329 +static Bitmask exprListTableUsage(ExprMaskSet*, ExprList*);
78.330 +static Bitmask exprSelectTableUsage(ExprMaskSet*, Select*);
78.331 +static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
78.332 + Bitmask mask = 0;
78.333 + if( p==0 ) return 0;
78.334 + if( p->op==TK_COLUMN ){
78.335 + mask = getMask(pMaskSet, p->iTable);
78.336 + return mask;
78.337 + }
78.338 + mask = exprTableUsage(pMaskSet, p->pRight);
78.339 + mask |= exprTableUsage(pMaskSet, p->pLeft);
78.340 + mask |= exprListTableUsage(pMaskSet, p->pList);
78.341 + mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
78.342 + return mask;
78.343 +}
78.344 +static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
78.345 + int i;
78.346 + Bitmask mask = 0;
78.347 + if( pList ){
78.348 + for(i=0; i<pList->nExpr; i++){
78.349 + mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
78.350 + }
78.351 + }
78.352 + return mask;
78.353 +}
78.354 +static Bitmask exprSelectTableUsage(ExprMaskSet *pMaskSet, Select *pS){
78.355 + Bitmask mask;
78.356 + if( pS==0 ){
78.357 + mask = 0;
78.358 + }else{
78.359 + mask = exprListTableUsage(pMaskSet, pS->pEList);
78.360 + mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
78.361 + mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
78.362 + mask |= exprTableUsage(pMaskSet, pS->pWhere);
78.363 + mask |= exprTableUsage(pMaskSet, pS->pHaving);
78.364 + }
78.365 + return mask;
78.366 +}
78.367 +
78.368 +/*
78.369 +** Return TRUE if the given operator is one of the operators that is
78.370 +** allowed for an indexable WHERE clause term. The allowed operators are
78.371 +** "=", "<", ">", "<=", ">=", and "IN".
78.372 +*/
78.373 +static int allowedOp(int op){
78.374 + assert( TK_GT>TK_EQ && TK_GT<TK_GE );
78.375 + assert( TK_LT>TK_EQ && TK_LT<TK_GE );
78.376 + assert( TK_LE>TK_EQ && TK_LE<TK_GE );
78.377 + assert( TK_GE==TK_EQ+4 );
78.378 + return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
78.379 +}
78.380 +
78.381 +/*
78.382 +** Swap two objects of type T.
78.383 +*/
78.384 +#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
78.385 +
78.386 +/*
78.387 +** Commute a comparision operator. Expressions of the form "X op Y"
78.388 +** are converted into "Y op X".
78.389 +*/
78.390 +static void exprCommute(Expr *pExpr){
78.391 + assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
78.392 + SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
78.393 + SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
78.394 + if( pExpr->op>=TK_GT ){
78.395 + assert( TK_LT==TK_GT+2 );
78.396 + assert( TK_GE==TK_LE+2 );
78.397 + assert( TK_GT>TK_EQ );
78.398 + assert( TK_GT<TK_LE );
78.399 + assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
78.400 + pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
78.401 + }
78.402 +}
78.403 +
78.404 +/*
78.405 +** Translate from TK_xx operator to WO_xx bitmask.
78.406 +*/
78.407 +static int operatorMask(int op){
78.408 + int c;
78.409 + assert( allowedOp(op) );
78.410 + if( op==TK_IN ){
78.411 + c = WO_IN;
78.412 + }else if( op==TK_ISNULL ){
78.413 + c = WO_ISNULL;
78.414 + }else{
78.415 + c = WO_EQ<<(op-TK_EQ);
78.416 + }
78.417 + assert( op!=TK_ISNULL || c==WO_ISNULL );
78.418 + assert( op!=TK_IN || c==WO_IN );
78.419 + assert( op!=TK_EQ || c==WO_EQ );
78.420 + assert( op!=TK_LT || c==WO_LT );
78.421 + assert( op!=TK_LE || c==WO_LE );
78.422 + assert( op!=TK_GT || c==WO_GT );
78.423 + assert( op!=TK_GE || c==WO_GE );
78.424 + return c;
78.425 +}
78.426 +
78.427 +/*
78.428 +** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
78.429 +** where X is a reference to the iColumn of table iCur and <op> is one of
78.430 +** the WO_xx operator codes specified by the op parameter.
78.431 +** Return a pointer to the term. Return 0 if not found.
78.432 +*/
78.433 +static WhereTerm *findTerm(
78.434 + WhereClause *pWC, /* The WHERE clause to be searched */
78.435 + int iCur, /* Cursor number of LHS */
78.436 + int iColumn, /* Column number of LHS */
78.437 + Bitmask notReady, /* RHS must not overlap with this mask */
78.438 + u16 op, /* Mask of WO_xx values describing operator */
78.439 + Index *pIdx /* Must be compatible with this index, if not NULL */
78.440 +){
78.441 + WhereTerm *pTerm;
78.442 + int k;
78.443 + for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
78.444 + if( pTerm->leftCursor==iCur
78.445 + && (pTerm->prereqRight & notReady)==0
78.446 + && pTerm->leftColumn==iColumn
78.447 + && (pTerm->eOperator & op)!=0
78.448 + ){
78.449 + if( iCur>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){
78.450 + Expr *pX = pTerm->pExpr;
78.451 + CollSeq *pColl;
78.452 + char idxaff;
78.453 + int j;
78.454 + Parse *pParse = pWC->pParse;
78.455 +
78.456 + idxaff = pIdx->pTable->aCol[iColumn].affinity;
78.457 + if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
78.458 +
78.459 + /* Figure out the collation sequence required from an index for
78.460 + ** it to be useful for optimising expression pX. Store this
78.461 + ** value in variable pColl.
78.462 + */
78.463 + assert(pX->pLeft);
78.464 + pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
78.465 + if( !pColl ){
78.466 + pColl = pParse->db->pDfltColl;
78.467 + }
78.468 +
78.469 + for(j=0; j<pIdx->nColumn && pIdx->aiColumn[j]!=iColumn; j++){}
78.470 + assert( j<pIdx->nColumn );
78.471 + if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
78.472 + }
78.473 + return pTerm;
78.474 + }
78.475 + }
78.476 + return 0;
78.477 +}
78.478 +
78.479 +/* Forward reference */
78.480 +static void exprAnalyze(SrcList*, WhereClause*, int);
78.481 +
78.482 +/*
78.483 +** Call exprAnalyze on all terms in a WHERE clause.
78.484 +**
78.485 +**
78.486 +*/
78.487 +static void exprAnalyzeAll(
78.488 + SrcList *pTabList, /* the FROM clause */
78.489 + WhereClause *pWC /* the WHERE clause to be analyzed */
78.490 +){
78.491 + int i;
78.492 + for(i=pWC->nTerm-1; i>=0; i--){
78.493 + exprAnalyze(pTabList, pWC, i);
78.494 + }
78.495 +}
78.496 +
78.497 +#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
78.498 +/*
78.499 +** Check to see if the given expression is a LIKE or GLOB operator that
78.500 +** can be optimized using inequality constraints. Return TRUE if it is
78.501 +** so and false if not.
78.502 +**
78.503 +** In order for the operator to be optimizible, the RHS must be a string
78.504 +** literal that does not begin with a wildcard.
78.505 +*/
78.506 +static int isLikeOrGlob(
78.507 + sqlite3 *db, /* The database */
78.508 + Expr *pExpr, /* Test this expression */
78.509 + int *pnPattern, /* Number of non-wildcard prefix characters */
78.510 + int *pisComplete /* True if the only wildcard is % in the last character */
78.511 +){
78.512 + const char *z;
78.513 + Expr *pRight, *pLeft;
78.514 + ExprList *pList;
78.515 + int c, cnt;
78.516 + int noCase;
78.517 + char wc[3];
78.518 + CollSeq *pColl;
78.519 +
78.520 + if( !sqlite3IsLikeFunction(db, pExpr, &noCase, wc) ){
78.521 + return 0;
78.522 + }
78.523 + pList = pExpr->pList;
78.524 + pRight = pList->a[0].pExpr;
78.525 + if( pRight->op!=TK_STRING ){
78.526 + return 0;
78.527 + }
78.528 + pLeft = pList->a[1].pExpr;
78.529 + if( pLeft->op!=TK_COLUMN ){
78.530 + return 0;
78.531 + }
78.532 + pColl = pLeft->pColl;
78.533 + if( pColl==0 ){
78.534 + /* TODO: Coverage testing doesn't get this case. Is it actually possible
78.535 + ** for an expression of type TK_COLUMN to not have an assigned collation
78.536 + ** sequence at this point?
78.537 + */
78.538 + pColl = db->pDfltColl;
78.539 + }
78.540 + if( (pColl->type!=SQLITE_COLL_BINARY || noCase) &&
78.541 + (pColl->type!=SQLITE_COLL_NOCASE || !noCase) ){
78.542 + return 0;
78.543 + }
78.544 + sqlite3DequoteExpr(pRight);
78.545 + z = (char *)pRight->token.z;
78.546 + for(cnt=0; (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2]; cnt++){}
78.547 + if( cnt==0 || 255==(u8)z[cnt] ){
78.548 + return 0;
78.549 + }
78.550 + *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
78.551 + *pnPattern = cnt;
78.552 + return 1;
78.553 +}
78.554 +#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
78.555 +
78.556 +
78.557 +#ifndef SQLITE_OMIT_VIRTUALTABLE
78.558 +/*
78.559 +** Check to see if the given expression is of the form
78.560 +**
78.561 +** column MATCH expr
78.562 +**
78.563 +** If it is then return TRUE. If not, return FALSE.
78.564 +*/
78.565 +static int isMatchOfColumn(
78.566 + Expr *pExpr /* Test this expression */
78.567 +){
78.568 + ExprList *pList;
78.569 +
78.570 + if( pExpr->op!=TK_FUNCTION ){
78.571 + return 0;
78.572 + }
78.573 + if( pExpr->token.n!=5 ||
78.574 + sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
78.575 + return 0;
78.576 + }
78.577 + pList = pExpr->pList;
78.578 + if( pList->nExpr!=2 ){
78.579 + return 0;
78.580 + }
78.581 + if( pList->a[1].pExpr->op != TK_COLUMN ){
78.582 + return 0;
78.583 + }
78.584 + return 1;
78.585 +}
78.586 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
78.587 +
78.588 +/*
78.589 +** If the pBase expression originated in the ON or USING clause of
78.590 +** a join, then transfer the appropriate markings over to derived.
78.591 +*/
78.592 +static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
78.593 + pDerived->flags |= pBase->flags & EP_FromJoin;
78.594 + pDerived->iRightJoinTable = pBase->iRightJoinTable;
78.595 +}
78.596 +
78.597 +#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
78.598 +/*
78.599 +** Return TRUE if the given term of an OR clause can be converted
78.600 +** into an IN clause. The iCursor and iColumn define the left-hand
78.601 +** side of the IN clause.
78.602 +**
78.603 +** The context is that we have multiple OR-connected equality terms
78.604 +** like this:
78.605 +**
78.606 +** a=<expr1> OR a=<expr2> OR b=<expr3> OR ...
78.607 +**
78.608 +** The pOrTerm input to this routine corresponds to a single term of
78.609 +** this OR clause. In order for the term to be a condidate for
78.610 +** conversion to an IN operator, the following must be true:
78.611 +**
78.612 +** * The left-hand side of the term must be the column which
78.613 +** is identified by iCursor and iColumn.
78.614 +**
78.615 +** * If the right-hand side is also a column, then the affinities
78.616 +** of both right and left sides must be such that no type
78.617 +** conversions are required on the right. (Ticket #2249)
78.618 +**
78.619 +** If both of these conditions are true, then return true. Otherwise
78.620 +** return false.
78.621 +*/
78.622 +static int orTermIsOptCandidate(WhereTerm *pOrTerm, int iCursor, int iColumn){
78.623 + int affLeft, affRight;
78.624 + assert( pOrTerm->eOperator==WO_EQ );
78.625 + if( pOrTerm->leftCursor!=iCursor ){
78.626 + return 0;
78.627 + }
78.628 + if( pOrTerm->leftColumn!=iColumn ){
78.629 + return 0;
78.630 + }
78.631 + affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
78.632 + if( affRight==0 ){
78.633 + return 1;
78.634 + }
78.635 + affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
78.636 + if( affRight!=affLeft ){
78.637 + return 0;
78.638 + }
78.639 + return 1;
78.640 +}
78.641 +
78.642 +/*
78.643 +** Return true if the given term of an OR clause can be ignored during
78.644 +** a check to make sure all OR terms are candidates for optimization.
78.645 +** In other words, return true if a call to the orTermIsOptCandidate()
78.646 +** above returned false but it is not necessary to disqualify the
78.647 +** optimization.
78.648 +**
78.649 +** Suppose the original OR phrase was this:
78.650 +**
78.651 +** a=4 OR a=11 OR a=b
78.652 +**
78.653 +** During analysis, the third term gets flipped around and duplicate
78.654 +** so that we are left with this:
78.655 +**
78.656 +** a=4 OR a=11 OR a=b OR b=a
78.657 +**
78.658 +** Since the last two terms are duplicates, only one of them
78.659 +** has to qualify in order for the whole phrase to qualify. When
78.660 +** this routine is called, we know that pOrTerm did not qualify.
78.661 +** This routine merely checks to see if pOrTerm has a duplicate that
78.662 +** might qualify. If there is a duplicate that has not yet been
78.663 +** disqualified, then return true. If there are no duplicates, or
78.664 +** the duplicate has also been disqualifed, return false.
78.665 +*/
78.666 +static int orTermHasOkDuplicate(WhereClause *pOr, WhereTerm *pOrTerm){
78.667 + if( pOrTerm->flags & TERM_COPIED ){
78.668 + /* This is the original term. The duplicate is to the left had
78.669 + ** has not yet been analyzed and thus has not yet been disqualified. */
78.670 + return 1;
78.671 + }
78.672 + if( (pOrTerm->flags & TERM_VIRTUAL)!=0
78.673 + && (pOr->a[pOrTerm->iParent].flags & TERM_OR_OK)!=0 ){
78.674 + /* This is a duplicate term. The original qualified so this one
78.675 + ** does not have to. */
78.676 + return 1;
78.677 + }
78.678 + /* This is either a singleton term or else it is a duplicate for
78.679 + ** which the original did not qualify. Either way we are done for. */
78.680 + return 0;
78.681 +}
78.682 +#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
78.683 +
78.684 +/*
78.685 +** The input to this routine is an WhereTerm structure with only the
78.686 +** "pExpr" field filled in. The job of this routine is to analyze the
78.687 +** subexpression and populate all the other fields of the WhereTerm
78.688 +** structure.
78.689 +**
78.690 +** If the expression is of the form "<expr> <op> X" it gets commuted
78.691 +** to the standard form of "X <op> <expr>". If the expression is of
78.692 +** the form "X <op> Y" where both X and Y are columns, then the original
78.693 +** expression is unchanged and a new virtual expression of the form
78.694 +** "Y <op> X" is added to the WHERE clause and analyzed separately.
78.695 +*/
78.696 +static void exprAnalyze(
78.697 + SrcList *pSrc, /* the FROM clause */
78.698 + WhereClause *pWC, /* the WHERE clause */
78.699 + int idxTerm /* Index of the term to be analyzed */
78.700 +){
78.701 + WhereTerm *pTerm = &pWC->a[idxTerm];
78.702 + ExprMaskSet *pMaskSet = pWC->pMaskSet;
78.703 + Expr *pExpr = pTerm->pExpr;
78.704 + Bitmask prereqLeft;
78.705 + Bitmask prereqAll;
78.706 + int nPattern;
78.707 + int isComplete;
78.708 + int op;
78.709 +
78.710 + if( sqlite3MallocFailed() ) return;
78.711 + prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
78.712 + op = pExpr->op;
78.713 + if( op==TK_IN ){
78.714 + assert( pExpr->pRight==0 );
78.715 + pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
78.716 + | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
78.717 + }else if( op==TK_ISNULL ){
78.718 + pTerm->prereqRight = 0;
78.719 + }else{
78.720 + pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
78.721 + }
78.722 + prereqAll = exprTableUsage(pMaskSet, pExpr);
78.723 + if( ExprHasProperty(pExpr, EP_FromJoin) ){
78.724 + prereqAll |= getMask(pMaskSet, pExpr->iRightJoinTable);
78.725 + }
78.726 + pTerm->prereqAll = prereqAll;
78.727 + pTerm->leftCursor = -1;
78.728 + pTerm->iParent = -1;
78.729 + pTerm->eOperator = 0;
78.730 + if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
78.731 + Expr *pLeft = pExpr->pLeft;
78.732 + Expr *pRight = pExpr->pRight;
78.733 + if( pLeft->op==TK_COLUMN ){
78.734 + pTerm->leftCursor = pLeft->iTable;
78.735 + pTerm->leftColumn = pLeft->iColumn;
78.736 + pTerm->eOperator = operatorMask(op);
78.737 + }
78.738 + if( pRight && pRight->op==TK_COLUMN ){
78.739 + WhereTerm *pNew;
78.740 + Expr *pDup;
78.741 + if( pTerm->leftCursor>=0 ){
78.742 + int idxNew;
78.743 + pDup = sqlite3ExprDup(pExpr);
78.744 + if( sqlite3MallocFailed() ){
78.745 + sqlite3ExprDelete(pDup);
78.746 + return;
78.747 + }
78.748 + idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
78.749 + if( idxNew==0 ) return;
78.750 + pNew = &pWC->a[idxNew];
78.751 + pNew->iParent = idxTerm;
78.752 + pTerm = &pWC->a[idxTerm];
78.753 + pTerm->nChild = 1;
78.754 + pTerm->flags |= TERM_COPIED;
78.755 + }else{
78.756 + pDup = pExpr;
78.757 + pNew = pTerm;
78.758 + }
78.759 + exprCommute(pDup);
78.760 + pLeft = pDup->pLeft;
78.761 + pNew->leftCursor = pLeft->iTable;
78.762 + pNew->leftColumn = pLeft->iColumn;
78.763 + pNew->prereqRight = prereqLeft;
78.764 + pNew->prereqAll = prereqAll;
78.765 + pNew->eOperator = operatorMask(pDup->op);
78.766 + }
78.767 + }
78.768 +
78.769 +#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
78.770 + /* If a term is the BETWEEN operator, create two new virtual terms
78.771 + ** that define the range that the BETWEEN implements.
78.772 + */
78.773 + else if( pExpr->op==TK_BETWEEN ){
78.774 + ExprList *pList = pExpr->pList;
78.775 + int i;
78.776 + static const u8 ops[] = {TK_GE, TK_LE};
78.777 + assert( pList!=0 );
78.778 + assert( pList->nExpr==2 );
78.779 + for(i=0; i<2; i++){
78.780 + Expr *pNewExpr;
78.781 + int idxNew;
78.782 + pNewExpr = sqlite3Expr(ops[i], sqlite3ExprDup(pExpr->pLeft),
78.783 + sqlite3ExprDup(pList->a[i].pExpr), 0);
78.784 + idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
78.785 + exprAnalyze(pSrc, pWC, idxNew);
78.786 + pTerm = &pWC->a[idxTerm];
78.787 + pWC->a[idxNew].iParent = idxTerm;
78.788 + }
78.789 + pTerm->nChild = 2;
78.790 + }
78.791 +#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
78.792 +
78.793 +#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
78.794 + /* Attempt to convert OR-connected terms into an IN operator so that
78.795 + ** they can make use of indices. Example:
78.796 + **
78.797 + ** x = expr1 OR expr2 = x OR x = expr3
78.798 + **
78.799 + ** is converted into
78.800 + **
78.801 + ** x IN (expr1,expr2,expr3)
78.802 + **
78.803 + ** This optimization must be omitted if OMIT_SUBQUERY is defined because
78.804 + ** the compiler for the the IN operator is part of sub-queries.
78.805 + */
78.806 + else if( pExpr->op==TK_OR ){
78.807 + int ok;
78.808 + int i, j;
78.809 + int iColumn, iCursor;
78.810 + WhereClause sOr;
78.811 + WhereTerm *pOrTerm;
78.812 +
78.813 + assert( (pTerm->flags & TERM_DYNAMIC)==0 );
78.814 + whereClauseInit(&sOr, pWC->pParse, pMaskSet);
78.815 + whereSplit(&sOr, pExpr, TK_OR);
78.816 + exprAnalyzeAll(pSrc, &sOr);
78.817 + assert( sOr.nTerm>=2 );
78.818 + j = 0;
78.819 + do{
78.820 + assert( j<sOr.nTerm );
78.821 + iColumn = sOr.a[j].leftColumn;
78.822 + iCursor = sOr.a[j].leftCursor;
78.823 + ok = iCursor>=0;
78.824 + for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
78.825 + if( pOrTerm->eOperator!=WO_EQ ){
78.826 + goto or_not_possible;
78.827 + }
78.828 + if( orTermIsOptCandidate(pOrTerm, iCursor, iColumn) ){
78.829 + pOrTerm->flags |= TERM_OR_OK;
78.830 + }else if( orTermHasOkDuplicate(&sOr, pOrTerm) ){
78.831 + pOrTerm->flags &= ~TERM_OR_OK;
78.832 + }else{
78.833 + ok = 0;
78.834 + }
78.835 + }
78.836 + }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<2 );
78.837 + if( ok ){
78.838 + ExprList *pList = 0;
78.839 + Expr *pNew, *pDup;
78.840 + Expr *pLeft = 0;
78.841 + for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
78.842 + if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
78.843 + pDup = sqlite3ExprDup(pOrTerm->pExpr->pRight);
78.844 + pList = sqlite3ExprListAppend(pList, pDup, 0);
78.845 + pLeft = pOrTerm->pExpr->pLeft;
78.846 + }
78.847 + assert( pLeft!=0 );
78.848 + pDup = sqlite3ExprDup(pLeft);
78.849 + pNew = sqlite3Expr(TK_IN, pDup, 0, 0);
78.850 + if( pNew ){
78.851 + int idxNew;
78.852 + transferJoinMarkings(pNew, pExpr);
78.853 + pNew->pList = pList;
78.854 + idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
78.855 + exprAnalyze(pSrc, pWC, idxNew);
78.856 + pTerm = &pWC->a[idxTerm];
78.857 + pWC->a[idxNew].iParent = idxTerm;
78.858 + pTerm->nChild = 1;
78.859 + }else{
78.860 + sqlite3ExprListDelete(pList);
78.861 + }
78.862 + }
78.863 +or_not_possible:
78.864 + whereClauseClear(&sOr);
78.865 + }
78.866 +#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
78.867 +
78.868 +#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
78.869 + /* Add constraints to reduce the search space on a LIKE or GLOB
78.870 + ** operator.
78.871 + */
78.872 + if( isLikeOrGlob(pWC->pParse->db, pExpr, &nPattern, &isComplete) ){
78.873 + Expr *pLeft, *pRight;
78.874 + Expr *pStr1, *pStr2;
78.875 + Expr *pNewExpr1, *pNewExpr2;
78.876 + int idxNew1, idxNew2;
78.877 +
78.878 + pLeft = pExpr->pList->a[1].pExpr;
78.879 + pRight = pExpr->pList->a[0].pExpr;
78.880 + pStr1 = sqlite3Expr(TK_STRING, 0, 0, 0);
78.881 + if( pStr1 ){
78.882 + sqlite3TokenCopy(&pStr1->token, &pRight->token);
78.883 + pStr1->token.n = nPattern;
78.884 + pStr1->flags = EP_Dequoted;
78.885 + }
78.886 + pStr2 = sqlite3ExprDup(pStr1);
78.887 + if( pStr2 ){
78.888 + assert( pStr2->token.dyn );
78.889 + ++*(u8*)&pStr2->token.z[nPattern-1];
78.890 + }
78.891 + pNewExpr1 = sqlite3Expr(TK_GE, sqlite3ExprDup(pLeft), pStr1, 0);
78.892 + idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
78.893 + exprAnalyze(pSrc, pWC, idxNew1);
78.894 + pNewExpr2 = sqlite3Expr(TK_LT, sqlite3ExprDup(pLeft), pStr2, 0);
78.895 + idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
78.896 + exprAnalyze(pSrc, pWC, idxNew2);
78.897 + pTerm = &pWC->a[idxTerm];
78.898 + if( isComplete ){
78.899 + pWC->a[idxNew1].iParent = idxTerm;
78.900 + pWC->a[idxNew2].iParent = idxTerm;
78.901 + pTerm->nChild = 2;
78.902 + }
78.903 + }
78.904 +#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
78.905 +
78.906 +#ifndef SQLITE_OMIT_VIRTUALTABLE
78.907 + /* Add a WO_MATCH auxiliary term to the constraint set if the
78.908 + ** current expression is of the form: column MATCH expr.
78.909 + ** This information is used by the xBestIndex methods of
78.910 + ** virtual tables. The native query optimizer does not attempt
78.911 + ** to do anything with MATCH functions.
78.912 + */
78.913 + if( isMatchOfColumn(pExpr) ){
78.914 + int idxNew;
78.915 + Expr *pRight, *pLeft;
78.916 + WhereTerm *pNewTerm;
78.917 + Bitmask prereqColumn, prereqExpr;
78.918 +
78.919 + pRight = pExpr->pList->a[0].pExpr;
78.920 + pLeft = pExpr->pList->a[1].pExpr;
78.921 + prereqExpr = exprTableUsage(pMaskSet, pRight);
78.922 + prereqColumn = exprTableUsage(pMaskSet, pLeft);
78.923 + if( (prereqExpr & prereqColumn)==0 ){
78.924 + Expr *pNewExpr;
78.925 + pNewExpr = sqlite3Expr(TK_MATCH, 0, sqlite3ExprDup(pRight), 0);
78.926 + idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
78.927 + pNewTerm = &pWC->a[idxNew];
78.928 + pNewTerm->prereqRight = prereqExpr;
78.929 + pNewTerm->leftCursor = pLeft->iTable;
78.930 + pNewTerm->leftColumn = pLeft->iColumn;
78.931 + pNewTerm->eOperator = WO_MATCH;
78.932 + pNewTerm->iParent = idxTerm;
78.933 + pTerm = &pWC->a[idxTerm];
78.934 + pTerm->nChild = 1;
78.935 + pTerm->flags |= TERM_COPIED;
78.936 + pNewTerm->prereqAll = pTerm->prereqAll;
78.937 + }
78.938 + }
78.939 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
78.940 +}
78.941 +
78.942 +/*
78.943 +** Return TRUE if any of the expressions in pList->a[iFirst...] contain
78.944 +** a reference to any table other than the iBase table.
78.945 +*/
78.946 +static int referencesOtherTables(
78.947 + ExprList *pList, /* Search expressions in ths list */
78.948 + ExprMaskSet *pMaskSet, /* Mapping from tables to bitmaps */
78.949 + int iFirst, /* Be searching with the iFirst-th expression */
78.950 + int iBase /* Ignore references to this table */
78.951 +){
78.952 + Bitmask allowed = ~getMask(pMaskSet, iBase);
78.953 + while( iFirst<pList->nExpr ){
78.954 + if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
78.955 + return 1;
78.956 + }
78.957 + }
78.958 + return 0;
78.959 +}
78.960 +
78.961 +
78.962 +/*
78.963 +** This routine decides if pIdx can be used to satisfy the ORDER BY
78.964 +** clause. If it can, it returns 1. If pIdx cannot satisfy the
78.965 +** ORDER BY clause, this routine returns 0.
78.966 +**
78.967 +** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
78.968 +** left-most table in the FROM clause of that same SELECT statement and
78.969 +** the table has a cursor number of "base". pIdx is an index on pTab.
78.970 +**
78.971 +** nEqCol is the number of columns of pIdx that are used as equality
78.972 +** constraints. Any of these columns may be missing from the ORDER BY
78.973 +** clause and the match can still be a success.
78.974 +**
78.975 +** All terms of the ORDER BY that match against the index must be either
78.976 +** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
78.977 +** index do not need to satisfy this constraint.) The *pbRev value is
78.978 +** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
78.979 +** the ORDER BY clause is all ASC.
78.980 +*/
78.981 +static int isSortingIndex(
78.982 + Parse *pParse, /* Parsing context */
78.983 + ExprMaskSet *pMaskSet, /* Mapping from table indices to bitmaps */
78.984 + Index *pIdx, /* The index we are testing */
78.985 + int base, /* Cursor number for the table to be sorted */
78.986 + ExprList *pOrderBy, /* The ORDER BY clause */
78.987 + int nEqCol, /* Number of index columns with == constraints */
78.988 + int *pbRev /* Set to 1 if ORDER BY is DESC */
78.989 +){
78.990 + int i, j; /* Loop counters */
78.991 + int sortOrder = 0; /* XOR of index and ORDER BY sort direction */
78.992 + int nTerm; /* Number of ORDER BY terms */
78.993 + struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
78.994 + sqlite3 *db = pParse->db;
78.995 +
78.996 + assert( pOrderBy!=0 );
78.997 + nTerm = pOrderBy->nExpr;
78.998 + assert( nTerm>0 );
78.999 +
78.1000 + /* Match terms of the ORDER BY clause against columns of
78.1001 + ** the index.
78.1002 + **
78.1003 + ** Note that indices have pIdx->nColumn regular columns plus
78.1004 + ** one additional column containing the rowid. The rowid column
78.1005 + ** of the index is also allowed to match against the ORDER BY
78.1006 + ** clause.
78.1007 + */
78.1008 + for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
78.1009 + Expr *pExpr; /* The expression of the ORDER BY pTerm */
78.1010 + CollSeq *pColl; /* The collating sequence of pExpr */
78.1011 + int termSortOrder; /* Sort order for this term */
78.1012 + int iColumn; /* The i-th column of the index. -1 for rowid */
78.1013 + int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
78.1014 + const char *zColl; /* Name of the collating sequence for i-th index term */
78.1015 +
78.1016 + pExpr = pTerm->pExpr;
78.1017 + if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
78.1018 + /* Can not use an index sort on anything that is not a column in the
78.1019 + ** left-most table of the FROM clause */
78.1020 + break;
78.1021 + }
78.1022 + pColl = sqlite3ExprCollSeq(pParse, pExpr);
78.1023 + if( !pColl ){
78.1024 + pColl = db->pDfltColl;
78.1025 + }
78.1026 + if( i<pIdx->nColumn ){
78.1027 + iColumn = pIdx->aiColumn[i];
78.1028 + if( iColumn==pIdx->pTable->iPKey ){
78.1029 + iColumn = -1;
78.1030 + }
78.1031 + iSortOrder = pIdx->aSortOrder[i];
78.1032 + zColl = pIdx->azColl[i];
78.1033 + }else{
78.1034 + iColumn = -1;
78.1035 + iSortOrder = 0;
78.1036 + zColl = pColl->zName;
78.1037 + }
78.1038 + if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
78.1039 + /* Term j of the ORDER BY clause does not match column i of the index */
78.1040 + if( i<nEqCol ){
78.1041 + /* If an index column that is constrained by == fails to match an
78.1042 + ** ORDER BY term, that is OK. Just ignore that column of the index
78.1043 + */
78.1044 + continue;
78.1045 + }else{
78.1046 + /* If an index column fails to match and is not constrained by ==
78.1047 + ** then the index cannot satisfy the ORDER BY constraint.
78.1048 + */
78.1049 + return 0;
78.1050 + }
78.1051 + }
78.1052 + assert( pIdx->aSortOrder!=0 );
78.1053 + assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
78.1054 + assert( iSortOrder==0 || iSortOrder==1 );
78.1055 + termSortOrder = iSortOrder ^ pTerm->sortOrder;
78.1056 + if( i>nEqCol ){
78.1057 + if( termSortOrder!=sortOrder ){
78.1058 + /* Indices can only be used if all ORDER BY terms past the
78.1059 + ** equality constraints are all either DESC or ASC. */
78.1060 + return 0;
78.1061 + }
78.1062 + }else{
78.1063 + sortOrder = termSortOrder;
78.1064 + }
78.1065 + j++;
78.1066 + pTerm++;
78.1067 + if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
78.1068 + /* If the indexed column is the primary key and everything matches
78.1069 + ** so far and none of the ORDER BY terms to the right reference other
78.1070 + ** tables in the join, then we are assured that the index can be used
78.1071 + ** to sort because the primary key is unique and so none of the other
78.1072 + ** columns will make any difference
78.1073 + */
78.1074 + j = nTerm;
78.1075 + }
78.1076 + }
78.1077 +
78.1078 + *pbRev = sortOrder!=0;
78.1079 + if( j>=nTerm ){
78.1080 + /* All terms of the ORDER BY clause are covered by this index so
78.1081 + ** this index can be used for sorting. */
78.1082 + return 1;
78.1083 + }
78.1084 + if( pIdx->onError!=OE_None && i==pIdx->nColumn
78.1085 + && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
78.1086 + /* All terms of this index match some prefix of the ORDER BY clause
78.1087 + ** and the index is UNIQUE and no terms on the tail of the ORDER BY
78.1088 + ** clause reference other tables in a join. If this is all true then
78.1089 + ** the order by clause is superfluous. */
78.1090 + return 1;
78.1091 + }
78.1092 + return 0;
78.1093 +}
78.1094 +
78.1095 +/*
78.1096 +** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
78.1097 +** by sorting in order of ROWID. Return true if so and set *pbRev to be
78.1098 +** true for reverse ROWID and false for forward ROWID order.
78.1099 +*/
78.1100 +static int sortableByRowid(
78.1101 + int base, /* Cursor number for table to be sorted */
78.1102 + ExprList *pOrderBy, /* The ORDER BY clause */
78.1103 + ExprMaskSet *pMaskSet, /* Mapping from tables to bitmaps */
78.1104 + int *pbRev /* Set to 1 if ORDER BY is DESC */
78.1105 +){
78.1106 + Expr *p;
78.1107 +
78.1108 + assert( pOrderBy!=0 );
78.1109 + assert( pOrderBy->nExpr>0 );
78.1110 + p = pOrderBy->a[0].pExpr;
78.1111 + if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
78.1112 + && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
78.1113 + *pbRev = pOrderBy->a[0].sortOrder;
78.1114 + return 1;
78.1115 + }
78.1116 + return 0;
78.1117 +}
78.1118 +
78.1119 +/*
78.1120 +** Prepare a crude estimate of the logarithm of the input value.
78.1121 +** The results need not be exact. This is only used for estimating
78.1122 +** the total cost of performing operatings with O(logN) or O(NlogN)
78.1123 +** complexity. Because N is just a guess, it is no great tragedy if
78.1124 +** logN is a little off.
78.1125 +*/
78.1126 +static double estLog(double N){
78.1127 + double logN = 1;
78.1128 + double x = 10;
78.1129 + while( N>x ){
78.1130 + logN += 1;
78.1131 + x *= 10;
78.1132 + }
78.1133 + return logN;
78.1134 +}
78.1135 +
78.1136 +/*
78.1137 +** Two routines for printing the content of an sqlite3_index_info
78.1138 +** structure. Used for testing and debugging only. If neither
78.1139 +** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
78.1140 +** are no-ops.
78.1141 +*/
78.1142 +#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
78.1143 +static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
78.1144 + int i;
78.1145 + if( !sqlite3_where_trace ) return;
78.1146 + for(i=0; i<p->nConstraint; i++){
78.1147 + sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
78.1148 + i,
78.1149 + p->aConstraint[i].iColumn,
78.1150 + p->aConstraint[i].iTermOffset,
78.1151 + p->aConstraint[i].op,
78.1152 + p->aConstraint[i].usable);
78.1153 + }
78.1154 + for(i=0; i<p->nOrderBy; i++){
78.1155 + sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
78.1156 + i,
78.1157 + p->aOrderBy[i].iColumn,
78.1158 + p->aOrderBy[i].desc);
78.1159 + }
78.1160 +}
78.1161 +static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
78.1162 + int i;
78.1163 + if( !sqlite3_where_trace ) return;
78.1164 + for(i=0; i<p->nConstraint; i++){
78.1165 + sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
78.1166 + i,
78.1167 + p->aConstraintUsage[i].argvIndex,
78.1168 + p->aConstraintUsage[i].omit);
78.1169 + }
78.1170 + sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
78.1171 + sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
78.1172 + sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
78.1173 + sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
78.1174 +}
78.1175 +#else
78.1176 +#define TRACE_IDX_INPUTS(A)
78.1177 +#define TRACE_IDX_OUTPUTS(A)
78.1178 +#endif
78.1179 +
78.1180 +#ifndef SQLITE_OMIT_VIRTUALTABLE
78.1181 +/*
78.1182 +** Compute the best index for a virtual table.
78.1183 +**
78.1184 +** The best index is computed by the xBestIndex method of the virtual
78.1185 +** table module. This routine is really just a wrapper that sets up
78.1186 +** the sqlite3_index_info structure that is used to communicate with
78.1187 +** xBestIndex.
78.1188 +**
78.1189 +** In a join, this routine might be called multiple times for the
78.1190 +** same virtual table. The sqlite3_index_info structure is created
78.1191 +** and initialized on the first invocation and reused on all subsequent
78.1192 +** invocations. The sqlite3_index_info structure is also used when
78.1193 +** code is generated to access the virtual table. The whereInfoDelete()
78.1194 +** routine takes care of freeing the sqlite3_index_info structure after
78.1195 +** everybody has finished with it.
78.1196 +*/
78.1197 +static double bestVirtualIndex(
78.1198 + Parse *pParse, /* The parsing context */
78.1199 + WhereClause *pWC, /* The WHERE clause */
78.1200 + struct SrcList_item *pSrc, /* The FROM clause term to search */
78.1201 + Bitmask notReady, /* Mask of cursors that are not available */
78.1202 + ExprList *pOrderBy, /* The order by clause */
78.1203 + int orderByUsable, /* True if we can potential sort */
78.1204 + sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
78.1205 +){
78.1206 + Table *pTab = pSrc->pTab;
78.1207 + sqlite3_index_info *pIdxInfo;
78.1208 + struct sqlite3_index_constraint *pIdxCons;
78.1209 + struct sqlite3_index_orderby *pIdxOrderBy;
78.1210 + struct sqlite3_index_constraint_usage *pUsage;
78.1211 + WhereTerm *pTerm;
78.1212 + int i, j;
78.1213 + int nOrderBy;
78.1214 + int rc;
78.1215 +
78.1216 + /* If the sqlite3_index_info structure has not been previously
78.1217 + ** allocated and initialized for this virtual table, then allocate
78.1218 + ** and initialize it now
78.1219 + */
78.1220 + pIdxInfo = *ppIdxInfo;
78.1221 + if( pIdxInfo==0 ){
78.1222 + WhereTerm *pTerm;
78.1223 + int nTerm;
78.1224 + WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
78.1225 +
78.1226 + /* Count the number of possible WHERE clause constraints referring
78.1227 + ** to this virtual table */
78.1228 + for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
78.1229 + if( pTerm->leftCursor != pSrc->iCursor ) continue;
78.1230 + if( pTerm->eOperator==WO_IN ) continue;
78.1231 + nTerm++;
78.1232 + }
78.1233 +
78.1234 + /* If the ORDER BY clause contains only columns in the current
78.1235 + ** virtual table then allocate space for the aOrderBy part of
78.1236 + ** the sqlite3_index_info structure.
78.1237 + */
78.1238 + nOrderBy = 0;
78.1239 + if( pOrderBy ){
78.1240 + for(i=0; i<pOrderBy->nExpr; i++){
78.1241 + Expr *pExpr = pOrderBy->a[i].pExpr;
78.1242 + if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
78.1243 + }
78.1244 + if( i==pOrderBy->nExpr ){
78.1245 + nOrderBy = pOrderBy->nExpr;
78.1246 + }
78.1247 + }
78.1248 +
78.1249 + /* Allocate the sqlite3_index_info structure
78.1250 + */
78.1251 + pIdxInfo = sqliteMalloc( sizeof(*pIdxInfo)
78.1252 + + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
78.1253 + + sizeof(*pIdxOrderBy)*nOrderBy );
78.1254 + if( pIdxInfo==0 ){
78.1255 + sqlite3ErrorMsg(pParse, "out of memory");
78.1256 + return 0.0;
78.1257 + }
78.1258 + *ppIdxInfo = pIdxInfo;
78.1259 +
78.1260 + /* Initialize the structure. The sqlite3_index_info structure contains
78.1261 + ** many fields that are declared "const" to prevent xBestIndex from
78.1262 + ** changing them. We have to do some funky casting in order to
78.1263 + ** initialize those fields.
78.1264 + */
78.1265 + pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
78.1266 + pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
78.1267 + pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
78.1268 + *(int*)&pIdxInfo->nConstraint = nTerm;
78.1269 + *(int*)&pIdxInfo->nOrderBy = nOrderBy;
78.1270 + *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
78.1271 + *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
78.1272 + *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
78.1273 + pUsage;
78.1274 +
78.1275 + for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
78.1276 + if( pTerm->leftCursor != pSrc->iCursor ) continue;
78.1277 + if( pTerm->eOperator==WO_IN ) continue;
78.1278 + pIdxCons[j].iColumn = pTerm->leftColumn;
78.1279 + pIdxCons[j].iTermOffset = i;
78.1280 + pIdxCons[j].op = (unsigned char)pTerm->eOperator;
78.1281 + /* The direct assignment in the previous line is possible only because
78.1282 + ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
78.1283 + ** following asserts verify this fact. */
78.1284 + assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
78.1285 + assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
78.1286 + assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
78.1287 + assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
78.1288 + assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
78.1289 + assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
78.1290 + assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
78.1291 + j++;
78.1292 + }
78.1293 + for(i=0; i<nOrderBy; i++){
78.1294 + Expr *pExpr = pOrderBy->a[i].pExpr;
78.1295 + pIdxOrderBy[i].iColumn = pExpr->iColumn;
78.1296 + pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
78.1297 + }
78.1298 + }
78.1299 +
78.1300 + /* At this point, the sqlite3_index_info structure that pIdxInfo points
78.1301 + ** to will have been initialized, either during the current invocation or
78.1302 + ** during some prior invocation. Now we just have to customize the
78.1303 + ** details of pIdxInfo for the current invocation and pass it to
78.1304 + ** xBestIndex.
78.1305 + */
78.1306 +
78.1307 + /* The module name must be defined. Also, by this point there must
78.1308 + ** be a pointer to an sqlite3_vtab structure. Otherwise
78.1309 + ** sqlite3ViewGetColumnNames() would have picked up the error.
78.1310 + */
78.1311 + assert( pTab->azModuleArg && pTab->azModuleArg[0] );
78.1312 + assert( pTab->pVtab );
78.1313 +#if 0
78.1314 + if( pTab->pVtab==0 ){
78.1315 + sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
78.1316 + pTab->azModuleArg[0], pTab->zName);
78.1317 + return 0.0;
78.1318 + }
78.1319 +#endif
78.1320 +
78.1321 + /* Set the aConstraint[].usable fields and initialize all
78.1322 + ** output variables to zero.
78.1323 + **
78.1324 + ** aConstraint[].usable is true for constraints where the right-hand
78.1325 + ** side contains only references to tables to the left of the current
78.1326 + ** table. In other words, if the constraint is of the form:
78.1327 + **
78.1328 + ** column = expr
78.1329 + **
78.1330 + ** and we are evaluating a join, then the constraint on column is
78.1331 + ** only valid if all tables referenced in expr occur to the left
78.1332 + ** of the table containing column.
78.1333 + **
78.1334 + ** The aConstraints[] array contains entries for all constraints
78.1335 + ** on the current table. That way we only have to compute it once
78.1336 + ** even though we might try to pick the best index multiple times.
78.1337 + ** For each attempt at picking an index, the order of tables in the
78.1338 + ** join might be different so we have to recompute the usable flag
78.1339 + ** each time.
78.1340 + */
78.1341 + pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
78.1342 + pUsage = pIdxInfo->aConstraintUsage;
78.1343 + for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
78.1344 + j = pIdxCons->iTermOffset;
78.1345 + pTerm = &pWC->a[j];
78.1346 + pIdxCons->usable = (pTerm->prereqRight & notReady)==0;
78.1347 + }
78.1348 + memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
78.1349 + if( pIdxInfo->needToFreeIdxStr ){
78.1350 + sqlite3_free(pIdxInfo->idxStr);
78.1351 + }
78.1352 + pIdxInfo->idxStr = 0;
78.1353 + pIdxInfo->idxNum = 0;
78.1354 + pIdxInfo->needToFreeIdxStr = 0;
78.1355 + pIdxInfo->orderByConsumed = 0;
78.1356 + pIdxInfo->estimatedCost = SQLITE_BIG_DBL / 2.0;
78.1357 + nOrderBy = pIdxInfo->nOrderBy;
78.1358 + if( pIdxInfo->nOrderBy && !orderByUsable ){
78.1359 + *(int*)&pIdxInfo->nOrderBy = 0;
78.1360 + }
78.1361 +
78.1362 + sqlite3SafetyOff(pParse->db);
78.1363 + WHERETRACE(("xBestIndex for %s\n", pTab->zName));
78.1364 + TRACE_IDX_INPUTS(pIdxInfo);
78.1365 + rc = pTab->pVtab->pModule->xBestIndex(pTab->pVtab, pIdxInfo);
78.1366 + TRACE_IDX_OUTPUTS(pIdxInfo);
78.1367 + if( rc!=SQLITE_OK ){
78.1368 + if( rc==SQLITE_NOMEM ){
78.1369 + sqlite3FailedMalloc();
78.1370 + }else {
78.1371 + sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
78.1372 + }
78.1373 + sqlite3SafetyOn(pParse->db);
78.1374 + }else{
78.1375 + rc = sqlite3SafetyOn(pParse->db);
78.1376 + }
78.1377 + *(int*)&pIdxInfo->nOrderBy = nOrderBy;
78.1378 +
78.1379 + return pIdxInfo->estimatedCost;
78.1380 +}
78.1381 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
78.1382 +
78.1383 +/*
78.1384 +** Find the best index for accessing a particular table. Return a pointer
78.1385 +** to the index, flags that describe how the index should be used, the
78.1386 +** number of equality constraints, and the "cost" for this index.
78.1387 +**
78.1388 +** The lowest cost index wins. The cost is an estimate of the amount of
78.1389 +** CPU and disk I/O need to process the request using the selected index.
78.1390 +** Factors that influence cost include:
78.1391 +**
78.1392 +** * The estimated number of rows that will be retrieved. (The
78.1393 +** fewer the better.)
78.1394 +**
78.1395 +** * Whether or not sorting must occur.
78.1396 +**
78.1397 +** * Whether or not there must be separate lookups in the
78.1398 +** index and in the main table.
78.1399 +**
78.1400 +*/
78.1401 +static double bestIndex(
78.1402 + Parse *pParse, /* The parsing context */
78.1403 + WhereClause *pWC, /* The WHERE clause */
78.1404 + struct SrcList_item *pSrc, /* The FROM clause term to search */
78.1405 + Bitmask notReady, /* Mask of cursors that are not available */
78.1406 + ExprList *pOrderBy, /* The order by clause */
78.1407 + Index **ppIndex, /* Make *ppIndex point to the best index */
78.1408 + int *pFlags, /* Put flags describing this choice in *pFlags */
78.1409 + int *pnEq /* Put the number of == or IN constraints here */
78.1410 +){
78.1411 + WhereTerm *pTerm;
78.1412 + Index *bestIdx = 0; /* Index that gives the lowest cost */
78.1413 + double lowestCost; /* The cost of using bestIdx */
78.1414 + int bestFlags = 0; /* Flags associated with bestIdx */
78.1415 + int bestNEq = 0; /* Best value for nEq */
78.1416 + int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
78.1417 + Index *pProbe; /* An index we are evaluating */
78.1418 + int rev; /* True to scan in reverse order */
78.1419 + int flags; /* Flags associated with pProbe */
78.1420 + int nEq; /* Number of == or IN constraints */
78.1421 + int eqTermMask; /* Mask of valid equality operators */
78.1422 + double cost; /* Cost of using pProbe */
78.1423 +
78.1424 + WHERETRACE(("bestIndex: tbl=%s notReady=%x\n", pSrc->pTab->zName, notReady));
78.1425 + lowestCost = SQLITE_BIG_DBL;
78.1426 + pProbe = pSrc->pTab->pIndex;
78.1427 +
78.1428 + /* If the table has no indices and there are no terms in the where
78.1429 + ** clause that refer to the ROWID, then we will never be able to do
78.1430 + ** anything other than a full table scan on this table. We might as
78.1431 + ** well put it first in the join order. That way, perhaps it can be
78.1432 + ** referenced by other tables in the join.
78.1433 + */
78.1434 + if( pProbe==0 &&
78.1435 + findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
78.1436 + (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
78.1437 + *pFlags = 0;
78.1438 + *ppIndex = 0;
78.1439 + *pnEq = 0;
78.1440 + return 0.0;
78.1441 + }
78.1442 +
78.1443 + /* Check for a rowid=EXPR or rowid IN (...) constraints
78.1444 + */
78.1445 + pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
78.1446 + if( pTerm ){
78.1447 + Expr *pExpr;
78.1448 + *ppIndex = 0;
78.1449 + bestFlags = WHERE_ROWID_EQ;
78.1450 + if( pTerm->eOperator & WO_EQ ){
78.1451 + /* Rowid== is always the best pick. Look no further. Because only
78.1452 + ** a single row is generated, output is always in sorted order */
78.1453 + *pFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
78.1454 + *pnEq = 1;
78.1455 + WHERETRACE(("... best is rowid\n"));
78.1456 + return 0.0;
78.1457 + }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
78.1458 + /* Rowid IN (LIST): cost is NlogN where N is the number of list
78.1459 + ** elements. */
78.1460 + lowestCost = pExpr->pList->nExpr;
78.1461 + lowestCost *= estLog(lowestCost);
78.1462 + }else{
78.1463 + /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
78.1464 + ** in the result of the inner select. We have no way to estimate
78.1465 + ** that value so make a wild guess. */
78.1466 + lowestCost = 200;
78.1467 + }
78.1468 + WHERETRACE(("... rowid IN cost: %.9g\n", lowestCost));
78.1469 + }
78.1470 +
78.1471 + /* Estimate the cost of a table scan. If we do not know how many
78.1472 + ** entries are in the table, use 1 million as a guess.
78.1473 + */
78.1474 + cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
78.1475 + WHERETRACE(("... table scan base cost: %.9g\n", cost));
78.1476 + flags = WHERE_ROWID_RANGE;
78.1477 +
78.1478 + /* Check for constraints on a range of rowids in a table scan.
78.1479 + */
78.1480 + pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
78.1481 + if( pTerm ){
78.1482 + if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
78.1483 + flags |= WHERE_TOP_LIMIT;
78.1484 + cost /= 3; /* Guess that rowid<EXPR eliminates two-thirds or rows */
78.1485 + }
78.1486 + if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
78.1487 + flags |= WHERE_BTM_LIMIT;
78.1488 + cost /= 3; /* Guess that rowid>EXPR eliminates two-thirds of rows */
78.1489 + }
78.1490 + WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
78.1491 + }else{
78.1492 + flags = 0;
78.1493 + }
78.1494 +
78.1495 + /* If the table scan does not satisfy the ORDER BY clause, increase
78.1496 + ** the cost by NlogN to cover the expense of sorting. */
78.1497 + if( pOrderBy ){
78.1498 + if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
78.1499 + flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
78.1500 + if( rev ){
78.1501 + flags |= WHERE_REVERSE;
78.1502 + }
78.1503 + }else{
78.1504 + cost += cost*estLog(cost);
78.1505 + WHERETRACE(("... sorting increases cost to %.9g\n", cost));
78.1506 + }
78.1507 + }
78.1508 + if( cost<lowestCost ){
78.1509 + lowestCost = cost;
78.1510 + bestFlags = flags;
78.1511 + }
78.1512 +
78.1513 + /* If the pSrc table is the right table of a LEFT JOIN then we may not
78.1514 + ** use an index to satisfy IS NULL constraints on that table. This is
78.1515 + ** because columns might end up being NULL if the table does not match -
78.1516 + ** a circumstance which the index cannot help us discover. Ticket #2177.
78.1517 + */
78.1518 + if( (pSrc->jointype & JT_LEFT)!=0 ){
78.1519 + eqTermMask = WO_EQ|WO_IN;
78.1520 + }else{
78.1521 + eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
78.1522 + }
78.1523 +
78.1524 + /* Look at each index.
78.1525 + */
78.1526 + for(; pProbe; pProbe=pProbe->pNext){
78.1527 + int i; /* Loop counter */
78.1528 + double inMultiplier = 1;
78.1529 +
78.1530 + WHERETRACE(("... index %s:\n", pProbe->zName));
78.1531 +
78.1532 + /* Count the number of columns in the index that are satisfied
78.1533 + ** by x=EXPR constraints or x IN (...) constraints.
78.1534 + */
78.1535 + flags = 0;
78.1536 + for(i=0; i<pProbe->nColumn; i++){
78.1537 + int j = pProbe->aiColumn[i];
78.1538 + pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
78.1539 + if( pTerm==0 ) break;
78.1540 + flags |= WHERE_COLUMN_EQ;
78.1541 + if( pTerm->eOperator & WO_IN ){
78.1542 + Expr *pExpr = pTerm->pExpr;
78.1543 + flags |= WHERE_COLUMN_IN;
78.1544 + if( pExpr->pSelect!=0 ){
78.1545 + inMultiplier *= 25;
78.1546 + }else if( pExpr->pList!=0 ){
78.1547 + inMultiplier *= pExpr->pList->nExpr + 1;
78.1548 + }
78.1549 + }
78.1550 + }
78.1551 + cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
78.1552 + nEq = i;
78.1553 + if( pProbe->onError!=OE_None && (flags & WHERE_COLUMN_IN)==0
78.1554 + && nEq==pProbe->nColumn ){
78.1555 + flags |= WHERE_UNIQUE;
78.1556 + }
78.1557 + WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n", nEq, inMultiplier, cost));
78.1558 +
78.1559 + /* Look for range constraints
78.1560 + */
78.1561 + if( nEq<pProbe->nColumn ){
78.1562 + int j = pProbe->aiColumn[nEq];
78.1563 + pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
78.1564 + if( pTerm ){
78.1565 + flags |= WHERE_COLUMN_RANGE;
78.1566 + if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
78.1567 + flags |= WHERE_TOP_LIMIT;
78.1568 + cost /= 3;
78.1569 + }
78.1570 + if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
78.1571 + flags |= WHERE_BTM_LIMIT;
78.1572 + cost /= 3;
78.1573 + }
78.1574 + WHERETRACE(("...... range reduces cost to %.9g\n", cost));
78.1575 + }
78.1576 + }
78.1577 +
78.1578 + /* Add the additional cost of sorting if that is a factor.
78.1579 + */
78.1580 + if( pOrderBy ){
78.1581 + if( (flags & WHERE_COLUMN_IN)==0 &&
78.1582 + isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
78.1583 + if( flags==0 ){
78.1584 + flags = WHERE_COLUMN_RANGE;
78.1585 + }
78.1586 + flags |= WHERE_ORDERBY;
78.1587 + if( rev ){
78.1588 + flags |= WHERE_REVERSE;
78.1589 + }
78.1590 + }else{
78.1591 + cost += cost*estLog(cost);
78.1592 + WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
78.1593 + }
78.1594 + }
78.1595 +
78.1596 + /* Check to see if we can get away with using just the index without
78.1597 + ** ever reading the table. If that is the case, then halve the
78.1598 + ** cost of this index.
78.1599 + */
78.1600 + if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
78.1601 + Bitmask m = pSrc->colUsed;
78.1602 + int j;
78.1603 + for(j=0; j<pProbe->nColumn; j++){
78.1604 + int x = pProbe->aiColumn[j];
78.1605 + if( x<BMS-1 ){
78.1606 + m &= ~(((Bitmask)1)<<x);
78.1607 + }
78.1608 + }
78.1609 + if( m==0 ){
78.1610 + flags |= WHERE_IDX_ONLY;
78.1611 + cost /= 2;
78.1612 + WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
78.1613 + }
78.1614 + }
78.1615 +
78.1616 + /* If this index has achieved the lowest cost so far, then use it.
78.1617 + */
78.1618 + if( cost < lowestCost ){
78.1619 + bestIdx = pProbe;
78.1620 + lowestCost = cost;
78.1621 + assert( flags!=0 );
78.1622 + bestFlags = flags;
78.1623 + bestNEq = nEq;
78.1624 + }
78.1625 + }
78.1626 +
78.1627 + /* Report the best result
78.1628 + */
78.1629 + *ppIndex = bestIdx;
78.1630 + WHERETRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
78.1631 + bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
78.1632 + *pFlags = bestFlags | eqTermMask;
78.1633 + *pnEq = bestNEq;
78.1634 + return lowestCost;
78.1635 +}
78.1636 +
78.1637 +
78.1638 +/*
78.1639 +** Disable a term in the WHERE clause. Except, do not disable the term
78.1640 +** if it controls a LEFT OUTER JOIN and it did not originate in the ON
78.1641 +** or USING clause of that join.
78.1642 +**
78.1643 +** Consider the term t2.z='ok' in the following queries:
78.1644 +**
78.1645 +** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
78.1646 +** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
78.1647 +** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
78.1648 +**
78.1649 +** The t2.z='ok' is disabled in the in (2) because it originates
78.1650 +** in the ON clause. The term is disabled in (3) because it is not part
78.1651 +** of a LEFT OUTER JOIN. In (1), the term is not disabled.
78.1652 +**
78.1653 +** Disabling a term causes that term to not be tested in the inner loop
78.1654 +** of the join. Disabling is an optimization. When terms are satisfied
78.1655 +** by indices, we disable them to prevent redundant tests in the inner
78.1656 +** loop. We would get the correct results if nothing were ever disabled,
78.1657 +** but joins might run a little slower. The trick is to disable as much
78.1658 +** as we can without disabling too much. If we disabled in (1), we'd get
78.1659 +** the wrong answer. See ticket #813.
78.1660 +*/
78.1661 +static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
78.1662 + if( pTerm
78.1663 + && (pTerm->flags & TERM_CODED)==0
78.1664 + && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
78.1665 + ){
78.1666 + pTerm->flags |= TERM_CODED;
78.1667 + if( pTerm->iParent>=0 ){
78.1668 + WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
78.1669 + if( (--pOther->nChild)==0 ){
78.1670 + disableTerm(pLevel, pOther);
78.1671 + }
78.1672 + }
78.1673 + }
78.1674 +}
78.1675 +
78.1676 +/*
78.1677 +** Generate code that builds a probe for an index.
78.1678 +**
78.1679 +** There should be nColumn values on the stack. The index
78.1680 +** to be probed is pIdx. Pop the values from the stack and
78.1681 +** replace them all with a single record that is the index
78.1682 +** problem.
78.1683 +*/
78.1684 +static void buildIndexProbe(
78.1685 + Vdbe *v, /* Generate code into this VM */
78.1686 + int nColumn, /* The number of columns to check for NULL */
78.1687 + Index *pIdx /* Index that we will be searching */
78.1688 +){
78.1689 + sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
78.1690 + sqlite3IndexAffinityStr(v, pIdx);
78.1691 +}
78.1692 +
78.1693 +
78.1694 +/*
78.1695 +** Generate code for a single equality term of the WHERE clause. An equality
78.1696 +** term can be either X=expr or X IN (...). pTerm is the term to be
78.1697 +** coded.
78.1698 +**
78.1699 +** The current value for the constraint is left on the top of the stack.
78.1700 +**
78.1701 +** For a constraint of the form X=expr, the expression is evaluated and its
78.1702 +** result is left on the stack. For constraints of the form X IN (...)
78.1703 +** this routine sets up a loop that will iterate over all values of X.
78.1704 +*/
78.1705 +static void codeEqualityTerm(
78.1706 + Parse *pParse, /* The parsing context */
78.1707 + WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
78.1708 + WhereLevel *pLevel /* When level of the FROM clause we are working on */
78.1709 +){
78.1710 + Expr *pX = pTerm->pExpr;
78.1711 + Vdbe *v = pParse->pVdbe;
78.1712 + if( pX->op==TK_EQ ){
78.1713 + sqlite3ExprCode(pParse, pX->pRight);
78.1714 + }else if( pX->op==TK_ISNULL ){
78.1715 + sqlite3VdbeAddOp(v, OP_Null, 0, 0);
78.1716 +#ifndef SQLITE_OMIT_SUBQUERY
78.1717 + }else{
78.1718 + int iTab;
78.1719 + struct InLoop *pIn;
78.1720 +
78.1721 + assert( pX->op==TK_IN );
78.1722 + sqlite3CodeSubselect(pParse, pX);
78.1723 + iTab = pX->iTable;
78.1724 + sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
78.1725 + VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
78.1726 + if( pLevel->nIn==0 ){
78.1727 + pLevel->nxt = sqlite3VdbeMakeLabel(v);
78.1728 + }
78.1729 + pLevel->nIn++;
78.1730 + pLevel->aInLoop = sqliteReallocOrFree(pLevel->aInLoop,
78.1731 + sizeof(pLevel->aInLoop[0])*pLevel->nIn);
78.1732 + pIn = pLevel->aInLoop;
78.1733 + if( pIn ){
78.1734 + pIn += pLevel->nIn - 1;
78.1735 + pIn->iCur = iTab;
78.1736 + pIn->topAddr = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
78.1737 + sqlite3VdbeAddOp(v, OP_IsNull, -1, 0);
78.1738 + }else{
78.1739 + pLevel->nIn = 0;
78.1740 + }
78.1741 +#endif
78.1742 + }
78.1743 + disableTerm(pLevel, pTerm);
78.1744 +}
78.1745 +
78.1746 +/*
78.1747 +** Generate code that will evaluate all == and IN constraints for an
78.1748 +** index. The values for all constraints are left on the stack.
78.1749 +**
78.1750 +** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
78.1751 +** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
78.1752 +** The index has as many as three equality constraints, but in this
78.1753 +** example, the third "c" value is an inequality. So only two
78.1754 +** constraints are coded. This routine will generate code to evaluate
78.1755 +** a==5 and b IN (1,2,3). The current values for a and b will be left
78.1756 +** on the stack - a is the deepest and b the shallowest.
78.1757 +**
78.1758 +** In the example above nEq==2. But this subroutine works for any value
78.1759 +** of nEq including 0. If nEq==0, this routine is nearly a no-op.
78.1760 +** The only thing it does is allocate the pLevel->iMem memory cell.
78.1761 +**
78.1762 +** This routine always allocates at least one memory cell and puts
78.1763 +** the address of that memory cell in pLevel->iMem. The code that
78.1764 +** calls this routine will use pLevel->iMem to store the termination
78.1765 +** key value of the loop. If one or more IN operators appear, then
78.1766 +** this routine allocates an additional nEq memory cells for internal
78.1767 +** use.
78.1768 +*/
78.1769 +static void codeAllEqualityTerms(
78.1770 + Parse *pParse, /* Parsing context */
78.1771 + WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
78.1772 + WhereClause *pWC, /* The WHERE clause */
78.1773 + Bitmask notReady /* Which parts of FROM have not yet been coded */
78.1774 +){
78.1775 + int nEq = pLevel->nEq; /* The number of == or IN constraints to code */
78.1776 + int termsInMem = 0; /* If true, store value in mem[] cells */
78.1777 + Vdbe *v = pParse->pVdbe; /* The virtual machine under construction */
78.1778 + Index *pIdx = pLevel->pIdx; /* The index being used for this loop */
78.1779 + int iCur = pLevel->iTabCur; /* The cursor of the table */
78.1780 + WhereTerm *pTerm; /* A single constraint term */
78.1781 + int j; /* Loop counter */
78.1782 +
78.1783 + /* Figure out how many memory cells we will need then allocate them.
78.1784 + ** We always need at least one used to store the loop terminator
78.1785 + ** value. If there are IN operators we'll need one for each == or
78.1786 + ** IN constraint.
78.1787 + */
78.1788 + pLevel->iMem = pParse->nMem++;
78.1789 + if( pLevel->flags & WHERE_COLUMN_IN ){
78.1790 + pParse->nMem += pLevel->nEq;
78.1791 + termsInMem = 1;
78.1792 + }
78.1793 +
78.1794 + /* Evaluate the equality constraints
78.1795 + */
78.1796 + assert( pIdx->nColumn>=nEq );
78.1797 + for(j=0; j<nEq; j++){
78.1798 + int k = pIdx->aiColumn[j];
78.1799 + pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx);
78.1800 + if( pTerm==0 ) break;
78.1801 + assert( (pTerm->flags & TERM_CODED)==0 );
78.1802 + codeEqualityTerm(pParse, pTerm, pLevel);
78.1803 + if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
78.1804 + sqlite3VdbeAddOp(v, OP_IsNull, termsInMem ? -1 : -(j+1), pLevel->brk);
78.1805 + }
78.1806 + if( termsInMem ){
78.1807 + sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem+j+1, 1);
78.1808 + }
78.1809 + }
78.1810 +
78.1811 + /* Make sure all the constraint values are on the top of the stack
78.1812 + */
78.1813 + if( termsInMem ){
78.1814 + for(j=0; j<nEq; j++){
78.1815 + sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem+j+1, 0);
78.1816 + }
78.1817 + }
78.1818 +}
78.1819 +
78.1820 +#if defined(SQLITE_TEST)
78.1821 +/*
78.1822 +** The following variable holds a text description of query plan generated
78.1823 +** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
78.1824 +** overwrites the previous. This information is used for testing and
78.1825 +** analysis only.
78.1826 +*/
78.1827 +char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
78.1828 +static int nQPlan = 0; /* Next free slow in _query_plan[] */
78.1829 +
78.1830 +#endif /* SQLITE_TEST */
78.1831 +
78.1832 +
78.1833 +/*
78.1834 +** Free a WhereInfo structure
78.1835 +*/
78.1836 +static void whereInfoFree(WhereInfo *pWInfo){
78.1837 + if( pWInfo ){
78.1838 + int i;
78.1839 + for(i=0; i<pWInfo->nLevel; i++){
78.1840 + sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
78.1841 + if( pInfo ){
78.1842 + if( pInfo->needToFreeIdxStr ){
78.1843 + /* Coverage: Don't think this can be reached. By the time this
78.1844 + ** function is called, the index-strings have been passed
78.1845 + ** to the vdbe layer for deletion.
78.1846 + */
78.1847 + sqlite3_free(pInfo->idxStr);
78.1848 + }
78.1849 + sqliteFree(pInfo);
78.1850 + }
78.1851 + }
78.1852 + sqliteFree(pWInfo);
78.1853 + }
78.1854 +}
78.1855 +
78.1856 +
78.1857 +/*
78.1858 +** Generate the beginning of the loop used for WHERE clause processing.
78.1859 +** The return value is a pointer to an opaque structure that contains
78.1860 +** information needed to terminate the loop. Later, the calling routine
78.1861 +** should invoke sqlite3WhereEnd() with the return value of this function
78.1862 +** in order to complete the WHERE clause processing.
78.1863 +**
78.1864 +** If an error occurs, this routine returns NULL.
78.1865 +**
78.1866 +** The basic idea is to do a nested loop, one loop for each table in
78.1867 +** the FROM clause of a select. (INSERT and UPDATE statements are the
78.1868 +** same as a SELECT with only a single table in the FROM clause.) For
78.1869 +** example, if the SQL is this:
78.1870 +**
78.1871 +** SELECT * FROM t1, t2, t3 WHERE ...;
78.1872 +**
78.1873 +** Then the code generated is conceptually like the following:
78.1874 +**
78.1875 +** foreach row1 in t1 do \ Code generated
78.1876 +** foreach row2 in t2 do |-- by sqlite3WhereBegin()
78.1877 +** foreach row3 in t3 do /
78.1878 +** ...
78.1879 +** end \ Code generated
78.1880 +** end |-- by sqlite3WhereEnd()
78.1881 +** end /
78.1882 +**
78.1883 +** Note that the loops might not be nested in the order in which they
78.1884 +** appear in the FROM clause if a different order is better able to make
78.1885 +** use of indices. Note also that when the IN operator appears in
78.1886 +** the WHERE clause, it might result in additional nested loops for
78.1887 +** scanning through all values on the right-hand side of the IN.
78.1888 +**
78.1889 +** There are Btree cursors associated with each table. t1 uses cursor
78.1890 +** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
78.1891 +** And so forth. This routine generates code to open those VDBE cursors
78.1892 +** and sqlite3WhereEnd() generates the code to close them.
78.1893 +**
78.1894 +** The code that sqlite3WhereBegin() generates leaves the cursors named
78.1895 +** in pTabList pointing at their appropriate entries. The [...] code
78.1896 +** can use OP_Column and OP_Rowid opcodes on these cursors to extract
78.1897 +** data from the various tables of the loop.
78.1898 +**
78.1899 +** If the WHERE clause is empty, the foreach loops must each scan their
78.1900 +** entire tables. Thus a three-way join is an O(N^3) operation. But if
78.1901 +** the tables have indices and there are terms in the WHERE clause that
78.1902 +** refer to those indices, a complete table scan can be avoided and the
78.1903 +** code will run much faster. Most of the work of this routine is checking
78.1904 +** to see if there are indices that can be used to speed up the loop.
78.1905 +**
78.1906 +** Terms of the WHERE clause are also used to limit which rows actually
78.1907 +** make it to the "..." in the middle of the loop. After each "foreach",
78.1908 +** terms of the WHERE clause that use only terms in that loop and outer
78.1909 +** loops are evaluated and if false a jump is made around all subsequent
78.1910 +** inner loops (or around the "..." if the test occurs within the inner-
78.1911 +** most loop)
78.1912 +**
78.1913 +** OUTER JOINS
78.1914 +**
78.1915 +** An outer join of tables t1 and t2 is conceptally coded as follows:
78.1916 +**
78.1917 +** foreach row1 in t1 do
78.1918 +** flag = 0
78.1919 +** foreach row2 in t2 do
78.1920 +** start:
78.1921 +** ...
78.1922 +** flag = 1
78.1923 +** end
78.1924 +** if flag==0 then
78.1925 +** move the row2 cursor to a null row
78.1926 +** goto start
78.1927 +** fi
78.1928 +** end
78.1929 +**
78.1930 +** ORDER BY CLAUSE PROCESSING
78.1931 +**
78.1932 +** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
78.1933 +** if there is one. If there is no ORDER BY clause or if this routine
78.1934 +** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
78.1935 +**
78.1936 +** If an index can be used so that the natural output order of the table
78.1937 +** scan is correct for the ORDER BY clause, then that index is used and
78.1938 +** *ppOrderBy is set to NULL. This is an optimization that prevents an
78.1939 +** unnecessary sort of the result set if an index appropriate for the
78.1940 +** ORDER BY clause already exists.
78.1941 +**
78.1942 +** If the where clause loops cannot be arranged to provide the correct
78.1943 +** output order, then the *ppOrderBy is unchanged.
78.1944 +*/
78.1945 +WhereInfo *sqlite3WhereBegin(
78.1946 + Parse *pParse, /* The parser context */
78.1947 + SrcList *pTabList, /* A list of all tables to be scanned */
78.1948 + Expr *pWhere, /* The WHERE clause */
78.1949 + ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
78.1950 +){
78.1951 + int i; /* Loop counter */
78.1952 + WhereInfo *pWInfo; /* Will become the return value of this function */
78.1953 + Vdbe *v = pParse->pVdbe; /* The virtual database engine */
78.1954 + int brk, cont = 0; /* Addresses used during code generation */
78.1955 + Bitmask notReady; /* Cursors that are not yet positioned */
78.1956 + WhereTerm *pTerm; /* A single term in the WHERE clause */
78.1957 + ExprMaskSet maskSet; /* The expression mask set */
78.1958 + WhereClause wc; /* The WHERE clause is divided into these terms */
78.1959 + struct SrcList_item *pTabItem; /* A single entry from pTabList */
78.1960 + WhereLevel *pLevel; /* A single level in the pWInfo list */
78.1961 + int iFrom; /* First unused FROM clause element */
78.1962 + int andFlags; /* AND-ed combination of all wc.a[].flags */
78.1963 +
78.1964 + /* The number of tables in the FROM clause is limited by the number of
78.1965 + ** bits in a Bitmask
78.1966 + */
78.1967 + if( pTabList->nSrc>BMS ){
78.1968 + sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
78.1969 + return 0;
78.1970 + }
78.1971 +
78.1972 + /* Split the WHERE clause into separate subexpressions where each
78.1973 + ** subexpression is separated by an AND operator.
78.1974 + */
78.1975 + initMaskSet(&maskSet);
78.1976 + whereClauseInit(&wc, pParse, &maskSet);
78.1977 + whereSplit(&wc, pWhere, TK_AND);
78.1978 +
78.1979 + /* Allocate and initialize the WhereInfo structure that will become the
78.1980 + ** return value.
78.1981 + */
78.1982 + pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
78.1983 + if( sqlite3MallocFailed() ){
78.1984 + goto whereBeginNoMem;
78.1985 + }
78.1986 + pWInfo->nLevel = pTabList->nSrc;
78.1987 + pWInfo->pParse = pParse;
78.1988 + pWInfo->pTabList = pTabList;
78.1989 + pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
78.1990 +
78.1991 + /* Special case: a WHERE clause that is constant. Evaluate the
78.1992 + ** expression and either jump over all of the code or fall thru.
78.1993 + */
78.1994 + if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
78.1995 + sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
78.1996 + pWhere = 0;
78.1997 + }
78.1998 +
78.1999 + /* Analyze all of the subexpressions. Note that exprAnalyze() might
78.2000 + ** add new virtual terms onto the end of the WHERE clause. We do not
78.2001 + ** want to analyze these virtual terms, so start analyzing at the end
78.2002 + ** and work forward so that the added virtual terms are never processed.
78.2003 + */
78.2004 + for(i=0; i<pTabList->nSrc; i++){
78.2005 + createMask(&maskSet, pTabList->a[i].iCursor);
78.2006 + }
78.2007 + exprAnalyzeAll(pTabList, &wc);
78.2008 + if( sqlite3MallocFailed() ){
78.2009 + goto whereBeginNoMem;
78.2010 + }
78.2011 +
78.2012 + /* Chose the best index to use for each table in the FROM clause.
78.2013 + **
78.2014 + ** This loop fills in the following fields:
78.2015 + **
78.2016 + ** pWInfo->a[].pIdx The index to use for this level of the loop.
78.2017 + ** pWInfo->a[].flags WHERE_xxx flags associated with pIdx
78.2018 + ** pWInfo->a[].nEq The number of == and IN constraints
78.2019 + ** pWInfo->a[].iFrom When term of the FROM clause is being coded
78.2020 + ** pWInfo->a[].iTabCur The VDBE cursor for the database table
78.2021 + ** pWInfo->a[].iIdxCur The VDBE cursor for the index
78.2022 + **
78.2023 + ** This loop also figures out the nesting order of tables in the FROM
78.2024 + ** clause.
78.2025 + */
78.2026 + notReady = ~(Bitmask)0;
78.2027 + pTabItem = pTabList->a;
78.2028 + pLevel = pWInfo->a;
78.2029 + andFlags = ~0;
78.2030 + WHERETRACE(("*** Optimizer Start ***\n"));
78.2031 + for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
78.2032 + Index *pIdx; /* Index for FROM table at pTabItem */
78.2033 + int flags; /* Flags asssociated with pIdx */
78.2034 + int nEq; /* Number of == or IN constraints */
78.2035 + double cost; /* The cost for pIdx */
78.2036 + int j; /* For looping over FROM tables */
78.2037 + Index *pBest = 0; /* The best index seen so far */
78.2038 + int bestFlags = 0; /* Flags associated with pBest */
78.2039 + int bestNEq = 0; /* nEq associated with pBest */
78.2040 + double lowestCost; /* Cost of the pBest */
78.2041 + int bestJ = 0; /* The value of j */
78.2042 + Bitmask m; /* Bitmask value for j or bestJ */
78.2043 + int once = 0; /* True when first table is seen */
78.2044 + sqlite3_index_info *pIndex; /* Current virtual index */
78.2045 +
78.2046 + lowestCost = SQLITE_BIG_DBL;
78.2047 + for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
78.2048 + int doNotReorder; /* True if this table should not be reordered */
78.2049 +
78.2050 + doNotReorder = (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
78.2051 + if( once && doNotReorder ) break;
78.2052 + m = getMask(&maskSet, pTabItem->iCursor);
78.2053 + if( (m & notReady)==0 ){
78.2054 + if( j==iFrom ) iFrom++;
78.2055 + continue;
78.2056 + }
78.2057 + assert( pTabItem->pTab );
78.2058 +#ifndef SQLITE_OMIT_VIRTUALTABLE
78.2059 + if( IsVirtual(pTabItem->pTab) ){
78.2060 + sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
78.2061 + cost = bestVirtualIndex(pParse, &wc, pTabItem, notReady,
78.2062 + ppOrderBy ? *ppOrderBy : 0, i==0,
78.2063 + ppIdxInfo);
78.2064 + flags = WHERE_VIRTUALTABLE;
78.2065 + pIndex = *ppIdxInfo;
78.2066 + if( pIndex && pIndex->orderByConsumed ){
78.2067 + flags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
78.2068 + }
78.2069 + pIdx = 0;
78.2070 + nEq = 0;
78.2071 + if( (SQLITE_BIG_DBL/2.0)<cost ){
78.2072 + /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
78.2073 + ** inital value of lowestCost in this loop. If it is, then
78.2074 + ** the (cost<lowestCost) test below will never be true and
78.2075 + ** pLevel->pBestIdx never set.
78.2076 + */
78.2077 + cost = (SQLITE_BIG_DBL/2.0);
78.2078 + }
78.2079 + }else
78.2080 +#endif
78.2081 + {
78.2082 + cost = bestIndex(pParse, &wc, pTabItem, notReady,
78.2083 + (i==0 && ppOrderBy) ? *ppOrderBy : 0,
78.2084 + &pIdx, &flags, &nEq);
78.2085 + pIndex = 0;
78.2086 + }
78.2087 + if( cost<lowestCost ){
78.2088 + once = 1;
78.2089 + lowestCost = cost;
78.2090 + pBest = pIdx;
78.2091 + bestFlags = flags;
78.2092 + bestNEq = nEq;
78.2093 + bestJ = j;
78.2094 + pLevel->pBestIdx = pIndex;
78.2095 + }
78.2096 + if( doNotReorder ) break;
78.2097 + }
78.2098 + WHERETRACE(("*** Optimizer choose table %d for loop %d\n", bestJ,
78.2099 + pLevel-pWInfo->a));
78.2100 + if( (bestFlags & WHERE_ORDERBY)!=0 ){
78.2101 + *ppOrderBy = 0;
78.2102 + }
78.2103 + andFlags &= bestFlags;
78.2104 + pLevel->flags = bestFlags;
78.2105 + pLevel->pIdx = pBest;
78.2106 + pLevel->nEq = bestNEq;
78.2107 + pLevel->aInLoop = 0;
78.2108 + pLevel->nIn = 0;
78.2109 + if( pBest ){
78.2110 + pLevel->iIdxCur = pParse->nTab++;
78.2111 + }else{
78.2112 + pLevel->iIdxCur = -1;
78.2113 + }
78.2114 + notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
78.2115 + pLevel->iFrom = bestJ;
78.2116 + }
78.2117 + WHERETRACE(("*** Optimizer Finished ***\n"));
78.2118 +
78.2119 + /* If the total query only selects a single row, then the ORDER BY
78.2120 + ** clause is irrelevant.
78.2121 + */
78.2122 + if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
78.2123 + *ppOrderBy = 0;
78.2124 + }
78.2125 +
78.2126 + /* Open all tables in the pTabList and any indices selected for
78.2127 + ** searching those tables.
78.2128 + */
78.2129 + sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
78.2130 + for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
78.2131 + Table *pTab; /* Table to open */
78.2132 + Index *pIx; /* Index used to access pTab (if any) */
78.2133 + int iDb; /* Index of database containing table/index */
78.2134 + int iIdxCur = pLevel->iIdxCur;
78.2135 +
78.2136 +#ifndef SQLITE_OMIT_EXPLAIN
78.2137 + if( pParse->explain==2 ){
78.2138 + char *zMsg;
78.2139 + struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
78.2140 + zMsg = sqlite3MPrintf("TABLE %s", pItem->zName);
78.2141 + if( pItem->zAlias ){
78.2142 + zMsg = sqlite3MPrintf("%z AS %s", zMsg, pItem->zAlias);
78.2143 + }
78.2144 + if( (pIx = pLevel->pIdx)!=0 ){
78.2145 + zMsg = sqlite3MPrintf("%z WITH INDEX %s", zMsg, pIx->zName);
78.2146 + }else if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
78.2147 + zMsg = sqlite3MPrintf("%z USING PRIMARY KEY", zMsg);
78.2148 + }
78.2149 +#ifndef SQLITE_OMIT_VIRTUALTABLE
78.2150 + else if( pLevel->pBestIdx ){
78.2151 + sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
78.2152 + zMsg = sqlite3MPrintf("%z VIRTUAL TABLE INDEX %d:%s", zMsg,
78.2153 + pBestIdx->idxNum, pBestIdx->idxStr);
78.2154 + }
78.2155 +#endif
78.2156 + if( pLevel->flags & WHERE_ORDERBY ){
78.2157 + zMsg = sqlite3MPrintf("%z ORDER BY", zMsg);
78.2158 + }
78.2159 + sqlite3VdbeOp3(v, OP_Explain, i, pLevel->iFrom, zMsg, P3_DYNAMIC);
78.2160 + }
78.2161 +#endif /* SQLITE_OMIT_EXPLAIN */
78.2162 + pTabItem = &pTabList->a[pLevel->iFrom];
78.2163 + pTab = pTabItem->pTab;
78.2164 + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78.2165 + if( pTab->isEphem || pTab->pSelect ) continue;
78.2166 +#ifndef SQLITE_OMIT_VIRTUALTABLE
78.2167 + if( pLevel->pBestIdx ){
78.2168 + int iCur = pTabItem->iCursor;
78.2169 + sqlite3VdbeOp3(v, OP_VOpen, iCur, 0, (const char*)pTab->pVtab, P3_VTAB);
78.2170 + }else
78.2171 +#endif
78.2172 + if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
78.2173 + sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, OP_OpenRead);
78.2174 + if( pTab->nCol<(sizeof(Bitmask)*8) ){
78.2175 + Bitmask b = pTabItem->colUsed;
78.2176 + int n = 0;
78.2177 + for(; b; b=b>>1, n++){}
78.2178 + sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-1, n);
78.2179 + assert( n<=pTab->nCol );
78.2180 + }
78.2181 + }else{
78.2182 + sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
78.2183 + }
78.2184 + pLevel->iTabCur = pTabItem->iCursor;
78.2185 + if( (pIx = pLevel->pIdx)!=0 ){
78.2186 + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
78.2187 + assert( pIx->pSchema==pTab->pSchema );
78.2188 + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
78.2189 + VdbeComment((v, "# %s", pIx->zName));
78.2190 + sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
78.2191 + (char*)pKey, P3_KEYINFO_HANDOFF);
78.2192 + }
78.2193 + if( (pLevel->flags & (WHERE_IDX_ONLY|WHERE_COLUMN_RANGE))!=0 ){
78.2194 + /* Only call OP_SetNumColumns on the index if we might later use
78.2195 + ** OP_Column on the index. */
78.2196 + sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
78.2197 + }
78.2198 + sqlite3CodeVerifySchema(pParse, iDb);
78.2199 + }
78.2200 + pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
78.2201 +
78.2202 + /* Generate the code to do the search. Each iteration of the for
78.2203 + ** loop below generates code for a single nested loop of the VM
78.2204 + ** program.
78.2205 + */
78.2206 + notReady = ~(Bitmask)0;
78.2207 + for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
78.2208 + int j;
78.2209 + int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */
78.2210 + Index *pIdx; /* The index we will be using */
78.2211 + int nxt; /* Where to jump to continue with the next IN case */
78.2212 + int iIdxCur; /* The VDBE cursor for the index */
78.2213 + int omitTable; /* True if we use the index only */
78.2214 + int bRev; /* True if we need to scan in reverse order */
78.2215 +
78.2216 + pTabItem = &pTabList->a[pLevel->iFrom];
78.2217 + iCur = pTabItem->iCursor;
78.2218 + pIdx = pLevel->pIdx;
78.2219 + iIdxCur = pLevel->iIdxCur;
78.2220 + bRev = (pLevel->flags & WHERE_REVERSE)!=0;
78.2221 + omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
78.2222 +
78.2223 + /* Create labels for the "break" and "continue" instructions
78.2224 + ** for the current loop. Jump to brk to break out of a loop.
78.2225 + ** Jump to cont to go immediately to the next iteration of the
78.2226 + ** loop.
78.2227 + **
78.2228 + ** When there is an IN operator, we also have a "nxt" label that
78.2229 + ** means to continue with the next IN value combination. When
78.2230 + ** there are no IN operators in the constraints, the "nxt" label
78.2231 + ** is the same as "brk".
78.2232 + */
78.2233 + brk = pLevel->brk = pLevel->nxt = sqlite3VdbeMakeLabel(v);
78.2234 + cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
78.2235 +
78.2236 + /* If this is the right table of a LEFT OUTER JOIN, allocate and
78.2237 + ** initialize a memory cell that records if this table matches any
78.2238 + ** row of the left table of the join.
78.2239 + */
78.2240 + if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
78.2241 + if( !pParse->nMem ) pParse->nMem++;
78.2242 + pLevel->iLeftJoin = pParse->nMem++;
78.2243 + sqlite3VdbeAddOp(v, OP_MemInt, 0, pLevel->iLeftJoin);
78.2244 + VdbeComment((v, "# init LEFT JOIN no-match flag"));
78.2245 + }
78.2246 +
78.2247 +#ifndef SQLITE_OMIT_VIRTUALTABLE
78.2248 + if( pLevel->pBestIdx ){
78.2249 + /* Case 0: The table is a virtual-table. Use the VFilter and VNext
78.2250 + ** to access the data.
78.2251 + */
78.2252 + int j;
78.2253 + sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
78.2254 + int nConstraint = pBestIdx->nConstraint;
78.2255 + struct sqlite3_index_constraint_usage *aUsage =
78.2256 + pBestIdx->aConstraintUsage;
78.2257 + const struct sqlite3_index_constraint *aConstraint =
78.2258 + pBestIdx->aConstraint;
78.2259 +
78.2260 + for(j=1; j<=nConstraint; j++){
78.2261 + int k;
78.2262 + for(k=0; k<nConstraint; k++){
78.2263 + if( aUsage[k].argvIndex==j ){
78.2264 + int iTerm = aConstraint[k].iTermOffset;
78.2265 + sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight);
78.2266 + break;
78.2267 + }
78.2268 + }
78.2269 + if( k==nConstraint ) break;
78.2270 + }
78.2271 + sqlite3VdbeAddOp(v, OP_Integer, j-1, 0);
78.2272 + sqlite3VdbeAddOp(v, OP_Integer, pBestIdx->idxNum, 0);
78.2273 + sqlite3VdbeOp3(v, OP_VFilter, iCur, brk, pBestIdx->idxStr,
78.2274 + pBestIdx->needToFreeIdxStr ? P3_MPRINTF : P3_STATIC);
78.2275 + pBestIdx->needToFreeIdxStr = 0;
78.2276 + for(j=0; j<pBestIdx->nConstraint; j++){
78.2277 + if( aUsage[j].omit ){
78.2278 + int iTerm = aConstraint[j].iTermOffset;
78.2279 + disableTerm(pLevel, &wc.a[iTerm]);
78.2280 + }
78.2281 + }
78.2282 + pLevel->op = OP_VNext;
78.2283 + pLevel->p1 = iCur;
78.2284 + pLevel->p2 = sqlite3VdbeCurrentAddr(v);
78.2285 + }else
78.2286 +#endif /* SQLITE_OMIT_VIRTUALTABLE */
78.2287 +
78.2288 + if( pLevel->flags & WHERE_ROWID_EQ ){
78.2289 + /* Case 1: We can directly reference a single row using an
78.2290 + ** equality comparison against the ROWID field. Or
78.2291 + ** we reference multiple rows using a "rowid IN (...)"
78.2292 + ** construct.
78.2293 + */
78.2294 + pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
78.2295 + assert( pTerm!=0 );
78.2296 + assert( pTerm->pExpr!=0 );
78.2297 + assert( pTerm->leftCursor==iCur );
78.2298 + assert( omitTable==0 );
78.2299 + codeEqualityTerm(pParse, pTerm, pLevel);
78.2300 + nxt = pLevel->nxt;
78.2301 + sqlite3VdbeAddOp(v, OP_MustBeInt, 1, nxt);
78.2302 + sqlite3VdbeAddOp(v, OP_NotExists, iCur, nxt);
78.2303 + VdbeComment((v, "pk"));
78.2304 + pLevel->op = OP_Noop;
78.2305 + }else if( pLevel->flags & WHERE_ROWID_RANGE ){
78.2306 + /* Case 2: We have an inequality comparison against the ROWID field.
78.2307 + */
78.2308 + int testOp = OP_Noop;
78.2309 + int start;
78.2310 + WhereTerm *pStart, *pEnd;
78.2311 +
78.2312 + assert( omitTable==0 );
78.2313 + pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
78.2314 + pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
78.2315 + if( bRev ){
78.2316 + pTerm = pStart;
78.2317 + pStart = pEnd;
78.2318 + pEnd = pTerm;
78.2319 + }
78.2320 + if( pStart ){
78.2321 + Expr *pX;
78.2322 + pX = pStart->pExpr;
78.2323 + assert( pX!=0 );
78.2324 + assert( pStart->leftCursor==iCur );
78.2325 + sqlite3ExprCode(pParse, pX->pRight);
78.2326 + sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
78.2327 + sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
78.2328 + VdbeComment((v, "pk"));
78.2329 + disableTerm(pLevel, pStart);
78.2330 + }else{
78.2331 + sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
78.2332 + }
78.2333 + if( pEnd ){
78.2334 + Expr *pX;
78.2335 + pX = pEnd->pExpr;
78.2336 + assert( pX!=0 );
78.2337 + assert( pEnd->leftCursor==iCur );
78.2338 + sqlite3ExprCode(pParse, pX->pRight);
78.2339 + pLevel->iMem = pParse->nMem++;
78.2340 + sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
78.2341 + if( pX->op==TK_LT || pX->op==TK_GT ){
78.2342 + testOp = bRev ? OP_Le : OP_Ge;
78.2343 + }else{
78.2344 + testOp = bRev ? OP_Lt : OP_Gt;
78.2345 + }
78.2346 + disableTerm(pLevel, pEnd);
78.2347 + }
78.2348 + start = sqlite3VdbeCurrentAddr(v);
78.2349 + pLevel->op = bRev ? OP_Prev : OP_Next;
78.2350 + pLevel->p1 = iCur;
78.2351 + pLevel->p2 = start;
78.2352 + if( testOp!=OP_Noop ){
78.2353 + sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
78.2354 + sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
78.2355 + sqlite3VdbeAddOp(v, testOp, SQLITE_AFF_NUMERIC|0x100, brk);
78.2356 + }
78.2357 + }else if( pLevel->flags & WHERE_COLUMN_RANGE ){
78.2358 + /* Case 3: The WHERE clause term that refers to the right-most
78.2359 + ** column of the index is an inequality. For example, if
78.2360 + ** the index is on (x,y,z) and the WHERE clause is of the
78.2361 + ** form "x=5 AND y<10" then this case is used. Only the
78.2362 + ** right-most column can be an inequality - the rest must
78.2363 + ** use the "==" and "IN" operators.
78.2364 + **
78.2365 + ** This case is also used when there are no WHERE clause
78.2366 + ** constraints but an index is selected anyway, in order
78.2367 + ** to force the output order to conform to an ORDER BY.
78.2368 + */
78.2369 + int start;
78.2370 + int nEq = pLevel->nEq;
78.2371 + int topEq=0; /* True if top limit uses ==. False is strictly < */
78.2372 + int btmEq=0; /* True if btm limit uses ==. False if strictly > */
78.2373 + int topOp, btmOp; /* Operators for the top and bottom search bounds */
78.2374 + int testOp;
78.2375 + int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0;
78.2376 + int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0;
78.2377 +
78.2378 + /* Generate code to evaluate all constraint terms using == or IN
78.2379 + ** and level the values of those terms on the stack.
78.2380 + */
78.2381 + codeAllEqualityTerms(pParse, pLevel, &wc, notReady);
78.2382 +
78.2383 + /* Duplicate the equality term values because they will all be
78.2384 + ** used twice: once to make the termination key and once to make the
78.2385 + ** start key.
78.2386 + */
78.2387 + for(j=0; j<nEq; j++){
78.2388 + sqlite3VdbeAddOp(v, OP_Dup, nEq-1, 0);
78.2389 + }
78.2390 +
78.2391 + /* Figure out what comparison operators to use for top and bottom
78.2392 + ** search bounds. For an ascending index, the bottom bound is a > or >=
78.2393 + ** operator and the top bound is a < or <= operator. For a descending
78.2394 + ** index the operators are reversed.
78.2395 + */
78.2396 + if( pIdx->aSortOrder[nEq]==SQLITE_SO_ASC ){
78.2397 + topOp = WO_LT|WO_LE;
78.2398 + btmOp = WO_GT|WO_GE;
78.2399 + }else{
78.2400 + topOp = WO_GT|WO_GE;
78.2401 + btmOp = WO_LT|WO_LE;
78.2402 + SWAP(int, topLimit, btmLimit);
78.2403 + }
78.2404 +
78.2405 + /* Generate the termination key. This is the key value that
78.2406 + ** will end the search. There is no termination key if there
78.2407 + ** are no equality terms and no "X<..." term.
78.2408 + **
78.2409 + ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
78.2410 + ** key computed here really ends up being the start key.
78.2411 + */
78.2412 + nxt = pLevel->nxt;
78.2413 + if( topLimit ){
78.2414 + Expr *pX;
78.2415 + int k = pIdx->aiColumn[j];
78.2416 + pTerm = findTerm(&wc, iCur, k, notReady, topOp, pIdx);
78.2417 + assert( pTerm!=0 );
78.2418 + pX = pTerm->pExpr;
78.2419 + assert( (pTerm->flags & TERM_CODED)==0 );
78.2420 + sqlite3ExprCode(pParse, pX->pRight);
78.2421 + sqlite3VdbeAddOp(v, OP_IsNull, -(nEq*2+1), nxt);
78.2422 + topEq = pTerm->eOperator & (WO_LE|WO_GE);
78.2423 + disableTerm(pLevel, pTerm);
78.2424 + testOp = OP_IdxGE;
78.2425 + }else{
78.2426 + testOp = nEq>0 ? OP_IdxGE : OP_Noop;
78.2427 + topEq = 1;
78.2428 + }
78.2429 + if( testOp!=OP_Noop ){
78.2430 + int nCol = nEq + topLimit;
78.2431 + pLevel->iMem = pParse->nMem++;
78.2432 + buildIndexProbe(v, nCol, pIdx);
78.2433 + if( bRev ){
78.2434 + int op = topEq ? OP_MoveLe : OP_MoveLt;
78.2435 + sqlite3VdbeAddOp(v, op, iIdxCur, nxt);
78.2436 + }else{
78.2437 + sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
78.2438 + }
78.2439 + }else if( bRev ){
78.2440 + sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
78.2441 + }
78.2442 +
78.2443 + /* Generate the start key. This is the key that defines the lower
78.2444 + ** bound on the search. There is no start key if there are no
78.2445 + ** equality terms and if there is no "X>..." term. In
78.2446 + ** that case, generate a "Rewind" instruction in place of the
78.2447 + ** start key search.
78.2448 + **
78.2449 + ** 2002-Dec-04: In the case of a reverse-order search, the so-called
78.2450 + ** "start" key really ends up being used as the termination key.
78.2451 + */
78.2452 + if( btmLimit ){
78.2453 + Expr *pX;
78.2454 + int k = pIdx->aiColumn[j];
78.2455 + pTerm = findTerm(&wc, iCur, k, notReady, btmOp, pIdx);
78.2456 + assert( pTerm!=0 );
78.2457 + pX = pTerm->pExpr;
78.2458 + assert( (pTerm->flags & TERM_CODED)==0 );
78.2459 + sqlite3ExprCode(pParse, pX->pRight);
78.2460 + sqlite3VdbeAddOp(v, OP_IsNull, -(nEq+1), nxt);
78.2461 + btmEq = pTerm->eOperator & (WO_LE|WO_GE);
78.2462 + disableTerm(pLevel, pTerm);
78.2463 + }else{
78.2464 + btmEq = 1;
78.2465 + }
78.2466 + if( nEq>0 || btmLimit ){
78.2467 + int nCol = nEq + btmLimit;
78.2468 + buildIndexProbe(v, nCol, pIdx);
78.2469 + if( bRev ){
78.2470 + pLevel->iMem = pParse->nMem++;
78.2471 + sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
78.2472 + testOp = OP_IdxLT;
78.2473 + }else{
78.2474 + int op = btmEq ? OP_MoveGe : OP_MoveGt;
78.2475 + sqlite3VdbeAddOp(v, op, iIdxCur, nxt);
78.2476 + }
78.2477 + }else if( bRev ){
78.2478 + testOp = OP_Noop;
78.2479 + }else{
78.2480 + sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
78.2481 + }
78.2482 +
78.2483 + /* Generate the the top of the loop. If there is a termination
78.2484 + ** key we have to test for that key and abort at the top of the
78.2485 + ** loop.
78.2486 + */
78.2487 + start = sqlite3VdbeCurrentAddr(v);
78.2488 + if( testOp!=OP_Noop ){
78.2489 + sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
78.2490 + sqlite3VdbeAddOp(v, testOp, iIdxCur, nxt);
78.2491 + if( (topEq && !bRev) || (!btmEq && bRev) ){
78.2492 + sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
78.2493 + }
78.2494 + }
78.2495 + if( topLimit | btmLimit ){
78.2496 + sqlite3VdbeAddOp(v, OP_Column, iIdxCur, nEq);
78.2497 + sqlite3VdbeAddOp(v, OP_IsNull, 1, cont);
78.2498 + }
78.2499 + if( !omitTable ){
78.2500 + sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
78.2501 + sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
78.2502 + }
78.2503 +
78.2504 + /* Record the instruction used to terminate the loop.
78.2505 + */
78.2506 + pLevel->op = bRev ? OP_Prev : OP_Next;
78.2507 + pLevel->p1 = iIdxCur;
78.2508 + pLevel->p2 = start;
78.2509 + }else if( pLevel->flags & WHERE_COLUMN_EQ ){
78.2510 + /* Case 4: There is an index and all terms of the WHERE clause that
78.2511 + ** refer to the index using the "==" or "IN" operators.
78.2512 + */
78.2513 + int start;
78.2514 + int nEq = pLevel->nEq;
78.2515 +
78.2516 + /* Generate code to evaluate all constraint terms using == or IN
78.2517 + ** and leave the values of those terms on the stack.
78.2518 + */
78.2519 + codeAllEqualityTerms(pParse, pLevel, &wc, notReady);
78.2520 + nxt = pLevel->nxt;
78.2521 +
78.2522 + /* Generate a single key that will be used to both start and terminate
78.2523 + ** the search
78.2524 + */
78.2525 + buildIndexProbe(v, nEq, pIdx);
78.2526 + sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
78.2527 +
78.2528 + /* Generate code (1) to move to the first matching element of the table.
78.2529 + ** Then generate code (2) that jumps to "nxt" after the cursor is past
78.2530 + ** the last matching element of the table. The code (1) is executed
78.2531 + ** once to initialize the search, the code (2) is executed before each
78.2532 + ** iteration of the scan to see if the scan has finished. */
78.2533 + if( bRev ){
78.2534 + /* Scan in reverse order */
78.2535 + sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, nxt);
78.2536 + start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
78.2537 + sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, nxt);
78.2538 + pLevel->op = OP_Prev;
78.2539 + }else{
78.2540 + /* Scan in the forward order */
78.2541 + sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, nxt);
78.2542 + start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
78.2543 + sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, nxt, "+", P3_STATIC);
78.2544 + pLevel->op = OP_Next;
78.2545 + }
78.2546 + if( !omitTable ){
78.2547 + sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
78.2548 + sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
78.2549 + }
78.2550 + pLevel->p1 = iIdxCur;
78.2551 + pLevel->p2 = start;
78.2552 + }else{
78.2553 + /* Case 5: There is no usable index. We must do a complete
78.2554 + ** scan of the entire table.
78.2555 + */
78.2556 + assert( omitTable==0 );
78.2557 + assert( bRev==0 );
78.2558 + pLevel->op = OP_Next;
78.2559 + pLevel->p1 = iCur;
78.2560 + pLevel->p2 = 1 + sqlite3VdbeAddOp(v, OP_Rewind, iCur, brk);
78.2561 + }
78.2562 + notReady &= ~getMask(&maskSet, iCur);
78.2563 +
78.2564 + /* Insert code to test every subexpression that can be completely
78.2565 + ** computed using the current set of tables.
78.2566 + */
78.2567 + for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
78.2568 + Expr *pE;
78.2569 + if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
78.2570 + if( (pTerm->prereqAll & notReady)!=0 ) continue;
78.2571 + pE = pTerm->pExpr;
78.2572 + assert( pE!=0 );
78.2573 + if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
78.2574 + continue;
78.2575 + }
78.2576 + sqlite3ExprIfFalse(pParse, pE, cont, 1);
78.2577 + pTerm->flags |= TERM_CODED;
78.2578 + }
78.2579 +
78.2580 + /* For a LEFT OUTER JOIN, generate code that will record the fact that
78.2581 + ** at least one row of the right table has matched the left table.
78.2582 + */
78.2583 + if( pLevel->iLeftJoin ){
78.2584 + pLevel->top = sqlite3VdbeCurrentAddr(v);
78.2585 + sqlite3VdbeAddOp(v, OP_MemInt, 1, pLevel->iLeftJoin);
78.2586 + VdbeComment((v, "# record LEFT JOIN hit"));
78.2587 + for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
78.2588 + if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
78.2589 + if( (pTerm->prereqAll & notReady)!=0 ) continue;
78.2590 + assert( pTerm->pExpr );
78.2591 + sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1);
78.2592 + pTerm->flags |= TERM_CODED;
78.2593 + }
78.2594 + }
78.2595 + }
78.2596 +
78.2597 +#ifdef SQLITE_TEST /* For testing and debugging use only */
78.2598 + /* Record in the query plan information about the current table
78.2599 + ** and the index used to access it (if any). If the table itself
78.2600 + ** is not used, its name is just '{}'. If no index is used
78.2601 + ** the index is listed as "{}". If the primary key is used the
78.2602 + ** index name is '*'.
78.2603 + */
78.2604 + for(i=0; i<pTabList->nSrc; i++){
78.2605 + char *z;
78.2606 + int n;
78.2607 + pLevel = &pWInfo->a[i];
78.2608 + pTabItem = &pTabList->a[pLevel->iFrom];
78.2609 + z = pTabItem->zAlias;
78.2610 + if( z==0 ) z = pTabItem->pTab->zName;
78.2611 + n = strlen(z);
78.2612 + if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
78.2613 + if( pLevel->flags & WHERE_IDX_ONLY ){
78.2614 + memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
78.2615 + nQPlan += 2;
78.2616 + }else{
78.2617 + memcpy(&sqlite3_query_plan[nQPlan], z, n);
78.2618 + nQPlan += n;
78.2619 + }
78.2620 + sqlite3_query_plan[nQPlan++] = ' ';
78.2621 + }
78.2622 + if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
78.2623 + memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
78.2624 + nQPlan += 2;
78.2625 + }else if( pLevel->pIdx==0 ){
78.2626 + memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
78.2627 + nQPlan += 3;
78.2628 + }else{
78.2629 + n = strlen(pLevel->pIdx->zName);
78.2630 + if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
78.2631 + memcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName, n);
78.2632 + nQPlan += n;
78.2633 + sqlite3_query_plan[nQPlan++] = ' ';
78.2634 + }
78.2635 + }
78.2636 + }
78.2637 + while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
78.2638 + sqlite3_query_plan[--nQPlan] = 0;
78.2639 + }
78.2640 + sqlite3_query_plan[nQPlan] = 0;
78.2641 + nQPlan = 0;
78.2642 +#endif /* SQLITE_TEST // Testing and debugging use only */
78.2643 +
78.2644 + /* Record the continuation address in the WhereInfo structure. Then
78.2645 + ** clean up and return.
78.2646 + */
78.2647 + pWInfo->iContinue = cont;
78.2648 + whereClauseClear(&wc);
78.2649 + return pWInfo;
78.2650 +
78.2651 + /* Jump here if malloc fails */
78.2652 +whereBeginNoMem:
78.2653 + whereClauseClear(&wc);
78.2654 + whereInfoFree(pWInfo);
78.2655 + return 0;
78.2656 +}
78.2657 +
78.2658 +/*
78.2659 +** Generate the end of the WHERE loop. See comments on
78.2660 +** sqlite3WhereBegin() for additional information.
78.2661 +*/
78.2662 +void sqlite3WhereEnd(WhereInfo *pWInfo){
78.2663 + Vdbe *v = pWInfo->pParse->pVdbe;
78.2664 + int i;
78.2665 + WhereLevel *pLevel;
78.2666 + SrcList *pTabList = pWInfo->pTabList;
78.2667 +
78.2668 + /* Generate loop termination code.
78.2669 + */
78.2670 + for(i=pTabList->nSrc-1; i>=0; i--){
78.2671 + pLevel = &pWInfo->a[i];
78.2672 + sqlite3VdbeResolveLabel(v, pLevel->cont);
78.2673 + if( pLevel->op!=OP_Noop ){
78.2674 + sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
78.2675 + }
78.2676 + if( pLevel->nIn ){
78.2677 + struct InLoop *pIn;
78.2678 + int j;
78.2679 + sqlite3VdbeResolveLabel(v, pLevel->nxt);
78.2680 + for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){
78.2681 + sqlite3VdbeJumpHere(v, pIn->topAddr+1);
78.2682 + sqlite3VdbeAddOp(v, OP_Next, pIn->iCur, pIn->topAddr);
78.2683 + sqlite3VdbeJumpHere(v, pIn->topAddr-1);
78.2684 + }
78.2685 + sqliteFree(pLevel->aInLoop);
78.2686 + }
78.2687 + sqlite3VdbeResolveLabel(v, pLevel->brk);
78.2688 + if( pLevel->iLeftJoin ){
78.2689 + int addr;
78.2690 + addr = sqlite3VdbeAddOp(v, OP_IfMemPos, pLevel->iLeftJoin, 0);
78.2691 + sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
78.2692 + if( pLevel->iIdxCur>=0 ){
78.2693 + sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
78.2694 + }
78.2695 + sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
78.2696 + sqlite3VdbeJumpHere(v, addr);
78.2697 + }
78.2698 + }
78.2699 +
78.2700 + /* The "break" point is here, just past the end of the outer loop.
78.2701 + ** Set it.
78.2702 + */
78.2703 + sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
78.2704 +
78.2705 + /* Close all of the cursors that were opened by sqlite3WhereBegin.
78.2706 + */
78.2707 + for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
78.2708 + struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
78.2709 + Table *pTab = pTabItem->pTab;
78.2710 + assert( pTab!=0 );
78.2711 + if( pTab->isEphem || pTab->pSelect ) continue;
78.2712 + if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
78.2713 + sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
78.2714 + }
78.2715 + if( pLevel->pIdx!=0 ){
78.2716 + sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
78.2717 + }
78.2718 +
78.2719 + /* Make cursor substitutions for cases where we want to use
78.2720 + ** just the index and never reference the table.
78.2721 + **
78.2722 + ** Calls to the code generator in between sqlite3WhereBegin and
78.2723 + ** sqlite3WhereEnd will have created code that references the table
78.2724 + ** directly. This loop scans all that code looking for opcodes
78.2725 + ** that reference the table and converts them into opcodes that
78.2726 + ** reference the index.
78.2727 + */
78.2728 + if( pLevel->flags & WHERE_IDX_ONLY ){
78.2729 + int k, j, last;
78.2730 + VdbeOp *pOp;
78.2731 + Index *pIdx = pLevel->pIdx;
78.2732 +
78.2733 + assert( pIdx!=0 );
78.2734 + pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
78.2735 + last = sqlite3VdbeCurrentAddr(v);
78.2736 + for(k=pWInfo->iTop; k<last; k++, pOp++){
78.2737 + if( pOp->p1!=pLevel->iTabCur ) continue;
78.2738 + if( pOp->opcode==OP_Column ){
78.2739 + pOp->p1 = pLevel->iIdxCur;
78.2740 + for(j=0; j<pIdx->nColumn; j++){
78.2741 + if( pOp->p2==pIdx->aiColumn[j] ){
78.2742 + pOp->p2 = j;
78.2743 + break;
78.2744 + }
78.2745 + }
78.2746 + }else if( pOp->opcode==OP_Rowid ){
78.2747 + pOp->p1 = pLevel->iIdxCur;
78.2748 + pOp->opcode = OP_IdxRowid;
78.2749 + }else if( pOp->opcode==OP_NullRow ){
78.2750 + pOp->opcode = OP_Noop;
78.2751 + }
78.2752 + }
78.2753 + }
78.2754 + }
78.2755 +
78.2756 + /* Final cleanup
78.2757 + */
78.2758 + whereInfoFree(pWInfo);
78.2759 + return;
78.2760 +}
79.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
79.2 +++ b/extensions/sqlite/svn_version.h Sun Jul 29 01:15:31 2007 +0000
79.3 @@ -0,0 +1,12 @@
79.4 +/**
79.5 + * Autogenerated by build scripts
79.6 + */
79.7 +
79.8 +#ifndef _INCLUDE_BINTOOLS_VERSION_H_
79.9 +#define _INCLUDE_BINTOOLS_VERSION_H_
79.10 +
79.11 +
79.12 +#define SVN_FULL_VERSION "1.0.0.431"
79.13 +#define SVN_FILE_VERSION 1,0,0,431
79.14 +
79.15 +#endif //_INCLUDE_BINTOOLS_VERSION_H_
80.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
80.2 +++ b/extensions/sqlite/svn_version.tpl Sun Jul 29 01:15:31 2007 +0000
80.3 @@ -0,0 +1,12 @@
80.4 +/**
80.5 + * Autogenerated by build scripts
80.6 + */
80.7 +
80.8 +#ifndef _INCLUDE_BINTOOLS_VERSION_H_
80.9 +#define _INCLUDE_BINTOOLS_VERSION_H_
80.10 +
80.11 +
80.12 +#define SVN_FULL_VERSION "$PMAJOR$.$PMINOR$.$PREVISION$.$LOCAL_BUILD$"
80.13 +#define SVN_FILE_VERSION $PMAJOR$,$PMINOR$,$PREVISION$,$LOCAL_BUILD$
80.14 +
80.15 +#endif //_INCLUDE_BINTOOLS_VERSION_H_
81.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
81.2 +++ b/extensions/sqlite/version.rc Sun Jul 29 01:15:31 2007 +0000
81.3 @@ -0,0 +1,104 @@
81.4 +// Microsoft Visual C++ generated resource script.
81.5 +//
81.6 +//#include "resource.h"
81.7 +
81.8 +#define APSTUDIO_READONLY_SYMBOLS
81.9 +/////////////////////////////////////////////////////////////////////////////
81.10 +//
81.11 +// Generated from the TEXTINCLUDE 2 resource.
81.12 +//
81.13 +#include "winres.h"
81.14 +
81.15 +#include "svn_version.h"
81.16 +
81.17 +/////////////////////////////////////////////////////////////////////////////
81.18 +#undef APSTUDIO_READONLY_SYMBOLS
81.19 +
81.20 +/////////////////////////////////////////////////////////////////////////////
81.21 +// English (U.S.) resources
81.22 +
81.23 +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
81.24 +#ifdef _WIN32
81.25 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
81.26 +#pragma code_page(1252)
81.27 +#endif //_WIN32
81.28 +
81.29 +/////////////////////////////////////////////////////////////////////////////
81.30 +//
81.31 +// Version
81.32 +//
81.33 +
81.34 +VS_VERSION_INFO VERSIONINFO
81.35 + FILEVERSION SVN_FILE_VERSION
81.36 + PRODUCTVERSION SVN_FILE_VERSION
81.37 + FILEFLAGSMASK 0x17L
81.38 +#ifdef _DEBUG
81.39 + FILEFLAGS 0x1L
81.40 +#else
81.41 + FILEFLAGS 0x0L
81.42 +#endif
81.43 + FILEOS 0x4L
81.44 + FILETYPE 0x2L
81.45 + FILESUBTYPE 0x0L
81.46 +BEGIN
81.47 + BLOCK "StringFileInfo"
81.48 + BEGIN
81.49 + BLOCK "000004b0"
81.50 + BEGIN
81.51 + VALUE "Comments", "SQLite Extension"
81.52 + VALUE "FileDescription", "SourceMod SQLite Extension"
81.53 + VALUE "FileVersion", SVN_FULL_VERSION
81.54 + VALUE "InternalName", "SourceMod SQLite Extension"
81.55 + VALUE "LegalCopyright", "Copyright (c) 2004-2007, AlliedModders LLC"
81.56 + VALUE "OriginalFilename", "dbi.sqlite.ext.dll"
81.57 + VALUE "ProductName", "SourceMod SQLite Extension"
81.58 + VALUE "ProductVersion", SVN_FULL_VERSION
81.59 + END
81.60 + END
81.61 + BLOCK "VarFileInfo"
81.62 + BEGIN
81.63 + VALUE "Translation", 0x0, 1200
81.64 + END
81.65 +END
81.66 +
81.67 +
81.68 +#ifdef APSTUDIO_INVOKED
81.69 +/////////////////////////////////////////////////////////////////////////////
81.70 +//
81.71 +// TEXTINCLUDE
81.72 +//
81.73 +
81.74 +1 TEXTINCLUDE
81.75 +BEGIN
81.76 + "resource.h\0"
81.77 +END
81.78 +
81.79 +2 TEXTINCLUDE
81.80 +BEGIN
81.81 + "#include ""winres.h""\r\n"
81.82 + "\0"
81.83 +END
81.84 +
81.85 +3 TEXTINCLUDE
81.86 +BEGIN
81.87 + "\r\n"
81.88 + "\0"
81.89 +END
81.90 +
81.91 +#endif // APSTUDIO_INVOKED
81.92 +
81.93 +#endif // English (U.S.) resources
81.94 +/////////////////////////////////////////////////////////////////////////////
81.95 +
81.96 +
81.97 +
81.98 +#ifndef APSTUDIO_INVOKED
81.99 +/////////////////////////////////////////////////////////////////////////////
81.100 +//
81.101 +// Generated from the TEXTINCLUDE 3 resource.
81.102 +//
81.103 +
81.104 +
81.105 +/////////////////////////////////////////////////////////////////////////////
81.106 +#endif // not APSTUDIO_INVOKED
81.107 +
82.1 --- a/public/IDBDriver.h Sun Jul 29 01:05:58 2007 +0000
82.2 +++ b/public/IDBDriver.h Sun Jul 29 01:15:31 2007 +0000
82.3 @@ -49,6 +49,9 @@
82.4 DBType_Blob, /**< Raw binary data (variable length) */
82.5 DBType_Integer, /**< 4-byte signed integer */
82.6 DBType_Float, /**< 4-byte floating point */
82.7 + DBType_NULL, /**< NULL (no data) */
82.8 + /* --------- */
82.9 + DBTypes_TOTAL, /**< Total number of database types known */
82.10 };
82.11
82.12 /**