function_name
stringlengths 1
80
| function
stringlengths 14
10.6k
| comment
stringlengths 12
8.02k
| normalized_comment
stringlengths 6
6.55k
|
|---|---|---|---|
unixRead
|
static int unixRead(OsFile *id, void *pBuf, int amt){
int got;
assert( id );
SimulateIOError(SQLITE_IOERR);
TIMER_START;
got = seekAndRead((unixFile*)id, pBuf, amt);
TIMER_END;
TRACE5("READ %-3d %5d %7d %d\n", ((unixFile*)id)->h, got,
last_page, TIMER_ELAPSED);
SEEK(0);
/* if( got<0 ) got = 0; */
if( got==amt ){
return SQLITE_OK;
}else{
return SQLITE_IOERR;
}
}
|
/*
** Read data from a file into a buffer. Return SQLITE_OK if all
** bytes were read successfully and SQLITE_IOERR if anything goes
** wrong.
*/
|
Read data from a file into a buffer. Return SQLITE_OK if all bytes were read successfully and SQLITE_IOERR if anything goes wrong.
|
seekAndWrite
|
static int seekAndWrite(unixFile *id, const void *pBuf, int cnt){
int got;
#ifdef USE_PREAD
got = pwrite(id->h, pBuf, cnt, id->offset);
#else
lseek(id->h, id->offset, SEEK_SET);
got = write(id->h, pBuf, cnt);
#endif
if( got>0 ){
id->offset += got;
}
return got;
}
|
/*
** Seek to the offset in id->offset then read cnt bytes into pBuf.
** Return the number of bytes actually read. Update the offset.
*/
|
Seek to the offset in id->offset then read cnt bytes into pBuf. Return the number of bytes actually read. Update the offset.
|
unixWrite
|
static int unixWrite(OsFile *id, const void *pBuf, int amt){
int wrote = 0;
assert( id );
assert( amt>0 );
SimulateIOError(SQLITE_IOERR);
SimulateDiskfullError;
TIMER_START;
while( amt>0 && (wrote = seekAndWrite((unixFile*)id, pBuf, amt))>0 ){
amt -= wrote;
pBuf = &((char*)pBuf)[wrote];
}
TIMER_END;
TRACE5("WRITE %-3d %5d %7d %d\n", ((unixFile*)id)->h, wrote,
last_page, TIMER_ELAPSED);
SEEK(0);
if( amt>0 ){
return SQLITE_FULL;
}
return SQLITE_OK;
}
|
/*
** Write data from a buffer into a file. Return SQLITE_OK on success
** or some other error code on failure.
*/
|
Write data from a buffer into a file. Return SQLITE_OK on success or some other error code on failure.
|
unixSeek
|
static int unixSeek(OsFile *id, i64 offset){
assert( id );
SEEK(offset/1024 + 1);
#ifdef SQLITE_TEST
if( offset ) SimulateDiskfullError
#endif
((unixFile*)id)->offset = offset;
return SQLITE_OK;
}
|
/*
** Move the read/write pointer in a file.
*/
|
Move the read/write pointer in a file.
|
full_fsync
|
static int full_fsync(int fd, int fullSync, int dataOnly){
int rc;
/* Record the number of times that we do a normal fsync() and
** FULLSYNC. This is used during testing to verify that this procedure
** gets called with the correct arguments.
*/
#ifdef SQLITE_TEST
if( fullSync ) sqlite3_fullsync_count++;
sqlite3_sync_count++;
#endif
/* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
** no-op
*/
#ifdef SQLITE_NO_SYNC
rc = SQLITE_OK;
#else
#if HAVE_FULLFSYNC
if( fullSync ){
rc = fcntl(fd, F_FULLFSYNC, 0);
}else{
rc = 1;
}
/* If the FULLSYNC failed, try to do a normal fsync() */
if( rc ) rc = fsync(fd);
#else /* if !defined(F_FULLSYNC) */
if( dataOnly ){
rc = fdatasync(fd);
}else{
rc = fsync(fd);
}
#endif /* defined(F_FULLFSYNC) */
#endif /* defined(SQLITE_NO_SYNC) */
return rc;
}
|
/*
** The fsync() system call does not work as advertised on many
** unix systems. The following procedure is an attempt to make
** it work better.
**
** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
** for testing when we want to run through the test suite quickly.
** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
** or power failure will likely corrupt the database file.
*/
|
The fsync() system call does not work as advertised on many unix systems. The following procedure is an attempt to make it work better.
The SQLITE_NO_SYNC macro disables all fsync()s. This is useful for testing when we want to run through the test suite quickly. You are strongly advised *not* to deploy with SQLITE_NO_SYNC enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash or power failure will likely corrupt the database file.
|
sqlite3UnixSyncDirectory
|
int sqlite3UnixSyncDirectory(const char *zDirname){
#ifdef SQLITE_DISABLE_DIRSYNC
return SQLITE_OK;
#else
int fd;
int r;
SimulateIOError(SQLITE_IOERR);
fd = open(zDirname, O_RDONLY|O_BINARY, 0);
TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
if( fd<0 ){
return SQLITE_CANTOPEN;
}
r = fsync(fd);
close(fd);
return ((r==0)?SQLITE_OK:SQLITE_IOERR);
#endif
}
|
/*
** Sync the directory zDirname. This is a no-op on operating systems other
** than UNIX.
**
** This is used to make sure the master journal file has truely been deleted
** before making changes to individual journals on a multi-database commit.
** The F_FULLFSYNC option is not needed here.
*/
|
Sync the directory zDirname. This is a no-op on operating systems other than UNIX.
This is used to make sure the master journal file has truely been deleted before making changes to individual journals on a multi-database commit. The F_FULLFSYNC option is not needed here.
|
unixTruncate
|
static int unixTruncate(OsFile *id, i64 nByte){
assert( id );
SimulateIOError(SQLITE_IOERR);
return ftruncate(((unixFile*)id)->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
}
|
/*
** Truncate an open file to a specified size
*/
|
Truncate an open file to a specified size
|
unixFileSize
|
static int unixFileSize(OsFile *id, i64 *pSize){
struct stat buf;
assert( id );
SimulateIOError(SQLITE_IOERR);
if( fstat(((unixFile*)id)->h, &buf)!=0 ){
return SQLITE_IOERR;
}
*pSize = buf.st_size;
return SQLITE_OK;
}
|
/*
** Determine the current size of a file in bytes
*/
|
Determine the current size of a file in bytes
|
unixCheckReservedLock
|
static int unixCheckReservedLock(OsFile *id){
int r = 0;
unixFile *pFile = (unixFile*)id;
assert( pFile );
sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */
/* Check if a thread in this process holds such a lock */
if( pFile->pLock->locktype>SHARED_LOCK ){
r = 1;
}
/* Otherwise see if some other process holds it.
*/
if( !r ){
struct flock lock;
lock.l_whence = SEEK_SET;
lock.l_start = RESERVED_BYTE;
lock.l_len = 1;
lock.l_type = F_WRLCK;
fcntl(pFile->h, F_GETLK, &lock);
if( lock.l_type!=F_UNLCK ){
r = 1;
}
}
sqlite3OsLeaveMutex();
TRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
return r;
}
|
/*
** This routine checks if there is a RESERVED lock held on the specified
** file by this or any other process. If such a lock is held, return
** non-zero. If the file is unlocked or holds only SHARED locks, then
** return zero.
*/
|
This routine checks if there is a RESERVED lock held on the specified file by this or any other process. If such a lock is held, return non-zero. If the file is unlocked or holds only SHARED locks, then return zero.
|
sqlite3UnixFullPathname
|
char *sqlite3UnixFullPathname(const char *zRelative){
char *zFull = 0;
if( zRelative[0]=='/' ){
sqlite3SetString(&zFull, zRelative, (char*)0);
}else{
char *zBuf = sqliteMalloc(5000);
if( zBuf==0 ){
return 0;
}
zBuf[0] = 0;
sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
(char*)0);
sqliteFree(zBuf);
}
#if 0
/*
** Remove "/./" path elements and convert "/A/./" path elements
** to just "/".
*/
if( zFull ){
int i, j;
for(i=j=0; zFull[i]; i++){
if( zFull[i]=='/' ){
if( zFull[i+1]=='/' ) continue;
if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
i += 1;
continue;
}
if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
while( j>0 && zFull[j-1]!='/' ){ j--; }
i += 3;
continue;
}
}
zFull[j++] = zFull[i];
}
zFull[j] = 0;
}
#endif
return zFull;
}
|
/*
** Turn a relative pathname into a full pathname. Return a pointer
** to the full pathname stored in space obtained from sqliteMalloc().
** The calling function is responsible for freeing this space once it
** is no longer needed.
*/
|
Turn a relative pathname into a full pathname. Return a pointer to the full pathname stored in space obtained from sqliteMalloc(). The calling function is responsible for freeing this space once it is no longer needed.
|
unixSetFullSync
|
static void unixSetFullSync(OsFile *id, int v){
((unixFile*)id)->fullSync = v;
}
|
/*
** Change the value of the fullsync flag in the given file descriptor.
*/
|
Change the value of the fullsync flag in the given file descriptor.
|
unixFileHandle
|
static int unixFileHandle(OsFile *id){
return ((unixFile*)id)->h;
}
|
/*
** Return the underlying file handle for an OsFile
*/
|
Return the underlying file handle for an OsFile
|
unixLockState
|
static int unixLockState(OsFile *id){
return ((unixFile*)id)->locktype;
}
|
/*
** Return an integer that indices the type of lock currently held
** by this handle. (Used for testing and analysis only.)
*/
|
Return an integer that indices the type of lock currently held by this handle. (Used for testing and analysis only.)
|
sqlite3UnixRandomSeed
|
int sqlite3UnixRandomSeed(char *zBuf){
/* We have to initialize zBuf to prevent valgrind from reporting
** errors. The reports issued by valgrind are incorrect - we would
** prefer that the randomness be increased by making use of the
** uninitialized space in zBuf - but valgrind errors tend to worry
** some users. Rather than argue, it seems easier just to initialize
** the whole array and silence valgrind, even if that means less randomness
** in the random seed.
**
** When testing, initializing zBuf[] to zero is all we do. That means
** that we always use the same random number sequence. This makes the
** tests repeatable.
*/
memset(zBuf, 0, 256);
#if !defined(SQLITE_TEST)
{
int pid, fd;
fd = open("/dev/urandom", O_RDONLY);
if( fd<0 ){
time_t t;
time(&t);
memcpy(zBuf, &t, sizeof(t));
pid = getpid();
memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
}else{
read(fd, zBuf, 256);
close(fd);
}
}
#endif
return SQLITE_OK;
}
|
/*
** Get information to seed the random number generator. The seed
** is written into the buffer zBuf[256]. The calling function must
** supply a sufficiently large buffer.
*/
|
Get information to seed the random number generator. The seed is written into the buffer zBuf[256]. The calling function must supply a sufficiently large buffer.
|
sqlite3UnixSleep
|
int sqlite3UnixSleep(int ms){
#if defined(HAVE_USLEEP) && HAVE_USLEEP
usleep(ms*1000);
return ms;
#else
sleep((ms+999)/1000);
return 1000*((ms+999)/1000);
#endif
}
|
/*
** Sleep for a little while. Return the amount of time slept.
** The argument is the number of milliseconds we want to sleep.
*/
|
Sleep for a little while. Return the amount of time slept. The argument is the number of milliseconds we want to sleep.
|
sqlite3UnixEnterMutex
|
void sqlite3UnixEnterMutex(){
#ifdef SQLITE_UNIX_THREADS
pthread_mutex_lock(&mutexAux);
if( !mutexOwnerValid || !pthread_equal(mutexOwner, pthread_self()) ){
pthread_mutex_unlock(&mutexAux);
pthread_mutex_lock(&mutexMain);
assert( inMutex==0 );
assert( !mutexOwnerValid );
pthread_mutex_lock(&mutexAux);
mutexOwner = pthread_self();
mutexOwnerValid = 1;
}
inMutex++;
pthread_mutex_unlock(&mutexAux);
#else
inMutex++;
#endif
}
|
/*
** The following pair of routine implement mutual exclusion for
** multi-threaded processes. Only a single thread is allowed to
** executed code that is surrounded by EnterMutex() and LeaveMutex().
**
** SQLite uses only a single Mutex. There is not much critical
** code and what little there is executes quickly and without blocking.
**
** As of version 3.3.2, this mutex must be recursive.
*/
|
The following pair of routine implement mutual exclusion for multi-threaded processes. Only a single thread is allowed to executed code that is surrounded by EnterMutex() and LeaveMutex().
SQLite uses only a single Mutex. There is not much critical code and what little there is executes quickly and without blocking.
As of version 3.3.2, this mutex must be recursive.
|
sqlite3UnixInMutex
|
int sqlite3UnixInMutex(int thisThrd){
#ifdef SQLITE_UNIX_THREADS
int rc;
pthread_mutex_lock(&mutexAux);
rc = inMutex>0 && (thisThrd==0 || pthread_equal(mutexOwner,pthread_self()));
pthread_mutex_unlock(&mutexAux);
return rc;
#else
return inMutex>0;
#endif
}
|
/*
** Return TRUE if the mutex is currently held.
**
** If the thisThrd parameter is true, return true only if the
** calling thread holds the mutex. If the parameter is false, return
** true if any thread holds the mutex.
*/
|
Return TRUE if the mutex is currently held.
If the thisThrd parameter is true, return true only if the calling thread holds the mutex. If the parameter is false, return true if any thread holds the mutex.
|
sqlite3UnixCurrentTime
|
int sqlite3UnixCurrentTime(double *prNow){
#ifdef NO_GETTOD
time_t t;
time(&t);
*prNow = t/86400.0 + 2440587.5;
#else
struct timeval sNow;
struct timezone sTz; /* Not used */
gettimeofday(&sNow, &sTz);
*prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
#endif
#ifdef SQLITE_TEST
if( sqlite3_current_time ){
*prNow = sqlite3_current_time/86400.0 + 2440587.5;
}
#endif
return 0;
}
|
/*
** Find the current time (in Universal Coordinated Time). Write the
** current time and date as a Julian Day number into *prNow and
** return 0. Return 1 if the time and date cannot be found.
*/
|
Find the current time (in Universal Coordinated Time). Write the current time and date as a Julian Day number into *prNow and return 0. Return 1 if the time and date cannot be found.
|
sqlite3_soft_heap_limit
|
void sqlite3_soft_heap_limit(int n){
ThreadData *pTd = sqlite3ThreadData();
if( pTd ){
pTd->nSoftHeapLimit = n;
}
sqlite3ReleaseThreadData();
}
|
/*
** Set the soft heap-size limit for the current thread. Passing a negative
** value indicates no limit.
*/
|
Set the soft heap-size limit for the current thread. Passing a negative value indicates no limit.
|
sqlite3_release_memory
|
int sqlite3_release_memory(int n){
return sqlite3pager_release_memory(n);
}
|
/*
** Release memory held by SQLite instances created by the current thread.
*/
|
Release memory held by SQLite instances created by the current thread.
|
sqlite3TestMallocFail
|
int sqlite3TestMallocFail(){
if( sqlite3_isFail ){
return 1;
}
if( sqlite3_iMallocFail>=0 ){
sqlite3_iMallocFail--;
if( sqlite3_iMallocFail==0 ){
sqlite3_iMallocFail = sqlite3_iMallocReset;
sqlite3_isFail = 1;
return 1;
}
}
return 0;
}
|
/*
** Check for a simulated memory allocation failure. Return true if
** the failure should be simulated. Return false to proceed as normal.
*/
|
Check for a simulated memory allocation failure. Return true if the failure should be simulated. Return false to proceed as normal.
|
checkGuards
|
static void checkGuards(u32 *p)
{
int i;
char *zAlloc = (char *)p;
char *z;
/* First set of guard words */
z = &zAlloc[TESTALLOC_OFFSET_GUARD1(p)];
for(i=0; i<TESTALLOC_NGUARD; i++){
assert(((u32 *)z)[i]==0xdead1122);
}
/* Second set of guard words */
z = &zAlloc[TESTALLOC_OFFSET_GUARD2(p)];
for(i=0; i<TESTALLOC_NGUARD; i++){
u32 guard = 0;
memcpy(&guard, &z[i*sizeof(u32)], sizeof(u32));
assert(guard==0xdead3344);
}
}
|
/*
** The argument is a pointer returned by sqlite3OsMalloc() or xRealloc().
** assert() that the first and last (TESTALLOC_NGUARD*4) bytes are set to the
** values set by the applyGuards() function.
*/
|
The argument is a pointer returned by sqlite3OsMalloc() or xRealloc(). assert() that the first and last (TESTALLOC_NGUARD*4) bytes are set to the values set by the applyGuards() function.
|
getOsPointer
|
static void *getOsPointer(void *p)
{
char *z = (char *)p;
return (void *)(&z[-1 * TESTALLOC_OFFSET_DATA(p)]);
}
|
/*
** The argument is a malloc()ed pointer as returned by the test-wrapper.
** Return a pointer to the Os level allocation.
*/
|
The argument is a malloc()ed pointer as returned by the test-wrapper. Return a pointer to the Os level allocation.
|
linkAlloc
|
static void linkAlloc(void *p){
void **pp = (void **)p;
pp[0] = 0;
pp[1] = sqlite3_pFirst;
if( sqlite3_pFirst ){
((void **)sqlite3_pFirst)[0] = p;
}
sqlite3_pFirst = p;
}
|
/*
** The argument points to an Os level allocation. Link it into the threads list
** of allocations.
*/
|
The argument points to an Os level allocation. Link it into the threads list of allocations.
|
relinkAlloc
|
static void relinkAlloc(void *p)
{
void **pp = (void **)p;
if( pp[0] ){
((void **)(pp[0]))[1] = p;
}else{
sqlite3_pFirst = p;
}
if( pp[1] ){
((void **)(pp[1]))[0] = p;
}
}
|
/*
** Pointer p is a pointer to an OS level allocation that has just been
** realloc()ed. Set the list pointers that point to this entry to it's new
** location.
*/
|
Pointer p is a pointer to an OS level allocation that has just been realloc()ed. Set the list pointers that point to this entry to it's new location.
|
OSMALLOC
|
static void * OSMALLOC(int n){
sqlite3OsEnterMutex();
#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
sqlite3_nMaxAlloc =
MAX(sqlite3_nMaxAlloc, sqlite3ThreadDataReadOnly()->nAlloc);
#endif
assert( !sqlite3_mallocDisallowed );
if( !sqlite3TestMallocFail() ){
u32 *p;
p = (u32 *)sqlite3OsMalloc(n + TESTALLOC_OVERHEAD);
assert(p);
sqlite3_nMalloc++;
applyGuards(p);
linkAlloc(p);
sqlite3OsLeaveMutex();
return (void *)(&p[TESTALLOC_NGUARD + 2*sizeof(void *)/sizeof(u32)]);
}
sqlite3OsLeaveMutex();
return 0;
}
|
/*
** This is the test layer's wrapper around sqlite3OsMalloc().
*/
|
This is the test layer's wrapper around sqlite3OsMalloc().
|
OSFREE
|
static void OSFREE(void *pFree){
sqlite3OsEnterMutex();
u32 *p = (u32 *)getOsPointer(pFree); /* p points to Os level allocation */
checkGuards(p);
unlinkAlloc(p);
memset(pFree, 0x55, OSSIZEOF(pFree));
sqlite3OsFree(p);
sqlite3_nFree++;
sqlite3OsLeaveMutex();
}
|
/*
** This is the test layer's wrapper around sqlite3OsFree(). The argument is a
** pointer to the space allocated for the application to use.
*/
|
This is the test layer's wrapper around sqlite3OsFree(). The argument is a pointer to the space allocated for the application to use.
|
OSREALLOC
|
static void * OSREALLOC(void *pRealloc, int n){
#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
sqlite3_nMaxAlloc =
MAX(sqlite3_nMaxAlloc, sqlite3ThreadDataReadOnly()->nAlloc);
#endif
assert( !sqlite3_mallocDisallowed );
if( !sqlite3TestMallocFail() ){
u32 *p = (u32 *)getOsPointer(pRealloc);
checkGuards(p);
p = sqlite3OsRealloc(p, n + TESTALLOC_OVERHEAD);
applyGuards(p);
relinkAlloc(p);
return (void *)(&p[TESTALLOC_NGUARD + 2*sizeof(void *)/sizeof(u32)]);
}
return 0;
}
|
/*
** This is the test layer's wrapper around sqlite3OsRealloc().
*/
|
This is the test layer's wrapper around sqlite3OsRealloc().
|
enforceSoftLimit
|
static int enforceSoftLimit(int n){
ThreadData *pTsd = sqlite3ThreadData();
if( pTsd==0 ){
return 0;
}
assert( pTsd->nAlloc>=0 );
if( n>0 && pTsd->nSoftHeapLimit>0 ){
while( pTsd->nAlloc+n>pTsd->nSoftHeapLimit && sqlite3_release_memory(n) ){}
}
return 1;
}
|
/*
** This routine is called when we are about to allocate n additional bytes
** of memory. If the new allocation will put is over the soft allocation
** limit, then invoke sqlite3_release_memory() to try to release some
** memory before continuing with the allocation.
**
** This routine also makes sure that the thread-specific-data (TSD) has
** be allocated. If it has not and can not be allocated, then return
** false. The updateMemoryUsedCount() routine below will deallocate
** the TSD if it ought to be.
**
** If SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, this routine is
** a no-op
*/
|
This routine is called when we are about to allocate n additional bytes of memory. If the new allocation will put is over the soft allocation limit, then invoke sqlite3_release_memory() to try to release some memory before continuing with the allocation.
This routine also makes sure that the thread-specific-data (TSD) has be allocated. If it has not and can not be allocated, then return false. The updateMemoryUsedCount() routine below will deallocate the TSD if it ought to be.
If SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, this routine is a no-op
|
updateMemoryUsedCount
|
static void updateMemoryUsedCount(int n){
ThreadData *pTsd = sqlite3ThreadData();
if( pTsd ){
pTsd->nAlloc += n;
assert( pTsd->nAlloc>=0 );
if( pTsd->nAlloc==0 && pTsd->nSoftHeapLimit==0 ){
sqlite3ReleaseThreadData();
}
}
}
|
/*
** Update the count of total outstanding memory that is held in
** thread-specific-data (TSD). If after this update the TSD is
** no longer being used, then deallocate it.
**
** If SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, this routine is
** a no-op
*/
|
Update the count of total outstanding memory that is held in thread-specific-data (TSD). If after this update the TSD is no longer being used, then deallocate it.
If SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, this routine is a no-op
|
sqlite3MallocRaw
|
void *sqlite3MallocRaw(int n, int doMemManage){
void *p = 0;
if( n>0 && !sqlite3MallocFailed() && (!doMemManage || enforceSoftLimit(n)) ){
while( (p = OSMALLOC(n))==0 && sqlite3_release_memory(n) ){}
if( !p ){
sqlite3FailedMalloc();
OSMALLOC_FAILED();
}else if( doMemManage ){
updateMemoryUsedCount(OSSIZEOF(p));
}
}
return p;
}
|
/*
** Allocate and return N bytes of uninitialised memory by calling
** sqlite3OsMalloc(). If the Malloc() call fails, attempt to free memory
** by calling sqlite3_release_memory().
*/
|
Allocate and return N bytes of uninitialised memory by calling sqlite3OsMalloc(). If the Malloc() call fails, attempt to free memory by calling sqlite3_release_memory().
|
sqlite3Realloc
|
void *sqlite3Realloc(void *p, int n){
if( sqlite3MallocFailed() ){
return 0;
}
if( !p ){
return sqlite3Malloc(n, 1);
}else{
void *np = 0;
#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
int origSize = OSSIZEOF(p);
#endif
if( enforceSoftLimit(n - origSize) ){
while( (np = OSREALLOC(p, n))==0 && sqlite3_release_memory(n) ){}
if( !np ){
sqlite3FailedMalloc();
OSMALLOC_FAILED();
}else{
updateMemoryUsedCount(OSSIZEOF(np) - origSize);
}
}
return np;
}
}
|
/*
** Resize the allocation at p to n bytes by calling sqlite3OsRealloc(). The
** pointer to the new allocation is returned. If the Realloc() call fails,
** attempt to free memory by calling sqlite3_release_memory().
*/
|
Resize the allocation at p to n bytes by calling sqlite3OsRealloc(). The pointer to the new allocation is returned. If the Realloc() call fails, attempt to free memory by calling sqlite3_release_memory().
|
sqlite3MallocX
|
void *sqlite3MallocX(int n){
return sqliteMalloc(n);
}
|
/*
** A version of sqliteMalloc() that is always a function, not a macro.
** Currently, this is used only to alloc to allocate the parser engine.
*/
|
A version of sqliteMalloc() that is always a function, not a macro. Currently, this is used only to alloc to allocate the parser engine.
|
sqlite3Malloc
|
void *sqlite3Malloc(int n, int doMemManage){
void *p = sqlite3MallocRaw(n, doMemManage);
if( p ){
memset(p, 0, n);
}
return p;
}
|
/*
** sqlite3Malloc
** sqlite3ReallocOrFree
**
** These two are implemented as wrappers around sqlite3MallocRaw(),
** sqlite3Realloc() and sqlite3Free().
*/
|
sqlite3Malloc sqlite3ReallocOrFree
These two are implemented as wrappers around sqlite3MallocRaw(), sqlite3Realloc() and sqlite3Free().
|
sqlite3StrDup
|
char *sqlite3StrDup(const char *z){
char *zNew;
if( z==0 ) return 0;
zNew = sqlite3MallocRaw(strlen(z)+1, 1);
if( zNew ) strcpy(zNew, z);
return zNew;
}
|
/*
** Make a copy of a string in memory obtained from sqliteMalloc(). These
** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
** is because when memory debugging is turned on, these two functions are
** called via macros that record the current file and line number in the
** ThreadData structure.
*/
|
Make a copy of a string in memory obtained from sqliteMalloc(). These functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This is because when memory debugging is turned on, these two functions are called via macros that record the current file and line number in the ThreadData structure.
|
sqlite3ErrorMsg
|
void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
va_list ap;
pParse->nErr++;
sqliteFree(pParse->zErrMsg);
va_start(ap, zFormat);
pParse->zErrMsg = sqlite3VMPrintf(zFormat, ap);
va_end(ap);
}
|
/*
** Add an error message to pParse->zErrMsg and increment pParse->nErr.
** The following formatting characters are allowed:
**
** %s Insert a string
** %z A string that should be freed after use
** %d Insert an integer
** %T Insert a token
** %S Insert the first element of a SrcList
**
** This function should be used to report any error that occurs whilst
** compiling an SQL statement (i.e. within sqlite3_prepare()). The
** last thing the sqlite3_prepare() function does is copy the error
** stored by this function into the database handle using sqlite3Error().
** Function sqlite3Error() should be used during statement execution
** (sqlite3_step() etc.).
*/
|
Add an error message to pParse->zErrMsg and increment pParse->nErr. The following formatting characters are allowed:
%s Insert a string %z A string that should be freed after use %d Insert an integer %T Insert a token %S Insert the first element of a SrcList
This function should be used to report any error that occurs whilst compiling an SQL statement (i.e. within sqlite3_prepare()). The last thing the sqlite3_prepare() function does is copy the error stored by this function into the database handle using sqlite3Error(). Function sqlite3Error() should be used during statement execution (sqlite3_step() etc.).
|
sqlite3ErrorClear
|
void sqlite3ErrorClear(Parse *pParse){
sqliteFree(pParse->zErrMsg);
pParse->zErrMsg = 0;
pParse->nErr = 0;
}
|
/*
** Clear the error message in pParse, if any
*/
|
Clear the error message in pParse, if any
|
sqlite3StrICmp
|
int sqlite3StrICmp(const char *zLeft, const char *zRight){
register unsigned char *a, *b;
a = (unsigned char *)zLeft;
b = (unsigned char *)zRight;
while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
return UpperToLower[*a] - UpperToLower[*b];
}
|
/*
** Some systems have stricmp(). Others have strcasecmp(). Because
** there is no consistency, we will define our own.
*/
|
Some systems have stricmp(). Others have strcasecmp(). Because there is no consistency, we will define our own.
|
sqlite3FitsIn32Bits
|
static int sqlite3FitsIn32Bits(const char *zNum){
int i, c;
if( *zNum=='-' || *zNum=='+' ) zNum++;
for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
return i<10 || (i==10 && memcmp(zNum,"2147483647",10)<=0);
}
|
/*
** The string zNum represents an integer. There might be some other
** information following the integer too, but that part is ignored.
** If the integer that the prefix of zNum represents will fit in a
** 32-bit signed integer, return TRUE. Otherwise return FALSE.
**
** This routine returns FALSE for the string -2147483648 even that
** that number will in fact fit in a 32-bit integer. But positive
** 2147483648 will not fit in 32 bits. So it seems safer to return
** false.
*/
|
The string zNum represents an integer. There might be some other information following the integer too, but that part is ignored. If the integer that the prefix of zNum represents will fit in a 32-bit signed integer, return TRUE. Otherwise return FALSE.
This routine returns FALSE for the string -2147483648 even that that number will in fact fit in a 32-bit integer. But positive 2147483648 will not fit in 32 bits. So it seems safer to return false.
|
sqlite3GetInt32
|
int sqlite3GetInt32(const char *zNum, int *pValue){
if( sqlite3FitsIn32Bits(zNum) ){
*pValue = atoi(zNum);
return 1;
}
return 0;
}
|
/*
** If zNum represents an integer that will fit in 32-bits, then set
** *pValue to that integer and return true. Otherwise return false.
*/
|
If zNum represents an integer that will fit in 32-bits, then set *pValue to that integer and return true. Otherwise return false.
|
sqlite3FitsIn64Bits
|
int sqlite3FitsIn64Bits(const char *zNum){
int i, c;
if( *zNum=='-' || *zNum=='+' ) zNum++;
for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
return i<19 || (i==19 && memcmp(zNum,"9223372036854775807",19)<=0);
}
|
/*
** The string zNum represents an integer. There might be some other
** information following the integer too, but that part is ignored.
** If the integer that the prefix of zNum represents will fit in a
** 64-bit signed integer, return TRUE. Otherwise return FALSE.
**
** This routine returns FALSE for the string -9223372036854775808 even that
** that number will, in theory fit in a 64-bit integer. Positive
** 9223373036854775808 will not fit in 64 bits. So it seems safer to return
** false.
*/
|
The string zNum represents an integer. There might be some other information following the integer too, but that part is ignored. If the integer that the prefix of zNum represents will fit in a 64-bit signed integer, return TRUE. Otherwise return FALSE.
This routine returns FALSE for the string -9223372036854775808 even that that number will, in theory fit in a 64-bit integer. Positive 9223373036854775808 will not fit in 64 bits. So it seems safer to return false.
|
sqlite3SafetyOn
|
int sqlite3SafetyOn(sqlite3 *db){
if( db->magic==SQLITE_MAGIC_OPEN ){
db->magic = SQLITE_MAGIC_BUSY;
return 0;
}else if( db->magic==SQLITE_MAGIC_BUSY ){
db->magic = SQLITE_MAGIC_ERROR;
db->flags |= SQLITE_Interrupt;
}
return 1;
}
|
/*
** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
** when this routine is called.
**
** This routine is a attempt to detect if two threads use the
** same sqlite* pointer at the same time. There is a race
** condition so it is possible that the error is not detected.
** But usually the problem will be seen. The result will be an
** error which can be used to debug the application that is
** using SQLite incorrectly.
**
** Ticket #202: If db->magic is not a valid open value, take care not
** to modify the db structure at all. It could be that db is a stale
** pointer. In other words, it could be that there has been a prior
** call to sqlite3_close(db) and db has been deallocated. And we do
** not want to write into deallocated memory.
*/
|
Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY. Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN when this routine is called.
This routine is a attempt to detect if two threads use the same sqlite* pointer at the same time. There is a race condition so it is possible that the error is not detected. But usually the problem will be seen. The result will be an error which can be used to debug the application that is using SQLite incorrectly.
Ticket #202: If db->magic is not a valid open value, take care not to modify the db structure at all. It could be that db is a stale pointer. In other words, it could be that there has been a prior call to sqlite3_close(db) and db has been deallocated. And we do not want to write into deallocated memory.
|
sqlite3SafetyOff
|
int sqlite3SafetyOff(sqlite3 *db){
if( db->magic==SQLITE_MAGIC_BUSY ){
db->magic = SQLITE_MAGIC_OPEN;
return 0;
}else if( db->magic==SQLITE_MAGIC_OPEN ){
db->magic = SQLITE_MAGIC_ERROR;
db->flags |= SQLITE_Interrupt;
}
return 1;
}
|
/*
** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
** when this routine is called.
*/
|
Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN. Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY when this routine is called.
|
sqlite3SafetyCheck
|
int sqlite3SafetyCheck(sqlite3 *db){
int magic;
if( db==0 ) return 1;
magic = db->magic;
if( magic!=SQLITE_MAGIC_CLOSED &&
magic!=SQLITE_MAGIC_OPEN &&
magic!=SQLITE_MAGIC_BUSY ) return 1;
return 0;
}
|
/*
** Check to make sure we have a valid db pointer. This test is not
** foolproof but it does provide some measure of protection against
** misuse of the interface such as passing in db pointers that are
** NULL or which have been previously closed. If this routine returns
** TRUE it means that the db pointer is invalid and should not be
** dereferenced for any reason. The calling function should invoke
** SQLITE_MISUSE immediately.
*/
|
Check to make sure we have a valid db pointer. This test is not foolproof but it does provide some measure of protection against misuse of the interface such as passing in db pointers that are NULL or which have been previously closed. If this routine returns TRUE it means that the db pointer is invalid and should not be dereferenced for any reason. The calling function should invoke SQLITE_MISUSE immediately.
|
sqlite3VarintLen
|
int sqlite3VarintLen(u64 v){
int i = 0;
do{
i++;
v >>= 7;
}while( v!=0 && i<9 );
return i;
}
|
/*
** Return the number of bytes that will be needed to store the given
** 64-bit integer.
*/
|
Return the number of bytes that will be needed to store the given 64-bit integer.
|
hexToInt
|
static int hexToInt(int h){
if( h>='0' && h<='9' ){
return h - '0';
}else if( h>='a' && h<='f' ){
return h - 'a' + 10;
}else{
assert( h>='A' && h<='F' );
return h - 'A' + 10;
}
}
|
/*
** Translate a single byte of Hex into an integer.
*/
|
Translate a single byte of Hex into an integer.
|
sqlite3HexToBlob
|
void *sqlite3HexToBlob(const char *z){
char *zBlob;
int i;
int n = strlen(z);
if( n%2 ) return 0;
zBlob = (char *)sqliteMalloc(n/2);
for(i=0; i<n; i+=2){
zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
}
return zBlob;
}
|
/*
** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
** value. Return a pointer to its binary value. Space to hold the
** binary value has been obtained from malloc and must be freed by
** the calling routine.
*/
|
Convert a BLOB literal of the form "x'hhhhhh'" into its binary value. Return a pointer to its binary value. Space to hold the binary value has been obtained from malloc and must be freed by the calling routine.
|
sqlite3TextToPtr
|
void *sqlite3TextToPtr(const char *z){
void *p;
u64 v;
u32 v2;
if( z[0]=='0' && z[1]=='x' ){
z += 2;
}
v = 0;
while( *z ){
v = (v<<4) + hexToInt(*z);
z++;
}
if( sizeof(p)==sizeof(v) ){
p = *(void**)&v;
}else{
assert( sizeof(p)==sizeof(v2) );
v2 = (u32)v;
p = *(void**)&v2;
}
return p;
}
|
/*
** Convert text generated by the "%p" conversion format back into
** a pointer.
*/
|
Convert text generated by the "%p" conversion format back into a pointer.
|
sqlite3ThreadData
|
ThreadData *sqlite3ThreadData(){
ThreadData *p = (ThreadData*)sqlite3OsThreadSpecificData(1);
if( !p ){
sqlite3FailedMalloc();
}
return p;
}
|
/*
** Return a pointer to the ThreadData associated with the calling thread.
*/
|
Return a pointer to the ThreadData associated with the calling thread.
|
sqlite3ThreadDataReadOnly
|
const ThreadData *sqlite3ThreadDataReadOnly(){
static const ThreadData zeroData = {0}; /* Initializer to silence warnings
** from broken compilers */
const ThreadData *pTd = sqlite3OsThreadSpecificData(0);
return pTd ? pTd : &zeroData;
}
|
/*
** Return a pointer to the ThreadData associated with the calling thread.
** If no ThreadData has been allocated to this thread yet, return a pointer
** to a substitute ThreadData structure that is all zeros.
*/
|
Return a pointer to the ThreadData associated with the calling thread. If no ThreadData has been allocated to this thread yet, return a pointer to a substitute ThreadData structure that is all zeros.
|
sqlite3ReleaseThreadData
|
void sqlite3ReleaseThreadData(){
sqlite3OsThreadSpecificData(-1);
}
|
/*
** Check to see if the ThreadData for this thread is all zero. If it
** is, then deallocate it.
*/
|
Check to see if the ThreadData for this thread is all zero. If it is, then deallocate it.
|
sqlite3MallocFailed
|
int sqlite3MallocFailed(){
return (mallocHasFailed && sqlite3OsInMutex(1));
}
|
/*
** Return true is a malloc has failed in this thread since the last call
** to sqlite3ApiExit(), or false otherwise.
*/
|
Return true is a malloc has failed in this thread since the last call to sqlite3ApiExit(), or false otherwise.
|
sqlite3FailedMalloc
|
void sqlite3FailedMalloc(){
sqlite3OsEnterMutex();
assert( mallocHasFailed==0 );
mallocHasFailed = 1;
}
|
/*
** Set the "malloc has failed" condition to true for this thread.
*/
|
Set the "malloc has failed" condition to true for this thread.
|
sqlite3MallocAllow
|
void sqlite3MallocAllow(){
assert( sqlite3_mallocDisallowed>0 );
sqlite3_mallocDisallowed--;
}
|
/*
** This function clears the flag set in the thread-specific-data structure set
** by sqlite3MallocDisallow().
*/
|
This function clears the flag set in the thread-specific-data structure set by sqlite3MallocDisallow().
|
resetParseObject
|
void resetParseObject(Parse *parseObj) {
if (parseObj != NULL) {
sqlite3ParseReset(parseObj);
}
}
|
/*int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){}*/
|
int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){}
|
sqlite3ParseReset
|
void sqlite3ParseReset(Parse *parseObj) {
if (parseObj == NULL) { return; }
TokenArray tokens = parseObj->tokens;
ParsedResultArray parsed = parseObj->parsed;
memset(parseObj, 0, sizeof(*parseObj));
parseObj->tokens = tokens; // restore tokens
parseObj->tokens.curSize = 0;
parseObj->parsed = parsed;
sqlite3ParsedResultArrayClean(&parseObj->parsed);
}
|
/**
* not free the tokens.array or parsed.array, just set it's size to 0
* free it, please use sqlite3ParseDelete
*/
|
not free the tokens.array or parsed.array, just set it's size to 0 free it, please use sqlite3ParseDelete
|
whereClauseInit
|
static void whereClauseInit(WhereClause *pWC, Parse *pParse){
pWC->pParse = pParse;
pWC->nTerm = 0;
pWC->nSlot = ARRAYSIZE(pWC->aStatic);
pWC->a = pWC->aStatic;
}
|
/*
** Initialize a preallocated WhereClause structure.
*/
|
Initialize a preallocated WhereClause structure.
|
whereClauseClear
|
static void whereClauseClear(WhereClause *pWC){
int i;
WhereTerm *a;
for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
if( a->flags & TERM_DYNAMIC ){
sqlite3ExprDelete(a->pExpr);
}
}
if( pWC->a!=pWC->aStatic ){
sqliteFree(pWC->a);
}
}
|
/*
** Deallocate a WhereClause structure. The WhereClause structure
** itself is not freed. This routine is the inverse of whereClauseInit().
*/
|
Deallocate a WhereClause structure. The WhereClause structure itself is not freed. This routine is the inverse of whereClauseInit().
|
getMask
|
static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
int i;
for(i=0; i<pMaskSet->n; i++){
if( pMaskSet->ix[i]==iCursor ){
return ((Bitmask)1)<<i;
}
}
return 0;
}
|
/*
** Return the bitmask for the given cursor number. Return 0 if
** iCursor is not in the set.
*/
|
Return the bitmask for the given cursor number. Return 0 if iCursor is not in the set.
|
createMask
|
static void createMask(ExprMaskSet *pMaskSet, int iCursor){
assert( pMaskSet->n < ARRAYSIZE(pMaskSet->ix) );
pMaskSet->ix[pMaskSet->n++] = iCursor;
}
|
/*
** Create a new mask for cursor iCursor.
**
** There is one cursor per table in the FROM clause. The number of
** tables in the FROM clause is limited by a test early in the
** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
** array will never overflow.
*/
|
Create a new mask for cursor iCursor.
There is one cursor per table in the FROM clause. The number of tables in the FROM clause is limited by a test early in the sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[] array will never overflow.
|
allowedOp
|
static int allowedOp(int op){
assert( TK_GT>TK_EQ && TK_GT<TK_GE );
assert( TK_LT>TK_EQ && TK_LT<TK_GE );
assert( TK_LE>TK_EQ && TK_LE<TK_GE );
assert( TK_GE==TK_EQ+4 );
return op==TK_IN || (op>=TK_EQ && op<=TK_GE);
}
|
/*
** Return TRUE if the given operator is one of the operators that is
** allowed for an indexable WHERE clause term. The allowed operators are
** "=", "<", ">", "<=", ">=", and "IN".
*/
|
Return TRUE if the given operator is one of the operators that is allowed for an indexable WHERE clause term. The allowed operators are "=", "<", ">", "<=", ">=", and "IN".
|
operatorMask
|
static int operatorMask(int op){
int c;
assert( allowedOp(op) );
if( op==TK_IN ){
c = WO_IN;
}else{
c = WO_EQ<<(op-TK_EQ);
}
assert( op!=TK_IN || c==WO_IN );
assert( op!=TK_EQ || c==WO_EQ );
assert( op!=TK_LT || c==WO_LT );
assert( op!=TK_LE || c==WO_LE );
assert( op!=TK_GT || c==WO_GT );
assert( op!=TK_GE || c==WO_GE );
return c;
}
|
/*
** Translate from TK_xx operator to WO_xx bitmask.
*/
|
Translate from TK_xx operator to WO_xx bitmask.
|
exprAnalyzeAll
|
static void exprAnalyzeAll(
SrcList *pTabList, /* the FROM clause */
ExprMaskSet *pMaskSet, /* table masks */
WhereClause *pWC /* the WHERE clause to be analyzed */
){
int i;
for(i=pWC->nTerm-1; i>=0; i--){
exprAnalyze(pTabList, pMaskSet, pWC, i);
}
}
|
/*
** Call exprAnalyze on all terms in a WHERE clause.
**
**
*/
|
Call exprAnalyze on all terms in a WHERE clause.
|
exprAnalyze
|
static void exprAnalyze(
SrcList *pSrc, /* the FROM clause */
ExprMaskSet *pMaskSet, /* table masks */
WhereClause *pWC, /* the WHERE clause */
int idxTerm /* Index of the term to be analyzed */
){
/* WhereTerm *pTerm = &pWC->a[idxTerm]; */
/* Expr *pExpr = pTerm->pExpr; */
/* Bitmask prereqLeft; */
/* Bitmask prereqAll; */
/* int nPattern; */
/* int isComplete; */
/* if( sqlite3MallocFailed() ) return; */
/* prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft); */
/* if( pExpr->op==TK_IN ){ */
/* assert( pExpr->pRight==0 ); */
/* pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList) */
/* | exprSelectTableUsage(pMaskSet, pExpr->pSelect); */
/* }else{ */
/* pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight); */
/* } */
/* prereqAll = exprTableUsage(pMaskSet, pExpr); */
/* if( ExprHasProperty(pExpr, EP_FromJoin) ){ */
/* prereqAll |= getMask(pMaskSet, pExpr->iRightJoinTable); */
/* } */
/* pTerm->prereqAll = prereqAll; */
/* pTerm->leftCursor = -1; */
/* pTerm->iParent = -1; */
/* pTerm->eOperator = 0; */
/* if( allowedOp(pExpr->op) && (pTerm->prereqRight & prereqLeft)==0 ){ */
/* Expr *pLeft = pExpr->pLeft; */
/* Expr *pRight = pExpr->pRight; */
/* if( pLeft->op==TK_COLUMN ){ */
/* pTerm->leftCursor = pLeft->iTable; */
/* pTerm->leftColumn = pLeft->iColumn; */
/* pTerm->eOperator = operatorMask(pExpr->op); */
/* } */
/* if( pRight && pRight->op==TK_COLUMN ){ */
/* WhereTerm *pNew; */
/* Expr *pDup; */
/* if( pTerm->leftCursor>=0 ){ */
/* int idxNew; */
/* pDup = sqlite3ExprDup(pExpr); */
/* idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC); */
/* if( idxNew==0 ) return; */
/* pNew = &pWC->a[idxNew]; */
/* pNew->iParent = idxTerm; */
/* pTerm = &pWC->a[idxTerm]; */
/* pTerm->nChild = 1; */
/* pTerm->flags |= TERM_COPIED; */
/* }else{ */
/* pDup = pExpr; */
/* pNew = pTerm; */
/* } */
/* exprCommute(pDup); */
/* pLeft = pDup->pLeft; */
/* pNew->leftCursor = pLeft->iTable; */
/* pNew->leftColumn = pLeft->iColumn; */
/* pNew->prereqRight = prereqLeft; */
/* pNew->prereqAll = prereqAll; */
/* pNew->eOperator = operatorMask(pDup->op); */
/* } */
/* } */
/* #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION */
/* /1* If a term is the BETWEEN operator, create two new virtual terms */
/* ** that define the range that the BETWEEN implements. */
/* *1/ */
/* else if( pExpr->op==TK_BETWEEN ){ */
/* ExprList *pList = pExpr->pList; */
/* int i; */
/* static const u8 ops[] = {TK_GE, TK_LE}; */
/* assert( pList!=0 ); */
/* assert( pList->nExpr==2 ); */
/* for(i=0; i<2; i++){ */
/* Expr *pNewExpr; */
/* int idxNew; */
/* pNewExpr = sqlite3Expr(ops[i], sqlite3ExprDup(pExpr->pLeft), */
/* sqlite3ExprDup(pList->a[i].pExpr), 0); */
/* idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); */
/* exprAnalyze(pSrc, pMaskSet, pWC, idxNew); */
/* pTerm = &pWC->a[idxTerm]; */
/* pWC->a[idxNew].iParent = idxTerm; */
/* } */
/* pTerm->nChild = 2; */
/* } */
/* #endif /1* SQLITE_OMIT_BETWEEN_OPTIMIZATION *1/ */
/* #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) */
/* /1* Attempt to convert OR-connected terms into an IN operator so that */
/* ** they can make use of indices. Example: */
/* ** */
/* ** x = expr1 OR expr2 = x OR x = expr3 */
/* ** */
/* ** is converted into */
/* ** */
/* ** x IN (expr1,expr2,expr3) */
/* ** */
/* ** This optimization must be omitted if OMIT_SUBQUERY is defined because */
/* ** the compiler for the the IN operator is part of sub-queries. */
/* *1/ */
/* else if( pExpr->op==TK_OR ){ */
/* int ok; */
/* int i, j; */
/* int iColumn, iCursor; */
/* WhereClause sOr; */
/* WhereTerm *pOrTerm; */
/* assert( (pTerm->flags & TERM_DYNAMIC)==0 ); */
/* whereClauseInit(&sOr, pWC->pParse); */
/* whereSplit(&sOr, pExpr, TK_OR); */
/* exprAnalyzeAll(pSrc, pMaskSet, &sOr); */
/* assert( sOr.nTerm>0 ); */
/* j = 0; */
/* do{ */
/* iColumn = sOr.a[j].leftColumn; */
/* iCursor = sOr.a[j].leftCursor; */
/* ok = iCursor>=0; */
/* for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){ */
/* if( pOrTerm->eOperator!=WO_EQ ){ */
/* goto or_not_possible; */
/* } */
/* if( pOrTerm->leftCursor==iCursor && pOrTerm->leftColumn==iColumn ){ */
/* pOrTerm->flags |= TERM_OR_OK; */
/* }else if( (pOrTerm->flags & TERM_COPIED)!=0 || */
/* ((pOrTerm->flags & TERM_VIRTUAL)!=0 && */
/* (sOr.a[pOrTerm->iParent].flags & TERM_OR_OK)!=0) ){ */
/* pOrTerm->flags &= ~TERM_OR_OK; */
/* }else{ */
/* ok = 0; */
/* } */
/* } */
/* }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<sOr.nTerm ); */
/* if( ok ){ */
/* ExprList *pList = 0; */
/* Expr *pNew, *pDup; */
/* for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){ */
/* if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue; */
/* pDup = sqlite3ExprDup(pOrTerm->pExpr->pRight); */
/* pList = sqlite3ExprListAppend(pList, pDup, 0); */
/* } */
/* pDup = sqlite3Expr(TK_COLUMN, 0, 0, 0); */
/* if( pDup ){ */
/* pDup->iTable = iCursor; */
/* pDup->iColumn = iColumn; */
/* } */
/* pNew = sqlite3Expr(TK_IN, pDup, 0, 0); */
/* if( pNew ){ */
/* int idxNew; */
/* transferJoinMarkings(pNew, pExpr); */
/* pNew->pList = pList; */
/* idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); */
/* exprAnalyze(pSrc, pMaskSet, pWC, idxNew); */
/* pTerm = &pWC->a[idxTerm]; */
/* pWC->a[idxNew].iParent = idxTerm; */
/* pTerm->nChild = 1; */
/* }else{ */
/* sqlite3ExprListDelete(pList); */
/* } */
/* } */
/* or_not_possible: */
/* whereClauseClear(&sOr); */
/* } */
/* #endif /1* SQLITE_OMIT_OR_OPTIMIZATION *1/ */
/* #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION */
/* /1* Add constraints to reduce the search space on a LIKE or GLOB */
/* ** operator. */
/* *1/ */
/* if( isLikeOrGlob(pWC->pParse->db, pExpr, &nPattern, &isComplete) ){ */
/* Expr *pLeft, *pRight; */
/* Expr *pStr1, *pStr2; */
/* Expr *pNewExpr1, *pNewExpr2; */
/* int idxNew1, idxNew2; */
/* pLeft = pExpr->pList->a[1].pExpr; */
/* pRight = pExpr->pList->a[0].pExpr; */
/* pStr1 = sqlite3Expr(TK_STRING, 0, 0, 0); */
/* if( pStr1 ){ */
/* sqlite3TokenCopy(&pStr1->token, &pRight->token); */
/* pStr1->token.n = nPattern; */
/* } */
/* pStr2 = sqlite3ExprDup(pStr1); */
/* if( pStr2 ){ */
/* assert( pStr2->token.dyn ); */
/* ++*(u8*)&pStr2->token.z[nPattern-1]; */
/* } */
/* pNewExpr1 = sqlite3Expr(TK_GE, sqlite3ExprDup(pLeft), pStr1, 0); */
/* idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC); */
/* exprAnalyze(pSrc, pMaskSet, pWC, idxNew1); */
/* pNewExpr2 = sqlite3Expr(TK_LT, sqlite3ExprDup(pLeft), pStr2, 0); */
/* idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC); */
/* exprAnalyze(pSrc, pMaskSet, pWC, idxNew2); */
/* pTerm = &pWC->a[idxTerm]; */
/* if( isComplete ){ */
/* pWC->a[idxNew1].iParent = idxTerm; */
/* pWC->a[idxNew2].iParent = idxTerm; */
/* pTerm->nChild = 2; */
/* } */
/* } */
/* #endif /1* SQLITE_OMIT_LIKE_OPTIMIZATION *1/ */
}
|
/*
** The input to this routine is an WhereTerm structure with only the
** "pExpr" field filled in. The job of this routine is to analyze the
** subexpression and populate all the other fields of the WhereTerm
** structure.
**
** If the expression is of the form "<expr> <op> X" it gets commuted
** to the standard form of "X <op> <expr>". If the expression is of
** the form "X <op> Y" where both X and Y are columns, then the original
** expression is unchanged and a new virtual expression of the form
** "Y <op> X" is added to the WHERE clause and analyzed separately.
*/
|
The input to this routine is an WhereTerm structure with only the "pExpr" field filled in. The job of this routine is to analyze the subexpression and populate all the other fields of the WhereTerm structure.
If the expression is of the form "<expr> <op> X" it gets commuted to the standard form of "X <op> <expr>". If the expression is of the form "X <op> Y" where both X and Y are columns, then the original expression is unchanged and a new virtual expression of the form "Y <op> X" is added to the WHERE clause and analyzed separately.
|
sortableByRowid
|
static int sortableByRowid(
int base, /* Cursor number for table to be sorted */
ExprList *pOrderBy, /* The ORDER BY clause */
int *pbRev /* Set to 1 if ORDER BY is DESC */
){
Expr *p;
assert( pOrderBy!=0 );
assert( pOrderBy->nExpr>0 );
p = pOrderBy->a[0].pExpr;
if( pOrderBy->nExpr==1 && p->op==TK_COLUMN && p->iTable==base
&& p->iColumn==-1 ){
*pbRev = pOrderBy->a[0].sortOrder;
return 1;
}
return 0;
}
|
/*
** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
** by sorting in order of ROWID. Return true if so and set *pbRev to be
** true for reverse ROWID and false for forward ROWID order.
*/
|
Check table to see if the ORDER BY clause in pOrderBy can be satisfied by sorting in order of ROWID. Return true if so and set *pbRev to be true for reverse ROWID and false for forward ROWID order.
|
estLog
|
static double estLog(double N){
double logN = 1;
double x = 10;
while( N>x ){
logN += 1;
x *= 10;
}
return logN;
}
|
/*
** Prepare a crude estimate of the logarithm of the input value.
** The results need not be exact. This is only used for estimating
** the total cost of performing operatings with O(logN) or O(NlogN)
** complexity. Because N is just a guess, it is no great tragedy if
** logN is a little off.
*/
|
Prepare a crude estimate of the logarithm of the input value. The results need not be exact. This is only used for estimating the total cost of performing operatings with O(logN) or O(NlogN) complexity. Because N is just a guess, it is no great tragedy if logN is a little off.
|
disableTerm
|
static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
if( pTerm
&& (pTerm->flags & TERM_CODED)==0
&& (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
){
pTerm->flags |= TERM_CODED;
if( pTerm->iParent>=0 ){
WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
if( (--pOther->nChild)==0 ){
disableTerm(pLevel, pOther);
}
}
}
}
|
/*
** Disable a term in the WHERE clause. Except, do not disable the term
** if it controls a LEFT OUTER JOIN and it did not originate in the ON
** or USING clause of that join.
**
** Consider the term t2.z='ok' in the following queries:
**
** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
**
** The t2.z='ok' is disabled in the in (2) because it originates
** in the ON clause. The term is disabled in (3) because it is not part
** of a LEFT OUTER JOIN. In (1), the term is not disabled.
**
** Disabling a term causes that term to not be tested in the inner loop
** of the join. Disabling is an optimization. When terms are satisfied
** by indices, we disable them to prevent redundant tests in the inner
** loop. We would get the correct results if nothing were ever disabled,
** but joins might run a little slower. The trick is to disable as much
** as we can without disabling too much. If we disabled in (1), we'd get
** the wrong answer. See ticket #813.
*/
|
Disable a term in the WHERE clause. Except, do not disable the term if it controls a LEFT OUTER JOIN and it did not originate in the ON or USING clause of that join.
Consider the term t2.z='ok' in the following queries:
(1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok' (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok' (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
The t2.z='ok' is disabled in the in (2) because it originates in the ON clause. The term is disabled in (3) because it is not part of a LEFT OUTER JOIN. In (1), the term is not disabled.
Disabling a term causes that term to not be tested in the inner loop of the join. Disabling is an optimization. When terms are satisfied by indices, we disable them to prevent redundant tests in the inner loop. We would get the correct results if nothing were ever disabled, but joins might run a little slower. The trick is to disable as much as we can without disabling too much. If we disabled in (1), we'd get the wrong answer. See ticket #813.
|
sqlite3Randomness
|
void sqlite3Randomness(int N, void *pBuf){
unsigned char *zBuf = pBuf;
sqlite3OsEnterMutex();
while( N-- ){
*(zBuf++) = randomByte();
}
sqlite3OsLeaveMutex();
}
|
/*
** Return N random bytes.
*/
|
Return N random bytes.
|
selectReadsTable
|
static int selectReadsTable(Select *p, Schema *pSchema, int iTab){
int i;
struct SrcList_item *pItem;
if( p->pSrc==0 ) return 0;
for(i=0, pItem=p->pSrc->a; i<p->pSrc->nSrc; i++, pItem++){
if( pItem->pSelect ){
if( selectReadsTable(pItem->pSelect, pSchema, iTab) ) return 1;
}else{
if( pItem->pTab->pSchema==pSchema && pItem->pTab->tnum==iTab ) return 1;
}
}
return 0;
}
|
/*
** Return non-zero if SELECT statement p opens the table with rootpage
** iTab in database iDb. This is used to see if a statement of the form
** "INSERT INTO <iDb, iTab> SELECT ..." can run without using temporary
** table for the results of the SELECT.
**
** No checking is done for sub-selects that are part of expressions.
*/
|
Return non-zero if SELECT statement p opens the table with rootpage iTab in database iDb. This is used to see if a statement of the form "INSERT INTO <iDb, iTab> SELECT ..." can run without using temporary table for the results of the SELECT.
No checking is done for sub-selects that are part of expressions.
|
sqlite3DeleteFrom
|
void sqlite3DeleteFrom(
Parse *pParse, /* The parser context */
SrcList *pTabList, /* The table from which we should delete things */
Expr *pWhere, /* The WHERE clause. May be null */
Expr *pLimit,
Expr *pOffset
){
Delete* deleteObj = sqlite3DeleteNew(pTabList, pWhere, pLimit, pOffset);
if (deleteObj == NULL) {
sqlite3ErrorMsg(pParse, "sqlite3DeleteNew return NULL, may the malloc failed!");
}
ParsedResultItem item;
item.sqltype = SQLTYPE_DELETE;
item.result.deleteObj = deleteObj;
sqlite3ParsedResultArrayAppend(&pParse->parsed, &item);
}
|
/*
** Generate code for a DELETE FROM statement.
**
** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
** \________/ \________________/
** pTabList pWhere
*/
|
Generate code for a DELETE FROM statement.
DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL; \________/ \________________/ pTabList pWhere
|
utf8ToUnicode
|
static WCHAR *utf8ToUnicode(const char *zFilename){
int nChar;
WCHAR *zWideFilename;
if( !isNT() ){
return 0;
}
nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
zWideFilename = sqliteMalloc( nChar*sizeof(zWideFilename[0]) );
if( zWideFilename==0 ){
return 0;
}
nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
if( nChar==0 ){
sqliteFree(zWideFilename);
zWideFilename = 0;
}
return zWideFilename;
}
|
/*
** Convert a UTF-8 string to UTF-32. Space to hold the returned string
** is obtained from sqliteMalloc.
*/
|
Convert a UTF-8 string to UTF-32. Space to hold the returned string is obtained from sqliteMalloc.
|
unicodeToUtf8
|
static char *unicodeToUtf8(const WCHAR *zWideFilename){
int nByte;
char *zFilename;
nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
zFilename = sqliteMalloc( nByte );
if( zFilename==0 ){
return 0;
}
nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
0, 0);
if( nByte == 0 ){
sqliteFree(zFilename);
zFilename = 0;
}
return zFilename;
}
|
/*
** Convert UTF-32 to UTF-8. Space to hold the returned string is
** obtained from sqliteMalloc().
*/
|
Convert UTF-32 to UTF-8. Space to hold the returned string is obtained from sqliteMalloc().
|
localtime
|
struct tm *__cdecl localtime(const time_t *t)
{
static struct tm y;
FILETIME uTm, lTm;
SYSTEMTIME pTm;
i64 t64;
t64 = *t;
t64 = (t64 + 11644473600)*10000000;
uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
uTm.dwHighDateTime= t64 >> 32;
FileTimeToLocalFileTime(&uTm,&lTm);
FileTimeToSystemTime(&lTm,&pTm);
y.tm_year = pTm.wYear - 1900;
y.tm_mon = pTm.wMonth - 1;
y.tm_wday = pTm.wDayOfWeek;
y.tm_mday = pTm.wDay;
y.tm_hour = pTm.wHour;
y.tm_min = pTm.wMinute;
y.tm_sec = pTm.wSecond;
return &y;
}
|
/*
** WindowsCE does not have a localtime() function. So create a
** substitute.
*/
|
WindowsCE does not have a localtime() function. So create a substitute.
|
winceMutexAcquire
|
static void winceMutexAcquire(HANDLE h){
DWORD dwErr;
do {
dwErr = WaitForSingleObject(h, INFINITE);
} while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
}
|
/*
** Acquire a lock on the handle h
*/
|
Acquire a lock on the handle h
|
winceDestroyLock
|
static void winceDestroyLock(winFile *pFile){
if (pFile->hMutex){
/* Acquire the mutex */
winceMutexAcquire(pFile->hMutex);
/* The following blocks should probably assert in debug mode, but they
are to cleanup in case any locks remained open */
if (pFile->local.nReaders){
pFile->shared->nReaders --;
}
if (pFile->local.bReserved){
pFile->shared->bReserved = FALSE;
}
if (pFile->local.bPending){
pFile->shared->bPending = FALSE;
}
if (pFile->local.bExclusive){
pFile->shared->bExclusive = FALSE;
}
/* De-reference and close our copy of the shared memory handle */
UnmapViewOfFile(pFile->shared);
CloseHandle(pFile->hShared);
/* Done with the mutex */
winceMutexRelease(pFile->hMutex);
CloseHandle(pFile->hMutex);
pFile->hMutex = NULL;
}
}
|
/*
** Destroy the part of winFile that deals with wince locks
*/
|
Destroy the part of winFile that deals with wince locks
|
winceLockFileEx
|
static BOOL winceLockFileEx(
HANDLE *phFile,
DWORD dwFlags,
DWORD dwReserved,
DWORD nNumberOfBytesToLockLow,
DWORD nNumberOfBytesToLockHigh,
LPOVERLAPPED lpOverlapped
){
/* If the caller wants a shared read lock, forward this call
** to winceLockFile */
if (lpOverlapped->Offset == SHARED_FIRST &&
dwFlags == 1 &&
nNumberOfBytesToLockLow == SHARED_SIZE){
return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
}
return FALSE;
}
|
/*
** An implementation of the LockFileEx() API of windows for wince
*/
|
An implementation of the LockFileEx() API of windows for wince
|
sqlite3WinDelete
|
int sqlite3WinDelete(const char *zFilename){
WCHAR *zWide = utf8ToUnicode(zFilename);
if( zWide ){
DeleteFileW(zWide);
sqliteFree(zWide);
}else{
#if OS_WINCE
return SQLITE_NOMEM;
#else
DeleteFileA(zFilename);
#endif
}
TRACE2("DELETE \"%s\"\n", zFilename);
return SQLITE_OK;
}
|
/*
** Delete the named file
*/
|
Delete the named file
|
sqlite3WinFileExists
|
int sqlite3WinFileExists(const char *zFilename){
int exists = 0;
WCHAR *zWide = utf8ToUnicode(zFilename);
if( zWide ){
exists = GetFileAttributesW(zWide) != 0xffffffff;
sqliteFree(zWide);
}else{
#if OS_WINCE
return SQLITE_NOMEM;
#else
exists = GetFileAttributesA(zFilename) != 0xffffffff;
#endif
}
return exists;
}
|
/*
** Return TRUE if the named file exists.
*/
|
Return TRUE if the named file exists.
|
winOpenDirectory
|
static int winOpenDirectory(
OsFile *id,
const char *zDirname
){
return SQLITE_OK;
}
|
/*
** Attempt to open a file descriptor for the directory that contains a
** file. This file descriptor can be used to fsync() the directory
** in order to make sure the creation of a new file is actually written
** to disk.
**
** This routine is only meaningful for Unix. It is a no-op under
** windows since windows does not support hard links.
**
** On success, a handle for a previously open file is at *id is
** updated with the new directory file descriptor and SQLITE_OK is
** returned.
**
** On failure, the function returns SQLITE_CANTOPEN and leaves
** *id unchanged.
*/
|
Attempt to open a file descriptor for the directory that contains a file. This file descriptor can be used to fsync() the directory in order to make sure the creation of a new file is actually written to disk.
This routine is only meaningful for Unix. It is a no-op under windows since windows does not support hard links.
On success, a handle for a previously open file is at *id is updated with the new directory file descriptor and SQLITE_OK is returned.
On failure, the function returns SQLITE_CANTOPEN and leaves *id unchanged.
|
winClose
|
static int winClose(OsFile **pId){
winFile *pFile;
if( pId && (pFile = (winFile*)*pId)!=0 ){
TRACE2("CLOSE %d\n", pFile->h);
CloseHandle(pFile->h);
#if OS_WINCE
winceDestroyLock(pFile);
if( pFile->zDeleteOnClose ){
DeleteFileW(pFile->zDeleteOnClose);
sqliteFree(pFile->zDeleteOnClose);
}
#endif
OpenCounter(-1);
sqliteFree(pFile);
*pId = 0;
}
return SQLITE_OK;
}
|
/*
** Close a file.
*/
|
Close a file.
|
winRead
|
static int winRead(OsFile *id, void *pBuf, int amt){
DWORD got;
assert( id!=0 );
SimulateIOError(SQLITE_IOERR);
TRACE3("READ %d lock=%d\n", ((winFile*)id)->h, ((winFile*)id)->locktype);
if( !ReadFile(((winFile*)id)->h, pBuf, amt, &got, 0) ){
got = 0;
}
if( got==(DWORD)amt ){
return SQLITE_OK;
}else{
return SQLITE_IOERR;
}
}
|
/*
** Read data from a file into a buffer. Return SQLITE_OK if all
** bytes were read successfully and SQLITE_IOERR if anything goes
** wrong.
*/
|
Read data from a file into a buffer. Return SQLITE_OK if all bytes were read successfully and SQLITE_IOERR if anything goes wrong.
|
winSeek
|
static int winSeek(OsFile *id, i64 offset){
LONG upperBits = offset>>32;
LONG lowerBits = offset & 0xffffffff;
DWORD rc;
assert( id!=0 );
#ifdef SQLITE_TEST
if( offset ) SimulateDiskfullError
#endif
SEEK(offset/1024 + 1);
rc = SetFilePointer(((winFile*)id)->h, lowerBits, &upperBits, FILE_BEGIN);
TRACE3("SEEK %d %lld\n", ((winFile*)id)->h, offset);
if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
return SQLITE_FULL;
}
return SQLITE_OK;
}
|
/*
** Move the read/write pointer in a file.
*/
|
Move the read/write pointer in a file.
|
winSync
|
static int winSync(OsFile *id, int dataOnly){
assert( id!=0 );
TRACE3("SYNC %d lock=%d\n", ((winFile*)id)->h, ((winFile*)id)->locktype);
if( FlushFileBuffers(((winFile*)id)->h) ){
return SQLITE_OK;
}else{
return SQLITE_IOERR;
}
}
|
/*
** Make sure all writes to a particular file are committed to disk.
*/
|
Make sure all writes to a particular file are committed to disk.
|
sqlite3WinSyncDirectory
|
int sqlite3WinSyncDirectory(const char *zDirname){
SimulateIOError(SQLITE_IOERR);
return SQLITE_OK;
}
|
/*
** Sync the directory zDirname. This is a no-op on operating systems other
** than UNIX.
*/
|
Sync the directory zDirname. This is a no-op on operating systems other than UNIX.
|
winTruncate
|
static int winTruncate(OsFile *id, i64 nByte){
LONG upperBits = nByte>>32;
assert( id!=0 );
TRACE3("TRUNCATE %d %lld\n", ((winFile*)id)->h, nByte);
SimulateIOError(SQLITE_IOERR);
SetFilePointer(((winFile*)id)->h, nByte, &upperBits, FILE_BEGIN);
SetEndOfFile(((winFile*)id)->h);
return SQLITE_OK;
}
|
/*
** Truncate an open file to a specified size
*/
|
Truncate an open file to a specified size
|
winFileSize
|
static int winFileSize(OsFile *id, i64 *pSize){
DWORD upperBits, lowerBits;
assert( id!=0 );
SimulateIOError(SQLITE_IOERR);
lowerBits = GetFileSize(((winFile*)id)->h, &upperBits);
*pSize = (((i64)upperBits)<<32) + lowerBits;
return SQLITE_OK;
}
|
/*
** Determine the current size of a file in bytes
*/
|
Determine the current size of a file in bytes
|
getReadLock
|
static int getReadLock(winFile *id){
int res;
if( isNT() ){
OVERLAPPED ovlp;
ovlp.Offset = SHARED_FIRST;
ovlp.OffsetHigh = 0;
ovlp.hEvent = 0;
res = LockFileEx(id->h, LOCKFILE_FAIL_IMMEDIATELY, 0, SHARED_SIZE,0,&ovlp);
}else{
int lk;
sqlite3Randomness(sizeof(lk), &lk);
id->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
res = LockFile(id->h, SHARED_FIRST+id->sharedLockByte, 0, 1, 0);
}
return res;
}
|
/*
** Acquire a reader lock.
** Different API routines are called depending on whether or not this
** is Win95 or WinNT.
*/
|
Acquire a reader lock. Different API routines are called depending on whether or not this is Win95 or WinNT.
|
unlockReadLock
|
static int unlockReadLock(winFile *pFile){
int res;
if( isNT() ){
res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
}else{
res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
}
return res;
}
|
/*
** Undo a readlock
*/
|
Undo a readlock
|
sqlite3WinIsDirWritable
|
int sqlite3WinIsDirWritable(char *zDirname){
int fileAttr;
WCHAR *zWide;
if( zDirname==0 ) return 0;
if( !isNT() && strlen(zDirname)>MAX_PATH ) return 0;
zWide = utf8ToUnicode(zDirname);
if( zWide ){
fileAttr = GetFileAttributesW(zWide);
sqliteFree(zWide);
}else{
#if OS_WINCE
return 0;
#else
fileAttr = GetFileAttributesA(zDirname);
#endif
}
if( fileAttr == 0xffffffff ) return 0;
if( (fileAttr & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY ){
return 0;
}
return 1;
}
|
/*
** Check that a given pathname is a directory and is writable
**
*/
|
Check that a given pathname is a directory and is writable
|
winCheckReservedLock
|
static int winCheckReservedLock(OsFile *id){
int rc;
winFile *pFile = (winFile*)id;
assert( pFile!=0 );
if( pFile->locktype>=RESERVED_LOCK ){
rc = 1;
TRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
}else{
rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
if( rc ){
UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
}
rc = !rc;
TRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
}
return rc;
}
|
/*
** This routine checks if there is a RESERVED lock held on the specified
** file by this or any other process. If such a lock is held, return
** non-zero, otherwise zero.
*/
|
This routine checks if there is a RESERVED lock held on the specified file by this or any other process. If such a lock is held, return non-zero, otherwise zero.
|
winSetFullSync
|
static void winSetFullSync(OsFile *id, int v){
return;
}
|
/*
** The fullSync option is meaningless on windows. This is a no-op.
*/
|
The fullSync option is meaningless on windows. This is a no-op.
|
winFileHandle
|
static int winFileHandle(OsFile *id){
return (int)((winFile*)id)->h;
}
|
/*
** Return the underlying file handle for an OsFile
*/
|
Return the underlying file handle for an OsFile
|
winLockState
|
static int winLockState(OsFile *id){
return ((winFile*)id)->locktype;
}
|
/*
** Return an integer that indices the type of lock currently held
** by this handle. (Used for testing and analysis only.)
*/
|
Return an integer that indices the type of lock currently held by this handle. (Used for testing and analysis only.)
|
allocateWinFile
|
static int allocateWinFile(winFile *pInit, OsFile **pId){
winFile *pNew;
pNew = sqliteMalloc( sizeof(*pNew) );
if( pNew==0 ){
CloseHandle(pInit->h);
#if OS_WINCE
sqliteFree(pInit->zDeleteOnClose);
#endif
*pId = 0;
return SQLITE_NOMEM;
}else{
*pNew = *pInit;
pNew->pMethod = &sqlite3WinIoMethod;
pNew->locktype = NO_LOCK;
pNew->sharedLockByte = 0;
*pId = (OsFile*)pNew;
OpenCounter(+1);
return SQLITE_OK;
}
}
|
/*
** Allocate memory for an OsFile. Initialize the new OsFile
** to the value given in pInit and return a pointer to the new
** OsFile. If we run out of memory, close the file and return NULL.
*/
|
Allocate memory for an OsFile. Initialize the new OsFile to the value given in pInit and return a pointer to the new OsFile. If we run out of memory, close the file and return NULL.
|
sqlite3WinRandomSeed
|
int sqlite3WinRandomSeed(char *zBuf){
/* We have to initialize zBuf to prevent valgrind from reporting
** errors. The reports issued by valgrind are incorrect - we would
** prefer that the randomness be increased by making use of the
** uninitialized space in zBuf - but valgrind errors tend to worry
** some users. Rather than argue, it seems easier just to initialize
** the whole array and silence valgrind, even if that means less randomness
** in the random seed.
**
** When testing, initializing zBuf[] to zero is all we do. That means
** that we always use the same random number sequence.* This makes the
** tests repeatable.
*/
memset(zBuf, 0, 256);
GetSystemTime((LPSYSTEMTIME)zBuf);
return SQLITE_OK;
}
|
/*
** Get information to seed the random number generator. The seed
** is written into the buffer zBuf[256]. The calling function must
** supply a sufficiently large buffer.
*/
|
Get information to seed the random number generator. The seed is written into the buffer zBuf[256]. The calling function must supply a sufficiently large buffer.
|
sqlite3WinSleep
|
int sqlite3WinSleep(int ms){
Sleep(ms);
return ms;
}
|
/*
** Sleep for a little while. Return the amount of time slept.
*/
|
Sleep for a little while. Return the amount of time slept.
|
sqlite3WinEnterMutex
|
void sqlite3WinEnterMutex(){
#ifdef SQLITE_W32_THREADS
static int isInit = 0;
while( !isInit ){
static long lock = 0;
if( InterlockedIncrement(&lock)==1 ){
InitializeCriticalSection(&cs);
isInit = 1;
}else{
Sleep(1);
}
}
EnterCriticalSection(&cs);
mutexOwner = GetCurrentThreadId();
#endif
inMutex++;
}
|
/*
** The following pair of routines implement mutual exclusion for
** multi-threaded processes. Only a single thread is allowed to
** executed code that is surrounded by EnterMutex() and LeaveMutex().
**
** SQLite uses only a single Mutex. There is not much critical
** code and what little there is executes quickly and without blocking.
**
** Version 3.3.1 and earlier used a simple mutex. Beginning with
** version 3.3.2, a recursive mutex is required.
*/
|
The following pair of routines implement mutual exclusion for multi-threaded processes. Only a single thread is allowed to executed code that is surrounded by EnterMutex() and LeaveMutex().
SQLite uses only a single Mutex. There is not much critical code and what little there is executes quickly and without blocking.
Version 3.3.1 and earlier used a simple mutex. Beginning with version 3.3.2, a recursive mutex is required.
|
sqlite3WinInMutex
|
int sqlite3WinInMutex(int thisThreadOnly){
#ifdef SQLITE_W32_THREADS
return inMutex>0 && (thisThreadOnly==0 || mutexOwner==GetCurrentThreadId());
#else
return inMutex>0;
#endif
}
|
/*
** Return TRUE if the mutex is currently held.
**
** If the thisThreadOnly parameter is true, return true if and only if the
** calling thread holds the mutex. If the parameter is false, return
** true if any thread holds the mutex.
*/
|
Return TRUE if the mutex is currently held.
If the thisThreadOnly parameter is true, return true if and only if the calling thread holds the mutex. If the parameter is false, return true if any thread holds the mutex.
|
sqlite3WinCurrentTime
|
int sqlite3WinCurrentTime(double *prNow){
FILETIME ft;
/* FILETIME structure is a 64-bit value representing the number of
100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
*/
double now;
#if OS_WINCE
SYSTEMTIME time;
GetSystemTime(&time);
SystemTimeToFileTime(&time,&ft);
#else
GetSystemTimeAsFileTime( &ft );
#endif
now = ((double)ft.dwHighDateTime) * 4294967296.0;
*prNow = (now + ft.dwLowDateTime)/864000000000.0 + 2305813.5;
#ifdef SQLITE_TEST
if( sqlite3_current_time ){
*prNow = sqlite3_current_time/86400.0 + 2440587.5;
}
#endif
return 0;
}
|
/*
** Find the current time (in Universal Coordinated Time). Write the
** current time and date as a Julian Day number into *prNow and
** return 0. Return 1 if the time and date cannot be found.
*/
|
Find the current time (in Universal Coordinated Time). Write the current time and date as a Julian Day number into *prNow and return 0. Return 1 if the time and date cannot be found.
|
clearSelect
|
static void clearSelect(Select *p){
sqlite3ExprListDelete(p->pEList);
sqlite3SrcListDelete(p->pSrc);
sqlite3ExprDelete(p->pWhere);
sqlite3ExprListDelete(p->pGroupBy);
sqlite3ExprDelete(p->pHaving);
sqlite3ExprListDelete(p->pOrderBy);
sqlite3SelectDelete(p->pPrior);
sqlite3ExprDelete(p->pLimit);
sqlite3ExprDelete(p->pOffset);
}
|
/*
** Delete all the content of a Select structure but do not deallocate
** the select structure itself.
*/
|
Delete all the content of a Select structure but do not deallocate the select structure itself.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.