33 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
35 #define _CRT_SECURE_NO_WARNINGS
42 #if !defined(SQLITE_OS_WINRT)
43 # define SQLITE_OS_WINRT 0
50 #pragma warning(disable : 4054)
51 #pragma warning(disable : 4055)
52 #pragma warning(disable : 4100)
53 #pragma warning(disable : 4127)
54 #pragma warning(disable : 4130)
55 #pragma warning(disable : 4152)
56 #pragma warning(disable : 4189)
57 #pragma warning(disable : 4206)
58 #pragma warning(disable : 4210)
59 #pragma warning(disable : 4232)
60 #pragma warning(disable : 4244)
61 #pragma warning(disable : 4305)
62 #pragma warning(disable : 4306)
63 #pragma warning(disable : 4702)
64 #pragma warning(disable : 4706)
70 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
71 # define SQLITE_OMIT_LOAD_EXTENSION 1
77 #ifndef SQLITE_DISABLE_LFS
78 # define _LARGE_FILE 1
79 # ifndef _FILE_OFFSET_BITS
80 # define _FILE_OFFSET_BITS 64
82 # define _LARGEFILE_SOURCE 1
92 typedef unsigned char u8;
93 #if SQLITE_USER_AUTHENTICATION
94 # include "sqlite3userauth.h"
99 #if !defined(_WIN32) && !defined(WIN32)
101 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
105 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
108 # define GETPID getpid
109 # if defined(__MINGW32__)
110 # define DIRENT dirent
112 # define S_ISLNK(mode) (0)
116 # define GETPID (int)GetCurrentProcessId
118 #include <sys/types.h>
119 #include <sys/stat.h>
122 # include <readline/readline.h>
123 # include <readline/history.h>
127 # include <editline/readline.h>
130 #if HAVE_EDITLINE || HAVE_READLINE
132 # define shell_add_history(X) add_history(X)
133 # define shell_read_history(X) read_history(X)
134 # define shell_write_history(X) write_history(X)
135 # define shell_stifle_history(X) stifle_history(X)
136 # define shell_readline(X) readline(X)
140 # include "linenoise.h"
141 # define shell_add_history(X) linenoiseHistoryAdd(X)
142 # define shell_read_history(X) linenoiseHistoryLoad(X)
143 # define shell_write_history(X) linenoiseHistorySave(X)
144 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
145 # define shell_readline(X) linenoise(X)
149 # define shell_read_history(X)
150 # define shell_write_history(X)
151 # define shell_stifle_history(X)
153 # define SHELL_USE_LOCAL_GETLINE 1
157 #if defined(_WIN32) || defined(WIN32)
159 # define SQLITE_OMIT_POPEN 1
163 # define isatty(h) _isatty(h)
165 # define access(f,m) _access((f),(m))
168 # define unlink _unlink
171 # define strdup _strdup
174 # define popen _popen
176 # define pclose _pclose
182 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
185 extern FILE *
popen(
const char*,
const char*);
188 # define SQLITE_OMIT_POPEN 1
192 #if defined(_WIN32_WCE)
201 #define IsSpace(X) isspace((unsigned char)X)
202 #define IsDigit(X) isdigit((unsigned char)X)
203 #define ToLower(X) (char)tolower((unsigned char)X)
205 #if defined(_WIN32) || defined(WIN32)
212 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
213 extern char *sqlite3_win32_mbcs_to_utf8_v2(
const char *,
int);
214 extern char *sqlite3_win32_utf8_to_mbcs_v2(
const char *,
int);
215 extern LPWSTR sqlite3_win32_utf8_to_unicode(
const char *zText);
224 #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
226 if( isOutput ) fflush(file);
227 _setmode(_fileno(file), _O_BINARY);
230 if( isOutput ) fflush(file);
231 _setmode(_fileno(file), _O_TEXT);
234 # define setBinaryMode(X,Y)
235 # define setTextMode(X,Y)
257 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
258 #include <sys/time.h>
259 #include <sys/resource.h>
262 #if defined(_WRS_KERNEL) || defined(__RTP__)
264 struct timeval ru_utime;
265 struct timeval ru_stime;
267 #define getrusage(A,B) memset(B,0,sizeof(*B))
271 static struct rusage
sBegin;
279 getrusage(RUSAGE_SELF, &
sBegin);
285 static double timeDiff(
struct timeval *pStart,
struct timeval *pEnd){
286 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
287 (double)(pEnd->tv_sec - pStart->tv_sec);
297 getrusage(RUSAGE_SELF, &sEnd);
298 printf(
"Run Time: real %.3f user %f sys %f\n",
305 #define BEGIN_TIMER beginTimer()
306 #define END_TIMER endTimer()
309 #elif (defined(_WIN32) || defined(WIN32))
312 static HANDLE hProcess;
313 static FILETIME ftKernelBegin;
314 static FILETIME ftUserBegin;
316 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
317 LPFILETIME, LPFILETIME);
318 static GETPROCTIMES getProcessTimesAddr =
NULL;
324 static int hasTimer(
void){
325 if( getProcessTimesAddr ){
333 hProcess = GetCurrentProcess();
335 HINSTANCE hinstLib = LoadLibrary(TEXT(
"Kernel32.dll"));
336 if(
NULL != hinstLib ){
337 getProcessTimesAddr =
338 (GETPROCTIMES) GetProcAddress(hinstLib,
"GetProcessTimes");
339 if(
NULL != getProcessTimesAddr ){
342 FreeLibrary(hinstLib);
355 FILETIME ftCreation, ftExit;
356 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
357 &ftKernelBegin,&ftUserBegin);
363 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
366 return (
double) ((i64End - i64Start) / 10000000.0);
374 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
376 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
377 printf(
"Run Time: real %.3f user %f sys %f\n",
378 (ftWallEnd - ftWallBegin)*0.001,
380 timeDiff(&ftKernelBegin, &ftKernelEnd));
384 #define BEGIN_TIMER beginTimer()
385 #define END_TIMER endTimer()
386 #define HAS_TIMER hasTimer()
397 #define UNUSED_PARAMETER(x) (void)(x)
402 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
439 static unsigned int oomCounter = 0;
440 static unsigned int oomRepeat = 0;
441 static void*(*defaultMalloc)(int) = 0;
462 #if defined(_WIN32) || defined(WIN32)
463 void utf8_printf(FILE *out,
const char *zFormat, ...){
465 va_start(ap, zFormat);
468 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
473 vfprintf(out, zFormat, ap);
477 #elif !defined(utf8_printf)
478 # define utf8_printf fprintf
485 #if !defined(raw_printf)
486 # define raw_printf fprintf
500 void shellOomFault(
void){
513 static void *oomMalloc(
int nByte){
522 return defaultMalloc(nByte);
529 static void registerOomSimulator(
void){
541 #ifdef SQLITE_ENABLE_IOTRACE
542 static FILE *iotrace = 0;
551 #ifdef SQLITE_ENABLE_IOTRACE
552 static void SQLITE_CDECL iotracePrintf(
const char *zFormat, ...){
555 if( iotrace==0 )
return;
556 va_start(ap, zFormat);
573 int aw = w<0 ? -w : w;
575 if( aw>(
int)
sizeof(zBuf)/3 ) aw = (int)
sizeof(zBuf)/3;
576 for(i=n=0; zUtf[i]; i++){
577 if( (zUtf[i]&0xc0)!=0x80 ){
580 do{ i++; }
while( (zUtf[i]&0xc0)==0x80 );
599 if( *z==
'-' || *z==
'+' ) z++;
604 if( realnum ) *realnum = 0;
610 if( realnum ) *realnum = 1;
612 if( *z==
'e' || *z==
'E' ){
614 if( *z==
'+' || *z==
'-' ) z++;
617 if( realnum ) *realnum = 1;
628 while( *z2 ){ z2++; }
629 return 0x3fffffff & (int)(z2 - z);
639 if( (0xc0&*(z++))!=0x80 ) n++;
654 int nLine = zLine==0 ? 0 : 100;
659 nLine = nLine*2 + 100;
660 zLine = realloc(zLine, nLine);
663 if( fgets(&zLine[n], nLine - n, in)==0 ){
671 while( zLine[n] ) n++;
672 if( n>0 && zLine[n-1]==
'\n' ){
674 if( n>0 && zLine[n-1]==
'\r' ) n--;
679 #if defined(_WIN32) || defined(WIN32)
683 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
687 zLine = realloc(zLine, nTrans);
690 memcpy(zLine, zTrans, nTrans);
719 #if SHELL_USE_LOCAL_GETLINE
720 printf(
"%s", zPrompt);
725 zResult = shell_readline(zPrompt);
726 if( zResult && *zResult ) shell_add_history(zResult);
738 if( c>=
'0' && c<=
'9' )
return c -
'0';
739 if( c>=
'a' && c<=
'f' )
return c -
'a' + 10;
740 if( c>=
'A' && c<=
'F' )
return c -
'A' + 10;
749 static const struct {
char *zSuffix;
int iMult; } aMult[] = {
751 {
"MiB", 1024*1024 },
752 {
"GiB", 1024*1024*1024 },
755 {
"GB", 1000000000 },
765 }
else if( zArg[0]==
'+' ){
768 if( zArg[0]==
'0' && zArg[1]==
'x' ){
777 v = v*10 + zArg[0] -
'0';
787 return isNeg? -v : v;
804 memset(p, 0,
sizeof(*p));
824 len = nAppend+p->
n+1;
827 for(i=0; i<nAppend; i++){
828 if( zAppend[i]==quote ) len++;
839 char *zCsr = p->
z+p->
n;
841 for(i=0; i<nAppend; i++){
842 *zCsr++ = zAppend[i];
843 if( zAppend[i]==quote ) *zCsr++ = quote;
846 p->
n = (int)(zCsr - p->
z);
849 memcpy(p->
z+p->
n, zAppend, nAppend);
865 if( !isalpha((
unsigned char)
zName[0]) &&
zName[0]!=
'_' )
return '"';
866 for(i=0;
zName[i]; i++){
867 if( !isalnum((
unsigned char)
zName[i]) &&
zName[i]!=
'_' )
return '"';
889 zSchema ? zSchema :
"main",
zName);
963 static const char *
aPrefix[] = {
977 if( zIn!=0 && strncmp(zIn,
"CREATE ", 7)==0 ){
980 if( strncmp(zIn+7,
aPrefix[i], n)==0 && zIn[n+7]==
' ' ){
1018 #define SQLITE_EXTENSION_INIT1
1019 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1021 #if defined(_WIN32) && defined(_MSC_VER)
1038 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
1039 #define SQLITE_WINDIRENT_H
1045 #ifndef WIN32_LEAN_AND_MEAN
1046 #define WIN32_LEAN_AND_MEAN
1049 #include "windows.h"
1066 #include <sys/types.h>
1067 #include <sys/stat.h>
1074 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
1078 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
1082 #define S_ISLNK(mode) (0)
1089 #ifndef MODE_T_DEFINED
1090 #define MODE_T_DEFINED
1091 typedef unsigned short mode_t;
1098 #ifndef INO_T_DEFINED
1099 #define INO_T_DEFINED
1100 typedef unsigned short ino_t;
1108 # ifdef FILENAME_MAX
1109 # define NAME_MAX (FILENAME_MAX)
1111 # define NAME_MAX (260)
1119 #ifndef NULL_INTPTR_T
1120 # define NULL_INTPTR_T ((intptr_t)(0))
1123 #ifndef BAD_INTPTR_T
1124 # define BAD_INTPTR_T ((intptr_t)(-1))
1131 #ifndef DIRENT_DEFINED
1132 #define DIRENT_DEFINED
1133 typedef struct DIRENT DIRENT;
1134 typedef DIRENT *LPDIRENT;
1137 unsigned d_attributes;
1138 char d_name[NAME_MAX + 1];
1144 typedef struct DIR DIR;
1161 # define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
1169 extern const char *windirent_getenv(
const char *
name);
1176 extern LPDIR opendir(
const char *dirname);
1177 extern LPDIRENT readdir(LPDIR dirp);
1178 extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *
result);
1179 extern INT closedir(LPDIR dirp);
1200 #if defined(_WIN32) && defined(_MSC_VER)
1207 const char *windirent_getenv(
1210 static char value[32768];
1211 DWORD dwSize =
sizeof(value) /
sizeof(
char);
1214 memset(value, 0,
sizeof(value));
1215 dwRet = GetEnvironmentVariableA(
name, value, dwSize);
1216 if( dwRet==0 || dwRet>dwSize ){
1237 struct _finddata_t data;
1239 SIZE_T namesize =
sizeof(data.name) /
sizeof(data.name[0]);
1242 memset(dirp, 0,
sizeof(DIR));
1246 dirname = windirent_getenv(
"SystemDrive");
1249 memset(&data, 0,
sizeof(
struct _finddata_t));
1250 _snprintf(data.name, namesize,
"%s\\*", dirname);
1251 dirp->d_handle = _findfirst(data.name, &data);
1253 if( dirp->d_handle==BAD_INTPTR_T ){
1259 if( is_filtered(data) ){
1262 memset(&data, 0,
sizeof(
struct _finddata_t));
1263 if( _findnext(dirp->d_handle, &data)==-1 ){
1269 if( is_filtered(data) )
goto next;
1272 dirp->d_first.d_attributes = data.attrib;
1273 strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
1274 dirp->d_first.d_name[NAME_MAX] =
'\0';
1285 struct _finddata_t data;
1289 if( dirp->d_first.d_ino==0 ){
1290 dirp->d_first.d_ino++;
1291 dirp->d_next.d_ino++;
1293 return &dirp->d_first;
1298 memset(&data, 0,
sizeof(
struct _finddata_t));
1299 if( _findnext(dirp->d_handle, &data)==-1 )
return NULL;
1302 if( is_filtered(data) )
goto next;
1304 dirp->d_next.d_ino++;
1305 dirp->d_next.d_attributes = data.attrib;
1306 strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
1307 dirp->d_next.d_name[NAME_MAX] =
'\0';
1309 return &dirp->d_next;
1320 struct _finddata_t data;
1322 if( dirp==
NULL )
return EBADF;
1324 if( dirp->d_first.d_ino==0 ){
1325 dirp->d_first.d_ino++;
1326 dirp->d_next.d_ino++;
1328 entry->d_ino = dirp->d_first.d_ino;
1329 entry->d_attributes = dirp->d_first.d_attributes;
1330 strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
1331 entry->d_name[NAME_MAX] =
'\0';
1339 memset(&data, 0,
sizeof(
struct _finddata_t));
1340 if( _findnext(dirp->d_handle, &data)==-1 ){
1346 if( is_filtered(data) )
goto next;
1348 entry->d_ino = (ino_t)-1;
1349 entry->d_attributes = data.attrib;
1350 strncpy(entry->d_name, data.name, NAME_MAX);
1351 entry->d_name[NAME_MAX] =
'\0';
1365 if( dirp==
NULL )
return EINVAL;
1367 if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
1368 result = _findclose(dirp->d_handle);
1378 #define dirent DIRENT
1428 #ifndef SHA3_BYTEORDER
1429 # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
1430 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
1431 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
1433 # define SHA3_BYTEORDER 1234
1434 # elif defined(sparc) || defined(__ppc__)
1435 # define SHA3_BYTEORDER 4321
1437 # define SHA3_BYTEORDER 0
1449 unsigned char x[1600];
1461 u64 b0, b1, b2, b3, b4;
1462 u64 c0, c1, c2, c3, c4;
1463 u64 d0, d1, d2, d3, d4;
1464 static const u64 RC[] = {
1465 0x0000000000000001ULL, 0x0000000000008082ULL,
1466 0x800000000000808aULL, 0x8000000080008000ULL,
1467 0x000000000000808bULL, 0x0000000080000001ULL,
1468 0x8000000080008081ULL, 0x8000000000008009ULL,
1469 0x000000000000008aULL, 0x0000000000000088ULL,
1470 0x0000000080008009ULL, 0x000000008000000aULL,
1471 0x000000008000808bULL, 0x800000000000008bULL,
1472 0x8000000000008089ULL, 0x8000000000008003ULL,
1473 0x8000000000008002ULL, 0x8000000000000080ULL,
1474 0x000000000000800aULL, 0x800000008000000aULL,
1475 0x8000000080008081ULL, 0x8000000000008080ULL,
1476 0x0000000080000001ULL, 0x8000000080008008ULL
1478 # define a00 (p->u.s[0])
1479 # define a01 (p->u.s[1])
1480 # define a02 (p->u.s[2])
1481 # define a03 (p->u.s[3])
1482 # define a04 (p->u.s[4])
1483 # define a10 (p->u.s[5])
1484 # define a11 (p->u.s[6])
1485 # define a12 (p->u.s[7])
1486 # define a13 (p->u.s[8])
1487 # define a14 (p->u.s[9])
1488 # define a20 (p->u.s[10])
1489 # define a21 (p->u.s[11])
1490 # define a22 (p->u.s[12])
1491 # define a23 (p->u.s[13])
1492 # define a24 (p->u.s[14])
1493 # define a30 (p->u.s[15])
1494 # define a31 (p->u.s[16])
1495 # define a32 (p->u.s[17])
1496 # define a33 (p->u.s[18])
1497 # define a34 (p->u.s[19])
1498 # define a40 (p->u.s[20])
1499 # define a41 (p->u.s[21])
1500 # define a42 (p->u.s[22])
1501 # define a43 (p->u.s[23])
1502 # define a44 (p->u.s[24])
1503 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
1505 for(i=0; i<24; i+=4){
1511 d0 = c4^
ROL64(c1, 1);
1512 d1 = c0^
ROL64(c2, 1);
1513 d2 = c1^
ROL64(c3, 1);
1514 d3 = c2^
ROL64(c4, 1);
1515 d4 = c3^
ROL64(c0, 1);
1522 a00 = b0 ^((~b1)& b2 );
1524 a11 = b1 ^((~b2)& b3 );
1525 a22 = b2 ^((~b3)& b4 );
1526 a33 = b3 ^((~b4)& b0 );
1527 a44 = b4 ^((~b0)& b1 );
1534 a20 = b0 ^((~b1)& b2 );
1535 a31 = b1 ^((~b2)& b3 );
1536 a42 = b2 ^((~b3)& b4 );
1537 a03 = b3 ^((~b4)& b0 );
1538 a14 = b4 ^((~b0)& b1 );
1545 a40 = b0 ^((~b1)& b2 );
1546 a01 = b1 ^((~b2)& b3 );
1547 a12 = b2 ^((~b3)& b4 );
1548 a23 = b3 ^((~b4)& b0 );
1549 a34 = b4 ^((~b0)& b1 );
1556 a10 = b0 ^((~b1)& b2 );
1557 a21 = b1 ^((~b2)& b3 );
1558 a32 = b2 ^((~b3)& b4 );
1559 a43 = b3 ^((~b4)& b0 );
1560 a04 = b4 ^((~b0)& b1 );
1567 a30 = b0 ^((~b1)& b2 );
1568 a41 = b1 ^((~b2)& b3 );
1569 a02 = b2 ^((~b3)& b4 );
1570 a13 = b3 ^((~b4)& b0 );
1571 a24 = b4 ^((~b0)& b1 );
1578 d0 = c4^
ROL64(c1, 1);
1579 d1 = c0^
ROL64(c2, 1);
1580 d2 = c1^
ROL64(c3, 1);
1581 d3 = c2^
ROL64(c4, 1);
1582 d4 = c3^
ROL64(c0, 1);
1589 a00 = b0 ^((~b1)& b2 );
1591 a31 = b1 ^((~b2)& b3 );
1592 a12 = b2 ^((~b3)& b4 );
1593 a43 = b3 ^((~b4)& b0 );
1594 a24 = b4 ^((~b0)& b1 );
1601 a40 = b0 ^((~b1)& b2 );
1602 a21 = b1 ^((~b2)& b3 );
1603 a02 = b2 ^((~b3)& b4 );
1604 a33 = b3 ^((~b4)& b0 );
1605 a14 = b4 ^((~b0)& b1 );
1612 a30 = b0 ^((~b1)& b2 );
1613 a11 = b1 ^((~b2)& b3 );
1614 a42 = b2 ^((~b3)& b4 );
1615 a23 = b3 ^((~b4)& b0 );
1616 a04 = b4 ^((~b0)& b1 );
1623 a20 = b0 ^((~b1)& b2 );
1624 a01 = b1 ^((~b2)& b3 );
1625 a32 = b2 ^((~b3)& b4 );
1626 a13 = b3 ^((~b4)& b0 );
1627 a44 = b4 ^((~b0)& b1 );
1634 a10 = b0 ^((~b1)& b2 );
1635 a41 = b1 ^((~b2)& b3 );
1636 a22 = b2 ^((~b3)& b4 );
1637 a03 = b3 ^((~b4)& b0 );
1638 a34 = b4 ^((~b0)& b1 );
1645 d0 = c4^
ROL64(c1, 1);
1646 d1 = c0^
ROL64(c2, 1);
1647 d2 = c1^
ROL64(c3, 1);
1648 d3 = c2^
ROL64(c4, 1);
1649 d4 = c3^
ROL64(c0, 1);
1656 a00 = b0 ^((~b1)& b2 );
1658 a21 = b1 ^((~b2)& b3 );
1659 a42 = b2 ^((~b3)& b4 );
1660 a13 = b3 ^((~b4)& b0 );
1661 a34 = b4 ^((~b0)& b1 );
1668 a30 = b0 ^((~b1)& b2 );
1669 a01 = b1 ^((~b2)& b3 );
1670 a22 = b2 ^((~b3)& b4 );
1671 a43 = b3 ^((~b4)& b0 );
1672 a14 = b4 ^((~b0)& b1 );
1679 a10 = b0 ^((~b1)& b2 );
1680 a31 = b1 ^((~b2)& b3 );
1681 a02 = b2 ^((~b3)& b4 );
1682 a23 = b3 ^((~b4)& b0 );
1683 a44 = b4 ^((~b0)& b1 );
1690 a40 = b0 ^((~b1)& b2 );
1691 a11 = b1 ^((~b2)& b3 );
1692 a32 = b2 ^((~b3)& b4 );
1693 a03 = b3 ^((~b4)& b0 );
1694 a24 = b4 ^((~b0)& b1 );
1701 a20 = b0 ^((~b1)& b2 );
1702 a41 = b1 ^((~b2)& b3 );
1703 a12 = b2 ^((~b3)& b4 );
1704 a33 = b3 ^((~b4)& b0 );
1705 a04 = b4 ^((~b0)& b1 );
1712 d0 = c4^
ROL64(c1, 1);
1713 d1 = c0^
ROL64(c2, 1);
1714 d2 = c1^
ROL64(c3, 1);
1715 d3 = c2^
ROL64(c4, 1);
1716 d4 = c3^
ROL64(c0, 1);
1723 a00 = b0 ^((~b1)& b2 );
1725 a01 = b1 ^((~b2)& b3 );
1726 a02 = b2 ^((~b3)& b4 );
1727 a03 = b3 ^((~b4)& b0 );
1728 a04 = b4 ^((~b0)& b1 );
1735 a10 = b0 ^((~b1)& b2 );
1736 a11 = b1 ^((~b2)& b3 );
1737 a12 = b2 ^((~b3)& b4 );
1738 a13 = b3 ^((~b4)& b0 );
1739 a14 = b4 ^((~b0)& b1 );
1746 a20 = b0 ^((~b1)& b2 );
1747 a21 = b1 ^((~b2)& b3 );
1748 a22 = b2 ^((~b3)& b4 );
1749 a23 = b3 ^((~b4)& b0 );
1750 a24 = b4 ^((~b0)& b1 );
1757 a30 = b0 ^((~b1)& b2 );
1758 a31 = b1 ^((~b2)& b3 );
1759 a32 = b2 ^((~b3)& b4 );
1760 a33 = b3 ^((~b4)& b0 );
1761 a34 = b4 ^((~b0)& b1 );
1768 a40 = b0 ^((~b1)& b2 );
1769 a41 = b1 ^((~b2)& b3 );
1770 a42 = b2 ^((~b3)& b4 );
1771 a43 = b3 ^((~b4)& b0 );
1772 a44 = b4 ^((~b0)& b1 );
1782 memset(p, 0,
sizeof(*p));
1783 if( iSize>=128 && iSize<=512 ){
1784 p->
nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1786 p->
nRate = (1600 - 2*256)/8;
1788 #if SHA3_BYTEORDER==1234
1790 #elif SHA3_BYTEORDER==4321
1794 static unsigned int one = 1;
1795 if( 1==*(
unsigned char*)&one ){
1812 const unsigned char *aData,
1816 #if SHA3_BYTEORDER==1234
1817 if( (p->
nLoaded % 8)==0 && ((aData - (
const unsigned char*)0)&7)==0 ){
1818 for(; i+7<nData; i+=8){
1828 for(; i<nData; i++){
1829 #if SHA3_BYTEORDER==1234
1831 #elif SHA3_BYTEORDER==4321
1852 const unsigned char c1 = 0x86;
1855 const unsigned char c2 = 0x06;
1856 const unsigned char c3 = 0x80;
1861 for(i=0; i<p->
nRate; i++){
1891 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1912 const char *zFormat,
1918 va_start(ap, zFormat);
1921 n = (int)strlen(zBuf);
1977 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1983 if( zSql==0 )
return;
2011 for(i=0; i<nCol; i++){
2014 SHA3Update(&cx, (
const unsigned char*)
"N",1);
2023 for(j=8; j>=1; j--){
2037 for(j=8; j>=1; j--){
2183 #include <sys/types.h>
2184 #include <sys/stat.h>
2186 #if !defined(_WIN32) && !defined(WIN32)
2187 # include <unistd.h>
2188 # include <dirent.h>
2190 # include <sys/time.h>
2192 # include "windows.h"
2194 # include <direct.h>
2196 # define dirent DIRENT
2198 # define chmod _chmod
2203 # define mkdir(path,mode) _mkdir(path)
2204 # define lstat(path,buf) stat(path,buf)
2214 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
2215 #define FSDIR_COLUMN_NAME 0
2216 #define FSDIR_COLUMN_MODE 1
2217 #define FSDIR_COLUMN_MTIME 2
2218 #define FSDIR_COLUMN_DATA 3
2219 #define FSDIR_COLUMN_PATH 4
2220 #define FSDIR_COLUMN_DIR 5
2241 in = fopen(
zName,
"rb");
2284 if(
zName==0 )
return;
2308 LPFILETIME pFileTime
2310 SYSTEMTIME epochSystemTime;
2311 ULARGE_INTEGER epochIntervals;
2312 FILETIME epochFileTime;
2313 ULARGE_INTEGER fileIntervals;
2315 memset(&epochSystemTime, 0,
sizeof(SYSTEMTIME));
2316 epochSystemTime.wYear = 1970;
2317 epochSystemTime.wMonth = 1;
2318 epochSystemTime.wDay = 1;
2319 SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
2320 epochIntervals.LowPart = epochFileTime.dwLowDateTime;
2321 epochIntervals.HighPart = epochFileTime.dwHighDateTime;
2323 fileIntervals.LowPart = pFileTime->dwLowDateTime;
2324 fileIntervals.HighPart = pFileTime->dwHighDateTime;
2326 return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
2334 static void statTimesToUtc(
2336 struct stat *pStatBuf
2339 WIN32_FIND_DATAW fd;
2340 LPWSTR zUnicodeName;
2341 extern LPWSTR sqlite3_win32_utf8_to_unicode(
const char*);
2342 zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
2344 memset(&fd, 0,
sizeof(WIN32_FIND_DATAW));
2345 hFindFile = FindFirstFileW(zUnicodeName, &fd);
2346 if( hFindFile!=
NULL ){
2347 pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
2348 pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
2349 pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
2350 FindClose(hFindFile);
2364 struct stat *pStatBuf
2367 int rc = stat(zPath, pStatBuf);
2368 if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
2371 return stat(zPath, pStatBuf);
2382 struct stat *pStatBuf
2385 int rc = lstat(zPath, pStatBuf);
2386 if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
2389 return lstat(zPath, pStatBuf);
2413 int nCopy = (int)strlen(zCopy);
2420 for(; zCopy[i]!=
'/' && i<nCopy; i++);
2421 if( i==nCopy )
break;
2451 #if !defined(_WIN32) && !defined(WIN32)
2452 if( S_ISLNK(mode) ){
2454 if( symlink(zTo, zFile)<0 )
return 1;
2458 if( S_ISDIR(mode) ){
2459 if( mkdir(zFile, mode) ){
2467 || !S_ISDIR(sStat.st_mode)
2468 || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
2477 FILE *out = fopen(zFile,
"wb");
2478 if( out==0 )
return 1;
2488 if( rc==0 && mode && chmod(zFile, mode & 0777) ){
2498 #if !SQLITE_OS_WINRT
2500 FILETIME lastAccess;
2502 SYSTEMTIME currentTime;
2505 LPWSTR zUnicodeName;
2506 extern LPWSTR sqlite3_win32_utf8_to_unicode(
const char*);
2508 GetSystemTime(¤tTime);
2509 SystemTimeToFileTime(¤tTime, &lastAccess);
2510 intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
2511 lastWrite.dwLowDateTime = (DWORD)intervals;
2512 lastWrite.dwHighDateTime = intervals >> 32;
2513 zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
2514 if( zUnicodeName==0 ){
2517 hFile = CreateFileW(
2518 zUnicodeName, FILE_WRITE_ATTRIBUTES, 0,
NULL, OPEN_EXISTING,
2519 FILE_FLAG_BACKUP_SEMANTICS,
NULL
2522 if( hFile!=INVALID_HANDLE_VALUE ){
2523 BOOL bResult = SetFileTime(hFile,
NULL, &lastAccess, &lastWrite);
2530 #elif defined(AT_FDCWD) && 0
2532 struct timespec times[2];
2533 times[0].tv_nsec = times[1].tv_nsec = 0;
2534 times[0].tv_sec = time(0);
2535 times[1].tv_sec = mtime;
2536 if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
2541 struct timeval times[2];
2542 times[0].tv_usec = times[1].tv_usec = 0;
2543 times[0].tv_sec = time(0);
2544 times[1].tv_sec = mtime;
2545 if( utimes(zFile, times) ){
2568 if( argc<2 || argc>4 ){
2570 "wrong number of arguments to function writefile()", -1
2576 if( zFile==0 )
return;
2585 if( res==1 && errno==ENOENT ){
2591 if( argc>2 && res!=0 ){
2592 if( S_ISLNK(mode) ){
2594 }
else if( S_ISDIR(mode) ){
2617 if( S_ISLNK(iMode) ){
2619 }
else if( S_ISREG(iMode) ){
2621 }
else if( S_ISDIR(iMode) ){
2627 int m = (iMode >> ((2-i)*3));
2628 char *a = &z[1 + i*3];
2629 a[0] = (m & 0x4) ?
'r' :
'-';
2630 a[1] = (m & 0x2) ?
'w' :
'-';
2631 a[2] = (m & 0x1) ?
'x' :
'-';
2637 #ifndef SQLITE_OMIT_VIRTUALTABLE
2676 int argc,
const char *
const*argv,
2690 memset(pNew, 0,
sizeof(*pNew));
2713 memset(pCur, 0,
sizeof(*pCur));
2715 *ppCursor = &pCur->
base;
2725 for(i=0; i<=pCur->
iLvl; i++){
2727 if( pLvl->
pDir ) closedir(pLvl->
pDir);
2769 mode_t m = pCur->
sStat.st_mode;
2774 int iNew = pCur->
iLvl + 1;
2776 if( iNew>=pCur->
nLvl ){
2786 pLvl = &pCur->
aLvl[iNew];
2791 if( pLvl->
pDir==0 ){
2797 while( pCur->
iLvl>=0 ){
2799 struct dirent *pEntry = readdir(pLvl->
pDir);
2801 if( pEntry->d_name[0]==
'.' ){
2802 if( pEntry->d_name[1]==
'.' && pEntry->d_name[2]==
'\0' )
continue;
2803 if( pEntry->d_name[1]==
'\0' )
continue;
2814 closedir(pLvl->
pDir);
2852 mode_t m = pCur->
sStat.st_mode;
2855 #if !defined(_WIN32) && !defined(WIN32)
2856 }
else if( S_ISLNK(m) ){
2858 char *aBuf = aStatic;
2863 n = readlink(pCur->
zPath, aBuf, nBuf);
2908 return (pCur->
zPath==0);
2919 int idxNum,
const char *idxStr,
2922 const char *zDir = 0;
2928 fsdirSetErrmsg(pCur,
"table function fsdir requires an argument");
2932 assert( argc==idxNum && (argc==1 || argc==2) );
2935 fsdirSetErrmsg(pCur,
"table function fsdir requires a non-NULL argument");
2948 if( pCur->
zPath==0 ){
2982 const struct sqlite3_index_constraint *pConstraint;
2986 for(i=0; i<pIdxInfo->
nConstraint; i++, pConstraint++){
2988 switch( pConstraint->iColumn ){
2990 if( pConstraint->usable ){
2993 }
else if( idxPath<0 ){
2999 if( pConstraint->usable ){
3002 }
else if( idxDir<0 ){
3009 if( seenPath || seenDir ){
3071 # define fsdirRegister(x) SQLITE_OK
3146 #ifndef SQLITE_OMIT_VIRTUALTABLE
3178 #define COMPLETION_FIRST_PHASE 1
3179 #define COMPLETION_KEYWORDS 1
3180 #define COMPLETION_PRAGMAS 2
3181 #define COMPLETION_FUNCTIONS 3
3182 #define COMPLETION_COLLATIONS 4
3183 #define COMPLETION_INDEXES 5
3184 #define COMPLETION_TRIGGERS 6
3185 #define COMPLETION_DATABASES 7
3186 #define COMPLETION_TABLES 8
3187 #define COMPLETION_COLUMNS 9
3188 #define COMPLETION_MODULES 10
3189 #define COMPLETION_EOF 11
3207 int argc,
const char *
const*argv,
3220 #define COMPLETION_COLUMN_CANDIDATE 0
3221 #define COMPLETION_COLUMN_PREFIX 1
3222 #define COMPLETION_COLUMN_WHOLELINE 2
3223 #define COMPLETION_COLUMN_PHASE 3
3229 " prefix TEXT HIDDEN,"
3230 " wholeline TEXT HIDDEN,"
3237 memset(pNew, 0,
sizeof(*pNew));
3258 memset(pCur, 0,
sizeof(*pCur));
3260 *ppCursor = &pCur->
base;
3315 if( pCur->
pStmt==0 ){
3324 if( pCur->
pStmt==0 ){
3327 const char *zSep =
"";
3333 "SELECT name FROM \"%w\".sqlite_master",
3348 if( pCur->
pStmt==0 ){
3351 const char *zSep =
"";
3357 "SELECT pti.name FROM \"%w\".sqlite_master AS sm"
3358 " JOIN pragma_table_info(sm.name,%Q) AS pti"
3359 " WHERE sm.type='table'",
3360 zSql, zSep, zDb, zDb
3386 pCur->
ePhase = eNextPhase;
3459 int idxNum,
const char *idxStr,
3477 if( pCur->
nLine>0 ){
3483 int i = pCur->
nLine;
3484 while( i>0 && (isalnum(pCur->
zLine[i-1]) || pCur->
zLine[i-1]==
'_') ){
3515 int wholelineIdx = -1;
3517 const struct sqlite3_index_constraint *pConstraint;
3521 for(i=0; i<pIdxInfo->
nConstraint; i++, pConstraint++){
3522 if( pConstraint->usable==0 )
continue;
3524 switch( pConstraint->iColumn ){
3539 if( wholelineIdx>=0 ){
3543 pIdxInfo->
idxNum = idxNum;
3584 #ifndef SQLITE_OMIT_VIRTUALTABLE
3601 #ifndef SQLITE_OMIT_VIRTUALTABLE
3671 #define APND_MARK_PREFIX "Start-Of-SQLite3-"
3672 #define APND_MARK_PREFIX_SZ 17
3673 #define APND_MARK_SIZE 25
3679 #define APND_MAX_SIZE (65536*15259)
3690 #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
3691 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
4000 static const char aSqliteHdr[] =
"SQLite format 3";
4001 if( sz<512 )
return 0;
4004 return memcmp(zHdr, aSqliteHdr,
sizeof(zHdr))==0;
4045 return pSubVfs->
xOpen(pSubVfs,
zName, pFile, flags, pOutFlags);
4048 memset(p, 0,
sizeof(*p));
4051 rc = pSubVfs->
xOpen(pSubVfs,
zName, pSubFile, flags, pOutFlags);
4052 if( rc )
goto apnd_open_done;
4056 goto apnd_open_done;
4059 memmove(pFile, pSubFile, pSubVfs->
szOsFile);
4089 return ORIGVFS(pVfs)->xAccess(
ORIGVFS(pVfs), zPath, flags, pResOut);
4097 return ORIGVFS(pVfs)->xFullPathname(
ORIGVFS(pVfs),zPath,nOut,zOut);
4112 return ORIGVFS(pVfs)->xRandomness(
ORIGVFS(pVfs), nByte, zBufOut);
4166 #ifdef APPENDVFS_TEST
4211 fprintf(
memtraceOut,
"MEMTRACE: allocate %d bytes\n",
4230 fprintf(
memtraceOut,
"MEMTRACE: resize %d -> %d bytes\n",
4329 int nKey1,
const void *pKey1,
4330 int nKey2,
const void *pKey2
4332 const unsigned char *zA = (
const unsigned char*)pKey1;
4333 const unsigned char *zB = (
const unsigned char*)pKey2;
4336 while( i<nKey1 && j<nKey2 ){
4338 if( isdigit(zA[i]) ){
4340 if( !isdigit(zB[j]) )
return x;
4341 while( i<nKey1 && zA[i]==
'0' ){ i++; }
4342 while( j<nKey2 && zB[j]==
'0' ){ j++; }
4344 while( i+k<nKey1 && isdigit(zA[i+k])
4345 && j+k<nKey2 && isdigit(zB[j+k]) ){
4348 if( i+k<nKey1 && isdigit(zA[i+k]) ){
4350 }
else if( j+k<nKey2 && isdigit(zB[j+k]) ){
4353 x = memcmp(zA+i, zB+j, k);
4365 return (nKey1 - i) - (nKey2 - j);
4382 #ifdef SQLITE_HAVE_ZLIB
4418 #ifndef SQLITE_OMIT_VIRTUALTABLE
4420 #ifndef SQLITE_AMALGAMATION
4424 typedef unsigned short u16;
4425 typedef unsigned long u32;
4426 #define MIN(a,b) ((a)<(b) ? (a) : (b))
4428 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
4429 # define ALWAYS(X) (1)
4430 # define NEVER(X) (0)
4431 #elif !defined(NDEBUG)
4432 # define ALWAYS(X) ((X)?1:(assert(0),0))
4433 # define NEVER(X) ((X)?(assert(0),1):0)
4435 # define ALWAYS(X) (X)
4436 # define NEVER(X) (X)
4451 # define S_IFDIR 0040000
4454 # define S_IFREG 0100000
4457 # define S_IFLNK 0120000
4460 static const char ZIPFILE_SCHEMA[] =
4472 #define ZIPFILE_F_COLUMN_IDX 7
4473 #define ZIPFILE_BUFFER_SIZE (64*1024)
4502 #define ZIPFILE_EXTRA_TIMESTAMP 0x5455
4503 #define ZIPFILE_NEWENTRY_MADEBY ((3<<8) + 30)
4504 #define ZIPFILE_NEWENTRY_REQUIRED 20
4505 #define ZIPFILE_NEWENTRY_FLAGS 0x800
4506 #define ZIPFILE_SIGNATURE_CDS 0x02014b50
4507 #define ZIPFILE_SIGNATURE_LFH 0x04034b50
4508 #define ZIPFILE_SIGNATURE_EOCD 0x06054b50
4514 #define ZIPFILE_LFH_FIXED_SZ 30
4515 #define ZIPFILE_EOCD_FIXED_SZ 22
4516 #define ZIPFILE_CDS_FIXED_SZ 46
4536 typedef struct ZipfileEOCD ZipfileEOCD;
4537 struct ZipfileEOCD {
4569 typedef struct ZipfileCDS ZipfileCDS;
4572 u16 iVersionExtract;
4606 typedef struct ZipfileLFH ZipfileLFH;
4608 u16 iVersionExtract;
4620 typedef struct ZipfileEntry ZipfileEntry;
4621 struct ZipfileEntry {
4627 ZipfileEntry *pNext;
4633 typedef struct ZipfileCsr ZipfileCsr;
4645 ZipfileEntry *pFreeEntry;
4646 ZipfileEntry *pCurrent;
4647 ZipfileCsr *pCsrNext;
4650 typedef struct ZipfileTab ZipfileTab;
4657 ZipfileCsr *pCsrList;
4661 ZipfileEntry *pFirstEntry;
4662 ZipfileEntry *pLastEntry;
4672 static void zipfileCtxErrorMsg(
sqlite3_context *ctx,
const char *zFmt, ...){
4686 static void zipfileDequote(
char *zIn){
4688 if( q==
'"' || q==
'\'' || q==
'`' || q==
'[' ){
4691 if( q==
'[' ) q =
']';
4692 while(
ALWAYS(zIn[iIn]) ){
4693 char c = zIn[iIn++];
4694 if( c==q && zIn[iIn++]!=q )
break;
4709 static int zipfileConnect(
4712 int argc,
const char *
const*argv,
4716 int nByte =
sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
4718 const char *zFile = 0;
4719 ZipfileTab *pNew = 0;
4733 *pzErr =
sqlite3_mprintf(
"zipfile constructor requires one argument");
4739 nFile = (int)strlen(zFile)+1;
4746 memset(pNew, 0, nByte+nFile);
4748 pNew->aBuffer = (
u8*)&pNew[1];
4750 pNew->zFile = (
char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
4751 memcpy(pNew->zFile, zFile, nFile);
4752 zipfileDequote(pNew->zFile);
4763 static void zipfileEntryFree(ZipfileEntry *p){
4774 static void zipfileCleanupTransaction(ZipfileTab *pTab){
4775 ZipfileEntry *pEntry;
4776 ZipfileEntry *pNext;
4778 if( pTab->pWriteFd ){
4779 fclose(pTab->pWriteFd);
4782 for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
4783 pNext = pEntry->pNext;
4784 zipfileEntryFree(pEntry);
4786 pTab->pFirstEntry = 0;
4787 pTab->pLastEntry = 0;
4788 pTab->szCurrent = 0;
4796 zipfileCleanupTransaction((ZipfileTab*)pVtab);
4805 ZipfileTab *pTab = (ZipfileTab*)p;
4812 memset(pCsr, 0,
sizeof(*pCsr));
4813 pCsr->iId = ++pTab->iNextCsrid;
4814 pCsr->pCsrNext = pTab->pCsrList;
4815 pTab->pCsrList = pCsr;
4823 static void zipfileResetCursor(ZipfileCsr *pCsr){
4825 ZipfileEntry *pNext;
4829 fclose(pCsr->pFile);
4831 zipfileEntryFree(pCsr->pCurrent);
4835 for(p=pCsr->pFreeEntry; p; p=pNext){
4837 zipfileEntryFree(p);
4845 ZipfileCsr *pCsr = (ZipfileCsr*)cur;
4846 ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
4848 zipfileResetCursor(pCsr);
4851 for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
4852 *pp = pCsr->pCsrNext;
4862 static void zipfileTableErr(ZipfileTab *pTab,
const char *zFmt, ...){
4869 static void zipfileCursorErr(ZipfileCsr *pCsr,
const char *zFmt, ...){
4887 static int zipfileReadData(
4895 fseek(pFile, (
long)iOff,
SEEK_SET);
4896 n = fread(aRead, 1, nRead, pFile);
4897 if( (
int)n!=nRead ){
4904 static int zipfileAppendData(
4910 fseek(pTab->pWriteFd, (
long)pTab->szCurrent,
SEEK_SET);
4911 n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
4912 if( (
int)n!=nWrite ){
4916 pTab->szCurrent += nWrite;
4923 static u16 zipfileGetU16(
const u8 *aBuf){
4924 return (aBuf[1] << 8) + aBuf[0];
4930 static u32 zipfileGetU32(
const u8 *aBuf){
4931 return ((
u32)(aBuf[3]) << 24)
4932 + ((
u32)(aBuf[2]) << 16)
4933 + ((
u32)(aBuf[1]) << 8)
4934 + ((
u32)(aBuf[0]) << 0);
4940 static void zipfilePutU16(
u8 *aBuf,
u16 val){
4941 aBuf[0] = val & 0xFF;
4942 aBuf[1] = (val>>8) & 0xFF;
4948 static void zipfilePutU32(
u8 *aBuf,
u32 val){
4949 aBuf[0] = val & 0xFF;
4950 aBuf[1] = (val>>8) & 0xFF;
4951 aBuf[2] = (val>>16) & 0xFF;
4952 aBuf[3] = (val>>24) & 0xFF;
4955 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
4956 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
4958 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
4959 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
4964 #define ZIPFILE_CDS_NFILE_OFF 28
4965 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
4971 static int zipfileReadCDS(
u8 *aBuf, ZipfileCDS *pCDS){
4973 u32 sig = zipfileRead32(aRead);
4975 if( sig!=ZIPFILE_SIGNATURE_CDS ){
4978 pCDS->iVersionMadeBy = zipfileRead16(aRead);
4979 pCDS->iVersionExtract = zipfileRead16(aRead);
4980 pCDS->flags = zipfileRead16(aRead);
4981 pCDS->iCompression = zipfileRead16(aRead);
4982 pCDS->mTime = zipfileRead16(aRead);
4983 pCDS->mDate = zipfileRead16(aRead);
4984 pCDS->crc32 = zipfileRead32(aRead);
4985 pCDS->szCompressed = zipfileRead32(aRead);
4986 pCDS->szUncompressed = zipfileRead32(aRead);
4987 assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
4988 pCDS->nFile = zipfileRead16(aRead);
4989 pCDS->nExtra = zipfileRead16(aRead);
4990 pCDS->nComment = zipfileRead16(aRead);
4991 pCDS->iDiskStart = zipfileRead16(aRead);
4992 pCDS->iInternalAttr = zipfileRead16(aRead);
4993 pCDS->iExternalAttr = zipfileRead32(aRead);
4994 pCDS->iOffset = zipfileRead32(aRead);
4995 assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
5005 static int zipfileReadLFH(
5009 u8 *aRead = aBuffer;
5012 u32 sig = zipfileRead32(aRead);
5013 if( sig!=ZIPFILE_SIGNATURE_LFH ){
5016 pLFH->iVersionExtract = zipfileRead16(aRead);
5017 pLFH->flags = zipfileRead16(aRead);
5018 pLFH->iCompression = zipfileRead16(aRead);
5019 pLFH->mTime = zipfileRead16(aRead);
5020 pLFH->mDate = zipfileRead16(aRead);
5021 pLFH->crc32 = zipfileRead32(aRead);
5022 pLFH->szCompressed = zipfileRead32(aRead);
5023 pLFH->szUncompressed = zipfileRead32(aRead);
5024 pLFH->nFile = zipfileRead16(aRead);
5025 pLFH->nExtra = zipfileRead16(aRead);
5046 static int zipfileScanExtra(
u8 *aExtra,
int nExtra,
u32 *pmTime){
5049 u8 *pEnd = &aExtra[nExtra];
5052 u16 id = zipfileRead16(p);
5053 u16 nByte = zipfileRead16(p);
5056 case ZIPFILE_EXTRA_TIMESTAMP: {
5059 *pmTime = zipfileGetU32(&p[1]);
5089 static u32 zipfileMtime(ZipfileCDS *pCDS){
5090 int Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
5091 int M = ((pCDS->mDate >> 5) & 0x0F);
5092 int D = (pCDS->mDate & 0x1F);
5095 int sec = (pCDS->mTime & 0x1F)*2;
5096 int min = (pCDS->mTime >> 5) & 0x3F;
5097 int hr = (pCDS->mTime >> 11) & 0x1F;
5107 JD = (
i64)(24*60*60) * (
5108 (int)(365.25 * (Y + 4716))
5109 + (
int)(30.6001 * (M + 1))
5114 JD += (hr-12) * 3600 +
min * 60 + sec;
5117 return (
u32)(JD - (
i64)(24405875) * 24*60*6);
5125 static void zipfileMtimeToDos(ZipfileCDS *pCds,
u32 mUnixTime){
5127 i64 JD = (
i64)2440588 + mUnixTime / (24*60*60);
5133 A = (int)((JD - 1867216.25)/36524.25);
5134 A = (int)(JD + 1 + A - (A/4));
5136 C = (int)((B - 122.1)/365.25);
5137 D = (36525*(C&32767))/100;
5138 E = (int)((B-D)/30.6001);
5140 day = B - D - (int)(30.6001*E);
5141 mon = (E<14 ? E-1 : E-13);
5142 yr = mon>2 ? C-4716 : C-4715;
5144 hr = (mUnixTime % (24*60*60)) / (60*60);
5145 min = (mUnixTime % (60*60)) / 60;
5146 sec = (mUnixTime % 60);
5149 pCds->mDate = (
u16)(day + (mon << 5) + ((yr-1980) << 9));
5150 pCds->mTime = (
u16)(sec/2 + (
min<<5) + (hr<<11));
5152 pCds->mDate = pCds->mTime = 0;
5155 assert( mUnixTime<315507600
5156 || mUnixTime==zipfileMtime(pCds)
5157 || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
5173 static int zipfileGetEntry(
5179 ZipfileEntry **ppEntry
5182 char **pzErr = &pTab->base.zErrMsg;
5186 aRead = pTab->aBuffer;
5187 rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
5189 aRead = (
u8*)&aBlob[iOff];
5196 int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
5197 int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
5198 nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
5200 nAlloc =
sizeof(ZipfileEntry) + nExtra;
5202 nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
5209 memset(pNew, 0,
sizeof(ZipfileEntry));
5210 rc = zipfileReadCDS(aRead, &pNew->cds);
5213 }
else if( aBlob==0 ){
5214 rc = zipfileReadData(
5215 pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
5218 aRead = (
u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
5223 u32 *pt = &pNew->mUnixTime;
5225 pNew->aExtra = (
u8*)&pNew[1];
5226 memcpy(pNew->aExtra, &aRead[nFile], nExtra);
5227 if( pNew->cds.zFile==0 ){
5229 }
else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
5230 pNew->mUnixTime = zipfileMtime(&pNew->cds);
5235 static const int szFix = ZIPFILE_LFH_FIXED_SZ;
5238 rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
5240 aRead = (
u8*)&aBlob[pNew->cds.iOffset];
5243 rc = zipfileReadLFH(aRead, &lfh);
5245 pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
5246 pNew->iDataOff += lfh.nFile + lfh.nExtra;
5247 if( aBlob && pNew->cds.szCompressed ){
5248 pNew->aData = &pNew->aExtra[nExtra];
5249 memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
5253 (
int)pNew->cds.iOffset
5259 zipfileEntryFree(pNew);
5272 ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5276 i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
5277 zipfileEntryFree(pCsr->pCurrent);
5279 if( pCsr->iNextOff>=iEof ){
5282 ZipfileEntry *p = 0;
5283 ZipfileTab *pTab = (ZipfileTab*)(cur->
pVtab);
5284 rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
5286 pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
5287 pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
5293 pCsr->pCurrent = pCsr->pCurrent->pNext;
5295 if( pCsr->pCurrent==0 ){
5304 static void zipfileFree(
void *p) {
5315 static void zipfileInflate(
5327 memset(&str, 0,
sizeof(str));
5329 str.next_in = (Byte*)aIn;
5331 str.next_out = (Byte*)aRes;
5332 str.avail_out = nOut;
5334 err = inflateInit2(&str, -15);
5336 zipfileCtxErrorMsg(pCtx,
"inflateInit2() failed (%d)", err);
5338 err = inflate(&str, Z_NO_FLUSH);
5339 if( err!=Z_STREAM_END ){
5340 zipfileCtxErrorMsg(pCtx,
"inflate() failed (%d)", err);
5363 static int zipfileDeflate(
5364 const u8 *aIn,
int nIn,
5365 u8 **ppOut,
int *pnOut,
5373 memset(&str, 0,
sizeof(str));
5374 str.next_in = (Bytef*)aIn;
5376 deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
5378 nAlloc = deflateBound(&str, nIn);
5384 str.next_out = aOut;
5385 str.avail_out = nAlloc;
5386 res = deflate(&str, Z_FINISH);
5387 if( res==Z_STREAM_END ){
5389 *pnOut = (int)str.total_out;
5406 static int zipfileColumn(
5411 ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5412 ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
5436 if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
5437 int sz = pCDS->szCompressed;
5438 int szFinal = pCDS->szUncompressed;
5442 if( pCsr->pCurrent->aData ){
5443 aBuf = pCsr->pCurrent->aData;
5449 FILE *pFile = pCsr->pFile;
5451 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
5453 rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
5454 &pCsr->base.pVtab->zErrMsg
5459 if( i==5 && pCDS->iCompression ){
5460 zipfileInflate(ctx, aBuf, sz, szFinal);
5470 u32 mode = pCDS->iExternalAttr >> 16;
5471 if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!=
'/' ){
5494 ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5508 static int zipfileReadEOCD(
5515 u8 *aRead = pTab->aBuffer;
5523 szFile = (
i64)ftell(pFile);
5525 memset(pEOCD, 0,
sizeof(ZipfileEOCD));
5528 nRead = (int)(
MIN(szFile, ZIPFILE_BUFFER_SIZE));
5529 iOff = szFile - nRead;
5530 rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
5532 nRead = (int)(
MIN(nBlob, ZIPFILE_BUFFER_SIZE));
5533 aRead = (
u8*)&aBlob[nBlob-nRead];
5540 for(i=nRead-20; i>=0; i--){
5541 if( aRead[i]==0x50 && aRead[i+1]==0x4b
5542 && aRead[i+2]==0x05 && aRead[i+3]==0x06
5549 "cannot find end of central directory record"
5555 pEOCD->iDisk = zipfileRead16(aRead);
5556 pEOCD->iFirstDisk = zipfileRead16(aRead);
5557 pEOCD->nEntry = zipfileRead16(aRead);
5558 pEOCD->nEntryTotal = zipfileRead16(aRead);
5559 pEOCD->nSize = zipfileRead32(aRead);
5560 pEOCD->iOffset = zipfileRead32(aRead);
5572 static void zipfileAddEntry(
5574 ZipfileEntry *pBefore,
5577 assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
5578 assert( pNew->pNext==0 );
5580 if( pTab->pFirstEntry==0 ){
5581 pTab->pFirstEntry = pTab->pLastEntry = pNew;
5583 assert( pTab->pLastEntry->pNext==0 );
5584 pTab->pLastEntry->pNext = pNew;
5585 pTab->pLastEntry = pNew;
5589 for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
5590 pNew->pNext = pBefore;
5595 static int zipfileLoadDirectory(ZipfileTab *pTab,
const u8 *aBlob,
int nBlob){
5601 rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
5602 iOff = eocd.iOffset;
5603 for(i=0; rc==
SQLITE_OK && i<eocd.nEntry; i++){
5604 ZipfileEntry *pNew = 0;
5605 rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
5608 zipfileAddEntry(pTab, 0, pNew);
5609 iOff += ZIPFILE_CDS_FIXED_SZ;
5610 iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
5619 static int zipfileFilter(
5621 int idxNum,
const char *idxStr,
5624 ZipfileTab *pTab = (ZipfileTab*)cur->
pVtab;
5625 ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5626 const char *zFile = 0;
5630 zipfileResetCursor(pCsr);
5633 zFile = pTab->zFile;
5634 }
else if( idxNum==0 ){
5635 zipfileCursorErr(pCsr,
"zipfile() function requires an argument");
5640 assert( pTab->pFirstEntry==0 );
5641 rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
5642 pCsr->pFreeEntry = pTab->pFirstEntry;
5643 pTab->pFirstEntry = pTab->pLastEntry = 0;
5650 if( 0==pTab->pWriteFd && 0==bInMemory ){
5651 pCsr->pFile = fopen(zFile,
"rb");
5652 if( pCsr->pFile==0 ){
5653 zipfileCursorErr(pCsr,
"cannot open file: %s", zFile);
5656 rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
5658 if( pCsr->eocd.nEntry==0 ){
5661 pCsr->iNextOff = pCsr->eocd.iOffset;
5662 rc = zipfileNext(cur);
5668 pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
5669 rc = zipfileNext(cur);
5678 static int zipfileBestIndex(
5687 const struct sqlite3_index_constraint *pCons = &pIdxInfo->
aConstraint[i];
5688 if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX )
continue;
5689 if( pCons->usable==0 ){
5700 }
else if( unusable ){
5706 static ZipfileEntry *zipfileNewEntry(
const char *zPath){
5710 memset(pNew, 0,
sizeof(ZipfileEntry));
5712 if( pNew->cds.zFile==0 ){
5720 static int zipfileSerializeLFH(ZipfileEntry *pEntry,
u8 *aBuf){
5721 ZipfileCDS *pCds = &pEntry->cds;
5727 zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
5728 zipfileWrite16(a, pCds->iVersionExtract);
5729 zipfileWrite16(a, pCds->flags);
5730 zipfileWrite16(a, pCds->iCompression);
5731 zipfileWrite16(a, pCds->mTime);
5732 zipfileWrite16(a, pCds->mDate);
5733 zipfileWrite32(a, pCds->crc32);
5734 zipfileWrite32(a, pCds->szCompressed);
5735 zipfileWrite32(a, pCds->szUncompressed);
5736 zipfileWrite16(a, (
u16)pCds->nFile);
5737 zipfileWrite16(a, pCds->nExtra);
5738 assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
5741 memcpy(a, pCds->zFile, (
int)pCds->nFile);
5742 a += (int)pCds->nFile;
5745 zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
5746 zipfileWrite16(a, 5);
5748 zipfileWrite32(a, pEntry->mUnixTime);
5753 static int zipfileAppendEntry(
5755 ZipfileEntry *pEntry,
5759 u8 *aBuf = pTab->aBuffer;
5763 nBuf = zipfileSerializeLFH(pEntry, aBuf);
5764 rc = zipfileAppendData(pTab, aBuf, nBuf);
5766 pEntry->iDataOff = pTab->szCurrent;
5767 rc = zipfileAppendData(pTab, pData, nData);
5773 static int zipfileGetMode(
5782 mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
5783 }
else if( z[0]>=
'0' && z[0]<=
'9' ){
5786 const char zTemplate[11] =
"-rwxrwxrwx";
5788 if( strlen(z)!=10 )
goto parse_error;
5790 case '-': mode |= S_IFREG;
break;
5791 case 'd': mode |= S_IFDIR;
break;
5792 case 'l': mode |= S_IFLNK;
break;
5793 default:
goto parse_error;
5795 for(i=1; i<10; i++){
5796 if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
5797 else if( z[i]!=
'-' )
goto parse_error;
5800 if( ((mode & S_IFDIR)==0)==bIsDir ){
5818 static int zipfileComparePath(
const char *zA,
const char *zB,
int nB){
5819 int nA = (int)strlen(zA);
5820 if( nA>0 && zA[nA-1]==
'/' ) nA--;
5821 if( nB>0 && zB[nB-1]==
'/' ) nB--;
5822 if( nA==nB && memcmp(zA, zB, nA)==0 )
return 0;
5827 ZipfileTab *pTab = (ZipfileTab*)pVtab;
5830 assert( pTab->pWriteFd==0 );
5831 if( pTab->zFile==0 || pTab->zFile[0]==0 ){
5840 pTab->pWriteFd = fopen(pTab->zFile,
"ab+");
5841 if( pTab->pWriteFd==0 ){
5843 "zipfile: failed to open file %s for writing", pTab->zFile
5847 fseek(pTab->pWriteFd, 0,
SEEK_END);
5848 pTab->szCurrent = pTab->szOrig = (
i64)ftell(pTab->pWriteFd);
5849 rc = zipfileLoadDirectory(pTab, 0, 0);
5853 zipfileCleanupTransaction(pTab);
5863 static u32 zipfileTime(
void){
5869 ret = (
u32)((ms/1000) - ((
i64)24405875 * 8640));
5873 ret = (
u32)((day - 2440587.5) * 86400);
5887 return zipfileTime();
5896 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
5899 for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));
5901 zipfileEntryFree(pOld);
5908 static int zipfileUpdate(
5914 ZipfileTab *pTab = (ZipfileTab*)pVtab;
5916 ZipfileEntry *pNew = 0;
5921 const char *zPath = 0;
5923 const u8 *pData = 0;
5928 ZipfileEntry *pOld = 0;
5929 ZipfileEntry *pOld2 = 0;
5934 if( pTab->pWriteFd==0 ){
5935 rc = zipfileBegin(pVtab);
5942 int nDelete = (int)strlen(zDelete);
5945 if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
5949 for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
5950 if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
5953 assert( pOld->pNext );
5960 zipfileTableErr(pTab,
"sz must be NULL");
5964 zipfileTableErr(pTab,
"rawdata must be NULL");
5983 if( iMethod!=0 && iMethod!=8 ){
5984 zipfileTableErr(pTab,
"unknown compression method: %d", iMethod);
5987 if( bAuto || iMethod ){
5989 rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
5991 if( iMethod || nCmp<nIn ){
5998 iCrc32 = crc32(0, aIn, nIn);
6004 rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
6009 if( zPath==0 ) zPath =
"";
6010 nPath = (int)strlen(zPath);
6011 mTime = zipfileGetTime(apVal[4]);
6019 if( nPath<=0 || zPath[nPath-1]!=
'/' ){
6021 zPath = (
const char*)zFree;
6026 nPath = (int)strlen(zPath);
6033 if( (pOld==0 || bUpdate) && rc==
SQLITE_OK ){
6035 for(p=pTab->pFirstEntry; p; p=p->pNext){
6036 if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
6039 goto zipfile_update_done;
6046 zipfileTableErr(pTab,
"duplicate name: \"%s\"", zPath);
6058 pNew = zipfileNewEntry(zPath);
6062 pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
6063 pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
6064 pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
6065 pNew->cds.iCompression = (
u16)iMethod;
6066 zipfileMtimeToDos(&pNew->cds, mTime);
6067 pNew->cds.crc32 = iCrc32;
6068 pNew->cds.szCompressed = nData;
6069 pNew->cds.szUncompressed = (
u32)sz;
6070 pNew->cds.iExternalAttr = (mode<<16);
6071 pNew->cds.iOffset = (
u32)pTab->szCurrent;
6072 pNew->cds.nFile = (
u16)nPath;
6073 pNew->mUnixTime = (
u32)mTime;
6074 rc = zipfileAppendEntry(pTab, pNew, pData, nData);
6075 zipfileAddEntry(pTab, pOld, pNew);
6082 for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
6083 if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
6084 pCsr->pCurrent = pCsr->pCurrent->pNext;
6089 zipfileRemoveEntryFromList(pTab, pOld);
6090 zipfileRemoveEntryFromList(pTab, pOld2);
6093 zipfile_update_done:
6099 static int zipfileSerializeEOCD(ZipfileEOCD *p,
u8 *aBuf){
6101 zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
6102 zipfileWrite16(a, p->iDisk);
6103 zipfileWrite16(a, p->iFirstDisk);
6104 zipfileWrite16(a, p->nEntry);
6105 zipfileWrite16(a, p->nEntryTotal);
6106 zipfileWrite32(a, p->nSize);
6107 zipfileWrite32(a, p->iOffset);
6108 zipfileWrite16(a, 0);
6113 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
6114 int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
6115 assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
6116 return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
6123 static int zipfileSerializeCDS(ZipfileEntry *pEntry,
u8 *aBuf){
6125 ZipfileCDS *pCDS = &pEntry->cds;
6127 if( pEntry->aExtra==0 ){
6131 zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
6132 zipfileWrite16(a, pCDS->iVersionMadeBy);
6133 zipfileWrite16(a, pCDS->iVersionExtract);
6134 zipfileWrite16(a, pCDS->flags);
6135 zipfileWrite16(a, pCDS->iCompression);
6136 zipfileWrite16(a, pCDS->mTime);
6137 zipfileWrite16(a, pCDS->mDate);
6138 zipfileWrite32(a, pCDS->crc32);
6139 zipfileWrite32(a, pCDS->szCompressed);
6140 zipfileWrite32(a, pCDS->szUncompressed);
6141 assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
6142 zipfileWrite16(a, pCDS->nFile);
6143 zipfileWrite16(a, pCDS->nExtra);
6144 zipfileWrite16(a, pCDS->nComment);
6145 zipfileWrite16(a, pCDS->iDiskStart);
6146 zipfileWrite16(a, pCDS->iInternalAttr);
6147 zipfileWrite32(a, pCDS->iExternalAttr);
6148 zipfileWrite32(a, pCDS->iOffset);
6150 memcpy(a, pCDS->zFile, pCDS->nFile);
6153 if( pEntry->aExtra ){
6154 int n = (int)pCDS->nExtra + (
int)pCDS->nComment;
6155 memcpy(a, pEntry->aExtra, n);
6158 assert( pCDS->nExtra==9 );
6159 zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
6160 zipfileWrite16(a, 5);
6162 zipfileWrite32(a, pEntry->mUnixTime);
6169 ZipfileTab *pTab = (ZipfileTab*)pVtab;
6171 if( pTab->pWriteFd ){
6172 i64 iOffset = pTab->szCurrent;
6178 for(p=pTab->pFirstEntry; rc==
SQLITE_OK && p; p=p->pNext){
6179 int n = zipfileSerializeCDS(p, pTab->aBuffer);
6180 rc = zipfileAppendData(pTab, pTab->aBuffer, n);
6186 eocd.iFirstDisk = 0;
6187 eocd.nEntry = (
u16)nEntry;
6188 eocd.nEntryTotal = (
u16)nEntry;
6189 eocd.nSize = (
u32)(pTab->szCurrent - iOffset);
6190 eocd.iOffset = (
u32)iOffset;
6191 rc = zipfileAppendEOCD(pTab, &eocd);
6193 zipfileCleanupTransaction(pTab);
6199 return zipfileCommit(pVtab);
6202 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab,
i64 iId){
6204 for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
6205 if( iId==pCsr->iId )
break;
6210 static void zipfileFunctionCds(
6221 ZipfileCDS *p = &pCsr->pCurrent->cds;
6223 "\"version-made-by\" : %u, "
6224 "\"version-to-extract\" : %u, "
6226 "\"compression\" : %u, "
6230 "\"compressed-size\" : %u, "
6231 "\"uncompressed-size\" : %u, "
6232 "\"file-name-length\" : %u, "
6233 "\"extra-field-length\" : %u, "
6234 "\"file-comment-length\" : %u, "
6235 "\"disk-number-start\" : %u, "
6236 "\"internal-attr\" : %u, "
6237 "\"external-attr\" : %u, "
6238 "\"offset\" : %u }",
6239 (
u32)p->iVersionMadeBy, (
u32)p->iVersionExtract,
6240 (
u32)p->flags, (
u32)p->iCompression,
6241 (
u32)p->mTime, (
u32)p->mDate,
6242 (
u32)p->crc32, (
u32)p->szCompressed,
6243 (
u32)p->szUncompressed, (
u32)p->nFile,
6244 (
u32)p->nExtra, (
u32)p->nComment,
6245 (
u32)p->iDiskStart, (
u32)p->iInternalAttr,
6246 (
u32)p->iExternalAttr, (
u32)p->iOffset
6261 static int zipfileFindFunction(
6269 *pxFunc = zipfileFunctionCds;
6270 *ppArg = (
void*)pVtab;
6276 typedef struct ZipfileBuffer ZipfileBuffer;
6277 struct ZipfileBuffer {
6283 typedef struct ZipfileCtx ZipfileCtx;
6290 static int zipfileBufferGrow(ZipfileBuffer *pBuf,
int nByte){
6291 if( pBuf->n+nByte>pBuf->nAlloc ){
6294 int nReq = pBuf->n + nByte;
6296 while( nNew<nReq ) nNew = nNew*2;
6300 pBuf->nAlloc = (int)nNew;
6330 const u8 *aData = 0;
6332 int szUncompressed = 0;
6341 memset(&e, 0,
sizeof(e));
6346 if( nVal!=2 && nVal!=4 && nVal!=5 ){
6347 zErr =
sqlite3_mprintf(
"wrong number of arguments to function zipfile()");
6349 goto zipfile_step_out;
6367 zErr =
sqlite3_mprintf(
"first argument to zipfile() must be non-NULL");
6369 goto zipfile_step_out;
6376 if( iMethod!=0 && iMethod!=8 ){
6379 goto zipfile_step_out;
6392 iCrc32 = crc32(0, aData, nData);
6393 if( iMethod<0 || iMethod==8 ){
6395 rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
6397 goto zipfile_step_out;
6399 if( iMethod==8 || nOut<nData ){
6410 rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
6411 if( rc )
goto zipfile_step_out;
6414 e.mUnixTime = zipfileGetTime(pMtime);
6423 goto zipfile_step_out;
6430 goto zipfile_step_out;
6439 e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
6440 e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
6441 e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
6442 e.cds.iCompression = (
u16)iMethod;
6443 zipfileMtimeToDos(&e.cds, (
u32)e.mUnixTime);
6444 e.cds.crc32 = iCrc32;
6445 e.cds.szCompressed = nData;
6446 e.cds.szUncompressed = szUncompressed;
6447 e.cds.iExternalAttr = (mode<<16);
6448 e.cds.iOffset = p->body.n;
6450 e.cds.zFile =
zName;
6453 nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
6454 if( (rc = zipfileBufferGrow(&p->body, nByte)) )
goto zipfile_step_out;
6455 p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
6459 if( (rc = zipfileBufferGrow(&p->body, nData)) )
goto zipfile_step_out;
6460 memcpy(&p->body.a[p->body.n], aData, nData);
6465 nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
6466 if( (rc = zipfileBufferGrow(&p->cds, nByte)) )
goto zipfile_step_out;
6467 p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
6497 memset(&eocd, 0,
sizeof(eocd));
6498 eocd.nEntry = (
u16)p->nEntry;
6499 eocd.nEntryTotal = (
u16)p->nEntry;
6500 eocd.nSize = p->cds.n;
6501 eocd.iOffset = p->body.n;
6503 nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
6508 memcpy(aZip, p->body.a, p->body.n);
6509 memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
6510 zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
6523 static int zipfileRegister(
sqlite3 *db){
6543 zipfileFindFunction,
6551 zipfileStep, zipfileFinal
6557 # define zipfileRegister(x) SQLITE_OK
6563 int sqlite3_zipfile_init(
6570 return zipfileRegister(db);
6611 static void sqlarCompressFunc(
6620 uLongf nOut = compressBound(nData);
6628 if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
6630 }
else if( nOut<nData ){
6652 static void sqlarUncompressFunc(
6668 if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
6681 int sqlite3_sqlar_init(
6691 sqlarCompressFunc, 0, 0);
6695 sqlarUncompressFunc, 0, 0);
6715 #if !defined(SQLITEEXPERT_H)
6716 #define SQLITEEXPERT_H 1
6762 #define EXPERT_CONFIG_SAMPLE 1
6858 #define EXPERT_REPORT_SQL 1
6859 #define EXPERT_REPORT_INDEXES 2
6860 #define EXPERT_REPORT_PLAN 3
6861 #define EXPERT_REPORT_CANDIDATES 4
6891 #ifndef SQLITE_OMIT_VIRTUALTABLE
6903 #define STRLEN (int)strlen
6910 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
6992 #define IDX_HASH_SIZE 1023
7037 memset(pRet, 0, nByte);
7048 memset(pHash, 0,
sizeof(
IdxHash));
7059 for(pEntry=pHash->
aHash[i]; pEntry; pEntry=pNext){
7065 memset(pHash, 0,
sizeof(
IdxHash));
7073 unsigned int ret = 0;
7076 ret += (ret<<3) + (
unsigned char)(z[i]);
7094 int nVal = (zVal ?
STRLEN(zVal) : 0);
7097 for(pEntry=pHash->
aHash[iHash]; pEntry; pEntry=pEntry->
pHashNext){
7098 if(
STRLEN(pEntry->
zKey)==nKey && 0==memcmp(pEntry->
zKey, zKey, nKey) ){
7104 pEntry->
zKey = (
char*)&pEntry[1];
7105 memcpy(pEntry->
zKey, zKey, nKey);
7107 pEntry->
zVal = &pEntry->
zKey[nKey+1];
7108 memcpy(pEntry->
zVal, zVal, nVal);
7111 pHash->
aHash[iHash] = pEntry;
7126 if( nKey<0 ) nKey =
STRLEN(zKey);
7129 for(pEntry=pHash->
aHash[iHash]; pEntry; pEntry=pEntry->
pHashNext){
7130 if(
STRLEN(pEntry->
zKey)==nKey && 0==memcmp(pEntry->
zKey, zKey, nKey) ){
7145 if( pEntry )
return pEntry->
zVal;
7155 int nColl =
STRLEN(zColl);
7160 pNew->
zColl = (
char*)&pNew[1];
7161 memcpy(pNew->
zColl, zColl, nColl+1);
7240 assert( zIn[0]==
'\'' );
7241 assert( zIn[n-1]==
'\'' );
7246 for(iIn=1; iIn<(n-1); iIn++){
7247 if( zIn[iIn]==
'\'' ){
7248 assert( zIn[iIn+1]==
'\'' );
7251 zRet[iOut++] = zIn[iIn];
7271 int argc,
const char *
const*argv,
7331 struct sqlite3_index_constraint *pCons = &pIdxInfo->
aConstraint[i];
7333 && pCons->iColumn>=0
7335 && (pCons->op & opmask)
7341 pNew->
iCol = pCons->iColumn;
7357 for(i=pIdxInfo->
nOrderBy-1; i>=0; i--){
7420 return pCsr->
pData==0;
7430 assert( pCsr->
pData );
7469 int idxNum,
const char *idxStr,
7485 "SELECT * FROM main.%Q WHERE sample()", pVtab->
pTab->
zName
7557 int nByte =
sizeof(
IdxTable) + nTab + 1;
7565 nByte += 1 +
STRLEN(zCol);
7567 db,
"main", zTab, zCol, 0, &zCol, 0, 0, 0
7569 nByte += 1 +
STRLEN(zCol);
7582 pCsr = (
char*)&pNew->
aCol[nCol];
7588 int nCopy =
STRLEN(zCol) + 1;
7591 memcpy(pCsr, zCol, nCopy);
7595 db,
"main", zTab, zCol, 0, &zCol, 0, 0, 0
7598 nCopy =
STRLEN(zCol) + 1;
7600 memcpy(pCsr, zCol, nCopy);
7613 memcpy(pNew->
zName, zTab, nTab+1);
7633 int nIn = zIn ?
STRLEN(zIn) : 0;
7639 nAppend =
STRLEN(zAppend);
7642 if( zAppend && zRet ){
7643 if( nIn ) memcpy(zRet, zIn, nIn);
7644 memcpy(&zRet[nIn], zAppend, nAppend+1);
7663 for(i=0; zId[i]; i++){
7665 && !(zId[i]>=
'0' && zId[i]<=
'9')
7666 && !(zId[i]>=
'a' && zId[i]<=
'z')
7667 && !(zId[i]>=
'A' && zId[i]<=
'Z')
7731 for(pIter=pEq; pIter; pIter=pIter->
pLink) nEq++;
7741 for(pIter=pEq; pIter; pIter=pIter->
pLink) pIter->
bFlag = 0;
7750 for(pIter=pEq; pIter; pIter=pIter->
pLink){
7751 if( pIter->
bFlag )
continue;
7752 if( pIter->
iCol!=iCol )
continue;
7800 for(pCons=pEq; pCons; pCons=pCons->
pLink){
7803 for(pCons=pTail; pCons; pCons=pCons->
pLink){
7809 const char *zTable = pScan->
pTab->
zName;
7812 for(i=0; zCols[i]; i++){
7813 h += ((h<<3) + zCols[i]);
7820 zFmt =
"CREATE INDEX '%q' ON %Q(%s)";
7822 zFmt =
"CREATE INDEX %s ON %s(%s)";
7847 for(pCmp=pList; pCmp; pCmp=pCmp->
pLink){
7848 if( p->
iCol==pCmp->
iCol )
return 1;
7863 for(pCon=pScan->
pEq; pCon; pCon=pCon->
pNext){
7878 assert( pCon->
pLink==0 );
7913 for(p=pConstraint; p; p=pNext){
7926 for(p=pScan; p!=pLast; p=pNext){
7942 for(p=pStatement; p!=pLast; p=pNext){
7956 for(pIter=pTab; pIter; pIter=pNext){
7957 pNext = pIter->
pNext;
7968 for(pIter=pTab; pIter; pIter=pNext){
7969 pNext = pIter->
pNext;
7997 "EXPLAIN QUERY PLAN %s", pStmt->
zSql
8007 if( !zDetail )
continue;
8008 nDetail =
STRLEN(zDetail);
8010 for(i=0; i<nDetail; i++){
8011 const char *zIdx = 0;
8012 if( i+13<nDetail && memcmp(&zDetail[i],
" USING INDEX ", 13)==0 ){
8013 zIdx = &zDetail[i+13];
8014 }
else if( i+22<nDetail
8015 && memcmp(&zDetail[i],
" USING COVERING INDEX ", 22)==0
8017 zIdx = &zDetail[i+22];
8022 while( zIdx[nIdx]!=
'\0' && (zIdx[nIdx]!=
' ' || zIdx[nIdx+1]!=
'(') ){
8028 if( rc )
goto find_indexes_out;
8034 if( zDetail[0]!=
'-' ){
8039 for(pEntry=hIdx.
pFirst; pEntry; pEntry=pEntry->
pNext){
8057 const char *zTrigger
8071 for(pWrite=p->
pWrite; pWrite; pWrite=pWrite->
pNext){
8072 if( pWrite->
pTab==pTab && pWrite->
eOp==eOp )
break;
8077 pWrite->
pTab = pTab;
8097 const char *zTab = pTab->
zName;
8099 "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_master "
8100 "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
8116 char *z =
sqlite3_mprintf(
"ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
8125 switch( pWrite->
eOp ){
8128 zWrite =
idxAppendText(&rc, zWrite,
"INSERT INTO %Q VALUES(", zInt);
8129 for(i=0; i<pTab->
nCol; i++){
8130 zWrite =
idxAppendText(&rc, zWrite,
"%s?", i==0 ?
"" :
", ");
8137 zWrite =
idxAppendText(&rc, zWrite,
"UPDATE %Q SET ", zInt);
8138 for(i=0; i<pTab->
nCol; i++){
8139 zWrite =
idxAppendText(&rc, zWrite,
"%s%Q=?", i==0 ?
"" :
", ",
8178 for(pIter=pFirst; rc==
SQLITE_OK && pIter!=pEnd; pIter=pIter->
pNext){
8199 "SELECT type, name, sql, 1 FROM sqlite_master "
8200 "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
8202 "SELECT type, name, sql, 2 FROM sqlite_master "
8203 "WHERE type = 'trigger'"
8204 " AND tbl_name IN(SELECT name FROM sqlite_master WHERE type = 'view') "
8212 if( zType[0]==
'v' || zType[1]==
'r' ){
8226 for(i=0; i<pTab->
nCol; i++){
8235 "CREATE VIRTUAL TABLE %Q USING expert(%Q)",
zName, zInner
8273 bRet = ((int)rnd % 100) <= p->
iTarget;
8279 p->
nRet += (double)bRet;
8303 struct IdxRemSlot *pSlot;
8308 assert( iSlot<=p->nSlot );
8309 pSlot = &p->
aSlot[iSlot];
8311 switch( pSlot->eType ){
8334 switch( pSlot->eType ){
8350 if( nByte>pSlot->nByte ){
8356 pSlot->nByte = nByte*2;
8373 "SELECT max(i.seqno) FROM "
8374 " sqlite_master AS s, "
8375 " pragma_index_list(s.name) AS l, "
8376 " pragma_index_info(l.name) AS i "
8377 "WHERE s.type = 'table'";
8412 const char *zComma = zCols==0 ?
"" :
", ";
8416 "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma,
zName, nCol,
zName, zColl
8418 zOrder =
idxAppendText(&rc, zOrder,
"%s%d", zComma, ++nCol);
8424 "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
8443 aStat = (
int*)
idxMalloc(&rc,
sizeof(
int)*(nCol+1));
8448 for(i=0; i<=nCol; i++) aStat[i] = 1;
8451 for(i=0; i<nCol; i++){
8463 for(i=1; rc==
SQLITE_OK && i<=nCol; i++){
8464 zStat =
idxAppendText(&rc, zStat,
" %d", (s0+aStat[i]/2) / aStat[i]);
8478 assert( pEntry->
zVal2==0 );
8479 pEntry->
zVal2 = zStat;
8520 i64 iPrev = -100000;
8525 const char *zAllIndex =
8526 "SELECT s.rowid, s.name, l.name FROM "
8527 " sqlite_master AS s, "
8528 " pragma_index_list(s.name) AS l "
8529 "WHERE s.type = 'table'";
8530 const char *zIndexXInfo =
8531 "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
8532 const char *zWrite =
"INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
8538 if( nMax<=0 || rc!=
SQLITE_OK )
return rc;
8540 rc =
sqlite3_exec(p->
dbm,
"ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
8543 int nByte =
sizeof(
struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
8560 pCtx->
nSlot = nMax+1;
8574 if( p->
iSample<100 && iPrev!=iRowid ){
8577 samplectx.
nRow = 0.0;
8578 samplectx.
nRet = 0.0;
8595 for(i=0; i<pCtx->
nSlot; i++){
8640 "SELECT sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%%'"
8641 " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
8678 int iVal = va_arg(ap,
int);
8679 if( iVal<0 ) iVal = 0;
8680 if( iVal>100 ) iVal = 100;
8704 const char *zStmt = zSql;
8708 while( rc==
SQLITE_OK && zStmt && zStmt[0] ){
8718 pNew->
zSql = (
char*)&pNew[1];
8719 memcpy(pNew->
zSql, z, n+1);
8734 p->
pScan = pScanOrig;
8761 "%s;%s%s\n", pEntry->
zVal,
8762 pEntry->
zVal2 ?
" -- stat1: " :
"", pEntry->
zVal2
8792 const char *zRet = 0;
8795 if( p->
bRun==0 )
return 0;
8799 if( pStmt ) zRet = pStmt->
zSql;
8802 if( pStmt ) zRet = pStmt->
zIdx;
8805 if( pStmt ) zRet = pStmt->
zEQP;
8835 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
8910 #if !defined(SQLITEINT_H)
8920 #define DBDATA_PADDING_BYTES 100
8922 typedef struct DbdataTable DbdataTable;
8923 typedef struct DbdataCursor DbdataCursor;
8926 struct DbdataCursor {
8951 struct DbdataTable {
8959 #define DBDATA_COLUMN_PGNO 0
8960 #define DBDATA_COLUMN_CELL 1
8961 #define DBDATA_COLUMN_FIELD 2
8962 #define DBDATA_COLUMN_VALUE 3
8963 #define DBDATA_COLUMN_SCHEMA 4
8964 #define DBDATA_SCHEMA \
8970 " schema TEXT HIDDEN" \
8974 #define DBPTR_COLUMN_PGNO 0
8975 #define DBPTR_COLUMN_CHILD 1
8976 #define DBPTR_COLUMN_SCHEMA 2
8977 #define DBPTR_SCHEMA \
8981 " schema TEXT HIDDEN" \
8988 static int dbdataConnect(
8991 int argc,
const char *
const*argv,
8995 DbdataTable *pTab = 0;
9003 memset(pTab, 0,
sizeof(DbdataTable));
9005 pTab->bPtr = (pAux!=0);
9017 DbdataTable *pTab = (DbdataTable*)pVtab;
9039 DbdataTable *pTab = (DbdataTable*)tab;
9043 int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
9046 struct sqlite3_index_constraint *p = &pIdx->
aConstraint[i];
9048 if( p->iColumn==colSchema ){
9052 if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
9081 pIdx->
idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
9095 memset(pCsr, 0,
sizeof(DbdataCursor));
9096 pCsr->base.pVtab = pVTab;
9107 static void dbdataResetCursor(DbdataCursor *pCsr){
9108 DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
9109 if( pTab->pStmt==0 ){
9110 pTab->pStmt = pCsr->pStmt;
9129 DbdataCursor *pCsr = (DbdataCursor*)pCursor;
9130 dbdataResetCursor(pCsr);
9138 static unsigned int get_uint16(
unsigned char *a){
9139 return (a[0]<<8)|a[1];
9141 static unsigned int get_uint32(
unsigned char *a){
9142 return ((
unsigned int)a[0]<<24)
9143 | ((
unsigned int)a[1]<<16)
9144 | ((
unsigned int)a[2]<<8)
9145 | ((
unsigned int)a[3]);
9158 static int dbdataLoadPage(
9180 memcpy(pPage, pCopy, nCopy);
9181 memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
9200 v = (v<<7) + (z[i]&0x7f);
9201 if( (z[i]&0x80)==0 ){ *pVal = v;
return i+1; }
9203 v = (v<<8) + (z[i]&0xff);
9212 static int dbdataValueBytes(
int eType){
9214 case 0:
case 8:
case 9:
9232 return ((
eType-12) / 2);
9242 static void dbdataValue(
9248 if(
eType>=0 && dbdataValueBytes(
eType)<=nData ){
9263 case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7: {
9268 case 6: v = (v<<16) + (pData[0]<<8) + pData[1]; pData += 2;
9269 case 5: v = (v<<16) + (pData[0]<<8) + pData[1]; pData += 2;
9270 case 4: v = (v<<8) + pData[0]; pData++;
9271 case 3: v = (v<<8) + pData[0]; pData++;
9272 case 2: v = (v<<8) + pData[0]; pData++;
9277 memcpy(&r, &v,
sizeof(r));
9286 int n = ((
eType-12) / 2);
9301 DbdataCursor *pCsr = (DbdataCursor*)pCursor;
9302 DbdataTable *pTab = (DbdataTable*)pCursor->
pVtab;
9307 int iOff = (pCsr->iPgno==1 ? 100 : 0);
9310 if( pCsr->aPage==0 ){
9312 if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb )
return SQLITE_OK;
9313 rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
9315 if( pCsr->aPage )
break;
9318 pCsr->iCell = pTab->bPtr ? -2 : 0;
9319 pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
9323 if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
9324 pCsr->iCell = pCsr->nCell;
9327 if( pCsr->iCell>=pCsr->nCell ){
9337 if( pCsr->pRec==0 ){
9346 switch( pCsr->aPage[iOff] ){
9357 pCsr->iCell = pCsr->nCell;
9361 if( pCsr->iCell>=pCsr->nCell ){
9365 iOff += 8 + nPointer + pCsr->iCell*2;
9366 if( iOff>pCsr->nPage ){
9369 iOff = get_uint16(&pCsr->aPage[iOff]);
9376 if( bNextPage || iOff>pCsr->nPage ){
9379 iOff += dbdataGetVarint(&pCsr->aPage[iOff], &nPayload);
9383 if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
9384 iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
9392 X = ((U-12)*64/255)-23;
9398 M = ((U-12)*32/255)-23;
9399 K = M+((nPayload-M)%(U-4));
9407 if( bNextPage || nLocal+iOff>pCsr->nPage ){
9416 memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
9417 pCsr->nRec = nPayload;
9420 memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
9424 if( nPayload>nLocal ){
9426 unsigned int pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
9431 rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
9432 assert( rc!=
SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
9434 if( aOvfl==0 )
break;
9437 if( nCopy>nRem ) nCopy = nRem;
9438 memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
9441 pgnoOvfl = get_uint32(aOvfl);
9446 iHdr = dbdataGetVarint(pCsr->pRec, &nHdr);
9448 pCsr->pHdrPtr = &pCsr->pRec[iHdr];
9449 pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
9450 pCsr->iField = (bHasRowid ? -1 : 0);
9455 if( pCsr->iField>0 ){
9457 if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
9460 pCsr->pHdrPtr += dbdataGetVarint(pCsr->pHdrPtr, &iType);
9461 pCsr->pPtr += dbdataValueBytes(iType);
9474 if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
9487 assert( !
"can't get here" );
9495 DbdataCursor *pCsr = (DbdataCursor*)pCursor;
9496 return pCsr->aPage==0;
9505 static int dbdataDbsize(DbdataCursor *pCsr,
const char *zSchema){
9506 DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
9526 static int dbdataFilter(
9528 int idxNum,
const char *idxStr,
9531 DbdataCursor *pCsr = (DbdataCursor*)pCursor;
9532 DbdataTable *pTab = (DbdataTable*)pCursor->
pVtab;
9534 const char *zSchema =
"main";
9536 dbdataResetCursor(pCsr);
9537 assert( pCsr->iPgno==1 );
9538 if( idxNum & 0x01 ){
9541 if( idxNum & 0x02 ){
9545 pCsr->nPage = dbdataDbsize(pCsr, zSchema);
9546 rc = dbdataDbsize(pCsr, zSchema);
9551 pCsr->pStmt = pTab->pStmt;
9555 "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
9566 rc = dbdataNext(pCursor);
9574 static int dbdataColumn(
9579 DbdataCursor *pCsr = (DbdataCursor*)pCursor;
9580 DbdataTable *pTab = (DbdataTable*)pCursor->
pVtab;
9583 case DBPTR_COLUMN_PGNO:
9586 case DBPTR_COLUMN_CHILD: {
9587 int iOff = pCsr->iPgno==1 ? 100 : 0;
9588 if( pCsr->iCell<0 ){
9591 iOff += 12 + pCsr->iCell*2;
9592 if( iOff>pCsr->nPage )
return SQLITE_OK;
9593 iOff = get_uint16(&pCsr->aPage[iOff]);
9595 if( iOff<=pCsr->nPage ){
9603 case DBDATA_COLUMN_PGNO:
9606 case DBDATA_COLUMN_CELL:
9609 case DBDATA_COLUMN_FIELD:
9612 case DBDATA_COLUMN_VALUE: {
9613 if( pCsr->iField<0 ){
9617 dbdataGetVarint(pCsr->pHdrPtr, &iType);
9619 ctx, iType, pCsr->pPtr, &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
9633 DbdataCursor *pCsr = (DbdataCursor*)pCursor;
9634 *pRowid = pCsr->iRowid;
9642 static int sqlite3DbdataRegister(
sqlite3 *db){
9680 int sqlite3_dbdata_init(
9686 return sqlite3DbdataRegister(db);
9692 #if defined(SQLITE_ENABLE_SESSION)
9696 typedef struct OpenSession OpenSession;
9697 struct OpenSession {
9800 #if defined(SQLITE_ENABLE_SESSION)
9802 OpenSession aSession[4];
9810 #define AUTOEQP_off 0
9811 #define AUTOEQP_on 1
9812 #define AUTOEQP_trigger 2
9813 #define AUTOEQP_full 3
9817 #define SHELL_OPEN_UNSPEC 0
9818 #define SHELL_OPEN_NORMAL 1
9819 #define SHELL_OPEN_APPENDVFS 2
9820 #define SHELL_OPEN_ZIPFILE 3
9821 #define SHELL_OPEN_READONLY 4
9822 #define SHELL_OPEN_DESERIALIZE 5
9823 #define SHELL_OPEN_HEXDB 6
9827 #define SHELL_TRACE_PLAIN 0
9828 #define SHELL_TRACE_EXPANDED 1
9829 #define SHELL_TRACE_NORMALIZED 2
9832 #define SHELL_PROGRESS_QUIET 0x01
9833 #define SHELL_PROGRESS_RESET 0x02
9836 #define SHELL_PROGRESS_ONCE 0x04
9841 #define SHFLG_Pagecache 0x00000001
9842 #define SHFLG_Lookaside 0x00000002
9843 #define SHFLG_Backslash 0x00000004
9844 #define SHFLG_PreserveRowid 0x00000008
9845 #define SHFLG_Newlines 0x00000010
9846 #define SHFLG_CountChanges 0x00000020
9847 #define SHFLG_Echo 0x00000040
9852 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
9853 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
9854 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
9860 #define MODE_Column 1
9864 #define MODE_Insert 5
9865 #define MODE_Quote 6
9868 #define MODE_Explain 9
9869 #define MODE_Ascii 10
9870 #define MODE_Pretty 11
9893 #define SEP_Column "|"
9894 #define SEP_Row "\n"
9895 #define SEP_Tab "\t"
9896 #define SEP_Space " "
9897 #define SEP_Comma ","
9898 #define SEP_CrLf "\r\n"
9899 #define SEP_Unit "\x1F"
9900 #define SEP_Record "\x1E"
9905 static void shellLog(
void *pArg,
int iErrCode,
const char *zMsg){
9907 if( p->
pLog==0 )
return;
9945 #ifndef SQLITE_NOHAVE_SYSTEM
9951 const char *zEditor;
9952 char *zTempFile = 0;
9961 unsigned char *p = 0;
9966 zEditor = getenv(
"VISUAL");
9991 f = fopen(zTempFile, bBin ?
"wb" :
"w");
10002 if( z && strstr(z,
"\r\n")!=0 ) hasCRNL = 1;
10009 goto edit_func_end;
10014 goto edit_func_end;
10020 goto edit_func_end;
10022 f = fopen(zTempFile,
"rb");
10025 "edit() cannot reopen temp file after edit", -1);
10026 goto edit_func_end;
10034 goto edit_func_end;
10036 x = fread(p, 1, (
size_t)sz, f);
10041 goto edit_func_end;
10053 for(i=j=0; i<sz; i++){
10054 if( p[i]==
'\r' && p[i+1]==
'\n' ) i++;
10092 static void output_hex_blob(FILE *out,
const void *pBlob,
int nBlob){
10094 char *zBlob = (
char *)pBlob;
10096 for(i=0; i<nBlob; i++){
raw_printf(out,
"%02x",zBlob[i]&0xff); }
10109 const char *zA,
const char *zB,
10113 if( strstr(z, zA)==0 )
return zA;
10114 if( strstr(z, zB)==0 )
return zB;
10117 }
while( strstr(z,zBuf)!=0 );
10130 for(i=0; (c = z[i])!=0 && c!=
'\''; i++){}
10136 for(i=0; (c = z[i])!=0 && c!=
'\''; i++){}
10169 for(i=0; (c = z[i])!=0 && c!=
'\'' && c!=
'\n' && c!=
'\r'; i++){}
10173 const char *zNL = 0;
10174 const char *zCR = 0;
10177 char zBuf1[20], zBuf2[20];
10178 for(i=0; z[i]; i++){
10179 if( z[i]==
'\n' ) nNL++;
10180 if( z[i]==
'\r' ) nCR++;
10192 for(i=0; (c = z[i])!=0 && c!=
'\n' && c!=
'\r' && c!=
'\''; i++){}
10229 while( (c = *(z++))!=0 ){
10233 }
else if( c==
'"' ){
10236 }
else if( c==
'\t' ){
10239 }
else if( c==
'\n' ){
10242 }
else if( c==
'\r' ){
10245 }
else if( !isprint(c&0xff) ){
10274 }
else if( z[i]==
'&' ){
10276 }
else if( z[i]==
'>' ){
10278 }
else if( z[i]==
'\"' ){
10280 }
else if( z[i]==
'\'' ){
10294 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
10295 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
10296 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
10297 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
10298 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
10299 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
10300 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
10301 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
10302 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
10303 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
10304 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
10305 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
10306 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
10307 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
10308 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
10309 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
10319 FILE *out = p->
out;
10325 for(i=0; z[i]; i++){
10356 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
10360 static BOOL WINAPI ConsoleCtrlHandler(
10363 if( dwCtrlType==CTRL_C_EVENT ){
10371 #ifndef SQLITE_OMIT_AUTHORIZATION
10385 static const char *azAction[] = { 0,
10386 "CREATE_INDEX",
"CREATE_TABLE",
"CREATE_TEMP_INDEX",
10387 "CREATE_TEMP_TABLE",
"CREATE_TEMP_TRIGGER",
"CREATE_TEMP_VIEW",
10388 "CREATE_TRIGGER",
"CREATE_VIEW",
"DELETE",
10389 "DROP_INDEX",
"DROP_TABLE",
"DROP_TEMP_INDEX",
10390 "DROP_TEMP_TABLE",
"DROP_TEMP_TRIGGER",
"DROP_TEMP_VIEW",
10391 "DROP_TRIGGER",
"DROP_VIEW",
"INSERT",
10392 "PRAGMA",
"READ",
"SELECT",
10393 "TRANSACTION",
"UPDATE",
"ATTACH",
10394 "DETACH",
"ALTER_TABLE",
"REINDEX",
10395 "ANALYZE",
"CREATE_VTABLE",
"DROP_VTABLE",
10396 "FUNCTION",
"SAVEPOINT",
"RECURSIVE"
10405 for(i=0; i<4; i++){
10424 static void printSchemaLine(FILE *out,
const char *z,
const char *zTail){
10426 if( zTail==0 )
return;
10428 utf8_printf(out,
"CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
10433 static void printSchemaLineN(FILE *out,
char *z,
int n,
const char *zTail){
10444 static int wsToEol(
const char *z){
10446 for(i=0; z[i]; i++){
10447 if( z[i]==
'\n' )
return 1;
10448 if(
IsSpace(z[i]) )
continue;
10449 if( z[i]==
'-' && z[i+1]==
'-' )
return 1;
10468 memcpy(pNew->
zText, zText, nText+1);
10484 for(pRow = p->
sGraph.
pRow; pRow; pRow = pNext){
10485 pNext = pRow->
pNext;
10507 for(pRow =
eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
10511 pNext ?
"|--" :
"`--", z);
10526 if( pRow->
zText[0]==
'-' ){
10527 if( pRow->
pNext==0 ){
10543 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10577 if( azArg==0 )
return 0;
10578 switch( p->
cMode ){
10581 if( azArg==0 )
break;
10582 for(i=0; i<nArg; i++){
10583 int len =
strlen30(azCol[i] ? azCol[i] :
"");
10584 if( len>w ) w = len;
10587 for(i=0; i<nArg; i++){
10595 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
10596 const int *colWidth;
10606 colWidth = aExplainWidths;
10612 for(i=0; i<nArg; i++){
10634 for(i=0; i<nArg; i++){
10643 "----------------------------------------------------------"
10644 "----------------------------------------------------------",
10645 i==nArg-1 ? rowSep :
" ");
10649 if( azArg==0 )
break;
10650 for(i=0; i<nArg; i++){
10683 if( azArg[0]==0 )
break;
10692 for(i=0;
IsSpace(z[i]); i++){}
10693 for(; (c = z[i])!=0; i++){
10695 if( z[j-1]==
'\r' ) z[j-1] =
'\n';
10696 if(
IsSpace(z[j-1]) || z[j-1]==
'(' )
continue;
10697 }
else if( (c==
'(' || c==
')') && j>0 &&
IsSpace(z[j-1]) ){
10702 while( j>0 &&
IsSpace(z[j-1]) ){ j--; }
10705 for(i=j=0; (c = z[i])!=0; i++){
10708 }
else if( c==
'"' || c==
'\'' || c==
'`' ){
10710 }
else if( c==
'[' ){
10712 }
else if( c==
'-' && z[i+1]==
'-' ){
10714 }
else if( c==
'(' ){
10716 }
else if( c==
')' ){
10718 if( nLine>0 && nParen==0 && j>0 ){
10724 if( nParen==1 && cEnd==0
10725 && (c==
'(' || c==
'\n' || (c==
',' && !
wsToEol(z+i+1)))
10731 while(
IsSpace(z[i+1]) ){ i++; }
10742 for(i=0; i<nArg; i++){
10747 if( azArg==0 )
break;
10748 for(i=0; i<nArg; i++){
10749 char *z = azArg[i];
10763 for(i=0; i<nArg; i++){
10770 if( azArg==0 )
break;
10772 for(i=0; i<nArg; i++){
10782 for(i=0; i<nArg; i++){
10788 if( azArg==0 )
break;
10789 for(i=0; i<nArg; i++){
10799 for(i=0; i<nArg; i++){
10800 output_csv(p, azCol[i] ? azCol[i] :
"", i<nArg-1);
10805 for(i=0; i<nArg; i++){
10814 if( azArg==0 )
break;
10818 for(i=0; i<nArg; i++){
10831 for(i=0; i<nArg; i++){
10833 if( (azArg[i]==0) || (aiType && aiType[i]==
SQLITE_NULL) ){
10847 memcpy(&ur,&r,
sizeof(r));
10848 if( ur==0x7ff0000000000000LL ){
10850 }
else if( ur==0xfff0000000000000LL ){
10860 }
else if(
isNumber(azArg[i], 0) ){
10872 if( azArg==0 )
break;
10874 for(i=0; i<nArg; i++){
10881 for(i=0; i<nArg; i++){
10883 if( (azArg[i]==0) || (aiType && aiType[i]==
SQLITE_NULL) ){
10898 }
else if(
isNumber(azArg[i], 0) ){
10909 for(i=0; i<nArg; i++){
10915 if( azArg==0 )
break;
10916 for(i=0; i<nArg; i++){
10924 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
10935 static int callback(
void *pArg,
int nArg,
char **azArg,
char **azCol){
10948 if( azArg==0 )
return 0;
10950 for(i=0; i<nArg; i++){
10963 "SAVEPOINT selftest_init;\n"
10964 "CREATE TABLE IF NOT EXISTS selftest(\n"
10965 " tno INTEGER PRIMARY KEY,\n"
10970 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
10971 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
10972 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
10973 " 'memo','Tests generated by --init');\n"
10974 "INSERT INTO [_shell$self]\n"
10976 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
10977 "FROM sqlite_master ORDER BY 2'',224))',\n"
10978 " hex(sha3_query('SELECT type,name,tbl_name,sql "
10979 "FROM sqlite_master ORDER BY 2',224));\n"
10980 "INSERT INTO [_shell$self]\n"
10982 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
10983 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
10984 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
10986 " SELECT name FROM sqlite_master\n"
10987 " WHERE type='table'\n"
10988 " AND name<>'selftest'\n"
10989 " AND coalesce(rootpage,0)>0\n"
10991 " ORDER BY name;\n"
10992 "INSERT INTO [_shell$self]\n"
10993 " VALUES('run','PRAGMA integrity_check','ok');\n"
10994 "INSERT INTO selftest(tno,op,cmd,ans)"
10995 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
10996 "DROP TABLE [_shell$self];"
10999 utf8_printf(stderr,
"SELFTEST initialization failure: %s\n", zErrMsg);
11020 if(
zName==0 )
return;
11023 if( cQuote ) n += n+2;
11027 if( cQuote ) z[n++] = cQuote;
11028 for(i=0;
zName[i]; i++){
11030 if(
zName[i]==cQuote ) z[n++] = cQuote;
11032 if( cQuote ) z[n++] = cQuote;
11049 const char *zSelect
11068 for(i=1; i<nResult; i++){
11072 while( z[0] && (z[0]!=
'-' || z[1]!=
'-') ) z++;
11107 static void displayLinuxIoStats(FILE *out){
11111 in = fopen(z,
"rb");
11112 if( in==0 )
return;
11113 while( fgets(z,
sizeof(z), in)!=0 ){
11114 static const struct {
11115 const char *zPattern;
11118 {
"rchar: ",
"Bytes received by read():" },
11119 {
"wchar: ",
"Bytes sent to write():" },
11120 {
"syscr: ",
"Read() system calls:" },
11121 {
"syscw: ",
"Write() system calls:" },
11122 {
"read_bytes: ",
"Bytes read from storage:" },
11123 {
"write_bytes: ",
"Bytes written to storage:" },
11124 {
"cancelled_write_bytes: ",
"Cancelled write bytes:" },
11128 int n =
strlen30(aTrans[i].zPattern);
11129 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
11130 utf8_printf(out,
"%-36s %s", aTrans[i].zDesc, &z[n]);
11154 for(i=0, nPercent=0; zFormat[i]; i++){
11155 if( zFormat[i]==
'%' ) nPercent++;
11176 if( pArg==0 || pArg->
out==0 )
return 0;
11184 raw_printf(out,
"%-36s %d\n",
"Number of output columns:", nCol);
11185 for(i=0; i<nCol; i++){
11188 #ifndef SQLITE_OMIT_DECLTYPE
11192 #ifdef SQLITE_ENABLE_COLUMN_METADATA
11217 #ifdef YYTRACKMAXSTACKDEPTH
11224 iHiwtr = iCur = -1;
11226 &iCur, &iHiwtr, bReset);
11228 "Lookaside Slots Used: %d (max %d)\n",
11231 &iCur, &iHiwtr, bReset);
11232 raw_printf(pArg->
out,
"Successful lookaside attempts: %d\n",
11235 &iCur, &iHiwtr, bReset);
11236 raw_printf(pArg->
out,
"Lookaside failures due to size: %d\n",
11239 &iCur, &iHiwtr, bReset);
11240 raw_printf(pArg->
out,
"Lookaside failures due to OOM: %d\n",
11243 iHiwtr = iCur = -1;
11247 iHiwtr = iCur = -1;
11250 iHiwtr = iCur = -1;
11253 iHiwtr = iCur = -1;
11256 iHiwtr = iCur = -1;
11259 iHiwtr = iCur = -1;
11263 iHiwtr = iCur = -1;
11265 raw_printf(pArg->
out,
"Statement Heap/Lookaside Usage: %d bytes\n",
11278 raw_printf(pArg->
out,
"Virtual Machine Steps: %d\n", iCur);
11284 raw_printf(pArg->
out,
"Memory used by prepared stmt: %d\n", iCur);
11288 displayLinuxIoStats(pArg->
out);
11303 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
11310 for(k=0; k<=mx; k++){
11311 double rEstLoop = 1.0;
11312 for(i=n=0; 1; i++){
11317 const char *zExplain;
11322 if( iSid>mx ) mx = iSid;
11323 if( iSid!=k )
continue;
11325 rEstLoop = (double)nLoop;
11326 if( k>0 )
raw_printf(pArg->
out,
"-------- subquery %d -------\n", k);
11335 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
11350 static int str_in_array(
const char *zStr,
const char **azArray){
11352 for(i=0; azArray[i]; i++){
11353 if( 0==strcmp(zStr, azArray[i]) )
return 1;
11383 const char *azNext[] = {
"Next",
"Prev",
"VPrev",
"VNext",
"SorterNext", 0 };
11384 const char *azYield[] = {
"Yield",
"SeekLT",
"SeekGT",
"RowSetRead",
11386 const char *azGoto[] = {
"Goto", 0 };
11395 if( zSql==0 )
return;
11396 for(z=zSql; *z==
' ' || *z==
'\t' || *z==
'\n' || *z==
'\f' || *z==
'\r'; z++);
11413 int p2op = (p2 + (iOp-iAddr));
11420 static const char *explainCols[] = {
11421 "addr",
"opcode",
"p1",
"p2",
"p3",
"p4",
"p5",
"comment" };
11423 for(jj=0; jj<
ArraySize(explainCols); jj++){
11442 for(i=p2op; i<iOp; i++) p->
aiIndent[i] += 2;
11447 for(i=p2op; i<iOp; i++) p->
aiIndent[i] += 2;
11469 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
11470 extern int sqlite3SelectTrace;
11471 static int savedSelectTrace;
11473 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
11474 extern int sqlite3WhereTrace;
11475 static int savedWhereTrace;
11478 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
11479 savedSelectTrace = sqlite3SelectTrace;
11480 sqlite3SelectTrace = 0;
11482 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
11483 savedWhereTrace = sqlite3WhereTrace;
11484 sqlite3WhereTrace = 0;
11488 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
11489 sqlite3SelectTrace = savedSelectTrace;
11491 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
11492 sqlite3WhereTrace = savedWhereTrace;
11499 int defensiveMode = 0;
11505 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
11506 " key TEXT PRIMARY KEY,\n"
11508 ") WITHOUT ROWID;",
11533 if( nVar==0 )
return;
11539 "SELECT value FROM temp.sqlite_parameters"
11540 " WHERE key=?1", -1, &pQ, 0);
11541 if( rc || pQ==0 )
return;
11542 for(i=1; i<=nVar; i++){
11581 char **azCols = (
char **)pData;
11582 char **azVals = &azCols[nCol];
11583 int *aiTypes = (
int *)&azVals[nCol];
11585 assert(
sizeof(
int) <=
sizeof(
char *));
11587 for(i=0; i<nCol; i++){
11592 for(i=0; i<nCol; i++){
11620 #ifndef SQLITE_OMIT_VIRTUALTABLE
11637 assert( pzErr==0 || *pzErr==0 );
11659 assert( bCancel || pzErr==0 || *pzErr==0 );
11661 FILE *out = pState->
out;
11671 raw_printf(out,
"-- Candidates -----------------------------\n");
11674 for(i=0; i<nQuery; i++){
11678 if( zIdx==0 ) zIdx =
"(no new indexes)\n";
11680 raw_printf(out,
"-- Query %d --------------------------------\n",i+1);
11709 for(i=1; rc==
SQLITE_OK && i<nArg; i++){
11710 char *z = azArg[i];
11712 if( z[0]==
'-' && z[1]==
'-' ) z++;
11714 if( n>=2 && 0==strncmp(z,
"-verbose", n) ){
11717 else if( n>=2 && 0==strncmp(z,
"-sample", n) ){
11719 raw_printf(stderr,
"option requires an argument: %s\n", z);
11723 if( iSample<0 || iSample>100 ){
11724 raw_printf(stderr,
"value out of range: %s\n", azArg[i]);
11730 raw_printf(stderr,
"unknown option: %s\n", z);
11738 raw_printf(stderr,
"sqlite3_expert_new: %s\n", zErr);
11768 const char *zLeftover;
11775 #ifndef SQLITE_OMIT_VIRTUALTABLE
11783 static const char *zStmtSql;
11793 while(
IsSpace(zSql[0]) ) zSql++;
11797 if( zStmtSql==0 ) zStmtSql =
"";
11798 while(
IsSpace(zStmtSql[0]) ) zStmtSql++;
11802 pArg->
pStmt = pStmt;
11815 int triggerEQP = 0;
11828 if( zEQPLine==0 ) zEQPLine =
"";
11830 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
11854 if( pArg ) pArg->
pStmt = pStmt;
11899 while(
IsSpace(zSql[0]) ) zSql++;
11900 }
else if( pzErrMsg ){
11919 for(i=1; azCol[i]; i++){
11955 if( nCol>=nAlloc-2 ){
11956 nAlloc = nAlloc*2 + nCol + 10;
11974 if( azCol==0 )
return 0;
11984 if( preserveRowid && isIPK ){
11993 " WHERE origin='pk'", zTab);
12004 if( preserveRowid ){
12007 static char *azRowid[] = {
"rowid",
"_rowid_",
"oid" };
12009 for(j=0; j<3; j++){
12010 for(i=1; i<=nCol; i++){
12019 if( rc==
SQLITE_OK ) azCol[0] = azRowid[j];
12040 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
12050 static int dump_callback(
void *pArg,
int nArg,
char **azArg,
char **azNotUsed){
12052 const char *zTable;
12058 if( nArg!=3 || azArg==0 )
return 0;
12063 if( strcmp(zTable,
"sqlite_sequence")==0 ){
12067 }
else if( strncmp(zTable,
"sqlite_", 7)==0 ){
12069 }
else if( strncmp(zSql,
"CREATE VIRTUAL TABLE", 20)==0 ){
12076 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
12077 "VALUES('table','%q','%q',0,'%q');",
12078 zTable, zTable, zSql);
12086 if( strcmp(zType,
"table")==0 ){
12091 char *savedDestTable;
12111 for(i=1; azCol[i]; i++){
12125 for(i=1; azCol[i]; i++){
12136 savedMode = p->
mode;
12147 p->
mode = savedMode;
12150 if( rc ) p->
nErr++;
12178 zQ2 = malloc( len+100 );
12179 if( zQ2==0 )
return rc;
12202 static const char *(
azHelp[]) = {
12203 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
12204 ".archive ... Manage SQL archives",
12205 " Each command must have exactly one of the following options:",
12206 " -c, --create Create a new archive",
12207 " -u, --update Add or update files with changed mtime",
12208 " -i, --insert Like -u but always add even if unchanged",
12209 " -t, --list List contents of archive",
12210 " -x, --extract Extract files from archive",
12211 " Optional arguments:",
12212 " -v, --verbose Print each filename as it is processed",
12213 " -f FILE, --file FILE Use archive FILE (default is current db)",
12214 " -a FILE, --append FILE Open FILE using the apndvfs VFS",
12215 " -C DIR, --directory DIR Read/extract files from directory DIR",
12216 " -n, --dryrun Show the SQL that would have occurred",
12218 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
12219 " .ar -tf ARCHIVE # List members of ARCHIVE",
12220 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
12222 " http://sqlite.org/cli.html#sqlar_archive_support",
12224 #ifndef SQLITE_OMIT_AUTHORIZATION
12225 ".auth ON|OFF Show authorizer callbacks",
12227 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
12228 " --append Use the appendvfs",
12229 " --async Write to FILE without journal and fsync()",
12230 ".bail on|off Stop after hitting an error. Default OFF",
12231 ".binary on|off Turn binary output on or off. Default OFF",
12232 ".cd DIRECTORY Change the working directory to DIRECTORY",
12233 ".changes on|off Show number of rows changed by SQL",
12234 ".check GLOB Fail if output since .testcase does not match",
12235 ".clone NEWDB Clone data into NEWDB from the existing database",
12236 ".databases List names and files of attached databases",
12237 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
12238 ".dbinfo ?DB? Show status information about the database",
12239 ".dump ?TABLE? Render database content as SQL",
12241 " --preserve-rowids Include ROWID values in the output",
12242 " --newlines Allow unescaped newline characters in output",
12243 " TABLE is a LIKE pattern for the tables to dump",
12244 " Additional LIKE patterns can be given in subsequent arguments",
12245 ".echo on|off Turn command echo on or off",
12246 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
12248 #ifdef SQLITE_DEBUG
12249 " test Show raw EXPLAIN QUERY PLAN output",
12250 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"",
12252 " trigger Like \"full\" but also show trigger bytecode",
12253 ".excel Display the output of next command in spreadsheet",
12254 " --bom Put a UTF8 byte-order mark on intermediate file",
12255 ".exit ?CODE? Exit this program with return-code CODE",
12256 ".expert EXPERIMENTAL. Suggest indexes for queries",
12257 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto",
12258 ".filectrl CMD ... Run various sqlite3_file_control() operations",
12259 " --schema SCHEMA Use SCHEMA instead of \"main\"",
12260 " --help Show CMD details",
12261 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
12262 ".headers on|off Turn display of headers on or off",
12263 ".help ?-all? ?PATTERN? Show help text for PATTERN",
12264 ".import FILE TABLE Import data from FILE into TABLE",
12266 " --ascii Use \\037 and \\036 as column and row separators",
12267 " --csv Use , and \\n as column and row separators",
12268 " --skip N Skip the first N rows of input",
12269 " -v \"Verbose\" - increase auxiliary output",
12271 " * If TABLE does not exist, it is created. The first row of input",
12272 " determines the column names.",
12273 " * If neither --csv or --ascii are used, the input mode is derived",
12274 " from the \".mode\" output mode",
12275 " * If FILE begins with \"|\" then it is a command that generates the",
12277 #ifndef SQLITE_OMIT_TEST_CONTROL
12278 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
12280 ".indexes ?TABLE? Show names of indexes",
12281 " If TABLE is specified, only show indexes for",
12282 " tables matching TABLE using the LIKE operator.",
12283 #ifdef SQLITE_ENABLE_IOTRACE
12284 ".iotrace FILE Enable I/O diagnostic logging to FILE",
12286 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
12287 ".lint OPTIONS Report potential schema issues.",
12289 " fkey-indexes Find missing foreign key indexes",
12290 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12291 ".load FILE ?ENTRY? Load an extension library",
12293 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
12294 ".mode MODE ?TABLE? Set output mode",
12295 " MODE is one of:",
12296 " ascii Columns/rows delimited by 0x1F and 0x1E",
12297 " csv Comma-separated values",
12298 " column Left-aligned columns. (See .width)",
12299 " html HTML <table> code",
12300 " insert SQL insert statements for TABLE",
12301 " line One value per line",
12302 " list Values delimited by \"|\"",
12303 " quote Escape answers as for SQL",
12304 " tabs Tab-separated values",
12305 " tcl TCL list elements",
12306 ".nullvalue STRING Use STRING in place of NULL values",
12307 ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE",
12308 " If FILE begins with '|' then open as a pipe",
12309 " --bom Put a UTF8 byte-order mark at the beginning",
12310 " -e Send output to the system text editor",
12311 " -x Send output as CSV to a spreadsheet (same as \".excel\")",
12312 #ifdef SQLITE_DEBUG
12313 ".oom [--repeat M] [N] Simulate an OOM error on the N-th allocation",
12315 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
12317 " --append Use appendvfs to append database to the end of FILE",
12318 #ifdef SQLITE_ENABLE_DESERIALIZE
12319 " --deserialize Load into memory useing sqlite3_deserialize()",
12320 " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
12321 " --maxsize N Maximum size for --hexdb or --deserialized database",
12323 " --new Initialize FILE to an empty database",
12324 " --nofollow Do not follow symbolic links",
12325 " --readonly Open FILE readonly",
12326 " --zip FILE is a ZIP archive",
12327 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
12328 " If FILE begins with '|' then open it as a pipe.",
12330 " --bom Prefix output with a UTF8 byte-order mark",
12331 " -e Send output to the system text editor",
12332 " -x Send output as CSV to a spreadsheet",
12333 ".parameter CMD ... Manage SQL parameter bindings",
12334 " clear Erase all bindings",
12335 " init Initialize the TEMP table that holds bindings",
12336 " list List the current parameter bindings",
12337 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
12338 " PARAMETER should start with one of: $ : @ ?",
12339 " unset PARAMETER Remove PARAMETER from the binding table",
12340 ".print STRING... Print literal STRING",
12341 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
12342 ".progress N Invoke progress handler after every N opcodes",
12343 " --limit N Interrupt after N progress callbacks",
12344 " --once Do no more than one progress interrupt",
12345 " --quiet|-q No output except at interrupts",
12346 " --reset Reset the count for each input and interrupt",
12348 ".prompt MAIN CONTINUE Replace the standard prompts",
12349 ".quit Exit this program",
12350 ".read FILE Read input from FILE",
12351 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
12352 ".recover Recover as much data as possible from corrupt db.",
12353 " --freelist-corrupt Assume the freelist is corrupt",
12354 " --recovery-db NAME Store recovery metadata in database file NAME",
12355 " --lost-and-found TABLE Alternative name for the lost-and-found table",
12356 " --no-rowids Do not attempt to recover rowid values",
12357 " that are not also INTEGER PRIMARY KEYs",
12359 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
12360 ".save FILE Write in-memory database into FILE",
12361 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
12362 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
12364 " --indent Try to pretty-print the schema",
12365 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
12367 " --init Create a new SELFTEST table",
12368 " -v Verbose output",
12369 ".separator COL ?ROW? Change the column and row separators",
12370 #if defined(SQLITE_ENABLE_SESSION)
12371 ".session ?NAME? CMD ... Create or control sessions",
12373 " attach TABLE Attach TABLE",
12374 " changeset FILE Write a changeset into FILE",
12375 " close Close one session",
12376 " enable ?BOOLEAN? Set or query the enable bit",
12377 " filter GLOB... Reject tables matching GLOBs",
12378 " indirect ?BOOLEAN? Mark or query the indirect status",
12379 " isempty Query whether the session is empty",
12380 " list List currently open session names",
12381 " open DB NAME Open a new session on DB",
12382 " patchset FILE Write a patchset into FILE",
12383 " If ?NAME? is omitted, the first defined session is used.",
12385 ".sha3sum ... Compute a SHA3 hash of database content",
12387 " --schema Also hash the sqlite_master table",
12388 " --sha3-224 Use the sha3-224 algorithm",
12389 " --sha3-256 Use the sha3-256 algorithm (default)",
12390 " --sha3-384 Use the sha3-384 algorithm",
12391 " --sha3-512 Use the sha3-512 algorithm",
12392 " Any other argument is a LIKE pattern for tables to hash",
12393 #ifndef SQLITE_NOHAVE_SYSTEM
12394 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
12396 ".show Show the current values for various settings",
12397 ".stats ?on|off? Show stats or turn stats on or off",
12398 #ifndef SQLITE_NOHAVE_SYSTEM
12399 ".system CMD ARGS... Run CMD ARGS... in a system shell",
12401 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
12402 ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
12403 ".testctrl CMD ... Run various sqlite3_test_control() operations",
12404 " Run \".testctrl\" with no arguments for details",
12405 ".timeout MS Try opening locked tables for MS milliseconds",
12406 ".timer on|off Turn SQL timer on or off",
12407 #ifndef SQLITE_OMIT_TRACE
12408 ".trace ?OPTIONS? Output each SQL statement as it is run",
12409 " FILE Send output to FILE",
12410 " stdout Send output to stdout",
12411 " stderr Send output to stderr",
12412 " off Disable tracing",
12413 " --expanded Expand query parameters",
12414 #ifdef SQLITE_ENABLE_NORMALIZE
12415 " --normalized Normal the SQL statements",
12417 " --plain Show SQL as it is input",
12418 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
12419 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
12420 " --row Trace each row (SQLITE_TRACE_ROW)",
12421 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
12423 #ifdef SQLITE_DEBUG
12424 ".unmodule NAME ... Unregister virtual table modules",
12425 " --allexcept Unregister everything except those named",
12427 ".vfsinfo ?AUX? Information about the top-level VFS",
12428 ".vfslist List all available VFSes",
12429 ".vfsname ?AUX? Print the name of the VFS stack",
12430 ".width NUM1 NUM2 ... Set column widths for \"column\" mode",
12431 " Negative values right-justify",
12443 static int showHelp(FILE *out,
const char *zPattern){
12449 || zPattern[0]==
'0'
12450 || strcmp(zPattern,
"-a")==0
12451 || strcmp(zPattern,
"-all")==0
12452 || strcmp(zPattern,
"--all")==0
12455 if( zPattern==0 ) zPattern =
"";
12457 if(
azHelp[i][0]==
'.' || zPattern[0] ){
12488 if(
azHelp[i][0]==
'.' ) j = i;
12523 FILE *in = fopen(
zName,
"rb");
12527 if( in==0 )
return 0;
12532 if( pBuf==0 ){ fclose(in);
return 0; }
12533 nRead = fread(pBuf, nIn, 1, in);
12540 if( pnByte ) *pnByte = nIn;
12544 #if defined(SQLITE_ENABLE_SESSION)
12549 static void session_close(OpenSession *pSession){
12551 sqlite3session_delete(pSession->p);
12553 for(i=0; i<pSession->nFilter; i++){
12557 memset(pSession, 0,
sizeof(OpenSession));
12564 #if defined(SQLITE_ENABLE_SESSION)
12567 for(i=0; i<p->nSession; i++){
12568 session_close(&p->aSession[i]);
12573 # define session_close_all(X)
12580 #if defined(SQLITE_ENABLE_SESSION)
12581 static int session_filter(
void *pCtx,
const char *zTab){
12582 OpenSession *pSession = (OpenSession*)pCtx;
12584 for(i=0; i<pSession->nFilter; i++){
12601 FILE *f = fopen(
zName,
"rb");
12612 n = fread(zBuf, 16, 1, f);
12613 if( n==1 && memcmp(zBuf,
"SQLite format 3", 16)==0 ){
12618 n = fread(zBuf, 25, 1, f);
12619 if( n==1 && memcmp(zBuf,
"Start-Of-SQLite3-", 17)==0 ){
12623 n = fread(zBuf, 22, 1, f);
12624 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
12625 && zBuf[3]==0x06 ){
12635 #ifdef SQLITE_ENABLE_DESERIALIZE
12641 static unsigned char *readHexDb(
ShellState *p,
int *pnData){
12642 unsigned char *a = 0;
12650 unsigned int x[16];
12662 if( in==0 ) in = stdin;
12666 if( fgets(zLine,
sizeof(zLine), in)==0 )
goto readHexDb_error;
12667 rc = sscanf(zLine,
"| size %d pagesize %d", &n, &pgsz);
12668 if( rc!=2 )
goto readHexDb_error;
12669 if( n<0 )
goto readHexDb_error;
12670 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 )
goto readHexDb_error;
12671 n = (n+pgsz-1)&~(pgsz-1);
12675 goto readHexDb_error;
12678 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
12680 goto readHexDb_error;
12682 for(nLine++; fgets(zLine,
sizeof(zLine), in)!=0; nLine++){
12683 rc = sscanf(zLine,
"| page %d offset %d", &j, &k);
12688 if( strncmp(zLine,
"| end ", 6)==0 ){
12691 rc = sscanf(zLine,
"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
12692 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
12693 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
12698 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
12714 while( fgets(zLine,
sizeof(zLine), p->
in)!=0 ){
12716 if(strncmp(zLine,
"| end ", 6)==0 )
break;
12721 utf8_printf(stderr,
"Error on line %d of --hexdb input\n", nLine);
12737 const unsigned char *pBlob;
12746 if( iInt>=0 && (iInt+1)*4<=nBlob ){
12747 const unsigned char *a = &pBlob[iInt*4];
12793 if( zText[0]==
'\'' ){
12798 const char *zNL = 0;
12799 const char *zCR = 0;
12803 for(i=0; zText[i]; i++){
12804 if( zNL==0 && zText[i]==
'\n' ){
12806 nNL = (int)strlen(zNL);
12808 if( zCR==0 && zText[i]==
'\r' ){
12810 nCR = (int)strlen(zCR);
12816 i64 nMax = (nNL > nCR) ? nNL : nCR;
12817 i64 nAlloc = nMax * nText + (nMax+64)*2;
12825 memcpy(&zOut[iOut],
"replace(replace(", 16);
12828 memcpy(&zOut[iOut],
"replace(", 8);
12831 for(i=0; zText[i]; i++){
12832 if( zText[i]==
'\n' ){
12833 memcpy(&zOut[iOut], zNL, nNL);
12835 }
else if( zText[i]==
'\r' ){
12836 memcpy(&zOut[iOut], zCR, nCR);
12839 zOut[iOut] = zText[i];
12845 memcpy(&zOut[iOut],
",'", 2); iOut += 2;
12846 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
12847 memcpy(&zOut[iOut],
"', char(10))", 12); iOut += 12;
12850 memcpy(&zOut[iOut],
",'", 2); iOut += 2;
12851 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
12852 memcpy(&zOut[iOut],
"', char(13))", 12); iOut += 12;
12874 #define OPEN_DB_KEEPALIVE 0x001
12875 #define OPEN_DB_ZIPFILE 0x002
12920 utf8_printf(stderr,
"Error: unable to open database \"%s\": %s\n",
12928 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12935 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
12936 sqlite3_dbdata_init(p->
db, 0, 0);
12938 #ifdef SQLITE_HAVE_ZLIB
12939 sqlite3_zipfile_init(p->
db, 0, 0);
12940 sqlite3_sqlar_init(p->
db, 0, 0);
12954 #ifndef SQLITE_NOHAVE_SYSTEM
12962 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->
zDbFilename);
12966 #ifdef SQLITE_ENABLE_DESERIALIZE
12971 unsigned char *aData;
12975 aData = readHexDb(p, &nData);
12984 utf8_printf(stderr,
"Error: sqlite3_deserialize() returns %d\n", rc);
13000 utf8_printf(stderr,
"Error: sqlite3_close() returns %d: %s\n",
13005 #if HAVE_READLINE || HAVE_EDITLINE
13009 static char *readline_completion_generator(
const char *text,
int state){
13016 " FROM completion(%Q) ORDER BY 1", text);
13029 static char **readline_completion(
const char *zText,
int iStart,
int iEnd){
13030 rl_attempted_completion_over = 1;
13031 return rl_completion_matches(zText, readline_completion_generator);
13034 #elif HAVE_LINENOISE
13038 static void linenoise_completion(
const char *zLine, linenoiseCompletions *lc){
13045 if( nLine>
sizeof(zBuf)-30 )
return;
13046 if( zLine[0]==
'.' || zLine[0]==
'#')
return;
13047 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]==
'_'); i--){}
13048 if( i==nLine-1 )
return;
13050 memcpy(zBuf, zLine, iStart);
13052 " FROM completion(%Q,%Q) ORDER BY 1",
13053 &zLine[iStart], zLine);
13060 if( iStart+nCompletion <
sizeof(zBuf)-1 ){
13061 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
13062 linenoiseAddCompletion(lc, zBuf);
13088 while( *z && *z!=
'\\' ) z++;
13089 for(i=j=0; (c = z[i])!=0; i++, j++){
13090 if( c==
'\\' && z[i+1]!=0 ){
13094 }
else if( c==
'b' ){
13096 }
else if( c==
't' ){
13098 }
else if( c==
'n' ){
13100 }
else if( c==
'v' ){
13102 }
else if( c==
'f' ){
13104 }
else if( c==
'r' ){
13106 }
else if( c==
'"' ){
13108 }
else if( c==
'\'' ){
13110 }
else if( c==
'\\' ){
13112 }
else if( c>=
'0' && c<=
'7' ){
13114 if( z[i+1]>=
'0' && z[i+1]<=
'7' ){
13116 c = (c<<3) + z[i] -
'0';
13117 if( z[i+1]>=
'0' && z[i+1]<=
'7' ){
13119 c = (c<<3) + z[i] -
'0';
13126 if( j<i ) z[j] = 0;
13135 if( zArg[0]==
'0' && zArg[1]==
'x' ){
13138 for(i=0; zArg[i]>=
'0' && zArg[i]<=
'9'; i++){}
13140 if( i>0 && zArg[i]==0 )
return (
int)(
integerValue(zArg) & 0xffffffff);
13147 utf8_printf(stderr,
"ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
13167 if( f && f!=stdout && f!=stderr ) fclose(f);
13177 if( strcmp(zFile,
"stdout")==0 ){
13179 }
else if( strcmp(zFile,
"stderr")==0 ){
13181 }
else if( strcmp(zFile,
"off")==0 ){
13184 f = fopen(zFile, bTextMode ?
"w" :
"wb");
13186 utf8_printf(stderr,
"Error: cannot open \"%s\"\n", zFile);
13192 #ifndef SQLITE_OMIT_TRACE
13212 zSql = (
const char*)pX;
13220 #ifdef SQLITE_ENABLE_NORMALIZE
13232 if( zSql==0 )
return 0;
13234 while( nSql>0 && zSql[nSql-1]==
';' ){ nSql--; }
13256 static int nCall = 0;
13286 p->
z[p->
n++] = (char)c;
13314 int startLine = p->
nLine;
13319 if( c==rSep ) p->
nLine++;
13326 if( (c==cSep && pc==cQuote)
13327 || (c==rSep && pc==cQuote)
13328 || (c==rSep && pc==
'\r' && ppc==cQuote)
13329 || (c==EOF && pc==cQuote)
13331 do{ p->
n--; }
while( p->
z[p->
n]!=cQuote );
13335 if( pc==cQuote && c!=
'\r' ){
13336 utf8_printf(stderr,
"%s:%d: unescaped %c character\n",
13340 utf8_printf(stderr,
"%s:%d: unterminated %c-quoted field\n",
13341 p->
zFile, startLine, cQuote);
13352 if( (c&0xff)==0xef && p->
bNotFirst==0 ){
13355 if( (c&0xff)==0xbb ){
13358 if( (c&0xff)==0xbf ){
13365 while( c!=EOF && c!=cSep && c!=rSep ){
13371 if( p->
n>0 && p->
z[p->
n-1]==
'\r' ) p->
n--;
13375 if( p->
z ) p->
z[p->
n] = 0;
13402 while( c!=EOF && c!=cSep && c!=rSep ){
13410 if( p->
z ) p->
z[p->
n] = 0;
13433 const int spinRate = 10000;
13441 goto end_data_xfer;
13447 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
13449 for(j=1; j<n; j++){
13450 memcpy(zInsert+i,
",?", 2);
13453 memcpy(zInsert+i,
");", 3);
13459 goto end_data_xfer;
13461 for(k=0; k<2; k++){
13463 for(i=0; i<n; i++){
13498 if( (cnt%spinRate)==0 ){
13499 printf(
"%c\b",
"|/-\\"[(cnt/spinRate)%4]);
13506 zQuery =
sqlite3_mprintf(
"SELECT * FROM \"%w\" ORDER BY rowid DESC;",
13510 utf8_printf(stderr,
"Warning: cannot step \"%s\" backwards", zTable);
13532 const char *zWhere,
13538 const unsigned char *
zName;
13539 const unsigned char *zSql;
13543 " WHERE %s", zWhere);
13549 goto end_schema_xfer;
13554 printf(
"%s... ",
zName); fflush(stdout);
13555 sqlite3_exec(newDb, (
const char*)zSql, 0, 0, &zErrMsg);
13557 utf8_printf(stderr,
"Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
13562 xForEach(p, newDb, (
const char*)
zName);
13570 " WHERE %s ORDER BY rowid DESC", zWhere);
13576 goto end_schema_xfer;
13581 printf(
"%s... ",
zName); fflush(stdout);
13582 sqlite3_exec(newDb, (
const char*)zSql, 0, 0, &zErrMsg);
13584 utf8_printf(stderr,
"Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
13589 xForEach(p, newDb, (
const char*)
zName);
13607 if( access(zNewDb,0)==0 ){
13608 utf8_printf(stderr,
"File \"%s\" already exists.\n", zNewDb);
13613 utf8_printf(stderr,
"Cannot create output database: %s\n",
13635 #ifndef SQLITE_OMIT_POPEN
13640 #ifndef SQLITE_NOHAVE_SYSTEM
13642 const char *zXdgOpenCmd =
13643 #if defined(_WIN32)
13645 #elif defined(__APPLE__)
13652 if( system(zCmd) ){
13687 static unsigned int get2byteInt(
unsigned char *a){
13688 return (a[0]<<8) + a[1];
13690 static unsigned int get4byteInt(
unsigned char *a){
13691 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
13700 static const struct {
const char *
zName;
int ofst; } aField[] = {
13701 {
"file change counter:", 24 },
13702 {
"database page count:", 28 },
13703 {
"freelist page count:", 36 },
13704 {
"schema cookie:", 40 },
13705 {
"schema format:", 44 },
13706 {
"default cache size:", 48 },
13707 {
"autovacuum top root:", 52 },
13708 {
"incremental vacuum:", 64 },
13709 {
"text encoding:", 56 },
13710 {
"user version:", 60 },
13711 {
"application id:", 68 },
13712 {
"software version:", 96 },
13714 static const struct {
const char *
zName;
const char *zSql; } aQuery[] = {
13715 {
"number of tables:",
13716 "SELECT count(*) FROM %s WHERE type='table'" },
13717 {
"number of indexes:",
13718 "SELECT count(*) FROM %s WHERE type='index'" },
13719 {
"number of triggers:",
13720 "SELECT count(*) FROM %s WHERE type='trigger'" },
13721 {
"number of views:",
13722 "SELECT count(*) FROM %s WHERE type='view'" },
13724 "SELECT total(length(sql)) FROM %s" },
13727 unsigned iDataVersion;
13729 char *zDb = nArg>=2 ? azArg[1] :
"main";
13731 unsigned char aHdr[100];
13733 if( p->
db==0 )
return 1;
13735 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
13749 raw_printf(stderr,
"unable to read database header\n");
13754 if( i==1 ) i = 65536;
13760 int ofst = aField[i].ofst;
13774 }
else if( strcmp(zDb,
"temp")==0 ){
13781 int val =
db_int(p, zSql);
13787 utf8_printf(p->
out,
"%-20s %u\n",
"data version", iDataVersion);
13823 static int testcase_glob(
const char *zGlob,
const char *z){
13828 while( (c = (*(zGlob++)))!=0 ){
13831 while(
IsSpace(*zGlob) ) zGlob++;
13833 }
else if( c==
'*' ){
13834 while( (c=(*(zGlob++))) ==
'*' || c==
'?' ){
13835 if( c==
'?' && (*(z++))==0 )
return 0;
13839 }
else if( c==
'[' ){
13845 while( (c2 = (*(z++)))!=0 ){
13848 if( c2==0 )
return 0;
13853 }
else if( c==
'?' ){
13854 if( (*(z++))==0 )
return 0;
13855 }
else if( c==
'[' ){
13860 if( c==0 )
return 0;
13867 if( c==
']' ) seen = 1;
13870 while( c2 && c2!=
']' ){
13871 if( c2==
'-' && zGlob[0]!=
']' && zGlob[0]!=0 && prior_c>0 ){
13873 if( c>=prior_c && c<=c2 ) seen = 1;
13883 if( c2==0 || (seen ^ invert)==0 )
return 0;
13884 }
else if( c==
'#' ){
13885 if( (z[0]==
'-' || z[0]==
'+') &&
IsDigit(z[1]) ) z++;
13886 if( !
IsDigit(z[0]) )
return 0;
13888 while(
IsDigit(z[0]) ){ z++; }
13890 if( c!=(*(z++)) )
return 0;
13902 static int optionMatch(
const char *zStr,
const char *zOpt){
13903 if( zStr[0]!=
'-' )
return 0;
13905 if( zStr[0]==
'-' ) zStr++;
13906 return strcmp(zStr, zOpt)==0;
13915 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
13919 rc = unlink(zFilename);
13952 zTemp = getenv(
"TEMP");
13953 if( zTemp==0 ) zTemp = getenv(
"TMP");
13993 const char *zParent;
13994 const char *zParentCol;
13995 const char *zParentSeq;
13996 const char *zChild;
13997 const char *zChildCol;
13998 const char *zChildSeq = 0;
14009 db,
"main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
14013 db,
"main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
14034 FILE *out = pState->
out;
14036 int bGroupByParent = 0;
14038 const char *zIndent =
"";
14079 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
14080 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
14081 " || fkey_collate_clause("
14082 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
14084 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
14085 " || group_concat('*=?', ' AND ') || ')'"
14087 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
14089 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
14091 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
14092 " || ' ON ' || quote(s.name) || '('"
14093 " || group_concat(quote(f.[from]) ||"
14094 " fkey_collate_clause("
14095 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
14099 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
14100 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
14101 "GROUP BY s.name, f.id "
14102 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
14104 const char *zGlobIPK =
"SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
14106 for(i=2; i<nArg; i++){
14112 bGroupByParent = 1;
14116 raw_printf(stderr,
"Usage: %s %s ?-verbose? ?-groupbyparent?\n",
14162 raw_printf(stderr,
"Error: internal error");
14166 && (bVerbose || res==0)
14169 raw_printf(out,
"-- Parent table %s\n", zParent);
14175 raw_printf(out,
"%s%s --> %s\n", zIndent, zCI, zTarget);
14176 }
else if( bVerbose ){
14177 raw_printf(out,
"%s/* no extra indexes required for %s -> %s */\n",
14178 zIndent, zFrom, zTarget
14210 n = (nArg>=2 ?
strlen30(azArg[1]) : 0);
14215 raw_printf(stderr,
"Usage %s sub-command ?switches...?\n", azArg[0]);
14216 raw_printf(stderr,
"Where sub-commands are:\n");
14221 #if !defined SQLITE_OMIT_VIRTUALTABLE
14258 va_start(ap, zFmt);
14313 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
14320 typedef struct ArCommand ArCommand;
14340 static int arUsage(FILE *f){
14349 static int arErrorMsg(ArCommand *pAr,
const char *zFmt, ...){
14352 va_start(ap, zFmt);
14356 if( pAr->fromCmdLine ){
14357 utf8_printf(stderr,
"Use \"-A\" for more help\n");
14359 utf8_printf(stderr,
"Use \".archive --help\" for more help\n");
14368 #define AR_CMD_CREATE 1
14369 #define AR_CMD_UPDATE 2
14370 #define AR_CMD_INSERT 3
14371 #define AR_CMD_EXTRACT 4
14372 #define AR_CMD_LIST 5
14373 #define AR_CMD_HELP 6
14378 #define AR_SWITCH_VERBOSE 7
14379 #define AR_SWITCH_FILE 8
14380 #define AR_SWITCH_DIRECTORY 9
14381 #define AR_SWITCH_APPEND 10
14382 #define AR_SWITCH_DRYRUN 11
14384 static int arProcessSwitch(ArCommand *pAr,
int eSwitch,
const char *zArg){
14386 case AR_CMD_CREATE:
14387 case AR_CMD_EXTRACT:
14389 case AR_CMD_UPDATE:
14390 case AR_CMD_INSERT:
14393 return arErrorMsg(pAr,
"multiple command options");
14395 pAr->eCmd = eSwitch;
14398 case AR_SWITCH_DRYRUN:
14401 case AR_SWITCH_VERBOSE:
14404 case AR_SWITCH_APPEND:
14407 case AR_SWITCH_FILE:
14410 case AR_SWITCH_DIRECTORY:
14424 static int arParseCommand(
14435 {
"create",
'c', AR_CMD_CREATE, 0 },
14436 {
"extract",
'x', AR_CMD_EXTRACT, 0 },
14437 {
"insert",
'i', AR_CMD_INSERT, 0 },
14438 {
"list",
't', AR_CMD_LIST, 0 },
14439 {
"update",
'u', AR_CMD_UPDATE, 0 },
14440 {
"help",
'h', AR_CMD_HELP, 0 },
14441 {
"verbose",
'v', AR_SWITCH_VERBOSE, 0 },
14442 {
"file",
'f', AR_SWITCH_FILE, 1 },
14443 {
"append",
'a', AR_SWITCH_APPEND, 1 },
14444 {
"directory",
'C', AR_SWITCH_DIRECTORY, 1 },
14445 {
"dryrun",
'n', AR_SWITCH_DRYRUN, 0 },
14447 int nSwitch =
sizeof(aSwitch) /
sizeof(
struct ArSwitch);
14448 struct ArSwitch *pEnd = &aSwitch[nSwitch];
14451 utf8_printf(stderr,
"Wrong number of arguments. Usage:\n");
14452 return arUsage(stderr);
14454 char *z = azArg[1];
14459 for(i=0; z[i]; i++){
14460 const char *zArg = 0;
14461 struct ArSwitch *pOpt;
14462 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
14463 if( z[i]==pOpt->cShort )
break;
14466 return arErrorMsg(pAr,
"unrecognized option: %c", z[i]);
14470 return arErrorMsg(pAr,
"option requires an argument: %c",z[i]);
14472 zArg = azArg[iArg++];
14474 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) )
return SQLITE_ERROR;
14476 pAr->nArg = nArg-iArg;
14478 pAr->azArg = &azArg[iArg];
14483 for(iArg=1; iArg<nArg; iArg++){
14488 pAr->azArg = &azArg[iArg];
14489 pAr->nArg = nArg-iArg;
14497 for(i=1; i<n; i++){
14498 const char *zArg = 0;
14499 struct ArSwitch *pOpt;
14500 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
14501 if( z[i]==pOpt->cShort )
break;
14504 return arErrorMsg(pAr,
"unrecognized option: %c", z[i]);
14511 if( iArg>=(nArg-1) ){
14512 return arErrorMsg(pAr,
"option requires an argument: %c",
14515 zArg = azArg[++iArg];
14518 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) )
return SQLITE_ERROR;
14520 }
else if( z[2]==
'\0' ){
14523 pAr->azArg = &azArg[iArg+1];
14524 pAr->nArg = nArg-iArg-1;
14528 const char *zArg = 0;
14529 struct ArSwitch *pMatch = 0;
14530 struct ArSwitch *pOpt;
14531 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
14532 const char *zLong = pOpt->zLong;
14533 if( (n-2)<=
strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
14535 return arErrorMsg(pAr,
"ambiguous option: %s",z);
14543 return arErrorMsg(pAr,
"unrecognized option: %s", z);
14545 if( pMatch->bArg ){
14546 if( iArg>=(nArg-1) ){
14547 return arErrorMsg(pAr,
"option requires an argument: %s", z);
14549 zArg = azArg[++iArg];
14551 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) )
return SQLITE_ERROR;
14572 static int arCheckEntries(ArCommand *pAr){
14579 "SELECT name FROM %s WHERE name=$name",
14583 for(i=0; i<pAr->nArg && rc==
SQLITE_OK; i++){
14584 char *z = pAr->azArg[i];
14587 while( n>0 && z[n-1]==
'/' ) n--;
14595 utf8_printf(stderr,
"not found in archive: %s\n", z);
14611 static void arWhereClause(
14618 if( pAr->nArg==0 ){
14622 const char *zSep =
"";
14623 for(i=0; i<pAr->nArg; i++){
14624 const char *z = pAr->azArg[i];
14626 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
14643 static int arListCommand(ArCommand *pAr){
14644 const char *zSql =
"SELECT %s FROM %s WHERE %s";
14645 const char *azCols[] = {
14647 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
14654 rc = arCheckEntries(pAr);
14655 arWhereClause(&rc, pAr, &zWhere);
14658 pAr->zSrcTable, zWhere);
14659 if( pAr->bDryRun ){
14663 if( pAr->bVerbose ){
14684 static int arExtractCommand(ArCommand *pAr){
14685 const char *zSql1 =
14688 " writefile(($dir || name), %s, mode, mtime) "
14689 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
14690 " AND name NOT GLOB '*..[/\\]*'";
14692 const char *azExtraArg[] = {
14693 "sqlar_uncompress(data, sz)",
14706 rc = arCheckEntries(pAr);
14707 arWhereClause(&rc, pAr, &zWhere);
14719 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
14731 for(i=0; i<2; i++){
14734 if( pAr->bDryRun ){
14738 if( i==0 && pAr->bVerbose ){
14756 static int arExecSql(ArCommand *pAr,
const char *zSql){
14758 if( pAr->bDryRun ){
14791 static int arCreateOrUpdateCommand(
14796 const char *zCreate =
14797 "CREATE TABLE IF NOT EXISTS sqlar(\n"
14798 " name TEXT PRIMARY KEY, -- name of the file\n"
14799 " mode INT, -- access permissions\n"
14800 " mtime INT, -- last modification time\n"
14801 " sz INT, -- original file size\n"
14802 " data BLOB -- compressed content\n"
14804 const char *zDrop =
"DROP TABLE IF EXISTS sqlar";
14805 const char *zInsertFmt[2] = {
14806 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
14811 " CASE substr(lsmode(mode),1,1)\n"
14812 " WHEN '-' THEN length(data)\n"
14813 " WHEN 'd' THEN 0\n"
14815 " sqlar_compress(data)\n"
14816 " FROM fsdir(%Q,%Q) AS disk\n"
14817 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
14819 "REPLACE INTO %s(name,mode,mtime,data)\n"
14825 " FROM fsdir(%Q,%Q) AS disk\n"
14826 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
14830 const char *zTab = 0;
14835 arExecSql(pAr,
"PRAGMA page_size=512");
14836 rc = arExecSql(pAr,
"SAVEPOINT ar;");
14847 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
14850 rc = arExecSql(pAr, zSql);
14859 rc = arExecSql(pAr, zDrop);
14860 if( rc!=
SQLITE_OK )
goto end_ar_transaction;
14862 rc = arExecSql(pAr, zCreate);
14864 if( bOnlyIfChanged ){
14867 "SELECT 1 FROM %s AS mem"
14868 " WHERE mem.name=disk.name"
14869 " AND mem.mtime=disk.mtime"
14870 " AND mem.mode=disk.mode)", zTab);
14875 for(i=0; i<pAr->nArg && rc==
SQLITE_OK; i++){
14877 pAr->bVerbose ?
"shell_putsnl(name)" :
"name",
14878 pAr->azArg[i], pAr->zDir, zExists);
14879 rc = arExecSql(pAr, zSql2);
14882 end_ar_transaction:
14884 sqlite3_exec(pAr->db,
"ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
14886 rc = arExecSql(pAr,
"RELEASE ar;");
14887 if( pAr->bZip && pAr->zFile ){
14889 arExecSql(pAr, zSql);
14900 static int arDotCommand(
14908 memset(&cmd, 0,
sizeof(cmd));
14909 cmd.fromCmdLine = fromCmdLine;
14910 rc = arParseCommand(azArg, nArg, &cmd);
14914 cmd.
db = pState->
db;
14921 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
14922 if( cmd.zFile==0 ){
14929 }
else if( cmd.zFile ){
14932 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
14933 || cmd.eCmd==AR_CMD_UPDATE ){
14940 utf8_printf(pState->
out,
"-- open database '%s'%s\n", cmd.zFile,
14946 utf8_printf(stderr,
"cannot open file: %s (%s)\n",
14949 goto end_ar_command;
14952 sqlite3_sqlar_init(cmd.db, 0, 0);
14957 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
14958 if( cmd.eCmd!=AR_CMD_CREATE
14961 utf8_printf(stderr,
"database does not contain an 'sqlar' table\n");
14963 goto end_ar_command;
14968 switch( cmd.eCmd ){
14969 case AR_CMD_CREATE:
14970 rc = arCreateOrUpdateCommand(&cmd, 0, 0);
14973 case AR_CMD_EXTRACT:
14974 rc = arExtractCommand(&cmd);
14978 rc = arListCommand(&cmd);
14982 arUsage(pState->
out);
14985 case AR_CMD_INSERT:
14986 rc = arCreateOrUpdateCommand(&cmd, 1, 0);
14990 assert( cmd.eCmd==AR_CMD_UPDATE );
14991 rc = arCreateOrUpdateCommand(&cmd, 1, 1);
14996 if( cmd.db!=pState->
db ){
15007 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
15014 static void shellExec(
sqlite3 *db,
int *pRc,
const char *zSql){
15020 raw_printf(stderr,
"SQL error: %s\n", zErr);
15029 static void shellExecPrintf(
sqlite3 *db,
int *pRc,
const char *zFmt, ...){
15033 va_start(ap, zFmt);
15039 shellExec(db, pRc, z);
15058 memset(pRet, 0, nByte);
15075 static char *shellMPrintf(
int *pRc,
const char *zFmt, ...){
15079 va_start(ap, zFmt);
15094 typedef struct RecoverTable RecoverTable;
15095 struct RecoverTable {
15106 static void recoverFreeTable(RecoverTable *pTab){
15109 if( pTab->azlCol ){
15111 for(i=0; i<=pTab->nCol; i++){
15127 static RecoverTable *recoverNewTable(
15136 RecoverTable *pTab = 0;
15138 pTab = (RecoverTable*)shellMalloc(&rc,
sizeof(RecoverTable));
15141 int bSqlIntkey = 0;
15150 rc =
sqlite3_exec(dbtmp,
"PRAGMA writable_schema = on", 0, 0, 0);
15160 "SELECT count(*) FROM pragma_table_info(%Q)",
zName
15173 " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
15174 ") FROM sqlite_master WHERE name = %Q",
zName
15181 if( bIntkey==bSqlIntkey ){
15183 const char *zPk =
"_rowid_";
15194 "SELECT cid, name FROM pragma_table_info(%Q) "
15195 " WHERE pk=1 AND type='integer' COLLATE nocase"
15196 " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
15205 pTab->zQuoted = shellMPrintf(&rc,
"\"%w\"",
zName);
15206 pTab->azlCol = (
char**)shellMalloc(&rc,
sizeof(
char*) * (nSqlCol+1));
15207 pTab->nCol = nSqlCol;
15210 pTab->azlCol[0] = shellMPrintf(&rc,
"\"%w\"", zPk);
15212 pTab->azlCol[0] = shellMPrintf(&rc,
"");
15216 "SELECT %Q || group_concat(shell_idquote(name), ', ') "
15217 " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
15218 "FROM pragma_table_info(%Q)",
15219 bIntkey ?
", " :
"", pTab->iPk,
15220 bIntkey ?
"" :
"(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
15225 pTab->azlCol[i] = shellMPrintf(&rc,
"%s%s", pTab->azlCol[0], zText);
15237 if( rc!=
SQLITE_OK || (pTab && pTab->zQuoted==0) ){
15238 recoverFreeTable(pTab);
15259 static RecoverTable *recoverFindTable(
15268 RecoverTable *pRet = 0;
15270 const char *zSql = 0;
15271 const char *
zName = 0;
15275 "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
15286 pRet = recoverNewTable(pRc,
zName, zSql, bIntkey, nCol);
15299 static RecoverTable *recoverOrphanTable(
15302 const char *zLostAndFound,
15305 RecoverTable *pTab = 0;
15314 char *zTab = shellMPrintf(pRc,
"%s", zLostAndFound);
15317 "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
15323 zTab = shellMPrintf(pRc,
"%s_%d", zLostAndFound, iTab++);
15328 pTab = (RecoverTable*)shellMalloc(pRc,
sizeof(RecoverTable));
15330 pTab->zQuoted = shellMPrintf(pRc,
"\"%w\"", zTab);
15334 pTab->azlCol = (
char**)shellMalloc(pRc,
sizeof(
char*) * (nCol+1));
15335 if( pTab->azlCol ){
15336 pTab->azlCol[nCol] = shellMPrintf(pRc,
"");
15337 for(i=nCol-1; i>=0; i--){
15338 pTab->azlCol[i] = shellMPrintf(pRc,
"%s, NULL", pTab->azlCol[i+1]);
15344 recoverFreeTable(pTab);
15348 "CREATE TABLE %s(rootpgno INTEGER, "
15349 "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
15351 for(i=0; i<nCol; i++){
15367 static int recoverDatabaseCmd(
ShellState *pState,
int nArg,
char **azArg){
15372 const char *zRecoveryDb =
"";
15373 const char *zLostAndFound =
"lost_and_found";
15376 RecoverTable *pOrphan = 0;
15380 for(i=1; i<nArg; i++){
15381 char *z = azArg[i];
15383 if( z[0]==
'-' && z[1]==
'-' ) z++;
15385 if( n<=17 && memcmp(
"-freelist-corrupt", z, n)==0 ){
15388 if( n<=12 && memcmp(
"-recovery-db", z, n)==0 && i<(nArg-1) ){
15390 zRecoveryDb = azArg[i];
15392 if( n<=15 && memcmp(
"-lost-and-found", z, n)==0 && i<(nArg-1) ){
15394 zLostAndFound = azArg[i];
15396 if( n<=10 && memcmp(
"-no-rowids", z, n)==0 ){
15400 utf8_printf(stderr,
"unexpected option: %s\n", azArg[i]);
15406 shellExecPrintf(pState->
db, &rc,
15409 "PRAGMA writable_schema = on;"
15410 "ATTACH %Q AS recovery;"
15411 "DROP TABLE IF EXISTS recovery.dbptr;"
15412 "DROP TABLE IF EXISTS recovery.freelist;"
15413 "DROP TABLE IF EXISTS recovery.map;"
15414 "DROP TABLE IF EXISTS recovery.schema;"
15415 "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
15419 shellExec(pState->
db, &rc,
15420 "WITH trunk(pgno) AS ("
15421 " SELECT shell_int32("
15422 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
15425 " SELECT shell_int32("
15426 " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
15427 " FROM trunk WHERE x>0"
15429 "freelist(data, n, freepgno) AS ("
15430 " SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
15431 " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
15433 " SELECT data, n-1, shell_int32(data, 2+n) "
15434 " FROM freelist WHERE n>=0"
15436 "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
15443 shellExec(pState->
db, &rc,
15444 "WITH ptrmap(pgno) AS ("
15445 " SELECT 2 WHERE shell_int32("
15446 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
15449 " SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
15450 " FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
15452 "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
15455 shellExec(pState->
db, &rc,
15456 "CREATE TABLE recovery.dbptr("
15457 " pgno, child, PRIMARY KEY(child, pgno)"
15459 "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
15460 " SELECT * FROM sqlite_dbptr"
15461 " WHERE pgno NOT IN freelist AND child NOT IN freelist;"
15465 "DELETE FROM recovery.dbptr WHERE child = 1;"
15470 "DELETE FROM recovery.dbptr WHERE child IN ("
15471 " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
15477 "CREATE TABLE recovery.map("
15478 "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
15484 "WITH pages(i, maxlen) AS ("
15485 " SELECT page_count, ("
15486 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
15487 " ) FROM pragma_page_count WHERE page_count>0"
15490 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
15491 " ) FROM pages WHERE i>=2"
15493 "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
15494 " SELECT i, maxlen, NULL, ("
15495 " WITH p(orig, pgno, parent) AS ("
15496 " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
15498 " SELECT i, p.parent, "
15499 " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
15501 " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
15503 "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
15504 "UPDATE recovery.map AS o SET intkey = ("
15505 " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
15510 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
15511 "INSERT INTO recovery.schema SELECT "
15512 " max(CASE WHEN field=0 THEN value ELSE NULL END),"
15513 " max(CASE WHEN field=1 THEN value ELSE NULL END),"
15514 " max(CASE WHEN field=2 THEN value ELSE NULL END),"
15515 " max(CASE WHEN field=3 THEN value ELSE NULL END),"
15516 " max(CASE WHEN field=4 THEN value ELSE NULL END)"
15517 "FROM sqlite_dbdata WHERE pgno IN ("
15518 " SELECT pgno FROM recovery.map WHERE root=1"
15520 "GROUP BY pgno, cell;"
15521 "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
15536 "SELECT sql FROM recovery.schema "
15537 "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
15541 raw_printf(pState->
out,
"CREATE TABLE IF NOT EXISTS %s;\n",
15551 "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
15561 "SELECT pgno FROM recovery.map WHERE root=?", &pPages
15565 "SELECT max(field), group_concat(shell_escape_crnl(quote"
15566 "(case when (? AND field<0) then NULL else value end)"
15569 "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
15570 "GROUP BY cell", &pCells
15575 "SELECT root, intkey, max(maxlen) FROM recovery.map"
15576 " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
15577 " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
15585 RecoverTable *pTab;
15587 assert( bIntkey==0 || bIntkey==1 );
15588 pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
15589 if( bNoop || rc )
continue;
15592 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
15595 if( pTab==0 )
break;
15602 if( bRowids==0 && pTab->iPk<0 ){
15617 RecoverTable *pTab2 = pTab;
15618 if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
15620 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
15623 if( pTab2==0 )
break;
15627 if( pTab2==pOrphan ){
15629 "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
15630 pTab2->zQuoted, iRoot, iPgno, nField,
15631 iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
15634 raw_printf(pState->
out,
"INSERT INTO %s(%s) VALUES( %s );\n",
15635 pTab2->zQuoted, pTab2->azlCol[nField], zVal
15642 if( pTab!=pOrphan ) recoverFreeTable(pTab);
15647 recoverFreeTable(pOrphan);
15653 "SELECT sql, name FROM recovery.schema "
15654 "WHERE sql NOT LIKE 'create table%'", &pStmt
15660 char *zPrint = shellMPrintf(&rc,
15661 "INSERT INTO sqlite_master VALUES('table', %Q, %Q, 0, %Q)",
15674 raw_printf(pState->
out,
"PRAGMA writable_schema = off;\n");
15696 #ifndef SQLITE_OMIT_VIRTUALTABLE
15704 while( zLine[h] && nArg<
ArraySize(azArg)-1 ){
15705 while(
IsSpace(zLine[h]) ){ h++; }
15706 if( zLine[h]==0 )
break;
15707 if( zLine[h]==
'\'' || zLine[h]==
'"' ){
15708 int delim = zLine[h++];
15709 azArg[nArg++] = &zLine[h];
15710 while( zLine[h] && zLine[h]!=delim ){
15711 if( zLine[h]==
'\\' && delim==
'"' && zLine[h+1]!=0 ) h++;
15714 if( zLine[h]==delim ){
15719 azArg[nArg++] = &zLine[h];
15720 while( zLine[h] && !
IsSpace(zLine[h]) ){ h++; }
15721 if( zLine[h] ) zLine[h++] = 0;
15729 if( nArg==0 )
return 0;
15734 #ifndef SQLITE_OMIT_AUTHORIZATION
15735 if( c==
'a' && strncmp(azArg[0],
"auth", n)==0 ){
15737 raw_printf(stderr,
"Usage: .auth ON|OFF\n");
15739 goto meta_command_exit;
15750 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
15751 if( c==
'a' && strncmp(azArg[0],
"archive", n)==0 ){
15753 rc = arDotCommand(p, 0, azArg, nArg);
15757 if( (c==
'b' && n>=3 && strncmp(azArg[0],
"backup", n)==0)
15758 || (c==
's' && n>=3 && strncmp(azArg[0],
"save", n)==0)
15760 const char *zDestFile = 0;
15761 const char *zDb = 0;
15766 const char *zVfs = 0;
15767 for(j=1; j<nArg; j++){
15768 const char *z = azArg[j];
15770 if( z[1]==
'-' ) z++;
15771 if( strcmp(z,
"-append")==0 ){
15774 if( strcmp(z,
"-async")==0 ){
15778 utf8_printf(stderr,
"unknown option: %s\n", azArg[j]);
15781 }
else if( zDestFile==0 ){
15782 zDestFile = azArg[j];
15783 }
else if( zDb==0 ){
15785 zDestFile = azArg[j];
15787 raw_printf(stderr,
"Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
15791 if( zDestFile==0 ){
15792 raw_printf(stderr,
"missing FILENAME argument on .backup\n");
15795 if( zDb==0 ) zDb =
"main";
15799 utf8_printf(stderr,
"Error: cannot open \"%s\"\n", zDestFile);
15804 sqlite3_exec(pDest,
"PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
15825 if( c==
'b' && n>=3 && strncmp(azArg[0],
"bail", n)==0 ){
15829 raw_printf(stderr,
"Usage: .bail on|off\n");
15834 if( c==
'b' && n>=3 && strncmp(azArg[0],
"binary", n)==0 ){
15842 raw_printf(stderr,
"Usage: .binary on|off\n");
15847 if( c==
'c' && strcmp(azArg[0],
"cd")==0 ){
15849 #if defined(_WIN32) || defined(WIN32)
15850 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
15851 rc = !SetCurrentDirectoryW(z);
15854 rc = chdir(azArg[1]);
15857 utf8_printf(stderr,
"Cannot change to directory \"%s\"\n", azArg[1]);
15861 raw_printf(stderr,
"Usage: .cd DIRECTORY\n");
15869 if( c==
'b' && n>=3 && strncmp(azArg[0],
"breakpoint", n)==0 ){
15873 if( c==
'c' && n>=3 && strncmp(azArg[0],
"changes", n)==0 ){
15877 raw_printf(stderr,
"Usage: .changes on|off\n");
15886 if( c==
'c' && n>=3 && strncmp(azArg[0],
"check", n)==0 ){
15890 raw_printf(stderr,
"Usage: .check GLOB-PATTERN\n");
15892 }
else if( (zRes =
readFile(
"testcase-out.txt", 0))==0 ){
15893 raw_printf(stderr,
"Error: cannot read 'testcase-out.txt'\n");
15897 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
15907 if( c==
'c' && strncmp(azArg[0],
"clone", n)==0 ){
15911 raw_printf(stderr,
"Usage: .clone FILENAME\n");
15916 if( c==
'd' && n>1 && strncmp(azArg[0],
"databases", n)==0 ){
15920 memcpy(&data, p,
sizeof(data));
15925 sqlite3_exec(p->
db,
"SELECT name, file FROM pragma_database_list",
15934 if( c==
'd' && n>=3 && strncmp(azArg[0],
"dbconfig", n)==0 ){
15935 static const struct DbConfigChoices {
15958 for(ii=0; ii<
ArraySize(aDbConfig); ii++){
15959 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].
zName)!=0 )
continue;
15964 utf8_printf(p->
out,
"%19s %s\n", aDbConfig[ii].zName, v ?
"on" :
"off");
15965 if( nArg>1 )
break;
15967 if( nArg>1 && ii==
ArraySize(aDbConfig) ){
15968 utf8_printf(stderr,
"Error: unknown dbconfig \"%s\"\n", azArg[1]);
15969 utf8_printf(stderr,
"Enter \".dbconfig\" with no arguments for a list\n");
15973 if( c==
'd' && n>=3 && strncmp(azArg[0],
"dbinfo", n)==0 ){
15977 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
15978 if( c==
'r' && strncmp(azArg[0],
"recover", n)==0 ){
15980 rc = recoverDatabaseCmd(p, nArg, azArg);
15984 if( c==
'd' && strncmp(azArg[0],
"dump", n)==0 ){
15991 for(i=1; i<nArg; i++){
15992 if( azArg[i][0]==
'-' ){
15993 const char *z = azArg[i]+1;
15994 if( z[0]==
'-' ) z++;
15995 if( strcmp(z,
"preserve-rowids")==0 ){
15996 #ifdef SQLITE_OMIT_VIRTUALTABLE
15997 raw_printf(stderr,
"The --preserve-rowids option is not compatible"
15998 " with SQLITE_OMIT_VIRTUALTABLE\n");
16000 goto meta_command_exit;
16005 if( strcmp(z,
"newlines")==0 ){
16009 raw_printf(stderr,
"Unknown option \"%s\" on \".dump\"\n", azArg[i]);
16011 goto meta_command_exit;
16033 sqlite3_exec(p->
db,
"SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
16037 "SELECT name, type, sql FROM sqlite_master "
16038 "WHERE (%s) AND type=='table'"
16039 " AND sql NOT NULL"
16040 " ORDER BY tbl_name='sqlite_sequence', rowid",
16046 "SELECT sql FROM sqlite_master "
16047 "WHERE (%s) AND sql NOT NULL"
16048 " AND type IN ('index','trigger','view')",
16065 if( c==
'e' && strncmp(azArg[0],
"echo", n)==0 ){
16069 raw_printf(stderr,
"Usage: .echo on|off\n");
16074 if( c==
'e' && strncmp(azArg[0],
"eqp", n)==0 ){
16081 if( strcmp(azArg[1],
"full")==0 ){
16083 }
else if( strcmp(azArg[1],
"trigger")==0 ){
16085 #ifdef SQLITE_DEBUG
16086 }
else if( strcmp(azArg[1],
"test")==0 ){
16089 }
else if( strcmp(azArg[1],
"trace")==0 ){
16093 sqlite3_exec(p->
db,
"SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0);
16100 raw_printf(stderr,
"Usage: .eqp off|on|trace|trigger|full\n");
16105 if( c==
'e' && strncmp(azArg[0],
"exit", n)==0 ){
16106 if( nArg>1 && (rc = (
int)
integerValue(azArg[1]))!=0 ) exit(rc);
16112 if( c==
'e' && strncmp(azArg[0],
"explain", n)==0 ){
16115 if( strcmp(azArg[1],
"auto")==0 ){
16125 }
else if( val==0 ){
16128 }
else if( val==99 ){
16134 #ifndef SQLITE_OMIT_VIRTUALTABLE
16135 if( c==
'e' && strncmp(azArg[0],
"expert", n)==0 ){
16141 if( c==
'f' && strncmp(azArg[0],
"filectrl", n)==0 ){
16142 static const struct {
16143 const char *zCtrlName;
16145 const char *zUsage;
16163 const char *zCmd = 0;
16164 const char *zSchema = 0;
16167 zCmd = nArg>=2 ? azArg[1] :
"help";
16170 && (strcmp(zCmd,
"--schema")==0 || strcmp(zCmd,
"-schema")==0)
16173 zSchema = azArg[2];
16174 for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
16180 if( zCmd[0]==
'-' && zCmd[1] ){
16182 if( zCmd[0]==
'-' && zCmd[1] ) zCmd++;
16186 if( strcmp(zCmd,
"help")==0 ){
16190 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
16193 goto meta_command_exit;
16200 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
16202 filectrl = aCtrl[i].ctrlCode;
16205 utf8_printf(stderr,
"Error: ambiguous file-control: \"%s\"\n"
16206 "Use \".filectrl --help\" for help\n", zCmd);
16208 goto meta_command_exit;
16213 utf8_printf(stderr,
"Error: unknown file-control: %s\n"
16214 "Use \".filectrl --help\" for help\n", zCmd);
16218 if( nArg!=2 && nArg!=3 )
break;
16227 if( nArg!=3 )
break;
16236 if( nArg!=2 && nArg!=3 )
break;
16245 if( nArg!=2 )
break;
16253 if( nArg!=2 )
break;
16265 x = atoi(azArg[2]);
16276 if( isOk==0 && iCtrl>=0 ){
16277 utf8_printf(p->
out,
"Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
16279 }
else if( isOk==1 ){
16286 if( c==
'f' && strncmp(azArg[0],
"fullschema", n)==0 ){
16290 memcpy(&data, p,
sizeof(data));
16293 if( nArg==2 &&
optionMatch(azArg[1],
"indent") ){
16298 raw_printf(stderr,
"Usage: .fullschema ?--indent?\n");
16300 goto meta_command_exit;
16305 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
16306 " FROM sqlite_master UNION ALL"
16307 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
16308 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
16315 "SELECT rowid FROM sqlite_master"
16316 " WHERE name GLOB 'sqlite_stat[134]'",
16329 shell_exec(&data,
"SELECT * FROM sqlite_stat1", &zErrMsg);
16331 shell_exec(&data,
"SELECT * FROM sqlite_stat4", &zErrMsg);
16336 if( c==
'h' && strncmp(azArg[0],
"headers", n)==0 ){
16340 raw_printf(stderr,
"Usage: .headers on|off\n");
16345 if( c==
'h' && strncmp(azArg[0],
"help", n)==0 ){
16356 if( c==
'i' && strncmp(azArg[0],
"import", n)==0 ){
16371 int useOutputMode = 1;
16373 memset(&sCtx, 0,
sizeof(sCtx));
16379 for(i=1; i<nArg; i++){
16380 char *z = azArg[i];
16381 if( z[0]==
'-' && z[1]==
'-' ) z++;
16385 }
else if( zTable==0 ){
16388 utf8_printf(p->
out,
"ERROR: extra argument: \"%s\". Usage:\n", z);
16391 goto meta_command_exit;
16393 }
else if( strcmp(z,
"-v")==0 ){
16395 }
else if( strcmp(z,
"-skip")==0 && i<nArg-1 ){
16397 }
else if( strcmp(z,
"-ascii")==0 ){
16402 }
else if( strcmp(z,
"-csv")==0 ){
16408 utf8_printf(p->
out,
"ERROR: unknown option: \"%s\". Usage:\n", z);
16411 goto meta_command_exit;
16416 zFile==0 ?
"FILE" :
"TABLE");
16419 goto meta_command_exit;
16423 if( useOutputMode ){
16429 "Error: non-null column separator required for import\n");
16431 goto meta_command_exit;
16435 "Error: multi-character column separators not allowed"
16438 goto meta_command_exit;
16443 "Error: non-null row separator required for import\n");
16445 goto meta_command_exit;
16456 raw_printf(stderr,
"Error: multi-character row separators not allowed"
16459 goto meta_command_exit;
16464 sCtx.
zFile = zFile;
16466 if( sCtx.
zFile[0]==
'|' ){
16467 #ifdef SQLITE_OMIT_POPEN
16468 raw_printf(stderr,
"Error: pipes are not supported in this OS\n");
16470 goto meta_command_exit;
16473 sCtx.
zFile =
"<pipe>";
16477 sCtx.
in = fopen(sCtx.
zFile,
"rb");
16481 utf8_printf(stderr,
"Error: cannot open \"%s\"\n", zFile);
16483 goto meta_command_exit;
16485 if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
16496 while( (nSkip--)>0 ){
16511 while( xRead(&sCtx) ){
16522 goto meta_command_exit;
16531 utf8_printf(stderr,
"CREATE TABLE %s(...) failed: %s\n", zTable,
16536 goto meta_command_exit;
16546 goto meta_command_exit;
16551 if( nCol==0 )
return 0;
16559 for(i=1; i<nCol; i++){
16575 goto meta_command_exit;
16580 int startLine = sCtx.
nLine;
16581 for(i=0; i<nCol; i++){
16582 char *z = xRead(&sCtx);
16587 if( z==0 && i==0 )
break;
16596 utf8_printf(stderr,
"%s:%d: expected %d columns but found %d - "
16597 "filling the rest with NULL\n",
16598 sCtx.
zFile, startLine, nCol, i+1);
16608 utf8_printf(stderr,
"%s:%d: expected %d columns but found %d - "
16609 "extras ignored\n",
16610 sCtx.
zFile, startLine, nCol, i);
16623 }
while( sCtx.
cTerm!=EOF );
16631 "Added %d rows with %d errors using %d lines of input\n",
16636 #ifndef SQLITE_UNTESTABLE
16637 if( c==
'i' && strncmp(azArg[0],
"imposter", n)==0 ){
16639 char *zCollist = 0;
16646 utf8_printf(stderr,
"Usage: .imposter INDEX IMPOSTER\n"
16647 " .imposter off\n");
16656 goto meta_command_exit;
16661 goto meta_command_exit;
16664 "SELECT rootpage, 0 FROM sqlite_master"
16665 " WHERE name='%q' AND type='index'"
16667 "SELECT rootpage, 1 FROM sqlite_master"
16668 " WHERE name='%q' AND type='table'"
16669 " AND sql LIKE '%%without%%rowid%%'",
16696 lenPK = (int)strlen(zCollist);
16705 if( i==0 || tnum==0 ){
16706 utf8_printf(stderr,
"no such index: \"%s\"\n", azArg[1]);
16709 goto meta_command_exit;
16711 if( lenPK==0 ) lenPK = 100000;
16713 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
16714 azArg[2], zCollist, lenPK, zCollist);
16725 "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
16726 azArg[1], isWO ?
"table" :
"index"
16730 raw_printf(stderr,
"SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
16737 #ifdef SQLITE_ENABLE_IOTRACE
16738 if( c==
'i' && strncmp(azArg[0],
"iotrace", n)==0 ){
16740 if( iotrace && iotrace!=stdout ) fclose(iotrace);
16743 sqlite3IoTrace = 0;
16744 }
else if( strcmp(azArg[1],
"-")==0 ){
16745 sqlite3IoTrace = iotracePrintf;
16748 iotrace = fopen(azArg[1],
"w");
16750 utf8_printf(stderr,
"Error: cannot open \"%s\"\n", azArg[1]);
16751 sqlite3IoTrace = 0;
16754 sqlite3IoTrace = iotracePrintf;
16760 if( c==
'l' && n>=5 && strncmp(azArg[0],
"limits", n)==0 ){
16761 static const struct {
16762 const char *zLimitName;
16782 printf(
"%20s %d\n", aLimit[i].zLimitName,
16785 }
else if( nArg>3 ){
16786 raw_printf(stderr,
"Usage: .limit NAME ?NEW-VALUE?\n");
16788 goto meta_command_exit;
16797 utf8_printf(stderr,
"ambiguous limit: \"%s\"\n", azArg[1]);
16799 goto meta_command_exit;
16805 "enter \".limits\" with no arguments for a list.\n",
16808 goto meta_command_exit;
16814 printf(
"%20s %d\n", aLimit[iLimit].zLimitName,
16819 if( c==
'l' && n>2 && strncmp(azArg[0],
"lint", n)==0 ){
16824 #ifndef SQLITE_OMIT_LOAD_EXTENSION
16825 if( c==
'l' && strncmp(azArg[0],
"load", n)==0 ){
16826 const char *zFile, *zProc;
16829 raw_printf(stderr,
"Usage: .load FILE ?ENTRYPOINT?\n");
16831 goto meta_command_exit;
16834 zProc = nArg>=3 ? azArg[2] : 0;
16845 if( c==
'l' && strncmp(azArg[0],
"log", n)==0 ){
16847 raw_printf(stderr,
"Usage: .log FILENAME\n");
16850 const char *zFile = azArg[1];
16856 if( c==
'm' && strncmp(azArg[0],
"mode", n)==0 ){
16857 const char *zMode = nArg>=2 ? azArg[1] :
"";
16860 if( c2==
'l' && n2>2 && strncmp(azArg[1],
"lines",n2)==0 ){
16863 }
else if( c2==
'c' && strncmp(azArg[1],
"columns",n2)==0 ){
16866 }
else if( c2==
'l' && n2>2 && strncmp(azArg[1],
"list",n2)==0 ){
16870 }
else if( c2==
'h' && strncmp(azArg[1],
"html",n2)==0 ){
16872 }
else if( c2==
't' && strncmp(azArg[1],
"tcl",n2)==0 ){
16876 }
else if( c2==
'c' && strncmp(azArg[1],
"csv",n2)==0 ){
16880 }
else if( c2==
't' && strncmp(azArg[1],
"tabs",n2)==0 ){
16883 }
else if( c2==
'i' && strncmp(azArg[1],
"insert",n2)==0 ){
16886 }
else if( c2==
'q' && strncmp(azArg[1],
"quote",n2)==0 ){
16888 }
else if( c2==
'a' && strncmp(azArg[1],
"ascii",n2)==0 ){
16892 }
else if( nArg==1 ){
16895 raw_printf(stderr,
"Error: mode should be one of: "
16896 "ascii column csv html insert line list quote tabs tcl\n");
16902 if( c==
'n' && strncmp(azArg[0],
"nullvalue", n)==0 ){
16907 raw_printf(stderr,
"Usage: .nullvalue STRING\n");
16912 #ifdef SQLITE_DEBUG
16913 if( c==
'o' && strcmp(azArg[0],
"oom")==0 ){
16915 for(i=1; i<nArg; i++){
16916 const char *z = azArg[i];
16917 if( z[0]==
'-' && z[1]==
'-' ) z++;
16918 if( strcmp(z,
"-repeat")==0 ){
16920 raw_printf(p->
out,
"missing argument on \"%s\"\n", azArg[i]);
16928 raw_printf(p->
out,
"unknown argument: \"%s\"\n", azArg[i]);
16940 if( c==
'o' && strncmp(azArg[0],
"open", n)==0 && n>=2 ){
16941 char *zNewFilename;
16955 for(iName=1; iName<nArg && azArg[iName][0]==
'-'; iName++){
16956 const char *z = azArg[iName];
16959 #ifdef SQLITE_HAVE_ZLIB
16969 #ifdef SQLITE_ENABLE_DESERIALIZE
16974 }
else if(
optionMatch(z,
"maxsize") && iName+1<nArg ){
16977 }
else if( z[0]==
'-' ){
16980 goto meta_command_exit;
16990 utf8_printf(stderr,
"Error: cannot open '%s'\n", zNewFilename);
17004 && (strncmp(azArg[0],
"output", n)==0||strncmp(azArg[0],
"once", n)==0))
17005 || (c==
'e' && n==5 && strcmp(azArg[0],
"excel")==0)
17007 const char *zFile = 0;
17017 }
else if( strncmp(azArg[0],
"once",n)==0 ){
17020 for(i=1; i<nArg; i++){
17021 char *z = azArg[i];
17023 if( z[1]==
'-' ) z++;
17024 if( strcmp(z,
"-bom")==0 ){
17026 }
else if( c!=
'e' && strcmp(z,
"-x")==0 ){
17028 }
else if( c!=
'e' && strcmp(z,
"-e")==0 ){
17035 goto meta_command_exit;
17037 }
else if( zFile==0 ){
17044 goto meta_command_exit;
17047 if( zFile==0 ) zFile =
"stdout";
17054 #ifndef SQLITE_NOHAVE_SYSTEM
17055 if( eMode==
'e' || eMode==
'x' ){
17073 if( zFile[0]==
'|' ){
17074 #ifdef SQLITE_OMIT_POPEN
17075 raw_printf(stderr,
"Error: pipes are not supported in this OS\n");
17081 utf8_printf(stderr,
"Error: cannot open pipe \"%s\"\n", zFile + 1);
17085 if( bBOM ) fprintf(p->
out,
"\357\273\277");
17092 if( strcmp(zFile,
"off")!=0 ){
17093 utf8_printf(stderr,
"Error: cannot write to \"%s\"\n", zFile);
17098 if( bBOM ) fprintf(p->
out,
"\357\273\277");
17104 if( c==
'p' && n>=3 && strncmp(azArg[0],
"parameter", n)==0 ){
17106 if( nArg<=1 )
goto parameter_syntax_error;
17111 if( nArg==2 && strcmp(azArg[1],
"clear")==0 ){
17112 sqlite3_exec(p->
db,
"DROP TABLE IF EXISTS temp.sqlite_parameters;",
17119 if( nArg==2 && strcmp(azArg[1],
"list")==0 ){
17124 "SELECT max(length(key)) "
17125 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
17128 if( len>40 ) len = 40;
17134 "SELECT key, quote(value) "
17135 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
17148 if( nArg==2 && strcmp(azArg[1],
"init")==0 ){
17158 if( nArg==4 && strcmp(azArg[1],
"set")==0 ){
17162 const char *zKey = azArg[2];
17163 const char *zValue = azArg[3];
17166 "REPLACE INTO temp.sqlite_parameters(key,value)"
17167 "VALUES(%Q,%s);", zKey, zValue);
17176 "REPLACE INTO temp.sqlite_parameters(key,value)"
17177 "VALUES(%Q,%Q);", zKey, zValue);
17196 if( nArg==3 && strcmp(azArg[1],
"unset")==0 ){
17198 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
17204 parameter_syntax_error:
17208 if( c==
'p' && n>=3 && strncmp(azArg[0],
"print", n)==0 ){
17210 for(i=1; i<nArg; i++){
17217 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
17218 if( c==
'p' && n>=3 && strncmp(azArg[0],
"progress", n)==0 ){
17224 for(i=1; i<nArg; i++){
17225 const char *z = azArg[i];
17228 if( z[0]==
'-' ) z++;
17229 if( strcmp(z,
"quiet")==0 || strcmp(z,
"q")==0 ){
17233 if( strcmp(z,
"reset")==0 ){
17237 if( strcmp(z,
"once")==0 ){
17241 if( strcmp(z,
"limit")==0 ){
17243 utf8_printf(stderr,
"Error: missing argument on --limit\n");
17245 goto meta_command_exit;
17251 utf8_printf(stderr,
"Error: unknown option: \"%s\"\n", azArg[i]);
17253 goto meta_command_exit;
17263 if( c==
'p' && strncmp(azArg[0],
"prompt", n)==0 ){
17272 if( c==
'q' && strncmp(azArg[0],
"quit", n)==0 ){
17276 if( c==
'r' && n>=3 && strncmp(azArg[0],
"read", n)==0 ){
17277 FILE *inSaved = p->
in;
17278 int savedLineno = p->
lineno;
17282 goto meta_command_exit;
17284 p->
in = fopen(azArg[1],
"rb");
17286 utf8_printf(stderr,
"Error: cannot open \"%s\"\n", azArg[1]);
17293 p->
lineno = savedLineno;
17296 if( c==
'r' && n>=3 && strncmp(azArg[0],
"restore", n)==0 ){
17297 const char *zSrcFile;
17304 zSrcFile = azArg[1];
17306 }
else if( nArg==3 ){
17307 zSrcFile = azArg[2];
17310 raw_printf(stderr,
"Usage: .restore ?DB? FILE\n");
17312 goto meta_command_exit;
17316 utf8_printf(stderr,
"Error: cannot open \"%s\"\n", zSrcFile);
17330 if( nTimeout++ >= 3 )
break;
17338 raw_printf(stderr,
"Error: source database is busy\n");
17347 if( c==
's' && strncmp(azArg[0],
"scanstats", n)==0 ){
17350 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
17351 raw_printf(stderr,
"Warning: .scanstats not available in this build.\n");
17354 raw_printf(stderr,
"Usage: .scanstats on|off\n");
17359 if( c==
's' && strncmp(azArg[0],
"schema", n)==0 ){
17363 const char *zDiv =
"(";
17364 const char *
zName = 0;
17370 memcpy(&data, p,
sizeof(data));
17374 for(ii=1; ii<nArg; ii++){
17379 }
else if(
zName==0 ){
17382 raw_printf(stderr,
"Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
17384 goto meta_command_exit;
17390 char *new_argv[2], *new_colv[2];
17392 "CREATE TABLE %s (\n"
17395 " tbl_name text,\n"
17396 " rootpage integer,\n"
17398 ")", isMaster ?
"sqlite_master" :
"sqlite_temp_master");
17400 new_colv[0] =
"sql";
17402 callback(&data, 1, new_argv, new_colv);
17414 goto meta_command_exit;
17423 zDiv =
" UNION ALL ";
17424 appendText(&sSelect,
"SELECT shell_add_schema(sql,", 0);
17430 appendText(&sSelect,
",name) AS sql, type, tbl_name, name, rowid,", 0);
17439 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
17442 " UNION ALL SELECT shell_module_schema(name),"
17443 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
17450 int bGlob = strchr(
zName,
'*') != 0 || strchr(
zName,
'?') != 0 ||
17451 strchr(
zName,
'[') != 0;
17452 if( strchr(
zName,
'.') ){
17453 appendText(&sSelect,
"lower(printf('%s.%s',sname,tbl_name))", 0);
17457 appendText(&sSelect, bGlob ?
" GLOB " :
" LIKE ", 0);
17465 appendText(&sSelect,
"type!='meta' AND sql IS NOT NULL"
17466 " ORDER BY snum, rowid", 0);
17479 raw_printf(stderr,
"Error: querying schema information\n");
17486 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
17487 if( c==
's' && n==11 && strncmp(azArg[0],
"selecttrace", n)==0 ){
17492 #if defined(SQLITE_ENABLE_SESSION)
17493 if( c==
's' && strncmp(azArg[0],
"session",n)==0 && n>=3 ){
17494 OpenSession *pSession = &p->aSession[0];
17495 char **azCmd = &azArg[1];
17497 int nCmd = nArg - 1;
17499 if( nArg<=1 )
goto session_syntax_error;
17502 for(iSes=0; iSes<p->nSession; iSes++){
17503 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 )
break;
17505 if( iSes<p->nSession ){
17506 pSession = &p->aSession[iSes];
17510 pSession = &p->aSession[0];
17519 if( strcmp(azCmd[0],
"attach")==0 ){
17520 if( nCmd!=2 )
goto session_syntax_error;
17521 if( pSession->p==0 ){
17523 raw_printf(stderr,
"ERROR: No sessions are open\n");
17525 rc = sqlite3session_attach(pSession->p, azCmd[1]);
17527 raw_printf(stderr,
"ERROR: sqlite3session_attach() returns %d\n", rc);
17537 if( strcmp(azCmd[0],
"changeset")==0 || strcmp(azCmd[0],
"patchset")==0 ){
17539 if( nCmd!=2 )
goto session_syntax_error;
17540 if( pSession->p==0 )
goto session_not_open;
17541 out = fopen(azCmd[1],
"wb");
17543 utf8_printf(stderr,
"ERROR: cannot open \"%s\" for writing\n",
17548 if( azCmd[0][0]==
'c' ){
17549 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
17551 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
17554 printf(
"Error: error code %d\n", rc);
17558 && fwrite(pChng, szChng, 1, out)!=1 ){
17559 raw_printf(stderr,
"ERROR: Failed to write entire %d-byte output\n",
17570 if( strcmp(azCmd[0],
"close")==0 ){
17571 if( nCmd!=1 )
goto session_syntax_error;
17573 session_close(pSession);
17574 p->aSession[iSes] = p->aSession[--p->nSession];
17581 if( strcmp(azCmd[0],
"enable")==0 ){
17583 if( nCmd>2 )
goto session_syntax_error;
17586 ii = sqlite3session_enable(pSession->p, ii);
17588 pSession->zName, ii);
17595 if( strcmp(azCmd[0],
"filter")==0 ){
17597 if( nCmd<2 )
goto session_syntax_error;
17599 for(ii=0; ii<pSession->nFilter; ii++){
17603 nByte =
sizeof(pSession->azFilter[0])*(nCmd-1);
17605 if( pSession->azFilter==0 ){
17606 raw_printf(stderr,
"Error: out or memory\n");
17609 for(ii=1; ii<nCmd; ii++){
17612 pSession->nFilter = ii-1;
17619 if( strcmp(azCmd[0],
"indirect")==0 ){
17621 if( nCmd>2 )
goto session_syntax_error;
17624 ii = sqlite3session_indirect(pSession->p, ii);
17626 pSession->zName, ii);
17633 if( strcmp(azCmd[0],
"isempty")==0 ){
17635 if( nCmd!=1 )
goto session_syntax_error;
17637 ii = sqlite3session_isempty(pSession->p);
17639 pSession->zName, ii);
17646 if( strcmp(azCmd[0],
"list")==0 ){
17647 for(i=0; i<p->nSession; i++){
17656 if( strcmp(azCmd[0],
"open")==0 ){
17658 if( nCmd!=3 )
goto session_syntax_error;
17660 if(
zName[0]==0 )
goto session_syntax_error;
17661 for(i=0; i<p->nSession; i++){
17662 if( strcmp(p->aSession[i].zName,
zName)==0 ){
17664 goto meta_command_exit;
17667 if( p->nSession>=
ArraySize(p->aSession) ){
17669 goto meta_command_exit;
17671 pSession = &p->aSession[p->nSession];
17672 rc = sqlite3session_create(p->
db, azCmd[1], &pSession->p);
17674 raw_printf(stderr,
"Cannot open session: error code=%d\n", rc);
17676 goto meta_command_exit;
17678 pSession->nFilter = 0;
17679 sqlite3session_table_filter(pSession->p, session_filter, pSession);
17684 session_syntax_error:
17689 #ifdef SQLITE_DEBUG
17692 if( c==
's' && n>=10 && strncmp(azArg[0],
"selftest-", 9)==0 ){
17693 if( strncmp(azArg[0]+9,
"boolean", n-9)==0 ){
17695 for(i=1; i<nArg; i++){
17700 if( strncmp(azArg[0]+9,
"integer", n-9)==0 ){
17702 for(i=1; i<nArg; i++){
17712 if( c==
's' && n>=4 && strncmp(azArg[0],
"selftest",n)==0 ){
17715 int bSelftestExists;
17723 for(i=1; i<nArg; i++){
17724 const char *z = azArg[i];
17725 if( z[0]==
'-' && z[1]==
'-' ) z++;
17726 if( strcmp(z,
"-init")==0 ){
17729 if( strcmp(z,
"-v")==0 ){
17733 utf8_printf(stderr,
"Unknown option \"%s\" on \"%s\"\n",
17734 azArg[i], azArg[0]);
17735 raw_printf(stderr,
"Should be one of: --init -v\n");
17737 goto meta_command_exit;
17742 bSelftestExists = 0;
17744 bSelftestExists = 1;
17748 bSelftestExists = 1;
17752 for(k=bSelftestExists; k>=0; k--){
17755 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
17759 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
17760 " (1,'run','PRAGMA integrity_check','ok')",
17764 raw_printf(stderr,
"Error querying the selftest table\n");
17767 goto meta_command_exit;
17778 printf(
"%d: %s %s\n", tno, zOp, zSql);
17781 if( strcmp(zOp,
"memo")==0 ){
17784 if( strcmp(zOp,
"run")==0 ){
17793 if( rc || zErrMsg ){
17796 utf8_printf(p->
out,
"%d: error-code-%d: %s\n", tno, rc, zErrMsg);
17798 }
else if( strcmp(zAns,str.
z)!=0 ){
17807 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
17815 utf8_printf(p->
out,
"%d errors out of %d tests\n", nErr, nTest);
17818 if( c==
's' && strncmp(azArg[0],
"separator", n)==0 ){
17819 if( nArg<2 || nArg>3 ){
17820 raw_printf(stderr,
"Usage: .separator COL ?ROW?\n");
17833 if( c==
's' && n>=4 && strncmp(azArg[0],
"sha3sum",n)==0 ){
17834 const char *zLike = 0;
17846 for(i=1; i<nArg; i++){
17847 const char *z = azArg[i];
17850 if( z[0]==
'-' ) z++;
17851 if( strcmp(z,
"schema")==0 ){
17854 if( strcmp(z,
"sha3-224")==0 || strcmp(z,
"sha3-256")==0
17855 || strcmp(z,
"sha3-384")==0 || strcmp(z,
"sha3-512")==0
17857 iSize = atoi(&z[5]);
17859 if( strcmp(z,
"debug")==0 ){
17863 utf8_printf(stderr,
"Unknown option \"%s\" on \"%s\"\n",
17864 azArg[i], azArg[0]);
17867 goto meta_command_exit;
17870 raw_printf(stderr,
"Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
17872 goto meta_command_exit;
17880 zSql =
"SELECT lower(name) FROM sqlite_master"
17881 " WHERE type='table' AND coalesce(rootpage,0)>1"
17882 " UNION ALL SELECT 'sqlite_master'"
17883 " ORDER BY 1 collate nocase";
17885 zSql =
"SELECT lower(name) FROM sqlite_master"
17886 " WHERE type='table' AND coalesce(rootpage,0)>1"
17887 " AND name NOT LIKE 'sqlite_%'"
17888 " ORDER BY 1 collate nocase";
17893 appendText(&sSql,
"WITH [sha3sum$query](a,b) AS(",0);
17898 if( strncmp(zTab,
"sqlite_",7)!=0 ){
17902 }
else if( strcmp(zTab,
"sqlite_master")==0 ){
17903 appendText(&sQuery,
"SELECT type,name,tbl_name,sql FROM sqlite_master"
17904 " ORDER BY name;", 0);
17905 }
else if( strcmp(zTab,
"sqlite_sequence")==0 ){
17906 appendText(&sQuery,
"SELECT name,seq FROM sqlite_sequence"
17907 " ORDER BY name;", 0);
17908 }
else if( strcmp(zTab,
"sqlite_stat1")==0 ){
17909 appendText(&sQuery,
"SELECT tbl,idx,stat FROM sqlite_stat1"
17910 " ORDER BY tbl,idx;", 0);
17911 }
else if( strcmp(zTab,
"sqlite_stat4")==0 ){
17914 appendText(&sQuery,
" ORDER BY tbl, idx, rowid;\n", 0);
17927 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
17928 " FROM [sha3sum$query]",
17933 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
17934 " FROM [sha3sum$query]",
17947 #ifndef SQLITE_NOHAVE_SYSTEM
17949 && (strncmp(azArg[0],
"shell", n)==0 || strncmp(azArg[0],
"system",n)==0)
17954 raw_printf(stderr,
"Usage: .system COMMAND\n");
17956 goto meta_command_exit;
17958 zCmd =
sqlite3_mprintf(strchr(azArg[1],
' ')==0?
"%s":
"\"%s\"", azArg[1]);
17959 for(i=2; i<nArg; i++){
17965 if( x )
raw_printf(stderr,
"System command returns %d\n", x);
17969 if( c==
's' && strncmp(azArg[0],
"show", n)==0 ){
17970 static const char *azBool[] = {
"off",
"on",
"trigger",
"full"};
17975 goto meta_command_exit;
18005 if( c==
's' && strncmp(azArg[0],
"stats", n)==0 ){
18008 }
else if( nArg==1 ){
18011 raw_printf(stderr,
"Usage: .stats ?on|off?\n");
18016 if( (c==
't' && n>1 && strncmp(azArg[0],
"tables", n)==0)
18017 || (c==
'i' && (strncmp(azArg[0],
"indices", n)==0
18018 || strncmp(azArg[0],
"indexes", n)==0) )
18033 if( nArg>2 && c==
'i' ){
18037 raw_printf(stderr,
"Usage: .indexes ?LIKE-PATTERN?\n");
18040 goto meta_command_exit;
18044 if( zDbName==0 )
continue;
18056 appendText(&s,
" WHERE type IN ('table','view')"
18057 " AND name NOT LIKE 'sqlite_%'"
18058 " AND name LIKE ?1", 0);
18061 " AND tbl_name LIKE ?1", 0);
18080 if( nRow>=nAlloc ){
18082 int n2 = nAlloc*2 + 10;
18097 if( rc==0 && nRow>0 ){
18098 int len, maxlen = 0;
18100 int nPrintCol, nPrintRow;
18101 for(i=0; i<nRow; i++){
18103 if( len>maxlen ) maxlen = len;
18105 nPrintCol = 80/(maxlen+2);
18106 if( nPrintCol<1 ) nPrintCol = 1;
18107 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
18108 for(i=0; i<nPrintRow; i++){
18109 for(j=i; j<nRow; j+=nPrintRow){
18110 char *zSp = j<nPrintRow ?
"" :
" ";
18112 azResult[j] ? azResult[j]:
"");
18123 if( c==
't' && strcmp(azArg[0],
"testcase")==0 ){
18127 raw_printf(stderr,
"Error: cannot open 'testcase-out.txt'\n");
18136 #ifndef SQLITE_UNTESTABLE
18137 if( c==
't' && n>=8 && strncmp(azArg[0],
"testctrl", n)==0 ){
18138 static const struct {
18139 const char *zCtrlName;
18141 const char *zUsage;
18168 const char *zCmd = 0;
18171 zCmd = nArg>=2 ? azArg[1] :
"help";
18174 if( zCmd[0]==
'-' && zCmd[1] ){
18176 if( zCmd[0]==
'-' && zCmd[1] ) zCmd++;
18180 if( strcmp(zCmd,
"help")==0 ){
18184 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
18187 goto meta_command_exit;
18194 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
18196 testctrl = aCtrl[i].ctrlCode;
18199 utf8_printf(stderr,
"Error: ambiguous test-control: \"%s\"\n"
18200 "Use \".testctrl --help\" for help\n", zCmd);
18202 goto meta_command_exit;
18207 utf8_printf(stderr,
"Error: unknown test-control: %s\n"
18208 "Use \".testctrl --help\" for help\n", zCmd);
18215 int opt = (int)strtol(azArg[2], 0, 0);
18235 unsigned int opt = (
unsigned int)
integerValue(azArg[2]);
18243 if( nArg==3 || nArg==4 ){
18246 if( ii==0 && strcmp(azArg[2],
"random")==0 ){
18248 printf(
"-- random seed: %d\n", ii);
18307 if( isOk==0 && iCtrl>=0 ){
18308 utf8_printf(p->
out,
"Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
18310 }
else if( isOk==1 ){
18312 }
else if( isOk==2 ){
18318 if( c==
't' && n>4 && strncmp(azArg[0],
"timeout", n)==0 ){
18323 if( c==
't' && n>=5 && strncmp(azArg[0],
"timer", n)==0 ){
18327 raw_printf(stderr,
"Error: timer not available on this system.\n");
18331 raw_printf(stderr,
"Usage: .timer on|off\n");
18336 #ifndef SQLITE_OMIT_TRACE
18337 if( c==
't' && strncmp(azArg[0],
"trace", n)==0 ){
18341 for(jj=1; jj<nArg; jj++){
18342 const char *z = azArg[jj];
18347 #ifdef SQLITE_ENABLE_NORMALIZE
18368 raw_printf(stderr,
"Unknown option \"%s\" on \".trace\"\n", z);
18370 goto meta_command_exit;
18386 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
18387 if( c==
'u' && strncmp(azArg[0],
"unmodule", n)==0 ){
18392 raw_printf(stderr,
"Usage: .unmodule [--allexcept] NAME ...\n");
18394 goto meta_command_exit;
18398 if( zOpt[0]==
'-' && zOpt[1]==
'-' && zOpt[2]!=0 ) zOpt++;
18399 lenOpt = (int)strlen(zOpt);
18400 if( lenOpt>=3 && strncmp(zOpt,
"-allexcept",lenOpt)==0 ){
18401 assert( azArg[nArg]==0 );
18404 for(ii=1; ii<nArg; ii++){
18411 #if SQLITE_USER_AUTHENTICATION
18412 if( c==
'u' && strncmp(azArg[0],
"user", n)==0 ){
18414 raw_printf(stderr,
"Usage: .user SUBCOMMAND ...\n");
18416 goto meta_command_exit;
18419 if( strcmp(azArg[1],
"login")==0 ){
18421 raw_printf(stderr,
"Usage: .user login USER PASSWORD\n");
18423 goto meta_command_exit;
18425 rc = sqlite3_user_authenticate(p->
db, azArg[2], azArg[3],
18428 utf8_printf(stderr,
"Authentication failed for user %s\n", azArg[2]);
18431 }
else if( strcmp(azArg[1],
"add")==0 ){
18433 raw_printf(stderr,
"Usage: .user add USER PASSWORD ISADMIN\n");
18435 goto meta_command_exit;
18437 rc = sqlite3_user_add(p->
db, azArg[2], azArg[3],
strlen30(azArg[3]),
18440 raw_printf(stderr,
"User-Add failed: %d\n", rc);
18443 }
else if( strcmp(azArg[1],
"edit")==0 ){
18445 raw_printf(stderr,
"Usage: .user edit USER PASSWORD ISADMIN\n");
18447 goto meta_command_exit;
18449 rc = sqlite3_user_change(p->
db, azArg[2], azArg[3],
strlen30(azArg[3]),
18452 raw_printf(stderr,
"User-Edit failed: %d\n", rc);
18455 }
else if( strcmp(azArg[1],
"delete")==0 ){
18457 raw_printf(stderr,
"Usage: .user delete USER\n");
18459 goto meta_command_exit;
18461 rc = sqlite3_user_delete(p->
db, azArg[2]);
18463 raw_printf(stderr,
"User-Delete failed: %d\n", rc);
18467 raw_printf(stderr,
"Usage: .user login|add|edit|delete ...\n");
18469 goto meta_command_exit;
18474 if( c==
'v' && strncmp(azArg[0],
"version", n)==0 ){
18477 #if SQLITE_HAVE_ZLIB
18480 #define CTIMEOPT_VAL_(opt) #opt
18481 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
18482 #if defined(__clang__) && defined(__clang_major__)
18486 #elif defined(_MSC_VER)
18488 #elif defined(__GNUC__) && defined(__VERSION__)
18493 if( c==
'v' && strncmp(azArg[0],
"vfsinfo", n)==0 ){
18494 const char *zDbName = nArg==2 ? azArg[1] :
"main";
18507 if( c==
'v' && strncmp(azArg[0],
"vfslist", n)==0 ){
18515 pVfs==pCurrent ?
" <--- CURRENT" :
"");
18520 raw_printf(p->
out,
"-----------------------------------\n");
18525 if( c==
'v' && strncmp(azArg[0],
"vfsname", n)==0 ){
18526 const char *zDbName = nArg==2 ? azArg[1] :
"main";
18527 char *zVfsName = 0;
18537 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
18538 if( c==
'w' && strncmp(azArg[0],
"wheretrace", n)==0 ){
18539 sqlite3WhereTrace = nArg>=2 ?
booleanValue(azArg[1]) : 0xff;
18543 if( c==
'w' && strncmp(azArg[0],
"width", n)==0 ){
18552 utf8_printf(stderr,
"Error: unknown command or invalid arguments: "
18553 " \"%s\". Enter \".help\" for help\n", azArg[0]);
18571 for(i=0; i<N; i++){
if( z[i]==
';' )
return 1; }
18580 if(
IsSpace(z[0]) )
continue;
18581 if( *z==
'/' && z[1]==
'*' ){
18583 while( *z && (*z!=
'*' || z[1]!=
'/') ){ z++; }
18584 if( *z==0 )
return 0;
18588 if( *z==
'-' && z[1]==
'-' ){
18590 while( *z && *z!=
'\n' ){ z++; }
18591 if( *z==0 )
return 1;
18605 while(
IsSpace(zLine[0]) ){ zLine++; };
18622 #ifdef SQLITE_OMIT_COMPLETE
18623 #define sqlite3_complete(x) 1
18632 if( zSql==0 )
return 1;
18653 if( rc || zErrMsg ){
18657 "Error: near line %d:", startline);
18662 utf8_printf(stderr,
"%s %s\n", zPrefix, zErrMsg);
18707 if( p->
in!=0 )
break;
18715 if( zLine && (zLine[0]==
'.' || zLine[0]==
'#') && nSql==0 ){
18717 if( zLine[0]==
'.' ){
18728 memcpy(zLine,
";",2);
18731 if( nSql+nLine+2>=nAlloc ){
18732 nAlloc = nSql+nLine+100;
18733 zSql = realloc(zSql, nAlloc);
18739 for(i=0; zLine[i] &&
IsSpace(zLine[i]); i++){}
18740 assert( nAlloc>0 && zSql!=0 );
18741 memcpy(zSql, zLine+i, nLine+1-i);
18745 zSql[nSql++] =
'\n';
18746 memcpy(zSql+nSql, zLine, nLine+1);
18777 static char *home_dir =
NULL;
18783 if( home_dir )
return home_dir;
18785 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
18786 && !defined(__RTP__) && !defined(_WRS_KERNEL)
18788 struct passwd *pwent;
18789 uid_t uid = getuid();
18790 if( (pwent=getpwuid(uid)) !=
NULL) {
18791 home_dir = pwent->pw_dir;
18796 #if defined(_WIN32_WCE)
18802 #if defined(_WIN32) || defined(WIN32)
18804 home_dir = getenv(
"USERPROFILE");
18809 home_dir = getenv(
"HOME");
18812 #if defined(_WIN32) || defined(WIN32)
18814 char *zDrive, *zPath;
18816 zDrive = getenv(
"HOMEDRIVE");
18817 zPath = getenv(
"HOMEPATH");
18818 if( zDrive && zPath ){
18820 home_dir = malloc( n );
18821 if( home_dir==0 )
return 0;
18833 char *z = malloc( n );
18834 if( z ) memcpy(z, home_dir, n);
18849 const char *sqliterc_override
18851 char *home_dir =
NULL;
18852 const char *sqliterc = sqliterc_override;
18854 FILE *inSaved = p->
in;
18855 int savedLineno = p->
lineno;
18857 if (sqliterc ==
NULL) {
18860 raw_printf(stderr,
"-- warning: cannot find home directory;"
18861 " cannot read ~/.sqliterc\n");
18867 p->
in = fopen(sqliterc,
"rb");
18870 utf8_printf(stderr,
"-- Loading resources from %s\n",sqliterc);
18876 p->
lineno = savedLineno;
18884 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
18885 " -A ARGS... run \".archive ARGS\" and exit\n"
18887 " -append append the database to the end of the file\n"
18888 " -ascii set output mode to 'ascii'\n"
18889 " -bail stop after hitting an error\n"
18890 " -batch force batch I/O\n"
18891 " -column set output mode to 'column'\n"
18892 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
18893 " -csv set output mode to 'csv'\n"
18894 #if defined(SQLITE_ENABLE_DESERIALIZE)
18895 " -deserialize open the database using sqlite3_deserialize()\n"
18897 " -echo print commands before execution\n"
18898 " -init FILENAME read/process named file\n"
18899 " -[no]header turn headers on or off\n"
18900 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
18901 " -heap SIZE Size of heap for memsys3 or memsys5\n"
18903 " -help show this message\n"
18904 " -html set output mode to HTML\n"
18905 " -interactive force interactive I/O\n"
18906 " -line set output mode to 'line'\n"
18907 " -list set output mode to 'list'\n"
18908 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
18909 #if defined(SQLITE_ENABLE_DESERIALIZE)
18910 " -maxsize N maximum size for a --deserialize database\n"
18912 " -memtrace trace all memory allocations and deallocations\n"
18913 " -mmap N default mmap size set to N\n"
18914 #ifdef SQLITE_ENABLE_MULTIPLEX
18915 " -multiplex enable the multiplexor VFS\n"
18917 " -newline SEP set output row separator. Default: '\\n'\n"
18918 " -nofollow refuse to open symbolic links to database files\n"
18919 " -nullvalue TEXT set text string for NULL values. Default ''\n"
18920 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
18921 " -quote set output mode to 'quote'\n"
18922 " -readonly open the database read-only\n"
18923 " -separator SEP set output column separator. Default: '|'\n"
18924 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
18925 " -sorterref SIZE sorter references threshold size\n"
18927 " -stats print memory stats before each finalize\n"
18928 " -version show SQLite version\n"
18929 " -vfs NAME use NAME as the default VFS\n"
18930 #ifdef SQLITE_ENABLE_VFSTRACE
18931 " -vfstrace enable tracing of all VFS calls\n"
18933 #ifdef SQLITE_HAVE_ZLIB
18934 " -zip open the file as a ZIP Archive\n"
18937 static void usage(
int showDetail){
18939 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
18940 "FILENAME is the name of an SQLite database. A new database is created\n"
18941 "if the file does not previously exist.\n",
Argv0);
18945 raw_printf(stderr,
"Use the -help option for additional information\n");
18956 utf8_printf(stdout,
"WARNING: attempt to configure SQLite after"
18957 " initialization.\n");
18965 memset(data, 0,
sizeof(*data));
18984 static void printBold(
const char *zText){
18985 #if !SQLITE_OS_WINRT
18986 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
18987 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
18988 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
18989 SetConsoleTextAttribute(out,
18990 FOREGROUND_RED|FOREGROUND_INTENSITY
18993 printf(
"%s", zText);
18994 #if !SQLITE_OS_WINRT
18995 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
18999 static void printBold(
const char *zText){
19000 printf(
"\033[1m%s\033[0m", zText);
19010 utf8_printf(stderr,
"%s: Error: missing argument to %s\n",
19011 argv[0], argv[argc-1]);
19017 #ifndef SQLITE_SHELL_IS_UTF8
19018 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
19019 # define SQLITE_SHELL_IS_UTF8 (0)
19021 # define SQLITE_SHELL_IS_UTF8 (1)
19025 #if SQLITE_SHELL_IS_UTF8
19033 const char *zInitFile = 0;
19036 int warnInmemoryDb = 0;
19040 const char *zVfs = 0;
19041 #if !SQLITE_SHELL_IS_UTF8
19042 char **argvToFree = 0;
19043 int argcToFree = 0;
19047 setvbuf(stderr, 0, _IONBF, 0);
19051 #ifdef SQLITE_DEBUG
19052 registerOomSimulator();
19055 #if !defined(_WIN32_WCE)
19056 if( getenv(
"SQLITE_DEBUG_BREAK") ){
19059 "attach debugger to process %d and press any key to continue.\n",
19063 #if defined(_WIN32) || defined(WIN32)
19064 #if SQLITE_OS_WINRT
19069 #elif defined(SIGTRAP)
19076 #if USE_SYSTEM_SQLITE+0!=1
19078 utf8_printf(stderr,
"SQLite header and source version mismatch\n%s\n%s\n",
19091 #if !SQLITE_SHELL_IS_UTF8
19093 argvToFree = malloc(
sizeof(argv[0])*argc*2);
19095 argv = argvToFree + argc;
19097 for(i=0; i<argc; i++){
19098 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
19101 n = (int)strlen(z);
19102 argv[i] = malloc( n+1 );
19104 memcpy(argv[i], z, n+1);
19105 argvToFree[i] = argv[i];
19111 assert( argc>=1 && argv && argv[0] );
19119 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
19120 SetConsoleCtrlHandler(ConsoleCtrlHandler,
TRUE);
19123 #ifdef SQLITE_SHELL_DBNAME_PROC
19129 extern void SQLITE_SHELL_DBNAME_PROC(
const char**);
19131 warnInmemoryDb = 0;
19141 for(i=1; i<argc; i++){
19152 azCmd = realloc(azCmd,
sizeof(azCmd[0])*nCmd);
19157 if( z[1]==
'-' ) z++;
19158 if( strcmp(z,
"-separator")==0
19159 || strcmp(z,
"-nullvalue")==0
19160 || strcmp(z,
"-newline")==0
19161 || strcmp(z,
"-cmd")==0
19164 }
else if( strcmp(z,
"-init")==0 ){
19166 }
else if( strcmp(z,
"-batch")==0 ){
19172 }
else if( strcmp(z,
"-heap")==0 ){
19173 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
19179 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
19184 }
else if( strcmp(z,
"-pagecache")==0 ){
19187 if( sz>70000 ) sz = 70000;
19191 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
19193 }
else if( strcmp(z,
"-lookaside")==0 ){
19201 #ifdef SQLITE_ENABLE_VFSTRACE
19202 }
else if( strcmp(z,
"-vfstrace")==0 ){
19203 extern int vfstrace_register(
19204 const char *zTraceName,
19205 const char *zOldVfsName,
19206 int (*xOut)(
const char*,
void*),
19210 vfstrace_register(
"trace",0,(
int(*)(
const char*,
void*))fputs,stderr,1);
19212 #ifdef SQLITE_ENABLE_MULTIPLEX
19213 }
else if( strcmp(z,
"-multiplex")==0 ){
19214 extern int sqlite3_multiple_initialize(
const char*,
int);
19215 sqlite3_multiplex_initialize(0, 1);
19217 }
else if( strcmp(z,
"-mmap")==0 ){
19220 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
19221 }
else if( strcmp(z,
"-sorterref")==0 ){
19225 }
else if( strcmp(z,
"-vfs")==0 ){
19227 #ifdef SQLITE_HAVE_ZLIB
19228 }
else if( strcmp(z,
"-zip")==0 ){
19231 }
else if( strcmp(z,
"-append")==0 ){
19233 #ifdef SQLITE_ENABLE_DESERIALIZE
19234 }
else if( strcmp(z,
"-deserialize")==0 ){
19236 }
else if( strcmp(z,
"-maxsize")==0 && i+1<argc ){
19239 }
else if( strcmp(z,
"-readonly")==0 ){
19241 }
else if( strcmp(z,
"-nofollow")==0 ){
19243 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
19244 }
else if( strncmp(z,
"-A",2)==0 ){
19249 }
else if( strcmp(z,
"-memtrace")==0 ){
19256 #ifdef SQLITE_SHELL_INIT_PROC
19262 extern void SQLITE_SHELL_INIT_PROC(
void);
19263 SQLITE_SHELL_INIT_PROC();
19276 utf8_printf(stderr,
"no such VFS: \"%s\"\n", argv[i]);
19282 #ifndef SQLITE_OMIT_MEMORYDB
19284 warnInmemoryDb = argc==1;
19313 for(i=1; i<argc; i++){
19315 if( z[0]!=
'-' )
continue;
19316 if( z[1]==
'-' ){ z++; }
19317 if( strcmp(z,
"-init")==0 ){
19319 }
else if( strcmp(z,
"-html")==0 ){
19321 }
else if( strcmp(z,
"-list")==0 ){
19323 }
else if( strcmp(z,
"-quote")==0 ){
19325 }
else if( strcmp(z,
"-line")==0 ){
19327 }
else if( strcmp(z,
"-column")==0 ){
19329 }
else if( strcmp(z,
"-csv")==0 ){
19332 #ifdef SQLITE_HAVE_ZLIB
19333 }
else if( strcmp(z,
"-zip")==0 ){
19336 }
else if( strcmp(z,
"-append")==0 ){
19338 #ifdef SQLITE_ENABLE_DESERIALIZE
19339 }
else if( strcmp(z,
"-deserialize")==0 ){
19341 }
else if( strcmp(z,
"-maxsize")==0 && i+1<argc ){
19344 }
else if( strcmp(z,
"-readonly")==0 ){
19346 }
else if( strcmp(z,
"-nofollow")==0 ){
19348 }
else if( strcmp(z,
"-ascii")==0 ){
19354 }
else if( strcmp(z,
"-separator")==0 ){
19357 }
else if( strcmp(z,
"-newline")==0 ){
19360 }
else if( strcmp(z,
"-nullvalue")==0 ){
19363 }
else if( strcmp(z,
"-header")==0 ){
19365 }
else if( strcmp(z,
"-noheader")==0 ){
19367 }
else if( strcmp(z,
"-echo")==0 ){
19369 }
else if( strcmp(z,
"-eqp")==0 ){
19371 }
else if( strcmp(z,
"-eqpfull")==0 ){
19373 }
else if( strcmp(z,
"-stats")==0 ){
19375 }
else if( strcmp(z,
"-scanstats")==0 ){
19377 }
else if( strcmp(z,
"-backslash")==0 ){
19384 }
else if( strcmp(z,
"-bail")==0 ){
19386 }
else if( strcmp(z,
"-version")==0 ){
19389 }
else if( strcmp(z,
"-interactive")==0 ){
19391 }
else if( strcmp(z,
"-batch")==0 ){
19393 }
else if( strcmp(z,
"-heap")==0 ){
19395 }
else if( strcmp(z,
"-pagecache")==0 ){
19397 }
else if( strcmp(z,
"-lookaside")==0 ){
19399 }
else if( strcmp(z,
"-mmap")==0 ){
19401 }
else if( strcmp(z,
"-memtrace")==0 ){
19403 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
19404 }
else if( strcmp(z,
"-sorterref")==0 ){
19407 }
else if( strcmp(z,
"-vfs")==0 ){
19409 #ifdef SQLITE_ENABLE_VFSTRACE
19410 }
else if( strcmp(z,
"-vfstrace")==0 ){
19413 #ifdef SQLITE_ENABLE_MULTIPLEX
19414 }
else if( strcmp(z,
"-multiplex")==0 ){
19417 }
else if( strcmp(z,
"-help")==0 ){
19419 }
else if( strcmp(z,
"-cmd")==0 ){
19424 if( i==argc-1 )
break;
19436 utf8_printf(stderr,
"Error: unable to process SQL \"%s\"\n", z);
19440 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
19441 }
else if( strncmp(z,
"-A", 2)==0 ){
19443 utf8_printf(stderr,
"Error: cannot mix regular SQL or dot-commands"
19444 " with \"%s\"\n", z);
19450 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
19452 arDotCommand(&data, 1, argv+i, argc-i);
19459 raw_printf(stderr,
"Use -help for a list of options.\n");
19470 for(i=0; i<nCmd; i++){
19471 if( azCmd[i][0]==
'.' ){
19473 if( rc )
return rc==2 ? 0 : rc;
19479 return rc!=0 ? rc : 1;
19481 utf8_printf(stderr,
"Error: unable to process SQL: %s\n", azCmd[i]);
19495 "SQLite version %s %.19s\n"
19496 "Enter \".help\" for usage hints.\n",
19499 if( warnInmemoryDb ){
19500 printf(
"Connected to a ");
19501 printBold(
"transient in-memory database");
19502 printf(
".\nUse \".open FILENAME\" to reopen on a "
19503 "persistent database.\n");
19505 zHistory = getenv(
"SQLITE_HISTORY");
19507 zHistory = strdup(zHistory);
19510 if( (zHistory = malloc(nHistory))!=0 ){
19515 #if HAVE_READLINE || HAVE_EDITLINE
19516 rl_attempted_completion_function = readline_completion;
19517 #elif HAVE_LINENOISE
19518 linenoiseSetCompletionCallback(linenoise_completion);
19542 #if !SQLITE_SHELL_IS_UTF8
19543 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
19548 memset(&data, 0,
sizeof(data));
static void output_c_string(FILE *out, const char *z)
static int apndWriteMark(ApndFile *p, sqlite3_file *pFile)
#define setBinaryMode(X, Y)
#define EXPERT_REPORT_PLAN
static int stdout_is_console
static int line_contains_semicolon(const char *z, int N)
static void shellLog(void *pArg, int iErrCode, const char *zMsg)
static int idxCreateFromWhere(sqlite3expert *p, IdxScan *pScan, IdxConstraint *pTail)
static int progress_handler(void *pClientData)
static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt,...)
static int callback(void *pArg, int nArg, char **azArg, char **azCol)
static int completionNext(sqlite3_vtab_cursor *cur)
static void endTimer(void)
static unsigned int get2byteInt(unsigned char *a)
static int shellDatabaseError(sqlite3 *db)
static char * idxAppendColDefn(int *pRc, char *zIn, IdxTable *pTab, IdxConstraint *pCons)
static void writefileFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
static void process_sqliterc(ShellState *p, const char *sqliterc_override)
int sqlite3CompletionVtabInit(sqlite3 *db)
static void tryToCloneData(ShellState *p, sqlite3 *newDb, const char *zTable)
static void readFileContents(sqlite3_context *ctx, const char *zName)
static int apndShmMap(sqlite3_file *, int iPg, int pgsz, int, void volatile **)
static char ** tableColumnList(ShellState *p, const char *zTab)
static int apndSectorSize(sqlite3_file *)
static char * find_home_dir(int clearFlag)
static void test_breakpoint(void)
static int idxHashString(const char *z, int n)
static void printBold(const char *zText)
static void * memtraceRealloc(void *p, int n)
static int completionClose(sqlite3_vtab_cursor *cur)
static int line_is_complete(char *zSql, int nSql)
static int process_input(ShellState *p)
static void shellEscapeCrnl(sqlite3_context *context, int argc, sqlite3_value **argv)
static void memtraceFree(void *p)
static char * cmdline_option_value(int argc, char **argv, int i)
static int apndDeviceCharacteristics(sqlite3_file *)
#define UNIQUE_TABLE_NAME
static struct rusage sBegin
static void explain_data_delete(ShellState *p)
static int apndOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int *)
static int apndFullPathname(sqlite3_vfs *, const char *zName, int, char *zOut)
static void idxHashInit(IdxHash *pHash)
int sqlite3_expert_count(sqlite3expert *)
static void appendText(ShellText *p, char const *zAppend, char quote)
static void freeText(ShellText *p)
static sqlite3_mem_methods ersaztMethods
static int fsdirRegister(sqlite3 *db)
static void apndShmBarrier(sqlite3_file *)
static FILE * memtraceOut
static int apndCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64 *)
static int expertEof(sqlite3_vtab_cursor *cur)
static int completionFilter(sqlite3_vtab_cursor *pVtabCursor, int idxNum, const char *idxStr, int argc, sqlite3_value **argv)
int idxFindIndexes(sqlite3expert *p, char **pzErr)
static int fileLinkStat(const char *zPath, struct stat *pStatBuf)
#define COMPLETION_COLUMN_PREFIX
static void beginTimer(void)
FILE * popen(const char *, const char *)
static void display_scanstats(sqlite3 *db, ShellState *pArg)
static int str_in_array(const char *zStr, const char **azArray)
static int optionMatch(const char *zStr, const char *zOpt)
static void bind_table_init(ShellState *p)
#define ShellSetFlag(P, X)
static int apndAccess(sqlite3_vfs *, const char *zName, int flags, int *)
#define EXPERT_REPORT_CANDIDATES
#define FSDIR_COLUMN_PATH
static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr)
static int apndDelete(sqlite3_vfs *, const char *zName, int syncDir)
#define COMPLETION_COLUMN_PHASE
#define SHELL_OPEN_APPENDVFS
static void apndDlError(sqlite3_vfs *, int nByte, char *zErrMsg)
static int shell_exec(ShellState *pArg, const char *zSql, char **pzErrMsg)
#define COMPLETION_DATABASES
static sqlite3_mem_methods memtraceBase
static int idxProcessOneTrigger(sqlite3expert *p, IdxWrite *pWrite, char **pzErr)
static void idxHashClear(IdxHash *pHash)
int main(int argc, char **argv)
static int idxAuthCallback(void *pCtx, int eOp, const char *z3, const char *z4, const char *zDb, const char *zTrigger)
static sqlite3_vfs apnd_vfs
#define UNUSED_PARAMETER(x)
static void eqp_render_level(ShellState *p, int iEqpId)
static void shellIdQuote(sqlite3_context *context, int argc, sqlite3_value **argv)
static int strlen30(const char *z)
static char quoteChar(const char *zName)
static int showHelp(FILE *out, const char *zPattern)
static int apndSync(sqlite3_file *, int flags)
static void verify_uninitialized(void)
#define SHFLG_PreserveRowid
static int expertDotCommand(ShellState *pState, char **azArg, int nArg)
static void resolve_backslashes(char *z)
void close_db(sqlite3 *db)
sqlite3expert * sqlite3_expert_new(sqlite3 *db, char **pzErr)
static int fsdirFilter(sqlite3_vtab_cursor *cur, int idxNum, const char *idxStr, int argc, sqlite3_value **argv)
#define SHELL_TRACE_PLAIN
static int apndFileControl(sqlite3_file *, int op, void *pArg)
#define SHELL_TRACE_NORMALIZED
static int expertFinish(ShellState *pState, int bCancel, char **pzErr)
static void sha3QueryFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
static int fsdirBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo)
#define SHELL_PROGRESS_QUIET
void shellReset(int *pRc, sqlite3_stmt *pStmt)
static int idxPopulateStat1(sqlite3expert *p, char **pzErr)
int sqlite3_expert_config(sqlite3expert *p, int op,...)
static int apndShmUnmap(sqlite3_file *, int deleteFlag)
static void eqp_reset(ShellState *p)
static int idxPrepareStmt(sqlite3 *db, sqlite3_stmt **ppStmt, char **pzErrmsg, const char *zSql)
static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid)
static int apndShmLock(sqlite3_file *, int offset, int n, int flags)
static void output_csv(ShellState *p, const char *z, int bSep)
static void open_db(ShellState *p, int openFlags)
static int apndRandomness(sqlite3_vfs *, int nByte, char *zOut)
static int fsdirColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i)
int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr)
static void sha3Func(sqlite3_context *context, int argc, sqlite3_value **argv)
static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt)
static int stdin_is_interactive
static void readfileFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText)
static void shellInt32(sqlite3_context *context, int argc, sqlite3_value **argv)
static void newTempFile(ShellState *p, const char *zSuffix)
static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed)
static const char * modeDescr[]
const char * sqlite3_expert_report(sqlite3expert *, int iStmt, int eReport)
static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast)
static sqlite3_module completionModule
static int apndUnfetch(sqlite3_file *, sqlite3_int64 iOfst, void *p)
static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid)
#define setTextMode(X, Y)
static int line_is_command_terminator(const char *zLine)
int sqlite3_appendvfs_init(sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi)
static void shellPutsFunc(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal)
static int completionColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i)
static int memtraceInit(void *p)
#define EXPERT_REPORT_SQL
static const char needCsvQuote[]
static int apndSleep(sqlite3_vfs *, int microseconds)
void shellPreparePrintf(sqlite3 *db, int *pRc, sqlite3_stmt **ppStmt, const char *zFmt,...)
static void output_quoted_escaped_string(FILE *out, const char *z)
#define COMPLETION_COLUMNS
static int expertNext(sqlite3_vtab_cursor *cur)
static int testcase_glob(const char *zGlob, const char *z)
#define OPEN_DB_KEEPALIVE
static unsigned char * SHA3Final(SHA3Context *p)
static sqlite3_int64 integerValue(const char *zArg)
static int uintCollFunc(void *notUsed, int nKey1, const void *pKey1, int nKey2, const void *pKey2)
static const char * unused_string(const char *z, const char *zA, const char *zB, char *zBuf)
static int writeFile(sqlite3_context *pCtx, const char *zFile, sqlite3_value *pData, mode_t mode, sqlite3_int64 mtime)
static sqlite3_int64 iBegin
struct IdxColumn IdxColumn
static void usage(int showDetail)
static void SHA3Update(SHA3Context *p, const unsigned char *aData, unsigned int nData)
static int makeDirectory(const char *zFile)
static void output_quoted_string(FILE *out, const char *z)
static void lsModeFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
int sqlite3_uint_init(sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi)
static void restore_debug_trace_modes(void)
static void interrupt_handler(int NotUsed)
static void main_init(ShellState *data)
#define SHELL_OPEN_UNSPEC
#define SHELL_OPEN_DESERIALIZE
#define ShellClearFlag(P, X)
static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor)
static int idxGetTableInfo(sqlite3 *db, const char *zTab, IdxTable **ppOut, char **pzErrmsg)
static int expertClose(sqlite3_vtab_cursor *cur)
int sqlite3_fileio_init(sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi)
static int apndSetSystemCall(sqlite3_vfs *, const char *, sqlite3_syscall_ptr)
int sqlite3MemTraceDeactivate(void)
#define SHELL_TRACE_EXPANDED
static void output_hex_blob(FILE *out, const void *pBlob, int nBlob)
static const char zOptions[]
static void displayStatLine(ShellState *p, char *zLabel, char *zFormat, int iStatusCtrl, int bReset)
static int apndLock(sqlite3_file *, int)
static void import_append_char(ImportCtx *p, int c)
static void output_html_string(FILE *out, const char *z)
static int run_table_dump_query(ShellState *p, const char *zSelect)
int sqlite3_shathree_init(sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi)
#define shell_stifle_history(X)
static int lintFkeyIndexes(ShellState *pState, char **azArg, int nArg)
static void idxConstraintFree(IdxConstraint *pConstraint)
static void toggleSelectOrder(sqlite3 *db)
static int apndRead(sqlite3_file *, void *, int iAmt, sqlite3_int64 iOfst)
static void eqp_render(ShellState *p)
static char * readFile(const char *zName, int *pnByte)
#define COMPLETION_COLUMN_CANDIDATE
static const char * apndNextSystemCall(sqlite3_vfs *, const char *zName)
static int completionDisconnect(sqlite3_vtab *pVtab)
static int expertFilter(sqlite3_vtab_cursor *cur, int idxNum, const char *idxStr, int argc, sqlite3_value **argv)
#define ShellHasFlag(P, X)
static void tryToClone(ShellState *p, const char *zNewDb)
static int apndWrite(sqlite3_file *, const void *, int iAmt, sqlite3_int64 iOfst)
static void * apndDlOpen(sqlite3_vfs *, const char *zFilename)
#define SHELL_OPEN_READONLY
static int strlenChar(const char *z)
void sqlite3_expert_destroy(sqlite3expert *)
static int apndClose(sqlite3_file *)
static int _all_whitespace(const char *z)
#define COMPLETION_KEYWORDS
static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg)
#define CTIMEOPT_VAL(opt)
#define COMPLETION_TABLES
void shellFinalize(int *pRc, sqlite3_stmt *pStmt)
static IdxHashEntry * idxHashFind(IdxHash *pHash, const char *zKey, int nKey)
static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p)
static void idxSampleFunc(sqlite3_context *pCtx, int argc, sqlite3_value **argv)
static void printSchemaLine(FILE *out, const char *z, const char *zTail)
#define FSDIR_COLUMN_MTIME
static int sql_trace_callback(unsigned mType, void *pArg, void *pP, void *pX)
#define shell_write_history(X)
static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile)
static void output_file_close(FILE *f)
static int expertConnect(sqlite3 *db, void *pAux, int argc, const char *const *argv, sqlite3_vtab **ppVtab, char **pzErr)
static int completionConnect(sqlite3 *db, void *pAux, int argc, const char *const *argv, sqlite3_vtab **ppVtab, char **pzErr)
static int completionEof(sqlite3_vtab_cursor *cur)
#define FSDIR_COLUMN_DATA
static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az)
static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor)
static int fsdirConnect(sqlite3 *db, void *pAux, int argc, const char *const *argv, sqlite3_vtab **ppVtab, char **pzErr)
static void outputModePop(ShellState *p)
static char * expertDequote(const char *zIn)
#define COMPLETION_COLUMN_WHOLELINE
static char * idxAppendText(int *pRc, char *zIn, const char *zFmt,...)
int deduceDatabaseType(const char *zName, int dfltZip)
static void editFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
static void tryToCloneSchema(ShellState *p, sqlite3 *newDb, const char *zWhere, void(*xForEach)(ShellState *, sqlite3 *, const char *))
static void outputModePush(ShellState *p)
static void KeccakF1600Step(SHA3Context *p)
static void idxTableFree(IdxTable *pTab)
static int wsToEol(const char *z)
#define APND_MARK_PREFIX_SZ
static void exec_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt)
static int expertDisconnect(sqlite3_vtab *pVtab)
#define FSDIR_COLUMN_MODE
static void(*)(void) apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym)
static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor)
static volatile int seenInterrupt
int sqlite3MemTraceActivate(FILE *out)
static char * ascii_read_one_field(ImportCtx *p)
static IdxConstraint * idxNewConstraint(int *pRc, const char *zColl)
static int idxIdentifierRequiresQuotes(const char *zId)
static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg)
static void idxScanFree(IdxScan *pScan, IdxScan *pLast)
static void SHA3Init(SHA3Context *p, int iSize)
static void fsdirResetCursor(fsdir_cursor *pCur)
static int apndGetLastError(sqlite3_vfs *, int, char *)
static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql)
static void shellFkeyCollateClause(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal)
static int idxBuildSampleTable(sqlite3expert *p, const char *zTab)
static EQPGraphRow * eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld)
static void createSelftestTable(ShellState *p)
static int shell_callback(void *pArg, int nArg, char **azArg, char **azCol, int *aiType)
static double timeDiff(struct timeval *pStart, struct timeval *pEnd)
#define SHFLG_CountChanges
static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i)
int sqlite3_completion_init(sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi)
static int memtraceSize(void *p)
static int apndTruncate(sqlite3_file *, sqlite3_int64 size)
#define COMPLETION_FIRST_PHASE
static int apndCurrentTime(sqlite3_vfs *, double *)
static int lintDotCommand(ShellState *pState, char **azArg, int nArg)
static int shellAuth(void *pClientData, int op, const char *zA1, const char *zA2, const char *zA3, const char *zA4)
static void freeColumnList(char **azCol)
#define EXPERT_CONFIG_SAMPLE
static char * csv_read_one_field(ImportCtx *p)
static int idxCreateCandidates(sqlite3expert *p)
static int fsdirClose(sqlite3_vtab_cursor *cur)
#define EXPERT_REPORT_INDEXES
static int idxRegisterVtab(sqlite3expert *p)
#define SQLITE_EXTENSION_INIT2(X)
static void shellAddSchemaName(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal)
static char * one_input_line(FILE *in, char *zPrior, int isContinuation)
static int apndCheckReservedLock(sqlite3_file *, int *pResOut)
static int idxHashAdd(int *pRc, IdxHash *pHash, const char *zKey, const char *zVal)
static char continuePrompt[20]
static int idxPopulateOneStat1(sqlite3expert *p, sqlite3_stmt *pIndexXInfo, sqlite3_stmt *pWriteStat, const char *zTab, const char *zIdx, char **pzErr)
static char mainPrompt[20]
static void idxDatabaseError(sqlite3 *db, char **pzErrmsg)
static int booleanValue(const char *zArg)
static int hexDigitValue(char c)
static char * shellFakeSchema(sqlite3 *db, const char *zSchema, const char *zName)
static int isNumber(const char *z, int *realnum)
static void completionCursorReset(completion_cursor *pCur)
static void set_table_name(ShellState *p, const char *zName)
static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile)
static int memtraceRoundup(int n)
static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo)
#define SHELL_PROGRESS_RESET
static const char * azHelp[]
static int db_int(ShellState *p, const char *zSql)
static int completionBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo)
static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs *, const char *z)
static void apndDlClose(sqlite3_vfs *, void *)
static int idxCreateFromCons(sqlite3expert *p, IdxScan *pScan, IdxConstraint *pEq, IdxConstraint *pTail)
static int display_stats(sqlite3 *db, ShellState *pArg, int bReset)
static int run_schema_dump_query(ShellState *p, const char *zQuery)
static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail)
static char * local_getline(char *zLine, FILE *in)
static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline)
static void idxRemFunc(sqlite3_context *pCtx, int argc, sqlite3_value **argv)
static void idxWriteFree(IdxWrite *pTab)
static void shell_out_of_memory(void)
static int idxFindCompatible(int *pRc, sqlite3 *dbm, IdxScan *pScan, IdxConstraint *pEq, IdxConstraint *pTail)
static int expertUpdate(sqlite3_vtab *pVtab, int nData, sqlite3_value **azData, sqlite_int64 *pRowid)
static int fsdirNext(sqlite3_vtab_cursor *cur)
static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt,...)
#define FSDIR_COLUMN_NAME
struct FsdirLevel FsdirLevel
static const char * idxHashSearch(IdxHash *pHash, const char *zKey, int nKey)
#define SHELL_OPEN_NORMAL
static void initText(ShellText *p)
static sqlite3 * globalDb
static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid)
static void shellModuleSchema(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal)
static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg)
static FILE * output_file_open(const char *zFile, int bTextMode)
static int apndUnlock(sqlite3_file *, int)
static void output_reset(ShellState *p)
static int idxPrintfPrepareStmt(sqlite3 *db, sqlite3_stmt **ppStmt, char **pzErrmsg, const char *zFmt,...)
static void clearTempFile(ShellState *p)
#define SHELL_OPEN_ZIPFILE
static unsigned int get4byteInt(unsigned char *a)
static int fsdirEof(sqlite3_vtab_cursor *cur)
int shellDeleteFile(const char *zFilename)
static void shellPrepare(sqlite3 *db, int *pRc, const char *zSql, sqlite3_stmt **ppStmt)
#define SHELL_PROGRESS_ONCE
static const sqlite3_io_methods apnd_io_methods
static int idxProcessTriggers(sqlite3expert *p, char **pzErr)
static int apndFetch(sqlite3_file *, sqlite3_int64 iOfst, int iAmt, void **pp)
static void disable_debug_trace_modes(void)
int sqlite3_expert_sql(sqlite3expert *p, const char *zSql, char **pzErr)
static void utf8_width_print(FILE *pOut, int w, const char *zUtf)
static void * memtraceMalloc(int n)
static int fsdirDisconnect(sqlite3_vtab *pVtab)
static void memtraceShutdown(void *p)
#define session_close_all(X)
static int fileStat(const char *zPath, struct stat *pStatBuf)
static int apndFileSize(sqlite3_file *, sqlite3_int64 *pSize)
#define shell_read_history(X)
static char * save_err_msg(sqlite3 *db)
static int do_meta_command(char *zLine, ShellState *p)
static sqlite3_int64 timeOfDay(void)
static int expertHandleSQL(ShellState *pState, const char *zSql, char **pzErr)
static void idxFinalize(int *pRc, sqlite3_stmt *pStmt)
static void hash_step_vformat(SHA3Context *p, const char *zFormat,...)
static void * idxMalloc(int *pRc, int nByte)
#define SQLITE_EXTENSION_INIT1
#define SQLITE_STMTSTATUS_MEMUSED
#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
#define SQLITE_TESTCTRL_PARSER_COVERAGE
#define SQLITE_FCNTL_DATA_VERSION
#define SQLITE_DESERIALIZE_FREEONCLOSE
#define SQLITE_FCNTL_SIZE_LIMIT
#define SQLITE_OPEN_CREATE
#define SQLITE_DBSTATUS_CACHE_HIT
#define SQLITE_TESTCTRL_ALWAYS
#define SQLITE_OK_LOAD_PERMANENTLY
sqlite_int64 sqlite3_int64
#define SQLITE_SCANSTAT_NLOOP
#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
#define SQLITE_DBSTATUS_STMT_USED
int sqlite3_initialize(void)
#define SQLITE_INDEX_CONSTRAINT_LT
#define SQLITE_LIMIT_ATTACHED
#define sqlite3_column_table_name
sqlite_uint64 sqlite3_uint64
#define SQLITE_SCANSTAT_EXPLAIN
static const char aPrefix[]
#define SQLITE_CONFIG_HEAP
#define SQLITE_DBCONFIG_DEFENSIVE
#define SQLITE_TESTCTRL_LOCALTIME_FAULT
#define SQLITE_TESTCTRL_IMPOSTER
#define SQLITE_DBCONFIG_DQS_DDL
int sqlite3_deserialize(sqlite3 *db, const char *zSchema, unsigned char *pData, sqlite3_int64 szDb, sqlite3_int64 szBuf, unsigned mFlags)
#define SQLITE_DETERMINISTIC
#define SQLITE_INDEX_CONSTRAINT_LE
#define SQLITE_LIMIT_COLUMN
#define SQLITE_STATUS_PAGECACHE_USED
#define SQLITE_STATUS_MALLOC_SIZE
#define SQLITE_DBCONFIG_ENABLE_TRIGGER
#define SQLITE_INDEX_CONSTRAINT_GE
#define SQLITE_LIMIT_WORKER_THREADS
#define SQLITE_OPEN_MAIN_DB
#define SQLITE_OPEN_READWRITE
#define SQLITE_LIMIT_COMPOUND_SELECT
#define SQLITE_VTAB_INNOCUOUS
#define SQLITE_STMTSTATUS_SORT
#define SQLITE_SCANSTAT_NVISIT
#define SQLITE_TESTCTRL_PRNG_SAVE
#define SQLITE_CONFIG_PAGECACHE
int sqlite3_enable_load_extension(sqlite3 *db, int onoff)
#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
#define SQLITE_DIRECTONLY
#define SQLITE_SCANSTAT_SELECTID
#define SQLITE_STMTSTATUS_AUTOINDEX
#define SQLITE_LIMIT_FUNCTION_ARG
#define SQLITE_LIMIT_VDBE_OP
#define SQLITE_CONFIG_GETMALLOC
long long int sqlite_int64
#define SQLITE_DBCONFIG_ENABLE_FKEY
#define SQLITE_TESTCTRL_PENDING_BYTE
#define SQLITE_CONFIG_LOG
#define SQLITE_TESTCTRL_PRNG_SEED
#define SQLITE_FCNTL_CHUNK_SIZE
#define SQLITE_DBSTATUS_CACHE_USED
#define SQLITE_CONSTRAINT
#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
#define SQLITE_CONFIG_MULTITHREAD
#define SQLITE_LIMIT_SQL_LENGTH
#define SQLITE_FCNTL_VFSNAME
#define SQLITE_LIMIT_EXPR_DEPTH
#define SQLITE_FCNTL_LOCK_TIMEOUT
#define SQLITE_SCANSTAT_EST
#define SQLITE_TRACE_PROFILE
#define SQLITE_TESTCTRL_PRNG_RESTORE
#define SQLITE_CONFIG_MALLOC
#define sqlite3_column_database_name
#define SQLITE_STATUS_PAGECACHE_OVERFLOW
#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS
#define SQLITE_DBSTATUS_LOOKASIDE_HIT
#define SQLITE_TESTCTRL_NEVER_CORRUPT
#define SQLITE_DBCONFIG_TRUSTED_SCHEMA
#define SQLITE_DBCONFIG_RESET_DATABASE
#define SQLITE_VTAB_DIRECTONLY
#define SQLITE_DBCONFIG_DQS_DML
#define SQLITE_DESERIALIZE_RESIZEABLE
#define SQLITE_TESTCTRL_ASSERT
#define SQLITE_STATUS_MEMORY_USED
#define SQLITE_TESTCTRL_OPTIMIZATIONS
int sqlite3_shutdown(void)
#define SQLITE_CONFIG_LOOKASIDE
#define SQLITE_INDEX_CONSTRAINT_EQ
#define SQLITE_DBCONFIG_ENABLE_QPSG
int sqlite3_config(int,...)
#define SQLITE_FCNTL_POWERSAFE_OVERWRITE
#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH
#define SQLITE_STMTSTATUS_RUN
#define SQLITE_FCNTL_VFS_POINTER
#define SQLITE_CONFIG_URI
#define SQLITE_FCNTL_HAS_MOVED
void(* sqlite3_syscall_ptr)(void)
#define SQLITE_CONFIG_MMAP_SIZE
#define SQLITE_FCNTL_TEMPFILENAME
#define SQLITE_DBCONFIG_WRITABLE_SCHEMA
#define SQLITE_OPEN_READONLY
#define sqlite3_column_origin_name
#define SQLITE_DBSTATUS_SCHEMA_USED
#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE
#define SQLITE_INDEX_CONSTRAINT_GT
#define SQLITE_LIMIT_TRIGGER_DEPTH
#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
#define SQLITE_OPEN_NOFOLLOW
#define SQLITE_STMTSTATUS_REPREPARE
#define SQLITE_TRACE_CLOSE
#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT
#define SQLITE_DBSTATUS_CACHE_WRITE
#define SQLITE_LIMIT_VARIABLE_NUMBER
#define SQLITE_FCNTL_PERSIST_WAL
#define SQLITE_STATUS_PAGECACHE_SIZE
int sqlite3_stmt_scanstatus(sqlite3_stmt *pStmt, int idx, int iScanStatusOp, void *pOut)
#define SQLITE_DBSTATUS_CACHE_SPILL
#define SQLITE_DBCONFIG_ENABLE_VIEW
#define SQLITE_STMTSTATUS_VM_STEP
#define SQLITE_DBSTATUS_LOOKASIDE_USED
#define SQLITE_FCNTL_RESERVE_BYTES
#define SQLITE_STATUS_PARSER_STACK
#define SQLITE_TRACE_STMT
#define SQLITE_CONFIG_SORTERREF_SIZE
#define SQLITE_LIMIT_LENGTH
#define SQLITE_TESTCTRL_BYTEORDER
#define SQLITE_DBSTATUS_CACHE_MISS
struct sqlite3_stmt sqlite3_stmt
#define SQLITE_TESTCTRL_PRNG_RESET
#define SQLITE_STMTSTATUS_FULLSCAN_STEP
#define SQLITE_DBCONFIG_TRIGGER_EQP
#define SQLITE_STATUS_MALLOC_COUNT
#define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
#define sqlite3_column_name
#define sqlite3_result_error
#define sqlite3_vsnprintf
#define sqlite3_value_int64
#define sqlite3_test_control
#define sqlite3_result_int
#define sqlite3_auto_extension
#define sqlite3_busy_timeout
#define sqlite3_column_double
#define sqlite3_vtab_on_conflict
#define sqlite3_bind_blob
#define sqlite3_total_changes
#define sqlite3_drop_modules
#define sqlite3_value_int
#define sqlite3_result_text
#define sqlite3_vfs_register
#define sqlite3_value_double
#define sqlite3_table_column_metadata
#define sqlite3_result_error_code
#define sqlite3_stmt_status
#define sqlite3_randomness
#define sqlite3_expanded_sql
#define sqlite3_set_authorizer
#define sqlite3_bind_double
#define sqlite3_bind_int64
#define sqlite3_normalized_sql
#define sqlite3_aggregate_context
#define sqlite3_backup_init
#define sqlite3_db_handle
#define sqlite3_load_extension
#define sqlite3_stmt_readonly
#define sqlite3_result_text64
#define sqlite3_realloc64
#define sqlite3_column_int64
#define sqlite3_keyword_name
#define sqlite3_get_autocommit
#define sqlite3_column_bytes
#define sqlite3_result_int64
#define sqlite3_vtab_config
#define sqlite3_libversion
#define sqlite3_vtab_collation
#define sqlite3_value_blob
#define sqlite3_stmt_isexplain
#define sqlite3_backup_finish
#define sqlite3_result_null
#define sqlite3_result_blob64
#define sqlite3_result_value
#define sqlite3_interrupt
#define sqlite3_result_error_nomem
#define sqlite3_db_status
#define sqlite3_column_decltype
#define sqlite3_extended_errcode
#define sqlite3_bind_value
#define sqlite3_column_type
#define sqlite3_column_int
#define sqlite3_file_control
#define sqlite3_column_value
#define sqlite3_create_collation
#define sqlite3_db_config
#define sqlite3_value_text
#define sqlite3_result_blob
#define sqlite3_backup_step
#define sqlite3_keyword_check
#define sqlite3_vtab_nochange
#define sqlite3_bind_null
#define sqlite3_prepare_v2
#define sqlite3_keyword_count
#define sqlite3_value_bytes
#define sqlite3_bind_parameter_count
#define sqlite3_bind_parameter_index
#define sqlite3_column_text
#define sqlite3_declare_vtab
#define sqlite3_bind_text
#define sqlite3_result_double
#define sqlite3_column_count
#define sqlite3_create_module
#define sqlite3_user_data
#define sqlite3_column_blob
#define sqlite3_create_function
#define sqlite3_bind_parameter_name
#define sqlite3_value_type
#define sqlite3_progress_handler
#define sqlite3_overload_function
#define sqlite3_context_db_handle
IdxHashEntry * aHash[1023]
struct IdxRemCtx::IdxRemSlot aSlot[1]
char outfile[FILENAME_MAX]
const struct sqlite3_io_methods * pMethods
struct sqlite3_index_info::sqlite3_index_constraint * aConstraint
struct sqlite3_index_info::sqlite3_index_orderby * aOrderBy
struct sqlite3_index_info::sqlite3_index_constraint_usage * aConstraintUsage
sqlite3_int64 estimatedRows
int(* xRead)(sqlite3_file *, void *, int iAmt, sqlite3_int64 iOfst)
int(* xClose)(sqlite3_file *)
int(* xLock)(sqlite3_file *, int)
int(* xShmMap)(sqlite3_file *, int iPg, int pgsz, int, void volatile **)
int(* xShmLock)(sqlite3_file *, int offset, int n, int flags)
int(* xFileControl)(sqlite3_file *, int op, void *pArg)
int(* xWrite)(sqlite3_file *, const void *, int iAmt, sqlite3_int64 iOfst)
int(* xUnfetch)(sqlite3_file *, sqlite3_int64 iOfst, void *p)
int(* xSectorSize)(sqlite3_file *)
int(* xSync)(sqlite3_file *, int flags)
int(* xCheckReservedLock)(sqlite3_file *, int *pResOut)
int(* xTruncate)(sqlite3_file *, sqlite3_int64 size)
int(* xUnlock)(sqlite3_file *, int)
int(* xDeviceCharacteristics)(sqlite3_file *)
int(* xFileSize)(sqlite3_file *, sqlite3_int64 *pSize)
int(* xFetch)(sqlite3_file *, sqlite3_int64 iOfst, int iAmt, void **pp)
void(* xShmBarrier)(sqlite3_file *)
int(* xShmUnmap)(sqlite3_file *, int deleteFlag)
void *(* xRealloc)(void *, int)
void(* xShutdown)(void *)
int(* xOpen)(sqlite3_vfs *, const char *zName, sqlite3_file *, int flags, int *pOutFlags)
int(* xCurrentTimeInt64)(sqlite3_vfs *, sqlite3_int64 *)
int(* xCurrentTime)(sqlite3_vfs *, double *)
IdxStatement * pStatement