Lines Matching +full:reset +full:- +full:pin +full:- +full:assert +full:- +full:time +full:- +full:ms

5 ** "shell.c" file used to implement the SQLite command-line shell.
13 ** source file to help make the command-line program easier to compile.
41 ** Optionally #include a user-defined header, whereby compilation options
64 ** the browser-mode build has much different user input requirements
98 ** Enable large-file support for fopen() and friends on unix.
119 #include <assert.h>
228 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
230 * overridden with the -batch command line option.
257 ** 2024-09-24
269 ** cross-platform I/O for UTF-8 content.
273 ** to the standard fopen() in the C-library.
275 ** But Windows does not have a standard C-library, at least not one that
276 ** can handle UTF-8. So for windows build, the interfaces resolve to new
277 ** C-language routines contained in the separate sqlite3_stdio.c source file.
279 ** So on all non-Windows platforms, simply #include this header file and
307 #define sqlite3_fsetmode(F,X) /*no-op*/
315 ** 2024-09-24
326 ** Implementation of standard I/O interfaces for UTF-8 that are missing
329 #ifdef _WIN32 /* This file is a no-op on all platforms except Windows */
339 #include <assert.h>
349 ** rendering ASCII text in cases where NL-to-CRLF expansion would
365 ** input and output. This is necessary for some non-Microsoft run-times
366 ** that implement stdio differently from Microsoft/Visual-Studio.
387 ** multi-byte representation in UTF-8). This is the only way we
389 ** at the same time avoiding undesirable \n to \r\n translation.
408 ** Work-alike for the fopen() routine from the standard C library.
434 ** Work-alike for the popen() routine from the standard C library.
458 ** Work-alike for fgets() from the standard C library.
462 /* When reading from the command-prompt in Windows, it is necessary in sqlite3_fgets()
463 ** to use _O_WTEXT input mode to read UTF-16 characters, then translate in sqlite3_fgets()
464 ** that into UTF-8. Otherwise, non-ASCII characters all get translated in sqlite3_fgets()
472 && ReadConsoleW(GetStdHandle(STD_INPUT_HANDLE), b1, sz-1, &nRead, 0) in sqlite3_fgets()
484 WideCharToMultiByte(CP_UTF8, 0, b1, -1, buf, sz, 0, 0); in sqlite3_fgets()
512 sz -= i; in piecemealOutput()
524 sz -= i; in piecemealOutput()
530 ** Work-alike for fputs() from the standard C library.
558 ** non-console I/O even if that macro is defined, write using the in sqlite3_fputs()
574 ** Work-alike for fprintf() from the standard C library.
579 /* When writing to the command-prompt in Windows, it is necessary in sqlite3_fprintf()
580 ** to use _O_WTEXT input mode and write UTF-16 characters. in sqlite3_fprintf()
651 /* Return the current wall-clock time */
657 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){ in timeOfDay()
658 clockVfs->xCurrentTimeInt64(clockVfs, &t); in timeOfDay()
661 clockVfs->xCurrentTime(clockVfs, &r); in timeOfDay()
668 #include <sys/time.h>
674 struct timeval ru_utime; /* user CPU time used */
675 struct timeval ru_stime; /* system CPU time used */
682 static struct rusage sBegin; /* CPU time at start */
683 static sqlite3_int64 iBegin; /* Wall-clock time at start */
697 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + in timeDiff()
698 (double)(pEnd->tv_sec - pStart->tv_sec); in timeDiff()
709 sqlite3_fprintf(out, "Run Time: real %.3f user %f sys %f\n", in endTimer()
710 (iEnd - iBegin)*0.001, in endTimer()
777 return (double) ((i64End - i64Start) / 10000000.0); in timeDiff()
788 sqlite3_fprintf(out, "Run Time: real %.3f user %f sys %f\n", in endTimer()
789 (ftWallEnd - ftWallBegin)*0.001, in endTimer()
801 #define END_TIMER(X) /*no-op*/
829 ** in order to show that UTF-16 translation is done in the sign-on
842 ** True if an interrupt (Control-C) has been received.
862 /* This is variant of the standard-library strncpy() routine with the
863 ** one change that the destination string is always zero-terminated, even
864 ** if there is no zero-terminator in the first n-1 characters of the source
869 for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i]; in shell_strncpy()
875 ** strcpy() workalike to squelch an unwarranted link-time warning
885 ** or open parentheses level if non-zero, or continuation prompt as set.
921 p->inParenLevel += ni; in trackParenLevel()
922 if( ni==0 ) p->inParenLevel = 0; in trackParenLevel()
923 p->zScannerAwaits = 0; in trackParenLevel()
929 p->zScannerAwaits = s; in setLexemeOpen()
930 p->acAwait[0] = 0; in setLexemeOpen()
932 p->acAwait[0] = c; in setLexemeOpen()
933 p->zScannerAwaits = p->acAwait; in setLexemeOpen()
946 if( ndp > ncp-3 ) return continuePrompt; in dynamicContinuePrompt()
950 PROMPT_LEN_MAX-4); in dynamicContinuePrompt()
961 PROMPT_LEN_MAX-4); in dynamicContinuePrompt()
968 /* Indicate out-of-memory and exit. */
975 ** out-of-memory error.
1081 ** estimate might be 0 or 2 for zero-width and double-width characters.
1096 iLast = sizeof(aUWidth)/sizeof(aUWidth[0]) - 1; in cli_wcwidth()
1097 while( iFirst<iLast-1 ){ in cli_wcwidth()
1103 iLast = iMid - 1; in cli_wcwidth()
1113 ** Compute the value and length of a multi-byte UTF-8 character that
1116 ** This routine only works for *multi-byte* UTF-8 characters.
1141 ** Return the width, in display columns, of a UTF-8 string.
1143 ** Each normal character counts as 1. Zero-width characters count
1144 ** as zero, and double-width characters count as 2.
1187 ** then right-justify the text. W is the width in UTF-8 characters, not
1191 ** Take into account zero-width and double-width Unicode characters.
1192 ** In other words, a zero-width character does not count toward the
1193 ** the w limit. A double-width character counts as two.
1201 int aw = w<0 ? -w : w; in utf8_width_print()
1225 sqlite3_fprintf(out, "%*s%s", aw-n, "", zUtf); in utf8_width_print()
1227 sqlite3_fprintf(out, "%s%*s", zUtf, aw-n, ""); in utf8_width_print()
1236 if( *z=='-' || *z=='+' ) z++; in isNumber()
1251 if( *z=='+' || *z=='-' ) z++; in isNumber()
1261 ** lower 30 bits of a 32-bit signed integer.
1266 return 0x3fffffff & (int)(z2 - z); in strlen30()
1334 if( sqlite3_fgets(&zLine[n], nLine - n, in)==0 ){ in local_getline()
1343 if( n>0 && zLine[n-1]=='\n' ){ in local_getline()
1344 n--; in local_getline()
1345 if( n>0 && zLine[n-1]=='\r' ) n--; in local_getline()
1401 ** Return the value of a hexadecimal digit. Return -1 if the input
1405 if( c>='0' && c<='9' ) return c - '0'; in hexDigitValue()
1406 if( c>='a' && c<='f' ) return c - 'a' + 10; in hexDigitValue()
1407 if( c>='A' && c<='F' ) return c - 'A' + 10; in hexDigitValue()
1408 return -1; in hexDigitValue()
1429 if( zArg[0]=='-' ){ in integerValue()
1444 v = v*10 + zArg[0] - '0'; in integerValue()
1454 return isNeg? -v : v; in integerValue()
1474 free(p->z); in freeText()
1478 /* zIn is either a pointer to a NULL-terminated string in memory obtained
1491 len = nAppend+p->n+1; in appendText()
1499 if( p->z==0 || p->n+len>=p->nAlloc ){ in appendText()
1500 p->nAlloc = p->nAlloc*2 + len + 20; in appendText()
1501 p->z = realloc(p->z, p->nAlloc); in appendText()
1502 shell_check_oom(p->z); in appendText()
1506 char *zCsr = p->z+p->n; in appendText()
1513 p->n = (int)(zCsr - p->z); in appendText()
1516 memcpy(p->z+p->n, zAppend, nAppend); in appendText()
1517 p->n += nAppend; in appendText()
1518 p->z[p->n] = '\0'; in appendText()
1524 ** because it contains non-alphanumeric characters, or because it is an
1559 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); in shellFakeSchema()
1591 ** Use the C-library strtod() function to convert string X into a double.
1592 ** Used for comparing the accuracy of SQLite's internal text-to-float conversion
1593 ** routines against the C-library.
1609 ** Use the C-library printf() function to convert real value X into a string.
1610 ** Used for comparing the accuracy of SQLite's internal float-to-text conversion
1611 ** routines against the C-library.
1624 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); in shellDtostr()
1633 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
1691 sqlite3_result_text(pCtx, z, -1, sqlite3_free); in shellAddSchemaName()
1701 ** The source code for several run-time loadable extensions is inserted
1813 # define BAD_INTPTR_T ((intptr_t)(-1))
1854 ** function. This function is not thread-safe.
1892 ** This function is not thread-safe.
1905 ** The function call to GetEnvironmentVariableA() failed -OR- in windirent_getenv()
1912 ** -AND- the buffer contains the entire value. in windirent_getenv()
1933 /* TODO: Remove this if Unix-style root paths are not used. */ in opendir()
1956 dirp->d_handle = _wfindfirst(data.name, &data); in opendir()
1958 if( dirp->d_handle==BAD_INTPTR_T ){ in opendir()
1968 if( _wfindnext(dirp->d_handle, &data)==-1 ){ in opendir()
1977 dirp->d_first.d_attributes = data.attrib; in opendir()
1978 WideCharToMultiByte(CP_UTF8, 0, data.name, -1, in opendir()
1979 dirp->d_first.d_name, DIRENT_NAME_MAX, 0, 0); in opendir()
1993 if( dirp->d_first.d_ino==0 ){ in readdir()
1994 dirp->d_first.d_ino++; in readdir()
1995 dirp->d_next.d_ino++; in readdir()
1997 return &dirp->d_first; in readdir()
2003 if( _wfindnext(dirp->d_handle, &data)==-1 ) return NULL; in readdir()
2008 dirp->d_next.d_ino++; in readdir()
2009 dirp->d_next.d_attributes = data.attrib; in readdir()
2010 WideCharToMultiByte(CP_UTF8, 0, data.name, -1, in readdir()
2011 dirp->d_next.d_name, DIRENT_NAME_MAX, 0, 0); in readdir()
2012 return &dirp->d_next; in readdir()
2025 if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){ in closedir()
2026 result = _findclose(dirp->d_handle); in closedir()
2040 ** 2019-01-21
2059 ** This extension is used to implement the --memtrace option of the
2060 ** command-line shell.
2062 #include <assert.h>
2092 fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n", in memtraceRealloc()
2151 ** 2023-06-21
2170 ** This extension is used to implement the --pcachetrace option of the
2171 ** command-line shell.
2173 #include <assert.h>
2189 fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p) -> %d\n", pArg, nRes); in pcachetraceInit()
2207 fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d) -> %p\n", in pcachetraceCreate()
2225 fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p) -> %d\n", p, nRes); in pcachetracePagecount()
2240 fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d) -> %p\n", in pcachetraceFetch()
2333 ** 2017-03-08
2345 ** in the way described by the (U.S.) NIST FIPS 202 SHA-3 Standard.
2353 ** X is NULL. If inputs X is text, the UTF-8 rendering of that text is
2356 ** then that number if converted into UTF-8 text and the hash is computed
2367 ** The SIZE argument is optional. If omitted, the SHA3-256 hash algorithm
2380 ** by an 8-byte big-endian binary of the
2381 ** 64-bit signed integer. (Nine bytes total.)
2383 ** typeof(Y)='real' The character "F" followed by an 8-byte
2384 ** big-ending binary of the double. (Nine
2389 ** in the prefix is the minimum-length decimal
2398 ** in the prefix is the minimum-length decimal
2399 ** representation of the byte-length of the blob.
2435 #include <assert.h>
2448 ** and whether or not that determination is run-time or compile-time.
2450 ** For best performance, an attempt is made to guess at the byte-order
2451 ** using C-preprocessor macros. If that is unsuccessful, or if
2452 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
2453 ** at run-time.
2485 ** A single step of the Keccak mixing function for a 1600-bit state
2506 # define a00 (p->u.s[0]) in KeccakF1600Step()
2507 # define a01 (p->u.s[1]) in KeccakF1600Step()
2508 # define a02 (p->u.s[2]) in KeccakF1600Step()
2509 # define a03 (p->u.s[3]) in KeccakF1600Step()
2510 # define a04 (p->u.s[4]) in KeccakF1600Step()
2511 # define a10 (p->u.s[5]) in KeccakF1600Step()
2512 # define a11 (p->u.s[6]) in KeccakF1600Step()
2513 # define a12 (p->u.s[7]) in KeccakF1600Step()
2514 # define a13 (p->u.s[8]) in KeccakF1600Step()
2515 # define a14 (p->u.s[9]) in KeccakF1600Step()
2516 # define a20 (p->u.s[10]) in KeccakF1600Step()
2517 # define a21 (p->u.s[11]) in KeccakF1600Step()
2518 # define a22 (p->u.s[12]) in KeccakF1600Step()
2519 # define a23 (p->u.s[13]) in KeccakF1600Step()
2520 # define a24 (p->u.s[14]) in KeccakF1600Step()
2521 # define a30 (p->u.s[15]) in KeccakF1600Step()
2522 # define a31 (p->u.s[16]) in KeccakF1600Step()
2523 # define a32 (p->u.s[17]) in KeccakF1600Step()
2524 # define a33 (p->u.s[18]) in KeccakF1600Step()
2525 # define a34 (p->u.s[19]) in KeccakF1600Step()
2526 # define a40 (p->u.s[20]) in KeccakF1600Step()
2527 # define a41 (p->u.s[21]) in KeccakF1600Step()
2528 # define a42 (p->u.s[22]) in KeccakF1600Step()
2529 # define a43 (p->u.s[23]) in KeccakF1600Step()
2530 # define a44 (p->u.s[24]) in KeccakF1600Step()
2531 # define ROL64(a,x) ((a<<x)|(a>>(64-x))) in KeccakF1600Step()
2811 p->iSize = iSize; in SHA3Init()
2813 p->nRate = (1600 - ((iSize + 31)&~31)*2)/8; in SHA3Init()
2815 p->nRate = (1600 - 2*256)/8; in SHA3Init()
2818 /* Known to be little-endian at compile-time. No-op */ in SHA3Init()
2820 p->ixMask = 7; /* Big-endian */ in SHA3Init()
2826 p->ixMask = 0; in SHA3Init()
2829 p->ixMask = 7; in SHA3Init()
2847 if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){ in SHA3Update()
2849 p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i]; in SHA3Update()
2850 p->nLoaded += 8; in SHA3Update()
2851 if( p->nLoaded>=p->nRate ){ in SHA3Update()
2853 p->nLoaded = 0; in SHA3Update()
2860 p->u.x[p->nLoaded] ^= aData[i]; in SHA3Update()
2862 p->u.x[p->nLoaded^0x07] ^= aData[i]; in SHA3Update()
2864 p->u.x[p->nLoaded^p->ixMask] ^= aData[i]; in SHA3Update()
2866 p->nLoaded++; in SHA3Update()
2867 if( p->nLoaded==p->nRate ){ in SHA3Update()
2869 p->nLoaded = 0; in SHA3Update()
2881 if( p->nLoaded==p->nRate-1 ){ in SHA3Final()
2888 p->nLoaded = p->nRate - 1; in SHA3Final()
2891 for(i=0; i<p->nRate; i++){ in SHA3Final()
2892 p->u.x[i+p->nRate] = p->u.x[i^p->ixMask]; in SHA3Final()
2894 return &p->u.x[p->nRate]; in SHA3Final()
2902 ** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
2904 ** For all other non-NULL types of input, X is converted into a UTF-8 string
2923 "384 512", -1); in sha3Func()
2970 for(j=8; j>=1; j--){ in sha3UpdateFromValue()
2984 for(j=8; j>=1; j--){ in sha3UpdateFromValue()
3013 ** argument. The results are hashed using a SIZE-bit SHA3. The default
3022 ** F<ieee-float>
3027 ** the size of that text. The SQL text is UTF-8. A single R character
3029 ** I mean an 8-byte little-endian integer <int>. F is a floating point
3030 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
3032 ** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
3063 "384 512", -1); in sha3QueryFunc()
3070 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql); in sha3QueryFunc()
3075 sqlite3_result_error(context, zMsg, -1); in sha3QueryFunc()
3080 char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt)); in sha3QueryFunc()
3082 sqlite3_result_error(context, zMsg, -1); in sha3QueryFunc()
3117 if( p->nRate==0 ){ in sha3AggStep()
3138 if( p->iSize ){ in sha3AggFinal()
3139 sqlite3_result_blob(context, SHA3Final(p), p->iSize/8, SQLITE_TRANSIENT); in sha3AggFinal()
3190 ** 2017-01-27
3215 #include <assert.h>
3231 #define rol(x,k) SHA_ROT(x,k,32-(k))
3232 #define ror(x,k) SHA_ROT(x,32-(k),k)
3243 * Rl0() for little-endian and Rb0() for big-endian. Endianness is
3244 * determined at run-time.
3260 * Hash a single 512-bit block. This is the core of the algorithm.
3275 /* Copy p->state[] to working vars */ in SHA1Transform()
3331 p->state[0] = 0x67452301; in hash_init()
3332 p->state[1] = 0xEFCDAB89; in hash_init()
3333 p->state[2] = 0x98BADCFE; in hash_init()
3334 p->state[3] = 0x10325476; in hash_init()
3335 p->state[4] = 0xC3D2E1F0; in hash_init()
3336 p->count[0] = p->count[1] = 0; in hash_init()
3347 j = p->count[0]; in hash_step()
3348 if( (p->count[0] += len << 3) < j ){ in hash_step()
3349 p->count[1] += (len>>29)+1; in hash_step()
3353 (void)memcpy(&p->buffer[j], data, (i = 64-j)); in hash_step()
3354 SHA1Transform(p->state, p->buffer); in hash_step()
3356 SHA1Transform(p->state, &data[i]); in hash_step()
3362 (void)memcpy(&p->buffer[j], &data[i], len - i); in hash_step()
3383 ** message digest as lower-case hexadecimal and put it into
3396 finalcount[i] = (unsigned char)((p->count[(i >= 4 ? 0 : 1)] in hash_finish()
3397 >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */ in hash_finish()
3400 while ((p->count[0] & 504) != 448){ in hash_finish()
3405 digest[i] = (unsigned char)((p->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255); in hash_finish()
3423 ** Return a lower-case hexadecimal rendering of the SHA1 hash of the
3425 ** types of input, X is converted into a UTF-8 string and the string
3439 assert( argc==1 ); in sha1Func()
3484 assert( argc==1 ); in sha1QueryFunc()
3488 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql); in sha1QueryFunc()
3493 sqlite3_result_error(context, zMsg, -1); in sha1QueryFunc()
3498 char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt)); in sha1QueryFunc()
3500 sqlite3_result_error(context, zMsg, -1); in sha1QueryFunc()
3525 for(j=8; j>=1; j--){ in sha1QueryFunc()
3539 for(j=8; j>=1; j--){ in sha1QueryFunc()
3602 ** 2020-04-14
3628 ** 64-bit machine integer.
3632 #include <assert.h>
3650 x = zA[i] - zB[j]; in uintCollFunc()
3664 return -1; in uintCollFunc()
3678 return (nKey1 - i) - (nKey2 - j); in uintCollFunc()
3697 ** 2020-06-22
3708 ** Routines to implement arbitrary-precision decimal math.
3714 #include <assert.h>
3745 sqlite3_free(p->a); in decimal_clear()
3769 p->sign = 0; in decimalNewFromText()
3770 p->oom = 0; in decimalNewFromText()
3771 p->isInit = 1; in decimalNewFromText()
3772 p->isNull = 0; in decimalNewFromText()
3773 p->nDigit = 0; in decimalNewFromText()
3774 p->nFrac = 0; in decimalNewFromText()
3775 p->a = sqlite3_malloc64( n+1 ); in decimalNewFromText()
3776 if( p->a==0 ) goto new_from_text_failed; in decimalNewFromText()
3778 if( zIn[i]=='-' ){ in decimalNewFromText()
3779 p->sign = 1; in decimalNewFromText()
3788 p->a[p->nDigit++] = c - '0'; in decimalNewFromText()
3790 p->nFrac = p->nDigit + 1; in decimalNewFromText()
3795 if( zIn[j]=='-' ){ in decimalNewFromText()
3803 iExp = iExp*10 + zIn[j] - '0'; in decimalNewFromText()
3807 if( neg ) iExp = -iExp; in decimalNewFromText()
3812 if( p->nFrac ){ in decimalNewFromText()
3813 p->nFrac = p->nDigit - (p->nFrac - 1); in decimalNewFromText()
3816 if( p->nFrac>0 ){ in decimalNewFromText()
3817 if( iExp<=p->nFrac ){ in decimalNewFromText()
3818 p->nFrac -= iExp; in decimalNewFromText()
3821 iExp -= p->nFrac; in decimalNewFromText()
3822 p->nFrac = 0; in decimalNewFromText()
3826 p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 ); in decimalNewFromText()
3827 if( p->a==0 ) goto new_from_text_failed; in decimalNewFromText()
3828 memset(p->a+p->nDigit, 0, iExp); in decimalNewFromText()
3829 p->nDigit += iExp; in decimalNewFromText()
3833 iExp = -iExp; in decimalNewFromText()
3834 nExtra = p->nDigit - p->nFrac - 1; in decimalNewFromText()
3837 p->nFrac += iExp; in decimalNewFromText()
3840 iExp -= nExtra; in decimalNewFromText()
3841 p->nFrac = p->nDigit - 1; in decimalNewFromText()
3845 p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 ); in decimalNewFromText()
3846 if( p->a==0 ) goto new_from_text_failed; in decimalNewFromText()
3847 memmove(p->a+iExp, p->a, p->nDigit); in decimalNewFromText()
3848 memset(p->a, 0, iExp); in decimalNewFromText()
3849 p->nDigit += iExp; in decimalNewFromText()
3850 p->nFrac += iExp; in decimalNewFromText()
3857 if( p->a ) sqlite3_free(p->a); in decimalNewFromText()
3871 ** If the pIn argument is SQLITE_TEXT or SQLITE_INTEGER, it is converted
3874 ** If pIn is NULL or if it is a BLOB that is not exactly 8 bytes in length,
3879 sqlite3_value *pIn, /* Construct the decimal object from this */ in decimal_new() argument
3880 int bTextOnly /* Always interpret pIn as text if true */ in decimal_new()
3883 int eType = sqlite3_value_type(pIn); in decimal_new()
3890 const char *zIn = (const char*)sqlite3_value_text(pIn); in decimal_new()
3891 int n = sqlite3_value_bytes(pIn); in decimal_new()
3898 p = decimalFromDouble(sqlite3_value_double(pIn)); in decimal_new()
3908 if( sqlite3_value_bytes(pIn)!=sizeof(r) ) break; in decimal_new()
3909 x = sqlite3_value_blob(pIn); in decimal_new()
3937 if( p==0 || p->oom ){ in decimal_result()
3941 if( p->isNull ){ in decimal_result()
3945 z = sqlite3_malloc( p->nDigit+4 ); in decimal_result()
3951 if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){ in decimal_result()
3952 p->sign = 0; in decimal_result()
3954 if( p->sign ){ in decimal_result()
3955 z[0] = '-'; in decimal_result()
3958 n = p->nDigit - p->nFrac; in decimal_result()
3963 while( n>1 && p->a[j]==0 ){ in decimal_result()
3965 n--; in decimal_result()
3968 z[i++] = p->a[j] + '0'; in decimal_result()
3970 n--; in decimal_result()
3972 if( p->nFrac ){ in decimal_result()
3975 z[i++] = p->a[j] + '0'; in decimal_result()
3977 }while( j<p->nDigit ); in decimal_result()
3998 if( p==0 || p->oom ){ in decimal_result_sci()
4002 if( p->isNull ){ in decimal_result_sci()
4006 for(nDigit=p->nDigit; nDigit>0 && p->a[nDigit-1]==0; nDigit--){} in decimal_result_sci()
4007 for(nZero=0; nZero<nDigit && p->a[nZero]==0; nZero++){} in decimal_result_sci()
4008 nFrac = p->nFrac + (nDigit - p->nDigit); in decimal_result_sci()
4009 nDigit -= nZero; in decimal_result_sci()
4021 a = &p->a[nZero]; in decimal_result_sci()
4023 if( p->sign && nDigit>0 ){ in decimal_result_sci()
4024 z[0] = '-'; in decimal_result_sci()
4039 exp = nDigit - nFrac - 1; in decimal_result_sci()
4040 sqlite3_snprintf(nDigit+20-i, &z[i], "e%+03d", exp); in decimal_result_sci()
4041 sqlite3_result_text(pCtx, z, -1, sqlite3_free); in decimal_result_sci()
4051 ** pA->isNull==0
4053 ** pB->isNull==0
4057 if( pA->sign!=pB->sign ){ in decimal_cmp()
4058 return pA->sign ? -1 : +1; in decimal_cmp()
4060 if( pA->sign ){ in decimal_cmp()
4065 nASig = pA->nDigit - pA->nFrac; in decimal_cmp()
4066 nBSig = pB->nDigit - pB->nFrac; in decimal_cmp()
4068 return nASig - nBSig; in decimal_cmp()
4070 n = pA->nDigit; in decimal_cmp()
4071 if( n>pB->nDigit ) n = pB->nDigit; in decimal_cmp()
4072 rc = memcmp(pA->a, pB->a, n); in decimal_cmp()
4074 rc = pA->nDigit - pB->nDigit; in decimal_cmp()
4095 if( pA==0 || pA->isNull ) goto cmp_done; in decimalCmpFunc()
4097 if( pB==0 || pB->isNull ) goto cmp_done; in decimalCmpFunc()
4099 if( rc<0 ) rc = -1; in decimalCmpFunc()
4115 nAddFrac = nFrac - p->nFrac; in decimal_expand()
4116 nAddSig = (nDigit - p->nDigit) - nAddFrac; in decimal_expand()
4118 p->a = sqlite3_realloc64(p->a, nDigit+1); in decimal_expand()
4119 if( p->a==0 ){ in decimal_expand()
4120 p->oom = 1; in decimal_expand()
4124 memmove(p->a+nAddSig, p->a, p->nDigit); in decimal_expand()
4125 memset(p->a, 0, nAddSig); in decimal_expand()
4126 p->nDigit += nAddSig; in decimal_expand()
4129 memset(p->a+p->nDigit, 0, nAddFrac); in decimal_expand()
4130 p->nDigit += nAddFrac; in decimal_expand()
4131 p->nFrac += nAddFrac; in decimal_expand()
4146 if( pA->oom || pB==0 || pB->oom ){ in decimal_add()
4147 pA->oom = 1; in decimal_add()
4150 if( pA->isNull || pB->isNull ){ in decimal_add()
4151 pA->isNull = 1; in decimal_add()
4154 nSig = pA->nDigit - pA->nFrac; in decimal_add()
4155 if( nSig && pA->a[0]==0 ) nSig--; in decimal_add()
4156 if( nSig<pB->nDigit-pB->nFrac ){ in decimal_add()
4157 nSig = pB->nDigit - pB->nFrac; in decimal_add()
4159 nFrac = pA->nFrac; in decimal_add()
4160 if( nFrac<pB->nFrac ) nFrac = pB->nFrac; in decimal_add()
4164 if( pA->oom || pB->oom ){ in decimal_add()
4165 pA->oom = 1; in decimal_add()
4167 if( pA->sign==pB->sign ){ in decimal_add()
4169 for(i=nDigit-1; i>=0; i--){ in decimal_add()
4170 int x = pA->a[i] + pB->a[i] + carry; in decimal_add()
4173 pA->a[i] = x - 10; in decimal_add()
4176 pA->a[i] = x; in decimal_add()
4182 rc = memcmp(pA->a, pB->a, nDigit); in decimal_add()
4184 aA = pB->a; in decimal_add()
4185 aB = pA->a; in decimal_add()
4186 pA->sign = !pA->sign; in decimal_add()
4188 aA = pA->a; in decimal_add()
4189 aB = pB->a; in decimal_add()
4191 for(i=nDigit-1; i>=0; i--){ in decimal_add()
4192 int x = aA[i] - aB[i] - borrow; in decimal_add()
4194 pA->a[i] = x+10; in decimal_add()
4197 pA->a[i] = x; in decimal_add()
4218 if( pA==0 || pA->oom || pA->isNull in decimalMul()
4219 || pB==0 || pB->oom || pB->isNull in decimalMul()
4223 acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 ); in decimalMul()
4225 pA->oom = 1; in decimalMul()
4228 memset(acc, 0, pA->nDigit + pB->nDigit + 2); in decimalMul()
4229 minFrac = pA->nFrac; in decimalMul()
4230 if( pB->nFrac<minFrac ) minFrac = pB->nFrac; in decimalMul()
4231 for(i=pA->nDigit-1; i>=0; i--){ in decimalMul()
4232 signed char f = pA->a[i]; in decimalMul()
4234 for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){ in decimalMul()
4235 x = acc[k] + f*pB->a[j] + carry; in decimalMul()
4241 acc[k-1] += x/10; in decimalMul()
4243 sqlite3_free(pA->a); in decimalMul()
4244 pA->a = acc; in decimalMul()
4246 pA->nDigit += pB->nDigit + 2; in decimalMul()
4247 pA->nFrac += pB->nFrac; in decimalMul()
4248 pA->sign ^= pB->sign; in decimalMul()
4249 while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){ in decimalMul()
4250 pA->nFrac--; in decimalMul()
4251 pA->nDigit--; in decimalMul()
4264 if( N<-20000 || N>20000 ) goto pow2_fault; in decimalPow2()
4266 if( pA==0 || pA->oom ) goto pow2_fault; in decimalPow2()
4271 N = -N; in decimalPow2()
4274 if( pX==0 || pX->oom ) goto pow2_fault; in decimalPow2()
4278 if( pA->oom ) goto pow2_fault; in decimalPow2()
4305 r = -r; in decimalFromDouble()
4315 m = a & ((((sqlite3_int64)1)<<52)-1); in decimalFromDouble()
4325 if( isNeg ) m = -m; in decimalFromDouble()
4326 e = e - 1075; in decimalFromDouble()
4348 ** point value is done. Or if X is an 8-byte blob, it is interpreted
4424 pB->sign = !pB->sign; in decimalSubFunc()
4447 if( !p->isInit ){ in decimalSumStep()
4448 p->isInit = 1; in decimalSumStep()
4449 p->a = sqlite3_malloc(2); in decimalSumStep()
4450 if( p->a==0 ){ in decimalSumStep()
4451 p->oom = 1; in decimalSumStep()
4453 p->a[0] = 0; in decimalSumStep()
4455 p->nDigit = 1; in decimalSumStep()
4456 p->nFrac = 0; in decimalSumStep()
4475 if( pArg ) pArg->sign = !pArg->sign; in decimalSumInverse()
4504 if( pA==0 || pA->oom || pA->isNull in decimalMulFunc()
4505 || pB==0 || pB->oom || pB->isNull in decimalMulFunc()
4510 if( pA->oom ){ in decimalMulFunc()
4523 ** Return the N-th power of 2. N must be an integer.
4587 ** 2013-05-28
4626 ** (8) If there are no non-NULL values for Y, then percentile(Y,P)
4629 ** (9) If there is exactly one non-NULL value for Y, the percentile(Y,P)
4632 ** (10) If there N non-NULL values of Y where N is two or more and
4634 ** drawn from 0 to N-1 such that the height of the graph at J is
4635 ** the J-th Y value and such that straight lines are drawn between
4637 ** the height of the graph at P*(N-1)/100.
4642 ** (12) The percentile(Y,P) is implemented as a single C99 source-code
4643 ** file that compiles into a shared-library or DLL that can be loaded
4670 ** -DSQLITE_ENABLE_ORDERED_SET_AGGREGATES option.
4682 ** Implementation notes as of 2024-08-31:
4684 ** * The regular aggregate-function versions of these routines work
4689 ** * For the window-function versions of these routines, the array of
4691 ** the array is kept in sorted order using an insert-sort. This
4702 /* no-op */
4709 #include <assert.h>
4744 ** Return TRUE if the input floating-point number is an infinity.
4748 assert( sizeof(u)==sizeof(r) ); in percentIsInfinity()
4757 a -= b; in percentSameValue()
4758 return a>=-0.001 && a<=0.001; in percentSameValue()
4762 ** Search p (which must have p->bSorted) looking for an entry with
4765 ** If bExact is true, return -1 if the entry is not found.
4770 ** the largest return value will be p->nUsed.
4774 int iLast = p->nUsed - 1; /* Last element of search range */ in percentBinarySearch()
4777 double x = p->a[iMid]; in percentBinarySearch()
4781 iLast = iMid - 1; in percentBinarySearch()
4786 if( bExact ) return -1; in percentBinarySearch()
4806 zMsg2 = zMsg1 ? sqlite3_mprintf(zMsg1, pFunc->zName) : 0; in percentError()
4807 sqlite3_result_error(pCtx, zMsg2, -1); in percentError()
4821 assert( argc==2 || argc==1 ); in percentStep()
4830 rPct = sqlite3_value_double(argv[1])/(double)pFunc->mxFrac; in percentStep()
4836 (double)pFunc->mxFrac); in percentStep()
4847 if( !p->bPctValid ){ in percentStep()
4848 p->rPct = rPct; in percentStep()
4849 p->bPctValid = 1; in percentStep()
4850 }else if( !percentSameValue(p->rPct,rPct) ){ in percentStep()
4875 if( p->nUsed>=p->nAlloc ){ in percentStep()
4876 unsigned n = p->nAlloc*2 + 250; in percentStep()
4877 double *a = sqlite3_realloc64(p->a, sizeof(double)*n); in percentStep()
4879 sqlite3_free(p->a); in percentStep()
4884 p->nAlloc = n; in percentStep()
4885 p->a = a; in percentStep()
4887 if( p->nUsed==0 ){ in percentStep()
4888 p->a[p->nUsed++] = y; in percentStep()
4889 p->bSorted = 1; in percentStep()
4890 }else if( !p->bSorted || y>=p->a[p->nUsed-1] ){ in percentStep()
4891 p->a[p->nUsed++] = y; in percentStep()
4892 }else if( p->bKeepSorted ){ in percentStep()
4895 if( i<(int)p->nUsed ){ in percentStep()
4896 memmove(&p->a[i+1], &p->a[i], (p->nUsed-i)*sizeof(p->a[0])); in percentStep()
4898 p->a[i] = y; in percentStep()
4899 p->nUsed++; in percentStep()
4901 p->a[p->nUsed++] = y; in percentStep()
4902 p->bSorted = 0; in percentStep()
4929 assert( n>=2 ); in percentSort()
4930 if( a[0]>a[n-1] ){ in percentSort()
4931 SWAP_DOUBLE(a[0],a[n-1]) in percentSort()
4934 iGt = n-1; in percentSort()
4951 iGt--; in percentSort()
4959 if( n-iGt>=2 ) percentSort(a+iGt, n-iGt); in percentSort()
4963 for(i=0; i<n-1; i++){ in percentSort()
4964 assert( a[i]<=a[i+1] ); in percentSort()
4979 assert( argc==2 || argc==1 ); in percentInverse()
4983 assert( p!=0 ); in percentInverse()
5000 if( p->bSorted==0 ){ in percentInverse()
5001 assert( p->nUsed>1 ); in percentInverse()
5002 percentSort(p->a, p->nUsed); in percentInverse()
5003 p->bSorted = 1; in percentInverse()
5005 p->bKeepSorted = 1; in percentInverse()
5010 p->nUsed--; in percentInverse()
5011 if( i<(int)p->nUsed ){ in percentInverse()
5012 memmove(&p->a[i], &p->a[i+1], (p->nUsed - i)*sizeof(p->a[0])); in percentInverse()
5029 if( p->a==0 ) return; in percentCompute()
5030 if( p->nUsed ){ in percentCompute()
5031 if( p->bSorted==0 ){ in percentCompute()
5032 assert( p->nUsed>1 ); in percentCompute()
5033 percentSort(p->a, p->nUsed); in percentCompute()
5034 p->bSorted = 1; in percentCompute()
5036 ix = p->rPct*(p->nUsed-1); in percentCompute()
5038 if( pFunc->bDiscrete ){ in percentCompute()
5039 vx = p->a[i1]; in percentCompute()
5041 i2 = ix==(double)i1 || i1==p->nUsed-1 ? i1 : i1+1; in percentCompute()
5042 v1 = p->a[i1]; in percentCompute()
5043 v2 = p->a[i2]; in percentCompute()
5044 vx = v1 + (v2-v1)*(ix-i1); in percentCompute()
5049 sqlite3_free(p->a); in percentCompute()
5052 p->bKeepSorted = 1; in percentCompute()
5095 ** 2022-11-18
5109 ** written as TCL brace-enclosed literals or SQL string literals,
5110 ** and can be used unmodified in XML-like documents.
5117 ** C source specifies that line-feeds are included in the encoded
5119 ** terminate any encoded blob having non-zero length.
5124 ** Generated base64 sequences, with their line-feeds included,
5133 ** This code relies on UTF-8 encoding only with respect to the
5134 ** meaning of the first 128 (7-bit) codes matching that of USASCII.
5136 ** Because it is table-driven, it could be enhanced to handle that,
5141 ** *Nix: gcc -O2 -shared -I$SQDIR -fPIC -o base64.so base64.c
5142 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o base64.dylib base64.c
5143 ** Win32: gcc -O2 -shared -I%SQDIR% -o base64.dll base64.c
5144 ** Win32: cl /Os -I%SQDIR% base64.c -link -dll -out:base64.dll
5147 #include <assert.h>
5164 #define ND 0x82 /* Not above or digit-value */
5172 /* Decoding table, ASCII (7-bit) value to base 64 digit value or other */
5207 static char* toBase64( u8 *pIn, int nbIn, char *pOut ){ in toBase64() argument
5210 /* Do the bit-shuffle, exploiting unsigned input to avoid masking. */ in toBase64()
5211 pOut[0] = BX_NUMERAL(pIn[0]>>2); in toBase64()
5212 pOut[1] = BX_NUMERAL(((pIn[0]<<4)|(pIn[1]>>4))&0x3f); in toBase64()
5213 pOut[2] = BX_NUMERAL(((pIn[1]&0xf)<<2)|(pIn[2]>>6)); in toBase64()
5214 pOut[3] = BX_NUMERAL(pIn[2]&0x3f); in toBase64()
5216 nbIn -= 3; in toBase64()
5217 pIn += 3; in toBase64()
5226 unsigned long qv = *pIn++; in toBase64()
5229 if( nbe<nbIn ) qv |= *pIn++; in toBase64()
5231 for( nbe=3; nbe>=0; --nbe ){ in toBase64()
5246 while( nc-- > 0 && (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s; in skipNonB64()
5251 static u8* fromBase64( char *pIn, int ncIn, u8 *pOut ){ in fromBase64() argument
5252 if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn; in fromBase64()
5253 while( ncIn>0 && *pIn!=PAD_CHAR ){ in fromBase64()
5255 char *pUse = skipNonB64(pIn, ncIn); in fromBase64()
5258 ncIn -= (pUse - pIn); in fromBase64()
5259 pIn = pUse; in fromBase64()
5261 ncIn -= nti; in fromBase64()
5265 char c = (nac<nti)? *pIn++ : b64Numerals[0]; in fromBase64()
5269 /* Treat dark non-digits as pad, but they terminate decode too. */ in fromBase64()
5278 --nbo; in fromBase64()
5305 SQLITE_LIMIT_LENGTH, -1); in base64()
5308 assert(na==1); in base64()
5313 nc += (nc+(B64_DARK_MAX-1))/B64_DARK_MAX + 1; /* LFs and a 0-terminator */ in base64()
5315 sqlite3_result_error(context, "blob expanded to base64 too big", -1); in base64()
5323 sqlite3_result_text(context,"",-1,SQLITE_STATIC); in base64()
5328 nc = (int)(toBase64(bBuf, nb, cBuf) - cBuf); in base64()
5335 sqlite3_result_error(context, "blob from base64 may be too big", -1); in base64()
5350 nb = (int)(fromBase64(cBuf, nc, bBuf) - bBuf); in base64()
5354 sqlite3_result_error(context, "base64 accepts only blob or text", -1); in base64()
5359 sqlite3_result_error(context, "base64 OOM", -1); in base64()
5396 ** 2022-11-16
5407 ** This is a utility for converting binary to base85 or vice-versa.
5412 ** written as TCL brace-enclosed literals or SQL string literals.
5413 ** It is not suited for unmodified use in XML-like documents.
5421 ** Base85 numerals are taken from the set of 7-bit USASCII codes,
5425 ** Groups of 4 bytes, interpreted as big-endian 32-bit values,
5426 ** are represented as 5-digit base85 numbers with MS to LS digit
5427 ** order. Groups of 1-3 bytes are represented with 2-4 digits,
5428 ** still big-endian but 8-24 bit values. (Using big-endian yields
5430 ** These byte groups can also be considered base-256 numbers.)
5431 ** Groups of 0 bytes are represented with 0 digits and vice-versa.
5433 ** (aka "group") length maps 1-to-1 to the decoded binary length.
5437 ** size, newline is used to separate it into sub-sequences of no
5444 ** a non-base85 character; the conversion to binary will then
5460 ** and variable OPTS to -DOMIT_BASE85_CHECKER if is_base85() unwanted.
5461 ** *Nix: gcc -O2 -shared -I$SQDIR $OPTS -fPIC -o base85.so base85.c
5462 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR $OPTS -o base85.dylib base85.c
5463 ** Win32: gcc -O2 -shared -I%SQDIR% %OPTS% -o base85.dll base85.c
5464 ** Win32: cl /Os -I%SQDIR% %OPTS% base85.c -link -dll -out:base85.dll
5467 ** *Nix or OSX: gcc -O2 -DBASE85_STANDALONE base85.c -o base85
5468 ** Win32: gcc -O2 -DBASE85_STANDALONE -o base85.exe base85.c
5469 ** Win32: cl /Os /MD -DBASE85_STANDALONE base85.c
5475 #include <assert.h>
5497 " <dirFlag> is either -r to read or -w to write <binFile>,\n"
5500 " Or, the name '-' refers to the stdin or stdout stream.\n"
5519 static u8 b85_cOffset[] = { 0, '#', 0, '*'-4, 0 };
5527 u8 dv = (u8)(c - '#');
5529 return (dv > 3)? dv-3 : dv;
5539 while( nc-- > 0 && (c = *s) && !IS_B85(c) ) ++s; in skipNonB85()
5544 * Do not use the macro form with argument expression having a side-effect.*/
5547 return (b < 4)? (char)(b + '#') : (char)(b - 4 + '*');
5551 ((char)(((dn) < 4)? (char)((dn) + '#') : (char)((dn) - 4 + '*')))
5564 static char* toBase85( u8 *pIn, int nbIn, char *pOut, char *pSep ){ in toBase85() argument
5568 unsigned long qbv = (((unsigned long)pIn[0])<<24) | in toBase85()
5569 (pIn[1]<<16) | (pIn[2]<<8) | pIn[3]; in toBase85()
5572 unsigned char dv = qbv - 85UL*nqv; in toBase85()
5574 pOut[--nco] = base85Numeral(dv); in toBase85()
5576 nbIn -= 4; in toBase85()
5577 pIn += 4; in toBase85()
5586 unsigned long qv = *pIn++; in toBase85()
5589 qv = (qv<<8) | *pIn++; in toBase85()
5595 pOut[--nco] = base85Numeral(dv); in toBase85()
5605 static u8* fromBase85( char *pIn, int ncIn, u8 *pOut ){ in fromBase85() argument
5606 if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn; in fromBase85()
5609 char *pUse = skipNonB85(pIn, ncIn); in fromBase85()
5612 ncIn -= (pUse - pIn); in fromBase85()
5613 pIn = pUse; in fromBase85()
5618 char c = *pIn++; in fromBase85()
5620 --ncIn; in fromBase85()
5622 qv = 85 * qv + (c - cdo); in fromBase85()
5623 --nti; in fromBase85()
5625 nbo -= nti; /* Adjust for early (non-digit) end of group. */ in fromBase85()
5650 while( len-- > 0 && (c = *p++) != 0 ){ in allBase85()
5662 assert(na==1); in is_base85()
5675 sqlite3_result_error(context, "is_base85 accepts only text or NULL", -1); in is_base85()
5685 SQLITE_LIMIT_LENGTH, -1); in base85()
5688 assert(na==1); in base85()
5695 sqlite3_result_error(context, "blob expanded to base85 too big", -1); in base85()
5703 sqlite3_result_text(context,"",-1,SQLITE_STATIC); in base85()
5708 nc = (int)(toBase85(bBuf, nb, cBuf, "\n") - cBuf); in base85()
5715 sqlite3_result_error(context, "blob from base85 may be too big", -1); in base85()
5730 nb = (int)(fromBase85(cBuf, nc, bBuf) - bBuf); in base85()
5734 sqlite3_result_error(context, "base85 accepts only blob or text.", -1); in base85()
5739 sqlite3_result_error(context, "base85 OOM", -1); in base85()
5793 if( na < 3 || av[1][0]!='-' || (rw = av[1][1])==0 || (rw!='r' && rw!='w') ){ in main()
5798 if( av[2][0]=='-' && av[2][1]==0 ){ in main()
5827 size_t nbo = fromBase85( cBuf, nc, bBuf ) - bBuf; in main()
5842 fprintf(stderr, "Base85 input had non-base85 dark or control content.\n"); in main()
5853 ** 2013-04-17
5865 ** and input of IEEE754 Binary64 floating-point numbers.
5870 ** In the first form, the value X should be a floating-point number.
5875 ** base-2 exponent of a new floating point number. The function returns
5876 ** a floating-point value equal to Y*pow(2,Z).
5880 ** ieee754(2.0) -> 'ieee754(2,0)'
5881 ** ieee754(45.25) -> 'ieee754(181,-2)'
5882 ** ieee754(2, 0) -> 2.0
5883 ** ieee754(181, -2) -> 45.25
5885 ** Two additional functions break apart the one-argument ieee754()
5888 ** ieee754_mantissa(45.25) -> 181
5889 ** ieee754_exponent(45.25) -> -2
5893 ** ieee754_from_blob(x'3ff0000000000000') -> 1.0
5894 ** ieee754_to_blob(1.0) -> x'3ff0000000000000'
5896 ** In all single-argument functions, if the argument is an 8-byte blob
5897 ** then that blob is interpreted as a big-endian binary64 value.
5901 ** -----------------------------------------------
5914 ** VALUES(-1,'0.5')
5916 ** SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
5923 ** ---------------^^^^^---- Replace with whatever you want
5941 #include <assert.h>
5964 assert( sizeof(m)==sizeof(r) ); in ieee754func()
5980 r = -r; in ieee754func()
5990 m = a & ((((sqlite3_int64)1)<<52)-1); in ieee754func()
6000 if( isNeg ) m = -m; in ieee754func()
6005 m, e-1075); in ieee754func()
6006 sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT); in ieee754func()
6012 sqlite3_result_int(context, e-1075); in ieee754func()
6022 /* Limit the range of e. Ticket 22dea1cfdb9151e4 2021-03-02 */ in ieee754func()
6025 }else if( e<-10000 ){ in ieee754func()
6026 e = -10000; in ieee754func()
6031 m = -m; in ieee754func()
6033 }else if( m==0 && e>-1000 && e<1000 ){ in ieee754func()
6043 e--; in ieee754func()
6048 if( 1-e >= 64 ){ in ieee754func()
6051 m >>= 1-e; in ieee754func()
6057 a = m & ((((sqlite3_int64)1)<<52)-1); in ieee754func()
6103 a[sizeof(r)-i] = v&0xff; in ieee754func_to_blob()
6116 ** Behind the scenes: this routine merely casts r into a 64-bit unsigned
6180 ** 2015-08-18, 2023-04-28
6191 ** This file demonstrates how to create a table-valued-function using
6194 ** within the limitation that its arguments are signed 64-bit integers.
6198 ** ( V[n] == start + n * step && sgn(V[n] - stop) * sgn(step) >= 0 )
6199 ** for each produced value (independent of production time ordering.)
6203 ** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
6221 ** SELECT * FROM generate_series(0,-100,-5);
6223 ** Integers 0 -5 -10 ... -100.
6225 ** SELECT * FROM generate_series(0,-1);
6269 ** series are well-defined.
6271 ** Update on 2024-08-22:
6293 #include <assert.h>
6300 ** Return that member of a generate_series(...) sequence whose 0-based
6313 ix -= mxI64; in genSeqMember()
6317 smBase += (mxI64 - mxI64/2) * smStep; in genSeqMember()
6324 ix -= ix2; in genSeqMember()
6351 pss->uSeqIndexMax = 0; in setupSequence()
6352 pss->isNotEOF = 0; in setupSequence()
6353 bSameSigns = (pss->iBase < 0)==(pss->iTerm < 0); in setupSequence()
6354 if( pss->iTerm < pss->iBase ){ in setupSequence()
6357 nuspan = (sqlite3_uint64)(pss->iBase - pss->iTerm); in setupSequence()
6362 nuspan += pss->iBase; in setupSequence()
6363 nuspan += -(pss->iTerm+1); in setupSequence()
6365 if( pss->iStep<0 ){ in setupSequence()
6366 pss->isNotEOF = 1; in setupSequence()
6368 pss->uSeqIndexMax = ( pss->iStep>LLONG_MIN )? nuspan/-pss->iStep : 1; in setupSequence()
6369 }else if( pss->iStep>LLONG_MIN ){ in setupSequence()
6370 pss->uSeqIndexMax = nuspan/-pss->iStep; in setupSequence()
6373 }else if( pss->iTerm > pss->iBase ){ in setupSequence()
6376 puspan = (sqlite3_uint64)(pss->iTerm - pss->iBase); in setupSequence()
6381 puspan += pss->iTerm; in setupSequence()
6382 puspan += -(pss->iBase+1); in setupSequence()
6384 if( pss->iStep>0 ){ in setupSequence()
6385 pss->isNotEOF = 1; in setupSequence()
6386 pss->uSeqIndexMax = puspan/pss->iStep; in setupSequence()
6388 }else if( pss->iTerm == pss->iBase ){ in setupSequence()
6389 pss->isNotEOF = 1; in setupSequence()
6390 pss->uSeqIndexMax = 0; in setupSequence()
6392 pss->uSeqIndexNow = (pss->isReversing)? pss->uSeqIndexMax : 0; in setupSequence()
6393 pss->iValueNow = (pss->isReversing) in setupSequence()
6394 ? genSeqMember(pss->iBase, pss->iStep, pss->uSeqIndexMax) in setupSequence()
6395 : pss->iBase; in setupSequence()
6404 if( !pss->isNotEOF ) return 0; in progressSequence()
6405 if( pss->isReversing ){ in progressSequence()
6406 if( pss->uSeqIndexNow > 0 ){ in progressSequence()
6407 pss->uSeqIndexNow--; in progressSequence()
6408 pss->iValueNow -= pss->iStep; in progressSequence()
6410 pss->isNotEOF = 0; in progressSequence()
6413 if( pss->uSeqIndexNow < pss->uSeqIndexMax ){ in progressSequence()
6414 pss->uSeqIndexNow++; in progressSequence()
6415 pss->iValueNow += pss->iStep; in progressSequence()
6417 pss->isNotEOF = 0; in progressSequence()
6420 return pss->isNotEOF; in progressSequence()
6429 sqlite3_vtab_cursor base; /* Base class - must be first */
6457 #define SERIES_COLUMN_ROWID (-1) in seriesConnect()
6495 *ppCursor = &pCur->base; in seriesOpen()
6513 progressSequence( & pCur->ss ); in seriesNext()
6529 case SERIES_COLUMN_START: x = pCur->ss.iOBase; break; in seriesColumn()
6530 case SERIES_COLUMN_STOP: x = pCur->ss.iOTerm; break; in seriesColumn()
6531 case SERIES_COLUMN_STEP: x = pCur->ss.iStep; break; in seriesColumn()
6532 default: x = pCur->ss.iValueNow; break; in seriesColumn()
6541 #define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
6549 *pRowid = pCur->ss.iValueNow; in seriesRowid()
6559 return !pCur->ss.isNotEOF; in seriesEof()
6562 /* True to cause run-time checking of the start=, stop=, and/or step=
6612 pCur->ss.iBase = sqlite3_value_int64(argv[i++]); in seriesFilter()
6614 pCur->ss.iBase = 0; in seriesFilter()
6617 pCur->ss.iTerm = sqlite3_value_int64(argv[i++]); in seriesFilter()
6619 pCur->ss.iTerm = 0xffffffff; in seriesFilter()
6622 pCur->ss.iStep = sqlite3_value_int64(argv[i++]); in seriesFilter()
6623 if( pCur->ss.iStep==0 ){ in seriesFilter()
6624 pCur->ss.iStep = 1; in seriesFilter()
6625 }else if( pCur->ss.iStep<0 ){ in seriesFilter()
6629 pCur->ss.iStep = 1; in seriesFilter()
6634 ** initialize the default range to be the entire range of 64-bit signed in seriesFilter()
6639 pCur->ss.iBase = SMALLEST_INT64; in seriesFilter()
6642 pCur->ss.iTerm = LARGEST_INT64; in seriesFilter()
6644 pCur->ss.iOBase = pCur->ss.iBase; in seriesFilter()
6645 pCur->ss.iOTerm = pCur->ss.iTerm; in seriesFilter()
6696 iMax = (sqlite3_int64)(r-1.0); in seriesFilter()
6706 iMax--; in seriesFilter()
6719 if( pCur->ss.iStep>0 ){ in seriesFilter()
6720 sqlite3_int64 szStep = pCur->ss.iStep; in seriesFilter()
6721 if( pCur->ss.iBase<iMin ){ in seriesFilter()
6722 sqlite3_uint64 d = iMin - pCur->ss.iBase; in seriesFilter()
6723 pCur->ss.iBase += ((d+szStep-1)/szStep)*szStep; in seriesFilter()
6725 if( pCur->ss.iTerm>iMax ){ in seriesFilter()
6726 pCur->ss.iTerm = iMax; in seriesFilter()
6729 sqlite3_int64 szStep = -pCur->ss.iStep; in seriesFilter()
6730 assert( szStep>0 ); in seriesFilter()
6731 if( pCur->ss.iBase>iMax ){ in seriesFilter()
6732 sqlite3_uint64 d = pCur->ss.iBase - iMax; in seriesFilter()
6733 pCur->ss.iBase -= ((d+szStep-1)/szStep)*szStep; in seriesFilter()
6735 if( pCur->ss.iTerm<iMin ){ in seriesFilter()
6736 pCur->ss.iTerm = iMin; in seriesFilter()
6744 pCur->ss.iBase += pCur->ss.iStep*iOffset; in seriesFilter()
6748 iTerm = pCur->ss.iBase + (iLimit - 1)*pCur->ss.iStep; in seriesFilter()
6749 if( pCur->ss.iStep<0 ){ in seriesFilter()
6750 if( iTerm>pCur->ss.iTerm ) pCur->ss.iTerm = iTerm; in seriesFilter()
6752 if( iTerm<pCur->ss.iTerm ) pCur->ss.iTerm = iTerm; in seriesFilter()
6767 pCur->ss.iBase = 1; in seriesFilter()
6768 pCur->ss.iTerm = 0; in seriesFilter()
6769 pCur->ss.iStep = 1; in seriesFilter()
6772 pCur->ss.isReversing = pCur->ss.iStep > 0; in seriesFilter()
6774 pCur->ss.isReversing = pCur->ss.iStep < 0; in seriesFilter()
6776 setupSequence( &pCur->ss ); in seriesFilter()
6839 assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 ); in seriesBestIndex()
6840 assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 ); in seriesBestIndex()
6842 aIdx[0] = aIdx[1] = aIdx[2] = aIdx[3] = aIdx[4] = aIdx[5] = aIdx[6] = -1; in seriesBestIndex()
6843 pConstraint = pIdxInfo->aConstraint; in seriesBestIndex()
6844 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ in seriesBestIndex()
6847 int op = pConstraint->op; in seriesBestIndex()
6851 if( pConstraint->usable==0 ){ in seriesBestIndex()
6857 assert( op==SQLITE_INDEX_CONSTRAINT_OFFSET ); in seriesBestIndex()
6863 if( pConstraint->iColumn<SERIES_COLUMN_START ){ in seriesBestIndex()
6864 if( (pConstraint->iColumn==SERIES_COLUMN_VALUE || in seriesBestIndex()
6865 pConstraint->iColumn==SERIES_COLUMN_ROWID) in seriesBestIndex()
6866 && pConstraint->usable in seriesBestIndex()
6874 aIdx[6] = -1; in seriesBestIndex()
6918 iCol = pConstraint->iColumn - SERIES_COLUMN_START; in seriesBestIndex()
6919 assert( iCol>=0 && iCol<=2 ); in seriesBestIndex()
6926 if( pConstraint->usable==0 ){ in seriesBestIndex()
6941 pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg; in seriesBestIndex()
6942 pIdxInfo->aConstraintUsage[j].omit = in seriesBestIndex()
6948 ** first argument was omitted. Compile with -DZERO_ARGUMENT_GENERATE_SERIES in seriesBestIndex()
6952 sqlite3_free(pVTab->zErrMsg); in seriesBestIndex()
6953 pVTab->zErrMsg = sqlite3_mprintf( in seriesBestIndex()
6967 pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0)); in seriesBestIndex()
6968 pIdxInfo->estimatedRows = 1000; in seriesBestIndex()
6969 if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){ in seriesBestIndex()
6970 if( pIdxInfo->aOrderBy[0].desc ){ in seriesBestIndex()
6975 pIdxInfo->orderByConsumed = 1; in seriesBestIndex()
6979 pIdxInfo->estimatedRows = 2500; in seriesBestIndex()
6984 pIdxInfo->estimatedRows = 2147483647; in seriesBestIndex()
6986 pIdxInfo->idxNum = idxNum; in seriesBestIndex()
6988 pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_HEX; in seriesBestIndex()
7004 seriesOpen, /* xOpen - open a cursor */
7005 seriesClose, /* xClose - close a cursor */
7006 seriesFilter, /* xFilter - configure scan constraints */
7007 seriesNext, /* xNext - advance a cursor */
7008 seriesEof, /* xEof - check for end of scan */
7009 seriesColumn, /* xColumn - read data */
7010 seriesRowid, /* xRowid - read data */
7051 ** 2012-11-13
7063 ** efficient regular-expression matcher for posix extended regular
7085 ** \c C-language escapes for c in afnrtv. ex: \t or \n
7090 ** [a-z] Any single character in the range a-z
7091 ** [^a-z] Any single character not in the range a-z
7093 ** \w Word character. [A-Za-z0-9_]
7094 ** \W Non-word character
7096 ** \D Non-digit
7098 ** \S Non-whitespace character
7104 ** to p copies of X following by q-p copies of X? and that the size of the
7115 ** this file to prevent name collisions with C-library functions of the
7122 /* The end-of-input character */
7124 #define RE_START 0xfffffff /* Start of input - larger than an UTF-8 */
7139 #define RE_OP_WORD 11 /* Perl word character [A-Za-z0-9_] */
7141 #define RE_OP_DIGIT 13 /* digit: [0-9] */
7145 #define RE_OP_BOUNDARY 17 /* Boundary between word and non-word */
7187 /* An input string read one character at a time.
7215 for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return; in re_add_state()
7216 pSet->aState[pSet->nState++] = (ReStateNumber)newState; in re_add_state()
7226 if( p->i>=p->mx ) return 0; in re_next_char()
7227 c = p->z[p->i++]; in re_next_char()
7229 if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){ in re_next_char()
7230 c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f); in re_next_char()
7232 }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80 in re_next_char()
7233 && (p->z[p->i+1]&0xc0)==0x80 ){ in re_next_char()
7234 c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f); in re_next_char()
7235 p->i += 2; in re_next_char()
7237 }else if( (c&0xf8)==0xf0 && p->i+2<p->mx && (p->z[p->i]&0xc0)==0x80 in re_next_char()
7238 && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){ in re_next_char()
7239 c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6) in re_next_char()
7240 | (p->z[p->i+2]&0x3f); in re_next_char()
7241 p->i += 3; in re_next_char()
7251 if( c>='A' && c<='Z' ) c += 'a' - 'A'; in re_next_char_nocase()
7255 /* Return true if c is a perl "word" character: [A-Za-z0-9_] */
7261 /* Return true if c is a "digit" character: [0-9] */
7271 /* Run a compiled regular expression on the zero-terminated input
7290 if( pRe->nInit ){ in re_match()
7291 unsigned char x = pRe->zInit[0]; in re_match()
7292 while( in.i+pRe->nInit<=in.mx in re_match()
7294 strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0) in re_match()
7298 if( in.i+pRe->nInit>in.mx ) return 0; in re_match()
7299 c = RE_START-1; in re_match()
7302 if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){ in re_match()
7306 pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState ); in re_match()
7307 if( pToFree==0 ) return -1; in re_match()
7310 aStateSet[1].aState = &aStateSet[0].aState[pRe->nState]; in re_match()
7312 pNext->nState = 0; in re_match()
7314 while( c!=RE_EOF && pNext->nState>0 ){ in re_match()
7316 c = pRe->xNextChar(&in); in re_match()
7319 iSwap = 1 - iSwap; in re_match()
7320 pNext->nState = 0; in re_match()
7321 for(i=0; i<pThis->nState; i++){ in re_match()
7322 int x = pThis->aState[i]; in re_match()
7323 switch( pRe->aOp[x] ){ in re_match()
7325 if( pRe->aArg[x]==c ) re_add_state(pNext, x+1); in re_match()
7370 re_add_state(pThis, x+pRe->aArg[x]); in re_match()
7375 re_add_state(pThis, x+pRe->aArg[x]); in re_match()
7384 /* fall-through */ goto re_op_cc_inc; in re_match()
7388 int n = pRe->aArg[x]; in re_match()
7391 if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){ in re_match()
7392 if( pRe->aArg[x+j]==c ){ in re_match()
7394 j = -1; in re_match()
7397 if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){ in re_match()
7399 j = -1; in re_match()
7405 if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit; in re_match()
7412 for(i=0; i<pNext->nState; i++){ in re_match()
7413 int x = pNext->aState[i]; in re_match()
7414 while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x]; in re_match()
7415 if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; } in re_match()
7427 aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0])); in re_resize()
7429 p->aOp = aOp; in re_resize()
7430 aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0])); in re_resize()
7432 p->aArg = aArg; in re_resize()
7433 p->nAlloc = N; in re_resize()
7442 if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0; in re_insert()
7443 for(i=p->nState; i>iBefore; i--){ in re_insert()
7444 p->aOp[i] = p->aOp[i-1]; in re_insert()
7445 p->aArg[i] = p->aArg[i-1]; in re_insert()
7447 p->nState++; in re_insert()
7448 p->aOp[iBefore] = (char)op; in re_insert()
7449 p->aArg[iBefore] = arg; in re_insert()
7456 return re_insert(p, p->nState, op, arg); in re_append()
7463 if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return; in re_copy()
7464 memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0])); in re_copy()
7465 memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0])); in re_copy()
7466 p->nState += N; in re_copy()
7469 /* Return true if c is a hexadecimal digit character: [0-9a-fA-F]
7475 c -= '0'; in re_hex()
7477 c -= 'a' - 10; in re_hex()
7479 c -= 'A' - 10; in re_hex()
7495 if( p->sIn.i>=p->sIn.mx ) return 0; in re_esc_char()
7496 c = p->sIn.z[p->sIn.i]; in re_esc_char()
7497 if( c=='u' && p->sIn.i+4<p->sIn.mx ){ in re_esc_char()
7498 const unsigned char *zIn = p->sIn.z + p->sIn.i; in re_esc_char()
7504 p->sIn.i += 5; in re_esc_char()
7508 if( c=='x' && p->sIn.i+2<p->sIn.mx ){ in re_esc_char()
7509 const unsigned char *zIn = p->sIn.z + p->sIn.i; in re_esc_char()
7513 p->sIn.i += 3; in re_esc_char()
7520 p->sIn.i++; in re_esc_char()
7522 p->zErr = "unknown \\ escape"; in re_esc_char()
7532 return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0; in rePeek()
7542 iStart = p->nState; in re_subcompile_re()
7546 iEnd = p->nState; in re_subcompile_re()
7547 re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart); in re_subcompile_re()
7549 p->sIn.i++; in re_subcompile_re()
7552 p->aArg[iGoto] = p->nState - iGoto; in re_subcompile_re()
7562 int iPrev = -1; in re_subcompile_string()
7566 while( (c = p->xNextChar(&p->sIn))!=0 ){ in re_subcompile_string()
7567 iStart = p->nState; in re_subcompile_string()
7571 p->sIn.i--; in re_subcompile_string()
7578 p->sIn.i++; in re_subcompile_string()
7584 p->sIn.i++; in re_subcompile_string()
7592 re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1); in re_subcompile_string()
7593 re_append(p, RE_OP_FORK, iPrev - p->nState + 1); in re_subcompile_string()
7598 re_append(p, RE_OP_FORK, iPrev - p->nState); in re_subcompile_string()
7603 re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1); in re_subcompile_string()
7618 while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; } in re_subcompile_string()
7621 p->sIn.i++; in re_subcompile_string()
7623 while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; } in re_subcompile_string()
7627 p->sIn.i++; in re_subcompile_string()
7628 sz = p->nState - iPrev; in re_subcompile_string()
7633 n--; in re_subcompile_string()
7642 re_append(p, RE_OP_FORK, -sz); in re_subcompile_string()
7647 unsigned int iFirst = p->nState; in re_subcompile_string()
7650 p->sIn.i++; in re_subcompile_string()
7654 while( (c = p->xNextChar(&p->sIn))!=0 ){ in re_subcompile_string()
7659 if( rePeek(p)=='-' ){ in re_subcompile_string()
7661 p->sIn.i++; in re_subcompile_string()
7662 c = p->xNextChar(&p->sIn); in re_subcompile_string()
7668 if( rePeek(p)==']' ){ p->sIn.i++; break; } in re_subcompile_string()
7671 if( p->nState>iFirst ) p->aArg[iFirst] = p->nState - iFirst; in re_subcompile_string()
7686 p->sIn.i++; in re_subcompile_string()
7711 sqlite3_free(pRe->aOp); in re_free()
7712 sqlite3_free(pRe->aArg); in re_free()
7734 pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char; in re_compile()
7744 pRe->sIn.z = (unsigned char*)zIn; in re_compile()
7745 pRe->sIn.i = 0; in re_compile()
7746 pRe->sIn.mx = (int)strlen(zIn); in re_compile()
7752 if( pRe->sIn.i>=pRe->sIn.mx ){ in re_compile()
7766 ** unicode characters beyond plane 0 - those are very rare and this is in re_compile()
7768 if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){ in re_compile()
7769 for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){ in re_compile()
7770 unsigned x = pRe->aArg[i]; in re_compile()
7772 pRe->zInit[j++] = (unsigned char)x; in re_compile()
7774 pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6)); in re_compile()
7775 pRe->zInit[j++] = 0x80 | (x&0x3f); in re_compile()
7777 pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12)); in re_compile()
7778 pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f); in re_compile()
7779 pRe->zInit[j++] = 0x80 | (x&0x3f); in re_compile()
7784 if( j>0 && pRe->zInit[j-1]==0 ) j--; in re_compile()
7785 pRe->nInit = j; in re_compile()
7787 return pRe->zErr; in re_compile()
7792 ** the build-in REGEXP operator. The first argument to the function is the
7818 sqlite3_result_error(context, zErr, -1); in re_sql_func()
7829 sqlite3_result_int(context, re_match(pRe, zStr, -1)); in re_sql_func()
7839 ** if the SQLITE_DEBUG compile-time option is used.
7863 sqlite3_result_error(context, zErr, -1); in re_bytecode_func()
7872 if( pRe->nInit>0 ){ in re_bytecode_func()
7874 for(i=0; i<pRe->nInit; i++){ in re_bytecode_func()
7875 sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]); in re_bytecode_func()
7879 for(i=0; (unsigned)i<pRe->nState; i++){ in re_bytecode_func()
7880 sqlite3_str_appendf(pStr, "%-8s %4d\n", in re_bytecode_func()
7881 ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]); in re_bytecode_func()
7888 sqlite3_result_text(context, z, n-1, sqlite3_free); in re_bytecode_func()
7917 /* The regexpi(PATTERN,STRING) function is a case-insensitive version in sqlite3_regexp_init()
7937 ** 2014-06-13
7957 ** If the first option argument - MODE - is present, then it must
7974 ** as an integer - the number of seconds since the unix epoch. The
7975 ** modification-time of the target file is set to this value before
8006 ** If a non-NULL value is specified for the optional $dir parameter and
8013 ** symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone
8020 #include <assert.h>
8029 # include <sys/time.h>
8041 #include <time.h>
8053 ** Structure of the fsdir() table-valued function
8059 #define FSDIR_COLUMN_MTIME 2 /* Last modification time */
8072 if( b1==0 ) return -1; in fileio_chmod()
8089 if( b1==0 ) return -1; in fileio_mkdir()
8126 mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1); in readFileContents()
8173 sqlite3_result_error(ctx, zMsg, -1); in ctxErrorMsg()
8181 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
8199 fileIntervals.LowPart = pFileTime->dwLowDateTime; in fileTimeToUnixTime()
8200 fileIntervals.HighPart = pFileTime->dwHighDateTime; in fileTimeToUnixTime()
8202 return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000; in fileTimeToUnixTime()
8212 int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0); in utf8_to_utf16()
8214 if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) ) in utf8_to_utf16()
8222 ** This function attempts to normalize the time values found in the stat()
8239 pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime); in statTimesToUtc()
8240 pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime); in statTimesToUtc()
8241 pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime); in statTimesToUtc()
8251 ** is required in order for the included time to be returned as UTC. On all
8275 ** is required in order for the included time to be returned as UTC. On all
8345 sqlite3_int64 mtime /* MTIME parameter (or -1 to not set time) */ in writeFile()
8360 ** be an error though - if there is already a directory at the same in writeFile()
8433 times[0].tv_sec = time(0); in writeFile()
8441 ** Do not use utimes() on a symbolic link - it sees through the link and in writeFile()
8447 times[0].tv_sec = time(0); in writeFile()
8471 sqlite3_int64 mtime = -1; in writefileFunc()
8475 "wrong number of arguments to function writefile()", -1 in writefileFunc()
8510 ** Given a numberic st_mode from stat(), convert it into a human-readable
8511 ** text string in the style of "ls -l".
8525 z[0] = '-'; in lsModeFunc()
8532 int m = (iMode >> ((2-i)*3)); in lsModeFunc()
8534 a[0] = (m & 0x4) ? 'r' : '-'; in lsModeFunc()
8535 a[1] = (m & 0x2) ? 'w' : '-'; in lsModeFunc()
8536 a[2] = (m & 0x1) ? 'x' : '-'; in lsModeFunc()
8539 sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT); in lsModeFunc()
8552 char *zDir; /* Name of directory (nul-terminated) */
8556 sqlite3_vtab_cursor base; /* Base class - must be first */
8572 sqlite3_vtab base; /* Base class - must be first */
8619 pCur->iLvl = -1; in fsdirOpen()
8620 *ppCursor = &pCur->base; in fsdirOpen()
8625 ** Reset a cursor back to the state it was in when first returned
8630 for(i=0; i<=pCur->iLvl; i++){ in fsdirResetCursor()
8631 FsdirLevel *pLvl = &pCur->aLvl[i]; in fsdirResetCursor()
8632 if( pLvl->pDir ) closedir(pLvl->pDir); in fsdirResetCursor()
8633 sqlite3_free(pLvl->zDir); in fsdirResetCursor()
8635 sqlite3_free(pCur->zPath); in fsdirResetCursor()
8636 sqlite3_free(pCur->aLvl); in fsdirResetCursor()
8637 pCur->aLvl = 0; in fsdirResetCursor()
8638 pCur->zPath = 0; in fsdirResetCursor()
8639 pCur->zBase = 0; in fsdirResetCursor()
8640 pCur->nBase = 0; in fsdirResetCursor()
8641 pCur->nLvl = 0; in fsdirResetCursor()
8642 pCur->iLvl = -1; in fsdirResetCursor()
8643 pCur->iRowid = 1; in fsdirResetCursor()
8664 pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); in fsdirSetErrmsg()
8674 mode_t m = pCur->sStat.st_mode; in fsdirNext()
8676 pCur->iRowid++; in fsdirNext()
8679 int iNew = pCur->iLvl + 1; in fsdirNext()
8681 if( iNew>=pCur->nLvl ){ in fsdirNext()
8684 FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte); in fsdirNext()
8686 memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl)); in fsdirNext()
8687 pCur->aLvl = aNew; in fsdirNext()
8688 pCur->nLvl = nNew; in fsdirNext()
8690 pCur->iLvl = iNew; in fsdirNext()
8691 pLvl = &pCur->aLvl[iNew]; in fsdirNext()
8693 pLvl->zDir = pCur->zPath; in fsdirNext()
8694 pCur->zPath = 0; in fsdirNext()
8695 pLvl->pDir = opendir(pLvl->zDir); in fsdirNext()
8696 if( pLvl->pDir==0 ){ in fsdirNext()
8697 fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath); in fsdirNext()
8702 while( pCur->iLvl>=0 ){ in fsdirNext()
8703 FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl]; in fsdirNext()
8704 struct dirent *pEntry = readdir(pLvl->pDir); in fsdirNext()
8706 if( pEntry->d_name[0]=='.' ){ in fsdirNext()
8707 if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue; in fsdirNext()
8708 if( pEntry->d_name[1]=='\0' ) continue; in fsdirNext()
8710 sqlite3_free(pCur->zPath); in fsdirNext()
8711 pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name); in fsdirNext()
8712 if( pCur->zPath==0 ) return SQLITE_NOMEM; in fsdirNext()
8713 if( fileLinkStat(pCur->zPath, &pCur->sStat) ){ in fsdirNext()
8714 fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath); in fsdirNext()
8719 closedir(pLvl->pDir); in fsdirNext()
8720 sqlite3_free(pLvl->zDir); in fsdirNext()
8721 pLvl->pDir = 0; in fsdirNext()
8722 pLvl->zDir = 0; in fsdirNext()
8723 pCur->iLvl--; in fsdirNext()
8727 sqlite3_free(pCur->zPath); in fsdirNext()
8728 pCur->zPath = 0; in fsdirNext()
8744 sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT); in fsdirColumn()
8749 sqlite3_result_int64(ctx, pCur->sStat.st_mode); in fsdirColumn()
8753 sqlite3_result_int64(ctx, pCur->sStat.st_mtime); in fsdirColumn()
8757 mode_t m = pCur->sStat.st_mode; in fsdirColumn()
8768 n = readlink(pCur->zPath, aBuf, nBuf); in fsdirColumn()
8783 readFileContents(ctx, pCur->zPath); in fsdirColumn()
8803 *pRowid = pCur->iRowid; in fsdirRowid()
8813 return (pCur->zPath==0); in fsdirEof()
8837 assert( argc==idxNum && (argc==1 || argc==2) ); in fsdirFilter()
8840 fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument"); in fsdirFilter()
8844 pCur->zBase = (const char*)sqlite3_value_text(argv[1]); in fsdirFilter()
8846 if( pCur->zBase ){ in fsdirFilter()
8847 pCur->nBase = (int)strlen(pCur->zBase)+1; in fsdirFilter()
8848 pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir); in fsdirFilter()
8850 pCur->zPath = sqlite3_mprintf("%s", zDir); in fsdirFilter()
8853 if( pCur->zPath==0 ){ in fsdirFilter()
8856 if( fileLinkStat(pCur->zPath, &pCur->sStat) ){ in fsdirFilter()
8857 fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath); in fsdirFilter()
8883 int idxPath = -1; /* Index in pIdxInfo->aConstraint of PATH= */ in fsdirBestIndex()
8884 int idxDir = -1; /* Index in pIdxInfo->aConstraint of DIR= */ in fsdirBestIndex()
8890 pConstraint = pIdxInfo->aConstraint; in fsdirBestIndex()
8891 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ in fsdirBestIndex()
8892 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; in fsdirBestIndex()
8893 switch( pConstraint->iColumn ){ in fsdirBestIndex()
8895 if( pConstraint->usable ){ in fsdirBestIndex()
8904 if( pConstraint->usable ){ in fsdirBestIndex()
8920 pIdxInfo->idxNum = 0; in fsdirBestIndex()
8921 /* The pIdxInfo->estimatedCost should have been initialized to a huge in fsdirBestIndex()
8923 pIdxInfo->estimatedRows = 0x7fffffff; in fsdirBestIndex()
8925 pIdxInfo->aConstraintUsage[idxPath].omit = 1; in fsdirBestIndex()
8926 pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1; in fsdirBestIndex()
8928 pIdxInfo->aConstraintUsage[idxDir].omit = 1; in fsdirBestIndex()
8929 pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2; in fsdirBestIndex()
8930 pIdxInfo->idxNum = 2; in fsdirBestIndex()
8931 pIdxInfo->estimatedCost = 10.0; in fsdirBestIndex()
8933 pIdxInfo->idxNum = 1; in fsdirBestIndex()
8934 pIdxInfo->estimatedCost = 100.0; in fsdirBestIndex()
8952 fsdirOpen, /* xOpen - open a cursor */ in fsdirRegister()
8953 fsdirClose, /* xClose - close a cursor */ in fsdirRegister()
8954 fsdirFilter, /* xFilter - configure scan constraints */ in fsdirRegister()
8955 fsdirNext, /* xNext - advance a cursor */ in fsdirRegister()
8956 fsdirEof, /* xEof - check for end of scan */ in fsdirRegister()
8957 fsdirColumn, /* xColumn - read data */ in fsdirRegister()
8958 fsdirRowid, /* xRowid - read data */ in fsdirRegister()
8995 rc = sqlite3_create_function(db, "writefile", -1, in sqlite3_fileio_init()
9020 ** 2017-07-10
9056 #include <assert.h>
9072 sqlite3_vtab base; /* Base class - must be first */
9082 sqlite3_vtab_cursor base; /* Base class - must be first */
9092 int j; /* inter-phase counter */
9142 #define COMPLETION_COLUMN_PHASE 3 /* ePhase - used for debugging only */ in completionConnect()
9157 pNew->db = db; in completionConnect()
9178 pCur->db = ((completion_vtab*)p)->db; in completionOpen()
9179 *ppCursor = &pCur->base; in completionOpen()
9184 ** Reset the completion_cursor.
9187 sqlite3_free(pCur->zPrefix); pCur->zPrefix = 0; pCur->nPrefix = 0; in completionCursorReset()
9188 sqlite3_free(pCur->zLine); pCur->zLine = 0; pCur->nLine = 0; in completionCursorReset()
9189 sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0; in completionCursorReset()
9190 pCur->j = 0; in completionCursorReset()
9205 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
9206 ** record the current state of the scan. This routine sets ->zCurrentRow
9208 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
9219 int iCol = -1; /* If >=0, step pCur->pStmt and use the i-th column */ in completionNext()
9220 pCur->iRowid++; in completionNext()
9221 while( pCur->ePhase!=COMPLETION_EOF ){ in completionNext()
9222 switch( pCur->ePhase ){ in completionNext()
9224 if( pCur->j >= sqlite3_keyword_count() ){ in completionNext()
9225 pCur->zCurrentRow = 0; in completionNext()
9226 pCur->ePhase = COMPLETION_DATABASES; in completionNext()
9228 sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow); in completionNext()
9230 iCol = -1; in completionNext()
9234 if( pCur->pStmt==0 ){ in completionNext()
9235 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, in completionNext()
9236 &pCur->pStmt, 0); in completionNext()
9243 if( pCur->pStmt==0 ){ in completionNext()
9247 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0); in completionNext()
9259 sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0); in completionNext()
9267 if( pCur->pStmt==0 ){ in completionNext()
9271 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0); in completionNext()
9285 sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0); in completionNext()
9295 if( pCur->zCurrentRow==0 ) continue; in completionNext()
9297 if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){ in completionNext()
9299 pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol); in completionNext()
9300 pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol); in completionNext()
9303 sqlite3_finalize(pCur->pStmt); in completionNext()
9304 pCur->pStmt = 0; in completionNext()
9305 pCur->ePhase = eNextPhase; in completionNext()
9309 if( pCur->nPrefix==0 ) break; in completionNext()
9310 if( pCur->nPrefix<=pCur->szRow in completionNext()
9311 && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0 in completionNext()
9332 sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT); in completionColumn()
9336 sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT); in completionColumn()
9340 sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT); in completionColumn()
9344 sqlite3_result_int(ctx, pCur->ePhase); in completionColumn()
9357 *pRowid = pCur->iRowid; in completionRowid()
9367 return pCur->ePhase >= COMPLETION_EOF; in completionEof()
9387 pCur->nPrefix = sqlite3_value_bytes(argv[iArg]); in completionFilter()
9388 if( pCur->nPrefix>0 ){ in completionFilter()
9389 pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg])); in completionFilter()
9390 if( pCur->zPrefix==0 ) return SQLITE_NOMEM; in completionFilter()
9395 pCur->nLine = sqlite3_value_bytes(argv[iArg]); in completionFilter()
9396 if( pCur->nLine>0 ){ in completionFilter()
9397 pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg])); in completionFilter()
9398 if( pCur->zLine==0 ) return SQLITE_NOMEM; in completionFilter()
9401 if( pCur->zLine!=0 && pCur->zPrefix==0 ){ in completionFilter()
9402 int i = pCur->nLine; in completionFilter()
9403 while( i>0 && (IsAlnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){ in completionFilter()
9404 i--; in completionFilter()
9406 pCur->nPrefix = pCur->nLine - i; in completionFilter()
9407 if( pCur->nPrefix>0 ){ in completionFilter()
9408 pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i); in completionFilter()
9409 if( pCur->zPrefix==0 ) return SQLITE_NOMEM; in completionFilter()
9412 pCur->iRowid = 0; in completionFilter()
9413 pCur->ePhase = COMPLETION_FIRST_PHASE; in completionFilter()
9423 ** There are two hidden parameters that act as arguments to the table-valued
9433 int prefixIdx = -1; /* Index of the start= constraint, or -1 if none */ in completionBestIndex()
9434 int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */ in completionBestIndex()
9439 pConstraint = pIdxInfo->aConstraint; in completionBestIndex()
9440 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ in completionBestIndex()
9441 if( pConstraint->usable==0 ) continue; in completionBestIndex()
9442 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; in completionBestIndex()
9443 switch( pConstraint->iColumn ){ in completionBestIndex()
9455 pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg; in completionBestIndex()
9456 pIdxInfo->aConstraintUsage[prefixIdx].omit = 1; in completionBestIndex()
9459 pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg; in completionBestIndex()
9460 pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1; in completionBestIndex()
9462 pIdxInfo->idxNum = idxNum; in completionBestIndex()
9463 pIdxInfo->estimatedCost = (double)5000 - 1000*nArg; in completionBestIndex()
9464 pIdxInfo->estimatedRows = 500 - 100*nArg; in completionBestIndex()
9479 completionOpen, /* xOpen - open a cursor */
9480 completionClose, /* xClose - close a cursor */
9481 completionFilter, /* xFilter - configure scan constraints */
9482 completionNext, /* xNext - advance a cursor */
9483 completionEof, /* xEof - check for end of scan */
9484 completionColumn, /* xColumn - read data */
9485 completionRowid, /* xRowid - read data */
9530 ** 2017-10-20
9558 ** "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
9575 ** this shim is a pass-through into the default underlying VFS. (rule 3)
9580 #include <assert.h>
9584 ** Start-Of-SQLite3-NNNNNNNN
9587 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
9590 #define APND_MARK_PREFIX "Start-Of-SQLite3-"
9596 ** Maximum size of the combined prefix + database + append-mark. This
9607 #define APND_ALIGN_MASK ((sqlite3_int64)(APND_ROUNDUP-1))
9616 /* Access to a lower-level VFS that (might) implement dynamic loading,
9619 #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
9628 ** append-mark.
9632 ** +-------------+---------+----------+-------------+
9633 ** | prefix-file | padding | database | append-mark |
9634 ** +-------------+---------+----------+-------------+
9640 ** "prefix file" - file onto which the database has been appended.
9641 ** "padding" - zero or more bytes inserted so that "database"
9643 ** "database" - The SQLite database file
9644 ** "append-mark" - The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
9645 ** the offset from the start of prefix-file to the start
9648 ** The size of the database is iMark - iPgOne.
9650 ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
9651 ** of iPgOne stored as a big-ending 64-bit integer.
9654 ** Or, iMark is -1 to indicate that it has not yet been written.
9659 sqlite3_int64 iMark; /* Offset of the append mark. -1 if unwritten */
9753 ** Close an apnd-file.
9757 return pFile->pMethods->xClose(pFile); in apndClose()
9761 ** Read data from an apnd-file.
9771 return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst); in apndRead()
9775 ** Add the append-mark onto what should become the end of the file.
9777 * Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
9784 sqlite_int64 iPgOne = paf->iPgOne; in apndWriteMark()
9788 assert(pFile == ORIGFILE(paf)); in apndWriteMark()
9790 while( --i >= 0 ){ in apndWriteMark()
9794 iWriteEnd += paf->iPgOne; in apndWriteMark()
9795 if( SQLITE_OK==(rc = pFile->pMethods->xWrite in apndWriteMark()
9797 paf->iMark = iWriteEnd; in apndWriteMark()
9803 ** Write data to an apnd-file.
9815 /* If append-mark is absent or will be overwritten, write it. */ in apndWrite()
9816 if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){ in apndWrite()
9820 return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst); in apndWrite()
9824 ** Truncate an apnd-file.
9832 return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE); in apndTruncate()
9836 ** Sync an apnd-file.
9840 return pFile->pMethods->xSync(pFile, flags); in apndSync()
9844 ** Return the current file-size of an apnd-file.
9845 ** If the append mark is not yet there, the file-size is 0.
9849 *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0; in apndFileSize()
9854 ** Lock an apnd-file.
9858 return pFile->pMethods->xLock(pFile, eLock); in apndLock()
9862 ** Unlock an apnd-file.
9866 return pFile->pMethods->xUnlock(pFile, eLock); in apndUnlock()
9870 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
9874 return pFile->pMethods->xCheckReservedLock(pFile, pResOut); in apndCheckReservedLock()
9878 ** File control method. For custom operations on an apnd-file.
9884 if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne; in apndFileControl()
9885 rc = pFile->pMethods->xFileControl(pFile, op, pArg); in apndFileControl()
9887 *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg); in apndFileControl()
9893 ** Return the sector-size in bytes for an apnd-file.
9897 return pFile->pMethods->xSectorSize(pFile); in apndSectorSize()
9901 ** Return the device characteristic flags supported by an apnd-file.
9905 return pFile->pMethods->xDeviceCharacteristics(pFile); in apndDeviceCharacteristics()
9917 return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp); in apndShmMap()
9920 /* Perform locking on a shared-memory segment */
9923 return pFile->pMethods->xShmLock(pFile,offset,n,flags); in apndShmLock()
9929 pFile->pMethods->xShmBarrier(pFile); in apndShmBarrier()
9935 return pFile->pMethods->xShmUnmap(pFile,deleteFlag); in apndShmUnmap()
9938 /* Fetch a page of a memory-mapped file */
9946 if( p->iMark < 0 || iOfst+iAmt > p->iMark ){ in apndFetch()
9950 return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp); in apndFetch()
9953 /* Release a memory-mapped page */
9957 return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage); in apndUnfetch()
9961 ** Try to read the append-mark off the end of a file. Return the
9962 ** start of the appended database if the append-mark is present.
9963 ** If there is no valid append-mark, return -1;
9965 ** An append-mark is only valid if the NNNNNNNN start-of-database offset
9967 ** start-of-database value must be a multiple of 512.
9972 int msbs = 8 * (APND_MARK_FOS_SZ-1); in apndReadMark()
9975 if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1; in apndReadMark()
9976 rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE); in apndReadMark()
9977 if( rc ) return -1; in apndReadMark()
9978 if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1; in apndReadMark()
9981 msbs -= 8; in apndReadMark()
9984 if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1; in apndReadMark()
9985 if( iMark & 0x1ff ) return -1; in apndReadMark()
9999 /* If file has the correct end-marker, the expected odd size, and the in apndIsAppendvfsDatabase()
10000 ** SQLite DB type marker where the end-marker puts it, then it in apndIsAppendvfsDatabase()
10003 rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark); in apndIsAppendvfsDatabase()
10023 || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0) in apndIsOrdinaryDatabaseFile()
10052 return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags); in apndOpen()
10055 pFile->pMethods = &apnd_io_methods; in apndOpen()
10056 pApndFile->iMark = -1; /* Append mark not yet written */ in apndOpen()
10058 rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags); in apndOpen()
10060 rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz); in apndOpen()
10062 pBaseFile->pMethods->xClose(pBaseFile); in apndOpen()
10066 pFile->pMethods = 0; in apndOpen()
10071 ** the base dispatch-table so this instance mimics the base VFS. in apndOpen()
10073 memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile); in apndOpen()
10076 pApndFile->iPgOne = apndReadMark(sz, pFile); in apndOpen()
10077 if( pApndFile->iPgOne>=0 ){ in apndOpen()
10078 pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */ in apndOpen()
10082 pBaseFile->pMethods->xClose(pBaseFile); in apndOpen()
10084 pFile->pMethods = 0; in apndOpen()
10089 ** Until then, paf->iMark value indicates it is not yet written. in apndOpen()
10091 pApndFile->iPgOne = APND_START_ROUNDUP(sz); in apndOpen()
10103 return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync); in apndDelete()
10107 ** All other VFS methods are pass-thrus.
10115 return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut); in apndAccess()
10123 return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut); in apndFullPathname()
10126 return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath); in apndDlOpen()
10129 ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg); in apndDlError()
10132 return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym); in apndDlSym()
10135 ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle); in apndDlClose()
10138 return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut); in apndRandomness()
10141 return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro); in apndSleep()
10144 return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut); in apndCurrentTime()
10147 return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b); in apndGetLastError()
10150 return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p); in apndCurrentTimeInt64()
10157 return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall); in apndSetSystemCall()
10163 return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName); in apndGetSystemCall()
10166 return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName); in apndNextSystemCall()
10189 apnd_vfs.iVersion = pOrig->iVersion; in sqlite3_appendvfs_init()
10191 apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile); in sqlite3_appendvfs_init()
10207 ** 2017-12-26
10236 #include <assert.h>
10271 /* typedef UINT32_TYPE u32; // 4-byte unsigned integer // */
10272 /* typedef UINT16_TYPE u16; // 2-byte unsigned integer // */
10282 # define ALWAYS(X) ((X)?1:(assert(0),0))
10283 # define NEVER(X) ((X)?(assert(0),1):0)
10314 "mtime," /* 2: Last modification time (secs since 1970)*/
10330 ** Use this value for the "version-made-by" field in new zip file
10333 ** This is what info-zip seems to do.
10336 ** Value for "version-required-to-extract" field of new entries.
10340 ** Value for "general-purpose-bit-flags" field of new entries. Bit
10341 ** 11 means "utf-8 filename and comment".
10361 ** The sizes of the fixed-size part of each of the three main data
10406 *** last mod file time 2 bytes
10408 *** crc-32 4 bytes
10447 *** last mod file time 2 bytes
10449 *** crc-32 4 bytes
10473 u32 mUnixTime; /* Modification time, in UNIX format */
10477 ZipfileEntry *pNext; /* Next element in in-memory CDS */
10485 sqlite3_vtab_cursor base; /* Base class - must be first */
10488 u8 bNoop; /* If next xNext() call is no-op */
10495 ZipfileEntry *pFreeEntry; /* Free this list when cursor is closed or reset */
10502 sqlite3_vtab base; /* Base class - must be first */
10527 sqlite3_result_error(ctx, zMsg, -1); in zipfileCtxErrorMsg()
10554 ** argv[0] -> module name ("zipfile")
10555 ** argv[1] -> database name
10556 ** argv[2] -> table name
10557 ** argv[...] -> "column name" and other module argument fields.
10582 assert( 0==sqlite3_stricmp(argv[0], "zipfile") ); in zipfileConnect()
10598 pNew->db = db; in zipfileConnect()
10599 pNew->aBuffer = (u8*)&pNew[1]; in zipfileConnect()
10601 pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE]; in zipfileConnect()
10602 memcpy(pNew->zFile, zFile, nFile); in zipfileConnect()
10603 zipfileDequote(pNew->zFile); in zipfileConnect()
10616 sqlite3_free(p->cds.zFile); in zipfileEntryFree()
10629 if( pTab->pWriteFd ){ in zipfileCleanupTransaction()
10630 fclose(pTab->pWriteFd); in zipfileCleanupTransaction()
10631 pTab->pWriteFd = 0; in zipfileCleanupTransaction()
10633 for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){ in zipfileCleanupTransaction()
10634 pNext = pEntry->pNext; in zipfileCleanupTransaction()
10637 pTab->pFirstEntry = 0; in zipfileCleanupTransaction()
10638 pTab->pLastEntry = 0; in zipfileCleanupTransaction()
10639 pTab->szCurrent = 0; in zipfileCleanupTransaction()
10640 pTab->szOrig = 0; in zipfileCleanupTransaction()
10664 pCsr->iId = ++pTab->iNextCsrid; in zipfileOpen()
10665 pCsr->pCsrNext = pTab->pCsrList; in zipfileOpen()
10666 pTab->pCsrList = pCsr; in zipfileOpen()
10671 ** Reset a cursor back to the state it was in when first returned
10678 pCsr->bEof = 0; in zipfileResetCursor()
10679 if( pCsr->pFile ){ in zipfileResetCursor()
10680 fclose(pCsr->pFile); in zipfileResetCursor()
10681 pCsr->pFile = 0; in zipfileResetCursor()
10682 zipfileEntryFree(pCsr->pCurrent); in zipfileResetCursor()
10683 pCsr->pCurrent = 0; in zipfileResetCursor()
10686 for(p=pCsr->pFreeEntry; p; p=pNext){ in zipfileResetCursor()
10687 pNext = p->pNext; in zipfileResetCursor()
10697 ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab); in zipfileClose()
10702 for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext)); in zipfileClose()
10703 *pp = pCsr->pCsrNext; in zipfileClose()
10716 sqlite3_free(pTab->base.zErrMsg); in zipfileTableErr()
10717 pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap); in zipfileTableErr()
10723 sqlite3_free(pCsr->base.pVtab->zErrMsg); in zipfileCursorErr()
10724 pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); in zipfileCursorErr()
10762 fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET); in zipfileAppendData()
10763 n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd); in zipfileAppendData()
10765 pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()"); in zipfileAppendData()
10768 pTab->szCurrent += nWrite; in zipfileAppendData()
10774 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
10781 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
10792 ** Write a 16-bit little endiate integer into buffer aBuf.
10800 ** Write a 32-bit little endiate integer into buffer aBuf.
10809 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
10810 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
10823 ** if the record is not well-formed, or SQLITE_OK otherwise.
10832 pCDS->iVersionMadeBy = zipfileRead16(aRead); in zipfileReadCDS()
10833 pCDS->iVersionExtract = zipfileRead16(aRead); in zipfileReadCDS()
10834 pCDS->flags = zipfileRead16(aRead); in zipfileReadCDS()
10835 pCDS->iCompression = zipfileRead16(aRead); in zipfileReadCDS()
10836 pCDS->mTime = zipfileRead16(aRead); in zipfileReadCDS()
10837 pCDS->mDate = zipfileRead16(aRead); in zipfileReadCDS()
10838 pCDS->crc32 = zipfileRead32(aRead); in zipfileReadCDS()
10839 pCDS->szCompressed = zipfileRead32(aRead); in zipfileReadCDS()
10840 pCDS->szUncompressed = zipfileRead32(aRead); in zipfileReadCDS()
10841 assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); in zipfileReadCDS()
10842 pCDS->nFile = zipfileRead16(aRead); in zipfileReadCDS()
10843 pCDS->nExtra = zipfileRead16(aRead); in zipfileReadCDS()
10844 pCDS->nComment = zipfileRead16(aRead); in zipfileReadCDS()
10845 pCDS->iDiskStart = zipfileRead16(aRead); in zipfileReadCDS()
10846 pCDS->iInternalAttr = zipfileRead16(aRead); in zipfileReadCDS()
10847 pCDS->iExternalAttr = zipfileRead32(aRead); in zipfileReadCDS()
10848 pCDS->iOffset = zipfileRead32(aRead); in zipfileReadCDS()
10849 assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] ); in zipfileReadCDS()
10857 ** if the record is not well-formed, or SQLITE_OK otherwise.
10870 pLFH->iVersionExtract = zipfileRead16(aRead); in zipfileReadLFH()
10871 pLFH->flags = zipfileRead16(aRead); in zipfileReadLFH()
10872 pLFH->iCompression = zipfileRead16(aRead); in zipfileReadLFH()
10873 pLFH->mTime = zipfileRead16(aRead); in zipfileReadLFH()
10874 pLFH->mDate = zipfileRead16(aRead); in zipfileReadLFH()
10875 pLFH->crc32 = zipfileRead32(aRead); in zipfileReadLFH()
10876 pLFH->szCompressed = zipfileRead32(aRead); in zipfileReadLFH()
10877 pLFH->szUncompressed = zipfileRead32(aRead); in zipfileReadLFH()
10878 pLFH->nFile = zipfileRead16(aRead); in zipfileReadLFH()
10879 pLFH->nExtra = zipfileRead16(aRead); in zipfileReadLFH()
10887 ** Scan through this buffer to find an "extra-timestamp" field. If one
10888 ** exists, extract the 32-bit modification-timestamp from it and store
10891 ** Zero is returned if no extra-timestamp record could be found (and so
10892 ** *pmTime is left unchanged), or non-zero otherwise.
10912 if( b & 0x01 ){ /* 0x01 -> modtime is present */ in zipfileScanExtra()
10926 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
10927 ** fields of the CDS structure passed as the only argument to a 32-bit
10928 ** UNIX seconds-since-the-epoch timestamp. Return the result.
10930 ** "Standard" MS-DOS time format:
10932 ** File modification time:
10933 ** Bits 00-04: seconds divided by 2
10934 ** Bits 05-10: minute
10935 ** Bits 11-15: hour
10937 ** Bits 00-04: day
10938 ** Bits 05-08: month (1-12)
10939 ** Bits 09-15: years from 1980
10941 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
10946 Y = (1980 + ((pCDS->mDate >> 9) & 0x7F)); in zipfileMtime()
10947 M = ((pCDS->mDate >> 5) & 0x0F); in zipfileMtime()
10948 D = (pCDS->mDate & 0x1F); in zipfileMtime()
10949 sec = (pCDS->mTime & 0x1F)*2; in zipfileMtime()
10950 min = (pCDS->mTime >> 5) & 0x3F; in zipfileMtime()
10951 hr = (pCDS->mTime >> 11) & 0x1F; in zipfileMtime()
10953 Y--; in zipfileMtime()
10959 B = 2 - A + (A/4); in zipfileMtime()
10960 JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec; in zipfileMtime()
10961 return (u32)(JDsec - (i64)24405875*(i64)8640); in zipfileMtime()
10977 A = (int)((JD - 1867216.25)/36524.25); in zipfileMtimeToDos()
10978 A = (int)(JD + 1 + A - (A/4)); in zipfileMtimeToDos()
10980 C = (int)((B - 122.1)/365.25); in zipfileMtimeToDos()
10982 E = (int)((B-D)/30.6001); in zipfileMtimeToDos()
10984 day = B - D - (int)(30.6001*E); in zipfileMtimeToDos()
10985 mon = (E<14 ? E-1 : E-13); in zipfileMtimeToDos()
10986 yr = mon>2 ? C-4716 : C-4715; in zipfileMtimeToDos()
10993 pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9)); in zipfileMtimeToDos()
10994 pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11)); in zipfileMtimeToDos()
10996 pCds->mDate = pCds->mTime = 0; in zipfileMtimeToDos()
10999 assert( mUnixTime<315507600 in zipfileMtimeToDos()
11001 || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) in zipfileMtimeToDos()
11009 ** then pFile is a file-handle open on a zip file. In either case, this
11019 const u8 *aBlob, /* Pointer to in-memory file image */ in zipfileGetEntry()
11026 char **pzErr = &pTab->base.zErrMsg; in zipfileGetEntry()
11031 aRead = pTab->aBuffer; in zipfileGetEntry()
11055 rc = zipfileReadCDS(aRead, &pNew->cds); in zipfileGetEntry()
11068 u32 *pt = &pNew->mUnixTime; in zipfileGetEntry()
11069 pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead); in zipfileGetEntry()
11070 pNew->aExtra = (u8*)&pNew[1]; in zipfileGetEntry()
11071 memcpy(pNew->aExtra, &aRead[nFile], nExtra); in zipfileGetEntry()
11072 if( pNew->cds.zFile==0 ){ in zipfileGetEntry()
11074 }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){ in zipfileGetEntry()
11075 pNew->mUnixTime = zipfileMtime(&pNew->cds); in zipfileGetEntry()
11083 rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr); in zipfileGetEntry()
11085 aRead = (u8*)&aBlob[pNew->cds.iOffset]; in zipfileGetEntry()
11090 pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ; in zipfileGetEntry()
11091 pNew->iDataOff += lfh.nFile + lfh.nExtra; in zipfileGetEntry()
11092 if( aBlob && pNew->cds.szCompressed ){ in zipfileGetEntry()
11093 pNew->aData = &pNew->aExtra[nExtra]; in zipfileGetEntry()
11094 memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed); in zipfileGetEntry()
11098 (int)pNew->cds.iOffset in zipfileGetEntry()
11120 if( pCsr->pFile ){ in zipfileNext()
11121 i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize; in zipfileNext()
11122 zipfileEntryFree(pCsr->pCurrent); in zipfileNext()
11123 pCsr->pCurrent = 0; in zipfileNext()
11124 if( pCsr->iNextOff>=iEof ){ in zipfileNext()
11125 pCsr->bEof = 1; in zipfileNext()
11128 ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab); in zipfileNext()
11129 rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p); in zipfileNext()
11131 pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ; in zipfileNext()
11132 pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment; in zipfileNext()
11134 pCsr->pCurrent = p; in zipfileNext()
11137 if( !pCsr->bNoop ){ in zipfileNext()
11138 pCsr->pCurrent = pCsr->pCurrent->pNext; in zipfileNext()
11140 if( pCsr->pCurrent==0 ){ in zipfileNext()
11141 pCsr->bEof = 1; in zipfileNext()
11145 pCsr->bNoop = 0; in zipfileNext()
11179 err = inflateInit2(&str, -15); in zipfileInflate()
11204 ** code is returned and an error message left in virtual-table handle
11221 deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); in zipfileDeflate()
11257 ZipfileCDS *pCDS = &pCsr->pCurrent->cds; in zipfileColumn()
11261 sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT); in zipfileColumn()
11266 sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16); in zipfileColumn()
11269 sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime); in zipfileColumn()
11274 sqlite3_result_int64(ctx, pCDS->szUncompressed); in zipfileColumn()
11281 if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){ in zipfileColumn()
11282 int sz = pCDS->szCompressed; in zipfileColumn()
11283 int szFinal = pCDS->szUncompressed; in zipfileColumn()
11287 if( pCsr->pCurrent->aData ){ in zipfileColumn()
11288 aBuf = pCsr->pCurrent->aData; in zipfileColumn()
11294 FILE *pFile = pCsr->pFile; in zipfileColumn()
11296 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd; in zipfileColumn()
11298 rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff, in zipfileColumn()
11299 &pCsr->base.pVtab->zErrMsg in zipfileColumn()
11304 if( i==5 && pCDS->iCompression ){ in zipfileColumn()
11312 /* Figure out if this is a directory or a zero-sized file. Consider in zipfileColumn()
11315 u32 mode = pCDS->iExternalAttr >> 16; in zipfileColumn()
11317 && pCDS->nFile>=1 in zipfileColumn()
11318 && pCDS->zFile[pCDS->nFile-1]!='/' in zipfileColumn()
11327 sqlite3_result_int(ctx, pCDS->iCompression); in zipfileColumn()
11330 assert( i==7 ); in zipfileColumn()
11331 sqlite3_result_int64(ctx, pCsr->iId); in zipfileColumn()
11343 return pCsr->bEof; in zipfileEof()
11349 ** is guaranteed to be a file-handle open on a zip file.
11354 ** an English language error message may be left in virtual-table pTab.
11358 const u8 *aBlob, /* Pointer to in-memory file image */ in zipfileReadEOCD()
11363 u8 *aRead = pTab->aBuffer; /* Temporary buffer */ in zipfileReadEOCD()
11377 iOff = szFile - nRead; in zipfileReadEOCD()
11378 rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg); in zipfileReadEOCD()
11381 aRead = (u8*)&aBlob[nBlob-nRead]; in zipfileReadEOCD()
11388 for(i=nRead-20; i>=0; i--){ in zipfileReadEOCD()
11396 pTab->base.zErrMsg = sqlite3_mprintf( in zipfileReadEOCD()
11403 pEOCD->iDisk = zipfileRead16(aRead); in zipfileReadEOCD()
11404 pEOCD->iFirstDisk = zipfileRead16(aRead); in zipfileReadEOCD()
11405 pEOCD->nEntry = zipfileRead16(aRead); in zipfileReadEOCD()
11406 pEOCD->nEntryTotal = zipfileRead16(aRead); in zipfileReadEOCD()
11407 pEOCD->nSize = zipfileRead32(aRead); in zipfileReadEOCD()
11408 pEOCD->iOffset = zipfileRead32(aRead); in zipfileReadEOCD()
11425 assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) ); in zipfileAddEntry()
11426 assert( pNew->pNext==0 ); in zipfileAddEntry()
11428 if( pTab->pFirstEntry==0 ){ in zipfileAddEntry()
11429 pTab->pFirstEntry = pTab->pLastEntry = pNew; in zipfileAddEntry()
11431 assert( pTab->pLastEntry->pNext==0 ); in zipfileAddEntry()
11432 pTab->pLastEntry->pNext = pNew; in zipfileAddEntry()
11433 pTab->pLastEntry = pNew; in zipfileAddEntry()
11437 for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext)); in zipfileAddEntry()
11438 pNew->pNext = pBefore; in zipfileAddEntry()
11449 rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd); in zipfileLoadDirectory()
11453 rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew); in zipfileLoadDirectory()
11458 iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment; in zipfileLoadDirectory()
11472 ZipfileTab *pTab = (ZipfileTab*)cur->pVtab; in zipfileFilter()
11476 int bInMemory = 0; /* True for an in-memory zipfile */ in zipfileFilter()
11483 if( pTab->zFile ){ in zipfileFilter()
11484 zFile = pTab->zFile; in zipfileFilter()
11492 assert( pTab->pFirstEntry==0 ); in zipfileFilter()
11498 pCsr->pFreeEntry = pTab->pFirstEntry; in zipfileFilter()
11499 pTab->pFirstEntry = pTab->pLastEntry = 0; in zipfileFilter()
11506 if( 0==pTab->pWriteFd && 0==bInMemory ){ in zipfileFilter()
11507 pCsr->pFile = zFile ? sqlite3_fopen(zFile, "rb") : 0; in zipfileFilter()
11508 if( pCsr->pFile==0 ){ in zipfileFilter()
11512 rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd); in zipfileFilter()
11514 if( pCsr->eocd.nEntry==0 ){ in zipfileFilter()
11515 pCsr->bEof = 1; in zipfileFilter()
11517 pCsr->iNextOff = pCsr->eocd.iOffset; in zipfileFilter()
11523 pCsr->bNoop = 1; in zipfileFilter()
11524 pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry; in zipfileFilter()
11539 int idx = -1; in zipfileBestIndex()
11543 for(i=0; i<pIdxInfo->nConstraint; i++){ in zipfileBestIndex()
11544 const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; in zipfileBestIndex()
11545 if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue; in zipfileBestIndex()
11546 if( pCons->usable==0 ){ in zipfileBestIndex()
11548 }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ in zipfileBestIndex()
11552 pIdxInfo->estimatedCost = 1000.0; in zipfileBestIndex()
11554 pIdxInfo->aConstraintUsage[idx].argvIndex = 1; in zipfileBestIndex()
11555 pIdxInfo->aConstraintUsage[idx].omit = 1; in zipfileBestIndex()
11556 pIdxInfo->idxNum = 1; in zipfileBestIndex()
11568 pNew->cds.zFile = sqlite3_mprintf("%s", zPath); in zipfileNewEntry()
11569 if( pNew->cds.zFile==0 ){ in zipfileNewEntry()
11578 ZipfileCDS *pCds = &pEntry->cds; in zipfileSerializeLFH()
11581 pCds->nExtra = 9; in zipfileSerializeLFH()
11585 zipfileWrite16(a, pCds->iVersionExtract); in zipfileSerializeLFH()
11586 zipfileWrite16(a, pCds->flags); in zipfileSerializeLFH()
11587 zipfileWrite16(a, pCds->iCompression); in zipfileSerializeLFH()
11588 zipfileWrite16(a, pCds->mTime); in zipfileSerializeLFH()
11589 zipfileWrite16(a, pCds->mDate); in zipfileSerializeLFH()
11590 zipfileWrite32(a, pCds->crc32); in zipfileSerializeLFH()
11591 zipfileWrite32(a, pCds->szCompressed); in zipfileSerializeLFH()
11592 zipfileWrite32(a, pCds->szUncompressed); in zipfileSerializeLFH()
11593 zipfileWrite16(a, (u16)pCds->nFile); in zipfileSerializeLFH()
11594 zipfileWrite16(a, pCds->nExtra); in zipfileSerializeLFH()
11595 assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] ); in zipfileSerializeLFH()
11598 memcpy(a, pCds->zFile, (int)pCds->nFile); in zipfileSerializeLFH()
11599 a += (int)pCds->nFile; in zipfileSerializeLFH()
11605 zipfileWrite32(a, pEntry->mUnixTime); in zipfileSerializeLFH()
11607 return a-aBuf; in zipfileSerializeLFH()
11616 u8 *aBuf = pTab->aBuffer; in zipfileAppendEntry()
11623 pEntry->iDataOff = pTab->szCurrent; in zipfileAppendEntry()
11643 const char zTemplate[11] = "-rwxrwxrwx"; in zipfileGetMode()
11647 case '-': mode |= S_IFREG; break; in zipfileGetMode()
11653 if( z[i]==zTemplate[i] ) mode |= 1 << (9-i); in zipfileGetMode()
11654 else if( z[i]!='-' ) goto parse_error; in zipfileGetMode()
11659 ** Or vice-versa - no data but "mode" is a file or symlink. */ in zipfileGetMode()
11672 ** Both (const char*) arguments point to nul-terminated strings. Argument
11677 if( nA>0 && zA[nA-1]=='/' ) nA--; in zipfileComparePath()
11678 if( nB>0 && zB[nB-1]=='/' ) nB--; in zipfileComparePath()
11687 assert( pTab->pWriteFd==0 ); in zipfileBegin()
11688 if( pTab->zFile==0 || pTab->zFile[0]==0 ){ in zipfileBegin()
11689 pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename"); in zipfileBegin()
11696 ** in main-memory until the transaction is committed. */ in zipfileBegin()
11697 pTab->pWriteFd = sqlite3_fopen(pTab->zFile, "ab+"); in zipfileBegin()
11698 if( pTab->pWriteFd==0 ){ in zipfileBegin()
11699 pTab->base.zErrMsg = sqlite3_mprintf( in zipfileBegin()
11700 "zipfile: failed to open file %s for writing", pTab->zFile in zipfileBegin()
11704 fseek(pTab->pWriteFd, 0, SEEK_END); in zipfileBegin()
11705 pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd); in zipfileBegin()
11717 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
11718 ** time(2)).
11724 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ in zipfileTime()
11725 i64 ms; in zipfileTime() local
11726 pVfs->xCurrentTimeInt64(pVfs, &ms); in zipfileTime()
11727 ret = (u32)((ms/1000) - ((i64)24405875 * 8640)); in zipfileTime()
11730 pVfs->xCurrentTime(pVfs, &day); in zipfileTime()
11731 ret = (u32)((day - 2440587.5) * 86400); in zipfileTime()
11737 ** Return a 32-bit timestamp in UNIX epoch format.
11740 ** return the current time. Otherwise, return the value stored in (*pVal)
11741 ** cast to a 32-bit unsigned integer.
11751 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
11756 if( pTab->pFirstEntry==pOld ){ in zipfileRemoveEntryFromList()
11757 pTab->pFirstEntry = pOld->pNext; in zipfileRemoveEntryFromList()
11758 if( pTab->pLastEntry==pOld ) pTab->pLastEntry = 0; in zipfileRemoveEntryFromList()
11761 for(p=pTab->pFirstEntry; p; p=p->pNext){ in zipfileRemoveEntryFromList()
11762 if( p->pNext==pOld ){ in zipfileRemoveEntryFromList()
11763 p->pNext = pOld->pNext; in zipfileRemoveEntryFromList()
11764 if( pTab->pLastEntry==pOld ) pTab->pLastEntry = p; in zipfileRemoveEntryFromList()
11784 ZipfileEntry *pNew = 0; /* New in-memory CDS entry */ in zipfileUpdate()
11787 u32 mTime = 0; /* Modification time for new entry */ in zipfileUpdate()
11804 if( pTab->pWriteFd==0 ){ in zipfileUpdate()
11819 for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){ in zipfileUpdate()
11820 if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){ in zipfileUpdate()
11823 assert( pOld->pNext ); in zipfileUpdate()
11859 rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg); in zipfileUpdate()
11874 rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg); in zipfileUpdate()
11886 ** '/'. This appears to be required for compatibility with info-zip in zipfileUpdate()
11889 if( nPath<=0 || zPath[nPath-1]!='/' ){ in zipfileUpdate()
11901 /* Check that we're not inserting a duplicate entry -OR- updating an in zipfileUpdate()
11905 for(p=pTab->pFirstEntry; p; p=p->pNext){ in zipfileUpdate()
11906 if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){ in zipfileUpdate()
11907 switch( sqlite3_vtab_on_conflict(pTab->db) ){ in zipfileUpdate()
11932 pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; in zipfileUpdate()
11933 pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; in zipfileUpdate()
11934 pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS; in zipfileUpdate()
11935 pNew->cds.iCompression = (u16)iMethod; in zipfileUpdate()
11936 zipfileMtimeToDos(&pNew->cds, mTime); in zipfileUpdate()
11937 pNew->cds.crc32 = iCrc32; in zipfileUpdate()
11938 pNew->cds.szCompressed = nData; in zipfileUpdate()
11939 pNew->cds.szUncompressed = (u32)sz; in zipfileUpdate()
11940 pNew->cds.iExternalAttr = (mode<<16); in zipfileUpdate()
11941 pNew->cds.iOffset = (u32)pTab->szCurrent; in zipfileUpdate()
11942 pNew->cds.nFile = (u16)nPath; in zipfileUpdate()
11943 pNew->mUnixTime = (u32)mTime; in zipfileUpdate()
11952 for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ in zipfileUpdate()
11953 if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){ in zipfileUpdate()
11954 pCsr->pCurrent = pCsr->pCurrent->pNext; in zipfileUpdate()
11955 pCsr->bNoop = 1; in zipfileUpdate()
11972 zipfileWrite16(a, p->iDisk); in zipfileSerializeEOCD()
11973 zipfileWrite16(a, p->iFirstDisk); in zipfileSerializeEOCD()
11974 zipfileWrite16(a, p->nEntry); in zipfileSerializeEOCD()
11975 zipfileWrite16(a, p->nEntryTotal); in zipfileSerializeEOCD()
11976 zipfileWrite32(a, p->nSize); in zipfileSerializeEOCD()
11977 zipfileWrite32(a, p->iOffset); in zipfileSerializeEOCD()
11980 return a-aBuf; in zipfileSerializeEOCD()
11984 int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer); in zipfileAppendEOCD()
11985 assert( nBuf==ZIPFILE_EOCD_FIXED_SZ ); in zipfileAppendEOCD()
11986 return zipfileAppendData(pTab, pTab->aBuffer, nBuf); in zipfileAppendEOCD()
11995 ZipfileCDS *pCDS = &pEntry->cds; in zipfileSerializeCDS()
11997 if( pEntry->aExtra==0 ){ in zipfileSerializeCDS()
11998 pCDS->nExtra = 9; in zipfileSerializeCDS()
12002 zipfileWrite16(a, pCDS->iVersionMadeBy); in zipfileSerializeCDS()
12003 zipfileWrite16(a, pCDS->iVersionExtract); in zipfileSerializeCDS()
12004 zipfileWrite16(a, pCDS->flags); in zipfileSerializeCDS()
12005 zipfileWrite16(a, pCDS->iCompression); in zipfileSerializeCDS()
12006 zipfileWrite16(a, pCDS->mTime); in zipfileSerializeCDS()
12007 zipfileWrite16(a, pCDS->mDate); in zipfileSerializeCDS()
12008 zipfileWrite32(a, pCDS->crc32); in zipfileSerializeCDS()
12009 zipfileWrite32(a, pCDS->szCompressed); in zipfileSerializeCDS()
12010 zipfileWrite32(a, pCDS->szUncompressed); in zipfileSerializeCDS()
12011 assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); in zipfileSerializeCDS()
12012 zipfileWrite16(a, pCDS->nFile); in zipfileSerializeCDS()
12013 zipfileWrite16(a, pCDS->nExtra); in zipfileSerializeCDS()
12014 zipfileWrite16(a, pCDS->nComment); in zipfileSerializeCDS()
12015 zipfileWrite16(a, pCDS->iDiskStart); in zipfileSerializeCDS()
12016 zipfileWrite16(a, pCDS->iInternalAttr); in zipfileSerializeCDS()
12017 zipfileWrite32(a, pCDS->iExternalAttr); in zipfileSerializeCDS()
12018 zipfileWrite32(a, pCDS->iOffset); in zipfileSerializeCDS()
12020 memcpy(a, pCDS->zFile, pCDS->nFile); in zipfileSerializeCDS()
12021 a += pCDS->nFile; in zipfileSerializeCDS()
12023 if( pEntry->aExtra ){ in zipfileSerializeCDS()
12024 int n = (int)pCDS->nExtra + (int)pCDS->nComment; in zipfileSerializeCDS()
12025 memcpy(a, pEntry->aExtra, n); in zipfileSerializeCDS()
12028 assert( pCDS->nExtra==9 ); in zipfileSerializeCDS()
12032 zipfileWrite32(a, pEntry->mUnixTime); in zipfileSerializeCDS()
12035 return a-aBuf; in zipfileSerializeCDS()
12041 if( pTab->pWriteFd ){ in zipfileCommit()
12042 i64 iOffset = pTab->szCurrent; in zipfileCommit()
12048 for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){ in zipfileCommit()
12049 int n = zipfileSerializeCDS(p, pTab->aBuffer); in zipfileCommit()
12050 rc = zipfileAppendData(pTab, pTab->aBuffer, n); in zipfileCommit()
12059 eocd.nSize = (u32)(pTab->szCurrent - iOffset); in zipfileCommit()
12074 for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ in zipfileFindCursor()
12075 if( iId==pCsr->iId ) break; in zipfileFindCursor()
12087 assert( argc>0 ); in zipfileFunctionCds()
12091 ZipfileCDS *p = &pCsr->pCurrent->cds; in zipfileFunctionCds()
12093 "\"version-made-by\" : %u, " in zipfileFunctionCds()
12094 "\"version-to-extract\" : %u, " in zipfileFunctionCds()
12097 "\"time\" : %u, " in zipfileFunctionCds()
12100 "\"compressed-size\" : %u, " in zipfileFunctionCds()
12101 "\"uncompressed-size\" : %u, " in zipfileFunctionCds()
12102 "\"file-name-length\" : %u, " in zipfileFunctionCds()
12103 "\"extra-field-length\" : %u, " in zipfileFunctionCds()
12104 "\"file-comment-length\" : %u, " in zipfileFunctionCds()
12105 "\"disk-number-start\" : %u, " in zipfileFunctionCds()
12106 "\"internal-attr\" : %u, " in zipfileFunctionCds()
12107 "\"external-attr\" : %u, " in zipfileFunctionCds()
12109 (u32)p->iVersionMadeBy, (u32)p->iVersionExtract, in zipfileFunctionCds()
12110 (u32)p->flags, (u32)p->iCompression, in zipfileFunctionCds()
12111 (u32)p->mTime, (u32)p->mDate, in zipfileFunctionCds()
12112 (u32)p->crc32, (u32)p->szCompressed, in zipfileFunctionCds()
12113 (u32)p->szUncompressed, (u32)p->nFile, in zipfileFunctionCds()
12114 (u32)p->nExtra, (u32)p->nComment, in zipfileFunctionCds()
12115 (u32)p->iDiskStart, (u32)p->iInternalAttr, in zipfileFunctionCds()
12116 (u32)p->iExternalAttr, (u32)p->iOffset in zipfileFunctionCds()
12122 sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT); in zipfileFunctionCds()
12162 if( pBuf->n+nByte>pBuf->nAlloc ){ in zipfileBufferGrow()
12164 sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512; in zipfileBufferGrow()
12165 int nReq = pBuf->n + nByte; in zipfileBufferGrow()
12168 aNew = sqlite3_realloc64(pBuf->a, nNew); in zipfileBufferGrow()
12170 pBuf->a = aNew; in zipfileBufferGrow()
12171 pBuf->nAlloc = (int)nNew; in zipfileBufferGrow()
12199 int iMethod = -1; /* Compression method to use (0 or 8) */ in zipfileStep()
12238 zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL"); in zipfileStep()
12291 if( nName>0 && zName[nName-1]=='/' ){ in zipfileStep()
12292 zErr = sqlite3_mprintf("non-directory name must not end with /"); in zipfileStep()
12297 if( nName==0 || zName[nName-1]!='/' ){ in zipfileStep()
12305 while( nName>1 && zName[nName-2]=='/' ) nName--; in zipfileStep()
12319 e.cds.iOffset = p->body.n; in zipfileStep()
12325 if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out; in zipfileStep()
12326 p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]); in zipfileStep()
12330 if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out; in zipfileStep()
12331 memcpy(&p->body.a[p->body.n], aData, nData); in zipfileStep()
12332 p->body.n += nData; in zipfileStep()
12337 if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out; in zipfileStep()
12338 p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]); in zipfileStep()
12341 p->nEntry++; in zipfileStep()
12348 sqlite3_result_error(pCtx, zErr, -1); in zipfileStep()
12367 if( p->nEntry>0 ){ in zipfileFinal()
12369 eocd.nEntry = (u16)p->nEntry; in zipfileFinal()
12370 eocd.nEntryTotal = (u16)p->nEntry; in zipfileFinal()
12371 eocd.nSize = p->cds.n; in zipfileFinal()
12372 eocd.iOffset = p->body.n; in zipfileFinal()
12374 nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ; in zipfileFinal()
12379 memcpy(aZip, p->body.a, p->body.n); in zipfileFinal()
12380 memcpy(&aZip[p->body.n], p->cds.a, p->cds.n); in zipfileFinal()
12381 zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]); in zipfileFinal()
12386 sqlite3_free(p->body.a); in zipfileFinal()
12387 sqlite3_free(p->cds.a); in zipfileFinal()
12402 zipfileOpen, /* xOpen - open a cursor */ in zipfileRegister()
12403 zipfileClose, /* xClose - close a cursor */ in zipfileRegister()
12404 zipfileFilter, /* xFilter - configure scan constraints */ in zipfileRegister()
12405 zipfileNext, /* xNext - advance a cursor */ in zipfileRegister()
12406 zipfileEof, /* xEof - check for end of scan */ in zipfileRegister()
12407 zipfileColumn, /* xColumn - read data */ in zipfileRegister()
12408 0, /* xRowid - read data */ in zipfileRegister()
12424 if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1); in zipfileRegister()
12426 rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0, in zipfileRegister()
12430 assert( sizeof(i64)==8 ); in zipfileRegister()
12431 assert( sizeof(u32)==4 ); in zipfileRegister()
12432 assert( sizeof(u16)==2 ); in zipfileRegister()
12433 assert( sizeof(u8)==1 ); in zipfileRegister()
12456 ** 2017-12-17
12468 ** for working with sqlar archives and used by the shell tool's built-in
12474 #include <assert.h>
12484 ** contains a two-byte identification header and a four-byte checksum at
12496 assert( argc==1 ); in sqlarCompressFunc()
12509 sqlite3_result_error(context, "error in compress()", -1); in sqlarCompressFunc()
12540 assert( argc==2 ); in sqlarUncompressFunc()
12552 sqlite3_result_error(context, "error in uncompress()", -1); in sqlarUncompressFunc()
12608 ** an English-language error message. In this case it is the responsibility
12628 ** the analysis - indexes are recommended based on the database schema only.
12652 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
12653 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
12688 ** possible to add further SQL statements to the object or to re-attempt
12706 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
12714 ** If an out-of-range value (less than zero or equal to or greater than the
12748 ** sqlite3-expert_new().
12769 #include <assert.h>
12781 # define ALWAYS(X) ((X)?1:(assert(0),0))
12782 # define NEVER(X) ((X)?(assert(0),1):0)
12813 ** any other type of single-ended range constraint on a column).
12859 ** An object of the following type is created for each unique table/write-op
12860 ** seen. The objects are stored in a singly-linked list beginning at
12895 char *zKey; /* nul-terminated key */
12896 char *zVal; /* nul-terminated value string */
12897 char *zVal2; /* nul-terminated value string 2 */
12912 sqlite3 *dbm; /* In-memory db for this analysis */
12932 assert( *pRc==SQLITE_OK ); in idxMalloc()
12933 assert( nByte>0 ); in idxMalloc()
12951 ** Reset an IdxHash hash table.
12958 for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){ in idxHashClear()
12959 pNext = pEntry->pHashNext; in idxHashClear()
12960 sqlite3_free(pEntry->zVal2); in idxHashClear()
12981 ** If zKey is already present in the hash table, return non-zero and do
12995 assert( iHash>=0 ); in idxHashAdd()
12996 for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){ in idxHashAdd()
12997 if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){ in idxHashAdd()
13003 pEntry->zKey = (char*)&pEntry[1]; in idxHashAdd()
13004 memcpy(pEntry->zKey, zKey, nKey); in idxHashAdd()
13006 pEntry->zVal = &pEntry->zKey[nKey+1]; in idxHashAdd()
13007 memcpy(pEntry->zVal, zVal, nVal); in idxHashAdd()
13009 pEntry->pHashNext = pHash->aHash[iHash]; in idxHashAdd()
13010 pHash->aHash[iHash] = pEntry; in idxHashAdd()
13012 pEntry->pNext = pHash->pFirst; in idxHashAdd()
13013 pHash->pFirst = pEntry; in idxHashAdd()
13020 ** hash-entry object.
13027 assert( iHash>=0 ); in idxHashFind()
13028 for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){ in idxHashFind()
13029 if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){ in idxHashFind()
13044 if( pEntry ) return pEntry->zVal; in idxHashSearch()
13050 ** variable to point to a copy of nul-terminated string zColl.
13056 assert( *pRc==SQLITE_OK ); in idxNewConstraint()
13059 pNew->zColl = (char*)&pNew[1]; in idxNewConstraint()
13060 memcpy(pNew->zColl, zColl, nColl+1); in idxNewConstraint()
13085 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); in idxPrepareStmt()
13139 assert( zIn[0]=='\'' ); in expertDequote()
13140 assert( zIn[n-1]=='\'' ); in expertDequote()
13145 for(iIn=1; iIn<(n-1); iIn++){ in expertDequote()
13147 assert( zIn[iIn+1]=='\'' ); in expertDequote()
13160 ** methods of the r-tree virtual table.
13162 ** argv[0] -> module name
13163 ** argv[1] -> database name
13164 ** argv[2] -> table name
13165 ** argv[...] -> column names...
13189 p->pExpert = pExpert; in expertConnect()
13190 p->pTab = pExpert->pTable; in expertConnect()
13191 assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 ); in expertConnect()
13224 pScan->pTab = p->pTab; in expertBestIndex()
13225 pScan->pNextScan = p->pExpert->pScan; in expertBestIndex()
13226 p->pExpert->pScan = pScan; in expertBestIndex()
13229 for(i=0; i<pIdxInfo->nConstraint; i++){ in expertBestIndex()
13230 struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; in expertBestIndex()
13231 if( pCons->usable in expertBestIndex()
13232 && pCons->iColumn>=0 in expertBestIndex()
13233 && p->pTab->aCol[pCons->iColumn].iPk==0 in expertBestIndex()
13234 && (pCons->op & opmask) in expertBestIndex()
13240 pNew->iCol = pCons->iColumn; in expertBestIndex()
13241 if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ in expertBestIndex()
13242 pNew->pNext = pScan->pEq; in expertBestIndex()
13243 pScan->pEq = pNew; in expertBestIndex()
13245 pNew->bRange = 1; in expertBestIndex()
13246 pNew->pNext = pScan->pRange; in expertBestIndex()
13247 pScan->pRange = pNew; in expertBestIndex()
13251 pIdxInfo->aConstraintUsage[i].argvIndex = n; in expertBestIndex()
13256 for(i=pIdxInfo->nOrderBy-1; i>=0; i--){ in expertBestIndex()
13257 int iCol = pIdxInfo->aOrderBy[i].iColumn; in expertBestIndex()
13259 IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl); in expertBestIndex()
13261 pNew->iCol = iCol; in expertBestIndex()
13262 pNew->bDesc = pIdxInfo->aOrderBy[i].desc; in expertBestIndex()
13263 pNew->pNext = pScan->pOrder; in expertBestIndex()
13264 pNew->pLink = pScan->pOrder; in expertBestIndex()
13265 pScan->pOrder = pNew; in expertBestIndex()
13272 pIdxInfo->estimatedCost = 1000000.0 / (n+1); in expertBestIndex()
13306 sqlite3_finalize(pCsr->pData); in expertClose()
13314 ** Return non-zero if the cursor does not currently point to a valid
13319 return pCsr->pData==0; in expertEof()
13329 assert( pCsr->pData ); in expertNext()
13330 rc = sqlite3_step(pCsr->pData); in expertNext()
13332 rc = sqlite3_finalize(pCsr->pData); in expertNext()
13333 pCsr->pData = 0; in expertNext()
13356 pVal = sqlite3_column_value(pCsr->pData, i); in expertColumn()
13372 ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab); in expertFilter()
13373 sqlite3expert *pExpert = pVtab->pExpert; in expertFilter()
13380 rc = sqlite3_finalize(pCsr->pData); in expertFilter()
13381 pCsr->pData = 0; in expertFilter()
13383 rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg, in expertFilter()
13384 "SELECT * FROM main.%Q WHERE sqlite_expert_sample()", pVtab->pTab->zName in expertFilter()
13397 expertConnect, /* xCreate - create a table */ in idxRegisterVtab()
13398 expertConnect, /* xConnect - connect to an existing table */ in idxRegisterVtab()
13399 expertBestIndex, /* xBestIndex - Determine search strategy */ in idxRegisterVtab()
13400 expertDisconnect, /* xDisconnect - Disconnect from a table */ in idxRegisterVtab()
13401 expertDisconnect, /* xDestroy - Drop a table */ in idxRegisterVtab()
13402 expertOpen, /* xOpen - open a cursor */ in idxRegisterVtab()
13403 expertClose, /* xClose - close a cursor */ in idxRegisterVtab()
13404 expertFilter, /* xFilter - configure scan constraints */ in idxRegisterVtab()
13405 expertNext, /* xNext - advance a cursor */ in idxRegisterVtab()
13407 expertColumn, /* xColumn - read data */ in idxRegisterVtab()
13408 expertRowid, /* xRowid - read data */ in idxRegisterVtab()
13409 expertUpdate, /* xUpdate - write data */ in idxRegisterVtab()
13410 0, /* xBegin - begin transaction */ in idxRegisterVtab()
13411 0, /* xSync - sync transaction */ in idxRegisterVtab()
13412 0, /* xCommit - commit transaction */ in idxRegisterVtab()
13413 0, /* xRollback - rollback transaction */ in idxRegisterVtab()
13414 0, /* xFindFunction - function overloading */ in idxRegisterVtab()
13415 0, /* xRename - rename the table */ in idxRegisterVtab()
13423 return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p); in idxRegisterVtab()
13492 pNew->aCol = (IdxColumn*)&pNew[1]; in idxGetTableInfo()
13493 pNew->nCol = nCol; in idxGetTableInfo()
13494 pCsr = (char*)&pNew->aCol[nCol]; in idxGetTableInfo()
13504 pNew->aCol[nCol].zName = pCsr; in idxGetTableInfo()
13505 pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1); in idxGetTableInfo()
13515 pNew->aCol[nCol].zColl = pCsr; in idxGetTableInfo()
13528 pNew->zName = pCsr; in idxGetTableInfo()
13529 if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1); in idxGetTableInfo()
13537 ** This function is a no-op if *pRc is set to anything other than
13606 IdxColumn *p = &pTab->aCol[pCons->iCol]; in idxAppendColDefn()
13609 if( idxIdentifierRequiresQuotes(p->zName) ){ in idxAppendColDefn()
13610 zRet = idxAppendText(pRc, zRet, "%Q", p->zName); in idxAppendColDefn()
13612 zRet = idxAppendText(pRc, zRet, "%s", p->zName); in idxAppendColDefn()
13615 if( sqlite3_stricmp(p->zColl, pCons->zColl) ){ in idxAppendColDefn()
13616 if( idxIdentifierRequiresQuotes(pCons->zColl) ){ in idxAppendColDefn()
13617 zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl); in idxAppendColDefn()
13619 zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl); in idxAppendColDefn()
13623 if( pCons->bDesc ){ in idxAppendColDefn()
13632 ** such an index is found, return non-zero. Or, if no such index is found,
13644 const char *zTbl = pScan->pTab->zName; in idxFindCompatible()
13651 for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++; in idxFindCompatible()
13662 for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0; in idxFindCompatible()
13671 for(pIter=pEq; pIter; pIter=pIter->pLink){ in idxFindCompatible()
13672 if( pIter->bFlag ) continue; in idxFindCompatible()
13673 if( pIter->iCol!=iCol ) continue; in idxFindCompatible()
13674 if( sqlite3_stricmp(pIter->zColl, zColl) ) continue; in idxFindCompatible()
13675 pIter->bFlag = 1; in idxFindCompatible()
13684 if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){ in idxFindCompatible()
13688 pT = pT->pLink; in idxFindCompatible()
13724 sqlite3 *dbm = p->dbm; in idxCreateFromCons()
13727 IdxTable *pTab = pScan->pTab; in idxCreateFromCons()
13734 for(pCons=pEq; pCons; pCons=pCons->pLink){ in idxCreateFromCons()
13737 for(pCons=pTail; pCons; pCons=pCons->pLink){ in idxCreateFromCons()
13743 const char *zTable = pScan->pTab->zName; in idxCreateFromCons()
13762 assert(rc==SQLITE_OK); in idxCreateFromCons()
13785 rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg); in idxCreateFromCons()
13789 idxHashAdd(&rc, &p->hIdx, zName, zIdx); in idxCreateFromCons()
13808 for(pCmp=pList; pCmp; pCmp=pCmp->pLink){ in idxFindConstraint()
13809 if( p->iCol==pCmp->iCol ) return 1; in idxFindConstraint()
13824 for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){ in idxCreateFromWhere()
13826 pCon->pLink = p1; in idxCreateFromWhere()
13838 for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){ in idxCreateFromWhere()
13839 assert( pCon->pLink==0 ); in idxCreateFromWhere()
13851 ** linked-list pScan.
13857 for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){ in idxCreateCandidates()
13859 if( rc==SQLITE_OK && pIter->pOrder ){ in idxCreateCandidates()
13860 rc = idxCreateFromWhere(p, pIter, pIter->pOrder); in idxCreateCandidates()
13875 pNext = p->pNext; in idxConstraintFree()
13888 pNext = p->pNextScan; in idxScanFree()
13889 idxConstraintFree(p->pOrder); in idxScanFree()
13890 idxConstraintFree(p->pEq); in idxScanFree()
13891 idxConstraintFree(p->pRange); in idxScanFree()
13904 pNext = p->pNext; in idxStatementFree()
13905 sqlite3_free(p->zEQP); in idxStatementFree()
13906 sqlite3_free(p->zIdx); in idxStatementFree()
13918 pNext = pIter->pNext; in idxTableFree()
13930 pNext = pIter->pNext; in idxWriteFree()
13947 sqlite3 *dbm = p->dbm; in idxFindIndexes()
13953 for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){ in idxFindIndexes()
13958 "EXPLAIN QUERY PLAN %s", pStmt->zSql in idxFindIndexes()
13986 zSql = idxHashSearch(&p->hIdx, zIdx, nIdx); in idxFindIndexes()
13995 if( zDetail[0]!='-' ){ in idxFindIndexes()
13996 pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail); in idxFindIndexes()
14000 for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){ in idxFindIndexes()
14001 pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey); in idxFindIndexes()
14027 for(pTab=p->pTable; pTab; pTab=pTab->pNext){ in idxAuthCallback()
14028 if( 0==sqlite3_stricmp(z3, pTab->zName) ) break; in idxAuthCallback()
14032 for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){ in idxAuthCallback()
14033 if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break; in idxAuthCallback()
14038 pWrite->pTab = pTab; in idxAuthCallback()
14039 pWrite->eOp = eOp; in idxAuthCallback()
14040 pWrite->pNext = p->pWrite; in idxAuthCallback()
14041 p->pWrite = pWrite; in idxAuthCallback()
14057 IdxTable *pTab = pWrite->pTab; in idxProcessOneTrigger()
14058 const char *zTab = pTab->zName; in idxProcessOneTrigger()
14068 rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab); in idxProcessOneTrigger()
14072 rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr); in idxProcessOneTrigger()
14082 rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr); in idxProcessOneTrigger()
14087 switch( pWrite->eOp ){ in idxProcessOneTrigger()
14091 for(i=0; i<pTab->nCol; i++){ in idxProcessOneTrigger()
14100 for(i=0; i<pTab->nCol; i++){ in idxProcessOneTrigger()
14102 pTab->aCol[i].zName in idxProcessOneTrigger()
14108 assert( pWrite->eOp==SQLITE_DELETE ); in idxProcessOneTrigger()
14118 rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0); in idxProcessOneTrigger()
14121 idxDatabaseError(p->dbv, pzErr); in idxProcessOneTrigger()
14127 rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr); in idxProcessOneTrigger()
14136 IdxWrite *pFirst = p->pWrite; in idxProcessTriggers()
14140 for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){ in idxProcessTriggers()
14144 pFirst = p->pWrite; in idxProcessTriggers()
14168 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); in expertDbContainsObject()
14170 sqlite3_bind_text(pSql, 1, zTab, -1, SQLITE_STATIC); in expertDbContainsObject()
14217 ** 1) Add an entry to the p->pTable list, and in idxCreateVtabSchema()
14220 rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg, in idxCreateVtabSchema()
14240 rc = expertDbContainsObject(p->dbv, zName, &bExists); in idxCreateVtabSchema()
14245 if( zSql ) rc = expertSchemaSql(p->dbv, zSql, pzErrmsg); in idxCreateVtabSchema()
14248 rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg); in idxCreateVtabSchema()
14253 pTab->pNext = p->pTable; in idxCreateVtabSchema()
14254 p->pTable = pTab; in idxCreateVtabSchema()
14258 for(i=0; i<pTab->nCol; i++){ in idxCreateVtabSchema()
14260 (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl in idxCreateVtabSchema()
14270 rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg); in idxCreateVtabSchema()
14297 assert( argc==0 ); in idxSampleFunc()
14298 if( p->nRow==0.0 ){ in idxSampleFunc()
14301 bRet = (p->nRet / p->nRow) <= p->target; in idxSampleFunc()
14305 bRet = ((int)rnd % 100) <= p->iTarget; in idxSampleFunc()
14310 p->nRow += 1.0; in idxSampleFunc()
14311 p->nRet += (double)bRet; in idxSampleFunc()
14337 assert( argc==2 ); in idxRemFunc()
14340 assert( iSlot<p->nSlot ); in idxRemFunc()
14341 pSlot = &p->aSlot[iSlot]; in idxRemFunc()
14343 switch( pSlot->eType ){ in idxRemFunc()
14345 /* no-op */ in idxRemFunc()
14349 sqlite3_result_int64(pCtx, pSlot->iVal); in idxRemFunc()
14353 sqlite3_result_double(pCtx, pSlot->rVal); in idxRemFunc()
14357 sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT); in idxRemFunc()
14361 sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT); in idxRemFunc()
14365 pSlot->eType = sqlite3_value_type(argv[1]); in idxRemFunc()
14366 switch( pSlot->eType ){ in idxRemFunc()
14368 /* no-op */ in idxRemFunc()
14372 pSlot->iVal = sqlite3_value_int64(argv[1]); in idxRemFunc()
14376 pSlot->rVal = sqlite3_value_double(argv[1]); in idxRemFunc()
14383 if( nByte>pSlot->nByte ){ in idxRemFunc()
14384 char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2); in idxRemFunc()
14389 pSlot->nByte = nByte*2; in idxRemFunc()
14390 pSlot->z = zNew; in idxRemFunc()
14392 pSlot->n = nByte; in idxRemFunc()
14393 if( pSlot->eType==SQLITE_BLOB ){ in idxRemFunc()
14395 if( pData ) memcpy(pSlot->z, pData, nByte); in idxRemFunc()
14398 memcpy(pSlot->z, pData, nByte); in idxRemFunc()
14442 assert( p->iSample>0 ); in idxPopulateOneStat1()
14445 sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC); in idxPopulateOneStat1()
14464 if( p->iSample==100 ){ in idxPopulateOneStat1()
14479 sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv); in idxPopulateOneStat1()
14496 for(/*no-op*/; i<nCol; i++){ in idxPopulateOneStat1()
14511 sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC); in idxPopulateOneStat1()
14512 sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC); in idxPopulateOneStat1()
14513 sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC); in idxPopulateOneStat1()
14518 pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx)); in idxPopulateOneStat1()
14520 assert( pEntry->zVal2==0 ); in idxPopulateOneStat1()
14521 pEntry->zVal2 = zStat; in idxPopulateOneStat1()
14536 rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0); in idxBuildSampleTable()
14543 rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0); in idxBuildSampleTable()
14562 i64 iPrev = -100000; in idxPopulateStat1()
14577 if( p->iSample==0 ) return SQLITE_OK; in idxPopulateStat1()
14579 rc = idxLargestIndex(p->dbm, &nMax, pzErr); in idxPopulateStat1()
14582 rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0); in idxPopulateStat1()
14590 sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv); in idxPopulateStat1()
14596 rc = sqlite3_create_function(p->db, "sqlite_expert_sample", in idxPopulateStat1()
14602 pCtx->nSlot = nMax+1; in idxPopulateStat1()
14603 rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex); in idxPopulateStat1()
14606 rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo); in idxPopulateStat1()
14609 rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite); in idxPopulateStat1()
14617 if( p->iSample<100 && iPrev!=iRowid ){ in idxPopulateStat1()
14618 samplectx.target = (double)p->iSample / 100.0; in idxPopulateStat1()
14619 samplectx.iTarget = p->iSample; in idxPopulateStat1()
14628 if( rc==SQLITE_OK && p->iSample<100 ){ in idxPopulateStat1()
14629 rc = sqlite3_exec(p->dbv, in idxPopulateStat1()
14639 for(i=0; i<pCtx->nSlot; i++){ in idxPopulateStat1()
14640 sqlite3_free(pCtx->aSlot[i].z); in idxPopulateStat1()
14646 rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0); in idxPopulateStat1()
14649 sqlite3_create_function(p->db, "sqlite_expert_rem", 2, SQLITE_UTF8, 0,0,0,0); in idxPopulateStat1()
14650 sqlite3_create_function(p->db, "sqlite_expert_sample", 0,SQLITE_UTF8,0,0,0,0); in idxPopulateStat1()
14652 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0); in idxPopulateStat1()
14666 assert(0); /* VDBE should never be run. */ in dummyCompare()
14678 ** dummy functions for no-op implementation of UDFs during expert's work
14684 assert(0); /* VDBE should never be run. */ in dummyUDF()
14688 assert(0); /* VDBE should never be run. */ in dummyUDFvalue()
14699 "WHERE builtin==0", -1, &pStmt, 0); in registerUDFs()
14708 /* no-op. Only happens on OOM */ in registerUDFs()
14747 /* Open two in-memory databases to work with. The "vtab database" (dbv) in sqlite3_expert_new()
14754 pNew->db = db; in sqlite3_expert_new()
14755 pNew->iSample = 100; in sqlite3_expert_new()
14756 rc = sqlite3_open(":memory:", &pNew->dbv); in sqlite3_expert_new()
14759 rc = sqlite3_open(":memory:", &pNew->dbm); in sqlite3_expert_new()
14761 sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0); in sqlite3_expert_new()
14766 if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbm,0,useDummyCS); in sqlite3_expert_new()
14767 if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbv,0,useDummyCS); in sqlite3_expert_new()
14773 rc = registerUDFs(pNew->db, pNew->dbm); in sqlite3_expert_new()
14776 rc = registerUDFs(pNew->db, pNew->dbv); in sqlite3_expert_new()
14783 rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg, in sqlite3_expert_new()
14792 rc = expertDbContainsObject(pNew->dbm, zName, &bExists); in sqlite3_expert_new()
14794 rc = expertSchemaSql(pNew->dbm, zSql, pzErrmsg); in sqlite3_expert_new()
14807 sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew); in sqlite3_expert_new()
14831 p->iSample = iVal; in sqlite3_expert_config()
14851 IdxScan *pScanOrig = p->pScan; in sqlite3_expert_sql()
14852 IdxStatement *pStmtOrig = p->pStatement; in sqlite3_expert_sql()
14856 if( p->bRun ) return SQLITE_MISUSE; in sqlite3_expert_sql()
14861 rc = idxPrepareStmt(p->db, &pStmt, pzErr, zStmt); in sqlite3_expert_sql()
14864 rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt); in sqlite3_expert_sql()
14872 pNew->zSql = (char*)&pNew[1]; in sqlite3_expert_sql()
14873 memcpy(pNew->zSql, z, n+1); in sqlite3_expert_sql()
14874 pNew->pNext = p->pStatement; in sqlite3_expert_sql()
14875 if( p->pStatement ) pNew->iId = p->pStatement->iId+1; in sqlite3_expert_sql()
14876 p->pStatement = pNew; in sqlite3_expert_sql()
14881 idxDatabaseError(p->dbv, pzErr); in sqlite3_expert_sql()
14886 idxScanFree(p->pScan, pScanOrig); in sqlite3_expert_sql()
14887 idxStatementFree(p->pStatement, pStmtOrig); in sqlite3_expert_sql()
14888 p->pScan = pScanOrig; in sqlite3_expert_sql()
14889 p->pStatement = pStmtOrig; in sqlite3_expert_sql()
14902 /* Create candidate indexes within the in-memory database file */ in sqlite3_expert_analyze()
14917 for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){ in sqlite3_expert_analyze()
14918 p->zCandidates = idxAppendText(&rc, p->zCandidates, in sqlite3_expert_analyze()
14919 "%s;%s%s\n", pEntry->zVal, in sqlite3_expert_analyze()
14920 pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2 in sqlite3_expert_analyze()
14931 p->bRun = 1; in sqlite3_expert_analyze()
14942 if( p->pStatement ) nRet = p->pStatement->iId+1; in sqlite3_expert_count()
14953 if( p->bRun==0 ) return 0; in sqlite3_expert_report()
14954 for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext); in sqlite3_expert_report()
14957 if( pStmt ) zRet = pStmt->zSql; in sqlite3_expert_report()
14960 if( pStmt ) zRet = pStmt->zIdx; in sqlite3_expert_report()
14963 if( pStmt ) zRet = pStmt->zEQP; in sqlite3_expert_report()
14966 zRet = p->zCandidates; in sqlite3_expert_report()
14977 sqlite3_close(p->dbm); in sqlite3_expert_destroy()
14978 sqlite3_close(p->dbv); in sqlite3_expert_destroy()
14979 idxScanFree(p->pScan, 0); in sqlite3_expert_destroy()
14980 idxStatementFree(p->pStatement, 0); in sqlite3_expert_destroy()
14981 idxTableFree(p->pTable); in sqlite3_expert_destroy()
14982 idxWriteFree(p->pWrite); in sqlite3_expert_destroy()
14983 idxHashClear(&p->hIdx); in sqlite3_expert_destroy()
14984 sqlite3_free(p->zCandidates); in sqlite3_expert_destroy()
14994 ** 2024-02-08
15007 ** Incremental Integrity-Check Extension
15008 ** -------------------------------------
15011 ** is well-formed or corrupt. This is the same task as performed by SQLite's
15012 ** built-in "PRAGMA integrity_check" command. This module differs from
15015 ** + It is less thorough - this module does not detect certain types
15022 ** + It allows integrity-check operations to be split into multiple
15023 ** transactions, so that the database does not need to be read-locked
15024 ** for the duration of the integrity-check.
15026 ** One way to use the API to run integrity-check on the "main" database
15045 ** integrity-check is complete. However, if sqlite3_intck_unlock() is
15060 ** An ongoing incremental integrity-check operation is represented by an
15066 ** Open a new incremental integrity-check object. If successful, populate
15071 ** The integrity-check will be conducted on database zDb (which must be "main",
15074 ** database handle db until the integrity-check object has been destroyed
15086 ** integrity-check handle after it has been passed to this function are
15092 ** Do the next step of the integrity-check operation specified by the handle
15094 ** integrity-check operation is finished, or an SQLite error code if
15095 ** an error occurs, or SQLITE_OK if no error occurs but the integrity-check
15100 ** SQLITE_OK), sqlite3_intck_message() returns a non-NULL value if
15104 ** returned, then the integrity-check handle is placed in an error state.
15115 ** containing a nul-terminated string describing the corruption in
15123 ** Close any read-transaction opened by an earlier call to
15128 ** If an error occurs, then the integrity-check handle is placed in an error
15140 ** may be set to point to a nul-terminated string containing an English
15151 ** This API is used for testing only. It returns the full-text of an SQL
15168 ** 2024-02-08
15182 #include <assert.h>
15195 ** the integrity-check operation is finished.
15225 ** Some error has occurred while using database p->db. Save the error message
15226 ** and error code currently held by the database handle in p->rc and p->zErr.
15229 p->rc = sqlite3_errcode(p->db); in intckSaveErrmsg()
15230 sqlite3_free(p->zErr); in intckSaveErrmsg()
15231 p->zErr = sqlite3_mprintf("%s", sqlite3_errmsg(p->db)); in intckSaveErrmsg()
15236 ** then this function is a no-op (returns NULL immediately). Otherwise, if an
15244 if( p->rc==SQLITE_OK ){ in intckPrepare()
15245 p->rc = sqlite3_prepare_v2(p->db, zSql, -1, &pRet, 0); in intckPrepare()
15246 if( p->rc!=SQLITE_OK ){ in intckPrepare()
15248 assert( pRet==0 ); in intckPrepare()
15256 ** then this function is a no-op (returns NULL immediately). Otherwise, if an
15270 if( p->rc==SQLITE_OK && zSql==0 ){ in intckPrepareFmt()
15271 p->rc = SQLITE_NOMEM; in intckPrepareFmt()
15286 if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){ in intckFinalize()
15296 if( p->rc ) return p->rc; in intckStep()
15321 if( p->rc==SQLITE_OK ){ in intckMprintf()
15323 p->rc = SQLITE_NOMEM; in intckMprintf()
15334 ** required to restart the current pCheck query as a nul-terminated string
15335 ** in p->zKey.
15344 assert( p->pCheck ); in intckSaveKey()
15345 assert( p->zKey==0 ); in intckSaveKey()
15351 p->zDb, p->zObj, p->zDb, p->zObj in intckSaveKey()
15353 if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXinfo) ){ in intckSaveKey()
15361 for(ii=0; ii<p->nKeyVal; ii++){ in intckSaveKey()
15369 assert( p->nKeyVal>1 ); in intckSaveKey()
15370 for(ii=p->nKeyVal; ii>0; ii--){ in intckSaveKey()
15371 int bLastIsDesc = zDir[ii-1]=='1'; in intckSaveKey()
15372 int bLastIsNull = sqlite3_column_type(p->pCheck, ii)==SQLITE_NULL; in intckSaveKey()
15373 const char *zLast = sqlite3_column_name(p->pCheck, ii); in intckSaveKey()
15390 for(jj=0; jj<ii-1; jj++){ in intckSaveKey()
15391 const char *zAlias = (const char*)sqlite3_column_name(p->pCheck,jj+1); in intckSaveKey()
15418 if( p->rc==SQLITE_OK ){ in intckSaveKey()
15419 for(ii=0; ii<p->nKeyVal; ii++){ in intckSaveKey()
15420 sqlite3_bind_value(pStmt, ii+1, sqlite3_column_value(p->pCheck, ii+1)); in intckSaveKey()
15423 p->zKey = intckMprintf(p,"%s",(const char*)sqlite3_column_text(pStmt, 0)); in intckSaveKey()
15434 ** set sqlite3_intck.zObj to point to a nul-terminated buffer containing
15439 char *zPrev = p->zObj; in intckFindObject()
15440 p->zObj = 0; in intckFindObject()
15442 assert( p->rc==SQLITE_OK ); in intckFindObject()
15443 assert( p->pCheck==0 ); in intckFindObject()
15455 , p->zDb, (p->zKey ? ">=" : ">") in intckFindObject()
15458 if( p->rc==SQLITE_OK ){ in intckFindObject()
15459 sqlite3_bind_text(pStmt, 1, zPrev, -1, SQLITE_TRANSIENT); in intckFindObject()
15461 p->zObj = intckMprintf(p,"%s",(const char*)sqlite3_column_text(pStmt, 0)); in intckFindObject()
15467 if( sqlite3_stricmp(p->zObj, zPrev) ){ in intckFindObject()
15468 sqlite3_free(p->zKey); in intckFindObject()
15469 p->zKey = 0; in intckFindObject()
15476 ** Return the size in bytes of the first token in nul-terminated buffer z.
15521 ** fragment does not include any trailing sort-order keywords - "ASC" or
15545 assert( z[iOff]=='(' ); in intckParseCreateIndex()
15554 /* Check if this is the end of the current column - either a "," or ")" in intckParseCreateIndex()
15560 nRet = (iEnd - iStart); in intckParseCreateIndex()
15571 if( z[iOff]==')' ) nOpen--; in intckParseCreateIndex()
15599 nRet--; in intckParseCreateIndex()
15602 while( nRet>0 && intckIsSpace(zRet[nRet-1]) ) nRet--; in intckParseCreateIndex()
15610 ** User-defined SQL function wrapper for intckParseCreateIndex():
15624 assert( nVal==2 ); in intckParseCreateIndexFunc()
15654 p->zDb, zObj in intckIsIndex()
15656 if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ in intckIsIndex()
15664 ** Return a pointer to a nul-terminated buffer containing the SQL statement
15667 ** vector key required to restart the check where it left off last time.
15677 int *pnKeyVal /* OUT: Number of key-values for this scan */ in intckCheckObjectSql()
15756 " (SELECT sql FROM sqlite_schema WHERE name=idx_name), -1" in intckCheckObjectSql()
15847 , p->zDb, p->zDb, zObj, zObj in intckCheckObjectSql()
15896 /* This table contains a single row consisting of a single value - in intckCheckObjectSql()
15927 p->zDb, zObj, zPrev, zCommon in intckCheckObjectSql()
15931 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ in intckCheckObjectSql()
15944 ** Open a new integrity-check object.
15949 sqlite3_intck **ppOut /* OUT: New integrity-check handle */ in sqlite3_intck_open()
15961 pNew->db = db; in sqlite3_intck_open()
15962 pNew->zDb = (const char*)&pNew[1]; in sqlite3_intck_open()
15978 ** Free the integrity-check object.
15982 sqlite3_finalize(p->pCheck); in sqlite3_intck_close()
15984 p->db, "parse_create_index", 1, SQLITE_UTF8, 0, 0, 0, 0 in sqlite3_intck_close()
15986 sqlite3_free(p->zObj); in sqlite3_intck_close()
15987 sqlite3_free(p->zKey); in sqlite3_intck_close()
15988 sqlite3_free(p->zTestSql); in sqlite3_intck_close()
15989 sqlite3_free(p->zErr); in sqlite3_intck_close()
15990 sqlite3_free(p->zMessage); in sqlite3_intck_close()
15996 ** Step the integrity-check object.
15999 if( p->rc==SQLITE_OK ){ in sqlite3_intck_step()
16001 if( p->zMessage ){ in sqlite3_intck_step()
16002 sqlite3_free(p->zMessage); in sqlite3_intck_step()
16003 p->zMessage = 0; in sqlite3_intck_step()
16006 if( p->bCorruptSchema ){ in sqlite3_intck_step()
16007 p->rc = SQLITE_DONE; in sqlite3_intck_step()
16009 if( p->pCheck==0 ){ in sqlite3_intck_step()
16011 if( p->rc==SQLITE_OK ){ in sqlite3_intck_step()
16012 if( p->zObj ){ in sqlite3_intck_step()
16014 zSql = intckCheckObjectSql(p, p->zObj, p->zKey, &p->nKeyVal); in sqlite3_intck_step()
16015 p->pCheck = intckPrepare(p, zSql); in sqlite3_intck_step()
16017 sqlite3_free(p->zKey); in sqlite3_intck_step()
16018 p->zKey = 0; in sqlite3_intck_step()
16020 p->rc = SQLITE_DONE; in sqlite3_intck_step()
16022 }else if( p->rc==SQLITE_CORRUPT ){ in sqlite3_intck_step()
16023 p->rc = SQLITE_OK; in sqlite3_intck_step()
16024 p->zMessage = intckMprintf(p, "%s", in sqlite3_intck_step()
16027 p->bCorruptSchema = 1; in sqlite3_intck_step()
16031 if( p->pCheck ){ in sqlite3_intck_step()
16032 assert( p->rc==SQLITE_OK ); in sqlite3_intck_step()
16033 if( sqlite3_step(p->pCheck)==SQLITE_ROW ){ in sqlite3_intck_step()
16036 intckFinalize(p, p->pCheck); in sqlite3_intck_step()
16037 p->pCheck = 0; in sqlite3_intck_step()
16038 p->nKeyVal = 0; in sqlite3_intck_step()
16039 if( p->rc==SQLITE_CORRUPT ){ in sqlite3_intck_step()
16040 p->rc = SQLITE_OK; in sqlite3_intck_step()
16041 p->zMessage = intckMprintf(p, in sqlite3_intck_step()
16042 "corruption found while scanning database object %s", p->zObj in sqlite3_intck_step()
16049 return p->rc; in sqlite3_intck_step()
16057 assert( p->pCheck==0 || p->zMessage==0 ); in sqlite3_intck_message()
16058 if( p->zMessage ){ in sqlite3_intck_message()
16059 return p->zMessage; in sqlite3_intck_message()
16061 if( p->pCheck ){ in sqlite3_intck_message()
16062 return (const char*)sqlite3_column_text(p->pCheck, 0); in sqlite3_intck_message()
16071 if( pzErr ) *pzErr = p->zErr; in sqlite3_intck_error()
16072 return (p->rc==SQLITE_DONE ? SQLITE_OK : p->rc); in sqlite3_intck_error()
16076 ** Close any read transaction the integrity-check object is holding open
16080 if( p->rc==SQLITE_OK && p->pCheck ){ in sqlite3_intck_unlock()
16081 assert( p->zKey==0 && p->nKeyVal>0 ); in sqlite3_intck_unlock()
16083 intckFinalize(p, p->pCheck); in sqlite3_intck_unlock()
16084 p->pCheck = 0; in sqlite3_intck_unlock()
16086 return p->rc; in sqlite3_intck_unlock()
16094 sqlite3_free(p->zTestSql); in sqlite3_intck_test_sql()
16096 p->zTestSql = intckCheckObjectSql(p, zObj, 0, 0); in sqlite3_intck_test_sql()
16098 if( p->zObj ){ in sqlite3_intck_test_sql()
16099 p->zTestSql = intckCheckObjectSql(p, p->zObj, p->zKey, 0); in sqlite3_intck_test_sql()
16101 sqlite3_free(p->zTestSql); in sqlite3_intck_test_sql()
16102 p->zTestSql = 0; in sqlite3_intck_test_sql()
16105 return p->zTestSql; in sqlite3_intck_test_sql()
16111 ** 2024-05-24
16122 ** An SQL function that return pseudo-random non-negative integers.
16138 #include <assert.h>
16141 /* State of the pseudo-random number generator */
16147 #define STMTRAND_KEY (-4418371)
16152 ** Return a pseudo-random number.
16174 p->x = seed | 1; in stmtrandFunc()
16175 p->y = seed; in stmtrandFunc()
16183 p->x = (p->x>>1) ^ ((1+~(p->x&1)) & 0xd0000001); in stmtrandFunc()
16184 p->y = p->y*1103515245 + 12345; in stmtrandFunc()
16185 sqlite3_result_int(context, (int)((p->x ^ p->y)&0x7fffffff)); in stmtrandFunc()
16245 ** for the command-line shell (see shell.c) is "fputs" from the standard
16247 ** specified by the second argument. In the case of the command-line shell
16255 ** the actual work. In this case the other VFS - the one that does the
16256 ** real work - is identified by the second parameter, zOldVfsName. If
16262 ** command-line shell, when the -vfstrace option is used, these parameters
16265 ** The fifth argument is true (non-zero) to cause the newly created VFS
16278 ** ENABLING VFSTRACE IN A COMMAND-LINE SHELL
16281 ** can be used with this module. To compile in -vfstrace support, first
16286 ** gcc -o sqlite3 -Os -I. -DSQLITE_ENABLE_VFSTRACE \
16287 ** -DSQLITE_THREADSAFE=0 -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_RTREE \
16288 ** -DHAVE_READLINE -DHAVE_USLEEP=1 \
16289 ** shell.c test_vfstrace.c sqlite3.c -ldl -lreadline -lncurses
16292 ** -vfstrace option) support for FTS3 and FTS4, RTREE, and command-line
16293 ** editing using the readline library. The command-line shell does not
16294 ** use threads so we added -DSQLITE_THREADSAFE=0 just to make the code
16296 ** to omit the -DHAVE_READLINE, the -lreadline, and the -lncurses options.
16299 ** gcc -DSQLITE_ENABLE_VFSTRACE \
16300 ** shell.c test_vfstrace.c sqlite3.c -ldl -lpthread
16303 ** Note that since the code is now threadsafe, we had to add the -lpthread
16306 ** To cross-compile for windows using MinGW, a command like this might
16309 ** /opt/mingw/bin/i386-mingw32msvc-gcc -o sqlite3.exe -Os -I \
16310 ** -DSQLITE_THREADSAFE=0 -DSQLITE_ENABLE_VFSTRACE \
16314 ** invariants are (1) you must have -DSQLITE_ENABLE_VFSTRACE so that
16315 ** the shell.c source file will know to include the -vfstrace command-line
16324 ** PRAGMA vfstrace('-all');
16334 ** PRAGMA vfstrace('-all, +Lock,Unlock,ShmLock');
16337 ** characters other than alphabetics, '+', and '-'.
16354 const char *zVfsName; /* Name of this trace-VFS */
16364 vfstrace_info *pInfo; /* The trace-VFS to which this file belongs */
16445 ** /home/drh/xyzzy.txt -> xyzzy.txt
16446 ** xyzzy.txt -> xyzzy.txt
16451 i = strlen(z)-1; in fileTail()
16452 while( i>0 && z[i-1]!='/' ){ i--; } in fileTail()
16466 if( pInfo->bOn ){ in vfstrace_printf()
16470 pInfo->xOut(zMsg, pInfo->pOutArg); in vfstrace_printf()
16575 pInfo->bOn = (pInfo->mTrace & mMask)!=0; in vfstraceOnOff()
16579 ** Close an vfstrace-file.
16583 vfstrace_info *pInfo = p->pInfo; in vfstraceClose()
16586 vfstrace_printf(pInfo, "%s.xClose(%s)", pInfo->zVfsName, p->zFName); in vfstraceClose()
16587 rc = p->pReal->pMethods->xClose(p->pReal); in vfstraceClose()
16588 vfstrace_print_errcode(pInfo, " -> %s\n", rc); in vfstraceClose()
16590 sqlite3_free((void*)p->base.pMethods); in vfstraceClose()
16591 p->base.pMethods = 0; in vfstraceClose()
16597 ** Read data from an vfstrace-file.
16606 vfstrace_info *pInfo = p->pInfo; in vfstraceRead()
16610 pInfo->zVfsName, p->zFName, iAmt, iOfst); in vfstraceRead()
16611 rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst); in vfstraceRead()
16612 vfstrace_print_errcode(pInfo, " -> %s\n", rc); in vfstraceRead()
16617 ** Write data to an vfstrace-file.
16626 vfstrace_info *pInfo = p->pInfo; in vfstraceWrite()
16630 pInfo->zVfsName, p->zFName, iAmt, iOfst); in vfstraceWrite()
16631 rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst); in vfstraceWrite()
16632 vfstrace_print_errcode(pInfo, " -> %s\n", rc); in vfstraceWrite()
16637 ** Truncate an vfstrace-file.
16641 vfstrace_info *pInfo = p->pInfo; in vfstraceTruncate()
16644 vfstrace_printf(pInfo, "%s.xTruncate(%s,%lld)", pInfo->zVfsName, p->zFName, in vfstraceTruncate()
16646 rc = p->pReal->pMethods->xTruncate(p->pReal, size); in vfstraceTruncate()
16647 vfstrace_printf(pInfo, " -> %d\n", rc); in vfstraceTruncate()
16652 ** Sync an vfstrace-file.
16656 vfstrace_info *pInfo = p->pInfo; in vfstraceSync()
16666 sqlite3_snprintf(sizeof(zBuf)-i, &zBuf[i], "|0x%x", flags); in vfstraceSync()
16669 vfstrace_printf(pInfo, "%s.xSync(%s,%s)", pInfo->zVfsName, p->zFName, in vfstraceSync()
16671 rc = p->pReal->pMethods->xSync(p->pReal, flags); in vfstraceSync()
16672 vfstrace_printf(pInfo, " -> %d\n", rc); in vfstraceSync()
16677 ** Return the current file-size of an vfstrace-file.
16681 vfstrace_info *pInfo = p->pInfo; in vfstraceFileSize()
16684 vfstrace_printf(pInfo, "%s.xFileSize(%s)", pInfo->zVfsName, p->zFName); in vfstraceFileSize()
16685 rc = p->pReal->pMethods->xFileSize(p->pReal, pSize); in vfstraceFileSize()
16686 vfstrace_print_errcode(pInfo, " -> %s,", rc); in vfstraceFileSize()
16706 ** Lock an vfstrace-file.
16710 vfstrace_info *pInfo = p->pInfo; in vfstraceLock()
16713 vfstrace_printf(pInfo, "%s.xLock(%s,%s)", pInfo->zVfsName, p->zFName, in vfstraceLock()
16715 rc = p->pReal->pMethods->xLock(p->pReal, eLock); in vfstraceLock()
16716 vfstrace_print_errcode(pInfo, " -> %s\n", rc); in vfstraceLock()
16721 ** Unlock an vfstrace-file.
16725 vfstrace_info *pInfo = p->pInfo; in vfstraceUnlock()
16728 vfstrace_printf(pInfo, "%s.xUnlock(%s,%s)", pInfo->zVfsName, p->zFName, in vfstraceUnlock()
16730 rc = p->pReal->pMethods->xUnlock(p->pReal, eLock); in vfstraceUnlock()
16731 vfstrace_print_errcode(pInfo, " -> %s\n", rc); in vfstraceUnlock()
16736 ** Check if another file-handle holds a RESERVED lock on an vfstrace-file.
16740 vfstrace_info *pInfo = p->pInfo; in vfstraceCheckReservedLock()
16744 pInfo->zVfsName, p->zFName); in vfstraceCheckReservedLock()
16745 rc = p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut); in vfstraceCheckReservedLock()
16746 vfstrace_print_errcode(pInfo, " -> %s", rc); in vfstraceCheckReservedLock()
16752 ** File control method. For custom operations on an vfstrace-file.
16756 vfstrace_info *pInfo = p->pInfo; in vfstraceFileControl()
16794 pInfo->mTrace = (sqlite3_uint64)strtoll(a[2], 0, 0); in vfstraceFileControl()
16835 while( zArg[0]!=0 && zArg[0]!='-' && zArg[0]!='+' in vfstraceFileControl()
16838 if( zArg[0]=='-' ){ in vfstraceFileControl()
16854 pInfo->mTrace |= aKw[jj].m; in vfstraceFileControl()
16856 pInfo->mTrace &= ~aKw[jj].m; in vfstraceFileControl()
16916 pInfo->zVfsName, p->zFName, zOp); in vfstraceFileControl()
16917 rc = p->pReal->pMethods->xFileControl(p->pReal, op, pArg); in vfstraceFileControl()
16922 pInfo->zVfsName, *(char**)pArg); in vfstraceFileControl()
16945 vfstrace_print_errcode(pInfo, " -> %s", rc); in vfstraceFileControl()
16948 vfstrace_print_errcode(pInfo, " -> %s\n", rc); in vfstraceFileControl()
16954 ** Return the sector-size in bytes for an vfstrace-file.
16958 vfstrace_info *pInfo = p->pInfo; in vfstraceSectorSize()
16961 vfstrace_printf(pInfo, "%s.xSectorSize(%s)", pInfo->zVfsName, p->zFName); in vfstraceSectorSize()
16962 rc = p->pReal->pMethods->xSectorSize(p->pReal); in vfstraceSectorSize()
16963 vfstrace_printf(pInfo, " -> %d\n", rc); in vfstraceSectorSize()
16968 ** Return the device characteristic flags supported by an vfstrace-file.
16972 vfstrace_info *pInfo = p->pInfo; in vfstraceDeviceCharacteristics()
16976 pInfo->zVfsName, p->zFName); in vfstraceDeviceCharacteristics()
16977 rc = p->pReal->pMethods->xDeviceCharacteristics(p->pReal); in vfstraceDeviceCharacteristics()
16978 vfstrace_printf(pInfo, " -> 0x%08x\n", rc); in vfstraceDeviceCharacteristics()
16983 ** Shared-memory operations.
16997 vfstrace_info *pInfo = p->pInfo; in vfstraceShmLock()
17008 sqlite3_snprintf(sizeof(zLck)-i, &zLck[i], "|0x%x", flags); in vfstraceShmLock()
17012 pInfo->zVfsName, p->zFName, ofst, azLockName[ofst], in vfstraceShmLock()
17016 pInfo->zVfsName, p->zFName, ofst, in vfstraceShmLock()
17019 rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags); in vfstraceShmLock()
17020 vfstrace_print_errcode(pInfo, " -> %s\n", rc); in vfstraceShmLock()
17031 vfstrace_info *pInfo = p->pInfo; in vfstraceShmMap()
17035 pInfo->zVfsName, p->zFName, iRegion, szRegion, isWrite); in vfstraceShmMap()
17036 rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp); in vfstraceShmMap()
17037 vfstrace_print_errcode(pInfo, " -> %s\n", rc); in vfstraceShmMap()
17042 vfstrace_info *pInfo = p->pInfo; in vfstraceShmBarrier()
17044 vfstrace_printf(pInfo, "%s.xShmBarrier(%s)\n", pInfo->zVfsName, p->zFName); in vfstraceShmBarrier()
17045 p->pReal->pMethods->xShmBarrier(p->pReal); in vfstraceShmBarrier()
17049 vfstrace_info *pInfo = p->pInfo; in vfstraceShmUnmap()
17053 pInfo->zVfsName, p->zFName, delFlag); in vfstraceShmUnmap()
17054 rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag); in vfstraceShmUnmap()
17055 vfstrace_print_errcode(pInfo, " -> %s\n", rc); in vfstraceShmUnmap()
17060 vfstrace_info *pInfo = p->pInfo; in vfstraceFetch()
17064 pInfo->zVfsName, p->zFName, iOff, nAmt, *pptr); in vfstraceFetch()
17065 rc = p->pReal->pMethods->xFetch(p->pReal, iOff, nAmt, pptr); in vfstraceFetch()
17066 vfstrace_print_errcode(pInfo, " -> %s\n", rc); in vfstraceFetch()
17071 vfstrace_info *pInfo = p->pInfo; in vfstraceUnfetch()
17075 pInfo->zVfsName, p->zFName, iOff, ptr); in vfstraceUnfetch()
17076 rc = p->pReal->pMethods->xUnfetch(p->pReal, iOff, ptr); in vfstraceUnfetch()
17077 vfstrace_print_errcode(pInfo, " -> %s\n", rc); in vfstraceUnfetch()
17094 vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; in vfstraceOpen()
17095 sqlite3_vfs *pRoot = pInfo->pRootVfs; in vfstraceOpen()
17096 p->pInfo = pInfo; in vfstraceOpen()
17097 p->zFName = zName ? fileTail(zName) : "<temp>"; in vfstraceOpen()
17098 p->pReal = (sqlite3_file *)&p[1]; in vfstraceOpen()
17099 rc = pRoot->xOpen(pRoot, zName, p->pReal, flags, pOutFlags); in vfstraceOpen()
17102 pInfo->zVfsName, p->zFName, flags); in vfstraceOpen()
17103 if( p->pReal->pMethods ){ in vfstraceOpen()
17105 const sqlite3_io_methods *pSub = p->pReal->pMethods; in vfstraceOpen()
17107 pNew->iVersion = pSub->iVersion; in vfstraceOpen()
17108 pNew->xClose = vfstraceClose; in vfstraceOpen()
17109 pNew->xRead = vfstraceRead; in vfstraceOpen()
17110 pNew->xWrite = vfstraceWrite; in vfstraceOpen()
17111 pNew->xTruncate = vfstraceTruncate; in vfstraceOpen()
17112 pNew->xSync = vfstraceSync; in vfstraceOpen()
17113 pNew->xFileSize = vfstraceFileSize; in vfstraceOpen()
17114 pNew->xLock = vfstraceLock; in vfstraceOpen()
17115 pNew->xUnlock = vfstraceUnlock; in vfstraceOpen()
17116 pNew->xCheckReservedLock = vfstraceCheckReservedLock; in vfstraceOpen()
17117 pNew->xFileControl = vfstraceFileControl; in vfstraceOpen()
17118 pNew->xSectorSize = vfstraceSectorSize; in vfstraceOpen()
17119 pNew->xDeviceCharacteristics = vfstraceDeviceCharacteristics; in vfstraceOpen()
17120 if( pNew->iVersion>=2 ){ in vfstraceOpen()
17121 pNew->xShmMap = pSub->xShmMap ? vfstraceShmMap : 0; in vfstraceOpen()
17122 pNew->xShmLock = pSub->xShmLock ? vfstraceShmLock : 0; in vfstraceOpen()
17123 pNew->xShmBarrier = pSub->xShmBarrier ? vfstraceShmBarrier : 0; in vfstraceOpen()
17124 pNew->xShmUnmap = pSub->xShmUnmap ? vfstraceShmUnmap : 0; in vfstraceOpen()
17126 if( pNew->iVersion>=3 ){ in vfstraceOpen()
17127 pNew->xFetch = pSub->xFetch ? vfstraceFetch : 0; in vfstraceOpen()
17128 pNew->xUnfetch = pSub->xUnfetch ? vfstraceUnfetch : 0; in vfstraceOpen()
17130 pFile->pMethods = pNew; in vfstraceOpen()
17132 vfstrace_print_errcode(pInfo, " -> %s", rc); in vfstraceOpen()
17143 ** ensure the file-system modifications are synced to disk before
17147 vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; in vfstraceDelete()
17148 sqlite3_vfs *pRoot = pInfo->pRootVfs; in vfstraceDelete()
17152 pInfo->zVfsName, zPath, dirSync); in vfstraceDelete()
17153 rc = pRoot->xDelete(pRoot, zPath, dirSync); in vfstraceDelete()
17154 vfstrace_print_errcode(pInfo, " -> %s\n", rc); in vfstraceDelete()
17168 vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; in vfstraceAccess()
17169 sqlite3_vfs *pRoot = pInfo->pRootVfs; in vfstraceAccess()
17173 pInfo->zVfsName, zPath, flags); in vfstraceAccess()
17174 rc = pRoot->xAccess(pRoot, zPath, flags, pResOut); in vfstraceAccess()
17175 vfstrace_print_errcode(pInfo, " -> %s", rc); in vfstraceAccess()
17191 vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; in vfstraceFullPathname()
17192 sqlite3_vfs *pRoot = pInfo->pRootVfs; in vfstraceFullPathname()
17196 pInfo->zVfsName, zPath); in vfstraceFullPathname()
17197 rc = pRoot->xFullPathname(pRoot, zPath, nOut, zOut); in vfstraceFullPathname()
17198 vfstrace_print_errcode(pInfo, " -> %s", rc); in vfstraceFullPathname()
17207 vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; in vfstraceDlOpen()
17208 sqlite3_vfs *pRoot = pInfo->pRootVfs; in vfstraceDlOpen()
17210 vfstrace_printf(pInfo, "%s.xDlOpen(\"%s\")\n", pInfo->zVfsName, zPath); in vfstraceDlOpen()
17211 return pRoot->xDlOpen(pRoot, zPath); in vfstraceDlOpen()
17216 ** utf-8 string describing the most recent error encountered associated
17220 vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; in vfstraceDlError()
17221 sqlite3_vfs *pRoot = pInfo->pRootVfs; in vfstraceDlError()
17223 vfstrace_printf(pInfo, "%s.xDlError(%d)", pInfo->zVfsName, nByte); in vfstraceDlError()
17224 pRoot->xDlError(pRoot, nByte, zErrMsg); in vfstraceDlError()
17225 vfstrace_printf(pInfo, " -> \"%s\"", zErrMsg); in vfstraceDlError()
17232 vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; in vfstraceDlSym()
17233 sqlite3_vfs *pRoot = pInfo->pRootVfs; in vfstraceDlSym()
17234 vfstrace_printf(pInfo, "%s.xDlSym(\"%s\")\n", pInfo->zVfsName, zSym); in vfstraceDlSym()
17235 return pRoot->xDlSym(pRoot, p, zSym); in vfstraceDlSym()
17242 vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; in vfstraceDlClose()
17243 sqlite3_vfs *pRoot = pInfo->pRootVfs; in vfstraceDlClose()
17245 vfstrace_printf(pInfo, "%s.xDlClose()\n", pInfo->zVfsName); in vfstraceDlClose()
17246 pRoot->xDlClose(pRoot, pHandle); in vfstraceDlClose()
17254 vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; in vfstraceRandomness()
17255 sqlite3_vfs *pRoot = pInfo->pRootVfs; in vfstraceRandomness()
17257 vfstrace_printf(pInfo, "%s.xRandomness(%d)\n", pInfo->zVfsName, nByte); in vfstraceRandomness()
17258 return pRoot->xRandomness(pRoot, nByte, zBufOut); in vfstraceRandomness()
17266 vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; in vfstraceSleep()
17267 sqlite3_vfs *pRoot = pInfo->pRootVfs; in vfstraceSleep()
17269 vfstrace_printf(pInfo, "%s.xSleep(%d)\n", pInfo->zVfsName, nMicro); in vfstraceSleep()
17270 return pRoot->xSleep(pRoot, nMicro); in vfstraceSleep()
17274 ** Return the current time as a Julian Day number in *pTimeOut.
17277 vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; in vfstraceCurrentTime()
17278 sqlite3_vfs *pRoot = pInfo->pRootVfs; in vfstraceCurrentTime()
17281 vfstrace_printf(pInfo, "%s.xCurrentTime()", pInfo->zVfsName); in vfstraceCurrentTime()
17282 rc = pRoot->xCurrentTime(pRoot, pTimeOut); in vfstraceCurrentTime()
17283 vfstrace_printf(pInfo, " -> %.17g\n", *pTimeOut); in vfstraceCurrentTime()
17287 vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; in vfstraceCurrentTimeInt64()
17288 sqlite3_vfs *pRoot = pInfo->pRootVfs; in vfstraceCurrentTimeInt64()
17291 vfstrace_printf(pInfo, "%s.xCurrentTimeInt64()", pInfo->zVfsName); in vfstraceCurrentTimeInt64()
17292 rc = pRoot->xCurrentTimeInt64(pRoot, pTimeOut); in vfstraceCurrentTimeInt64()
17293 vfstrace_printf(pInfo, " -> %lld\n", *pTimeOut); in vfstraceCurrentTimeInt64()
17301 vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; in vfstraceGetLastError()
17302 sqlite3_vfs *pRoot = pInfo->pRootVfs; in vfstraceGetLastError()
17305 vfstrace_printf(pInfo, "%s.xGetLastError(%d,zBuf)", pInfo->zVfsName, nErr); in vfstraceGetLastError()
17307 rc = pRoot->xGetLastError(pRoot, nErr, zErr); in vfstraceGetLastError()
17308 vfstrace_printf(pInfo, " -> zBuf[] = \"%s\", rc = %d\n", nErr?zErr:"", rc); in vfstraceGetLastError()
17320 vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; in vfstraceSetSystemCall()
17321 sqlite3_vfs *pRoot = pInfo->pRootVfs; in vfstraceSetSystemCall()
17322 return pRoot->xSetSystemCall(pRoot, zName, pFunc); in vfstraceSetSystemCall()
17328 vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; in vfstraceGetSystemCall()
17329 sqlite3_vfs *pRoot = pInfo->pRootVfs; in vfstraceGetSystemCall()
17330 return pRoot->xGetSystemCall(pRoot, zName); in vfstraceGetSystemCall()
17333 vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; in vfstraceNextSystemCall()
17334 sqlite3_vfs *pRoot = pInfo->pRootVfs; in vfstraceNextSystemCall()
17335 return pRoot->xNextSystemCall(pRoot, zName); in vfstraceNextSystemCall()
17340 ** Clients invoke this routine to construct a new trace-vfs shim.
17368 pNew->iVersion = pRoot->iVersion; in vfstrace_register()
17369 pNew->szOsFile = pRoot->szOsFile + sizeof(vfstrace_file); in vfstrace_register()
17370 pNew->mxPathname = pRoot->mxPathname; in vfstrace_register()
17371 pNew->zName = (char*)&pInfo[1]; in vfstrace_register()
17373 pNew->pAppData = pInfo; in vfstrace_register()
17374 pNew->xOpen = vfstraceOpen; in vfstrace_register()
17375 pNew->xDelete = vfstraceDelete; in vfstrace_register()
17376 pNew->xAccess = vfstraceAccess; in vfstrace_register()
17377 pNew->xFullPathname = vfstraceFullPathname; in vfstrace_register()
17378 pNew->xDlOpen = pRoot->xDlOpen==0 ? 0 : vfstraceDlOpen; in vfstrace_register()
17379 pNew->xDlError = pRoot->xDlError==0 ? 0 : vfstraceDlError; in vfstrace_register()
17380 pNew->xDlSym = pRoot->xDlSym==0 ? 0 : vfstraceDlSym; in vfstrace_register()
17381 pNew->xDlClose = pRoot->xDlClose==0 ? 0 : vfstraceDlClose; in vfstrace_register()
17382 pNew->xRandomness = vfstraceRandomness; in vfstrace_register()
17383 pNew->xSleep = vfstraceSleep; in vfstrace_register()
17384 pNew->xCurrentTime = vfstraceCurrentTime; in vfstrace_register()
17385 pNew->xGetLastError = pRoot->xGetLastError==0 ? 0 : vfstraceGetLastError; in vfstrace_register()
17386 if( pNew->iVersion>=2 ){ in vfstrace_register()
17387 pNew->xCurrentTimeInt64 = pRoot->xCurrentTimeInt64==0 ? 0 : in vfstrace_register()
17389 if( pNew->iVersion>=3 ){ in vfstrace_register()
17390 pNew->xSetSystemCall = pRoot->xSetSystemCall==0 ? 0 : in vfstrace_register()
17392 pNew->xGetSystemCall = pRoot->xGetSystemCall==0 ? 0 : in vfstrace_register()
17394 pNew->xNextSystemCall = pRoot->xNextSystemCall==0 ? 0 : in vfstrace_register()
17398 pInfo->pRootVfs = pRoot; in vfstrace_register()
17399 pInfo->xOut = xOut; in vfstrace_register()
17400 pInfo->pOutArg = pOutArg; in vfstrace_register()
17401 pInfo->zVfsName = pNew->zName; in vfstrace_register()
17402 pInfo->pTraceVfs = pNew; in vfstrace_register()
17403 pInfo->mTrace = 0xffffffff; in vfstrace_register()
17404 pInfo->bOn = 1; in vfstrace_register()
17406 pInfo->zVfsName, pRoot->zName); in vfstrace_register()
17417 if( pVfs->xOpen!=vfstraceOpen ) return; in vfstrace_unregister()
17432 ** 2022-08-27
17443 ** This file contains the public interface to the "recover" extension -
17463 ** error. If it returns some other non-SQLITE_OK value, then an error
17532 ** nul-terminated buffer containing the SQL statement formated as UTF-8 as
17537 ** If an out-of-memory error occurs, NULL may be returned instead of
17572 ** of a "lost-and-found" table in the output database, or NULL. If
17573 ** the argument is non-NULL and the database contains seemingly
17576 ** pages to add to the lost-and-found table.
17581 ** (argument is 1) and a lost-and-found table has been configured using
17601 ** module creates and populates non-UNIQUE indexes right at the end of the
17602 ** recovery operation - after all recoverable data has been inserted
17607 ** Or, if this option is set (argument is 1), then non-UNIQUE indexes
17631 ** all further such calls on the same recover handle are no-ops that return
17632 ** the same non-SQLITE_OK value.
17650 ** the error. If no error message is available, or if an out-of memory
17685 ** 2019-04-17
17701 ** sqlite_dbdata is used to extract data directly from a database b-tree
17702 ** page and its associated overflow pages, bypassing the b-tree layer.
17714 ** FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
17718 ** a b-tree page, or if it is a b-tree page containing 0 entries, the
17721 ** each cell on the page. For intkey b-trees, the key value is stored in
17722 ** field -1.
17726 ** CREATE TABLE t1(a, b); -- root page is page 2
17734 ** (2, 0, -1, 5 ),
17737 ** (2, 1, -1, 10 ),
17754 ** It contains one entry for each b-tree pointer between a parent and
17766 #include <assert.h>
17850 if( nMin>pBuf->nBuf ){ in dbdataBufferSize()
17852 u8 *aNew = (u8*)sqlite3_realloc64(pBuf->aBuf, nNew); in dbdataBufferSize()
17855 pBuf->aBuf = aNew; in dbdataBufferSize()
17856 pBuf->nBuf = nNew; in dbdataBufferSize()
17865 sqlite3_free(pBuf->aBuf); in dbdataBufferFree()
17893 pTab->db = db; in dbdataConnect()
17894 pTab->bPtr = (pAux!=0); in dbdataConnect()
17908 sqlite3_finalize(pTab->pStmt); in dbdataDisconnect()
17930 int iSchema = -1; in dbdataBestIndex()
17931 int iPgno = -1; in dbdataBestIndex()
17932 int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA); in dbdataBestIndex()
17934 for(i=0; i<pIdx->nConstraint; i++){ in dbdataBestIndex()
17935 struct sqlite3_index_constraint *p = &pIdx->aConstraint[i]; in dbdataBestIndex()
17936 if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ in dbdataBestIndex()
17937 if( p->iColumn==colSchema ){ in dbdataBestIndex()
17938 if( p->usable==0 ) return SQLITE_CONSTRAINT; in dbdataBestIndex()
17941 if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){ in dbdataBestIndex()
17948 pIdx->aConstraintUsage[iSchema].argvIndex = 1; in dbdataBestIndex()
17949 pIdx->aConstraintUsage[iSchema].omit = 1; in dbdataBestIndex()
17952 pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0); in dbdataBestIndex()
17953 pIdx->aConstraintUsage[iPgno].omit = 1; in dbdataBestIndex()
17954 pIdx->estimatedCost = 100; in dbdataBestIndex()
17955 pIdx->estimatedRows = 50; in dbdataBestIndex()
17957 if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){ in dbdataBestIndex()
17958 int iCol = pIdx->aOrderBy[0].iColumn; in dbdataBestIndex()
17959 if( pIdx->nOrderBy==1 ){ in dbdataBestIndex()
17960 pIdx->orderByConsumed = (iCol==0 || iCol==1); in dbdataBestIndex()
17961 }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){ in dbdataBestIndex()
17962 pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1); in dbdataBestIndex()
17967 pIdx->estimatedCost = 100000000; in dbdataBestIndex()
17968 pIdx->estimatedRows = 1000000000; in dbdataBestIndex()
17970 pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00); in dbdataBestIndex()
17985 pCsr->base.pVtab = pVTab; in dbdataOpen()
17997 DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab); in dbdataResetCursor()
17998 if( pTab->pStmt==0 ){ in dbdataResetCursor()
17999 pTab->pStmt = pCsr->pStmt; in dbdataResetCursor()
18001 sqlite3_finalize(pCsr->pStmt); in dbdataResetCursor()
18003 pCsr->pStmt = 0; in dbdataResetCursor()
18004 pCsr->iPgno = 1; in dbdataResetCursor()
18005 pCsr->iCell = 0; in dbdataResetCursor()
18006 pCsr->iField = 0; in dbdataResetCursor()
18007 pCsr->bOnePage = 0; in dbdataResetCursor()
18008 sqlite3_free(pCsr->aPage); in dbdataResetCursor()
18009 dbdataBufferFree(&pCsr->rec); in dbdataResetCursor()
18010 pCsr->aPage = 0; in dbdataResetCursor()
18011 pCsr->nRec = 0; in dbdataResetCursor()
18025 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
18055 sqlite3_stmt *pStmt = pCsr->pStmt; in dbdataLoadPage()
18136 return ((eType-12) / 2); in dbdataValueBytes()
18192 int n = ((eType-12) / 2); in dbdataValue()
18227 ** a page-size, it returns the maximum number of cells that may be present
18229 #define DBDATA_MX_CELL(pgsz) ((pgsz-8)/6)
18232 ** the "hard-limit", according to comments in sqliteLimit.h. */
18240 DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; in dbdataNext()
18242 pCsr->iRowid++; in dbdataNext()
18245 int iOff = (pCsr->iPgno==1 ? 100 : 0); in dbdataNext()
18248 if( pCsr->aPage==0 ){ in dbdataNext()
18250 if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK; in dbdataNext()
18251 rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage); in dbdataNext()
18253 if( pCsr->aPage && pCsr->nPage>=256 ) break; in dbdataNext()
18254 sqlite3_free(pCsr->aPage); in dbdataNext()
18255 pCsr->aPage = 0; in dbdataNext()
18256 if( pCsr->bOnePage ) return SQLITE_OK; in dbdataNext()
18257 pCsr->iPgno++; in dbdataNext()
18260 assert( iOff+3+2<=pCsr->nPage ); in dbdataNext()
18261 pCsr->iCell = pTab->bPtr ? -2 : 0; in dbdataNext()
18262 pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]); in dbdataNext()
18263 if( pCsr->nCell>DBDATA_MX_CELL(pCsr->nPage) ){ in dbdataNext()
18264 pCsr->nCell = DBDATA_MX_CELL(pCsr->nPage); in dbdataNext()
18268 if( pTab->bPtr ){ in dbdataNext()
18269 if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){ in dbdataNext()
18270 pCsr->iCell = pCsr->nCell; in dbdataNext()
18272 pCsr->iCell++; in dbdataNext()
18273 if( pCsr->iCell>=pCsr->nCell ){ in dbdataNext()
18274 sqlite3_free(pCsr->aPage); in dbdataNext()
18275 pCsr->aPage = 0; in dbdataNext()
18276 if( pCsr->bOnePage ) return SQLITE_OK; in dbdataNext()
18277 pCsr->iPgno++; in dbdataNext()
18283 assert( pCsr->rec.aBuf!=0 || pCsr->nRec==0 ); in dbdataNext()
18284 if( pCsr->nRec==0 ){ in dbdataNext()
18293 switch( pCsr->aPage[iOff] ){ in dbdataNext()
18303 /* This is not a b-tree page with records on it. Continue. */ in dbdataNext()
18304 pCsr->iCell = pCsr->nCell; in dbdataNext()
18308 if( pCsr->iCell>=pCsr->nCell ){ in dbdataNext()
18311 int iCellPtr = iOff + 8 + nPointer + pCsr->iCell*2; in dbdataNext()
18313 if( iCellPtr>pCsr->nPage ){ in dbdataNext()
18316 iOff = get_uint16(&pCsr->aPage[iCellPtr]); in dbdataNext()
18319 /* For an interior node cell, skip past the child-page number */ in dbdataNext()
18323 if( bNextPage || iOff>pCsr->nPage || iOff<=iCellPtr ){ in dbdataNext()
18326 iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload); in dbdataNext()
18332 if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){ in dbdataNext()
18333 iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey); in dbdataNext()
18337 U = pCsr->nPage; in dbdataNext()
18339 X = U-35; in dbdataNext()
18341 X = ((U-12)*64/255)-23; in dbdataNext()
18347 M = ((U-12)*32/255)-23; in dbdataNext()
18348 K = M+((nPayload-M)%(U-4)); in dbdataNext()
18356 if( bNextPage || nLocal+iOff>pCsr->nPage ){ in dbdataNext()
18363 rc = dbdataBufferSize(&pCsr->rec, nPayload+DBDATA_PADDING_BYTES); in dbdataNext()
18365 assert( pCsr->rec.aBuf!=0 ); in dbdataNext()
18366 assert( nPayload!=0 ); in dbdataNext()
18369 memcpy(pCsr->rec.aBuf, &pCsr->aPage[iOff], nLocal); in dbdataNext()
18374 sqlite3_int64 nRem = nPayload - nLocal; in dbdataNext()
18375 u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]); in dbdataNext()
18381 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage ); in dbdataNext()
18385 nCopy = U-4; in dbdataNext()
18387 memcpy(&pCsr->rec.aBuf[nPayload-nRem], &aOvfl[4], nCopy); in dbdataNext()
18388 nRem -= nCopy; in dbdataNext()
18393 nPayload -= nRem; in dbdataNext()
18395 memset(&pCsr->rec.aBuf[nPayload], 0, DBDATA_PADDING_BYTES); in dbdataNext()
18396 pCsr->nRec = nPayload; in dbdataNext()
18398 iHdr = dbdataGetVarintU32(pCsr->rec.aBuf, &nHdr); in dbdataNext()
18400 pCsr->nHdr = nHdr; in dbdataNext()
18401 pCsr->pHdrPtr = &pCsr->rec.aBuf[iHdr]; in dbdataNext()
18402 pCsr->pPtr = &pCsr->rec.aBuf[pCsr->nHdr]; in dbdataNext()
18403 pCsr->iField = (bHasRowid ? -1 : 0); in dbdataNext()
18407 pCsr->iField++; in dbdataNext()
18408 if( pCsr->iField>0 ){ in dbdataNext()
18410 if( pCsr->pHdrPtr>=&pCsr->rec.aBuf[pCsr->nRec] in dbdataNext()
18411 || pCsr->iField>=DBDATA_MX_FIELD in dbdataNext()
18416 pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType); in dbdataNext()
18418 if( (pCsr->nRec - (pCsr->pPtr - pCsr->rec.aBuf))<szField ){ in dbdataNext()
18419 pCsr->pPtr = &pCsr->rec.aBuf[pCsr->nRec]; in dbdataNext()
18421 pCsr->pPtr += szField; in dbdataNext()
18428 sqlite3_free(pCsr->aPage); in dbdataNext()
18429 pCsr->aPage = 0; in dbdataNext()
18430 pCsr->nRec = 0; in dbdataNext()
18431 if( pCsr->bOnePage ) return SQLITE_OK; in dbdataNext()
18432 pCsr->iPgno++; in dbdataNext()
18434 if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->rec.aBuf[pCsr->nHdr] ){ in dbdataNext()
18440 pCsr->nRec = 0; in dbdataNext()
18441 pCsr->iCell++; in dbdataNext()
18446 assert( !"can't get here" ); in dbdataNext()
18455 return pCsr->aPage==0; in dbdataEof()
18459 ** Return true if nul-terminated string zSchema ends in "()". Or false
18464 if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){ in dbdataIsFunction()
18465 return (int)n-2; in dbdataIsFunction()
18473 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
18477 DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab; in dbdataDbsize()
18490 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0); in dbdataDbsize()
18493 pCsr->szDb = sqlite3_column_int(pStmt, 0); in dbdataDbsize()
18502 ** and inspecting the header field. If successful, set the pCsr->enc variable
18511 pCsr->enc = get_uint32(&aPg1[56]); in dbdataGetEncoding()
18527 DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; in dbdataFilter()
18534 assert( pCsr->iPgno==1 ); in dbdataFilter()
18540 pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]); in dbdataFilter()
18541 pCsr->bOnePage = 1; in dbdataFilter()
18548 if( pTab->pStmt ){ in dbdataFilter()
18549 pCsr->pStmt = pTab->pStmt; in dbdataFilter()
18550 pTab->pStmt = 0; in dbdataFilter()
18556 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0); in dbdataFilter()
18560 rc = sqlite3_prepare_v2(pTab->db, in dbdataFilter()
18561 "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1, in dbdataFilter()
18562 &pCsr->pStmt, 0 in dbdataFilter()
18567 rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT); in dbdataFilter()
18577 pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db)); in dbdataFilter()
18595 DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; in dbdataColumn()
18596 if( pTab->bPtr ){ in dbdataColumn()
18599 sqlite3_result_int64(ctx, pCsr->iPgno); in dbdataColumn()
18602 int iOff = pCsr->iPgno==1 ? 100 : 0; in dbdataColumn()
18603 if( pCsr->iCell<0 ){ in dbdataColumn()
18606 iOff += 12 + pCsr->iCell*2; in dbdataColumn()
18607 if( iOff>pCsr->nPage ) return SQLITE_OK; in dbdataColumn()
18608 iOff = get_uint16(&pCsr->aPage[iOff]); in dbdataColumn()
18610 if( iOff<=pCsr->nPage ){ in dbdataColumn()
18611 sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff])); in dbdataColumn()
18619 sqlite3_result_int64(ctx, pCsr->iPgno); in dbdataColumn()
18622 sqlite3_result_int(ctx, pCsr->iCell); in dbdataColumn()
18625 sqlite3_result_int(ctx, pCsr->iField); in dbdataColumn()
18628 if( pCsr->iField<0 ){ in dbdataColumn()
18629 sqlite3_result_int64(ctx, pCsr->iIntkey); in dbdataColumn()
18630 }else if( &pCsr->rec.aBuf[pCsr->nRec] >= pCsr->pPtr ){ in dbdataColumn()
18632 dbdataGetVarintU32(pCsr->pHdrPtr, &iType); in dbdataColumn()
18634 ctx, pCsr->enc, iType, pCsr->pPtr, in dbdataColumn()
18635 &pCsr->rec.aBuf[pCsr->nRec] - pCsr->pPtr in dbdataColumn()
18650 *pRowid = pCsr->iRowid; in dbdataRowid()
18666 dbdataOpen, /* xOpen - open a cursor */ in sqlite3DbdataRegister()
18667 dbdataClose, /* xClose - close a cursor */ in sqlite3DbdataRegister()
18668 dbdataFilter, /* xFilter - configure scan constraints */ in sqlite3DbdataRegister()
18669 dbdataNext, /* xNext - advance a cursor */ in sqlite3DbdataRegister()
18670 dbdataEof, /* xEof - check for end of scan */ in sqlite3DbdataRegister()
18671 dbdataColumn, /* xColumn - read data */ in sqlite3DbdataRegister()
18672 dbdataRowid, /* xRowid - read data */ in sqlite3DbdataRegister()
18711 ** 2022-08-27
18726 #include <assert.h>
18746 ** Work around C99 "flex-array" syntax for pre-C99 compilers, so as
18747 ** to avoid complaints from -fsanitize=strict-bounds.
18783 ** Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
18790 ** the output database, before any non-schema data are recovered. They
18791 ** are then stored in a singly-linked list linked by this variable beginning
18809 ** The index of the associated field within database records. Or -1 if
18862 u32 aElem[FLEXARRAY]; /* Array of 32-bit bitmasks */
18924 char *zLostAndFound; /* Name of lost-and-found table (or NULL) */
18969 ** Populate the recovery.map table - used to figure out a "root" page
18974 ** Populate the lost-and-found table itself.
19010 ** recoverEnterMutex() - Enter the recovery mutex
19011 ** recoverLeaveMutex() - Leave the recovery mutex
19012 ** recoverAssertMutexHeld() - Assert that the recovery mutex is held
19027 assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) ); in recoverAssertMutexHeld()
19043 ** This function is a no-op if the recover handle passed as the first
19044 ** argument already contains an error (if p->errCode!=SQLITE_OK).
19049 ** (p->errCode) set to SQLITE_NOMEM.
19053 assert( nByte>0 ); in recoverMalloc()
19054 if( p->errCode==SQLITE_OK ){ in recoverMalloc()
19059 p->errCode = SQLITE_NOMEM; in recoverMalloc()
19090 sqlite3_free(p->zErrMsg); in recoverError()
19091 p->zErrMsg = z; in recoverError()
19092 p->errCode = errCode; in recoverError()
19098 ** This function is a no-op if p->errCode is initially other than SQLITE_OK.
19111 pRet->nPg = nPg; in recoverBitmapAlloc()
19127 if( iPg<=pMap->nPg ){ in recoverBitmapSet()
19130 pMap->aElem[iElem] |= (((u32)1) << iBit); in recoverBitmapSet()
19140 if( iPg<=pMap->nPg && iPg>0 ){ in recoverBitmapQuery()
19143 ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0; in recoverBitmapQuery()
19158 ** This function is a no-op if recover handle p already contains an error
19159 ** (if p->errCode!=SQLITE_OK).
19172 if( p->errCode==SQLITE_OK ){ in recoverPrepare()
19173 if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){ in recoverPrepare()
19181 ** This function is a no-op if recover handle p already contains an error
19182 ** (if p->errCode!=SQLITE_OK).
19187 ** the statment handle returned. Or, if an error occurs - either during
19188 ** the printf() formatting or when preparing the resulting SQL - an
19197 if( p->errCode==SQLITE_OK ){ in recoverPreparePrintf()
19204 p->errCode = SQLITE_NOMEM; in recoverPreparePrintf()
19214 ** Reset SQLite statement handle pStmt. If the call to sqlite3_reset()
19224 if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){ in recoverReset()
19239 if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){ in recoverFinalize()
19245 ** This function is a no-op if recover handle p already contains an error
19246 ** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this
19254 if( p->errCode==SQLITE_OK ){ in recoverExec()
19260 return p->errCode; in recoverExec()
19274 if( p->errCode==SQLITE_OK ){ in recoverBindValue()
19281 ** This function is a no-op if recover handle p already contains an error
19282 ** (if p->errCode!=SQLITE_OK). NULL is returned in this case.
19300 if( p->errCode==SQLITE_OK ){ in recoverMPrintf()
19301 if( z==0 ) p->errCode = SQLITE_NOMEM; in recoverMPrintf()
19310 ** This function is a no-op if recover handle p already contains an error
19311 ** (if p->errCode!=SQLITE_OK). Zero is returned in this case.
19320 if( p->errCode==SQLITE_OK ){ in recoverPageCount()
19322 pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb); in recoverPageCount()
19334 ** this function must be a blob. The second a non-negative integer. This
19335 ** function reads and returns a 32-bit big-endian integer from byte
19349 assert( argc==2 ); in recoverReadI32()
19367 ** lost-and-found table, and it depends on those routines having populated
19370 ** The only argument to this function is a page-number. It returns true
19383 assert( nArg==1 ); in recoverPageIsUsed()
19384 sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno)); in recoverPageIsUsed()
19388 ** The implementation of a user-defined SQL function invoked by the
19398 ** SELECT getpage(0); -- return number of pages in db
19399 ** SELECT getpage(4); -- return page 4 of db as a blob of data
19410 assert( nArg==1 ); in recoverGetPage()
19416 if( p->pGetPage==0 ){ in recoverGetPage()
19417 pStmt = p->pGetPage = recoverPreparePrintf( in recoverGetPage()
19418 p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb in recoverGetPage()
19420 }else if( p->errCode==SQLITE_OK ){ in recoverGetPage()
19421 pStmt = p->pGetPage; in recoverGetPage()
19429 assert( p->errCode==SQLITE_OK ); in recoverGetPage()
19432 if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){ in recoverGetPage()
19433 aPg = p->pPage1Disk; in recoverGetPage()
19435 sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT); in recoverGetPage()
19441 if( p->errCode ){ in recoverGetPage()
19442 if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1); in recoverGetPage()
19443 sqlite3_result_error_code(pCtx, p->errCode); in recoverGetPage()
19470 ** this function is the output of built-in function quote(). If the first
19559 ** This function is a no-op if recover handle p already contains an error
19560 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
19572 return recoverExec(p, p->dbOut, in recoverCacheSchema()
19593 ** this function is a no-op. Otherwise, issue a callback with SQL statement
19596 ** If the callback returns non-zero, set the recover handle error code to
19600 if( p->errCode==SQLITE_OK && p->xSql ){ in recoverSqlCallback()
19601 int res = p->xSql(p->pSqlCtx, zSql); in recoverSqlCallback()
19603 recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res); in recoverSqlCallback()
19612 ** + page-size,
19613 ** + auto-vacuum settings,
19615 ** + user-version (PRAGMA user_version), and
19616 ** + application-id (PRAGMA application_id), and
19631 if( p->errCode==SQLITE_OK ){ in recoverTransferSettings()
19642 p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag); in recoverTransferSettings()
19643 if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){ in recoverTransferSettings()
19657 if( p->errCode==SQLITE_OK ){ in recoverTransferSettings()
19658 sqlite3 *db = p->dbOut; in recoverTransferSettings()
19661 sqlite3_backup_step(pBackup, -1); in recoverTransferSettings()
19662 p->errCode = sqlite3_backup_finish(pBackup); in recoverTransferSettings()
19673 ** This function is a no-op if recover handle p already contains an error
19674 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
19702 assert( p->dbOut==0 ); in recoverOpenOutput()
19704 if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){ in recoverOpenOutput()
19709 ** These two are registered with the output database handle - this in recoverOpenOutput()
19712 if( p->errCode==SQLITE_OK ){ in recoverOpenOutput()
19713 p->errCode = sqlite3_dbdata_init(db, 0, 0); in recoverOpenOutput()
19716 /* Register the custom user-functions with the output handle. */ in recoverOpenOutput()
19718 p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0])); in recoverOpenOutput()
19720 p->errCode = sqlite3_create_function(db, aFunc[ii].zName, in recoverOpenOutput()
19725 p->dbOut = db; in recoverOpenOutput()
19726 return p->errCode; in recoverOpenOutput()
19735 char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb); in recoverOpenRecovery()
19736 recoverExec(p, p->dbOut, zSql); in recoverOpenRecovery()
19737 recoverExec(p, p->dbOut, in recoverOpenRecovery()
19747 ** This function is a no-op if recover handle p already contains an error
19748 ** (if p->errCode!=SQLITE_OK).
19764 sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut, in recoverAddTable()
19769 int iPk = -1; in recoverAddTable()
19787 pNew->aCol = (RecoverColumn*)&pNew[1]; in recoverAddTable()
19788 pNew->zTab = csr = (char*)&pNew->aCol[nCol]; in recoverAddTable()
19789 pNew->nCol = nCol; in recoverAddTable()
19790 pNew->iRoot = iRoot; in recoverAddTable()
19801 if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i; in recoverAddTable()
19802 if( iPKF>1 ) iPk = -2; in recoverAddTable()
19803 pNew->aCol[i].zCol = csr; in recoverAddTable()
19804 pNew->aCol[i].eHidden = eHidden; in recoverAddTable()
19806 pNew->aCol[i].iField = -1; in recoverAddTable()
19808 pNew->aCol[i].iField = iField++; in recoverAddTable()
19813 pNew->aCol[i].iBind = iBind++; in recoverAddTable()
19819 pNew->pNext = p->pTblList; in recoverAddTable()
19820 p->pTblList = pNew; in recoverAddTable()
19821 pNew->bIntkey = 1; in recoverAddTable()
19826 pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName); in recoverAddTable()
19831 assert( iCol<pNew->nCol ); in recoverAddTable()
19832 pNew->aCol[iCol].iField = iField; in recoverAddTable()
19834 pNew->bIntkey = 0; in recoverAddTable()
19835 iPk = -2; in recoverAddTable()
19839 if( p->errCode==SQLITE_OK ){ in recoverAddTable()
19841 pNew->aCol[iPk].bIPK = 1; in recoverAddTable()
19842 }else if( pNew->bIntkey ){ in recoverAddTable()
19843 pNew->iRowidBind = iBind++; in recoverAddTable()
19872 pSelect = recoverPrepare(p, p->dbOut, in recoverWriteSchema1()
19886 pTblname = recoverPrepare(p, p->dbOut, in recoverWriteSchema1()
19892 sqlite3_bind_int(pSelect, 1, p->bSlowIndexes); in recoverWriteSchema1()
19908 rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0); in recoverWriteSchema1()
19919 recoverDbError(p, p->dbOut); in recoverWriteSchema1()
19927 return p->errCode; in recoverWriteSchema1()
19933 ** database by recoverWriteSchema1() - everything except for tables and
19938 ** * non-UNIQUE indexes.
19946 pSelect = recoverPrepare(p, p->dbOut, in recoverWriteSchema2()
19947 p->bSlowIndexes ? in recoverWriteSchema2()
19958 int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0); in recoverWriteSchema2()
19962 recoverDbError(p, p->dbOut); in recoverWriteSchema2()
19968 return p->errCode; in recoverWriteSchema2()
19972 ** This function is a no-op if recover handle p already contains an error
19973 ** (if p->errCode!=SQLITE_OK). In this case it returns NULL.
19995 ** a single text value - itself an SQL statement similar to the above,
20018 int bSql = p->xSql ? 1 : 0; in recoverInsertStmt()
20022 assert( nField<=pTab->nCol ); in recoverInsertStmt()
20024 zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab); in recoverInsertStmt()
20026 if( pTab->iRowidBind ){ in recoverInsertStmt()
20027 assert( pTab->bIntkey ); in recoverInsertStmt()
20030 zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind); in recoverInsertStmt()
20032 zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind); in recoverInsertStmt()
20039 int eHidden = pTab->aCol[ii].eHidden; in recoverInsertStmt()
20043 assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 ); in recoverInsertStmt()
20044 zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol); in recoverInsertStmt()
20048 "%z%sescape_crlf(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind in recoverInsertStmt()
20052 zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind); in recoverInsertStmt()
20066 pRet = recoverPrepare(p, p->dbOut, zFinal); in recoverInsertStmt()
20076 ** Search the list of RecoverTable objects at p->pTblList for one that
20082 for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext); in recoverFindTable()
20103 pProbe = recoverPrepare(p, p->dbOut, in recoverLostAndFoundCreate()
20106 for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){ in recoverLostAndFoundCreate()
20109 zTbl = recoverMPrintf(p, "%s", p->zLostAndFound); in recoverLostAndFoundCreate()
20111 zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii); in recoverLostAndFoundCreate()
20114 if( p->errCode==SQLITE_OK ){ in recoverLostAndFoundCreate()
20115 sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC); in recoverLostAndFoundCreate()
20136 for(ii=0; p->errCode==SQLITE_OK && ii<nField; ii++){ in recoverLostAndFoundCreate()
20144 recoverExec(p, p->dbOut, zSql); in recoverLostAndFoundCreate()
20147 }else if( p->errCode==SQLITE_OK ){ in recoverLostAndFoundCreate()
20149 p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound in recoverLostAndFoundCreate()
20171 if( p->xSql==0 ){ in recoverLostAndFoundInsert()
20176 p, p->dbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind in recoverLostAndFoundInsert()
20185 p, p->dbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind in recoverLostAndFoundInsert()
20195 ** lost-and-found table of the output database. This function attempts
20207 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFoundFindRoot()
20209 if( pLaf->pFindRoot==0 ){ in recoverLostAndFoundFindRoot()
20210 pLaf->pFindRoot = recoverPrepare(p, p->dbOut, in recoverLostAndFoundFindRoot()
20220 if( p->errCode==SQLITE_OK ){ in recoverLostAndFoundFindRoot()
20221 sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg); in recoverLostAndFoundFindRoot()
20222 if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){ in recoverLostAndFoundFindRoot()
20223 *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0); in recoverLostAndFoundFindRoot()
20227 recoverReset(p, pLaf->pFindRoot); in recoverLostAndFoundFindRoot()
20229 return p->errCode; in recoverLostAndFoundFindRoot()
20234 ** the lost-and-found table in the output database.
20237 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFoundOnePage()
20238 sqlite3_value **apVal = pLaf->apVal; in recoverLostAndFoundOnePage()
20239 sqlite3_stmt *pPageData = pLaf->pPageData; in recoverLostAndFoundOnePage()
20240 sqlite3_stmt *pInsert = pLaf->pInsert; in recoverLostAndFoundOnePage()
20242 int nVal = -1; in recoverLostAndFoundOnePage()
20251 while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){ in recoverLostAndFoundOnePage()
20278 nVal = -1; in recoverLostAndFoundOnePage()
20284 assert( nVal==-1 ); in recoverLostAndFoundOnePage()
20288 }else if( iField<pLaf->nMaxField ){ in recoverLostAndFoundOnePage()
20291 assert( iField==nVal || (nVal==-1 && iField==0) ); in recoverLostAndFoundOnePage()
20311 ** RECOVER_STATE_LOSTANDFOUND3 state - during which the lost-and-found
20316 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound3Step()
20317 if( p->errCode==SQLITE_OK ){ in recoverLostAndFound3Step()
20318 if( pLaf->pInsert==0 ){ in recoverLostAndFound3Step()
20321 if( p->errCode==SQLITE_OK ){ in recoverLostAndFound3Step()
20322 int res = sqlite3_step(pLaf->pAllPage); in recoverLostAndFound3Step()
20324 i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0); in recoverLostAndFound3Step()
20325 if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){ in recoverLostAndFound3Step()
20329 recoverReset(p, pLaf->pAllPage); in recoverLostAndFound3Step()
20340 ** state - during which the lost-and-found table of the output database
20345 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound3Init()
20347 if( pLaf->nMaxField>0 ){ in recoverLostAndFound3Init()
20350 zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField); in recoverLostAndFound3Init()
20351 pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField); in recoverLostAndFound3Init()
20354 pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut, in recoverLostAndFound3Init()
20358 "SELECT ii FROM seq" , p->laf.nPg in recoverLostAndFound3Init()
20360 pLaf->pPageData = recoverPrepare(p, p->dbOut, in recoverLostAndFound3Init()
20364 "SELECT -1, -1, -1" in recoverLostAndFound3Init()
20367 pLaf->apVal = (sqlite3_value**)recoverMalloc(p, in recoverLostAndFound3Init()
20368 pLaf->nMaxField*sizeof(sqlite3_value*) in recoverLostAndFound3Init()
20374 ** Initialize resources required in RECOVER_STATE_WRITING state - during which
20379 RecoverStateW1 *p1 = &p->w1; in recoverWriteDataInit()
20384 assert( p1->nMax==0 ); in recoverWriteDataInit()
20385 for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){ in recoverWriteDataInit()
20386 if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol; in recoverWriteDataInit()
20391 nByte = sizeof(sqlite3_value*) * (p1->nMax+1); in recoverWriteDataInit()
20392 p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte); in recoverWriteDataInit()
20393 if( p1->apVal==0 ) return p->errCode; in recoverWriteDataInit()
20397 p1->pTbls = recoverPrepare(p, p->dbOut, in recoverWriteDataInit()
20402 p1->pSel = recoverPrepare(p, p->dbOut, in recoverWriteDataInit()
20415 return p->errCode; in recoverWriteDataInit()
20423 RecoverStateW1 *p1 = &p->w1; in recoverWriteDataCleanup()
20425 for(ii=0; ii<p1->nVal; ii++){ in recoverWriteDataCleanup()
20426 sqlite3_value_free(p1->apVal[ii]); in recoverWriteDataCleanup()
20428 sqlite3_free(p1->apVal); in recoverWriteDataCleanup()
20429 recoverFinalize(p, p1->pInsert); in recoverWriteDataCleanup()
20430 recoverFinalize(p, p1->pTbls); in recoverWriteDataCleanup()
20431 recoverFinalize(p, p1->pSel); in recoverWriteDataCleanup()
20438 ** RECOVER_STATE_WRITING state - during which tables recovered from the
20442 RecoverStateW1 *p1 = &p->w1; in recoverWriteDataStep()
20443 sqlite3_stmt *pSel = p1->pSel; in recoverWriteDataStep()
20444 sqlite3_value **apVal = p1->apVal; in recoverWriteDataStep()
20446 if( p->errCode==SQLITE_OK && p1->pTab==0 ){ in recoverWriteDataStep()
20447 if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){ in recoverWriteDataStep()
20448 i64 iRoot = sqlite3_column_int64(p1->pTbls, 0); in recoverWriteDataStep()
20449 p1->pTab = recoverFindTable(p, iRoot); in recoverWriteDataStep()
20451 recoverFinalize(p, p1->pInsert); in recoverWriteDataStep()
20452 p1->pInsert = 0; in recoverWriteDataStep()
20456 if( p1->pTab==0 ) return p->errCode; in recoverWriteDataStep()
20460 ** keys before recovering its contents. The p1->pTbls SELECT statement in recoverWriteDataStep()
20463 if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){ in recoverWriteDataStep()
20464 recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence"); in recoverWriteDataStep()
20469 ** SELECT statement p1->pSel. The SELECT statement will then iterate in recoverWriteDataStep()
20473 p1->nVal = 0; in recoverWriteDataStep()
20474 p1->bHaveRowid = 0; in recoverWriteDataStep()
20475 p1->iPrevPage = -1; in recoverWriteDataStep()
20476 p1->iPrevCell = -1; in recoverWriteDataStep()
20481 assert( p->errCode!=SQLITE_OK || p1->pTab ); in recoverWriteDataStep()
20483 if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){ in recoverWriteDataStep()
20484 RecoverTable *pTab = p1->pTab; in recoverWriteDataStep()
20490 int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell); in recoverWriteDataStep()
20492 assert( bNewCell==0 || (iField==-1 || iField==0) ); in recoverWriteDataStep()
20493 assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol ); in recoverWriteDataStep()
20497 if( p1->nVal>=0 ){ in recoverWriteDataStep()
20498 if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){ in recoverWriteDataStep()
20499 recoverFinalize(p, p1->pInsert); in recoverWriteDataStep()
20500 p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal); in recoverWriteDataStep()
20501 p1->nInsert = p1->nVal; in recoverWriteDataStep()
20503 if( p1->nVal>0 ){ in recoverWriteDataStep()
20504 sqlite3_stmt *pInsert = p1->pInsert; in recoverWriteDataStep()
20505 for(ii=0; ii<pTab->nCol; ii++){ in recoverWriteDataStep()
20506 RecoverColumn *pCol = &pTab->aCol[ii]; in recoverWriteDataStep()
20507 int iBind = pCol->iBind; in recoverWriteDataStep()
20509 if( pCol->bIPK ){ in recoverWriteDataStep()
20510 sqlite3_bind_int64(pInsert, iBind, p1->iRowid); in recoverWriteDataStep()
20511 }else if( pCol->iField<p1->nVal ){ in recoverWriteDataStep()
20512 recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]); in recoverWriteDataStep()
20516 if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){ in recoverWriteDataStep()
20517 sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid); in recoverWriteDataStep()
20524 assert( p->errCode || pInsert ); in recoverWriteDataStep()
20529 for(ii=0; ii<p1->nVal; ii++){ in recoverWriteDataStep()
20533 p1->nVal = -1; in recoverWriteDataStep()
20534 p1->bHaveRowid = 0; in recoverWriteDataStep()
20539 p1->iRowid = sqlite3_column_int64(pSel, 3); in recoverWriteDataStep()
20540 assert( p1->nVal==-1 ); in recoverWriteDataStep()
20541 p1->nVal = 0; in recoverWriteDataStep()
20542 p1->bHaveRowid = 1; in recoverWriteDataStep()
20543 }else if( iField<pTab->nCol ){ in recoverWriteDataStep()
20544 assert( apVal[iField]==0 ); in recoverWriteDataStep()
20549 p1->nVal = iField+1; in recoverWriteDataStep()
20550 }else if( pTab->nCol==0 ){ in recoverWriteDataStep()
20551 p1->nVal = pTab->nCol; in recoverWriteDataStep()
20553 p1->iPrevCell = iCell; in recoverWriteDataStep()
20554 p1->iPrevPage = iPage; in recoverWriteDataStep()
20558 p1->pTab = 0; in recoverWriteDataStep()
20561 return p->errCode; in recoverWriteDataStep()
20566 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
20570 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound1Init()
20573 assert( p->laf.pUsed==0 ); in recoverLostAndFound1Init()
20574 pLaf->nPg = recoverPageCount(p); in recoverLostAndFound1Init()
20575 pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg); in recoverLostAndFound1Init()
20579 ** if !p->bFreelistCorrupt, add all pages that appear to be part of the in recoverLostAndFound1Init()
20582 p, p->dbOut, in recoverLostAndFound1Init()
20592 " SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata" in recoverLostAndFound1Init()
20594 " SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0" in recoverLostAndFound1Init()
20611 if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt); in recoverLostAndFound1Init()
20612 pLaf->pUsedPages = pStmt; in recoverLostAndFound1Init()
20618 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
20622 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound1Step()
20623 int rc = p->errCode; in recoverLostAndFound1Step()
20625 rc = sqlite3_step(pLaf->pUsedPages); in recoverLostAndFound1Step()
20627 i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0); in recoverLostAndFound1Step()
20628 recoverBitmapSet(pLaf->pUsed, iPg); in recoverLostAndFound1Step()
20631 recoverFinalize(p, pLaf->pUsedPages); in recoverLostAndFound1Step()
20632 pLaf->pUsedPages = 0; in recoverLostAndFound1Step()
20640 ** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1
20644 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound2Init()
20646 assert( p->laf.pAllAndParent==0 ); in recoverLostAndFound2Init()
20647 assert( p->laf.pMapInsert==0 ); in recoverLostAndFound2Init()
20648 assert( p->laf.pMaxField==0 ); in recoverLostAndFound2Init()
20649 assert( p->laf.nMaxField==0 ); in recoverLostAndFound2Init()
20651 pLaf->pMapInsert = recoverPrepare(p, p->dbOut, in recoverLostAndFound2Init()
20654 pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut, in recoverLostAndFound2Init()
20660 "SELECT NULL, ii FROM seq", p->laf.nPg in recoverLostAndFound2Init()
20662 pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut, in recoverLostAndFound2Init()
20670 ** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified
20675 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound2Step()
20676 if( p->errCode==SQLITE_OK ){ in recoverLostAndFound2Step()
20677 int res = sqlite3_step(pLaf->pAllAndParent); in recoverLostAndFound2Step()
20679 i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1); in recoverLostAndFound2Step()
20680 if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){ in recoverLostAndFound2Step()
20681 sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild); in recoverLostAndFound2Step()
20682 sqlite3_bind_value(pLaf->pMapInsert, 2, in recoverLostAndFound2Step()
20683 sqlite3_column_value(pLaf->pAllAndParent, 0) in recoverLostAndFound2Step()
20685 sqlite3_step(pLaf->pMapInsert); in recoverLostAndFound2Step()
20686 recoverReset(p, pLaf->pMapInsert); in recoverLostAndFound2Step()
20687 sqlite3_bind_int64(pLaf->pMaxField, 1, iChild); in recoverLostAndFound2Step()
20688 if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){ in recoverLostAndFound2Step()
20689 int nMax = sqlite3_column_int(pLaf->pMaxField, 0); in recoverLostAndFound2Step()
20690 if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax; in recoverLostAndFound2Step()
20692 recoverReset(p, pLaf->pMaxField); in recoverLostAndFound2Step()
20695 recoverFinalize(p, pLaf->pAllAndParent); in recoverLostAndFound2Step()
20696 pLaf->pAllAndParent =0; in recoverLostAndFound2Step()
20700 return p->errCode; in recoverLostAndFound2Step()
20708 recoverBitmapFree(p->laf.pUsed); in recoverLostAndFoundCleanup()
20709 p->laf.pUsed = 0; in recoverLostAndFoundCleanup()
20710 sqlite3_finalize(p->laf.pUsedPages); in recoverLostAndFoundCleanup()
20711 sqlite3_finalize(p->laf.pAllAndParent); in recoverLostAndFoundCleanup()
20712 sqlite3_finalize(p->laf.pMapInsert); in recoverLostAndFoundCleanup()
20713 sqlite3_finalize(p->laf.pMaxField); in recoverLostAndFoundCleanup()
20714 sqlite3_finalize(p->laf.pFindRoot); in recoverLostAndFoundCleanup()
20715 sqlite3_finalize(p->laf.pInsert); in recoverLostAndFoundCleanup()
20716 sqlite3_finalize(p->laf.pAllPage); in recoverLostAndFoundCleanup()
20717 sqlite3_finalize(p->laf.pPageData); in recoverLostAndFoundCleanup()
20718 p->laf.pUsedPages = 0; in recoverLostAndFoundCleanup()
20719 p->laf.pAllAndParent = 0; in recoverLostAndFoundCleanup()
20720 p->laf.pMapInsert = 0; in recoverLostAndFoundCleanup()
20721 p->laf.pMaxField = 0; in recoverLostAndFoundCleanup()
20722 p->laf.pFindRoot = 0; in recoverLostAndFoundCleanup()
20723 p->laf.pInsert = 0; in recoverLostAndFoundCleanup()
20724 p->laf.pAllPage = 0; in recoverLostAndFoundCleanup()
20725 p->laf.pPageData = 0; in recoverLostAndFoundCleanup()
20726 sqlite3_free(p->laf.apVal); in recoverLostAndFoundCleanup()
20727 p->laf.apVal = 0; in recoverLostAndFoundCleanup()
20740 for(pTab=p->pTblList; pTab; pTab=pNext){ in recoverFinalCleanup()
20741 pNext = pTab->pNext; in recoverFinalCleanup()
20744 p->pTblList = 0; in recoverFinalCleanup()
20745 sqlite3_finalize(p->pGetPage); in recoverFinalCleanup()
20746 p->pGetPage = 0; in recoverFinalCleanup()
20747 sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0); in recoverFinalCleanup()
20753 sqlite3_close(p->dbOut); in recoverFinalCleanup()
20754 assert( res==SQLITE_OK ); in recoverFinalCleanup()
20756 p->dbOut = 0; in recoverFinalCleanup()
20760 ** Decode and return an unsigned 16-bit big-endian integer value from
20768 ** Decode and return an unsigned 32-bit big-endian integer value from
20793 ** or a prefix thereof appears to contain a well-formed SQLite b-tree page,
20794 ** return the page-size in bytes. Otherwise, if the buffer does not
20795 ** appear to contain a well-formed b-tree page, return 0.
20822 /* Follow the free-list. This is the same format for all b-tree pages. */ in recoverIsValidPage()
20827 if( iFree>(n-4) ) return 0; in recoverIsValidPage()
20858 int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23); in recoverIsValidPage()
20859 int M = ((n-12)*32/255)-23; in recoverIsValidPage()
20860 int K = M+((nPayload-M)%(n-4)); in recoverIsValidPage()
20932 assert( pFd->pMethods!=&recover_methods ); in recoverVfsClose()
20933 return pFd->pMethods->xClose(pFd); in recoverVfsClose()
20937 ** Write value v to buffer a[] as a 16-bit big-endian unsigned integer.
20945 ** Write value v to buffer a[] as a 32-bit big-endian unsigned integer.
20955 ** Detect the page-size of the database opened by file-handle pFd by
20956 ** searching the first part of the file for a well-formed SQLite b-tree
20957 ** page. If parameter nReserve is non-zero, then as well as searching for
20958 ** a b-tree page with zero reserved bytes, this function searches for one
20961 ** If successful, set variable p->detected_pgsz to the detected page-size
20963 ** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or,
20965 ** is returned. The final value of p->detected_pgsz is undefined in this
20970 sqlite3_file *pFd, /* File-handle open on input database */ in recoverVfsDetectPagesize()
20988 nBlk = (nSz+nMax-1)/nMax; in recoverVfsDetectPagesize()
20995 rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax); in recoverVfsDetectPagesize()
21001 if( recoverIsValidPage(aTmp, &aPg[iOff], pgsz2-nReserve) ){ in recoverVfsDetectPagesize()
21009 if( pgsz>(u32)p->detected_pgsz ){ in recoverVfsDetectPagesize()
21010 p->detected_pgsz = pgsz; in recoverVfsDetectPagesize()
21011 p->nReserve = nReserve; in recoverVfsDetectPagesize()
21017 p->detected_pgsz = pgsz; in recoverVfsDetectPagesize()
21028 if( pFd->pMethods==&recover_methods ){ in recoverVfsRead()
21029 pFd->pMethods = recover_g.pMethods; in recoverVfsRead()
21030 rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff); in recoverVfsRead()
21038 ** + Database page size (16-bits at offset 16) in recoverVfsRead()
21039 ** + Size of db in pages (32-bits at offset 28) in recoverVfsRead()
21040 ** + Database encoding (32-bits at offset 56) in recoverVfsRead()
21044 ** + first freelist page (32-bits at offset 32) in recoverVfsRead()
21045 ** + size of freelist (32-bits at offset 36) in recoverVfsRead()
21046 ** + the wal-mode flags (16-bits at offset 18) in recoverVfsRead()
21048 ** We also try to preserve the auto-vacuum, incr-value, user-version in recoverVfsRead()
21049 ** and application-id fields - all 32 bit quantities at offsets in recoverVfsRead()
21052 ** Byte offset 105 should also contain the page-size as a 16-bit in recoverVfsRead()
21084 rc = pFd->pMethods->xFileSize(pFd, &dbFileSize); in recoverVfsRead()
21086 if( rc==SQLITE_OK && p->detected_pgsz==0 ){ in recoverVfsRead()
21089 if( p->detected_pgsz ){ in recoverVfsRead()
21090 pgsz = p->detected_pgsz; in recoverVfsRead()
21091 nReserve = p->nReserve; in recoverVfsRead()
21101 sqlite3_free(p->pPage1Cache); in recoverVfsRead()
21102 p->pPage1Cache = 0; in recoverVfsRead()
21103 p->pPage1Disk = 0; in recoverVfsRead()
21105 p->pgsz = nByte; in recoverVfsRead()
21106 p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2); in recoverVfsRead()
21107 if( p->pPage1Cache ){ in recoverVfsRead()
21108 p->pPage1Disk = &p->pPage1Cache[nByte]; in recoverVfsRead()
21109 memcpy(p->pPage1Disk, aBuf, nByte); in recoverVfsRead()
21114 recoverPutU16(&aHdr[105], pgsz-nReserve); in recoverVfsRead()
21122 memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr)); in recoverVfsRead()
21124 memcpy(p->pPage1Cache, aBuf, nByte); in recoverVfsRead()
21126 rc = p->errCode; in recoverVfsRead()
21130 pFd->pMethods = &recover_methods; in recoverVfsRead()
21132 rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff); in recoverVfsRead()
21142 if( pFd->pMethods==&recover_methods ){ \
21143 pFd->pMethods = recover_g.pMethods; \
21145 pFd->pMethods = &recover_methods; \
21161 pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff) in recoverVfsWrite()
21166 pFd->pMethods->xTruncate(pFd, size) in recoverVfsTruncate()
21171 pFd->pMethods->xSync(pFd, flags) in recoverVfsSync()
21176 pFd->pMethods->xFileSize(pFd, pSize) in recoverVfsFileSize()
21181 pFd->pMethods->xLock(pFd, eLock) in recoverVfsLock()
21186 pFd->pMethods->xUnlock(pFd, eLock) in recoverVfsUnlock()
21191 pFd->pMethods->xCheckReservedLock(pFd, pResOut) in recoverVfsCheckReservedLock()
21196 (pFd->pMethods ? pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND) in recoverVfsFileControl()
21201 pFd->pMethods->xSectorSize(pFd) in recoverVfsSectorSize()
21206 pFd->pMethods->xDeviceCharacteristics(pFd) in recoverVfsDeviceCharacteristics()
21213 pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp) in recoverVfsShmMap()
21218 pFd->pMethods->xShmLock(pFd, offset, n, flags) in recoverVfsShmLock()
21222 if( pFd->pMethods==&recover_methods ){ in recoverVfsShmBarrier()
21223 pFd->pMethods = recover_g.pMethods; in recoverVfsShmBarrier()
21224 pFd->pMethods->xShmBarrier(pFd); in recoverVfsShmBarrier()
21225 pFd->pMethods = &recover_methods; in recoverVfsShmBarrier()
21227 pFd->pMethods->xShmBarrier(pFd); in recoverVfsShmBarrier()
21232 pFd->pMethods->xShmUnmap(pFd, deleteFlag) in recoverVfsShmUnmap()
21256 ** Install the VFS wrapper around the file-descriptor open on the input
21262 assert( recover_g.pMethods==0 ); in recoverInstallWrapper()
21264 sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd); in recoverInstallWrapper()
21265 assert( pFd==0 || pFd->pMethods!=&recover_methods ); in recoverInstallWrapper()
21266 if( pFd && pFd->pMethods ){ in recoverInstallWrapper()
21267 int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0); in recoverInstallWrapper()
21268 recover_g.pMethods = pFd->pMethods; in recoverInstallWrapper()
21271 pFd->pMethods = &recover_methods; in recoverInstallWrapper()
21276 ** Uninstall the VFS wrapper that was installed around the file-descriptor open
21283 sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd); in recoverUninstallWrapper()
21284 if( pFd && pFd->pMethods ){ in recoverUninstallWrapper()
21285 pFd->pMethods = recover_g.pMethods; in recoverUninstallWrapper()
21297 assert( p && p->errCode==SQLITE_OK ); in recoverStep()
21298 switch( p->eState ){ in recoverStep()
21314 ** Two attempts may be made - one with a wrapper installed to ensure in recoverStep()
21318 if( p->errCode==SQLITE_OK ){ in recoverStep()
21320 p->errCode = SQLITE_OK; in recoverStep()
21324 sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0); in recoverStep()
21325 recoverExec(p, p->dbIn, "PRAGMA writable_schema = on"); in recoverStep()
21326 recoverExec(p, p->dbIn, "BEGIN"); in recoverStep()
21327 if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1; in recoverStep()
21328 recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema"); in recoverStep()
21334 }while( p->errCode==SQLITE_NOTADB in recoverStep()
21335 && (bUseWrapper--) in recoverStep()
21336 && SQLITE_OK==sqlite3_exec(p->dbIn, "ROLLBACK", 0, 0, 0) in recoverStep()
21341 recoverExec(p, p->dbOut, "BEGIN"); in recoverStep()
21343 p->eState = RECOVER_STATE_WRITING; in recoverStep()
21348 if( p->w1.pTbls==0 ){ in recoverStep()
21353 if( p->zLostAndFound ){ in recoverStep()
21354 p->eState = RECOVER_STATE_LOSTANDFOUND1; in recoverStep()
21356 p->eState = RECOVER_STATE_SCHEMA2; in recoverStep()
21363 if( p->laf.pUsed==0 ){ in recoverStep()
21367 p->eState = RECOVER_STATE_LOSTANDFOUND2; in recoverStep()
21372 if( p->laf.pAllAndParent==0 ){ in recoverStep()
21376 p->eState = RECOVER_STATE_LOSTANDFOUND3; in recoverStep()
21382 if( p->laf.pInsert==0 ){ in recoverStep()
21386 p->eState = RECOVER_STATE_SCHEMA2; in recoverStep()
21395 p->eState = RECOVER_STATE_DONE; in recoverStep()
21400 recoverExec(p, p->dbOut, "COMMIT"); in recoverStep()
21401 rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0); in recoverStep()
21402 if( p->errCode==SQLITE_OK ) p->errCode = rc; in recoverStep()
21406 p->eState = RECOVER_STATE_DONE; in recoverStep()
21412 /* no-op */ in recoverStep()
21451 pRet->dbIn = db; in recoverInit()
21452 pRet->zDb = (char*)&pRet[1]; in recoverInit()
21453 pRet->zUri = &pRet->zDb[nDb+1]; in recoverInit()
21454 memcpy(pRet->zDb, zDb, nDb); in recoverInit()
21455 if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri); in recoverInit()
21456 pRet->xSql = xSql; in recoverInit()
21457 pRet->pSqlCtx = pSqlCtx; in recoverInit()
21458 pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT; in recoverInit()
21493 return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory"; in sqlite3_recover_errmsg()
21500 return p ? p->errCode : SQLITE_NOMEM; in sqlite3_recover_errcode()
21510 }else if( p->eState!=RECOVER_STATE_INIT ){ in sqlite3_recover_config()
21516 ** name of the auxiliary database that is ATTACH-ed to the database in sqlite3_recover_config()
21519 ** is subject to change or removal at any time. */ in sqlite3_recover_config()
21520 sqlite3_free(p->zStateDb); in sqlite3_recover_config()
21521 p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg); in sqlite3_recover_config()
21526 sqlite3_free(p->zLostAndFound); in sqlite3_recover_config()
21528 p->zLostAndFound = recoverMPrintf(p, "%s", zArg); in sqlite3_recover_config()
21530 p->zLostAndFound = 0; in sqlite3_recover_config()
21536 p->bFreelistCorrupt = *(int*)pArg; in sqlite3_recover_config()
21540 p->bRecoverRowid = *(int*)pArg; in sqlite3_recover_config()
21544 p->bSlowIndexes = *(int*)pArg; in sqlite3_recover_config()
21564 if( p->errCode==SQLITE_OK ) recoverStep(p); in sqlite3_recover_step()
21565 if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){ in sqlite3_recover_step()
21568 return p->errCode; in sqlite3_recover_step()
21596 if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){ in sqlite3_recover_finish()
21597 rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0); in sqlite3_recover_finish()
21598 if( p->errCode==SQLITE_OK ) p->errCode = rc; in sqlite3_recover_finish()
21600 rc = p->errCode; in sqlite3_recover_finish()
21601 sqlite3_free(p->zErrMsg); in sqlite3_recover_finish()
21602 sqlite3_free(p->zStateDb); in sqlite3_recover_finish()
21603 sqlite3_free(p->zLostAndFound); in sqlite3_recover_finish()
21604 sqlite3_free(p->pPage1Cache); in sqlite3_recover_finish()
21677 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
21681 u8 bSafeModePersist; /* The long-term value of bSafeMode */
21683 u8 crlfMode; /* Do NL-to-CRLF translations when enabled (maybe) */
21709 sqlite3_int64 szMax; /* --maxsize argument to .open */
21738 char *zNonce; /* Nonce for temporary safe-mode escapes */
21764 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
21768 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
21780 #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progress
21782 ** top-level SQL statement */
21783 #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
21797 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
21799 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
21801 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
21803 #define SHFLG_Echo 0x00000040 /* .echo on/off, or --echo setting */
21812 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
21813 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
21814 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
21826 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
21830 #define MODE_Pretty 11 /* Pretty-print schemas */
21834 #define MODE_Table 15 /* MySQL-style table formatting */
21835 #define MODE_Box 16 /* Unicode box-drawing characters */
21839 #define MODE_Www 20 /* Full web-page output */
21889 if( p->pLog==0 ) return; in shellLog()
21890 sqlite3_fprintf(p->pLog, "(%d) %s\n", iErrCode, zMsg); in shellLog()
21891 fflush(p->pLog); in shellLog()
21907 sqlite3_fprintf(p->out, "%s\n", sqlite3_value_text(apVal[0])); in shellPutsFunc()
21920 if( p->bSafeMode ){ in failIfSafeMode()
21926 sqlite3_fprintf(stderr, "line %d: %s\n", p->lineno, zMsg); in failIfSafeMode()
21945 ** Also throw an error if the EDITOR program returns a non-zero exit code.
21971 sqlite3_result_error(context, "no editor for edit()", -1); in editFunc()
21975 sqlite3_result_error(context, "NULL input to edit()", -1); in editFunc()
21995 sqlite3_result_error(context, "edit() cannot open temp file", -1); in editFunc()
22010 sqlite3_result_error(context, "edit() could not write the whole file", -1); in editFunc()
22021 sqlite3_result_error(context, "EDITOR returned non-zero", -1); in editFunc()
22027 "edit() cannot reopen temp file after edit", -1); in editFunc()
22042 sqlite3_result_error(context, "could not read back the whole file", -1); in editFunc()
22079 p->modePrior = p->mode; in outputModePush()
22080 p->priorShFlgs = p->shellFlgs; in outputModePush()
22081 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator)); in outputModePush()
22082 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator)); in outputModePush()
22085 p->mode = p->modePrior; in outputModePop()
22086 p->shellFlgs = p->priorShFlgs; in outputModePop()
22087 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator)); in outputModePop()
22088 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator)); in outputModePop()
22096 if( p->crlfMode ){ in setCrlfMode()
22097 sqlite3_fsetmode(p->out, _O_TEXT); in setCrlfMode()
22099 sqlite3_fsetmode(p->out, _O_BINARY); in setCrlfMode()
22107 ** Output the given string as a hex-encoded blob (eg. X'1234' )
22139 ** Step (3) is omitted if the control-character escape mode is OFF.
22150 FILE *out = p->out; in output_quoted_string()
22162 || (needDblQuote==0 && p->eEscMode==SHELL_ESC_OFF) in output_quoted_string()
22165 }else if( p->eEscMode==SHELL_ESC_OFF ){ in output_quoted_string()
22207 ** get corrupted by end-of-line translation facilities in some operating
22215 sqlite3_fsetmode(p->out, _O_BINARY); in output_quoted_escaped_string()
22216 if( p->eEscMode==SHELL_ESC_OFF ){ in output_quoted_escaped_string()
22221 sqlite3_fputs(zEscaped, p->out); in output_quoted_escaped_string()
22228 ** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
22237 ns = pcFirst - s; in anyOfInStr()
22244 /* Skip over as much z[] input char sequence as is valid UTF-8,
22247 ** sequence z:return (inclusive:exclusive) is validated UTF-8.
22251 int ng = (nAccept<0)? -nAccept : 0; in zSkipValidUtf8()
22253 assert(z!=0); in zSkipValidUtf8()
22254 while( (pcLimit)? (z<pcLimit) : (ng-- != 0) ){ in zSkipValidUtf8()
22266 if( ct==0 || (zt-z)>4 || (ct & 0xC0)!=0x80 ){ in zSkipValidUtf8()
22286 static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */ in output_c_string()
22295 sqlite3_fprintf(out, "%.*s", (int)(pcEnd-z), z); in output_c_string()
22339 const char *pcDQBS = anyOfInStr(z, zDQBS, pcLimit-z); in output_json_string()
22340 const char *pcPast = zSkipValidUtf8(z, (int)(pcLimit-z), ctrlMask); in output_json_string()
22343 sqlite3_fprintf(out, "%.*s", (int)(pcEnd-z), z); in output_json_string()
22385 ** The caller is responsible for freeing *ppFree if it is non-NULL in order
22401 if( p->eEscMode==SHELL_ESC_OFF ){ in escapeOutput()
22421 if( p->eEscMode==SHELL_ESC_SYMBOL ) nCtrl *= 2; in escapeOutput()
22437 i = -1; in escapeOutput()
22438 switch( p->eEscMode ){ in escapeOutput()
22518 ** Output a single term of CSV. Actually, p->colSeparator is used for
22519 ** the separator, which may or may not be a comma. p->nullValue is
22525 sqlite3_fprintf(p->out, "%s",p->nullValue); in output_csv()
22534 if( i==0 || strstr(z, p->colSeparator)!=0 ){ in output_csv()
22537 sqlite3_fputs(zQuoted, p->out); in output_csv()
22540 sqlite3_fputs(z, p->out); in output_csv()
22544 sqlite3_fputs(p->colSeparator, p->out); in output_csv()
22549 ** This routine runs when the user presses Ctrl-C
22559 ** This routine runs for console events (e.g. Ctrl-C) on Win32
22652 sqlite3_fprintf(p->out, "authorizer: %s", azAction[op]); in shellAuth()
22654 sqlite3_fputs(" ", p->out); in shellAuth()
22656 output_c_string(p->out, az[i]); in shellAuth()
22658 sqlite3_fputs("NULL", p->out); in shellAuth()
22661 sqlite3_fputs("\n", p->out); in shellAuth()
22662 if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4); in shellAuth()
22673 ** If the schema statement in z[] contains a start-of-comment and if
22681 if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){ in printSchemaLine()
22690 zNew[n-1] = 0; in printSchemaLine()
22721 if( z[i]=='-' && z[i+1]=='-' ) return 1; in wsToEol()
22735 if( p->autoEQPtest ){ in eqp_append()
22736 sqlite3_fprintf(p->out, "%d,%d,%s\n", iEqpId, p2, zText); in eqp_append()
22740 pNew->iEqpId = iEqpId; in eqp_append()
22741 pNew->iParentId = p2; in eqp_append()
22742 memcpy(pNew->zText, zText, nText+1); in eqp_append()
22743 pNew->pNext = 0; in eqp_append()
22744 if( p->sGraph.pLast ){ in eqp_append()
22745 p->sGraph.pLast->pNext = pNew; in eqp_append()
22747 p->sGraph.pRow = pNew; in eqp_append()
22749 p->sGraph.pLast = pNew; in eqp_append()
22753 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
22754 ** in p->sGraph.
22758 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){ in eqp_reset()
22759 pNext = pRow->pNext; in eqp_reset()
22762 memset(&p->sGraph, 0, sizeof(p->sGraph)); in eqp_reset()
22769 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow; in eqp_next_row()
22770 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext; in eqp_next_row()
22779 i64 n = strlen(p->sGraph.zPrefix); in eqp_render_level()
22783 z = pRow->zText; in eqp_render_level()
22784 sqlite3_fprintf(p->out, "%s%s%s\n", p->sGraph.zPrefix, in eqp_render_level()
22785 pNext ? "|--" : "`--", z); in eqp_render_level()
22786 if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){ in eqp_render_level()
22787 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4); in eqp_render_level()
22788 eqp_render_level(p, pRow->iEqpId); in eqp_render_level()
22789 p->sGraph.zPrefix[n] = 0; in eqp_render_level()
22795 ** Display and reset the EXPLAIN QUERY PLAN data
22798 EQPGraphRow *pRow = p->sGraph.pRow; in eqp_render()
22800 if( pRow->zText[0]=='-' ){ in eqp_render()
22801 if( pRow->pNext==0 ){ in eqp_render()
22805 sqlite3_fprintf(p->out, "%s\n", pRow->zText+3); in eqp_render()
22806 p->sGraph.pRow = pRow->pNext; in eqp_render()
22809 sqlite3_fprintf(p->out, "QUERY PLAN (cycles=%lld [100%%])\n", nCycle); in eqp_render()
22811 sqlite3_fputs("QUERY PLAN\n", p->out); in eqp_render()
22813 p->sGraph.zPrefix[0] = 0; in eqp_render()
22825 p->nProgress++; in progress_handler()
22826 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){ in progress_handler()
22827 sqlite3_fprintf(p->out, "Progress limit reached (%u)\n", p->nProgress); in progress_handler()
22828 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; in progress_handler()
22829 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0; in progress_handler()
22832 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){ in progress_handler()
22833 sqlite3_fprintf(p->out, "Progress %u\n", p->nProgress); in progress_handler()
22843 const char zDash[] = "--------------------------------------------------"; in print_dashes()
22844 const int nDash = sizeof(zDash) - 1; in print_dashes()
22847 N -= nDash; in print_dashes()
22853 ** Print a markdown or table-style row separator using ascii-art
22862 sqlite3_fputs(zSep, p->out); in print_row_separator()
22863 print_dashes(p->out, p->actualWidth[0]+2); in print_row_separator()
22865 sqlite3_fputs(zSep, p->out); in print_row_separator()
22866 print_dashes(p->out, p->actualWidth[i]+2); in print_row_separator()
22868 sqlite3_fputs(zSep, p->out); in print_row_separator()
22870 sqlite3_fputs("\n", p->out); in print_row_separator()
22888 switch( p->cMode ){ in shell_callback()
22900 if( p->cnt++>0 ) sqlite3_fputs(p->rowSeparator, p->out); in shell_callback()
22904 pDisplay = escapeOutput(p, azArg[i] ? azArg[i] : p->nullValue, &pFree); in shell_callback()
22905 sqlite3_fprintf(p->out, "%*s = %s%s", w, azCol[i], in shell_callback()
22906 pDisplay, p->rowSeparator); in shell_callback()
22923 if( p->cMode==MODE_ScanExp ){ in shell_callback()
22932 if( p->cnt++==0 ){ in shell_callback()
22934 utf8_width_print(p->out, aWidth[i], azCol[ aMap[i] ]); in shell_callback()
22935 sqlite3_fputs(i==nArg-1 ? "\n" : " ", p->out); in shell_callback()
22938 print_dashes(p->out, aWidth[i]); in shell_callback()
22939 sqlite3_fputs(i==nArg-1 ? "\n" : " ", p->out); in shell_callback()
22950 if( i==nArg-1 ) w = 0; in shell_callback()
22955 if( i==iIndent && p->aiIndent && p->pStmt ){ in shell_callback()
22956 if( p->iIndent<p->nIndent ){ in shell_callback()
22957 sqlite3_fprintf(p->out, "%*.s", p->aiIndent[p->iIndent], ""); in shell_callback()
22959 p->iIndent++; in shell_callback()
22961 utf8_width_print(p->out, w, zVal ? zVal : p->nullValue); in shell_callback()
22962 sqlite3_fputs(i==nArg-1 ? "\n" : zSep, p->out); in shell_callback()
22967 printSchemaLine(p->out, azArg[0], ";\n"); in shell_callback()
22970 case MODE_Pretty: { /* .schema and .fullschema with --indent */ in shell_callback()
22979 assert( nArg==1 ); in shell_callback()
22984 sqlite3_fprintf(p->out, "%s;\n", azArg[0]); in shell_callback()
22995 if( z[j-1]=='\r' ) z[j-1] = '\n'; in shell_callback()
22996 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue; in shell_callback()
22997 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){ in shell_callback()
22998 j--; in shell_callback()
23002 while( j>0 && IsSpace(z[j-1]) ){ j--; } in shell_callback()
23012 }else if( c=='-' && z[i+1]=='-' ){ in shell_callback()
23017 nParen--; in shell_callback()
23019 printSchemaLineN(p->out, z, j, "\n"); in shell_callback()
23031 printSchemaLineN(p->out, z, j, "\n "); in shell_callback()
23039 if( c=='\n' ) j--; in shell_callback()
23040 printSchemaLineN(p->out, z, j, "\n "); in shell_callback()
23048 printSchemaLine(p->out, z, ";\n"); in shell_callback()
23053 if( p->cnt++==0 && p->showHeader ){ in shell_callback()
23058 sqlite3_fprintf(p->out, "%s%s", zOut, in shell_callback()
23059 i==nArg-1 ? p->rowSeparator : p->colSeparator); in shell_callback()
23068 if( z==0 ) z = p->nullValue; in shell_callback()
23070 sqlite3_fputs(zOut, p->out); in shell_callback()
23072 sqlite3_fputs((i<nArg-1)? p->colSeparator : p->rowSeparator, p->out); in shell_callback()
23078 if( p->cnt==0 && p->cMode==MODE_Www ){ in shell_callback()
23082 ,p->out in shell_callback()
23085 if( p->cnt==0 && (p->showHeader || p->cMode==MODE_Www) ){ in shell_callback()
23086 sqlite3_fputs("<TR>", p->out); in shell_callback()
23088 sqlite3_fputs("<TH>", p->out); in shell_callback()
23089 output_html_string(p->out, azCol[i]); in shell_callback()
23090 sqlite3_fputs("</TH>\n", p->out); in shell_callback()
23092 sqlite3_fputs("</TR>\n", p->out); in shell_callback()
23094 p->cnt++; in shell_callback()
23096 sqlite3_fputs("<TR>", p->out); in shell_callback()
23098 sqlite3_fputs("<TD>", p->out); in shell_callback()
23099 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue); in shell_callback()
23100 sqlite3_fputs("</TD>\n", p->out); in shell_callback()
23102 sqlite3_fputs("</TR>\n", p->out); in shell_callback()
23106 if( p->cnt++==0 && p->showHeader ){ in shell_callback()
23108 output_c_string(p->out, azCol[i] ? azCol[i] : ""); in shell_callback()
23109 if(i<nArg-1) sqlite3_fputs(p->colSeparator, p->out); in shell_callback()
23111 sqlite3_fputs(p->rowSeparator, p->out); in shell_callback()
23115 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue); in shell_callback()
23116 if(i<nArg-1) sqlite3_fputs(p->colSeparator, p->out); in shell_callback()
23118 sqlite3_fputs(p->rowSeparator, p->out); in shell_callback()
23122 sqlite3_fsetmode(p->out, _O_BINARY); in shell_callback()
23123 if( p->cnt++==0 && p->showHeader ){ in shell_callback()
23125 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1); in shell_callback()
23127 sqlite3_fputs(p->rowSeparator, p->out); in shell_callback()
23131 output_csv(p, azArg[i], i<nArg-1); in shell_callback()
23133 sqlite3_fputs(p->rowSeparator, p->out); in shell_callback()
23140 sqlite3_fprintf(p->out, "INSERT INTO %s",p->zDestTable); in shell_callback()
23141 if( p->showHeader ){ in shell_callback()
23142 sqlite3_fputs("(", p->out); in shell_callback()
23144 if( i>0 ) sqlite3_fputs(",", p->out); in shell_callback()
23148 sqlite3_fputs(z, p->out); in shell_callback()
23151 sqlite3_fprintf(p->out, "%s", azCol[i]); in shell_callback()
23154 sqlite3_fputs(")", p->out); in shell_callback()
23156 p->cnt++; in shell_callback()
23158 sqlite3_fputs(i>0 ? "," : " VALUES(", p->out); in shell_callback()
23160 sqlite3_fputs("NULL", p->out); in shell_callback()
23168 sqlite3_fputs(azArg[i], p->out); in shell_callback()
23171 double r = sqlite3_column_double(p->pStmt, i); in shell_callback()
23175 sqlite3_fputs("9.0e+999", p->out); in shell_callback()
23177 sqlite3_fputs("-9.0e+999", p->out); in shell_callback()
23185 sqlite3_fputs(z, p->out); in shell_callback()
23187 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ in shell_callback()
23188 const void *pBlob = sqlite3_column_blob(p->pStmt, i); in shell_callback()
23189 int nBlob = sqlite3_column_bytes(p->pStmt, i); in shell_callback()
23190 output_hex_blob(p->out, pBlob, nBlob); in shell_callback()
23192 sqlite3_fputs(azArg[i], p->out); in shell_callback()
23199 sqlite3_fputs(");\n", p->out); in shell_callback()
23204 if( p->cnt==0 ){ in shell_callback()
23205 sqlite3_fputs("[{", p->out); in shell_callback()
23207 sqlite3_fputs(",\n{", p->out); in shell_callback()
23209 p->cnt++; in shell_callback()
23211 output_json_string(p->out, azCol[i], -1); in shell_callback()
23212 sqlite3_fputs(":", p->out); in shell_callback()
23214 sqlite3_fputs("null", p->out); in shell_callback()
23217 double r = sqlite3_column_double(p->pStmt, i); in shell_callback()
23221 sqlite3_fputs("9.0e+999", p->out); in shell_callback()
23223 sqlite3_fputs("-9.0e+999", p->out); in shell_callback()
23226 sqlite3_fputs(z, p->out); in shell_callback()
23228 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ in shell_callback()
23229 const void *pBlob = sqlite3_column_blob(p->pStmt, i); in shell_callback()
23230 int nBlob = sqlite3_column_bytes(p->pStmt, i); in shell_callback()
23231 output_json_string(p->out, pBlob, nBlob); in shell_callback()
23233 output_json_string(p->out, azArg[i], -1); in shell_callback()
23235 sqlite3_fputs(azArg[i], p->out); in shell_callback()
23237 if( i<nArg-1 ){ in shell_callback()
23238 sqlite3_fputs(",", p->out); in shell_callback()
23241 sqlite3_fputs("}", p->out); in shell_callback()
23246 if( p->cnt==0 && p->showHeader ){ in shell_callback()
23248 if( i>0 ) sqlite3_fputs(p->colSeparator, p->out); in shell_callback()
23251 sqlite3_fputs(p->rowSeparator, p->out); in shell_callback()
23253 p->cnt++; in shell_callback()
23255 if( i>0 ) sqlite3_fputs(p->colSeparator, p->out); in shell_callback()
23257 sqlite3_fputs("NULL", p->out); in shell_callback()
23261 sqlite3_fputs(azArg[i], p->out); in shell_callback()
23264 double r = sqlite3_column_double(p->pStmt, i); in shell_callback()
23266 sqlite3_fputs(z, p->out); in shell_callback()
23267 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ in shell_callback()
23268 const void *pBlob = sqlite3_column_blob(p->pStmt, i); in shell_callback()
23269 int nBlob = sqlite3_column_bytes(p->pStmt, i); in shell_callback()
23270 output_hex_blob(p->out, pBlob, nBlob); in shell_callback()
23272 sqlite3_fputs(azArg[i], p->out); in shell_callback()
23277 sqlite3_fputs(p->rowSeparator, p->out); in shell_callback()
23281 if( p->cnt++==0 && p->showHeader ){ in shell_callback()
23283 if( i>0 ) sqlite3_fputs(p->colSeparator, p->out); in shell_callback()
23284 sqlite3_fputs(azCol[i] ? azCol[i] : "", p->out); in shell_callback()
23286 sqlite3_fputs(p->rowSeparator, p->out); in shell_callback()
23290 if( i>0 ) sqlite3_fputs(p->colSeparator, p->out); in shell_callback()
23291 sqlite3_fputs(azArg[i] ? azArg[i] : p->nullValue, p->out); in shell_callback()
23293 sqlite3_fputs(p->rowSeparator, p->out); in shell_callback()
23322 if( p->n ) appendText(p, "|", 0); in captureOutputCallback()
23335 sqlite3_exec(p->db, in createSelftestTable()
23346 " 'memo','Tests generated by --init');\n" in createSelftestTable()
23375 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0); in createSelftestTable()
23389 if( p->zDestTable ){ in set_table_name()
23390 free(p->zDestTable); in set_table_name()
23391 p->zDestTable = 0; in set_table_name()
23397 z = p->zDestTable = malloc( n+1 ); in set_table_name()
23432 iOffset--; in shell_error_context()
23434 while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; } in shell_error_context()
23439 while( len>0 && (zSql[len]&0xc0)==0x80 ) len--; in shell_error_context()
23445 zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode,iOffset,""); in shell_error_context()
23447 zMsg = sqlite3_mprintf("\n %z\n %*serror here ---^", zCode,iOffset-14,""); in shell_error_context()
23455 ** the result columns, comma-separated, on a line and then add a
23458 ** If the number of columns is 1 and that column contains text "--"
23460 ** "--" comment occurs at the end of the statement, the comment
23472 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); in run_table_dump_query()
23474 char *zContext = shell_error_context(zSelect, p->db); in run_table_dump_query()
23475 sqlite3_fprintf(p->out, "/**** ERROR: (%d) %s *****/\n%s", in run_table_dump_query()
23476 rc, sqlite3_errmsg(p->db), zContext); in run_table_dump_query()
23478 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; in run_table_dump_query()
23485 sqlite3_fprintf(p->out, "%s", z); in run_table_dump_query()
23487 sqlite3_fprintf(p->out, ",%s", sqlite3_column_text(pSelect, i)); in run_table_dump_query()
23490 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; in run_table_dump_query()
23492 sqlite3_fputs("\n;\n", p->out); in run_table_dump_query()
23494 sqlite3_fputs(";\n", p->out); in run_table_dump_query()
23500 sqlite3_fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", in run_table_dump_query()
23501 rc, sqlite3_errmsg(p->db)); in run_table_dump_query()
23502 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; in run_table_dump_query()
23560 sqlite3_fprintf(out, "%-36s %s", aTrans[i].zDesc, &z[n]); in displayLinuxIoStats()
23570 ** Display a single line of status using 64-bit values.
23577 int bReset /* True to reset the stats */ in displayStatLine()
23579 sqlite3_int64 iCur = -1; in displayStatLine()
23580 sqlite3_int64 iHiwtr = -1; in displayStatLine()
23592 sqlite3_fprintf(out, "%-36s %s\n", zLabel, zLine); in displayStatLine()
23601 int bReset /* True to reset the stats */ in display_stats()
23606 if( pArg==0 || pArg->out==0 ) return 0; in display_stats()
23607 out = pArg->out; in display_stats()
23609 if( pArg->pStmt && pArg->statsOn==2 ){ in display_stats()
23611 sqlite3_stmt *pStmt = pArg->pStmt; in display_stats()
23614 sqlite3_fprintf(out, "%-36s %d\n", "Number of output columns:", nCol); in display_stats()
23617 sqlite3_fprintf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i)); in display_stats()
23620 sqlite3_fprintf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i)); in display_stats()
23624 sqlite3_fprintf(out, "%-36s %s\n", z, in display_stats()
23627 sqlite3_fprintf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i)); in display_stats()
23629 sqlite3_fprintf(out, "%-36s %s\n", z,sqlite3_column_origin_name(pStmt,i)); in display_stats()
23634 if( pArg->statsOn==3 ){ in display_stats()
23635 if( pArg->pStmt ){ in display_stats()
23636 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset); in display_stats()
23637 sqlite3_fprintf(out, "VM-steps: %d\n", iCur); in display_stats()
23646 if( pArg->shellFlgs & SHFLG_Pagecache ){ in display_stats()
23662 if( pArg->shellFlgs & SHFLG_Lookaside ){ in display_stats()
23663 iHiwtr = iCur = -1; in display_stats()
23681 iHiwtr = iCur = -1; in display_stats()
23685 iHiwtr = iCur = -1; in display_stats()
23689 iHiwtr = iCur = -1; in display_stats()
23693 iHiwtr = iCur = -1; in display_stats()
23697 iHiwtr = iCur = -1; in display_stats()
23701 iHiwtr = iCur = -1; in display_stats()
23705 iHiwtr = iCur = -1; in display_stats()
23711 if( pArg->pStmt ){ in display_stats()
23713 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, in display_stats()
23717 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); in display_stats()
23720 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); in display_stats()
23723 iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, in display_stats()
23725 iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, in display_stats()
23731 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); in display_stats()
23734 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset); in display_stats()
23737 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset); in display_stats()
23740 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset); in display_stats()
23746 displayLinuxIoStats(pArg->out); in display_stats()
23749 /* Do not remove this machine readable comment: extra-stats-output-here */ in display_stats()
23789 sqlite3_stmt *p = pArg->pStmt; in display_explain_scanstats()
23806 sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal); in display_explain_scanstats()
23844 if( zName && pArg->scanstatsOn>1 ){ in display_explain_scanstats()
23850 "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z in display_explain_scanstats()
23864 ** Parameter azArray points to a zero-terminated array of strings. zStr
23865 ** points to a single nul-terminated string. Return non-zero if zStr
23889 ** See tag-20220407a in wherecode.c and vdbe.c.
23900 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ in explain_data_prepare()
23901 int iOp; /* Index of operation in p->aiIndent[] */ in explain_data_prepare()
23913 assert( sqlite3_column_count(pSql)>=4 ); in explain_data_prepare()
23914 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 0), "addr" ) ); in explain_data_prepare()
23915 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 1), "opcode" ) ); in explain_data_prepare()
23916 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 2), "p1" ) ); in explain_data_prepare()
23917 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 3), "p2" ) ); in explain_data_prepare()
23928 ** different if the current instruction is part of a sub-program generated in explain_data_prepare()
23930 int p2op = (p2 + (iOp-iAddr)); in explain_data_prepare()
23932 /* Grow the p->aiIndent array as required */ in explain_data_prepare()
23935 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int)); in explain_data_prepare()
23936 shell_check_oom(p->aiIndent); in explain_data_prepare()
23942 p->aiIndent[iOp] = 0; in explain_data_prepare()
23943 p->nIndent = iOp+1; in explain_data_prepare()
23945 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; in explain_data_prepare()
23948 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; in explain_data_prepare()
23952 p->iIndent = 0; in explain_data_prepare()
23961 sqlite3_free(p->aiIndent); in explain_data_delete()
23962 p->aiIndent = 0; in explain_data_delete()
23963 p->nIndent = 0; in explain_data_delete()
23964 p->iIndent = 0; in explain_data_delete()
23980 if( pArg->scanstatsOn==3 ){ in display_scanstats()
23994 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); in display_scanstats()
23996 sqlite3_stmt *pSave = pArg->pStmt; in display_scanstats()
23997 pArg->pStmt = pStmt; in display_scanstats()
23998 sqlite3_bind_pointer(pStmt, 1, pSave, "stmt-pointer", 0); in display_scanstats()
24000 pArg->cnt = 0; in display_scanstats()
24001 pArg->cMode = MODE_ScanExp; in display_scanstats()
24007 pArg->pStmt = pSave; in display_scanstats()
24036 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode); in bind_table_init()
24037 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0); in bind_table_init()
24038 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema); in bind_table_init()
24039 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0); in bind_table_init()
24040 sqlite3_exec(p->db, in bind_table_init()
24046 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0); in bind_table_init()
24047 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0); in bind_table_init()
24070 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters", in bind_prepared_stmt()
24075 rc = sqlite3_prepare_v2(pArg->db, in bind_prepared_stmt()
24077 " WHERE key=?1", -1, &pQ, 0); in bind_prepared_stmt()
24086 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC); in bind_prepared_stmt()
24101 char *zBuf = sqlite3_malloc64( szVar-5 ); in bind_prepared_stmt()
24103 memcpy(zBuf, &zVar[6], szVar-5); in bind_prepared_stmt()
24104 sqlite3_bind_text64(pStmt, i, zBuf, szVar-6, sqlite3_free, SQLITE_UTF8); in bind_prepared_stmt()
24115 ** UTF8 box-drawing characters. Imagine box lines like this:
24119 ** 4 --+-- 2
24127 #define BOX_24 "\342\224\200" /* U+2500 --- */
24129 #define BOX_23 "\342\224\214" /* U+250c ,- */
24130 #define BOX_34 "\342\224\220" /* U+2510 -, */
24131 #define BOX_12 "\342\224\224" /* U+2514 '- */
24132 #define BOX_14 "\342\224\230" /* U+2518 -' */
24133 #define BOX_123 "\342\224\234" /* U+251c |- */
24134 #define BOX_134 "\342\224\244" /* U+2524 -| */
24135 #define BOX_234 "\342\224\254" /* U+252c -,- */
24136 #define BOX_124 "\342\224\264" /* U+2534 -'- */
24137 #define BOX_1234 "\342\224\274" /* U+253c -|- */
24146 const int nDash = sizeof(zDash) - 1; in print_box_line()
24150 N -= nDash; in print_box_line()
24167 sqlite3_fputs(zSep1, p->out); in print_box_row_separator()
24168 print_box_line(p->out, p->actualWidth[0]+2); in print_box_row_separator()
24170 sqlite3_fputs(zSep2, p->out); in print_box_row_separator()
24171 print_box_line(p->out, p->actualWidth[i]+2); in print_box_row_separator()
24173 sqlite3_fputs(zSep3, p->out); in print_box_row_separator()
24175 sqlite3_fputs("\n", p->out); in print_box_row_separator()
24194 u8 bWordWrap /* If true, avoid breaking mid-word */ in translateForDisplayAndDup()
24206 if( mxWidth<0 ) mxWidth = -mxWidth; in translateForDisplayAndDup()
24234 if( c==0x1b && p->eEscMode==SHELL_ESC_OFF && (k = isVt100(&z[i]))>0 ){ in translateForDisplayAndDup()
24245 for(k=i; k>i/2; k--){ in translateForDisplayAndDup()
24246 if( IsSpace(z[k-1]) ) break; in translateForDisplayAndDup()
24249 for(k=i; k>i/2; k--){ in translateForDisplayAndDup()
24250 if( IsAlnum(z[k-1])!=IsAlnum(z[k]) && (z[k]&0xc0)!=0x80 ) break; in translateForDisplayAndDup()
24279 do{ zOut[j++] = z[i++]; }while( (--len)>0 ); in translateForDisplayAndDup()
24297 switch( p->eEscMode ){ in translateForDisplayAndDup()
24312 i += nn - 1; in translateForDisplayAndDup()
24335 /* Extract the value of the i-th current column for pStmt as an SQL literal
24370 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
24398 int bw = p->cmOpts.bWordWrap; in exec_prepared_stmt_columnar()
24400 const char *zShowNull = p->nullValue; in exec_prepared_stmt_columnar()
24413 if( p->cmOpts.bQuote ){ in exec_prepared_stmt_columnar()
24420 if( nColumn>p->nWidth ){ in exec_prepared_stmt_columnar()
24421 p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int)); in exec_prepared_stmt_columnar()
24422 shell_check_oom(p->colWidth); in exec_prepared_stmt_columnar()
24423 for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0; in exec_prepared_stmt_columnar()
24424 p->nWidth = nColumn; in exec_prepared_stmt_columnar()
24425 p->actualWidth = &p->colWidth[nColumn]; in exec_prepared_stmt_columnar()
24427 memset(p->actualWidth, 0, nColumn*sizeof(int)); in exec_prepared_stmt_columnar()
24429 w = p->colWidth[i]; in exec_prepared_stmt_columnar()
24430 if( w<0 ) w = -w; in exec_prepared_stmt_columnar()
24431 p->actualWidth[i] = w; in exec_prepared_stmt_columnar()
24435 int wx = p->colWidth[i]; in exec_prepared_stmt_columnar()
24437 wx = p->cmOpts.iWrap; in exec_prepared_stmt_columnar()
24439 if( wx<0 ) wx = -wx; in exec_prepared_stmt_columnar()
24457 int wx = p->colWidth[i]; in exec_prepared_stmt_columnar()
24459 wx = p->cmOpts.iWrap; in exec_prepared_stmt_columnar()
24461 if( wx<0 ) wx = -wx; in exec_prepared_stmt_columnar()
24465 }else if( p->cmOpts.bQuote ){ in exec_prepared_stmt_columnar()
24466 assert( azQuoted!=0 ); in exec_prepared_stmt_columnar()
24478 abRowDiv[nRow-1] = 0; in exec_prepared_stmt_columnar()
24489 if( n>p->actualWidth[j] ) p->actualWidth[j] = n; in exec_prepared_stmt_columnar()
24492 switch( p->cMode ){ in exec_prepared_stmt_columnar()
24496 if( p->showHeader ){ in exec_prepared_stmt_columnar()
24498 w = p->actualWidth[i]; in exec_prepared_stmt_columnar()
24499 if( p->colWidth[i]<0 ) w = -w; in exec_prepared_stmt_columnar()
24500 utf8_width_print(p->out, w, azData[i]); in exec_prepared_stmt_columnar()
24501 sqlite3_fputs(i==nColumn-1?"\n":" ", p->out); in exec_prepared_stmt_columnar()
24504 print_dashes(p->out, p->actualWidth[i]); in exec_prepared_stmt_columnar()
24505 sqlite3_fputs(i==nColumn-1?"\n":" ", p->out); in exec_prepared_stmt_columnar()
24514 sqlite3_fputs("| ", p->out); in exec_prepared_stmt_columnar()
24516 w = p->actualWidth[i]; in exec_prepared_stmt_columnar()
24518 sqlite3_fprintf(p->out, "%*s%s%*s", (w-n)/2, "", in exec_prepared_stmt_columnar()
24519 azData[i], (w-n+1)/2, ""); in exec_prepared_stmt_columnar()
24520 sqlite3_fputs(i==nColumn-1?" |\n":" | ", p->out); in exec_prepared_stmt_columnar()
24528 sqlite3_fputs("| ", p->out); in exec_prepared_stmt_columnar()
24530 w = p->actualWidth[i]; in exec_prepared_stmt_columnar()
24532 sqlite3_fprintf(p->out, "%*s%s%*s", (w-n)/2, "", in exec_prepared_stmt_columnar()
24533 azData[i], (w-n+1)/2, ""); in exec_prepared_stmt_columnar()
24534 sqlite3_fputs(i==nColumn-1?" |\n":" | ", p->out); in exec_prepared_stmt_columnar()
24543 sqlite3_fputs(BOX_13 " ", p->out); in exec_prepared_stmt_columnar()
24545 w = p->actualWidth[i]; in exec_prepared_stmt_columnar()
24547 sqlite3_fprintf(p->out, "%*s%s%*s%s", in exec_prepared_stmt_columnar()
24548 (w-n)/2, "", azData[i], (w-n+1)/2, "", in exec_prepared_stmt_columnar()
24549 i==nColumn-1?" "BOX_13"\n":" "BOX_13" "); in exec_prepared_stmt_columnar()
24556 if( j==0 && p->cMode!=MODE_Column ){ in exec_prepared_stmt_columnar()
24557 sqlite3_fputs(p->cMode==MODE_Box?BOX_13" ":"| ", p->out); in exec_prepared_stmt_columnar()
24560 if( z==0 ) z = p->nullValue; in exec_prepared_stmt_columnar()
24561 w = p->actualWidth[j]; in exec_prepared_stmt_columnar()
24562 if( p->colWidth[j]<0 ) w = -w; in exec_prepared_stmt_columnar()
24563 utf8_width_print(p->out, w, z); in exec_prepared_stmt_columnar()
24564 if( j==nColumn-1 ){ in exec_prepared_stmt_columnar()
24565 sqlite3_fputs(rowSep, p->out); in exec_prepared_stmt_columnar()
24566 if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){ in exec_prepared_stmt_columnar()
24567 if( p->cMode==MODE_Table ){ in exec_prepared_stmt_columnar()
24569 }else if( p->cMode==MODE_Box ){ in exec_prepared_stmt_columnar()
24571 }else if( p->cMode==MODE_Column ){ in exec_prepared_stmt_columnar()
24572 sqlite3_fputs("\n", p->out); in exec_prepared_stmt_columnar()
24575 j = -1; in exec_prepared_stmt_columnar()
24578 sqlite3_fputs(colSep, p->out); in exec_prepared_stmt_columnar()
24581 if( p->cMode==MODE_Table ){ in exec_prepared_stmt_columnar()
24583 }else if( p->cMode==MODE_Box ){ in exec_prepared_stmt_columnar()
24588 sqlite3_fputs("Interrupt\n", p->out); in exec_prepared_stmt_columnar()
24614 if( pArg->cMode==MODE_Column in exec_prepared_stmt()
24615 || pArg->cMode==MODE_Table in exec_prepared_stmt()
24616 || pArg->cMode==MODE_Box in exec_prepared_stmt()
24617 || pArg->cMode==MODE_Markdown in exec_prepared_stmt()
24639 assert(sizeof(int) <= sizeof(char *)); in exec_prepared_stmt()
24651 && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote) in exec_prepared_stmt()
24674 if( pArg->cMode==MODE_Json ){ in exec_prepared_stmt()
24675 sqlite3_fputs("]\n", pArg->out); in exec_prepared_stmt()
24676 }else if( pArg->cMode==MODE_Www ){ in exec_prepared_stmt()
24677 sqlite3_fputs("</TABLE>\n<PRE>\n", pArg->out); in exec_prepared_stmt()
24678 }else if( pArg->cMode==MODE_Count ){ in exec_prepared_stmt()
24704 assert( pState->expert.pExpert ); in expertHandleSQL()
24705 assert( pzErr==0 || *pzErr==0 ); in expertHandleSQL()
24706 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr); in expertHandleSQL()
24725 sqlite3expert *p = pState->expert.pExpert; in expertFinish()
24726 FILE *out = pState->out; in expertFinish()
24727 assert( p ); in expertFinish()
24728 assert( bCancel || pzErr==0 || *pzErr==0 ); in expertFinish()
24730 int bVerbose = pState->expert.bVerbose; in expertFinish()
24739 sqlite3_fputs("-- Candidates -----------------------------\n", out); in expertFinish()
24749 "-- Query %d --------------------------------\n" in expertFinish()
24758 pState->expert.pExpert = 0; in expertFinish()
24775 assert( pState->expert.pExpert==0 ); in expertDotCommand()
24776 memset(&pState->expert, 0, sizeof(ExpertInfo)); in expertDotCommand()
24781 if( z[0]=='-' && z[1]=='-' ) z++; in expertDotCommand()
24783 if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){ in expertDotCommand()
24784 pState->expert.bVerbose = 1; in expertDotCommand()
24786 else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){ in expertDotCommand()
24787 if( i==(nArg-1) ){ in expertDotCommand()
24805 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr); in expertDotCommand()
24806 if( pState->expert.pExpert==0 ){ in expertDotCommand()
24812 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample in expertDotCommand()
24827 ** This is very similar to SQLite's built-in sqlite3_exec()
24840 sqlite3 *db = pArg->db; in shell_exec()
24847 if( pArg->expert.pExpert ){ in shell_exec()
24855 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); in shell_exec()
24862 /* this happens for a comment or white-space */ in shell_exec()
24871 /* save off the prepared statement handle and reset row count */ in shell_exec()
24873 pArg->pStmt = pStmt; in shell_exec()
24874 pArg->cnt = 0; in shell_exec()
24878 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){ in shell_exec()
24882 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP); in shell_exec()
24883 if( pArg->autoEQP>=AUTOEQP_trigger ){ in shell_exec()
24896 if( zEQPLine[0]=='-' ) eqp_render(pArg, 0); in shell_exec()
24901 if( pArg->autoEQP>=AUTOEQP_full ){ in shell_exec()
24906 pArg->cMode = MODE_Explain; in shell_exec()
24907 assert( sqlite3_stmt_isexplain(pExplain)==1 ); in shell_exec()
24914 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){ in shell_exec()
24924 pArg->cMode = pArg->mode; in shell_exec()
24925 if( pArg->autoExplain ){ in shell_exec()
24927 pArg->cMode = MODE_Explain; in shell_exec()
24930 pArg->cMode = MODE_EQP; in shell_exec()
24936 if( pArg->cMode==MODE_Explain && bIsExplain ){ in shell_exec()
24947 if( pArg && pArg->statsOn ){ in shell_exec()
24951 /* print loop-counters if required */ in shell_exec()
24952 if( pArg && pArg->scanstatsOn ){ in shell_exec()
24970 pArg->pStmt = NULL; in shell_exec()
25016 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in tableColumnList()
25020 if( nCol>=nAlloc-2 ){ in tableColumnList()
25061 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in tableColumnList()
25085 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0); in tableColumnList()
25101 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0); in toggleSelectOrder()
25133 dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0; in dump_callback()
25134 noSys = (p->shellFlgs & SHFLG_DumpNoSys)!=0; in dump_callback()
25137 /* no-op */ in dump_callback()
25139 if( !dataOnly ) sqlite3_fputs("ANALYZE sqlite_schema;\n", p->out); in dump_callback()
25143 /* no-op */ in dump_callback()
25146 if( !p->writableSchema ){ in dump_callback()
25147 sqlite3_fputs("PRAGMA writable_schema=ON;\n", p->out); in dump_callback()
25148 p->writableSchema = 1; in dump_callback()
25155 sqlite3_fprintf(p->out, "%s\n", zIns); in dump_callback()
25159 printSchemaLine(p->out, zSql, ";\n"); in dump_callback()
25172 p->nErr++; in dump_callback()
25211 savedDestTable = p->zDestTable; in dump_callback()
25212 savedMode = p->mode; in dump_callback()
25213 p->zDestTable = sTable.z; in dump_callback()
25214 p->mode = p->cMode = MODE_Insert; in dump_callback()
25217 sqlite3_fputs("/****** CORRUPTION ERROR *******/\n", p->out); in dump_callback()
25218 toggleSelectOrder(p->db); in dump_callback()
25220 toggleSelectOrder(p->db); in dump_callback()
25222 p->zDestTable = savedDestTable; in dump_callback()
25223 p->mode = savedMode; in dump_callback()
25226 if( rc ) p->nErr++; in dump_callback()
25244 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); in run_schema_dump_query()
25248 sqlite3_fputs("/****** CORRUPTION ERROR *******/\n", p->out); in run_schema_dump_query()
25250 sqlite3_fprintf(p->out, "/****** %s ******/\n", zErr); in run_schema_dump_query()
25257 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); in run_schema_dump_query()
25259 sqlite3_fprintf(p->out, "/****** ERROR: %s ******/\n", zErr); in run_schema_dump_query()
25283 " -c, --create Create a new archive",
25284 " -u, --update Add or update files with changed mtime",
25285 " -i, --insert Like -u but always add even if unchanged",
25286 " -r, --remove Remove files from archive",
25287 " -t, --list List contents of archive",
25288 " -x, --extract Extract files from archive",
25290 " -v, --verbose Print each filename as it is processed",
25291 " -f FILE, --file FILE Use archive FILE (default is current db)",
25292 " -a FILE, --append FILE Open FILE using the apndvfs VFS",
25293 " -C DIR, --directory DIR Read/extract files from directory DIR",
25294 " -g, --glob Use glob matching for names in archive",
25295 " -n, --dryrun Show the SQL that would have occurred",
25297 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
25298 " .ar -tf ARCHIVE # List members of ARCHIVE",
25299 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
25309 " --append Use the appendvfs",
25310 " --async Write to FILE without journal and fsync()",
25331 " --data-only Output only INSERT statements",
25332 " --newlines Allow unescaped newline characters in output",
25333 " --nosys Omit system tables (ex: \"sqlite_stat1\")",
25334 " --preserve-rowids Include ROWID values in the output",
25347 " --bom Put a UTF8 byte-order mark on intermediate file",
25350 ".exit ?CODE? Exit this program with return-code CODE",
25355 " --schema SCHEMA Use SCHEMA instead of \"main\"",
25356 " --help Show CMD details",
25357 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
25359 ".help ?-all? ?PATTERN? Show help text for PATTERN",
25363 " --ascii Use \\037 and \\036 as column and row separators",
25364 " --csv Use , and \\n as column and row separators",
25365 " --skip N Skip the first N rows of input",
25366 " --schema S Target table to be S.TABLE",
25367 " -v \"Verbose\" - increase auxiliary output",
25371 " * If neither --csv or --ascii are used, the input mode is derived",
25389 " fkey-indexes Find missing foreign key indexes",
25401 " box Tables using unicode box-drawing characters",
25402 " csv Comma-separated values",
25410 " qbox Shorthand for \"box --wrap 60 --quote\"",
25412 " table ASCII-art table",
25413 " tabs Tab-separated values",
25416 " --escape T ctrl-char escape; T is one of: symbol, ascii, off",
25417 " --wrap N Wrap output lines to no longer than N characters",
25418 " --wordwrap B Wrap or not at word boundaries per B (on/off)",
25419 " --ww Shorthand for \"--wordwrap 1\"",
25420 " --quote Quote output text as SQL literals",
25421 " --noquote Do not quote output text",
25430 " --bom Put a UTF8 byte-order mark at the beginning",
25431 " -e Send output to the system text editor",
25432 " --plain Use text/plain output instead of HTML for -w option",
25433 " -w Send output as HTML to a web browser (same as \".www\")",
25434 " -x Send output as CSV to a spreadsheet (same as \".excel\")",
25440 " --append Use appendvfs to append database to the end of FILE",
25443 " --deserialize Load into memory using sqlite3_deserialize()",
25444 " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
25445 " --maxsize N Maximum size for --hexdb or --deserialized database",
25447 " --new Initialize FILE to an empty database",
25448 " --nofollow Do not follow symbolic links",
25449 " --readonly Open FILE readonly",
25450 " --zip FILE is a ZIP archive",
25456 " --bom Prefix output with a UTF8 byte-order mark",
25457 " -e Send output to the system text editor",
25458 " --plain Use text/plain for -w option",
25459 " -w Send output to a web browser",
25460 " -x Send output as CSV to a spreadsheet",
25472 " --limit N Interrupt after N progress callbacks",
25473 " --once Do no more than one progress interrupt",
25474 " --quiet|-q No output except at interrupts",
25475 " --reset Reset the count for each input and interrupt",
25485 " --ignore-freelist Ignore pages that appear to be on db freelist",
25486 " --lost-and-found TABLE Alternative name for the lost-and-found table",
25487 " --no-rowids Do not attempt to recover rowid values",
25497 " --indent Try to pretty-print the schema",
25498 " --nosys Omit objects whose names start with \"sqlite_\"",
25501 " --init Create a new SELFTEST table",
25502 " -v Verbose output",
25521 " --schema Also hash the sqlite_schema table",
25522 " --sha3-224 Use the sha3-224 algorithm",
25523 " --sha3-256 Use the sha3-256 algorithm (default)",
25524 " --sha3-384 Use the sha3-384 algorithm",
25525 " --sha3-512 Use the sha3-512 algorithm",
25541 ",testcase NAME Begin redirecting output to 'testcase-out.txt'",
25545 ".timeout MS Try opening locked tables for MS milliseconds",
25553 " --expanded Expand query parameters",
25555 " --normalized Normal the SQL statements",
25557 " --plain Show SQL as it is input",
25558 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
25559 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
25560 " --row Trace each row (SQLITE_TRACE_ROW)",
25561 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
25565 " --allexcept Unregister everything except those named",
25568 ".vfsinfo ?AUX? Information about the top-level VFS",
25572 " Negative values right-justify",
25575 " --plain Show results as text/plain, not as HTML",
25583 ** only give a one-line summary of each.
25585 ** * If zPattern is "-a" or "-all" or "--all" then show all help text
25610 zPattern = "[a-z]"; in showHelp()
25611 }else if( cli_strcmp(zPattern,"-a")==0 in showHelp()
25612 || cli_strcmp(zPattern,"-all")==0 in showHelp()
25613 || cli_strcmp(zPattern,"--all")==0 in showHelp()
25649 while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){ in showHelp()
25663 while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i; in showHelp()
25669 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){ in showHelp()
25692 ** For convenience, a nul-terminator byte is always appended to the data read
25739 sqlite3session_delete(pSession->p); in session_close()
25740 sqlite3_free(pSession->zName); in session_close()
25741 for(i=0; i<pSession->nFilter; i++){ in session_close()
25742 sqlite3_free(pSession->azFilter[i]); in session_close()
25744 sqlite3_free(pSession->azFilter); in session_close()
25755 struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i]; in session_close_all()
25756 for(j=0; j<pAuxDb->nSession; j++){ in session_close_all()
25757 session_close(&pAuxDb->aSession[j]); in session_close_all()
25759 pAuxDb->nSession = 0; in session_close_all()
25773 for(i=0; i<pSession->nFilter; i++){ in session_filter()
25774 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0; in session_filter()
25806 fseek(f, -25, SEEK_END); in deduceDatabaseType()
25808 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){ in deduceDatabaseType()
25811 fseek(f, -22, SEEK_END); in deduceDatabaseType()
25826 ** Reconstruct an in-memory database using the output from the "dbtotxt"
25827 ** program. Read content from the file in p->aAuxDb[].zDbFilename.
25828 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
25839 const char *zDbFilename = p->pAuxDb->zDbFilename; in readHexDb()
25850 in = p->in; in readHexDb()
25851 nLine = p->lineno; in readHexDb()
25860 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error; in readHexDb()
25861 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */ in readHexDb()
25865 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){ in readHexDb()
25890 if( in!=p->in ){ in readHexDb()
25893 p->lineno = nLine; in readHexDb()
25898 if( in!=p->in ){ in readHexDb()
25901 while( sqlite3_fgets(zLine, sizeof(zLine), p->in)!=0 ){ in readHexDb()
25905 p->lineno = nLine; in readHexDb()
25908 sqlite3_fprintf(stderr,"Error on line %d of --hexdb input\n", nLine); in readHexDb()
25930 ** Return a fake schema for the table-valued function or eponymous virtual
25941 FILE *pSavedLog = p->pLog; in shellModuleSchema()
25949 p->pLog = 0; in shellModuleSchema()
25951 p->pLog = pSavedLog; in shellModuleSchema()
25955 -1, sqlite3_free); in shellModuleSchema()
25978 if( p->db==0 ){ in open_db()
25979 const char *zDbFilename = p->pAuxDb->zDbFilename; in open_db()
25980 if( p->openMode==SHELL_OPEN_UNSPEC ){ in open_db()
25982 p->openMode = SHELL_OPEN_NORMAL; in open_db()
25984 p->openMode = (u8)deduceDatabaseType(zDbFilename, in open_db()
25988 switch( p->openMode ){ in open_db()
25990 sqlite3_open_v2(zDbFilename, &p->db, in open_db()
25991 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs"); in open_db()
25996 sqlite3_open(0, &p->db); in open_db()
26000 sqlite3_open(":memory:", &p->db); in open_db()
26004 sqlite3_open_v2(zDbFilename, &p->db, in open_db()
26005 SQLITE_OPEN_READONLY|p->openFlags, 0); in open_db()
26010 sqlite3_open_v2(zDbFilename, &p->db, in open_db()
26011 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0); in open_db()
26015 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ in open_db()
26017 zDbFilename, sqlite3_errmsg(p->db)); in open_db()
26021 sqlite3_close(p->db); in open_db()
26022 sqlite3_open(":memory:", &p->db); in open_db()
26023 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ in open_db()
26024 sqlite3_fputs("Also: unable to open substitute in-memory database.\n", in open_db()
26029 "Notice: using substitute in-memory database instead of \"%s\"\n", in open_db()
26033 globalDb = p->db; in open_db()
26034 sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0); in open_db()
26036 /* Reflect the use or absence of --unsafe-testing invocation. */ in open_db()
26039 sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0); in open_db()
26040 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0); in open_db()
26044 sqlite3_enable_load_extension(p->db, 1); in open_db()
26046 sqlite3_sha_init(p->db, 0, 0); in open_db()
26047 sqlite3_shathree_init(p->db, 0, 0); in open_db()
26048 sqlite3_uint_init(p->db, 0, 0); in open_db()
26049 sqlite3_stmtrand_init(p->db, 0, 0); in open_db()
26050 sqlite3_decimal_init(p->db, 0, 0); in open_db()
26051 sqlite3_percentile_init(p->db, 0, 0); in open_db()
26052 sqlite3_base64_init(p->db, 0, 0); in open_db()
26053 sqlite3_base85_init(p->db, 0, 0); in open_db()
26054 sqlite3_regexp_init(p->db, 0, 0); in open_db()
26055 sqlite3_ieee_init(p->db, 0, 0); in open_db()
26056 sqlite3_series_init(p->db, 0, 0); in open_db()
26058 sqlite3_fileio_init(p->db, 0, 0); in open_db()
26059 sqlite3_completion_init(p->db, 0, 0); in open_db()
26062 if( !p->bSafeModePersist ){ in open_db()
26063 sqlite3_zipfile_init(p->db, 0, 0); in open_db()
26064 sqlite3_sqlar_init(p->db, 0, 0); in open_db()
26070 * This is a short-span macro. See further below for usage. in open_db()
26074 /* Let custom-included extensions get their ..._init() called. in open_db()
26080 int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db); in open_db()
26081 /* Let custom-included extensions expose their functionality. in open_db()
26088 SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0); in open_db()
26095 sqlite3_create_function(p->db, "strtod", 1, SQLITE_UTF8, 0, in open_db()
26097 sqlite3_create_function(p->db, "dtostr", 1, SQLITE_UTF8, 0, in open_db()
26099 sqlite3_create_function(p->db, "dtostr", 2, SQLITE_UTF8, 0, in open_db()
26101 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0, in open_db()
26103 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, p, in open_db()
26105 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p, in open_db()
26107 sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0, in open_db()
26110 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0, in open_db()
26112 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0, in open_db()
26116 if( p->openMode==SHELL_OPEN_ZIPFILE ){ in open_db()
26120 sqlite3_exec(p->db, zSql, 0, 0, 0); in open_db()
26125 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){ in open_db()
26129 if( p->openMode==SHELL_OPEN_DESERIALIZE ){ in open_db()
26137 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData, in open_db()
26143 if( p->szMax>0 ){ in open_db()
26144 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax); in open_db()
26149 if( p->db!=0 ){ in open_db()
26150 if( p->bSafeModePersist ){ in open_db()
26151 sqlite3_set_authorizer(p->db, safeModeAuth, p); in open_db()
26154 p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0 in open_db()
26184 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); in readline_completion_generator()
26225 if( nLine>(i64)sizeof(zBuf)-30 ) return; in linenoise_completion()
26227 for(i=nLine-1; i>=0 && (IsAlnum(zLine[i]) || zLine[i]=='_'); i--){} in linenoise_completion()
26228 if( i==nLine-1 ) return; in linenoise_completion()
26235 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); in linenoise_completion()
26241 if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){ in linenoise_completion()
26251 ** Do C-language style dequoting.
26253 ** \a -> alarm
26254 ** \b -> backspace
26255 ** \t -> tab
26256 ** \n -> newline
26257 ** \v -> vertical tab
26258 ** \f -> form feed
26259 ** \r -> carriage return
26260 ** \s -> space
26261 ** \" -> "
26262 ** \' -> '
26263 ** \\ -> backslash
26264 ** \NNN -> ascii character NNN in octal
26265 ** \xHH -> ascii character HH in hexadecimal
26304 c -= '0'; in resolve_backslashes()
26307 c = (c<<3) + z[i] - '0'; in resolve_backslashes()
26310 c = (c<<3) + z[i] - '0'; in resolve_backslashes()
26397 if( p->traceOut==0 ) return 0; in sql_trace_callback()
26399 sputz(p->traceOut, "-- closing database connection\n"); in sql_trace_callback()
26402 if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){ in sql_trace_callback()
26406 switch( p->eTraceType ){ in sql_trace_callback()
26426 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; } in sql_trace_callback()
26430 sqlite3_fprintf(p->traceOut, "%.*s;\n", (int)nSql, zSql); in sql_trace_callback()
26435 sqlite3_fprintf(p->traceOut, in sql_trace_callback()
26436 "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec); in sql_trace_callback()
26445 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
26478 if( p->in!=0 && p->xCloser!=0 ){ in import_cleanup()
26479 p->xCloser(p->in); in import_cleanup()
26480 p->in = 0; in import_cleanup()
26482 sqlite3_free(p->z); in import_cleanup()
26483 p->z = 0; in import_cleanup()
26488 if( p->n+1>=p->nAlloc ){ in import_append_char()
26489 p->nAlloc += p->nAlloc + 100; in import_append_char()
26490 p->z = sqlite3_realloc64(p->z, p->nAlloc); in import_append_char()
26491 shell_check_oom(p->z); in import_append_char()
26493 p->z[p->n++] = (char)c; in import_append_char()
26499 ** + Input comes from p->in.
26500 ** + Store results in p->z of length p->n. Space to hold p->z comes
26502 ** + Use p->cSep as the column separator. The default is ",".
26503 ** + Use p->rSep as the row separator. The default is "\n".
26504 ** + Keep track of the line number in p->nLine.
26505 ** + Store the character that terminates the field in p->cTerm. Store
26506 ** EOF on end-of-file.
26511 int cSep = (u8)p->cColSep; in csv_read_one_field()
26512 int rSep = (u8)p->cRowSep; in csv_read_one_field()
26513 p->n = 0; in csv_read_one_field()
26514 c = fgetc(p->in); in csv_read_one_field()
26516 p->cTerm = EOF; in csv_read_one_field()
26521 int startLine = p->nLine; in csv_read_one_field()
26525 c = fgetc(p->in); in csv_read_one_field()
26526 if( c==rSep ) p->nLine++; in csv_read_one_field()
26538 do{ p->n--; }while( p->z[p->n]!=cQuote ); in csv_read_one_field()
26539 p->cTerm = c; in csv_read_one_field()
26544 p->zFile, p->nLine, cQuote); in csv_read_one_field()
26547 sqlite3_fprintf(stderr,"%s:%d: unterminated %c-quoted field\n", in csv_read_one_field()
26548 p->zFile, startLine, cQuote); in csv_read_one_field()
26549 p->cTerm = c; in csv_read_one_field()
26558 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ in csv_read_one_field()
26559 if( (c&0xff)==0xef && p->bNotFirst==0 ){ in csv_read_one_field()
26561 c = fgetc(p->in); in csv_read_one_field()
26564 c = fgetc(p->in); in csv_read_one_field()
26566 p->bNotFirst = 1; in csv_read_one_field()
26567 p->n = 0; in csv_read_one_field()
26574 c = fgetc(p->in); in csv_read_one_field()
26577 p->nLine++; in csv_read_one_field()
26578 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; in csv_read_one_field()
26580 p->cTerm = c; in csv_read_one_field()
26582 if( p->z ) p->z[p->n] = 0; in csv_read_one_field()
26583 p->bNotFirst = 1; in csv_read_one_field()
26584 return p->z; in csv_read_one_field()
26589 ** + Input comes from p->in.
26590 ** + Store results in p->z of length p->n. Space to hold p->z comes
26592 ** + Use p->cSep as the column separator. The default is "\x1F".
26593 ** + Use p->rSep as the row separator. The default is "\x1E".
26594 ** + Keep track of the row number in p->nLine.
26595 ** + Store the character that terminates the field in p->cTerm. Store
26596 ** EOF on end-of-file.
26601 int cSep = (u8)p->cColSep; in ascii_read_one_field()
26602 int rSep = (u8)p->cRowSep; in ascii_read_one_field()
26603 p->n = 0; in ascii_read_one_field()
26604 c = fgetc(p->in); in ascii_read_one_field()
26606 p->cTerm = EOF; in ascii_read_one_field()
26611 c = fgetc(p->in); in ascii_read_one_field()
26614 p->nLine++; in ascii_read_one_field()
26616 p->cTerm = c; in ascii_read_one_field()
26617 if( p->z ) p->z[p->n] = 0; in ascii_read_one_field()
26618 return p->z; in ascii_read_one_field()
26644 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); in tryToCloneData()
26647 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery); in tryToCloneData()
26661 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0); in tryToCloneData()
26686 -1, SQLITE_STATIC); in tryToCloneData()
26705 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]); in tryToCloneData()
26715 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); in tryToCloneData()
26752 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); in tryToCloneSchema()
26755 "Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db), in tryToCloneSchema()
26756 sqlite3_errmsg(p->db), zQuery); in tryToCloneSchema()
26783 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); in tryToCloneSchema()
26786 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery); in tryToCloneSchema()
26829 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); in tryToClone()
26834 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); in tryToClone()
26844 if( p->out != stdout ){ in output_redir()
26847 p->out = pfNew; in output_redir()
26849 if( p->mode==MODE_Www ){ in output_redir()
26853 p->out in output_redir()
26862 ** If the p->doXdgOpen flag is set, that means the output was being
26863 ** redirected to a temporary file named by p->zTempFile. In that case,
26864 ** launch start/open/xdg-open on that temporary file.
26867 if( p->outfile[0]=='|' ){ in output_reset()
26869 pclose(p->out); in output_reset()
26872 if( p->mode==MODE_Www ){ in output_reset()
26873 sqlite3_fputs("</PRE></BODY></HTML>\n", p->out); in output_reset()
26875 output_file_close(p->out); in output_reset()
26877 if( p->doXdgOpen ){ in output_reset()
26884 "xdg-open"; in output_reset()
26887 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile); in output_reset()
26891 /* Give the start/open/xdg-open command some time to get in output_reset()
26893 ** p->zTempFile data file out from under it */ in output_reset()
26898 p->doXdgOpen = 0; in output_reset()
26902 p->outfile[0] = 0; in output_reset()
26903 p->out = stdout; in output_reset()
26922 sqlite3_prepare_v2(db, z, -1, &pStmt, 0); in db_int()
26933 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
26981 if( p->db==0 ) return 1; in shell_dbinfo_command()
26982 rc = sqlite3_prepare_v2(p->db, in shell_dbinfo_command()
26984 -1, &pStmt, 0); in shell_dbinfo_command()
26986 sqlite3_fprintf(stderr,"error: %s\n", sqlite3_errmsg(p->db)); in shell_dbinfo_command()
26990 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC); in shell_dbinfo_command()
27005 sqlite3_fprintf(p->out, "%-20s %d\n", "database page size:", i); in shell_dbinfo_command()
27006 sqlite3_fprintf(p->out, "%-20s %d\n", "write format:", aHdr[18]); in shell_dbinfo_command()
27007 sqlite3_fprintf(p->out, "%-20s %d\n", "read format:", aHdr[19]); in shell_dbinfo_command()
27008 sqlite3_fprintf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]); in shell_dbinfo_command()
27012 sqlite3_fprintf(p->out, "%-20s %u", aField[i].zName, val); in shell_dbinfo_command()
27015 if( val==1 ) sqlite3_fputs(" (utf8)", p->out); in shell_dbinfo_command()
27016 if( val==2 ) sqlite3_fputs(" (utf16le)", p->out); in shell_dbinfo_command()
27017 if( val==3 ) sqlite3_fputs(" (utf16be)", p->out); in shell_dbinfo_command()
27020 sqlite3_fputs("\n", p->out); in shell_dbinfo_command()
27030 int val = db_int(p->db, aQuery[i].zSql, zSchemaTab); in shell_dbinfo_command()
27031 sqlite3_fprintf(p->out, "%-20s %d\n", aQuery[i].zName, val); in shell_dbinfo_command()
27034 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion); in shell_dbinfo_command()
27035 sqlite3_fprintf(p->out, "%-20s %u\n", "data version", iDataVersion); in shell_dbinfo_command()
27060 rc = sqlite3_prepare_v2(p->db, "PRAGMA page_size", -1, &pStmt, 0); in shell_dbtotxt_command()
27067 if( pgSz<512 || pgSz>65536 || (pgSz&(pgSz-1))!=0 ) goto dbtotxt_error; in shell_dbtotxt_command()
27068 rc = sqlite3_prepare_v2(p->db, "PRAGMA page_count", -1, &pStmt, 0); in shell_dbtotxt_command()
27076 rc = sqlite3_prepare_v2(p->db, "PRAGMA databases", -1, &pStmt, 0); in shell_dbtotxt_command()
27090 sqlite3_fprintf(p->out, "| size %lld pagesize %d filename %s\n", in shell_dbtotxt_command()
27094 rc = sqlite3_prepare_v2(p->db, in shell_dbtotxt_command()
27095 "SELECT pgno, data FROM sqlite_dbpage ORDER BY pgno", -1, &pStmt, 0); in shell_dbtotxt_command()
27106 sqlite3_fprintf(p->out, "| page %lld offset %lld\n",pgno,(pgno-1)*pgSz); in shell_dbtotxt_command()
27109 sqlite3_fprintf(p->out, "| %5d:", i); in shell_dbtotxt_command()
27110 for(j=0; j<16; j++) sqlite3_fprintf(p->out, " %02x", aLine[j]); in shell_dbtotxt_command()
27111 sqlite3_fprintf(p->out, " "); in shell_dbtotxt_command()
27114 sqlite3_fprintf(p->out, "%c", bShow[c]); in shell_dbtotxt_command()
27116 sqlite3_fprintf(p->out, "\n"); in shell_dbtotxt_command()
27120 sqlite3_fprintf(p->out, "| end %s\n", zName); in shell_dbtotxt_command()
27126 sqlite3_fprintf(stderr, "ERROR: %s\n", sqlite3_errmsg(p->db)); in shell_dbtotxt_command()
27163 ** optional + or - sign in front
27187 while( *z && testcase_glob(zGlob-1,z)==0 ){ in testcase_glob()
27218 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ in testcase_glob()
27232 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++; in testcase_glob()
27246 ** Compare the string as a command-line option with either one or two
27247 ** initial "-" characters.
27250 if( zStr[0]!='-' ) return 0; in optionMatch()
27252 if( zStr[0]=='-' ) zStr++; in optionMatch()
27276 if( p->zTempFile==0 ) return; in clearTempFile()
27277 if( p->doXdgOpen ) return; in clearTempFile()
27278 if( shellDeleteFile(p->zTempFile) ) return; in clearTempFile()
27279 sqlite3_free(p->zTempFile); in clearTempFile()
27280 p->zTempFile = 0; in clearTempFile()
27288 sqlite3_free(p->zTempFile); in newTempFile()
27289 p->zTempFile = 0; in newTempFile()
27290 if( p->db ){ in newTempFile()
27291 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile); in newTempFile()
27293 if( p->zTempFile==0 ){ in newTempFile()
27294 /* If p->db is an in-memory database then the TEMPFILENAME file-control in newTempFile()
27308 p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix); in newTempFile()
27310 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix); in newTempFile()
27312 shell_check_oom(p->zTempFile); in newTempFile()
27318 ** by the ".lint fkey-indexes" command. This scalar function is always
27319 ** called with four arguments - the parent table name, the parent column name,
27322 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
27328 ** function returns the string " COLLATE <parent-collation>", where
27329 ** <parent-collation> is the default collation sequence of the parent column.
27342 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */ in shellFkeyCollateClause()
27345 assert( nVal==4 ); in shellFkeyCollateClause()
27351 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); in shellFkeyCollateClause()
27363 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); in shellFkeyCollateClause()
27370 ** The implementation of dot-command ".lint fkey-indexes".
27377 sqlite3 *db = pState->db; /* Database handle to query "main" db of */ in lintFkeyIndexes()
27378 int bVerbose = 0; /* If -verbose is present */ in lintFkeyIndexes()
27379 int bGroupByParent = 0; /* If -groupbyparent is present */ in lintFkeyIndexes()
27384 FILE *out = pState->out; /* Send output here */ in lintFkeyIndexes()
27444 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) " in lintFkeyIndexes()
27452 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){ in lintFkeyIndexes()
27455 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){ in lintFkeyIndexes()
27461 "Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1]); in lintFkeyIndexes()
27473 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); in lintFkeyIndexes()
27483 int res = -1; in lintFkeyIndexes()
27494 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); in lintFkeyIndexes()
27512 sqlite3_fprintf(out, "-- Parent table %s\n", zParent); in lintFkeyIndexes()
27518 sqlite3_fprintf(out, "%s%s --> %s\n", zIndent, zCI, zTarget); in lintFkeyIndexes()
27521 "%s/* no extra indexes required for %s -> %s */\n", in lintFkeyIndexes()
27555 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage; in lintDotCommand()
27559 sqlite3_fprintf(stderr,"Usage %s sub-command ?switches...?\n", azArg[0]); in lintDotCommand()
27560 sqlite3_fprintf(stderr, "Where sub-commands are:\n"); in lintDotCommand()
27561 sqlite3_fprintf(stderr, " fkey-indexes\n"); in lintDotCommand()
27573 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); in shellPrepare()
27583 ** Create a prepared statement using printf-style arguments for the SQL.
27628 /* Reset the prepared statement created using shellPreparePrintf().
27631 ** depending on compile-time options. By omitting the "static", we avoid
27659 u8 bVerbose; /* True if --verbose */
27661 u8 bDryRun; /* True if --dry-run */
27662 u8 bAppend; /* True if --append */
27663 u8 bGlob; /* True if --glob */
27664 u8 fromCmdLine; /* Run from -A instead of .archive */
27667 const char *zFile; /* --file argument, or NULL */
27668 const char *zDir; /* --directory argument, or NULL */
27694 if( pAr->fromCmdLine ){ in arErrorMsg()
27695 sqlite3_fputs("Use \"-A\" for more help\n", stderr); in arErrorMsg()
27697 sqlite3_fputs("Use \".archive --help\" for more help\n", stderr); in arErrorMsg()
27715 ** Other (non-command) switches.
27733 if( pAr->eCmd ){ in arProcessSwitch()
27736 pAr->eCmd = eSwitch; in arProcessSwitch()
27740 pAr->bDryRun = 1; in arProcessSwitch()
27743 pAr->bGlob = 1; in arProcessSwitch()
27746 pAr->bVerbose = 1; in arProcessSwitch()
27749 pAr->bAppend = 1; in arProcessSwitch()
27752 pAr->zFile = zArg; in arProcessSwitch()
27755 pAr->zDir = zArg; in arProcessSwitch()
27801 if( z[0]!='-' ){ in arParseCommand()
27809 if( z[i]==pOpt->cShort ) break; in arParseCommand()
27814 if( pOpt->bArg ){ in arParseCommand()
27820 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; in arParseCommand()
27822 pAr->nArg = nArg-iArg; in arParseCommand()
27823 if( pAr->nArg>0 ){ in arParseCommand()
27824 pAr->azArg = &azArg[iArg]; in arParseCommand()
27827 /* Non-traditional invocation */ in arParseCommand()
27832 if( z[0]!='-' ){ in arParseCommand()
27834 pAr->azArg = &azArg[iArg]; in arParseCommand()
27835 pAr->nArg = nArg-iArg; in arParseCommand()
27840 if( z[1]!='-' ){ in arParseCommand()
27847 if( z[i]==pOpt->cShort ) break; in arParseCommand()
27852 if( pOpt->bArg ){ in arParseCommand()
27853 if( i<(n-1) ){ in arParseCommand()
27857 if( iArg>=(nArg-1) ){ in arParseCommand()
27864 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; in arParseCommand()
27867 /* A -- option, indicating that all remaining command line words in arParseCommand()
27869 pAr->azArg = &azArg[iArg+1]; in arParseCommand()
27870 pAr->nArg = nArg-iArg-1; in arParseCommand()
27878 const char *zLong = pOpt->zLong; in arParseCommand()
27879 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){ in arParseCommand()
27891 if( pMatch->bArg ){ in arParseCommand()
27892 if( iArg>=(nArg-1) ){ in arParseCommand()
27897 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR; in arParseCommand()
27902 if( pAr->eCmd==0 ){ in arParseCommand()
27911 ** array refer to archive members, as for the --extract, --list or --remove
27916 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
27917 ** when pAr->bGlob is true.
27925 if( pAr->nArg ){ in arCheckEntries()
27928 const char *zSel = (pAr->bGlob) in arCheckEntries()
27932 shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable); in arCheckEntries()
27934 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ in arCheckEntries()
27935 char *z = pAr->azArg[i]; in arCheckEntries()
27938 while( n>0 && z[n-1]=='/' ) n--; in arCheckEntries()
27940 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC); in arCheckEntries()
27960 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
27961 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
27969 const char *zSameOp = (pAr->bGlob)? "GLOB" : "="; in arWhereClause()
27971 if( pAr->nArg==0 ){ in arWhereClause()
27976 for(i=0; i<pAr->nArg; i++){ in arWhereClause()
27977 const char *z = pAr->azArg[i]; in arWhereClause()
28010 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose], in arListCommand()
28011 pAr->zSrcTable, zWhere); in arListCommand()
28012 if( pAr->bDryRun ){ in arListCommand()
28013 sqlite3_fprintf(pAr->out, "%s\n", sqlite3_sql(pSql)); in arListCommand()
28016 if( pAr->bVerbose ){ in arListCommand()
28017 sqlite3_fprintf(pAr->out, "%s % 10d %s %s\n", in arListCommand()
28021 sqlite3_fprintf(pAr->out, "%s\n", sqlite3_column_text(pSql, 0)); in arListCommand()
28038 if( pAr->nArg ){ in arRemoveCommand()
28046 pAr->zSrcTable, zWhere); in arRemoveCommand()
28047 if( pAr->bDryRun ){ in arRemoveCommand()
28048 sqlite3_fprintf(pAr->out, "%s\n", zSql); in arRemoveCommand()
28051 rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0); in arRemoveCommand()
28053 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); in arRemoveCommand()
28055 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); in arRemoveCommand()
28057 rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0); in arRemoveCommand()
28100 if( pAr->zDir ){ in arExtractCommand()
28101 zDir = sqlite3_mprintf("%s/", pAr->zDir); in arExtractCommand()
28108 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, in arExtractCommand()
28109 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere in arExtractCommand()
28114 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC); in arExtractCommand()
28116 /* Run the SELECT statement twice. The first time, writefile() is called in arExtractCommand()
28117 ** for all archive members that should be extracted. The second time, in arExtractCommand()
28119 ** extracted directories must be reset after they are populated (as in arExtractCommand()
28124 if( pAr->bDryRun ){ in arExtractCommand()
28125 sqlite3_fprintf(pAr->out, "%s\n", sqlite3_sql(pSql)); in arExtractCommand()
28128 if( i==0 && pAr->bVerbose ){ in arExtractCommand()
28129 sqlite3_fprintf(pAr->out, "%s\n", sqlite3_column_text(pSql, 0)); in arExtractCommand()
28144 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
28148 if( pAr->bDryRun ){ in arExecSql()
28149 sqlite3_fprintf(pAr->out, "%s\n", zSql); in arExecSql()
28153 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); in arExecSql()
28166 ** create -> Create a new SQL archive
28167 ** insert -> Insert or reinsert all files listed
28168 ** update -> Insert files that have changed or that were not
28173 ** are added recursively. If argument bVerbose is non-zero, a message is
28178 ** always overwrites every file named on the command-line, where as
28183 int bUpdate, /* true for a --create. */ in arCreateOrUpdateCommand()
28188 " name TEXT PRIMARY KEY, -- name of the file\n" in arCreateOrUpdateCommand()
28189 " mode INT, -- access permissions\n" in arCreateOrUpdateCommand()
28190 " mtime INT, -- last modification time\n" in arCreateOrUpdateCommand()
28191 " sz INT, -- original file size\n" in arCreateOrUpdateCommand()
28192 " data BLOB -- compressed content\n" in arCreateOrUpdateCommand()
28202 " WHEN '-' THEN length(data)\n" in arCreateOrUpdateCommand()
28204 " ELSE -1 END,\n" in arCreateOrUpdateCommand()
28229 if( pAr->bZip ){ in arCreateOrUpdateCommand()
28231 if( pAr->zFile ){ in arCreateOrUpdateCommand()
28238 zTab, pAr->zFile in arCreateOrUpdateCommand()
28265 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ in arCreateOrUpdateCommand()
28266 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab, in arCreateOrUpdateCommand()
28267 pAr->bVerbose ? "shell_putsnl(name)" : "name", in arCreateOrUpdateCommand()
28268 pAr->azArg[i], pAr->zDir, zExists); in arCreateOrUpdateCommand()
28274 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); in arCreateOrUpdateCommand()
28277 if( pAr->bZip && pAr->zFile ){ in arCreateOrUpdateCommand()
28292 int fromCmdLine, /* True if -A command-line option, not .ar cmd */ in arDotCommand()
28304 cmd.out = pState->out; in arDotCommand()
28305 cmd.db = pState->db; in arDotCommand()
28309 eDbType = pState->openMode; in arDotCommand()
28331 sqlite3_fprintf(cmd.out, "-- open database '%s'%s\n", cmd.zFile, in arDotCommand()
28372 arUsage(pState->out); in arDotCommand()
28384 assert( cmd.eCmd==AR_CMD_UPDATE ); in arDotCommand()
28390 if( cmd.db!=pState->db ){ in arDotCommand()
28409 sqlite3_fprintf(pState->out, "%s;\n", zSql); in recoverSqlCb()
28416 ** on stream pState->out.
28422 int bFreelist = 1; /* 0 if --ignore-freelist is specified */ in recoverDatabaseCmd()
28423 int bRowids = 1; /* 0 if --no-rowids */ in recoverDatabaseCmd()
28430 if( z[0]=='-' && z[1]=='-' ) z++; in recoverDatabaseCmd()
28432 if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){ in recoverDatabaseCmd()
28435 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){ in recoverDatabaseCmd()
28436 /* This option determines the name of the ATTACH-ed database used in recoverDatabaseCmd()
28444 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){ in recoverDatabaseCmd()
28448 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){ in recoverDatabaseCmd()
28453 showHelp(pState->out, azArg[0]); in recoverDatabaseCmd()
28459 pState->db, "main", recoverSqlCb, (void*)pState in recoverDatabaseCmd()
28467 sqlite3_fprintf(pState->out, ".dbconfig defensive off\n"); in recoverDatabaseCmd()
28486 rc = sqlite3_intck_open(pState->db, "main", &p); in intckDatabaseCmd()
28494 sqlite3_fprintf(pState->out, "%s\n", zMsg); in intckDatabaseCmd()
28508 sqlite3_fprintf(pState->out, "%lld steps, %lld errors\n", nStep, nError); in intckDatabaseCmd()
28523 * pointer is non-zero, its referent will be set to a summary of renames
28531 sqlite3_fprintf(stderr,"E:%d\n",rc), assert(0)
28535 assert(rc==SQLITE_OK||rc==SQLITE_DONE); in rc_err_oom_die()
28573 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\ in zAutoColumn()
28581 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\ in zAutoColumn()
28589 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\ in zAutoColumn()
28647 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\ in zAutoColumn()
28650 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \ in zAutoColumn()
28655 " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff))," in zAutoColumn()
28661 assert(pDb!=0); in zAutoColumn()
28675 assert(*pDb!=0); in zAutoColumn()
28676 rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0); in zAutoColumn()
28678 rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0); in zAutoColumn()
28698 rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0); in zAutoColumn()
28705 assert(db_int(*pDb, "%s", zHasDupes)==0); /* Consider: remove this */ in zAutoColumn()
28706 rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0); in zAutoColumn()
28718 if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0) in zAutoColumn()
28743 shellPreparePrintf(p->db, &rc, &pStmt, in outputDumpWarning()
28750 p->out in outputDumpWarning()
28758 ** Fault-Simulator state and logic.
28761 int iId; /* ID that triggers a simulated fault. -1 means "any" */
28764 int iInterval; /* Reset iCnt to this value after each fault */
28769 } faultsim_state = {-1, 0, 0, 0, 0, 0, 0, 0};
28772 ** This is the fault-sim callback
28779 if( faultsim_state.iCnt>0 ) faultsim_state.iCnt--; in faultsim_callback()
28782 "FAULT-SIM id=%d no-fault (cnt=%d)\n", iArg, faultsim_state.iCnt); in faultsim_callback()
28788 "FAULT-SIM id=%d returns %d\n", iArg, faultsim_state.iErr); in faultsim_callback()
28793 faultsim_state.iCnt = -1; in faultsim_callback()
28812 if( p->expert.pExpert ){ in do_meta_command()
28819 while( zLine[h] && nArg<ArraySize(azArg)-1 ){ in do_meta_command()
28832 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]); in do_meta_command()
28857 sqlite3_set_authorizer(p->db, shellAuth, p); in do_meta_command()
28858 }else if( p->bSafeModePersist ){ in do_meta_command()
28859 sqlite3_set_authorizer(p->db, safeModeAuth, p); in do_meta_command()
28861 sqlite3_set_authorizer(p->db, 0, 0); in do_meta_command()
28889 if( z[0]=='-' ){ in do_meta_command()
28890 if( z[1]=='-' ) z++; in do_meta_command()
28891 if( cli_strcmp(z, "-append")==0 ){ in do_meta_command()
28894 if( cli_strcmp(z, "-async")==0 ){ in do_meta_command()
28928 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb); in do_meta_command()
28961 /* The undocumented ".breakpoint" command causes a call to the no-op in do_meta_command()
29001 ** Then read the content of the testcase-out.txt file and compare against in do_meta_command()
29008 eputz("Usage: .check GLOB-PATTERN\n"); in do_meta_command()
29010 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){ in do_meta_command()
29014 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n", in do_meta_command()
29015 p->zTestcase, azArg[1], zRes); in do_meta_command()
29018 sqlite3_fprintf(p->out, "testcase-%s ok\n", p->zTestcase); in do_meta_command()
29019 p->nCheck++; in do_meta_command()
29041 for(i=0; i<ArraySize(p->aAuxDb); i++){ in do_meta_command()
29042 const char *zFile = p->aAuxDb[i].zDbFilename; in do_meta_command()
29043 if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){ in do_meta_command()
29048 zFile = "(temporary-file)"; in do_meta_command()
29050 if( p->pAuxDb == &p->aAuxDb[i] ){ in do_meta_command()
29052 }else if( p->aAuxDb[i].db!=0 ){ in do_meta_command()
29057 int i = azArg[1][0] - '0'; in do_meta_command()
29058 if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){ in do_meta_command()
29059 p->pAuxDb->db = p->db; in do_meta_command()
29060 p->pAuxDb = &p->aAuxDb[i]; in do_meta_command()
29061 globalDb = p->db = p->pAuxDb->db; in do_meta_command()
29062 p->pAuxDb->db = 0; in do_meta_command()
29066 int i = azArg[2][0] - '0'; in do_meta_command()
29067 if( i<0 || i>=ArraySize(p->aAuxDb) ){ in do_meta_command()
29068 /* No-op */ in do_meta_command()
29069 }else if( p->pAuxDb == &p->aAuxDb[i] ){ in do_meta_command()
29072 }else if( p->aAuxDb[i].db ){ in do_meta_command()
29074 close_db(p->aAuxDb[i].db); in do_meta_command()
29075 p->aAuxDb[i].db = 0; in do_meta_command()
29078 eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n"); in do_meta_command()
29089 p->crlfMode = booleanValue(azArg[1]); in do_meta_command()
29091 p->crlfMode = 0; in do_meta_command()
29094 sqlite3_fprintf(stderr, "crlf is %s\n", p->crlfMode ? "ON" : "OFF"); in do_meta_command()
29103 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); in do_meta_command()
29105 shellDatabaseError(p->db); in do_meta_command()
29121 int eTxn = sqlite3_txn_state(p->db, azName[i*2]); in do_meta_command()
29122 int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]); in do_meta_command()
29124 sqlite3_fprintf(p->out, "%s: %s %s%s\n", in do_meta_command()
29127 eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn"); in do_meta_command()
29166 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0); in do_meta_command()
29168 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v); in do_meta_command()
29169 sqlite3_fprintf(p->out, "%19s %s\n", in do_meta_command()
29194 int savedShowHeader = p->showHeader; in do_meta_command()
29195 int savedShellFlags = p->shellFlgs; in do_meta_command()
29200 if( azArg[i][0]=='-' ){ in do_meta_command()
29202 if( z[0]=='-' ) z++; in do_meta_command()
29203 if( cli_strcmp(z,"preserve-rowids")==0 ){ in do_meta_command()
29205 eputz("The --preserve-rowids option is not compatible" in do_meta_command()
29217 if( cli_strcmp(z,"data-only")==0 ){ in do_meta_command()
29256 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ in do_meta_command()
29259 ** So disable foreign-key constraint enforcement to prevent problems. */ in do_meta_command()
29260 sqlite3_fputs("PRAGMA foreign_keys=OFF;\n", p->out); in do_meta_command()
29261 sqlite3_fputs("BEGIN TRANSACTION;\n", p->out); in do_meta_command()
29263 p->writableSchema = 0; in do_meta_command()
29264 p->showHeader = 0; in do_meta_command()
29268 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); in do_meta_command()
29269 p->nErr = 0; in do_meta_command()
29280 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ in do_meta_command()
29292 if( p->writableSchema ){ in do_meta_command()
29293 sqlite3_fputs("PRAGMA writable_schema=OFF;\n", p->out); in do_meta_command()
29294 p->writableSchema = 0; in do_meta_command()
29296 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); in do_meta_command()
29297 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); in do_meta_command()
29298 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ in do_meta_command()
29299 sqlite3_fputs(p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n", p->out); in do_meta_command()
29301 p->showHeader = savedShowHeader; in do_meta_command()
29302 p->shellFlgs = savedShellFlags; in do_meta_command()
29320 p->autoEQPtest = 0; in do_meta_command()
29321 if( p->autoEQPtrace ){ in do_meta_command()
29322 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0); in do_meta_command()
29323 p->autoEQPtrace = 0; in do_meta_command()
29326 p->autoEQP = AUTOEQP_full; in do_meta_command()
29328 p->autoEQP = AUTOEQP_trigger; in do_meta_command()
29331 p->autoEQP = AUTOEQP_on; in do_meta_command()
29332 p->autoEQPtest = 1; in do_meta_command()
29334 p->autoEQP = AUTOEQP_full; in do_meta_command()
29335 p->autoEQPtrace = 1; in do_meta_command()
29337 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0); in do_meta_command()
29338 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0); in do_meta_command()
29341 p->autoEQP = (u8)booleanValue(azArg[1]); in do_meta_command()
29367 if( val==1 && p->mode!=MODE_Explain ){ in do_meta_command()
29368 p->normalMode = p->mode; in do_meta_command()
29369 p->mode = MODE_Explain; in do_meta_command()
29370 p->autoExplain = 0; in do_meta_command()
29372 if( p->mode==MODE_Explain ) p->mode = p->normalMode; in do_meta_command()
29373 p->autoExplain = 0; in do_meta_command()
29375 if( p->mode==MODE_Explain ) p->mode = p->normalMode; in do_meta_command()
29376 p->autoExplain = 1; in do_meta_command()
29382 if( p->bSafeMode ){ in do_meta_command()
29396 const char *zCtrlName; /* Name of a test-control option */ in do_meta_command()
29412 int filectrl = -1; in do_meta_command()
29413 int iCtrl = -1; in do_meta_command()
29415 int isOk = 0; /* 0: usage 1: %lld 2: no-result */ in do_meta_command()
29423 if( zCmd[0]=='-' in do_meta_command()
29424 && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0) in do_meta_command()
29428 for(i=3; i<nArg; i++) azArg[i-2] = azArg[i]; in do_meta_command()
29429 nArg -= 2; in do_meta_command()
29433 /* The argument can optionally begin with "-" or "--" */ in do_meta_command()
29434 if( zCmd[0]=='-' && zCmd[1] ){ in do_meta_command()
29436 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; in do_meta_command()
29439 /* --help lists all file-controls */ in do_meta_command()
29441 sqlite3_fputs("Available file-controls:\n", p->out); in do_meta_command()
29443 sqlite3_fprintf(p->out, in do_meta_command()
29459 sqlite3_fprintf(stderr,"Error: ambiguous file-control: \"%s\"\n" in do_meta_command()
29460 "Use \".filectrl --help\" for help\n", zCmd); in do_meta_command()
29467 sqlite3_fprintf(stderr,"Error: unknown file-control: %s\n" in do_meta_command()
29468 "Use \".filectrl --help\" for help\n", zCmd); in do_meta_command()
29473 iRes = nArg==3 ? integerValue(azArg[2]) : -1; in do_meta_command()
29474 sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes); in do_meta_command()
29483 sqlite3_file_control(p->db, zSchema, filectrl, &x); in do_meta_command()
29491 x = nArg==3 ? booleanValue(azArg[2]) : -1; in do_meta_command()
29492 sqlite3_file_control(p->db, zSchema, filectrl, &x); in do_meta_command()
29501 sqlite3_file_control(p->db, zSchema, filectrl, &x); in do_meta_command()
29509 sqlite3_file_control(p->db, zSchema, filectrl, &z); in do_meta_command()
29511 sqlite3_fprintf(p->out, "%s\n", z); in do_meta_command()
29521 sqlite3_file_control(p->db, zSchema, filectrl, &x); in do_meta_command()
29523 x = -1; in do_meta_command()
29524 sqlite3_file_control(p->db, zSchema, filectrl, &x); in do_meta_command()
29525 sqlite3_fprintf(p->out, "%d\n", x); in do_meta_command()
29532 sqlite3_fprintf(p->out, "Usage: .filectrl %s %s\n", in do_meta_command()
29538 sqlite3_fprintf(p->out, "%s\n", zBuf); in do_meta_command()
29553 eputz("Usage: .fullschema ?--indent?\n"); in do_meta_command()
29558 rc = sqlite3_exec(p->db, in do_meta_command()
29569 rc = sqlite3_prepare_v2(p->db, in do_meta_command()
29572 -1, &pStmt, 0); in do_meta_command()
29579 sqlite3_fputs("/* No STAT tables available */\n", p->out); in do_meta_command()
29581 sqlite3_fputs("ANALYZE sqlite_schema;\n", p->out); in do_meta_command()
29587 sqlite3_fputs("ANALYZE sqlite_schema;\n", p->out); in do_meta_command()
29593 p->showHeader = booleanValue(azArg[1]); in do_meta_command()
29594 p->shellFlgs |= SHFLG_HeaderSet; in do_meta_command()
29603 n = showHelp(p->out, azArg[1]); in do_meta_command()
29605 sqlite3_fprintf(p->out, "Nothing matches '%s'\n", azArg[1]); in do_meta_command()
29608 showHelp(p->out, 0); in do_meta_command()
29622 int nSep; /* Number of bytes in p->colSeparator[] */ in do_meta_command()
29633 if( p->mode==MODE_Ascii ){ in do_meta_command()
29641 if( z[0]=='-' && z[1]=='-' ) z++; in do_meta_command()
29642 if( z[0]!='-' ){ in do_meta_command()
29648 sqlite3_fprintf(p->out, "ERROR: extra argument: \"%s\". Usage:\n",z); in do_meta_command()
29649 showHelp(p->out, "import"); in do_meta_command()
29652 }else if( cli_strcmp(z,"-v")==0 ){ in do_meta_command()
29654 }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){ in do_meta_command()
29656 }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){ in do_meta_command()
29658 }else if( cli_strcmp(z,"-ascii")==0 ){ in do_meta_command()
29663 }else if( cli_strcmp(z,"-csv")==0 ){ in do_meta_command()
29669 sqlite3_fprintf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", z); in do_meta_command()
29670 showHelp(p->out, "import"); in do_meta_command()
29675 sqlite3_fprintf(p->out, "ERROR: missing %s argument. Usage:\n", in do_meta_command()
29677 showHelp(p->out, "import"); in do_meta_command()
29683 /* If neither the --csv or --ascii options are specified, then set in do_meta_command()
29685 nSep = strlen30(p->colSeparator); in do_meta_command()
29687 eputz("Error: non-null column separator required for import\n"); in do_meta_command()
29691 eputz("Error: multi-character column separators not allowed" in do_meta_command()
29695 nSep = strlen30(p->rowSeparator); in do_meta_command()
29697 eputz("Error: non-null row separator required for import\n"); in do_meta_command()
29700 if( nSep==2 && p->mode==MODE_Csv in do_meta_command()
29701 && cli_strcmp(p->rowSeparator,SEP_CrLf)==0 in do_meta_command()
29707 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
29708 nSep = strlen30(p->rowSeparator); in do_meta_command()
29711 eputz("Error: multi-character row separators not allowed" in do_meta_command()
29715 sCtx.cColSep = (u8)p->colSeparator[0]; in do_meta_command()
29716 sCtx.cRowSep = (u8)p->rowSeparator[0]; in do_meta_command()
29741 sqlite3_fputs("Column separator ", p->out); in do_meta_command()
29742 output_c_string(p->out, zSep); in do_meta_command()
29743 sqlite3_fputs(", row separator ", p->out); in do_meta_command()
29745 output_c_string(p->out, zSep); in do_meta_command()
29746 sqlite3_fputs("\n", p->out); in do_meta_command()
29754 while( (nSkip--)>0 ){ in do_meta_command()
29758 if( sqlite3_table_column_metadata(p->db, zSchema, zTable,0,0,0,0,0,0) in do_meta_command()
29759 && 0==db_int(p->db, "SELECT count(*) FROM \"%w\".sqlite_schema" in do_meta_command()
29775 sqlite3_fprintf((stdin_is_interactive && p->in==stdin)? p->out : stderr, in do_meta_command()
29780 assert(dbCols==0); in do_meta_command()
29794 sqlite3_fprintf(p->out, "%s\n", zCreate); in do_meta_command()
29796 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); in do_meta_command()
29799 "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db)); in do_meta_command()
29815 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
29820 shellDatabaseError(p->db); in do_meta_command()
29856 assert( j<nByte ); in do_meta_command()
29858 sqlite3_fprintf(p->out, "Insert using: %s\n", zSql); in do_meta_command()
29860 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
29864 shellDatabaseError(p->db); in do_meta_command()
29870 needCommit = sqlite3_get_autocommit(p->db); in do_meta_command()
29871 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); in do_meta_command()
29877 ** Did we reach end-of-file before finding any columns? in do_meta_command()
29882 ** Did we reach end-of-file OR end-of-line before finding any in do_meta_command()
29886 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; in do_meta_command()
29889 ** record terminator but only for last field of multi-field row. in do_meta_command()
29892 if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){ in do_meta_command()
29895 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); in do_meta_command()
29896 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){ in do_meta_command()
29898 " - filling the rest with NULL\n", in do_meta_command()
29910 "%s:%d: expected %d columns but found %d - extras ignored\n", in do_meta_command()
29918 sCtx.zFile, startLine, sqlite3_errmsg(p->db)); in do_meta_command()
29928 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); in do_meta_command()
29930 sqlite3_fprintf(p->out, in do_meta_command()
29932 sCtx.nRow, sCtx.nErr, sCtx.nLine-1); in do_meta_command()
29947 sqlite3_fprintf(stderr,".%s unavailable without --unsafe-testing\n", in do_meta_command()
29967 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1); in do_meta_command()
29979 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
29987 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
29995 if( sqlite3_column_int(pStmt,1)==-1 ){ in do_meta_command()
30023 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum); in do_meta_command()
30025 rc = sqlite3_exec(p->db, zSql, 0, 0, 0); in do_meta_command()
30026 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0); in do_meta_command()
30029 "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db)); in do_meta_command()
30048 if( iArg==0 ) iArg = -1; in do_meta_command()
30066 }else if( cli_strcmp(azArg[1], "-")==0 ){ in do_meta_command()
30105 sqlite3_limit(p->db, aLimit[i].limitCode, -1)); in do_meta_command()
30108 eputz("Usage: .limit NAME ?NEW-VALUE?\n"); in do_meta_command()
30112 int iLimit = -1; in do_meta_command()
30133 sqlite3_limit(p->db, aLimit[iLimit].limitCode, in do_meta_command()
30137 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); in do_meta_command()
30152 /* Must have a non-empty FILE. (Will not load self.) */ in do_meta_command()
30160 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); in do_meta_command()
30175 if( p->bSafeMode in do_meta_command()
30183 output_file_close(p->pLog); in do_meta_command()
30185 p->pLog = output_file_open(zFile); in do_meta_command()
30213 /* See similar code at tag-20250224-1 */ in do_meta_command()
30218 p->eEscMode = k; in do_meta_command()
30225 " - choices:", zEsc); in do_meta_command()
30235 /* Apply defaults for qbox pseudo-mode. If that in do_meta_command()
30236 * overwrites already-set values, user was informed of this. in do_meta_command()
30246 }else if( z[0]=='-' ){ in do_meta_command()
30249 " --escape MODE\n" in do_meta_command()
30250 " --noquote\n" in do_meta_command()
30251 " --quote\n" in do_meta_command()
30252 " --wordwrap on/off\n" in do_meta_command()
30253 " --wrap N\n" in do_meta_command()
30254 " --ww\n"); in do_meta_command()
30264 if( p->mode==MODE_Column in do_meta_command()
30265 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box) in do_meta_command()
30267 sqlite3_fprintf(p->out, in do_meta_command()
30268 "current output mode: %s --wrap %d --wordwrap %s " in do_meta_command()
30269 "--%squote --escape %s\n", in do_meta_command()
30270 modeDescr[p->mode], p->cmOpts.iWrap, in do_meta_command()
30271 p->cmOpts.bWordWrap ? "on" : "off", in do_meta_command()
30272 p->cmOpts.bQuote ? "" : "no", in do_meta_command()
30273 shell_EscModeNames[p->eEscMode] in do_meta_command()
30276 sqlite3_fprintf(p->out, in do_meta_command()
30277 "current output mode: %s --escape %s\n", in do_meta_command()
30278 modeDescr[p->mode], in do_meta_command()
30279 shell_EscModeNames[p->eEscMode] in do_meta_command()
30284 zMode = modeDescr[p->mode]; in do_meta_command()
30285 if( (chng&1)==0 ) cmOpts = p->cmOpts; in do_meta_command()
30289 p->mode = MODE_Line; in do_meta_command()
30290 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
30292 p->mode = MODE_Column; in do_meta_command()
30293 if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){ in do_meta_command()
30294 p->showHeader = 1; in do_meta_command()
30296 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
30297 p->cmOpts = cmOpts; in do_meta_command()
30299 p->mode = MODE_List; in do_meta_command()
30300 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column); in do_meta_command()
30301 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
30303 p->mode = MODE_Html; in do_meta_command()
30305 p->mode = MODE_Tcl; in do_meta_command()
30306 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space); in do_meta_command()
30307 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
30309 p->mode = MODE_Csv; in do_meta_command()
30310 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); in do_meta_command()
30311 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); in do_meta_command()
30313 p->mode = MODE_List; in do_meta_command()
30314 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab); in do_meta_command()
30316 p->mode = MODE_Insert; in do_meta_command()
30318 if( p->eEscMode==SHELL_ESC_OFF ){ in do_meta_command()
30324 p->mode = MODE_Quote; in do_meta_command()
30325 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); in do_meta_command()
30326 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
30328 p->mode = MODE_Ascii; in do_meta_command()
30329 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit); in do_meta_command()
30330 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record); in do_meta_command()
30332 p->mode = MODE_Markdown; in do_meta_command()
30333 p->cmOpts = cmOpts; in do_meta_command()
30335 p->mode = MODE_Table; in do_meta_command()
30336 p->cmOpts = cmOpts; in do_meta_command()
30338 p->mode = MODE_Box; in do_meta_command()
30339 p->cmOpts = cmOpts; in do_meta_command()
30341 p->mode = MODE_Count; in do_meta_command()
30343 p->mode = MODE_Off; in do_meta_command()
30345 p->mode = MODE_Json; in do_meta_command()
30352 p->cMode = p->mode; in do_meta_command()
30360 }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){ in do_meta_command()
30362 p->lineno, azArg[1]); in do_meta_command()
30365 p->bSafeMode = 0; in do_meta_command()
30366 return 0; /* Return immediately to bypass the safe mode reset in do_meta_command()
30374 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue, in do_meta_command()
30375 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]); in do_meta_command()
30389 /* Check for command-line arguments */ in do_meta_command()
30404 p->openFlags |= SQLITE_OPEN_NOFOLLOW; in do_meta_command()
30411 p->szMax = integerValue(azArg[++iName]); in do_meta_command()
30415 if( z[0]=='-' ){ in do_meta_command()
30429 session_close_all(p, -1); in do_meta_command()
30430 close_db(p->db); in do_meta_command()
30431 p->db = 0; in do_meta_command()
30432 p->pAuxDb->zDbFilename = 0; in do_meta_command()
30433 sqlite3_free(p->pAuxDb->zFreeOnClose); in do_meta_command()
30434 p->pAuxDb->zFreeOnClose = 0; in do_meta_command()
30435 p->openMode = openMode; in do_meta_command()
30436 p->openFlags = 0; in do_meta_command()
30437 p->szMax = 0; in do_meta_command()
30440 if( zFN || p->openMode==SHELL_OPEN_HEXDB ){ in do_meta_command()
30441 if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN); in do_meta_command()
30443 if( p->bSafeMode in do_meta_command()
30444 && p->openMode!=SHELL_OPEN_HEXDB in do_meta_command()
30448 failIfSafeMode(p, "cannot open disk-based database files in safe mode"); in do_meta_command()
30451 /* WASM mode has its own sandboxed pseudo-filesystem. */ in do_meta_command()
30459 p->pAuxDb->zDbFilename = zNewFilename; in do_meta_command()
30461 if( p->db==0 ){ in do_meta_command()
30465 p->pAuxDb->zFreeOnClose = zNewFilename; in do_meta_command()
30468 if( p->db==0 ){ in do_meta_command()
30469 /* As a fall-back open a TEMP database */ in do_meta_command()
30470 p->pAuxDb->zDbFilename = 0; in do_meta_command()
30486 int bPlain = 0; /* --plain option */ in do_meta_command()
30502 if( z[0]=='-' ){ in do_meta_command()
30503 if( z[1]=='-' ) z++; in do_meta_command()
30504 if( cli_strcmp(z,"-bom")==0 ){ in do_meta_command()
30506 }else if( cli_strcmp(z,"-plain")==0 ){ in do_meta_command()
30508 }else if( c=='o' && cli_strcmp(z,"-x")==0 ){ in do_meta_command()
30510 }else if( c=='o' && cli_strcmp(z,"-e")==0 ){ in do_meta_command()
30512 }else if( c=='o' && cli_strcmp(z,"-w")==0 ){ in do_meta_command()
30515 sqlite3_fprintf(p->out, in do_meta_command()
30517 showHelp(p->out, azArg[0]); in do_meta_command()
30536 sqlite3_fprintf(p->out, in do_meta_command()
30538 showHelp(p->out, azArg[0]); in do_meta_command()
30549 p->outCount = 2; in do_meta_command()
30551 p->outCount = 0; in do_meta_command()
30556 p->doXdgOpen = 1; in do_meta_command()
30562 p->mode = MODE_Csv; in do_meta_command()
30563 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); in do_meta_command()
30564 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); in do_meta_command()
30570 /* web-browser mode. */ in do_meta_command()
30572 if( !bPlain ) p->mode = MODE_Www; in do_meta_command()
30578 zFile = sqlite3_mprintf("%s", p->zTempFile); in do_meta_command()
30590 assert( stderr!=NULL ); in do_meta_command()
30596 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); in do_meta_command()
30603 assert( stderr!=NULL ); in do_meta_command()
30616 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); in do_meta_command()
30631 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;", in do_meta_command()
30642 rx = sqlite3_prepare_v2(p->db, in do_meta_command()
30644 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); in do_meta_command()
30652 rx = sqlite3_prepare_v2(p->db, in do_meta_command()
30654 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); in do_meta_command()
30656 sqlite3_fprintf(p->out, in do_meta_command()
30657 "%-*s %s\n", len, sqlite3_column_text(pStmt,0), in do_meta_command()
30673 ** Set or reset a bind parameter. NAME should be the full parameter in do_meta_command()
30690 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
30699 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
30702 sqlite3_fprintf(p->out, "Error: %s\n", sqlite3_errmsg(p->db)); in do_meta_command()
30721 sqlite3_exec(p->db, zSql, 0, 0, 0); in do_meta_command()
30726 showHelp(p->out, "parameter"); in do_meta_command()
30732 if( i>1 ) sqlite3_fputs(" ", p->out); in do_meta_command()
30733 sqlite3_fputs(azArg[i], p->out); in do_meta_command()
30735 sqlite3_fputs("\n", p->out); in do_meta_command()
30742 p->flgProgress = 0; in do_meta_command()
30743 p->mxProgress = 0; in do_meta_command()
30744 p->nProgress = 0; in do_meta_command()
30747 if( z[0]=='-' ){ in do_meta_command()
30749 if( z[0]=='-' ) z++; in do_meta_command()
30751 p->flgProgress |= SHELL_PROGRESS_QUIET; in do_meta_command()
30754 if( cli_strcmp(z,"reset")==0 ){ in do_meta_command()
30755 p->flgProgress |= SHELL_PROGRESS_RESET; in do_meta_command()
30759 p->flgProgress |= SHELL_PROGRESS_ONCE; in do_meta_command()
30764 eputz("Error: missing argument on --limit\n"); in do_meta_command()
30768 p->mxProgress = (int)integerValue(azArg[++i]); in do_meta_command()
30780 sqlite3_progress_handler(p->db, nn, progress_handler, p); in do_meta_command()
30786 shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); in do_meta_command()
30789 shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); in do_meta_command()
30801 FILE *inSaved = p->in; in do_meta_command()
30802 int savedLineno = p->lineno; in do_meta_command()
30814 p->in = sqlite3_popen(azArg[1]+1, "r"); in do_meta_command()
30815 if( p->in==0 ){ in do_meta_command()
30820 pclose(p->in); in do_meta_command()
30823 }else if( (p->in = openChrSource(azArg[1]))==0 ){ in do_meta_command()
30828 fclose(p->in); in do_meta_command()
30830 p->in = inSaved; in do_meta_command()
30831 p->lineno = savedLineno; in do_meta_command()
30862 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); in do_meta_command()
30864 shellDatabaseError(p->db); in do_meta_command()
30882 shellDatabaseError(p->db); in do_meta_command()
30895 p->scanstatsOn = 3; in do_meta_command()
30898 p->scanstatsOn = 2; in do_meta_command()
30900 p->scanstatsOn = (u8)booleanValue(azArg[1]); in do_meta_command()
30904 p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0 in do_meta_command()
30909 if( p->scanstatsOn==3 ){ in do_meta_command()
30942 }else if( azArg[ii][0]=='-' ){ in do_meta_command()
30949 eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n"); in do_meta_command()
30979 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list", in do_meta_command()
30980 -1, &pStmt, 0); in do_meta_command()
30982 shellDatabaseError(p->db); in do_meta_command()
31044 sqlite3_fprintf(p->out, "SQL: %s;\n", sSelect.z); in do_meta_command()
31046 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg); in do_meta_command()
31071 struct AuxDb *pAuxDb = p->pAuxDb; in do_meta_command()
31072 OpenSession *pSession = &pAuxDb->aSession[0]; in do_meta_command()
31075 int nCmd = nArg - 1; in do_meta_command()
31080 for(iSes=0; iSes<pAuxDb->nSession; iSes++){ in do_meta_command()
31081 if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break; in do_meta_command()
31083 if( iSes<pAuxDb->nSession ){ in do_meta_command()
31084 pSession = &pAuxDb->aSession[iSes]; in do_meta_command()
31086 nCmd--; in do_meta_command()
31088 pSession = &pAuxDb->aSession[0]; in do_meta_command()
31099 if( pSession->p==0 ){ in do_meta_command()
31103 rc = sqlite3session_attach(pSession->p, azCmd[1]); in do_meta_command()
31122 if( pSession->p==0 ) goto session_not_open; in do_meta_command()
31131 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); in do_meta_command()
31133 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); in do_meta_command()
31142 "ERROR: Failed to write entire %d-byte output\n", szChng); in do_meta_command()
31154 if( pAuxDb->nSession ){ in do_meta_command()
31156 pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession]; in do_meta_command()
31166 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); in do_meta_command()
31167 if( pAuxDb->nSession ){ in do_meta_command()
31168 ii = sqlite3session_enable(pSession->p, ii); in do_meta_command()
31169 sqlite3_fprintf(p->out, in do_meta_command()
31170 "session %s enable flag = %d\n", pSession->zName, ii); in do_meta_command()
31180 if( pAuxDb->nSession ){ in do_meta_command()
31181 for(ii=0; ii<pSession->nFilter; ii++){ in do_meta_command()
31182 sqlite3_free(pSession->azFilter[ii]); in do_meta_command()
31184 sqlite3_free(pSession->azFilter); in do_meta_command()
31185 nByte = sizeof(pSession->azFilter[0])*(nCmd-1); in do_meta_command()
31186 pSession->azFilter = sqlite3_malloc( nByte ); in do_meta_command()
31187 shell_check_oom( pSession->azFilter ); in do_meta_command()
31189 char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); in do_meta_command()
31192 pSession->nFilter = ii-1; in do_meta_command()
31202 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); in do_meta_command()
31203 if( pAuxDb->nSession ){ in do_meta_command()
31204 ii = sqlite3session_indirect(pSession->p, ii); in do_meta_command()
31205 sqlite3_fprintf(p->out, in do_meta_command()
31206 "session %s indirect flag = %d\n", pSession->zName, ii); in do_meta_command()
31216 if( pAuxDb->nSession ){ in do_meta_command()
31217 ii = sqlite3session_isempty(pSession->p); in do_meta_command()
31218 sqlite3_fprintf(p->out, in do_meta_command()
31219 "session %s isempty flag = %d\n", pSession->zName, ii); in do_meta_command()
31227 for(i=0; i<pAuxDb->nSession; i++){ in do_meta_command()
31228 sqlite3_fprintf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName); in do_meta_command()
31241 for(i=0; i<pAuxDb->nSession; i++){ in do_meta_command()
31242 if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){ in do_meta_command()
31247 if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){ in do_meta_command()
31249 "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession)); in do_meta_command()
31252 pSession = &pAuxDb->aSession[pAuxDb->nSession]; in do_meta_command()
31253 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); in do_meta_command()
31259 pSession->nFilter = 0; in do_meta_command()
31260 sqlite3session_table_filter(pSession->p, session_filter, pSession); in do_meta_command()
31261 pAuxDb->nSession++; in do_meta_command()
31262 pSession->zName = sqlite3_mprintf("%s", zName); in do_meta_command()
31263 shell_check_oom(pSession->zName); in do_meta_command()
31267 showHelp(p->out, "session"); in do_meta_command()
31274 if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){ in do_meta_command()
31275 if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){ in do_meta_command()
31279 sqlite3_fprintf(p->out, "%s: %d 0x%x\n", azArg[i], v, v); in do_meta_command()
31282 if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){ in do_meta_command()
31288 sqlite3_fputs(zBuf, p->out); in do_meta_command()
31307 if( z[0]=='-' && z[1]=='-' ) z++; in do_meta_command()
31308 if( cli_strcmp(z,"-init")==0 ){ in do_meta_command()
31311 if( cli_strcmp(z,"-v")==0 ){ in do_meta_command()
31317 sqlite3_fputs("Should be one of: --init -v\n", stderr); in do_meta_command()
31322 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0) in do_meta_command()
31334 for(k=bSelftestExists; k>=0; k--){ in do_meta_command()
31336 rc = sqlite3_prepare_v2(p->db, in do_meta_command()
31338 -1, &pStmt, 0); in do_meta_command()
31340 rc = sqlite3_prepare_v2(p->db, in do_meta_command()
31341 "VALUES(0,'memo','Missing SELFTEST table - default checks only','')," in do_meta_command()
31343 -1, &pStmt, 0); in do_meta_command()
31365 sqlite3_fprintf(p->out, "%s\n", zSql); in do_meta_command()
31371 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg); in do_meta_command()
31374 sqlite3_fprintf(p->out, "Result: %s\n", str.z); in do_meta_command()
31379 sqlite3_fprintf(p->out, "%d: error-code-%d: %s\n", tno, rc,zErrMsg); in do_meta_command()
31384 sqlite3_fprintf(p->out, "%d: Expected: [%s]\n", tno, zAns); in do_meta_command()
31385 sqlite3_fprintf(p->out, "%d: Got: [%s]\n", tno, str.z); in do_meta_command()
31398 sqlite3_fprintf(p->out, "%d errors out of %d tests\n", nErr, nTest); in do_meta_command()
31407 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, in do_meta_command()
31408 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]); in do_meta_command()
31411 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, in do_meta_command()
31412 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]); in do_meta_command()
31431 if( z[0]=='-' ){ in do_meta_command()
31433 if( z[0]=='-' ) z++; in do_meta_command()
31437 if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0 in do_meta_command()
31438 || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0 in do_meta_command()
31448 showHelp(p->out, azArg[0]); in do_meta_command()
31453 eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n"); in do_meta_command()
31473 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
31525 sqlite3_fprintf(p->out, "%s\n", zSql); in do_meta_command()
31532 char *zRevText = /* Query for reversible to-blob-to-text check */ in do_meta_command()
31539 /* lower-case query is first run, producing upper-case query. */ in do_meta_command()
31555 if( bDebug ) sqlite3_fprintf(p->out, "%s\n", zRevText); in do_meta_command()
31556 lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0); in do_meta_command()
31558 /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the in do_meta_command()
31562 if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC); in do_meta_command()
31567 lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0); in do_meta_command()
31568 if( bDebug ) sqlite3_fprintf(p->out, "%s\n", zGenQuery); in do_meta_command()
31628 sqlite3_fprintf(p->out, "%12.12s: %s\n","echo", in do_meta_command()
31630 sqlite3_fprintf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]); in do_meta_command()
31631 sqlite3_fprintf(p->out, "%12.12s: %s\n","explain", in do_meta_command()
31632 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off"); in do_meta_command()
31633 sqlite3_fprintf(p->out, "%12.12s: %s\n","headers", in do_meta_command()
31634 azBool[p->showHeader!=0]); in do_meta_command()
31635 if( p->mode==MODE_Column in do_meta_command()
31636 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box) in do_meta_command()
31638 sqlite3_fprintf(p->out, in do_meta_command()
31639 "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode", in do_meta_command()
31640 modeDescr[p->mode], p->cmOpts.iWrap, in do_meta_command()
31641 p->cmOpts.bWordWrap ? "on" : "off", in do_meta_command()
31642 p->cmOpts.bQuote ? "" : "no"); in do_meta_command()
31644 sqlite3_fprintf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]); in do_meta_command()
31646 sqlite3_fprintf(p->out, "%12.12s: ", "nullvalue"); in do_meta_command()
31647 output_c_string(p->out, p->nullValue); in do_meta_command()
31648 sqlite3_fputs("\n", p->out); in do_meta_command()
31649 sqlite3_fprintf(p->out, "%12.12s: %s\n","output", in do_meta_command()
31650 strlen30(p->outfile) ? p->outfile : "stdout"); in do_meta_command()
31651 sqlite3_fprintf(p->out, "%12.12s: ", "colseparator"); in do_meta_command()
31652 output_c_string(p->out, p->colSeparator); in do_meta_command()
31653 sqlite3_fputs("\n", p->out); in do_meta_command()
31654 sqlite3_fprintf(p->out, "%12.12s: ", "rowseparator"); in do_meta_command()
31655 output_c_string(p->out, p->rowSeparator); in do_meta_command()
31656 sqlite3_fputs("\n", p->out); in do_meta_command()
31657 switch( p->statsOn ){ in do_meta_command()
31663 sqlite3_fprintf(p->out, "%12.12s: %s\n","stats", zOut); in do_meta_command()
31664 sqlite3_fprintf(p->out, "%12.12s: ", "width"); in do_meta_command()
31665 for (i=0;i<p->nWidth;i++) { in do_meta_command()
31666 sqlite3_fprintf(p->out, "%d ", p->colWidth[i]); in do_meta_command()
31668 sqlite3_fputs("\n", p->out); in do_meta_command()
31669 sqlite3_fprintf(p->out, "%12.12s: %s\n", "filename", in do_meta_command()
31670 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : ""); in do_meta_command()
31676 p->statsOn = 2; in do_meta_command()
31678 p->statsOn = 3; in do_meta_command()
31680 p->statsOn = (u8)booleanValue(azArg[1]); in do_meta_command()
31683 display_stats(p->db, p, 0); in do_meta_command()
31701 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); in do_meta_command()
31704 return shellDatabaseError(p->db); in do_meta_command()
31711 eputz("Usage: .indexes ?LIKE-PATTERN?\n"); in do_meta_command()
31741 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0); in do_meta_command()
31744 if( rc ) return shellDatabaseError(p->db); in do_meta_command()
31747 ** as an array of nul-terminated strings in azResult[]. */ in do_meta_command()
31751 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); in do_meta_command()
31753 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); in do_meta_command()
31769 rc = shellDatabaseError(p->db); in do_meta_command()
31772 /* Pretty-print the contents of array azResult[] to the output */ in do_meta_command()
31783 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; in do_meta_command()
31787 sqlite3_fprintf(p->out, in do_meta_command()
31788 "%s%-*s", zSp, maxlen, azResult[j] ? azResult[j]:""); in do_meta_command()
31790 sqlite3_fputs("\n", p->out); in do_meta_command()
31799 /* Begin redirecting output to the file "testcase-out.txt" */ in do_meta_command()
31802 p->out = output_file_open("testcase-out.txt"); in do_meta_command()
31803 if( p->out==0 ){ in do_meta_command()
31804 eputz("Error: cannot open 'testcase-out.txt'\n"); in do_meta_command()
31807 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]); in do_meta_command()
31809 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?"); in do_meta_command()
31817 const char *zCtrlName; /* Name of a test-control option */ in do_meta_command()
31819 int unSafe; /* Not valid unless --unsafe-testing */ in do_meta_command()
31823 {"assert", SQLITE_TESTCTRL_ASSERT, 1, "BOOLEAN" }, in do_meta_command()
31835 {"optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK ..."}, in do_meta_command()
31847 int testctrl = -1; in do_meta_command()
31848 int iCtrl = -1; in do_meta_command()
31849 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */ in do_meta_command()
31857 /* The argument can optionally begin with "-" or "--" */ in do_meta_command()
31858 if( zCmd[0]=='-' && zCmd[1] ){ in do_meta_command()
31860 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; in do_meta_command()
31863 /* --help lists all test-controls */ in do_meta_command()
31865 sqlite3_fputs("Available test-controls:\n", p->out); in do_meta_command()
31868 sqlite3_fprintf(p->out, " .testctrl %s %s\n", in do_meta_command()
31885 sqlite3_fprintf(stderr,"Error: ambiguous test-control: \"%s\"\n" in do_meta_command()
31886 "Use \".testctrl --help\" for help\n", zCmd); in do_meta_command()
31893 sqlite3_fprintf(stderr,"Error: unknown test-control: %s\n" in do_meta_command()
31894 "Use \".testctrl --help\" for help\n", zCmd); in do_meta_command()
31903 ** -LABEL Disable the named optimization in do_meta_command()
31951 sqlite3_test_control(SQLITE_TESTCTRL_GETOPT, p->db, &curOpt); in do_meta_command()
31957 if( (z[0]=='+'|| z[0]=='-') && !IsDigit(z[1]) ){ in do_meta_command()
31990 sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,p->db,newOpt); in do_meta_command()
31996 sqlite3_fputs("+All", p->out); in do_meta_command()
32000 sqlite3_fprintf(p->out, " -%s", aLabel[ii].zLabel); in do_meta_command()
32004 sqlite3_fputs("-All", p->out); in do_meta_command()
32008 sqlite3_fprintf(p->out, " +%s", aLabel[ii].zLabel); in do_meta_command()
32012 sqlite3_fputs("\n", p->out); in do_meta_command()
32021 rc2 = sqlite3_test_control(testctrl, p->db, opt); in do_meta_command()
32052 sqlite3_fprintf(stdout, "-- random seed: %d\n", ii); in do_meta_command()
32057 db = p->db; in do_meta_command()
32088 rc2 = sqlite3_test_control(testctrl, p->db); in do_meta_command()
32094 rc2 = sqlite3_test_control(testctrl, p->db, in do_meta_command()
32104 rc2 = sqlite3_test_control(testctrl, p->db, &x); in do_meta_command()
32105 sqlite3_fprintf(p->out, "%llu\n", x); in do_meta_command()
32113 sqlite3_test_control(testctrl, p->out); in do_meta_command()
32128 sqlite3_test_control(testctrl, -id, &rc2); in do_meta_command()
32134 rc2 = sqlite3_test_control(testctrl, -id, &val); in do_meta_command()
32136 if( id>1 ) sqlite3_fputs(" ", p->out); in do_meta_command()
32137 sqlite3_fprintf(p->out, "%d: %d", id, val); in do_meta_command()
32140 if( id>1 ) sqlite3_fputs("\n", p->out); in do_meta_command()
32149 rc2 = sqlite3_test_control(testctrl, p->db, opt); in do_meta_command()
32155 rc2 = -1; in do_meta_command()
32169 if( z[0]=='-' && z[1]=='-' ) z++; in do_meta_command()
32177 }else if( cli_strcmp(z,"reset")==0 ){ in do_meta_command()
32182 sqlite3_fprintf(p->out, "faultsim.iId: %d\n", in do_meta_command()
32184 sqlite3_fprintf(p->out, "faultsim.iErr: %d\n", in do_meta_command()
32186 sqlite3_fprintf(p->out, "faultsim.iCnt: %d\n", in do_meta_command()
32188 sqlite3_fprintf(p->out, "faultsim.nHit: %d\n", in do_meta_command()
32190 sqlite3_fprintf(p->out, "faultsim.iInterval: %d\n", in do_meta_command()
32192 sqlite3_fprintf(p->out, "faultsim.eVerbose: %d\n", in do_meta_command()
32194 sqlite3_fprintf(p->out, "faultsim.nRepeat: %d\n", in do_meta_command()
32196 sqlite3_fprintf(p->out, "faultsim.nSkip: %d\n", in do_meta_command()
32198 }else if( cli_strcmp(z,"-v")==0 ){ in do_meta_command()
32200 }else if( cli_strcmp(z,"-q")==0 ){ in do_meta_command()
32201 if( faultsim_state.eVerbose>0 ) faultsim_state.eVerbose--; in do_meta_command()
32202 }else if( cli_strcmp(z,"-id")==0 && kk+1<nArg ){ in do_meta_command()
32204 }else if( cli_strcmp(z,"-errcode")==0 && kk+1<nArg ){ in do_meta_command()
32206 }else if( cli_strcmp(z,"-interval")==0 && kk+1<nArg ){ in do_meta_command()
32208 }else if( cli_strcmp(z,"-repeat")==0 && kk+1<nArg ){ in do_meta_command()
32210 }else if( cli_strcmp(z,"-skip")==0 && kk+1<nArg ){ in do_meta_command()
32212 }else if( cli_strcmp(z,"-?")==0 || sqlite3_strglob("*help*",z)==0){ in do_meta_command()
32229 " reset Reset the trigger counter\n" in do_meta_command()
32231 " -v Increase verbosity\n" in do_meta_command()
32232 " -q Decrease verbosity\n" in do_meta_command()
32233 " --errcode N When triggered, return N as error code\n" in do_meta_command()
32234 " --id ID Trigger only for the ID specified\n" in do_meta_command()
32235 " --interval N Trigger only after every N-th call\n" in do_meta_command()
32236 " --repeat N Turn off after N hits. 0 means never\n" in do_meta_command()
32237 " --skip N Skip the first N encounters\n" in do_meta_command()
32238 ,p->out in do_meta_command()
32246 sqlite3_fprintf(p->out, in do_meta_command()
32250 sqlite3_fprintf(p->out, "%d\n", rc2); in do_meta_command()
32252 sqlite3_fprintf(p->out, "0x%08x\n", rc2); in do_meta_command()
32259 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); in do_meta_command()
32282 if( z[0]=='-' ){ in do_meta_command()
32284 p->eTraceType = SHELL_TRACE_EXPANDED; in do_meta_command()
32288 p->eTraceType = SHELL_TRACE_NORMALIZED; in do_meta_command()
32292 p->eTraceType = SHELL_TRACE_PLAIN; in do_meta_command()
32312 output_file_close(p->traceOut); in do_meta_command()
32313 p->traceOut = output_file_open(z); in do_meta_command()
32316 if( p->traceOut==0 ){ in do_meta_command()
32317 sqlite3_trace_v2(p->db, 0, 0, 0); in do_meta_command()
32320 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p); in do_meta_command()
32331 eputz("Usage: .unmodule [--allexcept] NAME ...\n"); in do_meta_command()
32337 if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++; in do_meta_command()
32339 if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){ in do_meta_command()
32340 assert( azArg[nArg]==0 ); in do_meta_command()
32341 sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0); in do_meta_command()
32344 sqlite3_create_module(p->db, azArg[ii], 0, 0); in do_meta_command()
32351 char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit"; in do_meta_command()
32352 sqlite3_fprintf(p->out, "SQLite %s %s\n" /*extra-version-info*/, in do_meta_command()
32355 sqlite3_fprintf(p->out, "zlib version %s\n", zlibVersion()); in do_meta_command()
32360 sqlite3_fprintf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "." in do_meta_command()
32364 sqlite3_fprintf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz); in do_meta_command()
32366 sqlite3_fprintf(p->out, "gcc-" __VERSION__ " (%s)\n", zPtrSz); in do_meta_command()
32373 if( p->db ){ in do_meta_command()
32374 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); in do_meta_command()
32376 sqlite3_fprintf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName); in do_meta_command()
32377 sqlite3_fprintf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); in do_meta_command()
32378 sqlite3_fprintf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); in do_meta_command()
32379 sqlite3_fprintf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); in do_meta_command()
32387 if( p->db ){ in do_meta_command()
32388 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); in do_meta_command()
32390 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ in do_meta_command()
32391 sqlite3_fprintf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName, in do_meta_command()
32392 pVfs==pCurrent ? " <--- CURRENT" : ""); in do_meta_command()
32393 sqlite3_fprintf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); in do_meta_command()
32394 sqlite3_fprintf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); in do_meta_command()
32395 sqlite3_fprintf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); in do_meta_command()
32396 if( pVfs->pNext ){ in do_meta_command()
32397 sqlite3_fputs("-----------------------------------\n", p->out); in do_meta_command()
32405 if( p->db ){ in do_meta_command()
32406 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); in do_meta_command()
32408 sqlite3_fprintf(p->out, "%s\n", zVfsName); in do_meta_command()
32421 assert( nArg<=ArraySize(azArg) ); in do_meta_command()
32422 p->nWidth = nArg-1; in do_meta_command()
32423 p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2); in do_meta_command()
32424 if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory(); in do_meta_command()
32425 if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth]; in do_meta_command()
32427 p->colWidth[j-1] = (int)integerValue(azArg[j]); in do_meta_command()
32438 if( p->outCount ){ in do_meta_command()
32439 p->outCount--; in do_meta_command()
32440 if( p->outCount==0 ) output_reset(p); in do_meta_command()
32442 p->bSafeMode = p->bSafeModePersist; in do_meta_command()
32453 QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
32477 case '-': in quickscan()
32478 if( *zLine!='-' ) in quickscan()
32508 CONTINUE_PAREN_INCR(pst, -1); in quickscan()
32529 /* Swallow doubled end-delimiter.*/ in quickscan()
32538 default: assert(0); in quickscan()
32548 ** than a semi-colon. The SQL Server style "go" command is understood
32572 ** ends in the middle of a string literal or C-style comment.
32592 ** 4. The shell is not running in --safe mode.
32598 ** 2-6: Currently running .dump transaction. If the "2" bit is set,
32600 ** 7: Nothing left to do. This function becomes a no-op.
32605 if( p->eRestoreState<7 ){ in doAutoDetectRestore()
32606 switch( p->eRestoreState ){ in doAutoDetectRestore()
32609 assert( strlen(zExpect)==24 ); in doAutoDetectRestore()
32610 if( p->bSafeMode==0 in doAutoDetectRestore()
32614 p->eRestoreState = 1; in doAutoDetectRestore()
32616 p->eRestoreState = 7; in doAutoDetectRestore()
32624 assert( strlen(zExpect)==18 ); in doAutoDetectRestore()
32631 shellPrepare(p->db, &rc, zQuery, &pStmt); in doAutoDetectRestore()
32640 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense); in doAutoDetectRestore()
32641 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl); in doAutoDetectRestore()
32642 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0); in doAutoDetectRestore()
32643 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, 0); in doAutoDetectRestore()
32644 p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0); in doAutoDetectRestore()
32646 p->eRestoreState = 7; in doAutoDetectRestore()
32652 if( sqlite3_get_autocommit(p->db) ){ in doAutoDetectRestore()
32653 if( (p->eRestoreState & 2) ){ in doAutoDetectRestore()
32654 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, 0); in doAutoDetectRestore()
32656 if( (p->eRestoreState & 4) ){ in doAutoDetectRestore()
32657 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, 0); in doAutoDetectRestore()
32659 p->eRestoreState = 7; in doAutoDetectRestore()
32678 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; in runOneSqlLine()
32681 END_TIMER(p->out); in runOneSqlLine()
32688 zErrorTail = sqlite3_errmsg(p->db); in runOneSqlLine()
32713 sqlite3_changes64(p->db), sqlite3_total_changes64(p->db)); in runOneSqlLine()
32714 sqlite3_fprintf(p->out, "%s\n", zLineBuf); in runOneSqlLine()
32723 sqlite3_fprintf(p->out, "%s\n", zDo); in echo_group_input()
32724 fflush(p->out); in echo_group_input()
32749 if(nZ>0 && '\r'==zBegin[nZ-1]){ in one_input_line()
32750 --nZ; in one_input_line()
32763 ** is interactive - the user is typing it it. Otherwise, input
32781 if( p->inputNesting==MAX_INPUT_NESTING ){ in process_input()
32784 " Check recursion.\n", MAX_INPUT_NESTING, p->lineno); in process_input()
32787 ++p->inputNesting; in process_input()
32788 p->lineno = 0; in process_input()
32790 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){ in process_input()
32791 fflush(p->out); in process_input()
32792 zLine = one_input_line(p->in, zLine, nSql>0); in process_input()
32795 if( p->in==0 && stdin_is_interactive ) sqlite3_fputs("\n", p->out); in process_input()
32799 if( p->in!=0 ) break; in process_input()
32802 p->lineno++; in process_input()
32810 /* Just swallow single-line whitespace */ in process_input()
32829 /* No single-line dispositions remain; accumulate line(s). */ in process_input()
32832 /* Grow buffer by half-again increments when big. */ in process_input()
32840 assert( nAlloc>0 && zSql!=0 ); in process_input()
32841 memcpy(zSql, zLine+i, nLine+1-i); in process_input()
32842 startline = p->lineno; in process_input()
32843 nSql = nLine-i; in process_input()
32851 errCnt += runOneSqlLine(p, zSql, p->in, startline); in process_input()
32854 if( p->outCount ){ in process_input()
32856 p->outCount = 0; in process_input()
32860 p->bSafeMode = p->bSafeModePersist; in process_input()
32871 errCnt += runOneSqlLine(p, zSql, p->in, startline); in process_input()
32876 --p->inputNesting; in process_input()
32899 home_dir = pwent->pw_dir; in find_home_dir()
32905 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() in find_home_dir()
32950 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
32998 FILE *inSaved = p->in; in process_sqliterc()
32999 int savedLineno = p->lineno; in process_sqliterc()
33007 eputz("-- warning: cannot find home directory;" in process_sqliterc()
33015 p->in = sqlite3_fopen(sqliterc,"rb"); in process_sqliterc()
33016 if( p->in ){ in process_sqliterc()
33018 sqlite3_fprintf(stderr,"-- Loading resources from %s\n", sqliterc); in process_sqliterc()
33021 fclose(p->in); in process_sqliterc()
33026 p->in = inSaved; in process_sqliterc()
33027 p->lineno = savedLineno; in process_sqliterc()
33035 " -- treat no subsequent arguments as options\n"
33037 " -A ARGS... run \".archive ARGS\" and exit\n"
33039 " -append append the database to the end of the file\n"
33040 " -ascii set output mode to 'ascii'\n"
33041 " -bail stop after hitting an error\n"
33042 " -batch force batch I/O\n"
33043 " -box set output mode to 'box'\n"
33044 " -column set output mode to 'column'\n"
33045 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
33046 " -csv set output mode to 'csv'\n"
33048 " -deserialize open the database using sqlite3_deserialize()\n"
33050 " -echo print inputs before execution\n"
33051 " -escape T ctrl-char escape; T is one of: symbol, ascii, off\n"
33052 " -init FILENAME read/process named file\n"
33053 " -[no]header turn headers on or off\n"
33055 " -heap SIZE Size of heap for memsys3 or memsys5\n"
33057 " -help show this message\n"
33058 " -html set output mode to HTML\n"
33059 " -interactive force interactive I/O\n"
33060 " -json set output mode to 'json'\n"
33061 " -line set output mode to 'line'\n"
33062 " -list set output mode to 'list'\n"
33063 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
33064 " -markdown set output mode to 'markdown'\n"
33066 " -maxsize N maximum size for a --deserialize database\n"
33068 " -memtrace trace all memory allocations and deallocations\n"
33069 " -mmap N default mmap size set to N\n"
33071 " -multiplex enable the multiplexor VFS\n"
33073 " -newline SEP set output row separator. Default: '\\n'\n"
33074 " -nofollow refuse to open symbolic links to database files\n"
33075 " -nonce STRING set the safe-mode escape nonce\n"
33076 " -no-rowid-in-view Disable rowid-in-view using sqlite3_config()\n"
33077 " -nullvalue TEXT set text string for NULL values. Default ''\n"
33078 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
33079 " -pcachetrace trace all page cache operations\n"
33080 " -quote set output mode to 'quote'\n"
33081 " -readonly open the database read-only\n"
33082 " -safe enable safe-mode\n"
33083 " -separator SEP set output column separator. Default: '|'\n"
33085 " -sorterref SIZE sorter references threshold size\n"
33087 " -stats print memory stats before each finalize\n"
33088 " -table set output mode to 'table'\n"
33089 " -tabs set output mode to 'tabs'\n"
33090 " -unsafe-testing allow unsafe commands and modes for testing\n"
33091 " -version show SQLite version\n"
33092 " -vfs NAME use NAME as the default VFS\n"
33093 " -vfstrace enable tracing of all VFS calls\n"
33095 " -zip open the file as a ZIP Archive\n"
33105 eputz("Use the -help option for additional information\n"); in usage()
33115 if( sqlite3_config(-1)==SQLITE_MISUSE ){ in verify_uninitialized()
33126 data->normalMode = data->cMode = data->mode = MODE_List; in main_init()
33127 data->autoExplain = 1; in main_init()
33129 data->crlfMode = 1; in main_init()
33131 data->pAuxDb = &data->aAuxDb[0]; in main_init()
33132 memcpy(data->colSeparator,SEP_Column, 2); in main_init()
33133 memcpy(data->rowSeparator,SEP_Row, 2); in main_init()
33134 data->showHeader = 0; in main_init()
33135 data->shellFlgs = SHFLG_Lookaside; in main_init()
33171 ** Get the argument to an --option. Throw an error and die if no argument
33177 "%s: Error: missing argument to %s\n", argv[0], argv[argc-1]); in cmdline_option_value()
33191 sqlite3_fputs(z, p->out); in vfstraceOut()
33192 fflush(p->out); in vfstraceOut()
33233 const char *zVfs = 0; /* Value of -vfs command-line option */
33296 /* On Windows, we must translate command-line arguments into UTF-8.
33322 assert( argc>=1 && argv && argv[0] );
33328 ** of a C-function that will provide the name of the database file. Use
33329 ** this compile-time option to embed this shell program in larger
33332 SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
33337 /* Do an initial pass through the command-line argument to locate
33348 if( z[0]!='-' || i>nOptsEnd ){
33349 if( data.aAuxDb->zDbFilename==0 ){
33350 data.aAuxDb->zDbFilename = z;
33352 /* Excess arguments are interpreted as SQL (or dot-commands) and
33358 azCmd[nCmd-1] = z;
33362 if( z[1]=='-' ) z++;
33363 if( cli_strcmp(z, "-")==0 ){
33366 }else if( cli_strcmp(z,"-separator")==0
33367 || cli_strcmp(z,"-nullvalue")==0
33368 || cli_strcmp(z,"-newline")==0
33369 || cli_strcmp(z,"-cmd")==0
33372 }else if( cli_strcmp(z,"-init")==0 ){
33374 }else if( cli_strcmp(z,"-interactive")==0 ){
33375 }else if( cli_strcmp(z,"-batch")==0 ){
33381 }else if( cli_strcmp(z,"-utf8")==0 ){
33382 }else if( cli_strcmp(z,"-no-utf8")==0 ){
33383 }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
33386 assert( val==0 );
33387 }else if( cli_strcmp(z,"-heap")==0 ){
33400 }else if( cli_strcmp(z,"-pagecache")==0 ){
33413 }else if( cli_strcmp(z,"-lookaside")==0 ){
33422 }else if( cli_strcmp(z,"-threadsafe")==0 ){
33431 }else if( cli_strcmp(z,"-vfstrace")==0 ){
33434 }else if( cli_strcmp(z,"-multiplex")==0 ){
33438 }else if( cli_strcmp(z,"-mmap")==0 ){
33443 }else if( cli_strcmp(z,"-sorterref")==0 ){
33448 }else if( cli_strcmp(z,"-vfs")==0 ){
33451 }else if( cli_strcmp(z,"-zip")==0 ){
33454 }else if( cli_strcmp(z,"-append")==0 ){
33457 }else if( cli_strcmp(z,"-deserialize")==0 ){
33459 }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
33462 }else if( cli_strcmp(z,"-readonly")==0 ){
33464 }else if( cli_strcmp(z,"-nofollow")==0 ){
33467 }else if( cli_strncmp(z, "-A",2)==0 ){
33468 /* All remaining command-line arguments are passed to the ".archive"
33472 }else if( cli_strcmp(z, "-memtrace")==0 ){
33474 }else if( cli_strcmp(z, "-pcachetrace")==0 ){
33476 }else if( cli_strcmp(z,"-bail")==0 ){
33478 }else if( cli_strcmp(z,"-nonce")==0 ){
33481 }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
33483 }else if( cli_strcmp(z,"-safe")==0 ){
33484 /* no-op - catch this on the second pass */
33485 }else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
33498 ** of a C-function that will perform initialization actions on SQLite that
33499 ** occur just before or after sqlite3_initialize(). Use this compile-time
33506 ** to call sqlite3_initialize() and process any command line -vfs option. */
33520 if( data.pAuxDb->zDbFilename==0 ){
33522 data.pAuxDb->zDbFilename = ":memory:";
33541 ** to the sqlite command-line tool.
33543 if( access(data.pAuxDb->zDbFilename, 0)==0 ){
33547 /* Process the initialization file if there is one. If no -init option
33553 /* Make a second pass through the command-line argument and set
33555 ** file is processed so that the command-line arguments will override
33560 if( z[0]!='-' || i>=nOptsEnd ) continue;
33561 if( z[1]=='-' ){ z++; }
33562 if( cli_strcmp(z,"-init")==0 ){
33564 }else if( cli_strcmp(z,"-html")==0 ){
33566 }else if( cli_strcmp(z,"-list")==0 ){
33568 }else if( cli_strcmp(z,"-quote")==0 ){
33572 }else if( cli_strcmp(z,"-line")==0 ){
33574 }else if( cli_strcmp(z,"-column")==0 ){
33576 }else if( cli_strcmp(z,"-json")==0 ){
33578 }else if( cli_strcmp(z,"-markdown")==0 ){
33580 }else if( cli_strcmp(z,"-table")==0 ){
33582 }else if( cli_strcmp(z,"-box")==0 ){
33584 }else if( cli_strcmp(z,"-csv")==0 ){
33587 }else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
33588 /* See similar code at tag-20250224-1 */
33599 " - choices:", zEsc);
33607 }else if( cli_strcmp(z,"-zip")==0 ){
33610 }else if( cli_strcmp(z,"-append")==0 ){
33613 }else if( cli_strcmp(z,"-deserialize")==0 ){
33615 }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
33618 }else if( cli_strcmp(z,"-readonly")==0 ){
33620 }else if( cli_strcmp(z,"-nofollow")==0 ){
33622 }else if( cli_strcmp(z,"-ascii")==0 ){
33626 }else if( cli_strcmp(z,"-tabs")==0 ){
33630 }else if( cli_strcmp(z,"-separator")==0 ){
33633 }else if( cli_strcmp(z,"-newline")==0 ){
33636 }else if( cli_strcmp(z,"-nullvalue")==0 ){
33639 }else if( cli_strcmp(z,"-header")==0 ){
33642 }else if( cli_strcmp(z,"-noheader")==0 ){
33645 }else if( cli_strcmp(z,"-echo")==0 ){
33647 }else if( cli_strcmp(z,"-eqp")==0 ){
33649 }else if( cli_strcmp(z,"-eqpfull")==0 ){
33651 }else if( cli_strcmp(z,"-stats")==0 ){
33653 }else if( cli_strcmp(z,"-scanstats")==0 ){
33655 }else if( cli_strcmp(z,"-backslash")==0 ){
33656 /* Undocumented command-line option: -backslash
33657 ** Causes C-style backslash escapes to be evaluated in SQL statements
33662 }else if( cli_strcmp(z,"-bail")==0 ){
33663 /* No-op. The bail_on_error flag should already be set. */
33664 }else if( cli_strcmp(z,"-version")==0 ){
33665 sqlite3_fprintf(stdout, "%s %s (%d-bit)\n",
33668 }else if( cli_strcmp(z,"-interactive")==0 ){
33673 }else if( cli_strcmp(z,"-batch")==0 ){
33675 }else if( cli_strcmp(z,"-utf8")==0 ){
33677 }else if( cli_strcmp(z,"-no-utf8")==0 ){
33679 }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
33681 }else if( cli_strcmp(z,"-heap")==0 ){
33683 }else if( cli_strcmp(z,"-pagecache")==0 ){
33685 }else if( cli_strcmp(z,"-lookaside")==0 ){
33687 }else if( cli_strcmp(z,"-threadsafe")==0 ){
33689 }else if( cli_strcmp(z,"-nonce")==0 ){
33691 }else if( cli_strcmp(z,"-mmap")==0 ){
33693 }else if( cli_strcmp(z,"-memtrace")==0 ){
33695 }else if( cli_strcmp(z,"-pcachetrace")==0 ){
33698 }else if( cli_strcmp(z,"-sorterref")==0 ){
33701 }else if( cli_strcmp(z,"-vfs")==0 ){
33703 }else if( cli_strcmp(z,"-vfstrace")==0 ){
33706 }else if( cli_strcmp(z,"-multiplex")==0 ){
33709 }else if( cli_strcmp(z,"-help")==0 ){
33711 }else if( cli_strcmp(z,"-cmd")==0 ){
33712 /* Run commands that follow -cmd first and separately from commands
33713 ** that simply appear on the command-line. This seems goofy. It would
33716 if( i==argc-1 ) break;
33733 }else if( cli_strncmp(z, "-A", 2)==0 ){
33735 sqlite3_fprintf(stderr,"Error: cannot mix regular SQL or dot-commands"
33742 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
33744 arDotCommand(&data, 1, argv+i, argc-i);
33749 }else if( cli_strcmp(z,"-safe")==0 ){
33751 }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
33755 eputz("Use -help for a list of options.\n");
33762 /* Run all arguments that do not begin with '-' as if they were separate
33763 ** command-line inputs, except for the argToSkip argument which contains
33798 "SQLite version %s %.19s\n" /*extra-version-info*/
33803 printBold("transient in-memory database");
33848 session_close_all(&data, -1);
33877 (unsigned int)(sqlite3_memory_used()-mem_main_enter));
33941 ** Completely wipes out the contents of the currently-opened database
33953 sqlite3_fputs("Rolling back in-progress transaction.\n", stdout);
33966 ** on success, non-0 on error. This function returns 0 on success,
33967 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
33968 ** code from the callback. Note that this is not thread-friendly: it
33983 rc = pFile->pMethods->xFileSize(pFile, &nSize);
33995 rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);