Lines Matching +full:io +full:- +full:multiplex
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.
201 # include <io.h>
233 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
235 * overridden with the -batch command line option.
281 ** by the SQLite project command-line tools. These interfaces are used
284 ** "single-source" forms or separate compilation then linking.
324 ** Returns the bit-wise OR of SAC_{In,Out,Err}Console values,
328 ** the given streams. As a side-effect, the given inputs are
354 ** Undo any side-effects left by consoleClassifySetup(...).
404 ** console and translation from UTF-8 is necessary, perform
406 ** to the provided stream almost as-is, possibly with newline
417 ** console and translation from UTF-8 is necessary, perform
419 ** provided stream almost as-is, possibly with newline
467 ** An additional side-effect is that if the stream is one passed
488 ** line-editing library or simple console interaction.
500 ** SHELL_ADD_HISTORY(T) as record-worthy input is taken;
520 ** This function may call upon services of a line-editing
529 ** completion candidates for use by the line-editor.
532 ** that does this. Yet, getting line-editing melded into
533 ** console I/O is desirable because a line-editing library
539 /* Skip over as much z[] input char sequence as is valid UTF-8,
542 ** sequence z:return (inclusive:exclusive) is validated UTF-8.
564 ** by the SQLite project command-line tools, as explained in console_io.h .
590 # include <io.h>
629 /* Define NULL-like value for things which can validly be 0. */
645 return (ppst->hx != INVALID_HANDLE_VALUE); in pstReachesConsole()
653 if( pstReachesConsole(ppst) ) SetConsoleMode(ppst->hx, ppst->consMode); in restoreConsoleArb()
665 ppst->pf = pf; in streamOfConsole()
669 ppst->hx = (rv)? fh : INVALID_HANDLE_VALUE; in streamOfConsole()
670 ppst->consMode = dwCM; in streamOfConsole()
673 ppst->pf = pf; in streamOfConsole()
674 ppst->reachesConsole = ( (short)isatty(fileno(pf)) ); in streamOfConsole()
675 return ppst->reachesConsole; in streamOfConsole()
699 return (ppst->pf != SHELL_INVALID_FILE_PTR); in isValidStreamInfo()
714 SetConsoleMode(ppst->hx, cm); in maybeSetupAsConsole()
726 &consoleInfo.pstSetup[ix] : &consoleInfo.pstDesignated[ix-3]; in consoleRenewSetup()
738 for( ix = 2; ix >= 0; --ix ){ in consoleClassifySetup()
754 if( pci->sacSetup ){ in consoleRestore()
757 if( pci->sacSetup & (SAC_InConsole<<ix) ){ in consoleRestore()
758 PerStreamTags *ppst = &pci->pstSetup[ix]; in consoleRestore()
759 SetConsoleMode(ppst->hx, ppst->consMode); in consoleRestore()
779 if( apst[ix]->pf == pf ) break; in isKnownReadable()
798 if( apst[ix]->pf == pf ) break; in isKnownWritable()
863 /* Translation from UTF-8 to UTF-16, then WCHARs out. */ in conZstrEmit()
864 if( WriteConsoleW(ppst->hx, zw,nwc, 0, NULL) ){ in conZstrEmit()
899 ** In either case, ppst references a caller-owned PerStreamTags
913 pfEmit = ppst->pf; in getEmitStreamInfo()
914 }else pfEmit = ppstTry->pf; in getEmitStreamInfo()
995 if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst); in fPrintfUtf8()
1019 if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst); in fPutsUtf8()
1070 /* Skip over as much z[] input char sequence as is valid UTF-8,
1073 ** sequence z:return (inclusive:exclusive) is validated UTF-8.
1078 int ng = (nAccept<0)? -nAccept : 0; in zSkipValidUtf8()
1081 while( (pcLimit)? (z<pcLimit) : (ng-- != 0) ){ in zSkipValidUtf8()
1093 if( ct==0 || (zt-z)>4 || (ct & 0xC0)!=0x80 ){ in zSkipValidUtf8()
1118 if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst); in fPutbUtf8()
1177 while( noc < ncMax-8-1 && !lend ){ in fGetsUtf8()
1178 /* There is room for at least 2 more characters and a 0-terminator. */ in fGetsUtf8()
1179 int na = (ncMax > SHELL_GULP*4+1 + noc)? SHELL_GULP : (ncMax-1 - noc)/4; in fGetsUtf8()
1183 if( bRC && nbr>0 && (wcBuf[nbr-1]&0xF800)==0xD800 ){ in fGetsUtf8()
1184 /* Last WHAR read is first of a UTF-16 surrogate pair. Grab its mate. */ in fGetsUtf8()
1196 /* Fixup line-ends as coded by Windows for CR (or "Enter".) in fGetsUtf8()
1201 if( cBuf[noc-1]=='\n' ){ in fGetsUtf8()
1203 if( noc > 1 && cBuf[noc-2]=='\r' ) cBuf[--noc-1] = '\n'; in fGetsUtf8()
1218 /* If got nothing, (after ^Z chop), must be at end-of-file. */ in fGetsUtf8()
1247 * sputz(s, z) => emit 0-terminated string z to given stream s
1249 * oputz(z) => emit 0-terminated string z to default stream
1251 * eputz(z) => emit 0-terminated string z to error stream
1253 * oputb(b, n) => emit char buffer b[0..n-1] to default stream
1258 * For the stand-alone CLI, it is stdout with no .output redirect.
1274 * from the WASM build are issued for non-formatted output, (when a mere
1276 * (This permits compile-time checking of format string / argument mismatch.)
1303 /* Return the current wall-clock time */
1309 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){ in timeOfDay()
1310 clockVfs->xCurrentTimeInt64(clockVfs, &t); in timeOfDay()
1313 clockVfs->xCurrentTime(clockVfs, &r); in timeOfDay()
1334 static sqlite3_int64 iBegin; /* Wall-clock time at start */
1348 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + in timeDiff()
1349 (double)(pEnd->tv_sec - pStart->tv_sec); in timeDiff()
1361 (iEnd - iBegin)*0.001, in endTimer()
1428 return (double) ((i64End - i64Start) / 10000000.0); in timeDiff()
1440 (ftWallEnd - ftWallBegin)*0.001, in endTimer()
1480 ** in order to show that UTF-16 translation is done in the sign-on
1493 ** True if an interrupt (Control-C) has been received.
1513 /* This is variant of the standard-library strncpy() routine with the
1514 ** one change that the destination string is always zero-terminated, even
1515 ** if there is no zero-terminator in the first n-1 characters of the source
1520 for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i]; in shell_strncpy()
1528 ** or open parentheses level if non-zero, or continuation prompt as set.
1564 p->inParenLevel += ni; in trackParenLevel()
1565 if( ni==0 ) p->inParenLevel = 0; in trackParenLevel()
1566 p->zScannerAwaits = 0; in trackParenLevel()
1572 p->zScannerAwaits = s; in setLexemeOpen()
1573 p->acAwait[0] = 0; in setLexemeOpen()
1575 p->acAwait[0] = c; in setLexemeOpen()
1576 p->zScannerAwaits = p->acAwait; in setLexemeOpen()
1589 if( ndp > ncp-3 ) return continuePrompt; in dynamicContinuePrompt()
1593 PROMPT_LEN_MAX-4); in dynamicContinuePrompt()
1604 PROMPT_LEN_MAX-4); in dynamicContinuePrompt()
1611 /* Indicate out-of-memory and exit. */
1618 ** out-of-memory error.
1652 ** then right-justify the text. W is the width in UTF-8 characters, not
1659 int aw = w<0 ? -w : w; in utf8_width_print()
1673 oputf("%*s%s", aw-n, "", zUtf); in utf8_width_print()
1675 oputf("%s%*s", zUtf, aw-n, ""); in utf8_width_print()
1684 if( *z=='-' || *z=='+' ) z++; in isNumber()
1699 if( *z=='+' || *z=='-' ) z++; in isNumber()
1709 ** lower 30 bits of a 32-bit signed integer.
1714 return 0x3fffffff & (int)(z2 - z); in strlen30()
1782 if( fgets(&zLine[n], nLine - n, in)==0 ){ in local_getline()
1791 if( n>0 && zLine[n-1]=='\n' ){ in local_getline()
1792 n--; in local_getline()
1793 if( n>0 && zLine[n-1]=='\r' ) n--; in local_getline()
1849 ** Return the value of a hexadecimal digit. Return -1 if the input
1853 if( c>='0' && c<='9' ) return c - '0'; in hexDigitValue()
1854 if( c>='a' && c<='f' ) return c - 'a' + 10; in hexDigitValue()
1855 if( c>='A' && c<='F' ) return c - 'A' + 10; in hexDigitValue()
1856 return -1; in hexDigitValue()
1877 if( zArg[0]=='-' ){ in integerValue()
1892 v = v*10 + zArg[0] - '0'; in integerValue()
1902 return isNeg? -v : v; in integerValue()
1922 free(p->z); in freeText()
1926 /* zIn is either a pointer to a NULL-terminated string in memory obtained
1939 len = nAppend+p->n+1; in appendText()
1947 if( p->z==0 || p->n+len>=p->nAlloc ){ in appendText()
1948 p->nAlloc = p->nAlloc*2 + len + 20; in appendText()
1949 p->z = realloc(p->z, p->nAlloc); in appendText()
1950 shell_check_oom(p->z); in appendText()
1954 char *zCsr = p->z+p->n; in appendText()
1961 p->n = (int)(zCsr - p->z); in appendText()
1964 memcpy(p->z+p->n, zAppend, nAppend); in appendText()
1965 p->n += nAppend; in appendText()
1966 p->z[p->n] = '\0'; in appendText()
1972 ** because it contains non-alphanumeric characters, or because it is an
2007 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); in shellFakeSchema()
2039 ** Use the C-library strtod() function to convert string X into a double.
2040 ** Used for comparing the accuracy of SQLite's internal text-to-float conversion
2041 ** routines against the C-library.
2057 ** Use the C-library printf() function to convert real value X into a string.
2058 ** Used for comparing the accuracy of SQLite's internal float-to-text conversion
2059 ** routines against the C-library.
2072 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); in shellDtostr()
2079 ** Return a fake schema for the table-valued function or eponymous virtual
2094 -1, sqlite3_free); in shellModuleSchema()
2105 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
2163 sqlite3_result_text(pCtx, z, -1, sqlite3_free); in shellAddSchemaName()
2173 ** The source code for several run-time loadable extensions is inserted
2224 #include <io.h>
2284 # define BAD_INTPTR_T ((intptr_t)(-1))
2326 ** function. This function is not thread-safe.
2365 ** This function is not thread-safe.
2378 ** The function call to GetEnvironmentVariableA() failed -OR- in windirent_getenv()
2385 ** -AND- the buffer contains the entire value. in windirent_getenv()
2404 /* TODO: Remove this if Unix-style root paths are not used. */ in opendir()
2411 dirp->d_handle = _findfirst(data.name, &data); in opendir()
2413 if( dirp->d_handle==BAD_INTPTR_T ){ in opendir()
2423 if( _findnext(dirp->d_handle, &data)==-1 ){ in opendir()
2432 dirp->d_first.d_attributes = data.attrib; in opendir()
2433 strncpy(dirp->d_first.d_name, data.name, NAME_MAX); in opendir()
2434 dirp->d_first.d_name[NAME_MAX] = '\0'; in opendir()
2449 if( dirp->d_first.d_ino==0 ){ in readdir()
2450 dirp->d_first.d_ino++; in readdir()
2451 dirp->d_next.d_ino++; in readdir()
2453 return &dirp->d_first; in readdir()
2459 if( _findnext(dirp->d_handle, &data)==-1 ) return NULL; in readdir()
2464 dirp->d_next.d_ino++; in readdir()
2465 dirp->d_next.d_attributes = data.attrib; in readdir()
2466 strncpy(dirp->d_next.d_name, data.name, NAME_MAX); in readdir()
2467 dirp->d_next.d_name[NAME_MAX] = '\0'; in readdir()
2469 return &dirp->d_next; in readdir()
2484 if( dirp->d_first.d_ino==0 ){ in readdir_r()
2485 dirp->d_first.d_ino++; in readdir_r()
2486 dirp->d_next.d_ino++; in readdir_r()
2488 entry->d_ino = dirp->d_first.d_ino; in readdir_r()
2489 entry->d_attributes = dirp->d_first.d_attributes; in readdir_r()
2490 strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX); in readdir_r()
2491 entry->d_name[NAME_MAX] = '\0'; in readdir_r()
2500 if( _findnext(dirp->d_handle, &data)==-1 ){ in readdir_r()
2508 entry->d_ino = (ino_t)-1; /* not available */ in readdir_r()
2509 entry->d_attributes = data.attrib; in readdir_r()
2510 strncpy(entry->d_name, data.name, NAME_MAX); in readdir_r()
2511 entry->d_name[NAME_MAX] = '\0'; in readdir_r()
2527 if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){ in closedir()
2528 result = _findclose(dirp->d_handle); in closedir()
2542 ** 2019-01-21
2561 ** This extension is used to implement the --memtrace option of the
2562 ** command-line shell.
2594 fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n", in memtraceRealloc()
2653 ** 2023-06-21
2672 ** This extension is used to implement the --pcachetrace option of the
2673 ** command-line shell.
2691 fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p) -> %d\n", pArg, nRes); in pcachetraceInit()
2709 fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d) -> %p\n", in pcachetraceCreate()
2727 fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p) -> %d\n", p, nRes); in pcachetracePagecount()
2742 fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d) -> %p\n", in pcachetraceFetch()
2835 ** 2017-03-08
2847 ** in the way described by the (U.S.) NIST FIPS 202 SHA-3 Standard.
2859 ** The SIZE argument is optional. If omitted, the SHA3-256 hash algorithm
2878 ** and whether or not that determination is run-time or compile-time.
2880 ** For best performance, an attempt is made to guess at the byte-order
2881 ** using C-preprocessor macros. If that is unsuccessful, or if
2882 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
2883 ** at run-time.
2914 ** A single step of the Keccak mixing function for a 1600-bit state
2935 # define a00 (p->u.s[0]) in KeccakF1600Step()
2936 # define a01 (p->u.s[1]) in KeccakF1600Step()
2937 # define a02 (p->u.s[2]) in KeccakF1600Step()
2938 # define a03 (p->u.s[3]) in KeccakF1600Step()
2939 # define a04 (p->u.s[4]) in KeccakF1600Step()
2940 # define a10 (p->u.s[5]) in KeccakF1600Step()
2941 # define a11 (p->u.s[6]) in KeccakF1600Step()
2942 # define a12 (p->u.s[7]) in KeccakF1600Step()
2943 # define a13 (p->u.s[8]) in KeccakF1600Step()
2944 # define a14 (p->u.s[9]) in KeccakF1600Step()
2945 # define a20 (p->u.s[10]) in KeccakF1600Step()
2946 # define a21 (p->u.s[11]) in KeccakF1600Step()
2947 # define a22 (p->u.s[12]) in KeccakF1600Step()
2948 # define a23 (p->u.s[13]) in KeccakF1600Step()
2949 # define a24 (p->u.s[14]) in KeccakF1600Step()
2950 # define a30 (p->u.s[15]) in KeccakF1600Step()
2951 # define a31 (p->u.s[16]) in KeccakF1600Step()
2952 # define a32 (p->u.s[17]) in KeccakF1600Step()
2953 # define a33 (p->u.s[18]) in KeccakF1600Step()
2954 # define a34 (p->u.s[19]) in KeccakF1600Step()
2955 # define a40 (p->u.s[20]) in KeccakF1600Step()
2956 # define a41 (p->u.s[21]) in KeccakF1600Step()
2957 # define a42 (p->u.s[22]) in KeccakF1600Step()
2958 # define a43 (p->u.s[23]) in KeccakF1600Step()
2959 # define a44 (p->u.s[24]) in KeccakF1600Step()
2960 # define ROL64(a,x) ((a<<x)|(a>>(64-x))) in KeccakF1600Step()
3241 p->nRate = (1600 - ((iSize + 31)&~31)*2)/8; in SHA3Init()
3243 p->nRate = (1600 - 2*256)/8; in SHA3Init()
3246 /* Known to be little-endian at compile-time. No-op */ in SHA3Init()
3248 p->ixMask = 7; /* Big-endian */ in SHA3Init()
3254 p->ixMask = 0; in SHA3Init()
3257 p->ixMask = 7; in SHA3Init()
3275 if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){ in SHA3Update()
3277 p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i]; in SHA3Update()
3278 p->nLoaded += 8; in SHA3Update()
3279 if( p->nLoaded>=p->nRate ){ in SHA3Update()
3281 p->nLoaded = 0; in SHA3Update()
3288 p->u.x[p->nLoaded] ^= aData[i]; in SHA3Update()
3290 p->u.x[p->nLoaded^0x07] ^= aData[i]; in SHA3Update()
3292 p->u.x[p->nLoaded^p->ixMask] ^= aData[i]; in SHA3Update()
3294 p->nLoaded++; in SHA3Update()
3295 if( p->nLoaded==p->nRate ){ in SHA3Update()
3297 p->nLoaded = 0; in SHA3Update()
3309 if( p->nLoaded==p->nRate-1 ){ in SHA3Final()
3316 p->nLoaded = p->nRate - 1; in SHA3Final()
3319 for(i=0; i<p->nRate; i++){ in SHA3Final()
3320 p->u.x[i+p->nRate] = p->u.x[i^p->ixMask]; in SHA3Final()
3322 return &p->u.x[p->nRate]; in SHA3Final()
3330 ** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
3332 ** For all other non-NULL types of input, X is converted into a UTF-8 string
3351 "384 512", -1); in sha3Func()
3387 ** argument. The results are hashed using a SIZE-bit SHA3. The default
3396 ** F<ieee-float>
3401 ** the size of that text. The SQL text is UTF-8. A single R character
3403 ** I mean an 8-byte little-endian integer <int>. F is a floating point
3404 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
3406 ** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
3437 "384 512", -1); in sha3QueryFunc()
3444 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql); in sha3QueryFunc()
3449 sqlite3_result_error(context, zMsg, -1); in sha3QueryFunc()
3454 char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt)); in sha3QueryFunc()
3456 sqlite3_result_error(context, zMsg, -1); in sha3QueryFunc()
3483 for(j=8; j>=1; j--){ in sha3QueryFunc()
3497 for(j=8; j>=1; j--){ in sha3QueryFunc()
3563 ** 2020-04-14
3589 ** 64-bit machine integer.
3611 x = zA[i] - zB[j]; in uintCollFunc()
3625 return -1; in uintCollFunc()
3639 return (nKey1 - i) - (nKey2 - j); in uintCollFunc()
3658 ** 2020-06-22
3669 ** Routines to implement arbitrary-precision decimal math.
3703 sqlite3_free(p->a); in decimal_clear()
3727 p->sign = 0; in decimalNewFromText()
3728 p->oom = 0; in decimalNewFromText()
3729 p->isInit = 1; in decimalNewFromText()
3730 p->isNull = 0; in decimalNewFromText()
3731 p->nDigit = 0; in decimalNewFromText()
3732 p->nFrac = 0; in decimalNewFromText()
3733 p->a = sqlite3_malloc64( n+1 ); in decimalNewFromText()
3734 if( p->a==0 ) goto new_from_text_failed; in decimalNewFromText()
3736 if( zIn[i]=='-' ){ in decimalNewFromText()
3737 p->sign = 1; in decimalNewFromText()
3746 p->a[p->nDigit++] = c - '0'; in decimalNewFromText()
3748 p->nFrac = p->nDigit + 1; in decimalNewFromText()
3753 if( zIn[j]=='-' ){ in decimalNewFromText()
3761 iExp = iExp*10 + zIn[j] - '0'; in decimalNewFromText()
3765 if( neg ) iExp = -iExp; in decimalNewFromText()
3770 if( p->nFrac ){ in decimalNewFromText()
3771 p->nFrac = p->nDigit - (p->nFrac - 1); in decimalNewFromText()
3774 if( p->nFrac>0 ){ in decimalNewFromText()
3775 if( iExp<=p->nFrac ){ in decimalNewFromText()
3776 p->nFrac -= iExp; in decimalNewFromText()
3779 iExp -= p->nFrac; in decimalNewFromText()
3780 p->nFrac = 0; in decimalNewFromText()
3784 p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 ); in decimalNewFromText()
3785 if( p->a==0 ) goto new_from_text_failed; in decimalNewFromText()
3786 memset(p->a+p->nDigit, 0, iExp); in decimalNewFromText()
3787 p->nDigit += iExp; in decimalNewFromText()
3791 iExp = -iExp; in decimalNewFromText()
3792 nExtra = p->nDigit - p->nFrac - 1; in decimalNewFromText()
3795 p->nFrac += iExp; in decimalNewFromText()
3798 iExp -= nExtra; in decimalNewFromText()
3799 p->nFrac = p->nDigit - 1; in decimalNewFromText()
3803 p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 ); in decimalNewFromText()
3804 if( p->a==0 ) goto new_from_text_failed; in decimalNewFromText()
3805 memmove(p->a+iExp, p->a, p->nDigit); in decimalNewFromText()
3806 memset(p->a, 0, iExp); in decimalNewFromText()
3807 p->nDigit += iExp; in decimalNewFromText()
3808 p->nFrac += iExp; in decimalNewFromText()
3815 if( p->a ) sqlite3_free(p->a); in decimalNewFromText()
3895 if( p==0 || p->oom ){ in decimal_result()
3899 if( p->isNull ){ in decimal_result()
3903 z = sqlite3_malloc( p->nDigit+4 ); in decimal_result()
3909 if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){ in decimal_result()
3910 p->sign = 0; in decimal_result()
3912 if( p->sign ){ in decimal_result()
3913 z[0] = '-'; in decimal_result()
3916 n = p->nDigit - p->nFrac; in decimal_result()
3921 while( n>1 && p->a[j]==0 ){ in decimal_result()
3923 n--; in decimal_result()
3926 z[i++] = p->a[j] + '0'; in decimal_result()
3928 n--; in decimal_result()
3930 if( p->nFrac ){ in decimal_result()
3933 z[i++] = p->a[j] + '0'; in decimal_result()
3935 }while( j<p->nDigit ); in decimal_result()
3956 if( p==0 || p->oom ){ in decimal_result_sci()
3960 if( p->isNull ){ in decimal_result_sci()
3964 for(nDigit=p->nDigit; nDigit>0 && p->a[nDigit-1]==0; nDigit--){} in decimal_result_sci()
3965 for(nZero=0; nZero<nDigit && p->a[nZero]==0; nZero++){} in decimal_result_sci()
3966 nFrac = p->nFrac + (nDigit - p->nDigit); in decimal_result_sci()
3967 nDigit -= nZero; in decimal_result_sci()
3979 a = &p->a[nZero]; in decimal_result_sci()
3981 if( p->sign && nDigit>0 ){ in decimal_result_sci()
3982 z[0] = '-'; in decimal_result_sci()
3997 exp = nDigit - nFrac - 1; in decimal_result_sci()
3998 sqlite3_snprintf(nDigit+20-i, &z[i], "e%+03d", exp); in decimal_result_sci()
3999 sqlite3_result_text(pCtx, z, -1, sqlite3_free); in decimal_result_sci()
4009 ** pA->isNull==0
4011 ** pB->isNull==0
4015 if( pA->sign!=pB->sign ){ in decimal_cmp()
4016 return pA->sign ? -1 : +1; in decimal_cmp()
4018 if( pA->sign ){ in decimal_cmp()
4023 nASig = pA->nDigit - pA->nFrac; in decimal_cmp()
4024 nBSig = pB->nDigit - pB->nFrac; in decimal_cmp()
4026 return nASig - nBSig; in decimal_cmp()
4028 n = pA->nDigit; in decimal_cmp()
4029 if( n>pB->nDigit ) n = pB->nDigit; in decimal_cmp()
4030 rc = memcmp(pA->a, pB->a, n); in decimal_cmp()
4032 rc = pA->nDigit - pB->nDigit; in decimal_cmp()
4053 if( pA==0 || pA->isNull ) goto cmp_done; in decimalCmpFunc()
4055 if( pB==0 || pB->isNull ) goto cmp_done; in decimalCmpFunc()
4057 if( rc<0 ) rc = -1; in decimalCmpFunc()
4073 nAddFrac = nFrac - p->nFrac; in decimal_expand()
4074 nAddSig = (nDigit - p->nDigit) - nAddFrac; in decimal_expand()
4076 p->a = sqlite3_realloc64(p->a, nDigit+1); in decimal_expand()
4077 if( p->a==0 ){ in decimal_expand()
4078 p->oom = 1; in decimal_expand()
4082 memmove(p->a+nAddSig, p->a, p->nDigit); in decimal_expand()
4083 memset(p->a, 0, nAddSig); in decimal_expand()
4084 p->nDigit += nAddSig; in decimal_expand()
4087 memset(p->a+p->nDigit, 0, nAddFrac); in decimal_expand()
4088 p->nDigit += nAddFrac; in decimal_expand()
4089 p->nFrac += nAddFrac; in decimal_expand()
4104 if( pA->oom || pB==0 || pB->oom ){ in decimal_add()
4105 pA->oom = 1; in decimal_add()
4108 if( pA->isNull || pB->isNull ){ in decimal_add()
4109 pA->isNull = 1; in decimal_add()
4112 nSig = pA->nDigit - pA->nFrac; in decimal_add()
4113 if( nSig && pA->a[0]==0 ) nSig--; in decimal_add()
4114 if( nSig<pB->nDigit-pB->nFrac ){ in decimal_add()
4115 nSig = pB->nDigit - pB->nFrac; in decimal_add()
4117 nFrac = pA->nFrac; in decimal_add()
4118 if( nFrac<pB->nFrac ) nFrac = pB->nFrac; in decimal_add()
4122 if( pA->oom || pB->oom ){ in decimal_add()
4123 pA->oom = 1; in decimal_add()
4125 if( pA->sign==pB->sign ){ in decimal_add()
4127 for(i=nDigit-1; i>=0; i--){ in decimal_add()
4128 int x = pA->a[i] + pB->a[i] + carry; in decimal_add()
4131 pA->a[i] = x - 10; in decimal_add()
4134 pA->a[i] = x; in decimal_add()
4140 rc = memcmp(pA->a, pB->a, nDigit); in decimal_add()
4142 aA = pB->a; in decimal_add()
4143 aB = pA->a; in decimal_add()
4144 pA->sign = !pA->sign; in decimal_add()
4146 aA = pA->a; in decimal_add()
4147 aB = pB->a; in decimal_add()
4149 for(i=nDigit-1; i>=0; i--){ in decimal_add()
4150 int x = aA[i] - aB[i] - borrow; in decimal_add()
4152 pA->a[i] = x+10; in decimal_add()
4155 pA->a[i] = x; in decimal_add()
4176 if( pA==0 || pA->oom || pA->isNull in decimalMul()
4177 || pB==0 || pB->oom || pB->isNull in decimalMul()
4181 acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 ); in decimalMul()
4183 pA->oom = 1; in decimalMul()
4186 memset(acc, 0, pA->nDigit + pB->nDigit + 2); in decimalMul()
4187 minFrac = pA->nFrac; in decimalMul()
4188 if( pB->nFrac<minFrac ) minFrac = pB->nFrac; in decimalMul()
4189 for(i=pA->nDigit-1; i>=0; i--){ in decimalMul()
4190 signed char f = pA->a[i]; in decimalMul()
4192 for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){ in decimalMul()
4193 x = acc[k] + f*pB->a[j] + carry; in decimalMul()
4199 acc[k-1] += x/10; in decimalMul()
4201 sqlite3_free(pA->a); in decimalMul()
4202 pA->a = acc; in decimalMul()
4204 pA->nDigit += pB->nDigit + 2; in decimalMul()
4205 pA->nFrac += pB->nFrac; in decimalMul()
4206 pA->sign ^= pB->sign; in decimalMul()
4207 while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){ in decimalMul()
4208 pA->nFrac--; in decimalMul()
4209 pA->nDigit--; in decimalMul()
4222 if( N<-20000 || N>20000 ) goto pow2_fault; in decimalPow2()
4224 if( pA==0 || pA->oom ) goto pow2_fault; in decimalPow2()
4229 N = -N; in decimalPow2()
4232 if( pX==0 || pX->oom ) goto pow2_fault; in decimalPow2()
4236 if( pA->oom ) goto pow2_fault; in decimalPow2()
4263 r = -r; in decimalFromDouble()
4273 m = a & ((((sqlite3_int64)1)<<52)-1); in decimalFromDouble()
4283 if( isNeg ) m = -m; in decimalFromDouble()
4284 e = e - 1075; in decimalFromDouble()
4306 ** point value is done. Or if X is an 8-byte blob, it is interpreted
4382 pB->sign = !pB->sign; in decimalSubFunc()
4405 if( !p->isInit ){ in decimalSumStep()
4406 p->isInit = 1; in decimalSumStep()
4407 p->a = sqlite3_malloc(2); in decimalSumStep()
4408 if( p->a==0 ){ in decimalSumStep()
4409 p->oom = 1; in decimalSumStep()
4411 p->a[0] = 0; in decimalSumStep()
4413 p->nDigit = 1; in decimalSumStep()
4414 p->nFrac = 0; in decimalSumStep()
4433 if( pArg ) pArg->sign = !pArg->sign; in decimalSumInverse()
4462 if( pA==0 || pA->oom || pA->isNull in decimalMulFunc()
4463 || pB==0 || pB->oom || pB->isNull in decimalMulFunc()
4468 if( pA->oom ){ in decimalMulFunc()
4481 ** Return the N-th power of 2. N must be an integer.
4547 ** 2022-11-18
4561 ** written as TCL brace-enclosed literals or SQL string literals,
4562 ** and can be used unmodified in XML-like documents.
4569 ** C source specifies that line-feeds are included in the encoded
4571 ** terminate any encoded blob having non-zero length.
4576 ** Generated base64 sequences, with their line-feeds included,
4585 ** This code relies on UTF-8 encoding only with respect to the
4586 ** meaning of the first 128 (7-bit) codes matching that of USASCII.
4588 ** Because it is table-driven, it could be enhanced to handle that,
4593 ** *Nix: gcc -O2 -shared -I$SQDIR -fPIC -o base64.so base64.c
4594 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o base64.dylib base64.c
4595 ** Win32: gcc -O2 -shared -I%SQDIR% -o base64.dll base64.c
4596 ** Win32: cl /Os -I%SQDIR% base64.c -link -dll -out:base64.dll
4616 #define ND 0x82 /* Not above or digit-value */
4624 /* Decoding table, ASCII (7-bit) value to base 64 digit value or other */
4662 /* Do the bit-shuffle, exploiting unsigned input to avoid masking. */ in toBase64()
4668 nbIn -= 3; in toBase64()
4683 for( nbe=3; nbe>=0; --nbe ){ in toBase64()
4698 while( nc-- > 0 && (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s; in skipNonB64()
4704 if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn; in fromBase64()
4710 ncIn -= (pUse - pIn); in fromBase64()
4713 ncIn -= nti; in fromBase64()
4721 /* Treat dark non-digits as pad, but they terminate decode too. */ in fromBase64()
4730 --nbo; in fromBase64()
4754 SQLITE_LIMIT_LENGTH, -1); in base64()
4762 nc += (nc+(B64_DARK_MAX-1))/B64_DARK_MAX + 1; /* LFs and a 0-terminator */ in base64()
4764 sqlite3_result_error(context, "blob expanded to base64 too big", -1); in base64()
4772 sqlite3_result_text(context,"",-1,SQLITE_STATIC); in base64()
4777 nc = (int)(toBase64(bBuf, nb, cBuf) - cBuf); in base64()
4784 sqlite3_result_error(context, "blob from base64 may be too big", -1); in base64()
4799 nb = (int)(fromBase64(cBuf, nc, bBuf) - bBuf); in base64()
4803 sqlite3_result_error(context, "base64 accepts only blob or text", -1); in base64()
4808 sqlite3_result_error(context, "base64 OOM", -1); in base64()
4845 ** 2022-11-16
4856 ** This is a utility for converting binary to base85 or vice-versa.
4861 ** written as TCL brace-enclosed literals or SQL string literals.
4862 ** It is not suited for unmodified use in XML-like documents.
4870 ** Base85 numerals are taken from the set of 7-bit USASCII codes,
4874 ** Groups of 4 bytes, interpreted as big-endian 32-bit values,
4875 ** are represented as 5-digit base85 numbers with MS to LS digit
4876 ** order. Groups of 1-3 bytes are represented with 2-4 digits,
4877 ** still big-endian but 8-24 bit values. (Using big-endian yields
4879 ** These byte groups can also be considered base-256 numbers.)
4880 ** Groups of 0 bytes are represented with 0 digits and vice-versa.
4882 ** (aka "group") length maps 1-to-1 to the decoded binary length.
4886 ** size, newline is used to separate it into sub-sequences of no
4893 ** a non-base85 character; the conversion to binary will then
4909 ** and variable OPTS to -DOMIT_BASE85_CHECKER if is_base85() unwanted.
4910 ** *Nix: gcc -O2 -shared -I$SQDIR $OPTS -fPIC -o base85.so base85.c
4911 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR $OPTS -o base85.dylib base85.c
4912 ** Win32: gcc -O2 -shared -I%SQDIR% %OPTS% -o base85.dll base85.c
4913 ** Win32: cl /Os -I%SQDIR% %OPTS% base85.c -link -dll -out:base85.dll
4916 ** *Nix or OSX: gcc -O2 -DBASE85_STANDALONE base85.c -o base85
4917 ** Win32: gcc -O2 -DBASE85_STANDALONE -o base85.exe base85.c
4918 ** Win32: cl /Os /MD -DBASE85_STANDALONE base85.c
4938 # include <io.h>
4946 " <dirFlag> is either -r to read or -w to write <binFile>,\n"
4949 " Or, the name '-' refers to the stdin or stdout stream.\n"
4968 static u8 b85_cOffset[] = { 0, '#', 0, '*'-4, 0 };
4976 u8 dv = (u8)(c - '#');
4978 return (dv > 3)? dv-3 : dv;
4988 while( nc-- > 0 && (c = *s) && !IS_B85(c) ) ++s; in skipNonB85()
4993 * Do not use the macro form with argument expression having a side-effect.*/
4996 return (b < 4)? (char)(b + '#') : (char)(b - 4 + '*');
5000 ((char)(((dn) < 4)? (char)((dn) + '#') : (char)((dn) - 4 + '*')))
5021 unsigned char dv = qbv - 85UL*nqv; in toBase85()
5023 pOut[--nco] = base85Numeral(dv); in toBase85()
5025 nbIn -= 4; in toBase85()
5044 pOut[--nco] = base85Numeral(dv); in toBase85()
5055 if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn; in fromBase85()
5061 ncIn -= (pUse - pIn); in fromBase85()
5069 --ncIn; in fromBase85()
5071 qv = 85 * qv + (c - cdo); in fromBase85()
5072 --nti; in fromBase85()
5074 nbo -= nti; /* Adjust for early (non-digit) end of group. */ in fromBase85()
5095 while( len-- > 0 && (c = *p++) != 0 ){ in allBase85()
5120 sqlite3_result_error(context, "is_base85 accepts only text or NULL", -1); in is_base85()
5130 SQLITE_LIMIT_LENGTH, -1); in base85()
5140 sqlite3_result_error(context, "blob expanded to base85 too big", -1); in base85()
5148 sqlite3_result_text(context,"",-1,SQLITE_STATIC); in base85()
5153 nc = (int)(toBase85(bBuf, nb, cBuf, "\n") - cBuf); in base85()
5160 sqlite3_result_error(context, "blob from base85 may be too big", -1); in base85()
5175 nb = (int)(fromBase85(cBuf, nc, bBuf) - bBuf); in base85()
5179 sqlite3_result_error(context, "base85 accepts only blob or text.", -1); in base85()
5184 sqlite3_result_error(context, "base85 OOM", -1); in base85()
5238 if( na < 3 || av[1][0]!='-' || (rw = av[1][1])==0 || (rw!='r' && rw!='w') ){ in main()
5243 if( av[2][0]=='-' && av[2][1]==0 ){ in main()
5272 size_t nbo = fromBase85( cBuf, nc, bBuf ) - bBuf; in main()
5287 fprintf(stderr, "Base85 input had non-base85 dark or control content.\n"); in main()
5298 ** 2013-04-17
5310 ** and input of IEEE754 Binary64 floating-point numbers.
5315 ** In the first form, the value X should be a floating-point number.
5320 ** base-2 exponent of a new floating point number. The function returns
5321 ** a floating-point value equal to Y*pow(2,Z).
5325 ** ieee754(2.0) -> 'ieee754(2,0)'
5326 ** ieee754(45.25) -> 'ieee754(181,-2)'
5327 ** ieee754(2, 0) -> 2.0
5328 ** ieee754(181, -2) -> 45.25
5330 ** Two additional functions break apart the one-argument ieee754()
5333 ** ieee754_mantissa(45.25) -> 181
5334 ** ieee754_exponent(45.25) -> -2
5338 ** ieee754_from_blob(x'3ff0000000000000') -> 1.0
5339 ** ieee754_to_blob(1.0) -> x'3ff0000000000000'
5341 ** In all single-argument functions, if the argument is an 8-byte blob
5342 ** then that blob is interpreted as a big-endian binary64 value.
5346 ** -----------------------------------------------
5359 ** VALUES(-1,'0.5')
5361 ** SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
5368 ** ---------------^^^^^---- Replace with whatever you want
5425 r = -r; in ieee754func()
5435 m = a & ((((sqlite3_int64)1)<<52)-1); in ieee754func()
5445 if( isNeg ) m = -m; in ieee754func()
5450 m, e-1075); in ieee754func()
5451 sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT); in ieee754func()
5457 sqlite3_result_int(context, e-1075); in ieee754func()
5467 /* Limit the range of e. Ticket 22dea1cfdb9151e4 2021-03-02 */ in ieee754func()
5470 }else if( e<-10000 ){ in ieee754func()
5471 e = -10000; in ieee754func()
5476 m = -m; in ieee754func()
5478 }else if( m==0 && e>-1000 && e<1000 ){ in ieee754func()
5488 e--; in ieee754func()
5493 if( 1-e >= 64 ){ in ieee754func()
5496 m >>= 1-e; in ieee754func()
5502 a = m & ((((sqlite3_int64)1)<<52)-1); in ieee754func()
5548 a[sizeof(r)-i] = v&0xff; in ieee754func_to_blob()
5561 ** Behind the scenes: this routine merely casts r into a 64-bit unsigned
5625 ** 2015-08-18, 2023-04-28
5636 ** This file demonstrates how to create a table-valued-function using
5639 ** within the limitation that its arguments are signed 64-bit integers.
5643 ** ( V[n] == start + n * step && sgn(V[n] - stop) * sgn(step) >= 0 )
5648 ** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
5666 ** SELECT * FROM generate_series(0,-100,-5);
5668 ** Integers 0 -5 -10 ... -100.
5670 ** SELECT * FROM generate_series(0,-1);
5715 ** series are well-defined.
5725 ** Return that member of a generate_series(...) sequence whose 0-based
5738 ix -= mxI64; in genSeqMember()
5742 smBase += (mxI64 - mxI64/2) * smStep; in genSeqMember()
5749 ix -= ix2; in genSeqMember()
5774 pss->uSeqIndexMax = 0; in setupSequence()
5775 pss->isNotEOF = 0; in setupSequence()
5776 bSameSigns = (pss->iBase < 0)==(pss->iTerm < 0); in setupSequence()
5777 if( pss->iTerm < pss->iBase ){ in setupSequence()
5780 nuspan = (sqlite3_uint64)(pss->iBase - pss->iTerm); in setupSequence()
5785 nuspan += pss->iBase; in setupSequence()
5786 nuspan += -(pss->iTerm+1); in setupSequence()
5788 if( pss->iStep<0 ){ in setupSequence()
5789 pss->isNotEOF = 1; in setupSequence()
5791 pss->uSeqIndexMax = ( pss->iStep>LLONG_MIN )? nuspan/-pss->iStep : 1; in setupSequence()
5792 }else if( pss->iStep>LLONG_MIN ){ in setupSequence()
5793 pss->uSeqIndexMax = nuspan/-pss->iStep; in setupSequence()
5796 }else if( pss->iTerm > pss->iBase ){ in setupSequence()
5799 puspan = (sqlite3_uint64)(pss->iTerm - pss->iBase); in setupSequence()
5804 puspan += pss->iTerm; in setupSequence()
5805 puspan += -(pss->iBase+1); in setupSequence()
5807 if( pss->iStep>0 ){ in setupSequence()
5808 pss->isNotEOF = 1; in setupSequence()
5809 pss->uSeqIndexMax = puspan/pss->iStep; in setupSequence()
5811 }else if( pss->iTerm == pss->iBase ){ in setupSequence()
5812 pss->isNotEOF = 1; in setupSequence()
5813 pss->uSeqIndexMax = 0; in setupSequence()
5815 pss->uSeqIndexNow = (pss->isReversing)? pss->uSeqIndexMax : 0; in setupSequence()
5816 pss->iValueNow = (pss->isReversing) in setupSequence()
5817 ? genSeqMember(pss->iBase, pss->iStep, pss->uSeqIndexMax) in setupSequence()
5818 : pss->iBase; in setupSequence()
5827 if( !pss->isNotEOF ) return 0; in progressSequence()
5828 if( pss->isReversing ){ in progressSequence()
5829 if( pss->uSeqIndexNow > 0 ){ in progressSequence()
5830 pss->uSeqIndexNow--; in progressSequence()
5831 pss->iValueNow -= pss->iStep; in progressSequence()
5833 pss->isNotEOF = 0; in progressSequence()
5836 if( pss->uSeqIndexNow < pss->uSeqIndexMax ){ in progressSequence()
5837 pss->uSeqIndexNow++; in progressSequence()
5838 pss->iValueNow += pss->iStep; in progressSequence()
5840 pss->isNotEOF = 0; in progressSequence()
5843 return pss->isNotEOF; in progressSequence()
5852 sqlite3_vtab_cursor base; /* Base class - must be first */
5917 *ppCursor = &pCur->base; in seriesOpen()
5935 progressSequence( & pCur->ss ); in seriesNext()
5951 case SERIES_COLUMN_START: x = pCur->ss.iBase; break; in seriesColumn()
5952 case SERIES_COLUMN_STOP: x = pCur->ss.iTerm; break; in seriesColumn()
5953 case SERIES_COLUMN_STEP: x = pCur->ss.iStep; break; in seriesColumn()
5954 default: x = pCur->ss.iValueNow; break; in seriesColumn()
5970 sqlite3_uint64 n = pCur->ss.uSeqIndexNow; in seriesRowid()
5981 return !pCur->ss.isNotEOF; in seriesEof()
5984 /* True to cause run-time checking of the start=, stop=, and/or step=
6023 pCur->ss.iBase = sqlite3_value_int64(argv[i++]); in seriesFilter()
6025 pCur->ss.iBase = 0; in seriesFilter()
6028 pCur->ss.iTerm = sqlite3_value_int64(argv[i++]); in seriesFilter()
6030 pCur->ss.iTerm = 0xffffffff; in seriesFilter()
6033 pCur->ss.iStep = sqlite3_value_int64(argv[i++]); in seriesFilter()
6034 if( pCur->ss.iStep==0 ){ in seriesFilter()
6035 pCur->ss.iStep = 1; in seriesFilter()
6036 }else if( pCur->ss.iStep<0 ){ in seriesFilter()
6040 pCur->ss.iStep = 1; in seriesFilter()
6048 pCur->ss.iBase += pCur->ss.iStep*iOffset; in seriesFilter()
6052 iTerm = pCur->ss.iBase + (iLimit - 1)*pCur->ss.iStep; in seriesFilter()
6053 if( pCur->ss.iStep<0 ){ in seriesFilter()
6054 if( iTerm>pCur->ss.iTerm ) pCur->ss.iTerm = iTerm; in seriesFilter()
6056 if( iTerm<pCur->ss.iTerm ) pCur->ss.iTerm = iTerm; in seriesFilter()
6064 pCur->ss.iBase = 1; in seriesFilter()
6065 pCur->ss.iTerm = 0; in seriesFilter()
6066 pCur->ss.iStep = 1; in seriesFilter()
6071 pCur->ss.isReversing = pCur->ss.iStep > 0; in seriesFilter()
6073 pCur->ss.isReversing = pCur->ss.iStep < 0; in seriesFilter()
6075 setupSequence( &pCur->ss ); in seriesFilter()
6090 ** 0x01 start = $value -- constraint exists
6091 ** 0x02 stop = $value -- constraint exists
6092 ** 0x04 step = $value -- constraint exists
6095 ** 0x20 LIMIT $value -- constraint exists
6096 ** 0x40 OFFSET $value -- constraint exists
6117 aIdx[0] = aIdx[1] = aIdx[2] = aIdx[3] = aIdx[4] = -1; in seriesBestIndex()
6118 pConstraint = pIdxInfo->aConstraint; in seriesBestIndex()
6119 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ in seriesBestIndex()
6122 int op = pConstraint->op; in seriesBestIndex()
6126 if( pConstraint->usable==0 ){ in seriesBestIndex()
6138 if( pConstraint->iColumn<SERIES_COLUMN_START ) continue; in seriesBestIndex()
6139 iCol = pConstraint->iColumn - SERIES_COLUMN_START; in seriesBestIndex()
6147 if( pConstraint->usable==0 ){ in seriesBestIndex()
6162 pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg; in seriesBestIndex()
6163 pIdxInfo->aConstraintUsage[j].omit = in seriesBestIndex()
6169 ** first argument was omitted. Compile with -DZERO_ARGUMENT_GENERATE_SERIES in seriesBestIndex()
6173 sqlite3_free(pVTab->zErrMsg); in seriesBestIndex()
6174 pVTab->zErrMsg = sqlite3_mprintf( in seriesBestIndex()
6188 pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0)); in seriesBestIndex()
6189 pIdxInfo->estimatedRows = 1000; in seriesBestIndex()
6190 if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){ in seriesBestIndex()
6191 if( pIdxInfo->aOrderBy[0].desc ){ in seriesBestIndex()
6196 pIdxInfo->orderByConsumed = 1; in seriesBestIndex()
6200 pIdxInfo->estimatedRows = 2500; in seriesBestIndex()
6205 pIdxInfo->estimatedRows = 2147483647; in seriesBestIndex()
6207 pIdxInfo->idxNum = idxNum; in seriesBestIndex()
6222 seriesOpen, /* xOpen - open a cursor */
6223 seriesClose, /* xClose - close a cursor */
6224 seriesFilter, /* xFilter - configure scan constraints */
6225 seriesNext, /* xNext - advance a cursor */
6226 seriesEof, /* xEof - check for end of scan */
6227 seriesColumn, /* xColumn - read data */
6228 seriesRowid, /* xRowid - read data */
6269 ** 2012-11-13
6281 ** efficient regular-expression matcher for posix extended regular
6303 ** \c C-language escapes for c in afnrtv. ex: \t or \n
6308 ** [a-z] Any single character in the range a-z
6309 ** [^a-z] Any single character not in the range a-z
6311 ** \w Word character. [A-Za-z0-9_]
6312 ** \W Non-word character
6314 ** \D Non-digit
6316 ** \S Non-whitespace character
6322 ** to p copies of X following by q-p copies of X? and that the size of the
6333 ** this file to prevent name collisions with C-library functions of the
6340 /* The end-of-input character */
6342 #define RE_START 0xfffffff /* Start of input - larger than an UTF-8 */
6357 #define RE_OP_WORD 11 /* Perl word character [A-Za-z0-9_] */
6359 #define RE_OP_DIGIT 13 /* digit: [0-9] */
6363 #define RE_OP_BOUNDARY 17 /* Boundary between word and non-word */
6433 for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return; in re_add_state()
6434 pSet->aState[pSet->nState++] = (ReStateNumber)newState; in re_add_state()
6444 if( p->i>=p->mx ) return 0; in re_next_char()
6445 c = p->z[p->i++]; in re_next_char()
6447 if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){ in re_next_char()
6448 c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f); in re_next_char()
6450 }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80 in re_next_char()
6451 && (p->z[p->i+1]&0xc0)==0x80 ){ in re_next_char()
6452 c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f); in re_next_char()
6453 p->i += 2; in re_next_char()
6455 }else if( (c&0xf8)==0xf0 && p->i+2<p->mx && (p->z[p->i]&0xc0)==0x80 in re_next_char()
6456 && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){ in re_next_char()
6457 c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6) in re_next_char()
6458 | (p->z[p->i+2]&0x3f); in re_next_char()
6459 p->i += 3; in re_next_char()
6469 if( c>='A' && c<='Z' ) c += 'a' - 'A'; in re_next_char_nocase()
6473 /* Return true if c is a perl "word" character: [A-Za-z0-9_] */
6479 /* Return true if c is a "digit" character: [0-9] */
6489 /* Run a compiled regular expression on the zero-terminated input
6508 if( pRe->nInit ){ in re_match()
6509 unsigned char x = pRe->zInit[0]; in re_match()
6510 while( in.i+pRe->nInit<=in.mx in re_match()
6512 strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0) in re_match()
6516 if( in.i+pRe->nInit>in.mx ) return 0; in re_match()
6517 c = RE_START-1; in re_match()
6520 if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){ in re_match()
6524 pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState ); in re_match()
6525 if( pToFree==0 ) return -1; in re_match()
6528 aStateSet[1].aState = &aStateSet[0].aState[pRe->nState]; in re_match()
6530 pNext->nState = 0; in re_match()
6532 while( c!=RE_EOF && pNext->nState>0 ){ in re_match()
6534 c = pRe->xNextChar(&in); in re_match()
6537 iSwap = 1 - iSwap; in re_match()
6538 pNext->nState = 0; in re_match()
6539 for(i=0; i<pThis->nState; i++){ in re_match()
6540 int x = pThis->aState[i]; in re_match()
6541 switch( pRe->aOp[x] ){ in re_match()
6543 if( pRe->aArg[x]==c ) re_add_state(pNext, x+1); in re_match()
6588 re_add_state(pThis, x+pRe->aArg[x]); in re_match()
6593 re_add_state(pThis, x+pRe->aArg[x]); in re_match()
6602 /* fall-through */ goto re_op_cc_inc; in re_match()
6606 int n = pRe->aArg[x]; in re_match()
6609 if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){ in re_match()
6610 if( pRe->aArg[x+j]==c ){ in re_match()
6612 j = -1; in re_match()
6615 if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){ in re_match()
6617 j = -1; in re_match()
6623 if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit; in re_match()
6630 for(i=0; i<pNext->nState; i++){ in re_match()
6631 int x = pNext->aState[i]; in re_match()
6632 while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x]; in re_match()
6633 if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; } in re_match()
6645 aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0])); in re_resize()
6647 p->aOp = aOp; in re_resize()
6648 aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0])); in re_resize()
6650 p->aArg = aArg; in re_resize()
6651 p->nAlloc = N; in re_resize()
6660 if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0; in re_insert()
6661 for(i=p->nState; i>iBefore; i--){ in re_insert()
6662 p->aOp[i] = p->aOp[i-1]; in re_insert()
6663 p->aArg[i] = p->aArg[i-1]; in re_insert()
6665 p->nState++; in re_insert()
6666 p->aOp[iBefore] = (char)op; in re_insert()
6667 p->aArg[iBefore] = arg; in re_insert()
6674 return re_insert(p, p->nState, op, arg); in re_append()
6681 if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return; in re_copy()
6682 memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0])); in re_copy()
6683 memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0])); in re_copy()
6684 p->nState += N; in re_copy()
6687 /* Return true if c is a hexadecimal digit character: [0-9a-fA-F]
6693 c -= '0'; in re_hex()
6695 c -= 'a' - 10; in re_hex()
6697 c -= 'A' - 10; in re_hex()
6713 if( p->sIn.i>=p->sIn.mx ) return 0; in re_esc_char()
6714 c = p->sIn.z[p->sIn.i]; in re_esc_char()
6715 if( c=='u' && p->sIn.i+4<p->sIn.mx ){ in re_esc_char()
6716 const unsigned char *zIn = p->sIn.z + p->sIn.i; in re_esc_char()
6722 p->sIn.i += 5; in re_esc_char()
6726 if( c=='x' && p->sIn.i+2<p->sIn.mx ){ in re_esc_char()
6727 const unsigned char *zIn = p->sIn.z + p->sIn.i; in re_esc_char()
6731 p->sIn.i += 3; in re_esc_char()
6738 p->sIn.i++; in re_esc_char()
6740 p->zErr = "unknown \\ escape"; in re_esc_char()
6750 return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0; in rePeek()
6760 iStart = p->nState; in re_subcompile_re()
6764 iEnd = p->nState; in re_subcompile_re()
6765 re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart); in re_subcompile_re()
6767 p->sIn.i++; in re_subcompile_re()
6770 p->aArg[iGoto] = p->nState - iGoto; in re_subcompile_re()
6780 int iPrev = -1; in re_subcompile_string()
6784 while( (c = p->xNextChar(&p->sIn))!=0 ){ in re_subcompile_string()
6785 iStart = p->nState; in re_subcompile_string()
6789 p->sIn.i--; in re_subcompile_string()
6796 p->sIn.i++; in re_subcompile_string()
6802 p->sIn.i++; in re_subcompile_string()
6810 re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1); in re_subcompile_string()
6811 re_append(p, RE_OP_FORK, iPrev - p->nState + 1); in re_subcompile_string()
6816 re_append(p, RE_OP_FORK, iPrev - p->nState); in re_subcompile_string()
6821 re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1); in re_subcompile_string()
6836 while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; } in re_subcompile_string()
6839 p->sIn.i++; in re_subcompile_string()
6841 while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; } in re_subcompile_string()
6845 p->sIn.i++; in re_subcompile_string()
6846 sz = p->nState - iPrev; in re_subcompile_string()
6851 n--; in re_subcompile_string()
6860 re_append(p, RE_OP_FORK, -sz); in re_subcompile_string()
6865 unsigned int iFirst = p->nState; in re_subcompile_string()
6868 p->sIn.i++; in re_subcompile_string()
6872 while( (c = p->xNextChar(&p->sIn))!=0 ){ in re_subcompile_string()
6877 if( rePeek(p)=='-' ){ in re_subcompile_string()
6879 p->sIn.i++; in re_subcompile_string()
6880 c = p->xNextChar(&p->sIn); in re_subcompile_string()
6886 if( rePeek(p)==']' ){ p->sIn.i++; break; } in re_subcompile_string()
6889 if( p->nState>iFirst ) p->aArg[iFirst] = p->nState - iFirst; in re_subcompile_string()
6904 p->sIn.i++; in re_subcompile_string()
6928 sqlite3_free(pRe->aOp); in re_free()
6929 sqlite3_free(pRe->aArg); in re_free()
6951 pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char; in re_compile()
6961 pRe->sIn.z = (unsigned char*)zIn; in re_compile()
6962 pRe->sIn.i = 0; in re_compile()
6963 pRe->sIn.mx = (int)strlen(zIn); in re_compile()
6969 if( pRe->sIn.i>=pRe->sIn.mx ){ in re_compile()
6983 ** unicode characters beyond plane 0 - those are very rare and this is in re_compile()
6985 if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){ in re_compile()
6986 for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){ in re_compile()
6987 unsigned x = pRe->aArg[i]; in re_compile()
6989 pRe->zInit[j++] = (unsigned char)x; in re_compile()
6991 pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6)); in re_compile()
6992 pRe->zInit[j++] = 0x80 | (x&0x3f); in re_compile()
6994 pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12)); in re_compile()
6995 pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f); in re_compile()
6996 pRe->zInit[j++] = 0x80 | (x&0x3f); in re_compile()
7001 if( j>0 && pRe->zInit[j-1]==0 ) j--; in re_compile()
7002 pRe->nInit = j; in re_compile()
7004 return pRe->zErr; in re_compile()
7009 ** the build-in REGEXP operator. The first argument to the function is the
7035 sqlite3_result_error(context, zErr, -1); in re_sql_func()
7046 sqlite3_result_int(context, re_match(pRe, zStr, -1)); in re_sql_func()
7056 ** if the SQLITE_DEBUG compile-time option is used.
7080 sqlite3_result_error(context, zErr, -1); in re_bytecode_func()
7089 if( pRe->nInit>0 ){ in re_bytecode_func()
7091 for(i=0; i<pRe->nInit; i++){ in re_bytecode_func()
7092 sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]); in re_bytecode_func()
7096 for(i=0; (unsigned)i<pRe->nState; i++){ in re_bytecode_func()
7097 sqlite3_str_appendf(pStr, "%-8s %4d\n", in re_bytecode_func()
7098 ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]); in re_bytecode_func()
7105 sqlite3_result_text(context, z, n-1, sqlite3_free); in re_bytecode_func()
7134 /* The regexpi(PATTERN,STRING) function is a case-insensitive version in sqlite3_regexp_init()
7154 ** 2014-06-13
7174 ** If the first option argument - MODE - is present, then it must
7191 ** as an integer - the number of seconds since the unix epoch. The
7192 ** modification-time of the target file is set to this value before
7223 ** If a non-NULL value is specified for the optional $dir parameter and
7230 ** symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone
7249 # include <io.h>
7267 ** Structure of the fsdir() table-valued function
7306 mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1); in readFileContents()
7353 sqlite3_result_error(ctx, zMsg, -1); in ctxErrorMsg()
7361 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
7379 fileIntervals.LowPart = pFileTime->dwLowDateTime; in fileTimeToUnixTime()
7380 fileIntervals.HighPart = pFileTime->dwHighDateTime; in fileTimeToUnixTime()
7382 return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000; in fileTimeToUnixTime()
7392 int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0); in utf8_to_utf16()
7394 if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) ) in utf8_to_utf16()
7419 pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime); in statTimesToUtc()
7420 pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime); in statTimesToUtc()
7421 pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime); in statTimesToUtc()
7521 sqlite3_int64 mtime /* MTIME parameter (or -1 to not set time) */ in writeFile()
7536 ** be an error though - if there is already a directory at the same in writeFile()
7617 ** Do not use utimes() on a symbolic link - it sees through the link and in writeFile()
7647 sqlite3_int64 mtime = -1; in writefileFunc()
7651 "wrong number of arguments to function writefile()", -1 in writefileFunc()
7686 ** Given a numberic st_mode from stat(), convert it into a human-readable
7687 ** text string in the style of "ls -l".
7701 z[0] = '-'; in lsModeFunc()
7708 int m = (iMode >> ((2-i)*3)); in lsModeFunc()
7710 a[0] = (m & 0x4) ? 'r' : '-'; in lsModeFunc()
7711 a[1] = (m & 0x2) ? 'w' : '-'; in lsModeFunc()
7712 a[2] = (m & 0x1) ? 'x' : '-'; in lsModeFunc()
7715 sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT); in lsModeFunc()
7728 char *zDir; /* Name of directory (nul-terminated) */
7732 sqlite3_vtab_cursor base; /* Base class - must be first */
7748 sqlite3_vtab base; /* Base class - must be first */
7795 pCur->iLvl = -1; in fsdirOpen()
7796 *ppCursor = &pCur->base; in fsdirOpen()
7806 for(i=0; i<=pCur->iLvl; i++){ in fsdirResetCursor()
7807 FsdirLevel *pLvl = &pCur->aLvl[i]; in fsdirResetCursor()
7808 if( pLvl->pDir ) closedir(pLvl->pDir); in fsdirResetCursor()
7809 sqlite3_free(pLvl->zDir); in fsdirResetCursor()
7811 sqlite3_free(pCur->zPath); in fsdirResetCursor()
7812 sqlite3_free(pCur->aLvl); in fsdirResetCursor()
7813 pCur->aLvl = 0; in fsdirResetCursor()
7814 pCur->zPath = 0; in fsdirResetCursor()
7815 pCur->zBase = 0; in fsdirResetCursor()
7816 pCur->nBase = 0; in fsdirResetCursor()
7817 pCur->nLvl = 0; in fsdirResetCursor()
7818 pCur->iLvl = -1; in fsdirResetCursor()
7819 pCur->iRowid = 1; in fsdirResetCursor()
7840 pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); in fsdirSetErrmsg()
7850 mode_t m = pCur->sStat.st_mode; in fsdirNext()
7852 pCur->iRowid++; in fsdirNext()
7855 int iNew = pCur->iLvl + 1; in fsdirNext()
7857 if( iNew>=pCur->nLvl ){ in fsdirNext()
7860 FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte); in fsdirNext()
7862 memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl)); in fsdirNext()
7863 pCur->aLvl = aNew; in fsdirNext()
7864 pCur->nLvl = nNew; in fsdirNext()
7866 pCur->iLvl = iNew; in fsdirNext()
7867 pLvl = &pCur->aLvl[iNew]; in fsdirNext()
7869 pLvl->zDir = pCur->zPath; in fsdirNext()
7870 pCur->zPath = 0; in fsdirNext()
7871 pLvl->pDir = opendir(pLvl->zDir); in fsdirNext()
7872 if( pLvl->pDir==0 ){ in fsdirNext()
7873 fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath); in fsdirNext()
7878 while( pCur->iLvl>=0 ){ in fsdirNext()
7879 FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl]; in fsdirNext()
7880 struct dirent *pEntry = readdir(pLvl->pDir); in fsdirNext()
7882 if( pEntry->d_name[0]=='.' ){ in fsdirNext()
7883 if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue; in fsdirNext()
7884 if( pEntry->d_name[1]=='\0' ) continue; in fsdirNext()
7886 sqlite3_free(pCur->zPath); in fsdirNext()
7887 pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name); in fsdirNext()
7888 if( pCur->zPath==0 ) return SQLITE_NOMEM; in fsdirNext()
7889 if( fileLinkStat(pCur->zPath, &pCur->sStat) ){ in fsdirNext()
7890 fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath); in fsdirNext()
7895 closedir(pLvl->pDir); in fsdirNext()
7896 sqlite3_free(pLvl->zDir); in fsdirNext()
7897 pLvl->pDir = 0; in fsdirNext()
7898 pLvl->zDir = 0; in fsdirNext()
7899 pCur->iLvl--; in fsdirNext()
7903 sqlite3_free(pCur->zPath); in fsdirNext()
7904 pCur->zPath = 0; in fsdirNext()
7920 sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT); in fsdirColumn()
7925 sqlite3_result_int64(ctx, pCur->sStat.st_mode); in fsdirColumn()
7929 sqlite3_result_int64(ctx, pCur->sStat.st_mtime); in fsdirColumn()
7933 mode_t m = pCur->sStat.st_mode; in fsdirColumn()
7944 n = readlink(pCur->zPath, aBuf, nBuf); in fsdirColumn()
7959 readFileContents(ctx, pCur->zPath); in fsdirColumn()
7979 *pRowid = pCur->iRowid; in fsdirRowid()
7989 return (pCur->zPath==0); in fsdirEof()
8016 fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument"); in fsdirFilter()
8020 pCur->zBase = (const char*)sqlite3_value_text(argv[1]); in fsdirFilter()
8022 if( pCur->zBase ){ in fsdirFilter()
8023 pCur->nBase = (int)strlen(pCur->zBase)+1; in fsdirFilter()
8024 pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir); in fsdirFilter()
8026 pCur->zPath = sqlite3_mprintf("%s", zDir); in fsdirFilter()
8029 if( pCur->zPath==0 ){ in fsdirFilter()
8032 if( fileLinkStat(pCur->zPath, &pCur->sStat) ){ in fsdirFilter()
8033 fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath); in fsdirFilter()
8059 int idxPath = -1; /* Index in pIdxInfo->aConstraint of PATH= */ in fsdirBestIndex()
8060 int idxDir = -1; /* Index in pIdxInfo->aConstraint of DIR= */ in fsdirBestIndex()
8066 pConstraint = pIdxInfo->aConstraint; in fsdirBestIndex()
8067 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ in fsdirBestIndex()
8068 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; in fsdirBestIndex()
8069 switch( pConstraint->iColumn ){ in fsdirBestIndex()
8071 if( pConstraint->usable ){ in fsdirBestIndex()
8080 if( pConstraint->usable ){ in fsdirBestIndex()
8096 pIdxInfo->idxNum = 0; in fsdirBestIndex()
8097 /* The pIdxInfo->estimatedCost should have been initialized to a huge in fsdirBestIndex()
8099 pIdxInfo->estimatedRows = 0x7fffffff; in fsdirBestIndex()
8101 pIdxInfo->aConstraintUsage[idxPath].omit = 1; in fsdirBestIndex()
8102 pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1; in fsdirBestIndex()
8104 pIdxInfo->aConstraintUsage[idxDir].omit = 1; in fsdirBestIndex()
8105 pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2; in fsdirBestIndex()
8106 pIdxInfo->idxNum = 2; in fsdirBestIndex()
8107 pIdxInfo->estimatedCost = 10.0; in fsdirBestIndex()
8109 pIdxInfo->idxNum = 1; in fsdirBestIndex()
8110 pIdxInfo->estimatedCost = 100.0; in fsdirBestIndex()
8128 fsdirOpen, /* xOpen - open a cursor */ in fsdirRegister()
8129 fsdirClose, /* xClose - close a cursor */ in fsdirRegister()
8130 fsdirFilter, /* xFilter - configure scan constraints */ in fsdirRegister()
8131 fsdirNext, /* xNext - advance a cursor */ in fsdirRegister()
8132 fsdirEof, /* xEof - check for end of scan */ in fsdirRegister()
8133 fsdirColumn, /* xColumn - read data */ in fsdirRegister()
8134 fsdirRowid, /* xRowid - read data */ in fsdirRegister()
8171 rc = sqlite3_create_function(db, "writefile", -1, in sqlite3_fileio_init()
8196 ** 2017-07-10
8243 sqlite3_vtab base; /* Base class - must be first */
8253 sqlite3_vtab_cursor base; /* Base class - must be first */
8263 int j; /* inter-phase counter */
8313 #define COMPLETION_COLUMN_PHASE 3 /* ePhase - used for debugging only */ in completionConnect()
8328 pNew->db = db; in completionConnect()
8349 pCur->db = ((completion_vtab*)p)->db; in completionOpen()
8350 *ppCursor = &pCur->base; in completionOpen()
8358 sqlite3_free(pCur->zPrefix); pCur->zPrefix = 0; pCur->nPrefix = 0; in completionCursorReset()
8359 sqlite3_free(pCur->zLine); pCur->zLine = 0; pCur->nLine = 0; in completionCursorReset()
8360 sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0; in completionCursorReset()
8361 pCur->j = 0; in completionCursorReset()
8376 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
8377 ** record the current state of the scan. This routine sets ->zCurrentRow
8379 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
8390 int iCol = -1; /* If >=0, step pCur->pStmt and use the i-th column */ in completionNext()
8391 pCur->iRowid++; in completionNext()
8392 while( pCur->ePhase!=COMPLETION_EOF ){ in completionNext()
8393 switch( pCur->ePhase ){ in completionNext()
8395 if( pCur->j >= sqlite3_keyword_count() ){ in completionNext()
8396 pCur->zCurrentRow = 0; in completionNext()
8397 pCur->ePhase = COMPLETION_DATABASES; in completionNext()
8399 sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow); in completionNext()
8401 iCol = -1; in completionNext()
8405 if( pCur->pStmt==0 ){ in completionNext()
8406 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, in completionNext()
8407 &pCur->pStmt, 0); in completionNext()
8414 if( pCur->pStmt==0 ){ in completionNext()
8418 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0); in completionNext()
8430 sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0); in completionNext()
8438 if( pCur->pStmt==0 ){ in completionNext()
8442 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0); in completionNext()
8456 sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0); in completionNext()
8466 if( pCur->zCurrentRow==0 ) continue; in completionNext()
8468 if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){ in completionNext()
8470 pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol); in completionNext()
8471 pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol); in completionNext()
8474 sqlite3_finalize(pCur->pStmt); in completionNext()
8475 pCur->pStmt = 0; in completionNext()
8476 pCur->ePhase = eNextPhase; in completionNext()
8480 if( pCur->nPrefix==0 ) break; in completionNext()
8481 if( pCur->nPrefix<=pCur->szRow in completionNext()
8482 && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0 in completionNext()
8503 sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT); in completionColumn()
8507 sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT); in completionColumn()
8511 sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT); in completionColumn()
8515 sqlite3_result_int(ctx, pCur->ePhase); in completionColumn()
8528 *pRowid = pCur->iRowid; in completionRowid()
8538 return pCur->ePhase >= COMPLETION_EOF; in completionEof()
8558 pCur->nPrefix = sqlite3_value_bytes(argv[iArg]); in completionFilter()
8559 if( pCur->nPrefix>0 ){ in completionFilter()
8560 pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg])); in completionFilter()
8561 if( pCur->zPrefix==0 ) return SQLITE_NOMEM; in completionFilter()
8566 pCur->nLine = sqlite3_value_bytes(argv[iArg]); in completionFilter()
8567 if( pCur->nLine>0 ){ in completionFilter()
8568 pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg])); in completionFilter()
8569 if( pCur->zLine==0 ) return SQLITE_NOMEM; in completionFilter()
8572 if( pCur->zLine!=0 && pCur->zPrefix==0 ){ in completionFilter()
8573 int i = pCur->nLine; in completionFilter()
8574 while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){ in completionFilter()
8575 i--; in completionFilter()
8577 pCur->nPrefix = pCur->nLine - i; in completionFilter()
8578 if( pCur->nPrefix>0 ){ in completionFilter()
8579 pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i); in completionFilter()
8580 if( pCur->zPrefix==0 ) return SQLITE_NOMEM; in completionFilter()
8583 pCur->iRowid = 0; in completionFilter()
8584 pCur->ePhase = COMPLETION_FIRST_PHASE; in completionFilter()
8594 ** There are two hidden parameters that act as arguments to the table-valued
8604 int prefixIdx = -1; /* Index of the start= constraint, or -1 if none */ in completionBestIndex()
8605 int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */ in completionBestIndex()
8610 pConstraint = pIdxInfo->aConstraint; in completionBestIndex()
8611 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ in completionBestIndex()
8612 if( pConstraint->usable==0 ) continue; in completionBestIndex()
8613 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; in completionBestIndex()
8614 switch( pConstraint->iColumn ){ in completionBestIndex()
8626 pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg; in completionBestIndex()
8627 pIdxInfo->aConstraintUsage[prefixIdx].omit = 1; in completionBestIndex()
8630 pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg; in completionBestIndex()
8631 pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1; in completionBestIndex()
8633 pIdxInfo->idxNum = idxNum; in completionBestIndex()
8634 pIdxInfo->estimatedCost = (double)5000 - 1000*nArg; in completionBestIndex()
8635 pIdxInfo->estimatedRows = 500 - 100*nArg; in completionBestIndex()
8650 completionOpen, /* xOpen - open a cursor */
8651 completionClose, /* xClose - close a cursor */
8652 completionFilter, /* xFilter - configure scan constraints */
8653 completionNext, /* xNext - advance a cursor */
8654 completionEof, /* xEof - check for end of scan */
8655 completionColumn, /* xColumn - read data */
8656 completionRowid, /* xRowid - read data */
8701 ** 2017-10-20
8729 ** "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
8746 ** this shim is a pass-through into the default underlying VFS. (rule 3)
8755 ** Start-Of-SQLite3-NNNNNNNN
8758 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
8761 #define APND_MARK_PREFIX "Start-Of-SQLite3-"
8767 ** Maximum size of the combined prefix + database + append-mark. This
8778 #define APND_ALIGN_MASK ((sqlite3_int64)(APND_ROUNDUP-1))
8787 /* Access to a lower-level VFS that (might) implement dynamic loading,
8790 #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
8799 ** append-mark.
8803 ** +-------------+---------+----------+-------------+
8804 ** | prefix-file | padding | database | append-mark |
8805 ** +-------------+---------+----------+-------------+
8811 ** "prefix file" - file onto which the database has been appended.
8812 ** "padding" - zero or more bytes inserted so that "database"
8814 ** "database" - The SQLite database file
8815 ** "append-mark" - The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
8816 ** the offset from the start of prefix-file to the start
8819 ** The size of the database is iMark - iPgOne.
8821 ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
8822 ** of iPgOne stored as a big-ending 64-bit integer.
8825 ** Or, iMark is -1 to indicate that it has not yet been written.
8830 sqlite3_int64 iMark; /* Offset of the append mark. -1 if unwritten */
8924 ** Close an apnd-file.
8928 return pFile->pMethods->xClose(pFile); in apndClose()
8932 ** Read data from an apnd-file.
8942 return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst); in apndRead()
8946 ** Add the append-mark onto what should become the end of the file.
8948 * Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
8955 sqlite_int64 iPgOne = paf->iPgOne; in apndWriteMark()
8961 while( --i >= 0 ){ in apndWriteMark()
8965 iWriteEnd += paf->iPgOne; in apndWriteMark()
8966 if( SQLITE_OK==(rc = pFile->pMethods->xWrite in apndWriteMark()
8968 paf->iMark = iWriteEnd; in apndWriteMark()
8974 ** Write data to an apnd-file.
8986 /* If append-mark is absent or will be overwritten, write it. */ in apndWrite()
8987 if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){ in apndWrite()
8991 return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst); in apndWrite()
8995 ** Truncate an apnd-file.
9003 return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE); in apndTruncate()
9007 ** Sync an apnd-file.
9011 return pFile->pMethods->xSync(pFile, flags); in apndSync()
9015 ** Return the current file-size of an apnd-file.
9016 ** If the append mark is not yet there, the file-size is 0.
9020 *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0; in apndFileSize()
9025 ** Lock an apnd-file.
9029 return pFile->pMethods->xLock(pFile, eLock); in apndLock()
9033 ** Unlock an apnd-file.
9037 return pFile->pMethods->xUnlock(pFile, eLock); in apndUnlock()
9041 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
9045 return pFile->pMethods->xCheckReservedLock(pFile, pResOut); in apndCheckReservedLock()
9049 ** File control method. For custom operations on an apnd-file.
9055 if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne; in apndFileControl()
9056 rc = pFile->pMethods->xFileControl(pFile, op, pArg); in apndFileControl()
9058 *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg); in apndFileControl()
9064 ** Return the sector-size in bytes for an apnd-file.
9068 return pFile->pMethods->xSectorSize(pFile); in apndSectorSize()
9072 ** Return the device characteristic flags supported by an apnd-file.
9076 return pFile->pMethods->xDeviceCharacteristics(pFile); in apndDeviceCharacteristics()
9088 return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp); in apndShmMap()
9091 /* Perform locking on a shared-memory segment */
9094 return pFile->pMethods->xShmLock(pFile,offset,n,flags); in apndShmLock()
9100 pFile->pMethods->xShmBarrier(pFile); in apndShmBarrier()
9106 return pFile->pMethods->xShmUnmap(pFile,deleteFlag); in apndShmUnmap()
9109 /* Fetch a page of a memory-mapped file */
9117 if( p->iMark < 0 || iOfst+iAmt > p->iMark ){ in apndFetch()
9121 return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp); in apndFetch()
9124 /* Release a memory-mapped page */
9128 return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage); in apndUnfetch()
9132 ** Try to read the append-mark off the end of a file. Return the
9133 ** start of the appended database if the append-mark is present.
9134 ** If there is no valid append-mark, return -1;
9136 ** An append-mark is only valid if the NNNNNNNN start-of-database offset
9138 ** start-of-database value must be a multiple of 512.
9143 int msbs = 8 * (APND_MARK_FOS_SZ-1); in apndReadMark()
9146 if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1; in apndReadMark()
9147 rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE); in apndReadMark()
9148 if( rc ) return -1; in apndReadMark()
9149 if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1; in apndReadMark()
9152 msbs -= 8; in apndReadMark()
9155 if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1; in apndReadMark()
9156 if( iMark & 0x1ff ) return -1; in apndReadMark()
9170 /* If file has the correct end-marker, the expected odd size, and the in apndIsAppendvfsDatabase()
9171 ** SQLite DB type marker where the end-marker puts it, then it in apndIsAppendvfsDatabase()
9174 rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark); in apndIsAppendvfsDatabase()
9194 || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0) in apndIsOrdinaryDatabaseFile()
9223 return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags); in apndOpen()
9226 pFile->pMethods = &apnd_io_methods; in apndOpen()
9227 pApndFile->iMark = -1; /* Append mark not yet written */ in apndOpen()
9229 rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags); in apndOpen()
9231 rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz); in apndOpen()
9233 pBaseFile->pMethods->xClose(pBaseFile); in apndOpen()
9237 pFile->pMethods = 0; in apndOpen()
9242 ** the base dispatch-table so this instance mimics the base VFS. in apndOpen()
9244 memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile); in apndOpen()
9247 pApndFile->iPgOne = apndReadMark(sz, pFile); in apndOpen()
9248 if( pApndFile->iPgOne>=0 ){ in apndOpen()
9249 pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */ in apndOpen()
9253 pBaseFile->pMethods->xClose(pBaseFile); in apndOpen()
9255 pFile->pMethods = 0; in apndOpen()
9260 ** Until then, paf->iMark value indicates it is not yet written. in apndOpen()
9262 pApndFile->iPgOne = APND_START_ROUNDUP(sz); in apndOpen()
9274 return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync); in apndDelete()
9278 ** All other VFS methods are pass-thrus.
9286 return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut); in apndAccess()
9294 return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut); in apndFullPathname()
9297 return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath); in apndDlOpen()
9300 ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg); in apndDlError()
9303 return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym); in apndDlSym()
9306 ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle); in apndDlClose()
9309 return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut); in apndRandomness()
9312 return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro); in apndSleep()
9315 return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut); in apndCurrentTime()
9318 return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b); in apndGetLastError()
9321 return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p); in apndCurrentTimeInt64()
9328 return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall); in apndSetSystemCall()
9334 return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName); in apndGetSystemCall()
9337 return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName); in apndNextSystemCall()
9360 apnd_vfs.iVersion = pOrig->iVersion; in sqlite3_appendvfs_init()
9362 apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile); in sqlite3_appendvfs_init()
9378 ** 2017-12-26
9432 /* typedef UINT32_TYPE u32; // 4-byte unsigned integer // */
9433 /* typedef UINT16_TYPE u16; // 2-byte unsigned integer // */
9491 ** Use this value for the "version-made-by" field in new zip file
9494 ** This is what info-zip seems to do.
9497 ** Value for "version-required-to-extract" field of new entries.
9501 ** Value for "general-purpose-bit-flags" field of new entries. Bit
9502 ** 11 means "utf-8 filename and comment".
9522 ** The sizes of the fixed-size part of each of the three main data
9569 *** crc-32 4 bytes
9610 *** crc-32 4 bytes
9638 ZipfileEntry *pNext; /* Next element in in-memory CDS */
9646 sqlite3_vtab_cursor base; /* Base class - must be first */
9649 u8 bNoop; /* If next xNext() call is no-op */
9663 sqlite3_vtab base; /* Base class - must be first */
9688 sqlite3_result_error(ctx, zMsg, -1); in zipfileCtxErrorMsg()
9715 ** argv[0] -> module name ("zipfile")
9716 ** argv[1] -> database name
9717 ** argv[2] -> table name
9718 ** argv[...] -> "column name" and other module argument fields.
9759 pNew->db = db; in zipfileConnect()
9760 pNew->aBuffer = (u8*)&pNew[1]; in zipfileConnect()
9762 pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE]; in zipfileConnect()
9763 memcpy(pNew->zFile, zFile, nFile); in zipfileConnect()
9764 zipfileDequote(pNew->zFile); in zipfileConnect()
9777 sqlite3_free(p->cds.zFile); in zipfileEntryFree()
9790 if( pTab->pWriteFd ){ in zipfileCleanupTransaction()
9791 fclose(pTab->pWriteFd); in zipfileCleanupTransaction()
9792 pTab->pWriteFd = 0; in zipfileCleanupTransaction()
9794 for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){ in zipfileCleanupTransaction()
9795 pNext = pEntry->pNext; in zipfileCleanupTransaction()
9798 pTab->pFirstEntry = 0; in zipfileCleanupTransaction()
9799 pTab->pLastEntry = 0; in zipfileCleanupTransaction()
9800 pTab->szCurrent = 0; in zipfileCleanupTransaction()
9801 pTab->szOrig = 0; in zipfileCleanupTransaction()
9825 pCsr->iId = ++pTab->iNextCsrid; in zipfileOpen()
9826 pCsr->pCsrNext = pTab->pCsrList; in zipfileOpen()
9827 pTab->pCsrList = pCsr; in zipfileOpen()
9839 pCsr->bEof = 0; in zipfileResetCursor()
9840 if( pCsr->pFile ){ in zipfileResetCursor()
9841 fclose(pCsr->pFile); in zipfileResetCursor()
9842 pCsr->pFile = 0; in zipfileResetCursor()
9843 zipfileEntryFree(pCsr->pCurrent); in zipfileResetCursor()
9844 pCsr->pCurrent = 0; in zipfileResetCursor()
9847 for(p=pCsr->pFreeEntry; p; p=pNext){ in zipfileResetCursor()
9848 pNext = p->pNext; in zipfileResetCursor()
9858 ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab); in zipfileClose()
9863 for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext)); in zipfileClose()
9864 *pp = pCsr->pCsrNext; in zipfileClose()
9877 sqlite3_free(pTab->base.zErrMsg); in zipfileTableErr()
9878 pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap); in zipfileTableErr()
9884 sqlite3_free(pCsr->base.pVtab->zErrMsg); in zipfileCursorErr()
9885 pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); in zipfileCursorErr()
9923 fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET); in zipfileAppendData()
9924 n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd); in zipfileAppendData()
9926 pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()"); in zipfileAppendData()
9929 pTab->szCurrent += nWrite; in zipfileAppendData()
9935 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
9942 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
9953 ** Write a 16-bit little endiate integer into buffer aBuf.
9961 ** Write a 32-bit little endiate integer into buffer aBuf.
9970 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
9971 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
9984 ** if the record is not well-formed, or SQLITE_OK otherwise.
9993 pCDS->iVersionMadeBy = zipfileRead16(aRead); in zipfileReadCDS()
9994 pCDS->iVersionExtract = zipfileRead16(aRead); in zipfileReadCDS()
9995 pCDS->flags = zipfileRead16(aRead); in zipfileReadCDS()
9996 pCDS->iCompression = zipfileRead16(aRead); in zipfileReadCDS()
9997 pCDS->mTime = zipfileRead16(aRead); in zipfileReadCDS()
9998 pCDS->mDate = zipfileRead16(aRead); in zipfileReadCDS()
9999 pCDS->crc32 = zipfileRead32(aRead); in zipfileReadCDS()
10000 pCDS->szCompressed = zipfileRead32(aRead); in zipfileReadCDS()
10001 pCDS->szUncompressed = zipfileRead32(aRead); in zipfileReadCDS()
10003 pCDS->nFile = zipfileRead16(aRead); in zipfileReadCDS()
10004 pCDS->nExtra = zipfileRead16(aRead); in zipfileReadCDS()
10005 pCDS->nComment = zipfileRead16(aRead); in zipfileReadCDS()
10006 pCDS->iDiskStart = zipfileRead16(aRead); in zipfileReadCDS()
10007 pCDS->iInternalAttr = zipfileRead16(aRead); in zipfileReadCDS()
10008 pCDS->iExternalAttr = zipfileRead32(aRead); in zipfileReadCDS()
10009 pCDS->iOffset = zipfileRead32(aRead); in zipfileReadCDS()
10018 ** if the record is not well-formed, or SQLITE_OK otherwise.
10031 pLFH->iVersionExtract = zipfileRead16(aRead); in zipfileReadLFH()
10032 pLFH->flags = zipfileRead16(aRead); in zipfileReadLFH()
10033 pLFH->iCompression = zipfileRead16(aRead); in zipfileReadLFH()
10034 pLFH->mTime = zipfileRead16(aRead); in zipfileReadLFH()
10035 pLFH->mDate = zipfileRead16(aRead); in zipfileReadLFH()
10036 pLFH->crc32 = zipfileRead32(aRead); in zipfileReadLFH()
10037 pLFH->szCompressed = zipfileRead32(aRead); in zipfileReadLFH()
10038 pLFH->szUncompressed = zipfileRead32(aRead); in zipfileReadLFH()
10039 pLFH->nFile = zipfileRead16(aRead); in zipfileReadLFH()
10040 pLFH->nExtra = zipfileRead16(aRead); in zipfileReadLFH()
10048 ** Scan through this buffer to find an "extra-timestamp" field. If one
10049 ** exists, extract the 32-bit modification-timestamp from it and store
10052 ** Zero is returned if no extra-timestamp record could be found (and so
10053 ** *pmTime is left unchanged), or non-zero otherwise.
10073 if( b & 0x01 ){ /* 0x01 -> modtime is present */ in zipfileScanExtra()
10087 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
10088 ** fields of the CDS structure passed as the only argument to a 32-bit
10089 ** UNIX seconds-since-the-epoch timestamp. Return the result.
10091 ** "Standard" MS-DOS time format:
10094 ** Bits 00-04: seconds divided by 2
10095 ** Bits 05-10: minute
10096 ** Bits 11-15: hour
10098 ** Bits 00-04: day
10099 ** Bits 05-08: month (1-12)
10100 ** Bits 09-15: years from 1980
10102 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
10107 Y = (1980 + ((pCDS->mDate >> 9) & 0x7F)); in zipfileMtime()
10108 M = ((pCDS->mDate >> 5) & 0x0F); in zipfileMtime()
10109 D = (pCDS->mDate & 0x1F); in zipfileMtime()
10110 sec = (pCDS->mTime & 0x1F)*2; in zipfileMtime()
10111 min = (pCDS->mTime >> 5) & 0x3F; in zipfileMtime()
10112 hr = (pCDS->mTime >> 11) & 0x1F; in zipfileMtime()
10114 Y--; in zipfileMtime()
10120 B = 2 - A + (A/4); in zipfileMtime()
10121 JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec; in zipfileMtime()
10122 return (u32)(JDsec - (i64)24405875*(i64)8640); in zipfileMtime()
10138 A = (int)((JD - 1867216.25)/36524.25); in zipfileMtimeToDos()
10139 A = (int)(JD + 1 + A - (A/4)); in zipfileMtimeToDos()
10141 C = (int)((B - 122.1)/365.25); in zipfileMtimeToDos()
10143 E = (int)((B-D)/30.6001); in zipfileMtimeToDos()
10145 day = B - D - (int)(30.6001*E); in zipfileMtimeToDos()
10146 mon = (E<14 ? E-1 : E-13); in zipfileMtimeToDos()
10147 yr = mon>2 ? C-4716 : C-4715; in zipfileMtimeToDos()
10154 pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9)); in zipfileMtimeToDos()
10155 pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11)); in zipfileMtimeToDos()
10157 pCds->mDate = pCds->mTime = 0; in zipfileMtimeToDos()
10162 || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) in zipfileMtimeToDos()
10170 ** then pFile is a file-handle open on a zip file. In either case, this
10180 const u8 *aBlob, /* Pointer to in-memory file image */ in zipfileGetEntry()
10187 char **pzErr = &pTab->base.zErrMsg; in zipfileGetEntry()
10192 aRead = pTab->aBuffer; in zipfileGetEntry()
10216 rc = zipfileReadCDS(aRead, &pNew->cds); in zipfileGetEntry()
10229 u32 *pt = &pNew->mUnixTime; in zipfileGetEntry()
10230 pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead); in zipfileGetEntry()
10231 pNew->aExtra = (u8*)&pNew[1]; in zipfileGetEntry()
10232 memcpy(pNew->aExtra, &aRead[nFile], nExtra); in zipfileGetEntry()
10233 if( pNew->cds.zFile==0 ){ in zipfileGetEntry()
10235 }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){ in zipfileGetEntry()
10236 pNew->mUnixTime = zipfileMtime(&pNew->cds); in zipfileGetEntry()
10244 rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr); in zipfileGetEntry()
10246 aRead = (u8*)&aBlob[pNew->cds.iOffset]; in zipfileGetEntry()
10251 pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ; in zipfileGetEntry()
10252 pNew->iDataOff += lfh.nFile + lfh.nExtra; in zipfileGetEntry()
10253 if( aBlob && pNew->cds.szCompressed ){ in zipfileGetEntry()
10254 pNew->aData = &pNew->aExtra[nExtra]; in zipfileGetEntry()
10255 memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed); in zipfileGetEntry()
10259 (int)pNew->cds.iOffset in zipfileGetEntry()
10281 if( pCsr->pFile ){ in zipfileNext()
10282 i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize; in zipfileNext()
10283 zipfileEntryFree(pCsr->pCurrent); in zipfileNext()
10284 pCsr->pCurrent = 0; in zipfileNext()
10285 if( pCsr->iNextOff>=iEof ){ in zipfileNext()
10286 pCsr->bEof = 1; in zipfileNext()
10289 ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab); in zipfileNext()
10290 rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p); in zipfileNext()
10292 pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ; in zipfileNext()
10293 pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment; in zipfileNext()
10295 pCsr->pCurrent = p; in zipfileNext()
10298 if( !pCsr->bNoop ){ in zipfileNext()
10299 pCsr->pCurrent = pCsr->pCurrent->pNext; in zipfileNext()
10301 if( pCsr->pCurrent==0 ){ in zipfileNext()
10302 pCsr->bEof = 1; in zipfileNext()
10306 pCsr->bNoop = 0; in zipfileNext()
10340 err = inflateInit2(&str, -15); in zipfileInflate()
10365 ** code is returned and an error message left in virtual-table handle
10382 deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); in zipfileDeflate()
10418 ZipfileCDS *pCDS = &pCsr->pCurrent->cds; in zipfileColumn()
10422 sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT); in zipfileColumn()
10427 sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16); in zipfileColumn()
10430 sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime); in zipfileColumn()
10435 sqlite3_result_int64(ctx, pCDS->szUncompressed); in zipfileColumn()
10442 if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){ in zipfileColumn()
10443 int sz = pCDS->szCompressed; in zipfileColumn()
10444 int szFinal = pCDS->szUncompressed; in zipfileColumn()
10448 if( pCsr->pCurrent->aData ){ in zipfileColumn()
10449 aBuf = pCsr->pCurrent->aData; in zipfileColumn()
10455 FILE *pFile = pCsr->pFile; in zipfileColumn()
10457 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd; in zipfileColumn()
10459 rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff, in zipfileColumn()
10460 &pCsr->base.pVtab->zErrMsg in zipfileColumn()
10465 if( i==5 && pCDS->iCompression ){ in zipfileColumn()
10473 /* Figure out if this is a directory or a zero-sized file. Consider in zipfileColumn()
10476 u32 mode = pCDS->iExternalAttr >> 16; in zipfileColumn()
10478 && pCDS->nFile>=1 in zipfileColumn()
10479 && pCDS->zFile[pCDS->nFile-1]!='/' in zipfileColumn()
10488 sqlite3_result_int(ctx, pCDS->iCompression); in zipfileColumn()
10492 sqlite3_result_int64(ctx, pCsr->iId); in zipfileColumn()
10504 return pCsr->bEof; in zipfileEof()
10510 ** is guaranteed to be a file-handle open on a zip file.
10515 ** an English language error message may be left in virtual-table pTab.
10519 const u8 *aBlob, /* Pointer to in-memory file image */ in zipfileReadEOCD()
10524 u8 *aRead = pTab->aBuffer; /* Temporary buffer */ in zipfileReadEOCD()
10538 iOff = szFile - nRead; in zipfileReadEOCD()
10539 rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg); in zipfileReadEOCD()
10542 aRead = (u8*)&aBlob[nBlob-nRead]; in zipfileReadEOCD()
10549 for(i=nRead-20; i>=0; i--){ in zipfileReadEOCD()
10557 pTab->base.zErrMsg = sqlite3_mprintf( in zipfileReadEOCD()
10564 pEOCD->iDisk = zipfileRead16(aRead); in zipfileReadEOCD()
10565 pEOCD->iFirstDisk = zipfileRead16(aRead); in zipfileReadEOCD()
10566 pEOCD->nEntry = zipfileRead16(aRead); in zipfileReadEOCD()
10567 pEOCD->nEntryTotal = zipfileRead16(aRead); in zipfileReadEOCD()
10568 pEOCD->nSize = zipfileRead32(aRead); in zipfileReadEOCD()
10569 pEOCD->iOffset = zipfileRead32(aRead); in zipfileReadEOCD()
10586 assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) ); in zipfileAddEntry()
10587 assert( pNew->pNext==0 ); in zipfileAddEntry()
10589 if( pTab->pFirstEntry==0 ){ in zipfileAddEntry()
10590 pTab->pFirstEntry = pTab->pLastEntry = pNew; in zipfileAddEntry()
10592 assert( pTab->pLastEntry->pNext==0 ); in zipfileAddEntry()
10593 pTab->pLastEntry->pNext = pNew; in zipfileAddEntry()
10594 pTab->pLastEntry = pNew; in zipfileAddEntry()
10598 for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext)); in zipfileAddEntry()
10599 pNew->pNext = pBefore; in zipfileAddEntry()
10610 rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd); in zipfileLoadDirectory()
10614 rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew); in zipfileLoadDirectory()
10619 iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment; in zipfileLoadDirectory()
10633 ZipfileTab *pTab = (ZipfileTab*)cur->pVtab; in zipfileFilter()
10637 int bInMemory = 0; /* True for an in-memory zipfile */ in zipfileFilter()
10644 if( pTab->zFile ){ in zipfileFilter()
10645 zFile = pTab->zFile; in zipfileFilter()
10653 assert( pTab->pFirstEntry==0 ); in zipfileFilter()
10659 pCsr->pFreeEntry = pTab->pFirstEntry; in zipfileFilter()
10660 pTab->pFirstEntry = pTab->pLastEntry = 0; in zipfileFilter()
10667 if( 0==pTab->pWriteFd && 0==bInMemory ){ in zipfileFilter()
10668 pCsr->pFile = zFile ? fopen(zFile, "rb") : 0; in zipfileFilter()
10669 if( pCsr->pFile==0 ){ in zipfileFilter()
10673 rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd); in zipfileFilter()
10675 if( pCsr->eocd.nEntry==0 ){ in zipfileFilter()
10676 pCsr->bEof = 1; in zipfileFilter()
10678 pCsr->iNextOff = pCsr->eocd.iOffset; in zipfileFilter()
10684 pCsr->bNoop = 1; in zipfileFilter()
10685 pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry; in zipfileFilter()
10700 int idx = -1; in zipfileBestIndex()
10704 for(i=0; i<pIdxInfo->nConstraint; i++){ in zipfileBestIndex()
10705 const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; in zipfileBestIndex()
10706 if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue; in zipfileBestIndex()
10707 if( pCons->usable==0 ){ in zipfileBestIndex()
10709 }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ in zipfileBestIndex()
10713 pIdxInfo->estimatedCost = 1000.0; in zipfileBestIndex()
10715 pIdxInfo->aConstraintUsage[idx].argvIndex = 1; in zipfileBestIndex()
10716 pIdxInfo->aConstraintUsage[idx].omit = 1; in zipfileBestIndex()
10717 pIdxInfo->idxNum = 1; in zipfileBestIndex()
10729 pNew->cds.zFile = sqlite3_mprintf("%s", zPath); in zipfileNewEntry()
10730 if( pNew->cds.zFile==0 ){ in zipfileNewEntry()
10739 ZipfileCDS *pCds = &pEntry->cds; in zipfileSerializeLFH()
10742 pCds->nExtra = 9; in zipfileSerializeLFH()
10746 zipfileWrite16(a, pCds->iVersionExtract); in zipfileSerializeLFH()
10747 zipfileWrite16(a, pCds->flags); in zipfileSerializeLFH()
10748 zipfileWrite16(a, pCds->iCompression); in zipfileSerializeLFH()
10749 zipfileWrite16(a, pCds->mTime); in zipfileSerializeLFH()
10750 zipfileWrite16(a, pCds->mDate); in zipfileSerializeLFH()
10751 zipfileWrite32(a, pCds->crc32); in zipfileSerializeLFH()
10752 zipfileWrite32(a, pCds->szCompressed); in zipfileSerializeLFH()
10753 zipfileWrite32(a, pCds->szUncompressed); in zipfileSerializeLFH()
10754 zipfileWrite16(a, (u16)pCds->nFile); in zipfileSerializeLFH()
10755 zipfileWrite16(a, pCds->nExtra); in zipfileSerializeLFH()
10759 memcpy(a, pCds->zFile, (int)pCds->nFile); in zipfileSerializeLFH()
10760 a += (int)pCds->nFile; in zipfileSerializeLFH()
10766 zipfileWrite32(a, pEntry->mUnixTime); in zipfileSerializeLFH()
10768 return a-aBuf; in zipfileSerializeLFH()
10777 u8 *aBuf = pTab->aBuffer; in zipfileAppendEntry()
10784 pEntry->iDataOff = pTab->szCurrent; in zipfileAppendEntry()
10804 const char zTemplate[11] = "-rwxrwxrwx"; in zipfileGetMode()
10808 case '-': mode |= S_IFREG; break; in zipfileGetMode()
10814 if( z[i]==zTemplate[i] ) mode |= 1 << (9-i); in zipfileGetMode()
10815 else if( z[i]!='-' ) goto parse_error; in zipfileGetMode()
10820 ** Or vice-versa - no data but "mode" is a file or symlink. */ in zipfileGetMode()
10833 ** Both (const char*) arguments point to nul-terminated strings. Argument
10838 if( nA>0 && zA[nA-1]=='/' ) nA--; in zipfileComparePath()
10839 if( nB>0 && zB[nB-1]=='/' ) nB--; in zipfileComparePath()
10848 assert( pTab->pWriteFd==0 ); in zipfileBegin()
10849 if( pTab->zFile==0 || pTab->zFile[0]==0 ){ in zipfileBegin()
10850 pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename"); in zipfileBegin()
10857 ** in main-memory until the transaction is committed. */ in zipfileBegin()
10858 pTab->pWriteFd = fopen(pTab->zFile, "ab+"); in zipfileBegin()
10859 if( pTab->pWriteFd==0 ){ in zipfileBegin()
10860 pTab->base.zErrMsg = sqlite3_mprintf( in zipfileBegin()
10861 "zipfile: failed to open file %s for writing", pTab->zFile in zipfileBegin()
10865 fseek(pTab->pWriteFd, 0, SEEK_END); in zipfileBegin()
10866 pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd); in zipfileBegin()
10878 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
10885 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ in zipfileTime()
10887 pVfs->xCurrentTimeInt64(pVfs, &ms); in zipfileTime()
10888 ret = (u32)((ms/1000) - ((i64)24405875 * 8640)); in zipfileTime()
10891 pVfs->xCurrentTime(pVfs, &day); in zipfileTime()
10892 ret = (u32)((day - 2440587.5) * 86400); in zipfileTime()
10898 ** Return a 32-bit timestamp in UNIX epoch format.
10902 ** cast to a 32-bit unsigned integer.
10912 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
10917 if( pTab->pFirstEntry==pOld ){ in zipfileRemoveEntryFromList()
10918 pTab->pFirstEntry = pOld->pNext; in zipfileRemoveEntryFromList()
10919 if( pTab->pLastEntry==pOld ) pTab->pLastEntry = 0; in zipfileRemoveEntryFromList()
10922 for(p=pTab->pFirstEntry; p; p=p->pNext){ in zipfileRemoveEntryFromList()
10923 if( p->pNext==pOld ){ in zipfileRemoveEntryFromList()
10924 p->pNext = pOld->pNext; in zipfileRemoveEntryFromList()
10925 if( pTab->pLastEntry==pOld ) pTab->pLastEntry = p; in zipfileRemoveEntryFromList()
10945 ZipfileEntry *pNew = 0; /* New in-memory CDS entry */ in zipfileUpdate()
10965 if( pTab->pWriteFd==0 ){ in zipfileUpdate()
10980 for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){ in zipfileUpdate()
10981 if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){ in zipfileUpdate()
10984 assert( pOld->pNext ); in zipfileUpdate()
11020 rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg); in zipfileUpdate()
11035 rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg); in zipfileUpdate()
11047 ** '/'. This appears to be required for compatibility with info-zip in zipfileUpdate()
11050 if( nPath<=0 || zPath[nPath-1]!='/' ){ in zipfileUpdate()
11062 /* Check that we're not inserting a duplicate entry -OR- updating an in zipfileUpdate()
11066 for(p=pTab->pFirstEntry; p; p=p->pNext){ in zipfileUpdate()
11067 if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){ in zipfileUpdate()
11068 switch( sqlite3_vtab_on_conflict(pTab->db) ){ in zipfileUpdate()
11093 pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; in zipfileUpdate()
11094 pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; in zipfileUpdate()
11095 pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS; in zipfileUpdate()
11096 pNew->cds.iCompression = (u16)iMethod; in zipfileUpdate()
11097 zipfileMtimeToDos(&pNew->cds, mTime); in zipfileUpdate()
11098 pNew->cds.crc32 = iCrc32; in zipfileUpdate()
11099 pNew->cds.szCompressed = nData; in zipfileUpdate()
11100 pNew->cds.szUncompressed = (u32)sz; in zipfileUpdate()
11101 pNew->cds.iExternalAttr = (mode<<16); in zipfileUpdate()
11102 pNew->cds.iOffset = (u32)pTab->szCurrent; in zipfileUpdate()
11103 pNew->cds.nFile = (u16)nPath; in zipfileUpdate()
11104 pNew->mUnixTime = (u32)mTime; in zipfileUpdate()
11113 for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ in zipfileUpdate()
11114 if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){ in zipfileUpdate()
11115 pCsr->pCurrent = pCsr->pCurrent->pNext; in zipfileUpdate()
11116 pCsr->bNoop = 1; in zipfileUpdate()
11133 zipfileWrite16(a, p->iDisk); in zipfileSerializeEOCD()
11134 zipfileWrite16(a, p->iFirstDisk); in zipfileSerializeEOCD()
11135 zipfileWrite16(a, p->nEntry); in zipfileSerializeEOCD()
11136 zipfileWrite16(a, p->nEntryTotal); in zipfileSerializeEOCD()
11137 zipfileWrite32(a, p->nSize); in zipfileSerializeEOCD()
11138 zipfileWrite32(a, p->iOffset); in zipfileSerializeEOCD()
11141 return a-aBuf; in zipfileSerializeEOCD()
11145 int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer); in zipfileAppendEOCD()
11147 return zipfileAppendData(pTab, pTab->aBuffer, nBuf); in zipfileAppendEOCD()
11156 ZipfileCDS *pCDS = &pEntry->cds; in zipfileSerializeCDS()
11158 if( pEntry->aExtra==0 ){ in zipfileSerializeCDS()
11159 pCDS->nExtra = 9; in zipfileSerializeCDS()
11163 zipfileWrite16(a, pCDS->iVersionMadeBy); in zipfileSerializeCDS()
11164 zipfileWrite16(a, pCDS->iVersionExtract); in zipfileSerializeCDS()
11165 zipfileWrite16(a, pCDS->flags); in zipfileSerializeCDS()
11166 zipfileWrite16(a, pCDS->iCompression); in zipfileSerializeCDS()
11167 zipfileWrite16(a, pCDS->mTime); in zipfileSerializeCDS()
11168 zipfileWrite16(a, pCDS->mDate); in zipfileSerializeCDS()
11169 zipfileWrite32(a, pCDS->crc32); in zipfileSerializeCDS()
11170 zipfileWrite32(a, pCDS->szCompressed); in zipfileSerializeCDS()
11171 zipfileWrite32(a, pCDS->szUncompressed); in zipfileSerializeCDS()
11173 zipfileWrite16(a, pCDS->nFile); in zipfileSerializeCDS()
11174 zipfileWrite16(a, pCDS->nExtra); in zipfileSerializeCDS()
11175 zipfileWrite16(a, pCDS->nComment); in zipfileSerializeCDS()
11176 zipfileWrite16(a, pCDS->iDiskStart); in zipfileSerializeCDS()
11177 zipfileWrite16(a, pCDS->iInternalAttr); in zipfileSerializeCDS()
11178 zipfileWrite32(a, pCDS->iExternalAttr); in zipfileSerializeCDS()
11179 zipfileWrite32(a, pCDS->iOffset); in zipfileSerializeCDS()
11181 memcpy(a, pCDS->zFile, pCDS->nFile); in zipfileSerializeCDS()
11182 a += pCDS->nFile; in zipfileSerializeCDS()
11184 if( pEntry->aExtra ){ in zipfileSerializeCDS()
11185 int n = (int)pCDS->nExtra + (int)pCDS->nComment; in zipfileSerializeCDS()
11186 memcpy(a, pEntry->aExtra, n); in zipfileSerializeCDS()
11189 assert( pCDS->nExtra==9 ); in zipfileSerializeCDS()
11193 zipfileWrite32(a, pEntry->mUnixTime); in zipfileSerializeCDS()
11196 return a-aBuf; in zipfileSerializeCDS()
11202 if( pTab->pWriteFd ){ in zipfileCommit()
11203 i64 iOffset = pTab->szCurrent; in zipfileCommit()
11209 for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){ in zipfileCommit()
11210 int n = zipfileSerializeCDS(p, pTab->aBuffer); in zipfileCommit()
11211 rc = zipfileAppendData(pTab, pTab->aBuffer, n); in zipfileCommit()
11220 eocd.nSize = (u32)(pTab->szCurrent - iOffset); in zipfileCommit()
11235 for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ in zipfileFindCursor()
11236 if( iId==pCsr->iId ) break; in zipfileFindCursor()
11252 ZipfileCDS *p = &pCsr->pCurrent->cds; in zipfileFunctionCds()
11254 "\"version-made-by\" : %u, " in zipfileFunctionCds()
11255 "\"version-to-extract\" : %u, " in zipfileFunctionCds()
11261 "\"compressed-size\" : %u, " in zipfileFunctionCds()
11262 "\"uncompressed-size\" : %u, " in zipfileFunctionCds()
11263 "\"file-name-length\" : %u, " in zipfileFunctionCds()
11264 "\"extra-field-length\" : %u, " in zipfileFunctionCds()
11265 "\"file-comment-length\" : %u, " in zipfileFunctionCds()
11266 "\"disk-number-start\" : %u, " in zipfileFunctionCds()
11267 "\"internal-attr\" : %u, " in zipfileFunctionCds()
11268 "\"external-attr\" : %u, " in zipfileFunctionCds()
11270 (u32)p->iVersionMadeBy, (u32)p->iVersionExtract, in zipfileFunctionCds()
11271 (u32)p->flags, (u32)p->iCompression, in zipfileFunctionCds()
11272 (u32)p->mTime, (u32)p->mDate, in zipfileFunctionCds()
11273 (u32)p->crc32, (u32)p->szCompressed, in zipfileFunctionCds()
11274 (u32)p->szUncompressed, (u32)p->nFile, in zipfileFunctionCds()
11275 (u32)p->nExtra, (u32)p->nComment, in zipfileFunctionCds()
11276 (u32)p->iDiskStart, (u32)p->iInternalAttr, in zipfileFunctionCds()
11277 (u32)p->iExternalAttr, (u32)p->iOffset in zipfileFunctionCds()
11283 sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT); in zipfileFunctionCds()
11323 if( pBuf->n+nByte>pBuf->nAlloc ){ in zipfileBufferGrow()
11325 sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512; in zipfileBufferGrow()
11326 int nReq = pBuf->n + nByte; in zipfileBufferGrow()
11329 aNew = sqlite3_realloc64(pBuf->a, nNew); in zipfileBufferGrow()
11331 pBuf->a = aNew; in zipfileBufferGrow()
11332 pBuf->nAlloc = (int)nNew; in zipfileBufferGrow()
11360 int iMethod = -1; /* Compression method to use (0 or 8) */ in zipfileStep()
11399 zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL"); in zipfileStep()
11452 if( nName>0 && zName[nName-1]=='/' ){ in zipfileStep()
11453 zErr = sqlite3_mprintf("non-directory name must not end with /"); in zipfileStep()
11458 if( nName==0 || zName[nName-1]!='/' ){ in zipfileStep()
11466 while( nName>1 && zName[nName-2]=='/' ) nName--; in zipfileStep()
11480 e.cds.iOffset = p->body.n; in zipfileStep()
11486 if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out; in zipfileStep()
11487 p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]); in zipfileStep()
11491 if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out; in zipfileStep()
11492 memcpy(&p->body.a[p->body.n], aData, nData); in zipfileStep()
11493 p->body.n += nData; in zipfileStep()
11498 if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out; in zipfileStep()
11499 p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]); in zipfileStep()
11502 p->nEntry++; in zipfileStep()
11509 sqlite3_result_error(pCtx, zErr, -1); in zipfileStep()
11528 if( p->nEntry>0 ){ in zipfileFinal()
11530 eocd.nEntry = (u16)p->nEntry; in zipfileFinal()
11531 eocd.nEntryTotal = (u16)p->nEntry; in zipfileFinal()
11532 eocd.nSize = p->cds.n; in zipfileFinal()
11533 eocd.iOffset = p->body.n; in zipfileFinal()
11535 nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ; in zipfileFinal()
11540 memcpy(aZip, p->body.a, p->body.n); in zipfileFinal()
11541 memcpy(&aZip[p->body.n], p->cds.a, p->cds.n); in zipfileFinal()
11542 zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]); in zipfileFinal()
11547 sqlite3_free(p->body.a); in zipfileFinal()
11548 sqlite3_free(p->cds.a); in zipfileFinal()
11563 zipfileOpen, /* xOpen - open a cursor */ in zipfileRegister()
11564 zipfileClose, /* xClose - close a cursor */ in zipfileRegister()
11565 zipfileFilter, /* xFilter - configure scan constraints */ in zipfileRegister()
11566 zipfileNext, /* xNext - advance a cursor */ in zipfileRegister()
11567 zipfileEof, /* xEof - check for end of scan */ in zipfileRegister()
11568 zipfileColumn, /* xColumn - read data */ in zipfileRegister()
11569 0, /* xRowid - read data */ in zipfileRegister()
11585 if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1); in zipfileRegister()
11587 rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0, in zipfileRegister()
11617 ** 2017-12-17
11629 ** for working with sqlar archives and used by the shell tool's built-in
11645 ** contains a two-byte identification header and a four-byte checksum at
11670 sqlite3_result_error(context, "error in compress()", -1); in sqlarCompressFunc()
11713 sqlite3_result_error(context, "error in uncompress()", -1); in sqlarUncompressFunc()
11769 ** an English-language error message. In this case it is the responsibility
11789 ** the analysis - indexes are recommended based on the database schema only.
11813 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
11814 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
11849 ** possible to add further SQL statements to the object or to re-attempt
11867 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
11875 ** If an out-of-range value (less than zero or equal to or greater than the
11909 ** sqlite3-expert_new().
11974 ** any other type of single-ended range constraint on a column).
12020 ** An object of the following type is created for each unique table/write-op
12021 ** seen. The objects are stored in a singly-linked list beginning at
12056 char *zKey; /* nul-terminated key */
12057 char *zVal; /* nul-terminated value string */
12058 char *zVal2; /* nul-terminated value string 2 */
12073 sqlite3 *dbm; /* In-memory db for this analysis */
12119 for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){ in idxHashClear()
12120 pNext = pEntry->pHashNext; in idxHashClear()
12121 sqlite3_free(pEntry->zVal2); in idxHashClear()
12142 ** If zKey is already present in the hash table, return non-zero and do
12157 for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){ in idxHashAdd()
12158 if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){ in idxHashAdd()
12164 pEntry->zKey = (char*)&pEntry[1]; in idxHashAdd()
12165 memcpy(pEntry->zKey, zKey, nKey); in idxHashAdd()
12167 pEntry->zVal = &pEntry->zKey[nKey+1]; in idxHashAdd()
12168 memcpy(pEntry->zVal, zVal, nVal); in idxHashAdd()
12170 pEntry->pHashNext = pHash->aHash[iHash]; in idxHashAdd()
12171 pHash->aHash[iHash] = pEntry; in idxHashAdd()
12173 pEntry->pNext = pHash->pFirst; in idxHashAdd()
12174 pHash->pFirst = pEntry; in idxHashAdd()
12181 ** hash-entry object.
12189 for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){ in idxHashFind()
12190 if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){ in idxHashFind()
12205 if( pEntry ) return pEntry->zVal; in idxHashSearch()
12211 ** variable to point to a copy of nul-terminated string zColl.
12220 pNew->zColl = (char*)&pNew[1]; in idxNewConstraint()
12221 memcpy(pNew->zColl, zColl, nColl+1); in idxNewConstraint()
12246 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); in idxPrepareStmt()
12301 assert( zIn[n-1]=='\'' ); in expertDequote()
12306 for(iIn=1; iIn<(n-1); iIn++){ in expertDequote()
12321 ** methods of the r-tree virtual table.
12323 ** argv[0] -> module name
12324 ** argv[1] -> database name
12325 ** argv[2] -> table name
12326 ** argv[...] -> column names...
12350 p->pExpert = pExpert; in expertConnect()
12351 p->pTab = pExpert->pTable; in expertConnect()
12352 assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 ); in expertConnect()
12385 pScan->pTab = p->pTab; in expertBestIndex()
12386 pScan->pNextScan = p->pExpert->pScan; in expertBestIndex()
12387 p->pExpert->pScan = pScan; in expertBestIndex()
12390 for(i=0; i<pIdxInfo->nConstraint; i++){ in expertBestIndex()
12391 struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; in expertBestIndex()
12392 if( pCons->usable in expertBestIndex()
12393 && pCons->iColumn>=0 in expertBestIndex()
12394 && p->pTab->aCol[pCons->iColumn].iPk==0 in expertBestIndex()
12395 && (pCons->op & opmask) in expertBestIndex()
12401 pNew->iCol = pCons->iColumn; in expertBestIndex()
12402 if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ in expertBestIndex()
12403 pNew->pNext = pScan->pEq; in expertBestIndex()
12404 pScan->pEq = pNew; in expertBestIndex()
12406 pNew->bRange = 1; in expertBestIndex()
12407 pNew->pNext = pScan->pRange; in expertBestIndex()
12408 pScan->pRange = pNew; in expertBestIndex()
12412 pIdxInfo->aConstraintUsage[i].argvIndex = n; in expertBestIndex()
12417 for(i=pIdxInfo->nOrderBy-1; i>=0; i--){ in expertBestIndex()
12418 int iCol = pIdxInfo->aOrderBy[i].iColumn; in expertBestIndex()
12420 IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl); in expertBestIndex()
12422 pNew->iCol = iCol; in expertBestIndex()
12423 pNew->bDesc = pIdxInfo->aOrderBy[i].desc; in expertBestIndex()
12424 pNew->pNext = pScan->pOrder; in expertBestIndex()
12425 pNew->pLink = pScan->pOrder; in expertBestIndex()
12426 pScan->pOrder = pNew; in expertBestIndex()
12433 pIdxInfo->estimatedCost = 1000000.0 / (n+1); in expertBestIndex()
12467 sqlite3_finalize(pCsr->pData); in expertClose()
12475 ** Return non-zero if the cursor does not currently point to a valid
12480 return pCsr->pData==0; in expertEof()
12490 assert( pCsr->pData ); in expertNext()
12491 rc = sqlite3_step(pCsr->pData); in expertNext()
12493 rc = sqlite3_finalize(pCsr->pData); in expertNext()
12494 pCsr->pData = 0; in expertNext()
12517 pVal = sqlite3_column_value(pCsr->pData, i); in expertColumn()
12533 ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab); in expertFilter()
12534 sqlite3expert *pExpert = pVtab->pExpert; in expertFilter()
12541 rc = sqlite3_finalize(pCsr->pData); in expertFilter()
12542 pCsr->pData = 0; in expertFilter()
12544 rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg, in expertFilter()
12545 "SELECT * FROM main.%Q WHERE sqlite_expert_sample()", pVtab->pTab->zName in expertFilter()
12558 expertConnect, /* xCreate - create a table */ in idxRegisterVtab()
12559 expertConnect, /* xConnect - connect to an existing table */ in idxRegisterVtab()
12560 expertBestIndex, /* xBestIndex - Determine search strategy */ in idxRegisterVtab()
12561 expertDisconnect, /* xDisconnect - Disconnect from a table */ in idxRegisterVtab()
12562 expertDisconnect, /* xDestroy - Drop a table */ in idxRegisterVtab()
12563 expertOpen, /* xOpen - open a cursor */ in idxRegisterVtab()
12564 expertClose, /* xClose - close a cursor */ in idxRegisterVtab()
12565 expertFilter, /* xFilter - configure scan constraints */ in idxRegisterVtab()
12566 expertNext, /* xNext - advance a cursor */ in idxRegisterVtab()
12568 expertColumn, /* xColumn - read data */ in idxRegisterVtab()
12569 expertRowid, /* xRowid - read data */ in idxRegisterVtab()
12570 expertUpdate, /* xUpdate - write data */ in idxRegisterVtab()
12571 0, /* xBegin - begin transaction */ in idxRegisterVtab()
12572 0, /* xSync - sync transaction */ in idxRegisterVtab()
12573 0, /* xCommit - commit transaction */ in idxRegisterVtab()
12574 0, /* xRollback - rollback transaction */ in idxRegisterVtab()
12575 0, /* xFindFunction - function overloading */ in idxRegisterVtab()
12576 0, /* xRename - rename the table */ in idxRegisterVtab()
12584 return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p); in idxRegisterVtab()
12653 pNew->aCol = (IdxColumn*)&pNew[1]; in idxGetTableInfo()
12654 pNew->nCol = nCol; in idxGetTableInfo()
12655 pCsr = (char*)&pNew->aCol[nCol]; in idxGetTableInfo()
12665 pNew->aCol[nCol].zName = pCsr; in idxGetTableInfo()
12666 pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1); in idxGetTableInfo()
12676 pNew->aCol[nCol].zColl = pCsr; in idxGetTableInfo()
12689 pNew->zName = pCsr; in idxGetTableInfo()
12690 if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1); in idxGetTableInfo()
12698 ** This function is a no-op if *pRc is set to anything other than
12767 IdxColumn *p = &pTab->aCol[pCons->iCol]; in idxAppendColDefn()
12770 if( idxIdentifierRequiresQuotes(p->zName) ){ in idxAppendColDefn()
12771 zRet = idxAppendText(pRc, zRet, "%Q", p->zName); in idxAppendColDefn()
12773 zRet = idxAppendText(pRc, zRet, "%s", p->zName); in idxAppendColDefn()
12776 if( sqlite3_stricmp(p->zColl, pCons->zColl) ){ in idxAppendColDefn()
12777 if( idxIdentifierRequiresQuotes(pCons->zColl) ){ in idxAppendColDefn()
12778 zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl); in idxAppendColDefn()
12780 zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl); in idxAppendColDefn()
12784 if( pCons->bDesc ){ in idxAppendColDefn()
12793 ** such an index is found, return non-zero. Or, if no such index is found,
12805 const char *zTbl = pScan->pTab->zName; in idxFindCompatible()
12812 for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++; in idxFindCompatible()
12823 for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0; in idxFindCompatible()
12832 for(pIter=pEq; pIter; pIter=pIter->pLink){ in idxFindCompatible()
12833 if( pIter->bFlag ) continue; in idxFindCompatible()
12834 if( pIter->iCol!=iCol ) continue; in idxFindCompatible()
12835 if( sqlite3_stricmp(pIter->zColl, zColl) ) continue; in idxFindCompatible()
12836 pIter->bFlag = 1; in idxFindCompatible()
12845 if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){ in idxFindCompatible()
12849 pT = pT->pLink; in idxFindCompatible()
12885 sqlite3 *dbm = p->dbm; in idxCreateFromCons()
12888 IdxTable *pTab = pScan->pTab; in idxCreateFromCons()
12895 for(pCons=pEq; pCons; pCons=pCons->pLink){ in idxCreateFromCons()
12898 for(pCons=pTail; pCons; pCons=pCons->pLink){ in idxCreateFromCons()
12904 const char *zTable = pScan->pTab->zName; in idxCreateFromCons()
12946 rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg); in idxCreateFromCons()
12950 idxHashAdd(&rc, &p->hIdx, zName, zIdx); in idxCreateFromCons()
12969 for(pCmp=pList; pCmp; pCmp=pCmp->pLink){ in idxFindConstraint()
12970 if( p->iCol==pCmp->iCol ) return 1; in idxFindConstraint()
12985 for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){ in idxCreateFromWhere()
12987 pCon->pLink = p1; in idxCreateFromWhere()
12999 for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){ in idxCreateFromWhere()
13000 assert( pCon->pLink==0 ); in idxCreateFromWhere()
13012 ** linked-list pScan.
13018 for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){ in idxCreateCandidates()
13020 if( rc==SQLITE_OK && pIter->pOrder ){ in idxCreateCandidates()
13021 rc = idxCreateFromWhere(p, pIter, pIter->pOrder); in idxCreateCandidates()
13036 pNext = p->pNext; in idxConstraintFree()
13049 pNext = p->pNextScan; in idxScanFree()
13050 idxConstraintFree(p->pOrder); in idxScanFree()
13051 idxConstraintFree(p->pEq); in idxScanFree()
13052 idxConstraintFree(p->pRange); in idxScanFree()
13065 pNext = p->pNext; in idxStatementFree()
13066 sqlite3_free(p->zEQP); in idxStatementFree()
13067 sqlite3_free(p->zIdx); in idxStatementFree()
13079 pNext = pIter->pNext; in idxTableFree()
13091 pNext = pIter->pNext; in idxWriteFree()
13108 sqlite3 *dbm = p->dbm; in idxFindIndexes()
13114 for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){ in idxFindIndexes()
13119 "EXPLAIN QUERY PLAN %s", pStmt->zSql in idxFindIndexes()
13147 zSql = idxHashSearch(&p->hIdx, zIdx, nIdx); in idxFindIndexes()
13156 if( zDetail[0]!='-' ){ in idxFindIndexes()
13157 pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail); in idxFindIndexes()
13161 for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){ in idxFindIndexes()
13162 pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey); in idxFindIndexes()
13188 for(pTab=p->pTable; pTab; pTab=pTab->pNext){ in idxAuthCallback()
13189 if( 0==sqlite3_stricmp(z3, pTab->zName) ) break; in idxAuthCallback()
13193 for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){ in idxAuthCallback()
13194 if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break; in idxAuthCallback()
13199 pWrite->pTab = pTab; in idxAuthCallback()
13200 pWrite->eOp = eOp; in idxAuthCallback()
13201 pWrite->pNext = p->pWrite; in idxAuthCallback()
13202 p->pWrite = pWrite; in idxAuthCallback()
13218 IdxTable *pTab = pWrite->pTab; in idxProcessOneTrigger()
13219 const char *zTab = pTab->zName; in idxProcessOneTrigger()
13229 rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab); in idxProcessOneTrigger()
13233 rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr); in idxProcessOneTrigger()
13243 rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr); in idxProcessOneTrigger()
13248 switch( pWrite->eOp ){ in idxProcessOneTrigger()
13252 for(i=0; i<pTab->nCol; i++){ in idxProcessOneTrigger()
13261 for(i=0; i<pTab->nCol; i++){ in idxProcessOneTrigger()
13263 pTab->aCol[i].zName in idxProcessOneTrigger()
13269 assert( pWrite->eOp==SQLITE_DELETE ); in idxProcessOneTrigger()
13279 rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0); in idxProcessOneTrigger()
13282 idxDatabaseError(p->dbv, pzErr); in idxProcessOneTrigger()
13288 rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr); in idxProcessOneTrigger()
13297 IdxWrite *pFirst = p->pWrite; in idxProcessTriggers()
13301 for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){ in idxProcessTriggers()
13305 pFirst = p->pWrite; in idxProcessTriggers()
13318 ** 1) Add an entry to the p->pTable list, and in idxCreateVtabSchema()
13321 rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg, in idxCreateVtabSchema()
13337 if( zSql ) rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg); in idxCreateVtabSchema()
13340 rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg); in idxCreateVtabSchema()
13345 pTab->pNext = p->pTable; in idxCreateVtabSchema()
13346 p->pTable = pTab; in idxCreateVtabSchema()
13350 for(i=0; i<pTab->nCol; i++){ in idxCreateVtabSchema()
13352 (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl in idxCreateVtabSchema()
13362 rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg); in idxCreateVtabSchema()
13390 if( p->nRow==0.0 ){ in idxSampleFunc()
13393 bRet = (p->nRet / p->nRow) <= p->target; in idxSampleFunc()
13397 bRet = ((int)rnd % 100) <= p->iTarget; in idxSampleFunc()
13402 p->nRow += 1.0; in idxSampleFunc()
13403 p->nRet += (double)bRet; in idxSampleFunc()
13432 assert( iSlot<p->nSlot ); in idxRemFunc()
13433 pSlot = &p->aSlot[iSlot]; in idxRemFunc()
13435 switch( pSlot->eType ){ in idxRemFunc()
13437 /* no-op */ in idxRemFunc()
13441 sqlite3_result_int64(pCtx, pSlot->iVal); in idxRemFunc()
13445 sqlite3_result_double(pCtx, pSlot->rVal); in idxRemFunc()
13449 sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT); in idxRemFunc()
13453 sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT); in idxRemFunc()
13457 pSlot->eType = sqlite3_value_type(argv[1]); in idxRemFunc()
13458 switch( pSlot->eType ){ in idxRemFunc()
13460 /* no-op */ in idxRemFunc()
13464 pSlot->iVal = sqlite3_value_int64(argv[1]); in idxRemFunc()
13468 pSlot->rVal = sqlite3_value_double(argv[1]); in idxRemFunc()
13475 if( nByte>pSlot->nByte ){ in idxRemFunc()
13476 char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2); in idxRemFunc()
13481 pSlot->nByte = nByte*2; in idxRemFunc()
13482 pSlot->z = zNew; in idxRemFunc()
13484 pSlot->n = nByte; in idxRemFunc()
13485 if( pSlot->eType==SQLITE_BLOB ){ in idxRemFunc()
13487 if( pData ) memcpy(pSlot->z, pData, nByte); in idxRemFunc()
13490 memcpy(pSlot->z, pData, nByte); in idxRemFunc()
13534 assert( p->iSample>0 ); in idxPopulateOneStat1()
13537 sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC); in idxPopulateOneStat1()
13550 if( p->iSample==100 ){ in idxPopulateOneStat1()
13565 sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv); in idxPopulateOneStat1()
13582 for(/*no-op*/; i<nCol; i++){ in idxPopulateOneStat1()
13597 sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC); in idxPopulateOneStat1()
13598 sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC); in idxPopulateOneStat1()
13599 sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC); in idxPopulateOneStat1()
13604 pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx)); in idxPopulateOneStat1()
13606 assert( pEntry->zVal2==0 ); in idxPopulateOneStat1()
13607 pEntry->zVal2 = zStat; in idxPopulateOneStat1()
13622 rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0); in idxBuildSampleTable()
13629 rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0); in idxBuildSampleTable()
13648 i64 iPrev = -100000; in idxPopulateStat1()
13663 if( p->iSample==0 ) return SQLITE_OK; in idxPopulateStat1()
13665 rc = idxLargestIndex(p->dbm, &nMax, pzErr); in idxPopulateStat1()
13668 rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0); in idxPopulateStat1()
13676 sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv); in idxPopulateStat1()
13682 rc = sqlite3_create_function(p->db, "sqlite_expert_sample", in idxPopulateStat1()
13688 pCtx->nSlot = nMax+1; in idxPopulateStat1()
13689 rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex); in idxPopulateStat1()
13692 rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo); in idxPopulateStat1()
13695 rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite); in idxPopulateStat1()
13703 if( p->iSample<100 && iPrev!=iRowid ){ in idxPopulateStat1()
13704 samplectx.target = (double)p->iSample / 100.0; in idxPopulateStat1()
13705 samplectx.iTarget = p->iSample; in idxPopulateStat1()
13714 if( rc==SQLITE_OK && p->iSample<100 ){ in idxPopulateStat1()
13715 rc = sqlite3_exec(p->dbv, in idxPopulateStat1()
13725 for(i=0; i<pCtx->nSlot; i++){ in idxPopulateStat1()
13726 sqlite3_free(pCtx->aSlot[i].z); in idxPopulateStat1()
13732 rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0); in idxPopulateStat1()
13735 sqlite3_create_function(p->db, "sqlite_expert_rem", 2, SQLITE_UTF8, 0,0,0,0); in idxPopulateStat1()
13736 sqlite3_create_function(p->db, "sqlite_expert_sample", 0,SQLITE_UTF8,0,0,0,0); in idxPopulateStat1()
13738 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0); in idxPopulateStat1()
13764 ** dummy functions for no-op implementation of UDFs during expert's work
13785 "WHERE builtin==0", -1, &pStmt, 0); in registerUDFs()
13794 /* no-op. Only happens on OOM */ in registerUDFs()
13833 /* Open two in-memory databases to work with. The "vtab database" (dbv) in sqlite3_expert_new()
13840 pNew->db = db; in sqlite3_expert_new()
13841 pNew->iSample = 100; in sqlite3_expert_new()
13842 rc = sqlite3_open(":memory:", &pNew->dbv); in sqlite3_expert_new()
13845 rc = sqlite3_open(":memory:", &pNew->dbm); in sqlite3_expert_new()
13847 sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0); in sqlite3_expert_new()
13852 if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbm,0,useDummyCS); in sqlite3_expert_new()
13853 if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbv,0,useDummyCS); in sqlite3_expert_new()
13859 rc = registerUDFs(pNew->db, pNew->dbm); in sqlite3_expert_new()
13862 rc = registerUDFs(pNew->db, pNew->dbv); in sqlite3_expert_new()
13869 rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg, in sqlite3_expert_new()
13875 if( zSql ) rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg); in sqlite3_expert_new()
13887 sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew); in sqlite3_expert_new()
13911 p->iSample = iVal; in sqlite3_expert_config()
13931 IdxScan *pScanOrig = p->pScan; in sqlite3_expert_sql()
13932 IdxStatement *pStmtOrig = p->pStatement; in sqlite3_expert_sql()
13936 if( p->bRun ) return SQLITE_MISUSE; in sqlite3_expert_sql()
13941 rc = idxPrepareStmt(p->db, &pStmt, pzErr, zStmt); in sqlite3_expert_sql()
13944 rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt); in sqlite3_expert_sql()
13952 pNew->zSql = (char*)&pNew[1]; in sqlite3_expert_sql()
13953 memcpy(pNew->zSql, z, n+1); in sqlite3_expert_sql()
13954 pNew->pNext = p->pStatement; in sqlite3_expert_sql()
13955 if( p->pStatement ) pNew->iId = p->pStatement->iId+1; in sqlite3_expert_sql()
13956 p->pStatement = pNew; in sqlite3_expert_sql()
13961 idxDatabaseError(p->dbv, pzErr); in sqlite3_expert_sql()
13966 idxScanFree(p->pScan, pScanOrig); in sqlite3_expert_sql()
13967 idxStatementFree(p->pStatement, pStmtOrig); in sqlite3_expert_sql()
13968 p->pScan = pScanOrig; in sqlite3_expert_sql()
13969 p->pStatement = pStmtOrig; in sqlite3_expert_sql()
13982 /* Create candidate indexes within the in-memory database file */ in sqlite3_expert_analyze()
13997 for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){ in sqlite3_expert_analyze()
13998 p->zCandidates = idxAppendText(&rc, p->zCandidates, in sqlite3_expert_analyze()
13999 "%s;%s%s\n", pEntry->zVal, in sqlite3_expert_analyze()
14000 pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2 in sqlite3_expert_analyze()
14011 p->bRun = 1; in sqlite3_expert_analyze()
14022 if( p->pStatement ) nRet = p->pStatement->iId+1; in sqlite3_expert_count()
14033 if( p->bRun==0 ) return 0; in sqlite3_expert_report()
14034 for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext); in sqlite3_expert_report()
14037 if( pStmt ) zRet = pStmt->zSql; in sqlite3_expert_report()
14040 if( pStmt ) zRet = pStmt->zIdx; in sqlite3_expert_report()
14043 if( pStmt ) zRet = pStmt->zEQP; in sqlite3_expert_report()
14046 zRet = p->zCandidates; in sqlite3_expert_report()
14057 sqlite3_close(p->dbm); in sqlite3_expert_destroy()
14058 sqlite3_close(p->dbv); in sqlite3_expert_destroy()
14059 idxScanFree(p->pScan, 0); in sqlite3_expert_destroy()
14060 idxStatementFree(p->pStatement, 0); in sqlite3_expert_destroy()
14061 idxTableFree(p->pTable); in sqlite3_expert_destroy()
14062 idxWriteFree(p->pWrite); in sqlite3_expert_destroy()
14063 idxHashClear(&p->hIdx); in sqlite3_expert_destroy()
14064 sqlite3_free(p->zCandidates); in sqlite3_expert_destroy()
14075 ** 2024-02-08
14088 ** Incremental Integrity-Check Extension
14089 ** -------------------------------------
14092 ** is well-formed or corrupt. This is the same task as performed by SQLite's
14093 ** built-in "PRAGMA integrity_check" command. This module differs from
14096 ** + It is less thorough - this module does not detect certain types
14103 ** + It allows integrity-check operations to be split into multiple
14104 ** transactions, so that the database does not need to be read-locked
14105 ** for the duration of the integrity-check.
14107 ** One way to use the API to run integrity-check on the "main" database
14126 ** integrity-check is complete. However, if sqlite3_intck_unlock() is
14141 ** An ongoing incremental integrity-check operation is represented by an
14147 ** Open a new incremental integrity-check object. If successful, populate
14152 ** The integrity-check will be conducted on database zDb (which must be "main",
14155 ** database handle db until the integrity-check object has been destroyed
14167 ** integrity-check handle after it has been passed to this function are
14173 ** Do the next step of the integrity-check operation specified by the handle
14175 ** integrity-check operation is finished, or an SQLite error code if
14176 ** an error occurs, or SQLITE_OK if no error occurs but the integrity-check
14181 ** SQLITE_OK), sqlite3_intck_message() returns a non-NULL value if
14185 ** returned, then the integrity-check handle is placed in an error state.
14196 ** containing a nul-terminated string describing the corruption in
14204 ** Close any read-transaction opened by an earlier call to
14209 ** If an error occurs, then the integrity-check handle is placed in an error
14221 ** may be set to point to a nul-terminated string containing an English
14232 ** This API is used for testing only. It returns the full-text of an SQL
14249 ** 2024-02-08
14276 ** the integrity-check operation is finished.
14306 ** Some error has occurred while using database p->db. Save the error message
14307 ** and error code currently held by the database handle in p->rc and p->zErr.
14310 p->rc = sqlite3_errcode(p->db); in intckSaveErrmsg()
14311 sqlite3_free(p->zErr); in intckSaveErrmsg()
14312 p->zErr = sqlite3_mprintf("%s", sqlite3_errmsg(p->db)); in intckSaveErrmsg()
14317 ** then this function is a no-op (returns NULL immediately). Otherwise, if an
14325 if( p->rc==SQLITE_OK ){ in intckPrepare()
14326 p->rc = sqlite3_prepare_v2(p->db, zSql, -1, &pRet, 0); in intckPrepare()
14327 if( p->rc!=SQLITE_OK ){ in intckPrepare()
14337 ** then this function is a no-op (returns NULL immediately). Otherwise, if an
14351 if( p->rc==SQLITE_OK && zSql==0 ){ in intckPrepareFmt()
14352 p->rc = SQLITE_NOMEM; in intckPrepareFmt()
14367 if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){ in intckFinalize()
14377 if( p->rc ) return p->rc; in intckStep()
14402 if( p->rc==SQLITE_OK ){ in intckMprintf()
14404 p->rc = SQLITE_NOMEM; in intckMprintf()
14415 ** required to restart the current pCheck query as a nul-terminated string
14416 ** in p->zKey.
14425 assert( p->pCheck ); in intckSaveKey()
14426 assert( p->zKey==0 ); in intckSaveKey()
14432 p->zDb, p->zObj, p->zDb, p->zObj in intckSaveKey()
14434 if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXinfo) ){ in intckSaveKey()
14442 for(ii=0; ii<p->nKeyVal; ii++){ in intckSaveKey()
14450 assert( p->nKeyVal>1 ); in intckSaveKey()
14451 for(ii=p->nKeyVal; ii>0; ii--){ in intckSaveKey()
14452 int bLastIsDesc = zDir[ii-1]=='1'; in intckSaveKey()
14453 int bLastIsNull = sqlite3_column_type(p->pCheck, ii)==SQLITE_NULL; in intckSaveKey()
14454 const char *zLast = sqlite3_column_name(p->pCheck, ii); in intckSaveKey()
14471 for(jj=0; jj<ii-1; jj++){ in intckSaveKey()
14472 const char *zAlias = (const char*)sqlite3_column_name(p->pCheck,jj+1); in intckSaveKey()
14499 if( p->rc==SQLITE_OK ){ in intckSaveKey()
14500 for(ii=0; ii<p->nKeyVal; ii++){ in intckSaveKey()
14501 sqlite3_bind_value(pStmt, ii+1, sqlite3_column_value(p->pCheck, ii+1)); in intckSaveKey()
14504 p->zKey = intckMprintf(p,"%s",(const char*)sqlite3_column_text(pStmt, 0)); in intckSaveKey()
14515 ** set sqlite3_intck.zObj to point to a nul-terminated buffer containing
14520 char *zPrev = p->zObj; in intckFindObject()
14521 p->zObj = 0; in intckFindObject()
14523 assert( p->rc==SQLITE_OK ); in intckFindObject()
14524 assert( p->pCheck==0 ); in intckFindObject()
14536 , p->zDb, (p->zKey ? ">=" : ">") in intckFindObject()
14539 if( p->rc==SQLITE_OK ){ in intckFindObject()
14540 sqlite3_bind_text(pStmt, 1, zPrev, -1, SQLITE_TRANSIENT); in intckFindObject()
14542 p->zObj = intckMprintf(p,"%s",(const char*)sqlite3_column_text(pStmt, 0)); in intckFindObject()
14548 if( sqlite3_stricmp(p->zObj, zPrev) ){ in intckFindObject()
14549 sqlite3_free(p->zKey); in intckFindObject()
14550 p->zKey = 0; in intckFindObject()
14557 ** Return the size in bytes of the first token in nul-terminated buffer z.
14602 ** fragment does not include any trailing sort-order keywords - "ASC" or
14635 /* Check if this is the end of the current column - either a "," or ")" in intckParseCreateIndex()
14641 nRet = (iEnd - iStart); in intckParseCreateIndex()
14652 if( z[iOff]==')' ) nOpen--; in intckParseCreateIndex()
14680 nRet--; in intckParseCreateIndex()
14683 while( nRet>0 && intckIsSpace(zRet[nRet-1]) ) nRet--; in intckParseCreateIndex()
14691 ** User-defined SQL function wrapper for intckParseCreateIndex():
14735 p->zDb, zObj in intckIsIndex()
14737 if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ in intckIsIndex()
14745 ** Return a pointer to a nul-terminated buffer containing the SQL statement
14758 int *pnKeyVal /* OUT: Number of key-values for this scan */ in intckCheckObjectSql()
14837 " (SELECT sql FROM sqlite_schema WHERE name=idx_name), -1" in intckCheckObjectSql()
14928 , p->zDb, p->zDb, zObj, zObj in intckCheckObjectSql()
14977 /* This table contains a single row consisting of a single value - in intckCheckObjectSql()
15008 p->zDb, zObj, zPrev, zCommon in intckCheckObjectSql()
15012 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ in intckCheckObjectSql()
15025 ** Open a new integrity-check object.
15030 sqlite3_intck **ppOut /* OUT: New integrity-check handle */ in sqlite3_intck_open()
15042 pNew->db = db; in sqlite3_intck_open()
15043 pNew->zDb = (const char*)&pNew[1]; in sqlite3_intck_open()
15059 ** Free the integrity-check object.
15063 sqlite3_finalize(p->pCheck); in sqlite3_intck_close()
15065 p->db, "parse_create_index", 1, SQLITE_UTF8, 0, 0, 0, 0 in sqlite3_intck_close()
15067 sqlite3_free(p->zObj); in sqlite3_intck_close()
15068 sqlite3_free(p->zKey); in sqlite3_intck_close()
15069 sqlite3_free(p->zTestSql); in sqlite3_intck_close()
15070 sqlite3_free(p->zErr); in sqlite3_intck_close()
15071 sqlite3_free(p->zMessage); in sqlite3_intck_close()
15077 ** Step the integrity-check object.
15080 if( p->rc==SQLITE_OK ){ in sqlite3_intck_step()
15082 if( p->zMessage ){ in sqlite3_intck_step()
15083 sqlite3_free(p->zMessage); in sqlite3_intck_step()
15084 p->zMessage = 0; in sqlite3_intck_step()
15087 if( p->bCorruptSchema ){ in sqlite3_intck_step()
15088 p->rc = SQLITE_DONE; in sqlite3_intck_step()
15090 if( p->pCheck==0 ){ in sqlite3_intck_step()
15092 if( p->rc==SQLITE_OK ){ in sqlite3_intck_step()
15093 if( p->zObj ){ in sqlite3_intck_step()
15095 zSql = intckCheckObjectSql(p, p->zObj, p->zKey, &p->nKeyVal); in sqlite3_intck_step()
15096 p->pCheck = intckPrepare(p, zSql); in sqlite3_intck_step()
15098 sqlite3_free(p->zKey); in sqlite3_intck_step()
15099 p->zKey = 0; in sqlite3_intck_step()
15101 p->rc = SQLITE_DONE; in sqlite3_intck_step()
15103 }else if( p->rc==SQLITE_CORRUPT ){ in sqlite3_intck_step()
15104 p->rc = SQLITE_OK; in sqlite3_intck_step()
15105 p->zMessage = intckMprintf(p, "%s", in sqlite3_intck_step()
15108 p->bCorruptSchema = 1; in sqlite3_intck_step()
15112 if( p->pCheck ){ in sqlite3_intck_step()
15113 assert( p->rc==SQLITE_OK ); in sqlite3_intck_step()
15114 if( sqlite3_step(p->pCheck)==SQLITE_ROW ){ in sqlite3_intck_step()
15117 intckFinalize(p, p->pCheck); in sqlite3_intck_step()
15118 p->pCheck = 0; in sqlite3_intck_step()
15119 p->nKeyVal = 0; in sqlite3_intck_step()
15120 if( p->rc==SQLITE_CORRUPT ){ in sqlite3_intck_step()
15121 p->rc = SQLITE_OK; in sqlite3_intck_step()
15122 p->zMessage = intckMprintf(p, in sqlite3_intck_step()
15123 "corruption found while scanning database object %s", p->zObj in sqlite3_intck_step()
15130 return p->rc; in sqlite3_intck_step()
15138 assert( p->pCheck==0 || p->zMessage==0 ); in sqlite3_intck_message()
15139 if( p->zMessage ){ in sqlite3_intck_message()
15140 return p->zMessage; in sqlite3_intck_message()
15142 if( p->pCheck ){ in sqlite3_intck_message()
15143 return (const char*)sqlite3_column_text(p->pCheck, 0); in sqlite3_intck_message()
15152 if( pzErr ) *pzErr = p->zErr; in sqlite3_intck_error()
15153 return (p->rc==SQLITE_DONE ? SQLITE_OK : p->rc); in sqlite3_intck_error()
15157 ** Close any read transaction the integrity-check object is holding open
15161 if( p->rc==SQLITE_OK && p->pCheck ){ in sqlite3_intck_unlock()
15162 assert( p->zKey==0 && p->nKeyVal>0 ); in sqlite3_intck_unlock()
15164 intckFinalize(p, p->pCheck); in sqlite3_intck_unlock()
15165 p->pCheck = 0; in sqlite3_intck_unlock()
15167 return p->rc; in sqlite3_intck_unlock()
15175 sqlite3_free(p->zTestSql); in sqlite3_intck_test_sql()
15177 p->zTestSql = intckCheckObjectSql(p, zObj, 0, 0); in sqlite3_intck_test_sql()
15179 if( p->zObj ){ in sqlite3_intck_test_sql()
15180 p->zTestSql = intckCheckObjectSql(p, p->zObj, p->zKey, 0); in sqlite3_intck_test_sql()
15182 sqlite3_free(p->zTestSql); in sqlite3_intck_test_sql()
15183 p->zTestSql = 0; in sqlite3_intck_test_sql()
15186 return p->zTestSql; in sqlite3_intck_test_sql()
15199 ** 2022-08-27
15210 ** This file contains the public interface to the "recover" extension -
15230 ** error. If it returns some other non-SQLITE_OK value, then an error
15299 ** nul-terminated buffer containing the SQL statement formated as UTF-8 as
15304 ** If an out-of-memory error occurs, NULL may be returned instead of
15339 ** of a "lost-and-found" table in the output database, or NULL. If
15340 ** the argument is non-NULL and the database contains seemingly
15343 ** pages to add to the lost-and-found table.
15348 ** (argument is 1) and a lost-and-found table has been configured using
15368 ** module creates and populates non-UNIQUE indexes right at the end of the
15369 ** recovery operation - after all recoverable data has been inserted
15374 ** Or, if this option is set (argument is 1), then non-UNIQUE indexes
15398 ** all further such calls on the same recover handle are no-ops that return
15399 ** the same non-SQLITE_OK value.
15417 ** the error. If no error message is available, or if an out-of memory
15452 ** 2019-04-17
15468 ** sqlite_dbdata is used to extract data directly from a database b-tree
15469 ** page and its associated overflow pages, bypassing the b-tree layer.
15481 ** FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
15485 ** a b-tree page, or if it is a b-tree page containing 0 entries, the
15488 ** each cell on the page. For intkey b-trees, the key value is stored in
15489 ** field -1.
15493 ** CREATE TABLE t1(a, b); -- root page is page 2
15501 ** (2, 0, -1, 5 ),
15504 ** (2, 1, -1, 10 ),
15521 ** It contains one entry for each b-tree pointer between a parent and
15617 if( nMin>pBuf->nBuf ){ in dbdataBufferSize()
15619 u8 *aNew = (u8*)sqlite3_realloc64(pBuf->aBuf, nNew); in dbdataBufferSize()
15622 pBuf->aBuf = aNew; in dbdataBufferSize()
15623 pBuf->nBuf = nNew; in dbdataBufferSize()
15632 sqlite3_free(pBuf->aBuf); in dbdataBufferFree()
15660 pTab->db = db; in dbdataConnect()
15661 pTab->bPtr = (pAux!=0); in dbdataConnect()
15675 sqlite3_finalize(pTab->pStmt); in dbdataDisconnect()
15697 int iSchema = -1; in dbdataBestIndex()
15698 int iPgno = -1; in dbdataBestIndex()
15699 int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA); in dbdataBestIndex()
15701 for(i=0; i<pIdx->nConstraint; i++){ in dbdataBestIndex()
15702 struct sqlite3_index_constraint *p = &pIdx->aConstraint[i]; in dbdataBestIndex()
15703 if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ in dbdataBestIndex()
15704 if( p->iColumn==colSchema ){ in dbdataBestIndex()
15705 if( p->usable==0 ) return SQLITE_CONSTRAINT; in dbdataBestIndex()
15708 if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){ in dbdataBestIndex()
15715 pIdx->aConstraintUsage[iSchema].argvIndex = 1; in dbdataBestIndex()
15716 pIdx->aConstraintUsage[iSchema].omit = 1; in dbdataBestIndex()
15719 pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0); in dbdataBestIndex()
15720 pIdx->aConstraintUsage[iPgno].omit = 1; in dbdataBestIndex()
15721 pIdx->estimatedCost = 100; in dbdataBestIndex()
15722 pIdx->estimatedRows = 50; in dbdataBestIndex()
15724 if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){ in dbdataBestIndex()
15725 int iCol = pIdx->aOrderBy[0].iColumn; in dbdataBestIndex()
15726 if( pIdx->nOrderBy==1 ){ in dbdataBestIndex()
15727 pIdx->orderByConsumed = (iCol==0 || iCol==1); in dbdataBestIndex()
15728 }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){ in dbdataBestIndex()
15729 pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1); in dbdataBestIndex()
15734 pIdx->estimatedCost = 100000000; in dbdataBestIndex()
15735 pIdx->estimatedRows = 1000000000; in dbdataBestIndex()
15737 pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00); in dbdataBestIndex()
15752 pCsr->base.pVtab = pVTab; in dbdataOpen()
15764 DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab); in dbdataResetCursor()
15765 if( pTab->pStmt==0 ){ in dbdataResetCursor()
15766 pTab->pStmt = pCsr->pStmt; in dbdataResetCursor()
15768 sqlite3_finalize(pCsr->pStmt); in dbdataResetCursor()
15770 pCsr->pStmt = 0; in dbdataResetCursor()
15771 pCsr->iPgno = 1; in dbdataResetCursor()
15772 pCsr->iCell = 0; in dbdataResetCursor()
15773 pCsr->iField = 0; in dbdataResetCursor()
15774 pCsr->bOnePage = 0; in dbdataResetCursor()
15775 sqlite3_free(pCsr->aPage); in dbdataResetCursor()
15776 dbdataBufferFree(&pCsr->rec); in dbdataResetCursor()
15777 pCsr->aPage = 0; in dbdataResetCursor()
15778 pCsr->nRec = 0; in dbdataResetCursor()
15792 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
15822 sqlite3_stmt *pStmt = pCsr->pStmt; in dbdataLoadPage()
15903 return ((eType-12) / 2); in dbdataValueBytes()
15959 int n = ((eType-12) / 2); in dbdataValue()
15994 ** a page-size, it returns the maximum number of cells that may be present
15996 #define DBDATA_MX_CELL(pgsz) ((pgsz-8)/6)
15999 ** the "hard-limit", according to comments in sqliteLimit.h. */
16007 DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; in dbdataNext()
16009 pCsr->iRowid++; in dbdataNext()
16012 int iOff = (pCsr->iPgno==1 ? 100 : 0); in dbdataNext()
16015 if( pCsr->aPage==0 ){ in dbdataNext()
16017 if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK; in dbdataNext()
16018 rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage); in dbdataNext()
16020 if( pCsr->aPage && pCsr->nPage>=256 ) break; in dbdataNext()
16021 sqlite3_free(pCsr->aPage); in dbdataNext()
16022 pCsr->aPage = 0; in dbdataNext()
16023 if( pCsr->bOnePage ) return SQLITE_OK; in dbdataNext()
16024 pCsr->iPgno++; in dbdataNext()
16027 assert( iOff+3+2<=pCsr->nPage ); in dbdataNext()
16028 pCsr->iCell = pTab->bPtr ? -2 : 0; in dbdataNext()
16029 pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]); in dbdataNext()
16030 if( pCsr->nCell>DBDATA_MX_CELL(pCsr->nPage) ){ in dbdataNext()
16031 pCsr->nCell = DBDATA_MX_CELL(pCsr->nPage); in dbdataNext()
16035 if( pTab->bPtr ){ in dbdataNext()
16036 if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){ in dbdataNext()
16037 pCsr->iCell = pCsr->nCell; in dbdataNext()
16039 pCsr->iCell++; in dbdataNext()
16040 if( pCsr->iCell>=pCsr->nCell ){ in dbdataNext()
16041 sqlite3_free(pCsr->aPage); in dbdataNext()
16042 pCsr->aPage = 0; in dbdataNext()
16043 if( pCsr->bOnePage ) return SQLITE_OK; in dbdataNext()
16044 pCsr->iPgno++; in dbdataNext()
16050 assert( pCsr->rec.aBuf!=0 || pCsr->nRec==0 ); in dbdataNext()
16051 if( pCsr->nRec==0 ){ in dbdataNext()
16060 switch( pCsr->aPage[iOff] ){ in dbdataNext()
16070 /* This is not a b-tree page with records on it. Continue. */ in dbdataNext()
16071 pCsr->iCell = pCsr->nCell; in dbdataNext()
16075 if( pCsr->iCell>=pCsr->nCell ){ in dbdataNext()
16078 int iCellPtr = iOff + 8 + nPointer + pCsr->iCell*2; in dbdataNext()
16080 if( iCellPtr>pCsr->nPage ){ in dbdataNext()
16083 iOff = get_uint16(&pCsr->aPage[iCellPtr]); in dbdataNext()
16086 /* For an interior node cell, skip past the child-page number */ in dbdataNext()
16090 if( bNextPage || iOff>pCsr->nPage || iOff<=iCellPtr ){ in dbdataNext()
16093 iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload); in dbdataNext()
16099 if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){ in dbdataNext()
16100 iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey); in dbdataNext()
16104 U = pCsr->nPage; in dbdataNext()
16106 X = U-35; in dbdataNext()
16108 X = ((U-12)*64/255)-23; in dbdataNext()
16114 M = ((U-12)*32/255)-23; in dbdataNext()
16115 K = M+((nPayload-M)%(U-4)); in dbdataNext()
16123 if( bNextPage || nLocal+iOff>pCsr->nPage ){ in dbdataNext()
16130 rc = dbdataBufferSize(&pCsr->rec, nPayload+DBDATA_PADDING_BYTES); in dbdataNext()
16135 memcpy(pCsr->rec.aBuf, &pCsr->aPage[iOff], nLocal); in dbdataNext()
16140 sqlite3_int64 nRem = nPayload - nLocal; in dbdataNext()
16141 u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]); in dbdataNext()
16147 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage ); in dbdataNext()
16151 nCopy = U-4; in dbdataNext()
16153 memcpy(&pCsr->rec.aBuf[nPayload-nRem], &aOvfl[4], nCopy); in dbdataNext()
16154 nRem -= nCopy; in dbdataNext()
16159 nPayload -= nRem; in dbdataNext()
16161 memset(&pCsr->rec.aBuf[nPayload], 0, DBDATA_PADDING_BYTES); in dbdataNext()
16162 pCsr->nRec = nPayload; in dbdataNext()
16164 iHdr = dbdataGetVarintU32(pCsr->rec.aBuf, &nHdr); in dbdataNext()
16166 pCsr->nHdr = nHdr; in dbdataNext()
16167 pCsr->pHdrPtr = &pCsr->rec.aBuf[iHdr]; in dbdataNext()
16168 pCsr->pPtr = &pCsr->rec.aBuf[pCsr->nHdr]; in dbdataNext()
16169 pCsr->iField = (bHasRowid ? -1 : 0); in dbdataNext()
16173 pCsr->iField++; in dbdataNext()
16174 if( pCsr->iField>0 ){ in dbdataNext()
16176 if( pCsr->pHdrPtr>=&pCsr->rec.aBuf[pCsr->nRec] in dbdataNext()
16177 || pCsr->iField>=DBDATA_MX_FIELD in dbdataNext()
16182 pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType); in dbdataNext()
16184 if( (pCsr->nRec - (pCsr->pPtr - pCsr->rec.aBuf))<szField ){ in dbdataNext()
16185 pCsr->pPtr = &pCsr->rec.aBuf[pCsr->nRec]; in dbdataNext()
16187 pCsr->pPtr += szField; in dbdataNext()
16194 sqlite3_free(pCsr->aPage); in dbdataNext()
16195 pCsr->aPage = 0; in dbdataNext()
16196 pCsr->nRec = 0; in dbdataNext()
16197 if( pCsr->bOnePage ) return SQLITE_OK; in dbdataNext()
16198 pCsr->iPgno++; in dbdataNext()
16200 if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->rec.aBuf[pCsr->nHdr] ){ in dbdataNext()
16206 pCsr->nRec = 0; in dbdataNext()
16207 pCsr->iCell++; in dbdataNext()
16221 return pCsr->aPage==0; in dbdataEof()
16225 ** Return true if nul-terminated string zSchema ends in "()". Or false
16230 if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){ in dbdataIsFunction()
16231 return (int)n-2; in dbdataIsFunction()
16239 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
16243 DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab; in dbdataDbsize()
16256 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0); in dbdataDbsize()
16259 pCsr->szDb = sqlite3_column_int(pStmt, 0); in dbdataDbsize()
16268 ** and inspecting the header field. If successful, set the pCsr->enc variable
16277 pCsr->enc = get_uint32(&aPg1[56]); in dbdataGetEncoding()
16293 DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; in dbdataFilter()
16300 assert( pCsr->iPgno==1 ); in dbdataFilter()
16306 pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]); in dbdataFilter()
16307 pCsr->bOnePage = 1; in dbdataFilter()
16314 if( pTab->pStmt ){ in dbdataFilter()
16315 pCsr->pStmt = pTab->pStmt; in dbdataFilter()
16316 pTab->pStmt = 0; in dbdataFilter()
16322 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0); in dbdataFilter()
16326 rc = sqlite3_prepare_v2(pTab->db, in dbdataFilter()
16327 "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1, in dbdataFilter()
16328 &pCsr->pStmt, 0 in dbdataFilter()
16333 rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT); in dbdataFilter()
16343 pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db)); in dbdataFilter()
16361 DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; in dbdataColumn()
16362 if( pTab->bPtr ){ in dbdataColumn()
16365 sqlite3_result_int64(ctx, pCsr->iPgno); in dbdataColumn()
16368 int iOff = pCsr->iPgno==1 ? 100 : 0; in dbdataColumn()
16369 if( pCsr->iCell<0 ){ in dbdataColumn()
16372 iOff += 12 + pCsr->iCell*2; in dbdataColumn()
16373 if( iOff>pCsr->nPage ) return SQLITE_OK; in dbdataColumn()
16374 iOff = get_uint16(&pCsr->aPage[iOff]); in dbdataColumn()
16376 if( iOff<=pCsr->nPage ){ in dbdataColumn()
16377 sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff])); in dbdataColumn()
16385 sqlite3_result_int64(ctx, pCsr->iPgno); in dbdataColumn()
16388 sqlite3_result_int(ctx, pCsr->iCell); in dbdataColumn()
16391 sqlite3_result_int(ctx, pCsr->iField); in dbdataColumn()
16394 if( pCsr->iField<0 ){ in dbdataColumn()
16395 sqlite3_result_int64(ctx, pCsr->iIntkey); in dbdataColumn()
16396 }else if( &pCsr->rec.aBuf[pCsr->nRec] >= pCsr->pPtr ){ in dbdataColumn()
16398 dbdataGetVarintU32(pCsr->pHdrPtr, &iType); in dbdataColumn()
16400 ctx, pCsr->enc, iType, pCsr->pPtr, in dbdataColumn()
16401 &pCsr->rec.aBuf[pCsr->nRec] - pCsr->pPtr in dbdataColumn()
16416 *pRowid = pCsr->iRowid; in dbdataRowid()
16432 dbdataOpen, /* xOpen - open a cursor */ in sqlite3DbdataRegister()
16433 dbdataClose, /* xClose - close a cursor */ in sqlite3DbdataRegister()
16434 dbdataFilter, /* xFilter - configure scan constraints */ in sqlite3DbdataRegister()
16435 dbdataNext, /* xNext - advance a cursor */ in sqlite3DbdataRegister()
16436 dbdataEof, /* xEof - check for end of scan */ in sqlite3DbdataRegister()
16437 dbdataColumn, /* xColumn - read data */ in sqlite3DbdataRegister()
16438 dbdataRowid, /* xRowid - read data */ in sqlite3DbdataRegister()
16474 ** 2022-08-27
16536 ** Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
16543 ** the output database, before any non-schema data are recovered. They
16544 ** are then stored in a singly-linked list linked by this variable beginning
16562 ** The index of the associated field within database records. Or -1 if
16615 u32 aElem[1]; /* Array of 32-bit bitmasks */
16674 char *zLostAndFound; /* Name of lost-and-found table (or NULL) */
16719 ** Populate the recovery.map table - used to figure out a "root" page
16724 ** Populate the lost-and-found table itself.
16760 ** recoverEnterMutex() - Enter the recovery mutex
16761 ** recoverLeaveMutex() - Leave the recovery mutex
16762 ** recoverAssertMutexHeld() - Assert that the recovery mutex is held
16793 ** This function is a no-op if the recover handle passed as the first
16794 ** argument already contains an error (if p->errCode!=SQLITE_OK).
16799 ** (p->errCode) set to SQLITE_NOMEM.
16804 if( p->errCode==SQLITE_OK ){ in recoverMalloc()
16809 p->errCode = SQLITE_NOMEM; in recoverMalloc()
16840 sqlite3_free(p->zErrMsg); in recoverError()
16841 p->zErrMsg = z; in recoverError()
16842 p->errCode = errCode; in recoverError()
16848 ** This function is a no-op if p->errCode is initially other than SQLITE_OK.
16861 pRet->nPg = nPg; in recoverBitmapAlloc()
16877 if( iPg<=pMap->nPg ){ in recoverBitmapSet()
16880 pMap->aElem[iElem] |= (((u32)1) << iBit); in recoverBitmapSet()
16890 if( iPg<=pMap->nPg && iPg>0 ){ in recoverBitmapQuery()
16893 ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0; in recoverBitmapQuery()
16908 ** This function is a no-op if recover handle p already contains an error
16909 ** (if p->errCode!=SQLITE_OK).
16922 if( p->errCode==SQLITE_OK ){ in recoverPrepare()
16923 if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){ in recoverPrepare()
16931 ** This function is a no-op if recover handle p already contains an error
16932 ** (if p->errCode!=SQLITE_OK).
16937 ** the statment handle returned. Or, if an error occurs - either during
16938 ** the printf() formatting or when preparing the resulting SQL - an
16947 if( p->errCode==SQLITE_OK ){ in recoverPreparePrintf()
16954 p->errCode = SQLITE_NOMEM; in recoverPreparePrintf()
16974 if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){ in recoverReset()
16989 if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){ in recoverFinalize()
16995 ** This function is a no-op if recover handle p already contains an error
16996 ** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this
17004 if( p->errCode==SQLITE_OK ){ in recoverExec()
17010 return p->errCode; in recoverExec()
17024 if( p->errCode==SQLITE_OK ){ in recoverBindValue()
17031 ** This function is a no-op if recover handle p already contains an error
17032 ** (if p->errCode!=SQLITE_OK). NULL is returned in this case.
17050 if( p->errCode==SQLITE_OK ){ in recoverMPrintf()
17051 if( z==0 ) p->errCode = SQLITE_NOMEM; in recoverMPrintf()
17060 ** This function is a no-op if recover handle p already contains an error
17061 ** (if p->errCode!=SQLITE_OK). Zero is returned in this case.
17070 if( p->errCode==SQLITE_OK ){ in recoverPageCount()
17072 pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb); in recoverPageCount()
17084 ** this function must be a blob. The second a non-negative integer. This
17085 ** function reads and returns a 32-bit big-endian integer from byte
17117 ** lost-and-found table, and it depends on those routines having populated
17120 ** The only argument to this function is a page-number. It returns true
17134 sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno)); in recoverPageIsUsed()
17138 ** The implementation of a user-defined SQL function invoked by the
17148 ** SELECT getpage(0); -- return number of pages in db
17149 ** SELECT getpage(4); -- return page 4 of db as a blob of data
17166 if( p->pGetPage==0 ){ in recoverGetPage()
17167 pStmt = p->pGetPage = recoverPreparePrintf( in recoverGetPage()
17168 p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb in recoverGetPage()
17170 }else if( p->errCode==SQLITE_OK ){ in recoverGetPage()
17171 pStmt = p->pGetPage; in recoverGetPage()
17179 assert( p->errCode==SQLITE_OK ); in recoverGetPage()
17182 if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){ in recoverGetPage()
17183 aPg = p->pPage1Disk; in recoverGetPage()
17185 sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT); in recoverGetPage()
17191 if( p->errCode ){ in recoverGetPage()
17192 if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1); in recoverGetPage()
17193 sqlite3_result_error_code(pCtx, p->errCode); in recoverGetPage()
17220 ** this function is the output of built-in function quote(). If the first
17309 ** This function is a no-op if recover handle p already contains an error
17310 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
17322 return recoverExec(p, p->dbOut, in recoverCacheSchema()
17343 ** this function is a no-op. Otherwise, issue a callback with SQL statement
17346 ** If the callback returns non-zero, set the recover handle error code to
17350 if( p->errCode==SQLITE_OK && p->xSql ){ in recoverSqlCallback()
17351 int res = p->xSql(p->pSqlCtx, zSql); in recoverSqlCallback()
17353 recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res); in recoverSqlCallback()
17362 ** + page-size,
17363 ** + auto-vacuum settings,
17365 ** + user-version (PRAGMA user_version), and
17366 ** + application-id (PRAGMA application_id), and
17381 if( p->errCode==SQLITE_OK ){ in recoverTransferSettings()
17392 p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag); in recoverTransferSettings()
17393 if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){ in recoverTransferSettings()
17407 if( p->errCode==SQLITE_OK ){ in recoverTransferSettings()
17408 sqlite3 *db = p->dbOut; in recoverTransferSettings()
17411 sqlite3_backup_step(pBackup, -1); in recoverTransferSettings()
17412 p->errCode = sqlite3_backup_finish(pBackup); in recoverTransferSettings()
17423 ** This function is a no-op if recover handle p already contains an error
17424 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
17452 assert( p->dbOut==0 ); in recoverOpenOutput()
17454 if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){ in recoverOpenOutput()
17459 ** These two are registered with the output database handle - this in recoverOpenOutput()
17462 if( p->errCode==SQLITE_OK ){ in recoverOpenOutput()
17463 p->errCode = sqlite3_dbdata_init(db, 0, 0); in recoverOpenOutput()
17466 /* Register the custom user-functions with the output handle. */ in recoverOpenOutput()
17468 p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0])); in recoverOpenOutput()
17470 p->errCode = sqlite3_create_function(db, aFunc[ii].zName, in recoverOpenOutput()
17475 p->dbOut = db; in recoverOpenOutput()
17476 return p->errCode; in recoverOpenOutput()
17485 char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb); in recoverOpenRecovery()
17486 recoverExec(p, p->dbOut, zSql); in recoverOpenRecovery()
17487 recoverExec(p, p->dbOut, in recoverOpenRecovery()
17497 ** This function is a no-op if recover handle p already contains an error
17498 ** (if p->errCode!=SQLITE_OK).
17514 sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut, in recoverAddTable()
17519 int iPk = -1; in recoverAddTable()
17537 pNew->aCol = (RecoverColumn*)&pNew[1]; in recoverAddTable()
17538 pNew->zTab = csr = (char*)&pNew->aCol[nCol]; in recoverAddTable()
17539 pNew->nCol = nCol; in recoverAddTable()
17540 pNew->iRoot = iRoot; in recoverAddTable()
17551 if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i; in recoverAddTable()
17552 if( iPKF>1 ) iPk = -2; in recoverAddTable()
17553 pNew->aCol[i].zCol = csr; in recoverAddTable()
17554 pNew->aCol[i].eHidden = eHidden; in recoverAddTable()
17556 pNew->aCol[i].iField = -1; in recoverAddTable()
17558 pNew->aCol[i].iField = iField++; in recoverAddTable()
17563 pNew->aCol[i].iBind = iBind++; in recoverAddTable()
17569 pNew->pNext = p->pTblList; in recoverAddTable()
17570 p->pTblList = pNew; in recoverAddTable()
17571 pNew->bIntkey = 1; in recoverAddTable()
17576 pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName); in recoverAddTable()
17581 assert( iCol<pNew->nCol ); in recoverAddTable()
17582 pNew->aCol[iCol].iField = iField; in recoverAddTable()
17584 pNew->bIntkey = 0; in recoverAddTable()
17585 iPk = -2; in recoverAddTable()
17589 if( p->errCode==SQLITE_OK ){ in recoverAddTable()
17591 pNew->aCol[iPk].bIPK = 1; in recoverAddTable()
17592 }else if( pNew->bIntkey ){ in recoverAddTable()
17593 pNew->iRowidBind = iBind++; in recoverAddTable()
17622 pSelect = recoverPrepare(p, p->dbOut, in recoverWriteSchema1()
17636 pTblname = recoverPrepare(p, p->dbOut, in recoverWriteSchema1()
17642 sqlite3_bind_int(pSelect, 1, p->bSlowIndexes); in recoverWriteSchema1()
17658 rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0); in recoverWriteSchema1()
17669 recoverDbError(p, p->dbOut); in recoverWriteSchema1()
17677 return p->errCode; in recoverWriteSchema1()
17683 ** database by recoverWriteSchema1() - everything except for tables and
17688 ** * non-UNIQUE indexes.
17696 pSelect = recoverPrepare(p, p->dbOut, in recoverWriteSchema2()
17697 p->bSlowIndexes ? in recoverWriteSchema2()
17708 int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0); in recoverWriteSchema2()
17712 recoverDbError(p, p->dbOut); in recoverWriteSchema2()
17718 return p->errCode; in recoverWriteSchema2()
17722 ** This function is a no-op if recover handle p already contains an error
17723 ** (if p->errCode!=SQLITE_OK). In this case it returns NULL.
17745 ** a single text value - itself an SQL statement similar to the above,
17768 int bSql = p->xSql ? 1 : 0; in recoverInsertStmt()
17772 assert( nField<=pTab->nCol ); in recoverInsertStmt()
17774 zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab); in recoverInsertStmt()
17776 if( pTab->iRowidBind ){ in recoverInsertStmt()
17777 assert( pTab->bIntkey ); in recoverInsertStmt()
17780 zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind); in recoverInsertStmt()
17782 zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind); in recoverInsertStmt()
17789 int eHidden = pTab->aCol[ii].eHidden; in recoverInsertStmt()
17793 assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 ); in recoverInsertStmt()
17794 zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol); in recoverInsertStmt()
17798 "%z%sescape_crnl(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind in recoverInsertStmt()
17802 zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind); in recoverInsertStmt()
17816 pRet = recoverPrepare(p, p->dbOut, zFinal); in recoverInsertStmt()
17826 ** Search the list of RecoverTable objects at p->pTblList for one that
17832 for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext); in recoverFindTable()
17853 pProbe = recoverPrepare(p, p->dbOut, in recoverLostAndFoundCreate()
17856 for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){ in recoverLostAndFoundCreate()
17859 zTbl = recoverMPrintf(p, "%s", p->zLostAndFound); in recoverLostAndFoundCreate()
17861 zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii); in recoverLostAndFoundCreate()
17864 if( p->errCode==SQLITE_OK ){ in recoverLostAndFoundCreate()
17865 sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC); in recoverLostAndFoundCreate()
17886 for(ii=0; p->errCode==SQLITE_OK && ii<nField; ii++){ in recoverLostAndFoundCreate()
17894 recoverExec(p, p->dbOut, zSql); in recoverLostAndFoundCreate()
17897 }else if( p->errCode==SQLITE_OK ){ in recoverLostAndFoundCreate()
17899 p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound in recoverLostAndFoundCreate()
17921 if( p->xSql==0 ){ in recoverLostAndFoundInsert()
17926 p, p->dbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind in recoverLostAndFoundInsert()
17935 p, p->dbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind in recoverLostAndFoundInsert()
17945 ** lost-and-found table of the output database. This function attempts
17957 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFoundFindRoot()
17959 if( pLaf->pFindRoot==0 ){ in recoverLostAndFoundFindRoot()
17960 pLaf->pFindRoot = recoverPrepare(p, p->dbOut, in recoverLostAndFoundFindRoot()
17970 if( p->errCode==SQLITE_OK ){ in recoverLostAndFoundFindRoot()
17971 sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg); in recoverLostAndFoundFindRoot()
17972 if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){ in recoverLostAndFoundFindRoot()
17973 *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0); in recoverLostAndFoundFindRoot()
17977 recoverReset(p, pLaf->pFindRoot); in recoverLostAndFoundFindRoot()
17979 return p->errCode; in recoverLostAndFoundFindRoot()
17984 ** the lost-and-found table in the output database.
17987 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFoundOnePage()
17988 sqlite3_value **apVal = pLaf->apVal; in recoverLostAndFoundOnePage()
17989 sqlite3_stmt *pPageData = pLaf->pPageData; in recoverLostAndFoundOnePage()
17990 sqlite3_stmt *pInsert = pLaf->pInsert; in recoverLostAndFoundOnePage()
17992 int nVal = -1; in recoverLostAndFoundOnePage()
18001 while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){ in recoverLostAndFoundOnePage()
18028 nVal = -1; in recoverLostAndFoundOnePage()
18034 assert( nVal==-1 ); in recoverLostAndFoundOnePage()
18038 }else if( iField<pLaf->nMaxField ){ in recoverLostAndFoundOnePage()
18041 assert( iField==nVal || (nVal==-1 && iField==0) ); in recoverLostAndFoundOnePage()
18061 ** RECOVER_STATE_LOSTANDFOUND3 state - during which the lost-and-found
18066 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound3Step()
18067 if( p->errCode==SQLITE_OK ){ in recoverLostAndFound3Step()
18068 if( pLaf->pInsert==0 ){ in recoverLostAndFound3Step()
18071 if( p->errCode==SQLITE_OK ){ in recoverLostAndFound3Step()
18072 int res = sqlite3_step(pLaf->pAllPage); in recoverLostAndFound3Step()
18074 i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0); in recoverLostAndFound3Step()
18075 if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){ in recoverLostAndFound3Step()
18079 recoverReset(p, pLaf->pAllPage); in recoverLostAndFound3Step()
18090 ** state - during which the lost-and-found table of the output database
18095 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound3Init()
18097 if( pLaf->nMaxField>0 ){ in recoverLostAndFound3Init()
18100 zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField); in recoverLostAndFound3Init()
18101 pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField); in recoverLostAndFound3Init()
18104 pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut, in recoverLostAndFound3Init()
18108 "SELECT ii FROM seq" , p->laf.nPg in recoverLostAndFound3Init()
18110 pLaf->pPageData = recoverPrepare(p, p->dbOut, in recoverLostAndFound3Init()
18114 "SELECT -1, -1, -1" in recoverLostAndFound3Init()
18117 pLaf->apVal = (sqlite3_value**)recoverMalloc(p, in recoverLostAndFound3Init()
18118 pLaf->nMaxField*sizeof(sqlite3_value*) in recoverLostAndFound3Init()
18124 ** Initialize resources required in RECOVER_STATE_WRITING state - during which
18129 RecoverStateW1 *p1 = &p->w1; in recoverWriteDataInit()
18134 assert( p1->nMax==0 ); in recoverWriteDataInit()
18135 for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){ in recoverWriteDataInit()
18136 if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol; in recoverWriteDataInit()
18141 nByte = sizeof(sqlite3_value*) * (p1->nMax+1); in recoverWriteDataInit()
18142 p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte); in recoverWriteDataInit()
18143 if( p1->apVal==0 ) return p->errCode; in recoverWriteDataInit()
18147 p1->pTbls = recoverPrepare(p, p->dbOut, in recoverWriteDataInit()
18152 p1->pSel = recoverPrepare(p, p->dbOut, in recoverWriteDataInit()
18165 return p->errCode; in recoverWriteDataInit()
18173 RecoverStateW1 *p1 = &p->w1; in recoverWriteDataCleanup()
18175 for(ii=0; ii<p1->nVal; ii++){ in recoverWriteDataCleanup()
18176 sqlite3_value_free(p1->apVal[ii]); in recoverWriteDataCleanup()
18178 sqlite3_free(p1->apVal); in recoverWriteDataCleanup()
18179 recoverFinalize(p, p1->pInsert); in recoverWriteDataCleanup()
18180 recoverFinalize(p, p1->pTbls); in recoverWriteDataCleanup()
18181 recoverFinalize(p, p1->pSel); in recoverWriteDataCleanup()
18188 ** RECOVER_STATE_WRITING state - during which tables recovered from the
18192 RecoverStateW1 *p1 = &p->w1; in recoverWriteDataStep()
18193 sqlite3_stmt *pSel = p1->pSel; in recoverWriteDataStep()
18194 sqlite3_value **apVal = p1->apVal; in recoverWriteDataStep()
18196 if( p->errCode==SQLITE_OK && p1->pTab==0 ){ in recoverWriteDataStep()
18197 if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){ in recoverWriteDataStep()
18198 i64 iRoot = sqlite3_column_int64(p1->pTbls, 0); in recoverWriteDataStep()
18199 p1->pTab = recoverFindTable(p, iRoot); in recoverWriteDataStep()
18201 recoverFinalize(p, p1->pInsert); in recoverWriteDataStep()
18202 p1->pInsert = 0; in recoverWriteDataStep()
18206 if( p1->pTab==0 ) return p->errCode; in recoverWriteDataStep()
18210 ** keys before recovering its contents. The p1->pTbls SELECT statement in recoverWriteDataStep()
18213 if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){ in recoverWriteDataStep()
18214 recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence"); in recoverWriteDataStep()
18219 ** SELECT statement p1->pSel. The SELECT statement will then iterate in recoverWriteDataStep()
18223 p1->nVal = 0; in recoverWriteDataStep()
18224 p1->bHaveRowid = 0; in recoverWriteDataStep()
18225 p1->iPrevPage = -1; in recoverWriteDataStep()
18226 p1->iPrevCell = -1; in recoverWriteDataStep()
18231 assert( p->errCode!=SQLITE_OK || p1->pTab ); in recoverWriteDataStep()
18233 if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){ in recoverWriteDataStep()
18234 RecoverTable *pTab = p1->pTab; in recoverWriteDataStep()
18240 int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell); in recoverWriteDataStep()
18242 assert( bNewCell==0 || (iField==-1 || iField==0) ); in recoverWriteDataStep()
18243 assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol ); in recoverWriteDataStep()
18247 if( p1->nVal>=0 ){ in recoverWriteDataStep()
18248 if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){ in recoverWriteDataStep()
18249 recoverFinalize(p, p1->pInsert); in recoverWriteDataStep()
18250 p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal); in recoverWriteDataStep()
18251 p1->nInsert = p1->nVal; in recoverWriteDataStep()
18253 if( p1->nVal>0 ){ in recoverWriteDataStep()
18254 sqlite3_stmt *pInsert = p1->pInsert; in recoverWriteDataStep()
18255 for(ii=0; ii<pTab->nCol; ii++){ in recoverWriteDataStep()
18256 RecoverColumn *pCol = &pTab->aCol[ii]; in recoverWriteDataStep()
18257 int iBind = pCol->iBind; in recoverWriteDataStep()
18259 if( pCol->bIPK ){ in recoverWriteDataStep()
18260 sqlite3_bind_int64(pInsert, iBind, p1->iRowid); in recoverWriteDataStep()
18261 }else if( pCol->iField<p1->nVal ){ in recoverWriteDataStep()
18262 recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]); in recoverWriteDataStep()
18266 if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){ in recoverWriteDataStep()
18267 sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid); in recoverWriteDataStep()
18274 assert( p->errCode || pInsert ); in recoverWriteDataStep()
18279 for(ii=0; ii<p1->nVal; ii++){ in recoverWriteDataStep()
18283 p1->nVal = -1; in recoverWriteDataStep()
18284 p1->bHaveRowid = 0; in recoverWriteDataStep()
18289 p1->iRowid = sqlite3_column_int64(pSel, 3); in recoverWriteDataStep()
18290 assert( p1->nVal==-1 ); in recoverWriteDataStep()
18291 p1->nVal = 0; in recoverWriteDataStep()
18292 p1->bHaveRowid = 1; in recoverWriteDataStep()
18293 }else if( iField<pTab->nCol ){ in recoverWriteDataStep()
18299 p1->nVal = iField+1; in recoverWriteDataStep()
18301 p1->iPrevCell = iCell; in recoverWriteDataStep()
18302 p1->iPrevPage = iPage; in recoverWriteDataStep()
18306 p1->pTab = 0; in recoverWriteDataStep()
18309 return p->errCode; in recoverWriteDataStep()
18314 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
18318 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound1Init()
18321 assert( p->laf.pUsed==0 ); in recoverLostAndFound1Init()
18322 pLaf->nPg = recoverPageCount(p); in recoverLostAndFound1Init()
18323 pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg); in recoverLostAndFound1Init()
18327 ** if !p->bFreelistCorrupt, add all pages that appear to be part of the in recoverLostAndFound1Init()
18330 p, p->dbOut, in recoverLostAndFound1Init()
18340 " SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata" in recoverLostAndFound1Init()
18342 " SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0" in recoverLostAndFound1Init()
18359 if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt); in recoverLostAndFound1Init()
18360 pLaf->pUsedPages = pStmt; in recoverLostAndFound1Init()
18366 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
18370 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound1Step()
18371 int rc = p->errCode; in recoverLostAndFound1Step()
18373 rc = sqlite3_step(pLaf->pUsedPages); in recoverLostAndFound1Step()
18375 i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0); in recoverLostAndFound1Step()
18376 recoverBitmapSet(pLaf->pUsed, iPg); in recoverLostAndFound1Step()
18379 recoverFinalize(p, pLaf->pUsedPages); in recoverLostAndFound1Step()
18380 pLaf->pUsedPages = 0; in recoverLostAndFound1Step()
18388 ** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1
18392 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound2Init()
18394 assert( p->laf.pAllAndParent==0 ); in recoverLostAndFound2Init()
18395 assert( p->laf.pMapInsert==0 ); in recoverLostAndFound2Init()
18396 assert( p->laf.pMaxField==0 ); in recoverLostAndFound2Init()
18397 assert( p->laf.nMaxField==0 ); in recoverLostAndFound2Init()
18399 pLaf->pMapInsert = recoverPrepare(p, p->dbOut, in recoverLostAndFound2Init()
18402 pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut, in recoverLostAndFound2Init()
18408 "SELECT NULL, ii FROM seq", p->laf.nPg in recoverLostAndFound2Init()
18410 pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut, in recoverLostAndFound2Init()
18418 ** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified
18423 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound2Step()
18424 if( p->errCode==SQLITE_OK ){ in recoverLostAndFound2Step()
18425 int res = sqlite3_step(pLaf->pAllAndParent); in recoverLostAndFound2Step()
18427 i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1); in recoverLostAndFound2Step()
18428 if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){ in recoverLostAndFound2Step()
18429 sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild); in recoverLostAndFound2Step()
18430 sqlite3_bind_value(pLaf->pMapInsert, 2, in recoverLostAndFound2Step()
18431 sqlite3_column_value(pLaf->pAllAndParent, 0) in recoverLostAndFound2Step()
18433 sqlite3_step(pLaf->pMapInsert); in recoverLostAndFound2Step()
18434 recoverReset(p, pLaf->pMapInsert); in recoverLostAndFound2Step()
18435 sqlite3_bind_int64(pLaf->pMaxField, 1, iChild); in recoverLostAndFound2Step()
18436 if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){ in recoverLostAndFound2Step()
18437 int nMax = sqlite3_column_int(pLaf->pMaxField, 0); in recoverLostAndFound2Step()
18438 if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax; in recoverLostAndFound2Step()
18440 recoverReset(p, pLaf->pMaxField); in recoverLostAndFound2Step()
18443 recoverFinalize(p, pLaf->pAllAndParent); in recoverLostAndFound2Step()
18444 pLaf->pAllAndParent =0; in recoverLostAndFound2Step()
18448 return p->errCode; in recoverLostAndFound2Step()
18456 recoverBitmapFree(p->laf.pUsed); in recoverLostAndFoundCleanup()
18457 p->laf.pUsed = 0; in recoverLostAndFoundCleanup()
18458 sqlite3_finalize(p->laf.pUsedPages); in recoverLostAndFoundCleanup()
18459 sqlite3_finalize(p->laf.pAllAndParent); in recoverLostAndFoundCleanup()
18460 sqlite3_finalize(p->laf.pMapInsert); in recoverLostAndFoundCleanup()
18461 sqlite3_finalize(p->laf.pMaxField); in recoverLostAndFoundCleanup()
18462 sqlite3_finalize(p->laf.pFindRoot); in recoverLostAndFoundCleanup()
18463 sqlite3_finalize(p->laf.pInsert); in recoverLostAndFoundCleanup()
18464 sqlite3_finalize(p->laf.pAllPage); in recoverLostAndFoundCleanup()
18465 sqlite3_finalize(p->laf.pPageData); in recoverLostAndFoundCleanup()
18466 p->laf.pUsedPages = 0; in recoverLostAndFoundCleanup()
18467 p->laf.pAllAndParent = 0; in recoverLostAndFoundCleanup()
18468 p->laf.pMapInsert = 0; in recoverLostAndFoundCleanup()
18469 p->laf.pMaxField = 0; in recoverLostAndFoundCleanup()
18470 p->laf.pFindRoot = 0; in recoverLostAndFoundCleanup()
18471 p->laf.pInsert = 0; in recoverLostAndFoundCleanup()
18472 p->laf.pAllPage = 0; in recoverLostAndFoundCleanup()
18473 p->laf.pPageData = 0; in recoverLostAndFoundCleanup()
18474 sqlite3_free(p->laf.apVal); in recoverLostAndFoundCleanup()
18475 p->laf.apVal = 0; in recoverLostAndFoundCleanup()
18488 for(pTab=p->pTblList; pTab; pTab=pNext){ in recoverFinalCleanup()
18489 pNext = pTab->pNext; in recoverFinalCleanup()
18492 p->pTblList = 0; in recoverFinalCleanup()
18493 sqlite3_finalize(p->pGetPage); in recoverFinalCleanup()
18494 p->pGetPage = 0; in recoverFinalCleanup()
18495 sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0); in recoverFinalCleanup()
18501 sqlite3_close(p->dbOut); in recoverFinalCleanup()
18504 p->dbOut = 0; in recoverFinalCleanup()
18508 ** Decode and return an unsigned 16-bit big-endian integer value from
18516 ** Decode and return an unsigned 32-bit big-endian integer value from
18541 ** or a prefix thereof appears to contain a well-formed SQLite b-tree page,
18542 ** return the page-size in bytes. Otherwise, if the buffer does not
18543 ** appear to contain a well-formed b-tree page, return 0.
18570 /* Follow the free-list. This is the same format for all b-tree pages. */ in recoverIsValidPage()
18575 if( iFree>(n-4) ) return 0; in recoverIsValidPage()
18606 int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23); in recoverIsValidPage()
18607 int M = ((n-12)*32/255)-23; in recoverIsValidPage()
18608 int K = M+((nPayload-M)%(n-4)); in recoverIsValidPage()
18680 assert( pFd->pMethods!=&recover_methods ); in recoverVfsClose()
18681 return pFd->pMethods->xClose(pFd); in recoverVfsClose()
18685 ** Write value v to buffer a[] as a 16-bit big-endian unsigned integer.
18693 ** Write value v to buffer a[] as a 32-bit big-endian unsigned integer.
18703 ** Detect the page-size of the database opened by file-handle pFd by
18704 ** searching the first part of the file for a well-formed SQLite b-tree
18705 ** page. If parameter nReserve is non-zero, then as well as searching for
18706 ** a b-tree page with zero reserved bytes, this function searches for one
18709 ** If successful, set variable p->detected_pgsz to the detected page-size
18711 ** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or,
18712 ** if an error occurs (e.g. an IO or OOM error), then an SQLite error code
18713 ** is returned. The final value of p->detected_pgsz is undefined in this
18718 sqlite3_file *pFd, /* File-handle open on input database */ in recoverVfsDetectPagesize()
18736 nBlk = (nSz+nMax-1)/nMax; in recoverVfsDetectPagesize()
18743 rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax); in recoverVfsDetectPagesize()
18749 if( recoverIsValidPage(aTmp, &aPg[iOff], pgsz2-nReserve) ){ in recoverVfsDetectPagesize()
18757 if( pgsz>(u32)p->detected_pgsz ){ in recoverVfsDetectPagesize()
18758 p->detected_pgsz = pgsz; in recoverVfsDetectPagesize()
18759 p->nReserve = nReserve; in recoverVfsDetectPagesize()
18765 p->detected_pgsz = pgsz; in recoverVfsDetectPagesize()
18776 if( pFd->pMethods==&recover_methods ){ in recoverVfsRead()
18777 pFd->pMethods = recover_g.pMethods; in recoverVfsRead()
18778 rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff); in recoverVfsRead()
18786 ** + Database page size (16-bits at offset 16) in recoverVfsRead()
18787 ** + Size of db in pages (32-bits at offset 28) in recoverVfsRead()
18788 ** + Database encoding (32-bits at offset 56) in recoverVfsRead()
18792 ** + first freelist page (32-bits at offset 32) in recoverVfsRead()
18793 ** + size of freelist (32-bits at offset 36) in recoverVfsRead()
18794 ** + the wal-mode flags (16-bits at offset 18) in recoverVfsRead()
18796 ** We also try to preserve the auto-vacuum, incr-value, user-version in recoverVfsRead()
18797 ** and application-id fields - all 32 bit quantities at offsets in recoverVfsRead()
18800 ** Byte offset 105 should also contain the page-size as a 16-bit in recoverVfsRead()
18832 rc = pFd->pMethods->xFileSize(pFd, &dbFileSize); in recoverVfsRead()
18834 if( rc==SQLITE_OK && p->detected_pgsz==0 ){ in recoverVfsRead()
18837 if( p->detected_pgsz ){ in recoverVfsRead()
18838 pgsz = p->detected_pgsz; in recoverVfsRead()
18839 nReserve = p->nReserve; in recoverVfsRead()
18849 sqlite3_free(p->pPage1Cache); in recoverVfsRead()
18850 p->pPage1Cache = 0; in recoverVfsRead()
18851 p->pPage1Disk = 0; in recoverVfsRead()
18853 p->pgsz = nByte; in recoverVfsRead()
18854 p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2); in recoverVfsRead()
18855 if( p->pPage1Cache ){ in recoverVfsRead()
18856 p->pPage1Disk = &p->pPage1Cache[nByte]; in recoverVfsRead()
18857 memcpy(p->pPage1Disk, aBuf, nByte); in recoverVfsRead()
18862 recoverPutU16(&aHdr[105], pgsz-nReserve); in recoverVfsRead()
18870 memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr)); in recoverVfsRead()
18872 memcpy(p->pPage1Cache, aBuf, nByte); in recoverVfsRead()
18874 rc = p->errCode; in recoverVfsRead()
18878 pFd->pMethods = &recover_methods; in recoverVfsRead()
18880 rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff); in recoverVfsRead()
18890 if( pFd->pMethods==&recover_methods ){ \
18891 pFd->pMethods = recover_g.pMethods; \
18893 pFd->pMethods = &recover_methods; \
18909 pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff) in recoverVfsWrite()
18914 pFd->pMethods->xTruncate(pFd, size) in recoverVfsTruncate()
18919 pFd->pMethods->xSync(pFd, flags) in recoverVfsSync()
18924 pFd->pMethods->xFileSize(pFd, pSize) in recoverVfsFileSize()
18929 pFd->pMethods->xLock(pFd, eLock) in recoverVfsLock()
18934 pFd->pMethods->xUnlock(pFd, eLock) in recoverVfsUnlock()
18939 pFd->pMethods->xCheckReservedLock(pFd, pResOut) in recoverVfsCheckReservedLock()
18944 (pFd->pMethods ? pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND) in recoverVfsFileControl()
18949 pFd->pMethods->xSectorSize(pFd) in recoverVfsSectorSize()
18954 pFd->pMethods->xDeviceCharacteristics(pFd) in recoverVfsDeviceCharacteristics()
18961 pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp) in recoverVfsShmMap()
18966 pFd->pMethods->xShmLock(pFd, offset, n, flags) in recoverVfsShmLock()
18970 if( pFd->pMethods==&recover_methods ){ in recoverVfsShmBarrier()
18971 pFd->pMethods = recover_g.pMethods; in recoverVfsShmBarrier()
18972 pFd->pMethods->xShmBarrier(pFd); in recoverVfsShmBarrier()
18973 pFd->pMethods = &recover_methods; in recoverVfsShmBarrier()
18975 pFd->pMethods->xShmBarrier(pFd); in recoverVfsShmBarrier()
18980 pFd->pMethods->xShmUnmap(pFd, deleteFlag) in recoverVfsShmUnmap()
19004 ** Install the VFS wrapper around the file-descriptor open on the input
19012 sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd); in recoverInstallWrapper()
19013 assert( pFd==0 || pFd->pMethods!=&recover_methods ); in recoverInstallWrapper()
19014 if( pFd && pFd->pMethods ){ in recoverInstallWrapper()
19015 int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0); in recoverInstallWrapper()
19016 recover_g.pMethods = pFd->pMethods; in recoverInstallWrapper()
19019 pFd->pMethods = &recover_methods; in recoverInstallWrapper()
19024 ** Uninstall the VFS wrapper that was installed around the file-descriptor open
19031 sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd); in recoverUninstallWrapper()
19032 if( pFd && pFd->pMethods ){ in recoverUninstallWrapper()
19033 pFd->pMethods = recover_g.pMethods; in recoverUninstallWrapper()
19045 assert( p && p->errCode==SQLITE_OK ); in recoverStep()
19046 switch( p->eState ){ in recoverStep()
19061 sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0); in recoverStep()
19062 recoverExec(p, p->dbIn, "PRAGMA writable_schema = on"); in recoverStep()
19063 recoverExec(p, p->dbIn, "BEGIN"); in recoverStep()
19064 if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1; in recoverStep()
19065 recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema"); in recoverStep()
19073 recoverExec(p, p->dbOut, "BEGIN"); in recoverStep()
19076 p->eState = RECOVER_STATE_WRITING; in recoverStep()
19080 if( p->w1.pTbls==0 ){ in recoverStep()
19085 if( p->zLostAndFound ){ in recoverStep()
19086 p->eState = RECOVER_STATE_LOSTANDFOUND1; in recoverStep()
19088 p->eState = RECOVER_STATE_SCHEMA2; in recoverStep()
19095 if( p->laf.pUsed==0 ){ in recoverStep()
19099 p->eState = RECOVER_STATE_LOSTANDFOUND2; in recoverStep()
19104 if( p->laf.pAllAndParent==0 ){ in recoverStep()
19108 p->eState = RECOVER_STATE_LOSTANDFOUND3; in recoverStep()
19114 if( p->laf.pInsert==0 ){ in recoverStep()
19118 p->eState = RECOVER_STATE_SCHEMA2; in recoverStep()
19127 p->eState = RECOVER_STATE_DONE; in recoverStep()
19132 recoverExec(p, p->dbOut, "COMMIT"); in recoverStep()
19133 rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0); in recoverStep()
19134 if( p->errCode==SQLITE_OK ) p->errCode = rc; in recoverStep()
19138 p->eState = RECOVER_STATE_DONE; in recoverStep()
19144 /* no-op */ in recoverStep()
19183 pRet->dbIn = db; in recoverInit()
19184 pRet->zDb = (char*)&pRet[1]; in recoverInit()
19185 pRet->zUri = &pRet->zDb[nDb+1]; in recoverInit()
19186 memcpy(pRet->zDb, zDb, nDb); in recoverInit()
19187 if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri); in recoverInit()
19188 pRet->xSql = xSql; in recoverInit()
19189 pRet->pSqlCtx = pSqlCtx; in recoverInit()
19190 pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT; in recoverInit()
19225 return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory"; in sqlite3_recover_errmsg()
19232 return p ? p->errCode : SQLITE_NOMEM; in sqlite3_recover_errcode()
19242 }else if( p->eState!=RECOVER_STATE_INIT ){ in sqlite3_recover_config()
19248 ** name of the auxiliary database that is ATTACH-ed to the database in sqlite3_recover_config()
19252 sqlite3_free(p->zStateDb); in sqlite3_recover_config()
19253 p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg); in sqlite3_recover_config()
19258 sqlite3_free(p->zLostAndFound); in sqlite3_recover_config()
19260 p->zLostAndFound = recoverMPrintf(p, "%s", zArg); in sqlite3_recover_config()
19262 p->zLostAndFound = 0; in sqlite3_recover_config()
19268 p->bFreelistCorrupt = *(int*)pArg; in sqlite3_recover_config()
19272 p->bRecoverRowid = *(int*)pArg; in sqlite3_recover_config()
19276 p->bSlowIndexes = *(int*)pArg; in sqlite3_recover_config()
19296 if( p->errCode==SQLITE_OK ) recoverStep(p); in sqlite3_recover_step()
19297 if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){ in sqlite3_recover_step()
19300 return p->errCode; in sqlite3_recover_step()
19328 if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){ in sqlite3_recover_finish()
19329 rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0); in sqlite3_recover_finish()
19330 if( p->errCode==SQLITE_OK ) p->errCode = rc; in sqlite3_recover_finish()
19332 rc = p->errCode; in sqlite3_recover_finish()
19333 sqlite3_free(p->zErrMsg); in sqlite3_recover_finish()
19334 sqlite3_free(p->zStateDb); in sqlite3_recover_finish()
19335 sqlite3_free(p->zLostAndFound); in sqlite3_recover_finish()
19336 sqlite3_free(p->pPage1Cache); in sqlite3_recover_finish()
19409 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
19413 u8 bSafeModePersist; /* The long-term value of bSafeMode */
19439 sqlite3_int64 szMax; /* --maxsize argument to .open */
19468 char *zNonce; /* Nonce for temporary safe-mode escapes */
19494 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
19498 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
19512 ** top-level SQL statement */
19513 #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
19518 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
19520 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
19522 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
19524 #define SHFLG_Echo 0x00000040 /* .echo on/off, or --echo setting */
19533 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
19534 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
19535 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
19547 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
19551 #define MODE_Pretty 11 /* Pretty-print schemas */
19555 #define MODE_Table 15 /* MySQL-style table formatting */
19556 #define MODE_Box 16 /* Unicode box-drawing characters */
19607 if( p->pLog==0 ) return; in shellLog()
19608 sputf(p->pLog, "(%d) %s\n", iErrCode, zMsg); in shellLog()
19609 fflush(p->pLog); in shellLog()
19638 if( p->bSafeMode ){ in failIfSafeMode()
19644 eputf("line %d: %s\n", p->lineno, zMsg); in failIfSafeMode()
19663 ** Also throw an error if the EDITOR program returns a non-zero exit code.
19689 sqlite3_result_error(context, "no editor for edit()", -1); in editFunc()
19693 sqlite3_result_error(context, "NULL input to edit()", -1); in editFunc()
19713 sqlite3_result_error(context, "edit() cannot open temp file", -1); in editFunc()
19728 sqlite3_result_error(context, "edit() could not write the whole file", -1); in editFunc()
19739 sqlite3_result_error(context, "EDITOR returned non-zero", -1); in editFunc()
19745 "edit() cannot reopen temp file after edit", -1); in editFunc()
19760 sqlite3_result_error(context, "could not read back the whole file", -1); in editFunc()
19797 p->modePrior = p->mode; in outputModePush()
19798 p->priorShFlgs = p->shellFlgs; in outputModePush()
19799 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator)); in outputModePush()
19800 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator)); in outputModePush()
19803 p->mode = p->modePrior; in outputModePop()
19804 p->shellFlgs = p->priorShFlgs; in outputModePop()
19805 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator)); in outputModePop()
19806 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator)); in outputModePop()
19810 ** Output the given string as a hex-encoded blob (eg. X'1234' )
19900 ** get corrupted by end-of-line translation facilities in some operating
19973 ** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
19982 ns = pcFirst - s; in anyOfInStr()
19995 static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */ in output_c_string()
20003 if( pcEnd > z ) oputb(z, (int)(pcEnd-z)); in output_c_string()
20046 const char *pcDQBS = anyOfInStr(z, zDQBS, pcLimit-z); in output_json_string()
20047 const char *pcPast = zSkipValidUtf8(z, (int)(pcLimit-z), ctrlMask); in output_json_string()
20050 oputb(z, (int)(pcEnd-z)); in output_json_string()
20138 ** Output a single term of CSV. Actually, p->colSeparator is used for
20139 ** the separator, which may or may not be a comma. p->nullValue is
20145 oputf("%s",p->nullValue); in output_csv()
20154 if( i==0 || strstr(z, p->colSeparator)!=0 ){ in output_csv()
20164 oputz(p->colSeparator); in output_csv()
20169 ** This routine runs when the user presses Ctrl-C
20179 ** This routine runs for console events (e.g. Ctrl-C) on Win32
20282 if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4); in shellAuth()
20293 ** If the schema statement in z[] contains a start-of-comment and if
20301 if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){ in printSchemaLine()
20310 zNew[n-1] = 0; in printSchemaLine()
20341 if( z[i]=='-' && z[i+1]=='-' ) return 1; in wsToEol()
20355 if( p->autoEQPtest ){ in eqp_append()
20360 pNew->iEqpId = iEqpId; in eqp_append()
20361 pNew->iParentId = p2; in eqp_append()
20362 memcpy(pNew->zText, zText, nText+1); in eqp_append()
20363 pNew->pNext = 0; in eqp_append()
20364 if( p->sGraph.pLast ){ in eqp_append()
20365 p->sGraph.pLast->pNext = pNew; in eqp_append()
20367 p->sGraph.pRow = pNew; in eqp_append()
20369 p->sGraph.pLast = pNew; in eqp_append()
20374 ** in p->sGraph.
20378 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){ in eqp_reset()
20379 pNext = pRow->pNext; in eqp_reset()
20382 memset(&p->sGraph, 0, sizeof(p->sGraph)); in eqp_reset()
20389 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow; in eqp_next_row()
20390 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext; in eqp_next_row()
20399 i64 n = strlen(p->sGraph.zPrefix); in eqp_render_level()
20403 z = pRow->zText; in eqp_render_level()
20404 oputf("%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z); in eqp_render_level()
20405 if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){ in eqp_render_level()
20406 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4); in eqp_render_level()
20407 eqp_render_level(p, pRow->iEqpId); in eqp_render_level()
20408 p->sGraph.zPrefix[n] = 0; in eqp_render_level()
20417 EQPGraphRow *pRow = p->sGraph.pRow; in eqp_render()
20419 if( pRow->zText[0]=='-' ){ in eqp_render()
20420 if( pRow->pNext==0 ){ in eqp_render()
20424 oputf("%s\n", pRow->zText+3); in eqp_render()
20425 p->sGraph.pRow = pRow->pNext; in eqp_render()
20432 p->sGraph.zPrefix[0] = 0; in eqp_render()
20444 p->nProgress++; in progress_handler()
20445 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){ in progress_handler()
20446 oputf("Progress limit reached (%u)\n", p->nProgress); in progress_handler()
20447 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; in progress_handler()
20448 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0; in progress_handler()
20451 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){ in progress_handler()
20452 oputf("Progress %u\n", p->nProgress); in progress_handler()
20462 const char zDash[] = "--------------------------------------------------"; in print_dashes()
20463 const int nDash = sizeof(zDash) - 1; in print_dashes()
20466 N -= nDash; in print_dashes()
20472 ** Print a markdown or table-style row separator using ascii-art
20482 print_dashes(p->actualWidth[0]+2); in print_row_separator()
20485 print_dashes(p->actualWidth[i]+2); in print_row_separator()
20507 switch( p->cMode ){ in shell_callback()
20519 if( p->cnt++>0 ) oputz(p->rowSeparator); in shell_callback()
20522 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator); in shell_callback()
20538 if( p->cMode==MODE_ScanExp ){ in shell_callback()
20547 if( p->cnt++==0 ){ in shell_callback()
20550 oputz(i==nArg-1 ? "\n" : " "); in shell_callback()
20554 oputz(i==nArg-1 ? "\n" : " "); in shell_callback()
20565 if( i==nArg-1 ) w = 0; in shell_callback()
20570 if( i==iIndent && p->aiIndent && p->pStmt ){ in shell_callback()
20571 if( p->iIndent<p->nIndent ){ in shell_callback()
20572 oputf("%*.s", p->aiIndent[p->iIndent], ""); in shell_callback()
20574 p->iIndent++; in shell_callback()
20576 utf8_width_print(w, zVal ? zVal : p->nullValue); in shell_callback()
20577 oputz(i==nArg-1 ? "\n" : zSep); in shell_callback()
20585 case MODE_Pretty: { /* .schema and .fullschema with --indent */ in shell_callback()
20606 if( z[j-1]=='\r' ) z[j-1] = '\n'; in shell_callback()
20607 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue; in shell_callback()
20608 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){ in shell_callback()
20609 j--; in shell_callback()
20613 while( j>0 && IsSpace(z[j-1]) ){ j--; } in shell_callback()
20623 }else if( c=='-' && z[i+1]=='-' ){ in shell_callback()
20628 nParen--; in shell_callback()
20638 if( c=='\n' ) j--; in shell_callback()
20652 if( p->cnt++==0 && p->showHeader ){ in shell_callback()
20654 oputf("%s%s",azCol[i], i==nArg-1 ? p->rowSeparator : p->colSeparator); in shell_callback()
20660 if( z==0 ) z = p->nullValue; in shell_callback()
20662 oputz((i<nArg-1)? p->colSeparator : p->rowSeparator); in shell_callback()
20667 if( p->cnt++==0 && p->showHeader ){ in shell_callback()
20680 output_html_string(azArg[i] ? azArg[i] : p->nullValue); in shell_callback()
20687 if( p->cnt++==0 && p->showHeader ){ in shell_callback()
20690 if(i<nArg-1) oputz(p->colSeparator); in shell_callback()
20692 oputz(p->rowSeparator); in shell_callback()
20696 output_c_string(azArg[i] ? azArg[i] : p->nullValue); in shell_callback()
20697 if(i<nArg-1) oputz(p->colSeparator); in shell_callback()
20699 oputz(p->rowSeparator); in shell_callback()
20703 setBinaryMode(p->out, 1); in shell_callback()
20704 if( p->cnt++==0 && p->showHeader ){ in shell_callback()
20706 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1); in shell_callback()
20708 oputz(p->rowSeparator); in shell_callback()
20712 output_csv(p, azArg[i], i<nArg-1); in shell_callback()
20714 oputz(p->rowSeparator); in shell_callback()
20716 setTextMode(p->out, 1); in shell_callback()
20721 oputf("INSERT INTO %s",p->zDestTable); in shell_callback()
20722 if( p->showHeader ){ in shell_callback()
20737 p->cnt++; in shell_callback()
20752 double r = sqlite3_column_double(p->pStmt, i); in shell_callback()
20758 oputz("-9.0e+999"); in shell_callback()
20768 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ in shell_callback()
20769 const void *pBlob = sqlite3_column_blob(p->pStmt, i); in shell_callback()
20770 int nBlob = sqlite3_column_bytes(p->pStmt, i); in shell_callback()
20785 if( p->cnt==0 ){ in shell_callback()
20786 fputs("[{", p->out); in shell_callback()
20788 fputs(",\n{", p->out); in shell_callback()
20790 p->cnt++; in shell_callback()
20792 output_json_string(azCol[i], -1); in shell_callback()
20798 double r = sqlite3_column_double(p->pStmt, i); in shell_callback()
20804 oputz("-9.0e+999"); in shell_callback()
20809 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ in shell_callback()
20810 const void *pBlob = sqlite3_column_blob(p->pStmt, i); in shell_callback()
20811 int nBlob = sqlite3_column_bytes(p->pStmt, i); in shell_callback()
20814 output_json_string(azArg[i], -1); in shell_callback()
20818 if( i<nArg-1 ){ in shell_callback()
20827 if( p->cnt==0 && p->showHeader ){ in shell_callback()
20829 if( i>0 ) fputs(p->colSeparator, p->out); in shell_callback()
20832 fputs(p->rowSeparator, p->out); in shell_callback()
20834 p->cnt++; in shell_callback()
20836 if( i>0 ) fputs(p->colSeparator, p->out); in shell_callback()
20845 double r = sqlite3_column_double(p->pStmt, i); in shell_callback()
20848 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ in shell_callback()
20849 const void *pBlob = sqlite3_column_blob(p->pStmt, i); in shell_callback()
20850 int nBlob = sqlite3_column_bytes(p->pStmt, i); in shell_callback()
20858 fputs(p->rowSeparator, p->out); in shell_callback()
20862 if( p->cnt++==0 && p->showHeader ){ in shell_callback()
20864 if( i>0 ) oputz(p->colSeparator); in shell_callback()
20867 oputz(p->rowSeparator); in shell_callback()
20871 if( i>0 ) oputz(p->colSeparator); in shell_callback()
20872 oputz(azArg[i] ? azArg[i] : p->nullValue); in shell_callback()
20874 oputz(p->rowSeparator); in shell_callback()
20903 if( p->n ) appendText(p, "|", 0); in captureOutputCallback()
20916 sqlite3_exec(p->db, in createSelftestTable()
20927 " 'memo','Tests generated by --init');\n" in createSelftestTable()
20956 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0); in createSelftestTable()
20970 if( p->zDestTable ){ in set_table_name()
20971 free(p->zDestTable); in set_table_name()
20972 p->zDestTable = 0; in set_table_name()
20978 z = p->zDestTable = malloc( n+1 ); in set_table_name()
21013 iOffset--; in shell_error_context()
21015 while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; } in shell_error_context()
21020 while( len>0 && (zSql[len]&0xc0)==0x80 ) len--; in shell_error_context()
21026 zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode,iOffset,""); in shell_error_context()
21028 zMsg = sqlite3_mprintf("\n %z\n %*serror here ---^", zCode,iOffset-14,""); in shell_error_context()
21036 ** the result columns, comma-separated, on a line and then add a
21039 ** If the number of columns is 1 and that column contains text "--"
21041 ** "--" comment occurs at the end of the statement, the comment
21053 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); in run_table_dump_query()
21055 char *zContext = shell_error_context(zSelect, p->db); in run_table_dump_query()
21057 rc, sqlite3_errmsg(p->db), zContext); in run_table_dump_query()
21059 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; in run_table_dump_query()
21071 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; in run_table_dump_query()
21081 oputf("/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); in run_table_dump_query()
21082 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; in run_table_dump_query()
21115 ** Attempt to display I/O stats on Linux using /proc/PID/io
21120 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid()); in displayLinuxIoStats()
21140 oputf("%-36s %s", aTrans[i].zDesc, &z[n]); in displayLinuxIoStats()
21150 ** Display a single line of status using 64-bit values.
21158 sqlite3_int64 iCur = -1; in displayStatLine()
21159 sqlite3_int64 iHiwtr = -1; in displayStatLine()
21171 oputf("%-36s %s\n", zLabel, zLine); in displayStatLine()
21184 if( pArg==0 || pArg->out==0 ) return 0; in display_stats()
21186 if( pArg->pStmt && pArg->statsOn==2 ){ in display_stats()
21188 sqlite3_stmt *pStmt = pArg->pStmt; in display_stats()
21191 oputf("%-36s %d\n", "Number of output columns:", nCol); in display_stats()
21194 oputf("%-36s %s\n", z, sqlite3_column_name(pStmt,i)); in display_stats()
21197 oputf("%-36s %s\n", z, sqlite3_column_decltype(pStmt, i)); in display_stats()
21201 oputf("%-36s %s\n", z, sqlite3_column_database_name(pStmt,i)); in display_stats()
21203 oputf("%-36s %s\n", z, sqlite3_column_table_name(pStmt,i)); in display_stats()
21205 oputf("%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i)); in display_stats()
21210 if( pArg->statsOn==3 ){ in display_stats()
21211 if( pArg->pStmt ){ in display_stats()
21212 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset); in display_stats()
21213 oputf("VM-steps: %d\n", iCur); in display_stats()
21222 if( pArg->shellFlgs & SHFLG_Pagecache ){ in display_stats()
21238 if( pArg->shellFlgs & SHFLG_Lookaside ){ in display_stats()
21239 iHiwtr = iCur = -1; in display_stats()
21253 iHiwtr = iCur = -1; in display_stats()
21256 iHiwtr = iCur = -1; in display_stats()
21259 iHiwtr = iCur = -1; in display_stats()
21262 iHiwtr = iCur = -1; in display_stats()
21265 iHiwtr = iCur = -1; in display_stats()
21268 iHiwtr = iCur = -1; in display_stats()
21271 iHiwtr = iCur = -1; in display_stats()
21276 if( pArg->pStmt ){ in display_stats()
21278 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, in display_stats()
21281 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); in display_stats()
21283 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); in display_stats()
21285 iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, in display_stats()
21287 iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, in display_stats()
21292 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); in display_stats()
21294 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset); in display_stats()
21296 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset); in display_stats()
21298 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset); in display_stats()
21306 /* Do not remove this machine readable comment: extra-stats-output-here */ in display_stats()
21346 sqlite3_stmt *p = pArg->pStmt; in display_explain_scanstats()
21363 sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal); in display_explain_scanstats()
21401 if( zName && pArg->scanstatsOn>1 ){ in display_explain_scanstats()
21407 "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z in display_explain_scanstats()
21421 ** Parameter azArray points to a zero-terminated array of strings. zStr
21422 ** points to a single nul-terminated string. Return non-zero if zStr
21446 ** See tag-20220407a in wherecode.c and vdbe.c.
21457 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ in explain_data_prepare()
21458 int iOp; /* Index of operation in p->aiIndent[] */ in explain_data_prepare()
21485 ** different if the current instruction is part of a sub-program generated in explain_data_prepare()
21487 int p2op = (p2 + (iOp-iAddr)); in explain_data_prepare()
21489 /* Grow the p->aiIndent array as required */ in explain_data_prepare()
21492 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int)); in explain_data_prepare()
21493 shell_check_oom(p->aiIndent); in explain_data_prepare()
21499 p->aiIndent[iOp] = 0; in explain_data_prepare()
21500 p->nIndent = iOp+1; in explain_data_prepare()
21502 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; in explain_data_prepare()
21505 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; in explain_data_prepare()
21509 p->iIndent = 0; in explain_data_prepare()
21518 sqlite3_free(p->aiIndent); in explain_data_delete()
21519 p->aiIndent = 0; in explain_data_delete()
21520 p->nIndent = 0; in explain_data_delete()
21521 p->iIndent = 0; in explain_data_delete()
21537 if( pArg->scanstatsOn==3 ){ in display_scanstats()
21545 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); in display_scanstats()
21547 sqlite3_stmt *pSave = pArg->pStmt; in display_scanstats()
21548 pArg->pStmt = pStmt; in display_scanstats()
21549 sqlite3_bind_pointer(pStmt, 1, pSave, "stmt-pointer", 0); in display_scanstats()
21551 pArg->cnt = 0; in display_scanstats()
21552 pArg->cMode = MODE_ScanExp; in display_scanstats()
21558 pArg->pStmt = pSave; in display_scanstats()
21587 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode); in bind_table_init()
21588 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0); in bind_table_init()
21589 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema); in bind_table_init()
21590 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0); in bind_table_init()
21591 sqlite3_exec(p->db, in bind_table_init()
21597 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0); in bind_table_init()
21598 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0); in bind_table_init()
21621 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters", in bind_prepared_stmt()
21626 rc = sqlite3_prepare_v2(pArg->db, in bind_prepared_stmt()
21628 " WHERE key=?1", -1, &pQ, 0); in bind_prepared_stmt()
21637 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC); in bind_prepared_stmt()
21657 ** UTF8 box-drawing characters. Imagine box lines like this:
21661 ** 4 --+-- 2
21669 #define BOX_24 "\342\224\200" /* U+2500 --- */
21671 #define BOX_23 "\342\224\214" /* U+250c ,- */
21672 #define BOX_34 "\342\224\220" /* U+2510 -, */
21673 #define BOX_12 "\342\224\224" /* U+2514 '- */
21674 #define BOX_14 "\342\224\230" /* U+2518 -' */
21675 #define BOX_123 "\342\224\234" /* U+251c |- */
21676 #define BOX_134 "\342\224\244" /* U+2524 -| */
21677 #define BOX_234 "\342\224\254" /* U+252c -,- */
21678 #define BOX_124 "\342\224\264" /* U+2534 -'- */
21679 #define BOX_1234 "\342\224\274" /* U+253c -|- */
21688 const int nDash = sizeof(zDash) - 1; in print_box_line()
21692 N -= nDash; in print_box_line()
21710 print_box_line(p->actualWidth[0]+2); in print_box_row_separator()
21713 print_box_line(p->actualWidth[i]+2); in print_box_row_separator()
21735 u8 bWordWrap /* If true, avoid breaking mid-word */ in translateForDisplayAndDup()
21747 if( mxWidth<0 ) mxWidth = -mxWidth; in translateForDisplayAndDup()
21768 for(k=i; k>i/2; k--){ in translateForDisplayAndDup()
21769 if( isspace(z[k-1]) ) break; in translateForDisplayAndDup()
21772 for(k=i; k>i/2; k--){ in translateForDisplayAndDup()
21773 if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break; in translateForDisplayAndDup()
21817 /* Extract the value of the i-th current column for pStmt as an SQL literal
21851 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
21879 int bw = p->cmOpts.bWordWrap; in exec_prepared_stmt_columnar()
21881 const char *zShowNull = p->nullValue; in exec_prepared_stmt_columnar()
21894 if( p->cmOpts.bQuote ){ in exec_prepared_stmt_columnar()
21901 if( nColumn>p->nWidth ){ in exec_prepared_stmt_columnar()
21902 p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int)); in exec_prepared_stmt_columnar()
21903 shell_check_oom(p->colWidth); in exec_prepared_stmt_columnar()
21904 for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0; in exec_prepared_stmt_columnar()
21905 p->nWidth = nColumn; in exec_prepared_stmt_columnar()
21906 p->actualWidth = &p->colWidth[nColumn]; in exec_prepared_stmt_columnar()
21908 memset(p->actualWidth, 0, nColumn*sizeof(int)); in exec_prepared_stmt_columnar()
21910 w = p->colWidth[i]; in exec_prepared_stmt_columnar()
21911 if( w<0 ) w = -w; in exec_prepared_stmt_columnar()
21912 p->actualWidth[i] = w; in exec_prepared_stmt_columnar()
21916 int wx = p->colWidth[i]; in exec_prepared_stmt_columnar()
21918 wx = p->cmOpts.iWrap; in exec_prepared_stmt_columnar()
21920 if( wx<0 ) wx = -wx; in exec_prepared_stmt_columnar()
21938 int wx = p->colWidth[i]; in exec_prepared_stmt_columnar()
21940 wx = p->cmOpts.iWrap; in exec_prepared_stmt_columnar()
21942 if( wx<0 ) wx = -wx; in exec_prepared_stmt_columnar()
21946 }else if( p->cmOpts.bQuote ){ in exec_prepared_stmt_columnar()
21958 abRowDiv[nRow-1] = 0; in exec_prepared_stmt_columnar()
21969 if( n>p->actualWidth[j] ) p->actualWidth[j] = n; in exec_prepared_stmt_columnar()
21972 switch( p->cMode ){ in exec_prepared_stmt_columnar()
21976 if( p->showHeader ){ in exec_prepared_stmt_columnar()
21978 w = p->actualWidth[i]; in exec_prepared_stmt_columnar()
21979 if( p->colWidth[i]<0 ) w = -w; in exec_prepared_stmt_columnar()
21981 fputs(i==nColumn-1?"\n":" ", p->out); in exec_prepared_stmt_columnar()
21984 print_dashes(p->actualWidth[i]); in exec_prepared_stmt_columnar()
21985 fputs(i==nColumn-1?"\n":" ", p->out); in exec_prepared_stmt_columnar()
21994 fputs("| ", p->out); in exec_prepared_stmt_columnar()
21996 w = p->actualWidth[i]; in exec_prepared_stmt_columnar()
21998 oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, ""); in exec_prepared_stmt_columnar()
21999 oputz(i==nColumn-1?" |\n":" | "); in exec_prepared_stmt_columnar()
22007 fputs("| ", p->out); in exec_prepared_stmt_columnar()
22009 w = p->actualWidth[i]; in exec_prepared_stmt_columnar()
22011 oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, ""); in exec_prepared_stmt_columnar()
22012 oputz(i==nColumn-1?" |\n":" | "); in exec_prepared_stmt_columnar()
22023 w = p->actualWidth[i]; in exec_prepared_stmt_columnar()
22026 (w-n)/2, "", azData[i], (w-n+1)/2, "", in exec_prepared_stmt_columnar()
22027 i==nColumn-1?" "BOX_13"\n":" "BOX_13" "); in exec_prepared_stmt_columnar()
22034 if( j==0 && p->cMode!=MODE_Column ){ in exec_prepared_stmt_columnar()
22035 oputz(p->cMode==MODE_Box?BOX_13" ":"| "); in exec_prepared_stmt_columnar()
22038 if( z==0 ) z = p->nullValue; in exec_prepared_stmt_columnar()
22039 w = p->actualWidth[j]; in exec_prepared_stmt_columnar()
22040 if( p->colWidth[j]<0 ) w = -w; in exec_prepared_stmt_columnar()
22042 if( j==nColumn-1 ){ in exec_prepared_stmt_columnar()
22044 if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){ in exec_prepared_stmt_columnar()
22045 if( p->cMode==MODE_Table ){ in exec_prepared_stmt_columnar()
22047 }else if( p->cMode==MODE_Box ){ in exec_prepared_stmt_columnar()
22049 }else if( p->cMode==MODE_Column ){ in exec_prepared_stmt_columnar()
22053 j = -1; in exec_prepared_stmt_columnar()
22059 if( p->cMode==MODE_Table ){ in exec_prepared_stmt_columnar()
22061 }else if( p->cMode==MODE_Box ){ in exec_prepared_stmt_columnar()
22092 if( pArg->cMode==MODE_Column in exec_prepared_stmt()
22093 || pArg->cMode==MODE_Table in exec_prepared_stmt()
22094 || pArg->cMode==MODE_Box in exec_prepared_stmt()
22095 || pArg->cMode==MODE_Markdown in exec_prepared_stmt()
22129 && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote) in exec_prepared_stmt()
22152 if( pArg->cMode==MODE_Json ){ in exec_prepared_stmt()
22153 fputs("]\n", pArg->out); in exec_prepared_stmt()
22154 }else if( pArg->cMode==MODE_Count ){ in exec_prepared_stmt()
22180 assert( pState->expert.pExpert ); in expertHandleSQL()
22182 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr); in expertHandleSQL()
22201 sqlite3expert *p = pState->expert.pExpert; in expertFinish()
22205 int bVerbose = pState->expert.bVerbose; in expertFinish()
22214 oputz("-- Candidates -----------------------------\n"); in expertFinish()
22223 oputf("-- Query %d --------------------------------\n",i+1); in expertFinish()
22232 pState->expert.pExpert = 0; in expertFinish()
22249 assert( pState->expert.pExpert==0 ); in expertDotCommand()
22250 memset(&pState->expert, 0, sizeof(ExpertInfo)); in expertDotCommand()
22255 if( z[0]=='-' && z[1]=='-' ) z++; in expertDotCommand()
22257 if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){ in expertDotCommand()
22258 pState->expert.bVerbose = 1; in expertDotCommand()
22260 else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){ in expertDotCommand()
22261 if( i==(nArg-1) ){ in expertDotCommand()
22279 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr); in expertDotCommand()
22280 if( pState->expert.pExpert==0 ){ in expertDotCommand()
22285 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample in expertDotCommand()
22300 ** This is very similar to SQLite's built-in sqlite3_exec()
22313 sqlite3 *db = pArg->db; in shell_exec()
22320 if( pArg->expert.pExpert ){ in shell_exec()
22328 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); in shell_exec()
22335 /* this happens for a comment or white-space */ in shell_exec()
22346 pArg->pStmt = pStmt; in shell_exec()
22347 pArg->cnt = 0; in shell_exec()
22351 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){ in shell_exec()
22355 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP); in shell_exec()
22356 if( pArg->autoEQP>=AUTOEQP_trigger ){ in shell_exec()
22368 if( zEQPLine[0]=='-' ) eqp_render(pArg, 0); in shell_exec()
22373 if( pArg->autoEQP>=AUTOEQP_full ){ in shell_exec()
22378 pArg->cMode = MODE_Explain; in shell_exec()
22385 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){ in shell_exec()
22395 pArg->cMode = pArg->mode; in shell_exec()
22396 if( pArg->autoExplain ){ in shell_exec()
22398 pArg->cMode = MODE_Explain; in shell_exec()
22401 pArg->cMode = MODE_EQP; in shell_exec()
22407 if( pArg->cMode==MODE_Explain && bIsExplain ){ in shell_exec()
22418 if( pArg && pArg->statsOn ){ in shell_exec()
22422 /* print loop-counters if required */ in shell_exec()
22423 if( pArg && pArg->scanstatsOn ){ in shell_exec()
22441 pArg->pStmt = NULL; in shell_exec()
22487 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in tableColumnList()
22491 if( nCol>=nAlloc-2 ){ in tableColumnList()
22532 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in tableColumnList()
22556 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0); in tableColumnList()
22572 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0); in toggleSelectOrder()
22604 dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0; in dump_callback()
22605 noSys = (p->shellFlgs & SHFLG_DumpNoSys)!=0; in dump_callback()
22614 /* no-op */ in dump_callback()
22617 if( !p->writableSchema ){ in dump_callback()
22619 p->writableSchema = 1; in dump_callback()
22643 p->nErr++; in dump_callback()
22682 savedDestTable = p->zDestTable; in dump_callback()
22683 savedMode = p->mode; in dump_callback()
22684 p->zDestTable = sTable.z; in dump_callback()
22685 p->mode = p->cMode = MODE_Insert; in dump_callback()
22689 toggleSelectOrder(p->db); in dump_callback()
22691 toggleSelectOrder(p->db); in dump_callback()
22693 p->zDestTable = savedDestTable; in dump_callback()
22694 p->mode = savedMode; in dump_callback()
22697 if( rc ) p->nErr++; in dump_callback()
22715 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); in run_schema_dump_query()
22728 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); in run_schema_dump_query()
22754 " -c, --create Create a new archive",
22755 " -u, --update Add or update files with changed mtime",
22756 " -i, --insert Like -u but always add even if unchanged",
22757 " -r, --remove Remove files from archive",
22758 " -t, --list List contents of archive",
22759 " -x, --extract Extract files from archive",
22761 " -v, --verbose Print each filename as it is processed",
22762 " -f FILE, --file FILE Use archive FILE (default is current db)",
22763 " -a FILE, --append FILE Open FILE using the apndvfs VFS",
22764 " -C DIR, --directory DIR Read/extract files from directory DIR",
22765 " -g, --glob Use glob matching for names in archive",
22766 " -n, --dryrun Show the SQL that would have occurred",
22768 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
22769 " .ar -tf ARCHIVE # List members of ARCHIVE",
22770 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
22780 " --append Use the appendvfs",
22781 " --async Write to FILE without journal and fsync()",
22803 " --data-only Output only INSERT statements",
22804 " --newlines Allow unescaped newline characters in output",
22805 " --nosys Omit system tables (ex: \"sqlite_stat1\")",
22806 " --preserve-rowids Include ROWID values in the output",
22819 " --bom Put a UTF8 byte-order mark on intermediate file",
22822 ".exit ?CODE? Exit this program with return-code CODE",
22827 " --schema SCHEMA Use SCHEMA instead of \"main\"",
22828 " --help Show CMD details",
22829 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
22831 ".help ?-all? ?PATTERN? Show help text for PATTERN",
22835 " --ascii Use \\037 and \\036 as column and row separators",
22836 " --csv Use , and \\n as column and row separators",
22837 " --skip N Skip the first N rows of input",
22838 " --schema S Target table to be S.TABLE",
22839 " -v \"Verbose\" - increase auxiliary output",
22843 " * If neither --csv or --ascii are used, the input mode is derived",
22861 " fkey-indexes Find missing foreign key indexes",
22873 " box Tables using unicode box-drawing characters",
22874 " csv Comma-separated values",
22882 " qbox Shorthand for \"box --wrap 60 --quote\"",
22884 " table ASCII-art table",
22885 " tabs Tab-separated values",
22888 " --wrap N Wrap output lines to no longer than N characters",
22889 " --wordwrap B Wrap or not at word boundaries per B (on/off)",
22890 " --ww Shorthand for \"--wordwrap 1\"",
22891 " --quote Quote output text as SQL literals",
22892 " --noquote Do not quote output text",
22901 " --bom Put a UTF8 byte-order mark at the beginning",
22902 " -e Send output to the system text editor",
22903 " -x Send output as CSV to a spreadsheet (same as \".excel\")",
22909 " --append Use appendvfs to append database to the end of FILE",
22912 " --deserialize Load into memory using sqlite3_deserialize()",
22913 " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
22914 " --maxsize N Maximum size for --hexdb or --deserialized database",
22916 " --new Initialize FILE to an empty database",
22917 " --nofollow Do not follow symbolic links",
22918 " --readonly Open FILE readonly",
22919 " --zip FILE is a ZIP archive",
22924 " --bom Prefix output with a UTF8 byte-order mark",
22925 " -e Send output to the system text editor",
22926 " -x Send output as CSV to a spreadsheet",
22938 " --limit N Interrupt after N progress callbacks",
22939 " --once Do no more than one progress interrupt",
22940 " --quiet|-q No output except at interrupts",
22941 " --reset Reset the count for each input and interrupt",
22951 " --ignore-freelist Ignore pages that appear to be on db freelist",
22952 " --lost-and-found TABLE Alternative name for the lost-and-found table",
22953 " --no-rowids Do not attempt to recover rowid values",
22963 " --indent Try to pretty-print the schema",
22964 " --nosys Omit objects whose names start with \"sqlite_\"",
22967 " --init Create a new SELFTEST table",
22968 " -v Verbose output",
22987 " --schema Also hash the sqlite_schema table",
22988 " --sha3-224 Use the sha3-224 algorithm",
22989 " --sha3-256 Use the sha3-256 algorithm (default)",
22990 " --sha3-384 Use the sha3-384 algorithm",
22991 " --sha3-512 Use the sha3-512 algorithm",
23007 ",testcase NAME Begin redirecting output to 'testcase-out.txt'",
23019 " --expanded Expand query parameters",
23021 " --normalized Normal the SQL statements",
23023 " --plain Show SQL as it is input",
23024 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
23025 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
23026 " --row Trace each row (SQLITE_TRACE_ROW)",
23027 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
23031 " --allexcept Unregister everything except those named",
23034 ".vfsinfo ?AUX? Information about the top-level VFS",
23038 " Negative values right-justify",
23045 ** If zPattern is NULL, then show all commands, but only give a one-line
23057 || cli_strcmp(zPattern,"-a")==0 in showHelp()
23058 || cli_strcmp(zPattern,"-all")==0 in showHelp()
23059 || cli_strcmp(zPattern,"--all")==0 in showHelp()
23110 while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){ in showHelp()
23123 while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i; in showHelp()
23129 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){ in showHelp()
23153 ** For convenience, a nul-terminator byte is always appended to the data read
23200 sqlite3session_delete(pSession->p); in session_close()
23201 sqlite3_free(pSession->zName); in session_close()
23202 for(i=0; i<pSession->nFilter; i++){ in session_close()
23203 sqlite3_free(pSession->azFilter[i]); in session_close()
23205 sqlite3_free(pSession->azFilter); in session_close()
23216 struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i]; in session_close_all()
23217 for(j=0; j<pAuxDb->nSession; j++){ in session_close_all()
23218 session_close(&pAuxDb->aSession[j]); in session_close_all()
23220 pAuxDb->nSession = 0; in session_close_all()
23234 for(i=0; i<pSession->nFilter; i++){ in session_filter()
23235 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0; in session_filter()
23267 fseek(f, -25, SEEK_END); in deduceDatabaseType()
23269 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){ in deduceDatabaseType()
23272 fseek(f, -22, SEEK_END); in deduceDatabaseType()
23287 ** Reconstruct an in-memory database using the output from the "dbtotxt"
23288 ** program. Read content from the file in p->aAuxDb[].zDbFilename.
23289 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
23300 const char *zDbFilename = p->pAuxDb->zDbFilename; in readHexDb()
23311 in = p->in; in readHexDb()
23312 nLine = p->lineno; in readHexDb()
23321 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error; in readHexDb()
23322 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */ in readHexDb()
23326 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){ in readHexDb()
23351 if( in!=p->in ){ in readHexDb()
23354 p->lineno = nLine; in readHexDb()
23359 if( in!=p->in ){ in readHexDb()
23362 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){ in readHexDb()
23366 p->lineno = nLine; in readHexDb()
23369 eputf("Error on line %d of --hexdb input\n", nLine); in readHexDb()
23406 if( p->db==0 ){ in open_db()
23407 const char *zDbFilename = p->pAuxDb->zDbFilename; in open_db()
23408 if( p->openMode==SHELL_OPEN_UNSPEC ){ in open_db()
23410 p->openMode = SHELL_OPEN_NORMAL; in open_db()
23412 p->openMode = (u8)deduceDatabaseType(zDbFilename, in open_db()
23416 switch( p->openMode ){ in open_db()
23418 sqlite3_open_v2(zDbFilename, &p->db, in open_db()
23419 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs"); in open_db()
23424 sqlite3_open(0, &p->db); in open_db()
23428 sqlite3_open(":memory:", &p->db); in open_db()
23432 sqlite3_open_v2(zDbFilename, &p->db, in open_db()
23433 SQLITE_OPEN_READONLY|p->openFlags, 0); in open_db()
23438 sqlite3_open_v2(zDbFilename, &p->db, in open_db()
23439 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0); in open_db()
23443 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ in open_db()
23445 zDbFilename, sqlite3_errmsg(p->db)); in open_db()
23449 sqlite3_close(p->db); in open_db()
23450 sqlite3_open(":memory:", &p->db); in open_db()
23451 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ in open_db()
23452 eputz("Also: unable to open substitute in-memory database.\n"); in open_db()
23455 eputf("Notice: using substitute in-memory database instead of \"%s\"\n", in open_db()
23459 globalDb = p->db; in open_db()
23460 sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0); in open_db()
23462 /* Reflect the use or absence of --unsafe-testing invocation. */ in open_db()
23465 sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0); in open_db()
23466 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0); in open_db()
23470 sqlite3_enable_load_extension(p->db, 1); in open_db()
23472 sqlite3_shathree_init(p->db, 0, 0); in open_db()
23473 sqlite3_uint_init(p->db, 0, 0); in open_db()
23474 sqlite3_decimal_init(p->db, 0, 0); in open_db()
23475 sqlite3_base64_init(p->db, 0, 0); in open_db()
23476 sqlite3_base85_init(p->db, 0, 0); in open_db()
23477 sqlite3_regexp_init(p->db, 0, 0); in open_db()
23478 sqlite3_ieee_init(p->db, 0, 0); in open_db()
23479 sqlite3_series_init(p->db, 0, 0); in open_db()
23481 sqlite3_fileio_init(p->db, 0, 0); in open_db()
23482 sqlite3_completion_init(p->db, 0, 0); in open_db()
23485 if( !p->bSafeModePersist ){ in open_db()
23486 sqlite3_zipfile_init(p->db, 0, 0); in open_db()
23487 sqlite3_sqlar_init(p->db, 0, 0); in open_db()
23493 * This is a short-span macro. See further below for usage. in open_db()
23497 /* Let custom-included extensions get their ..._init() called. in open_db()
23503 int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db); in open_db()
23504 /* Let custom-included extensions expose their functionality. in open_db()
23511 SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0); in open_db()
23518 sqlite3_create_function(p->db, "strtod", 1, SQLITE_UTF8, 0, in open_db()
23520 sqlite3_create_function(p->db, "dtostr", 1, SQLITE_UTF8, 0, in open_db()
23522 sqlite3_create_function(p->db, "dtostr", 2, SQLITE_UTF8, 0, in open_db()
23524 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0, in open_db()
23526 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0, in open_db()
23528 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p, in open_db()
23530 sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0, in open_db()
23533 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0, in open_db()
23535 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0, in open_db()
23539 if( p->openMode==SHELL_OPEN_ZIPFILE ){ in open_db()
23543 sqlite3_exec(p->db, zSql, 0, 0, 0); in open_db()
23548 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){ in open_db()
23552 if( p->openMode==SHELL_OPEN_DESERIALIZE ){ in open_db()
23560 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData, in open_db()
23566 if( p->szMax>0 ){ in open_db()
23567 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax); in open_db()
23572 if( p->db!=0 ){ in open_db()
23573 if( p->bSafeModePersist ){ in open_db()
23574 sqlite3_set_authorizer(p->db, safeModeAuth, p); in open_db()
23577 p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0 in open_db()
23605 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); in readline_completion_generator()
23636 if( nLine>(i64)sizeof(zBuf)-30 ) return; in linenoise_completion()
23638 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){} in linenoise_completion()
23639 if( i==nLine-1 ) return; in linenoise_completion()
23646 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); in linenoise_completion()
23652 if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){ in linenoise_completion()
23662 ** Do C-language style dequoting.
23664 ** \a -> alarm
23665 ** \b -> backspace
23666 ** \t -> tab
23667 ** \n -> newline
23668 ** \v -> vertical tab
23669 ** \f -> form feed
23670 ** \r -> carriage return
23671 ** \s -> space
23672 ** \" -> "
23673 ** \' -> '
23674 ** \\ -> backslash
23675 ** \NNN -> ascii character NNN in octal
23676 ** \xHH -> ascii character HH in hexadecimal
23715 c -= '0'; in resolve_backslashes()
23718 c = (c<<3) + z[i] - '0'; in resolve_backslashes()
23721 c = (c<<3) + z[i] - '0'; in resolve_backslashes()
23807 if( p->traceOut==0 ) return 0; in sql_trace_callback()
23809 sputz(p->traceOut, "-- closing database connection\n"); in sql_trace_callback()
23812 if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){ in sql_trace_callback()
23816 switch( p->eTraceType ){ in sql_trace_callback()
23836 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; } in sql_trace_callback()
23840 sputf(p->traceOut, "%.*s;\n", (int)nSql, zSql); in sql_trace_callback()
23845 sputf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec); in sql_trace_callback()
23854 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
23887 if( p->in!=0 && p->xCloser!=0 ){ in import_cleanup()
23888 p->xCloser(p->in); in import_cleanup()
23889 p->in = 0; in import_cleanup()
23891 sqlite3_free(p->z); in import_cleanup()
23892 p->z = 0; in import_cleanup()
23897 if( p->n+1>=p->nAlloc ){ in import_append_char()
23898 p->nAlloc += p->nAlloc + 100; in import_append_char()
23899 p->z = sqlite3_realloc64(p->z, p->nAlloc); in import_append_char()
23900 shell_check_oom(p->z); in import_append_char()
23902 p->z[p->n++] = (char)c; in import_append_char()
23908 ** + Input comes from p->in.
23909 ** + Store results in p->z of length p->n. Space to hold p->z comes
23911 ** + Use p->cSep as the column separator. The default is ",".
23912 ** + Use p->rSep as the row separator. The default is "\n".
23913 ** + Keep track of the line number in p->nLine.
23914 ** + Store the character that terminates the field in p->cTerm. Store
23915 ** EOF on end-of-file.
23920 int cSep = (u8)p->cColSep; in csv_read_one_field()
23921 int rSep = (u8)p->cRowSep; in csv_read_one_field()
23922 p->n = 0; in csv_read_one_field()
23923 c = fgetc(p->in); in csv_read_one_field()
23925 p->cTerm = EOF; in csv_read_one_field()
23930 int startLine = p->nLine; in csv_read_one_field()
23934 c = fgetc(p->in); in csv_read_one_field()
23935 if( c==rSep ) p->nLine++; in csv_read_one_field()
23947 do{ p->n--; }while( p->z[p->n]!=cQuote ); in csv_read_one_field()
23948 p->cTerm = c; in csv_read_one_field()
23952 eputf("%s:%d: unescaped %c character\n", p->zFile, p->nLine, cQuote); in csv_read_one_field()
23955 eputf("%s:%d: unterminated %c-quoted field\n", in csv_read_one_field()
23956 p->zFile, startLine, cQuote); in csv_read_one_field()
23957 p->cTerm = c; in csv_read_one_field()
23966 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ in csv_read_one_field()
23967 if( (c&0xff)==0xef && p->bNotFirst==0 ){ in csv_read_one_field()
23969 c = fgetc(p->in); in csv_read_one_field()
23972 c = fgetc(p->in); in csv_read_one_field()
23974 p->bNotFirst = 1; in csv_read_one_field()
23975 p->n = 0; in csv_read_one_field()
23982 c = fgetc(p->in); in csv_read_one_field()
23985 p->nLine++; in csv_read_one_field()
23986 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; in csv_read_one_field()
23988 p->cTerm = c; in csv_read_one_field()
23990 if( p->z ) p->z[p->n] = 0; in csv_read_one_field()
23991 p->bNotFirst = 1; in csv_read_one_field()
23992 return p->z; in csv_read_one_field()
23997 ** + Input comes from p->in.
23998 ** + Store results in p->z of length p->n. Space to hold p->z comes
24000 ** + Use p->cSep as the column separator. The default is "\x1F".
24001 ** + Use p->rSep as the row separator. The default is "\x1E".
24002 ** + Keep track of the row number in p->nLine.
24003 ** + Store the character that terminates the field in p->cTerm. Store
24004 ** EOF on end-of-file.
24009 int cSep = (u8)p->cColSep; in ascii_read_one_field()
24010 int rSep = (u8)p->cRowSep; in ascii_read_one_field()
24011 p->n = 0; in ascii_read_one_field()
24012 c = fgetc(p->in); in ascii_read_one_field()
24014 p->cTerm = EOF; in ascii_read_one_field()
24019 c = fgetc(p->in); in ascii_read_one_field()
24022 p->nLine++; in ascii_read_one_field()
24024 p->cTerm = c; in ascii_read_one_field()
24025 if( p->z ) p->z[p->n] = 0; in ascii_read_one_field()
24026 return p->z; in ascii_read_one_field()
24052 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); in tryToCloneData()
24055 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery); in tryToCloneData()
24069 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0); in tryToCloneData()
24094 -1, SQLITE_STATIC); in tryToCloneData()
24113 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]); in tryToCloneData()
24123 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); in tryToCloneData()
24160 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); in tryToCloneSchema()
24162 eputf("Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db), in tryToCloneSchema()
24163 sqlite3_errmsg(p->db), zQuery); in tryToCloneSchema()
24190 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); in tryToCloneSchema()
24193 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery); in tryToCloneSchema()
24235 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); in tryToClone()
24240 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); in tryToClone()
24250 if( p->out != stdout ) eputz("Output already redirected.\n"); in output_redir()
24252 p->out = pfNew; in output_redir()
24260 ** If the p->doXdgOpen flag is set, that means the output was being
24261 ** redirected to a temporary file named by p->zTempFile. In that case,
24262 ** launch start/open/xdg-open on that temporary file.
24265 if( p->outfile[0]=='|' ){ in output_reset()
24267 pclose(p->out); in output_reset()
24270 output_file_close(p->out); in output_reset()
24272 if( p->doXdgOpen ){ in output_reset()
24279 "xdg-open"; in output_reset()
24282 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile); in output_reset()
24286 /* Give the start/open/xdg-open command some time to get in output_reset()
24288 ** p->zTempFile data file out from under it */ in output_reset()
24293 p->doXdgOpen = 0; in output_reset()
24297 p->outfile[0] = 0; in output_reset()
24298 p->out = stdout; in output_reset()
24312 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); in db_int()
24322 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
24370 if( p->db==0 ) return 1; in shell_dbinfo_command()
24371 rc = sqlite3_prepare_v2(p->db, in shell_dbinfo_command()
24373 -1, &pStmt, 0); in shell_dbinfo_command()
24375 eputf("error: %s\n", sqlite3_errmsg(p->db)); in shell_dbinfo_command()
24379 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC); in shell_dbinfo_command()
24394 oputf("%-20s %d\n", "database page size:", i); in shell_dbinfo_command()
24395 oputf("%-20s %d\n", "write format:", aHdr[18]); in shell_dbinfo_command()
24396 oputf("%-20s %d\n", "read format:", aHdr[19]); in shell_dbinfo_command()
24397 oputf("%-20s %d\n", "reserved bytes:", aHdr[20]); in shell_dbinfo_command()
24401 oputf("%-20s %u", aField[i].zName, val); in shell_dbinfo_command()
24420 int val = db_int(p->db, zSql); in shell_dbinfo_command()
24422 oputf("%-20s %d\n", aQuery[i].zName, val); in shell_dbinfo_command()
24425 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion); in shell_dbinfo_command()
24426 oputf("%-20s %u\n", "data version", iDataVersion); in shell_dbinfo_command()
24456 ** optional + or - sign in front
24480 while( *z && testcase_glob(zGlob-1,z)==0 ){ in testcase_glob()
24511 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ in testcase_glob()
24525 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++; in testcase_glob()
24539 ** Compare the string as a command-line option with either one or two
24540 ** initial "-" characters.
24543 if( zStr[0]!='-' ) return 0; in optionMatch()
24545 if( zStr[0]=='-' ) zStr++; in optionMatch()
24569 if( p->zTempFile==0 ) return; in clearTempFile()
24570 if( p->doXdgOpen ) return; in clearTempFile()
24571 if( shellDeleteFile(p->zTempFile) ) return; in clearTempFile()
24572 sqlite3_free(p->zTempFile); in clearTempFile()
24573 p->zTempFile = 0; in clearTempFile()
24581 sqlite3_free(p->zTempFile); in newTempFile()
24582 p->zTempFile = 0; in newTempFile()
24583 if( p->db ){ in newTempFile()
24584 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile); in newTempFile()
24586 if( p->zTempFile==0 ){ in newTempFile()
24587 /* If p->db is an in-memory database then the TEMPFILENAME file-control in newTempFile()
24601 p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix); in newTempFile()
24603 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix); in newTempFile()
24605 shell_check_oom(p->zTempFile); in newTempFile()
24611 ** by the ".lint fkey-indexes" command. This scalar function is always
24612 ** called with four arguments - the parent table name, the parent column name,
24615 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
24621 ** function returns the string " COLLATE <parent-collation>", where
24622 ** <parent-collation> is the default collation sequence of the parent column.
24635 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */ in shellFkeyCollateClause()
24644 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); in shellFkeyCollateClause()
24656 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); in shellFkeyCollateClause()
24663 ** The implementation of dot-command ".lint fkey-indexes".
24670 sqlite3 *db = pState->db; /* Database handle to query "main" db of */ in lintFkeyIndexes()
24671 int bVerbose = 0; /* If -verbose is present */ in lintFkeyIndexes()
24672 int bGroupByParent = 0; /* If -groupbyparent is present */ in lintFkeyIndexes()
24736 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) " in lintFkeyIndexes()
24744 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){ in lintFkeyIndexes()
24747 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){ in lintFkeyIndexes()
24752 eputf("Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1]); in lintFkeyIndexes()
24764 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); in lintFkeyIndexes()
24774 int res = -1; in lintFkeyIndexes()
24785 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); in lintFkeyIndexes()
24803 oputf("-- Parent table %s\n", zParent); in lintFkeyIndexes()
24809 oputf("%s%s --> %s\n", zIndent, zCI, zTarget); in lintFkeyIndexes()
24811 oputf("%s/* no extra indexes required for %s -> %s */\n", in lintFkeyIndexes()
24845 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage; in lintDotCommand()
24849 eputf("Usage %s sub-command ?switches...?\n", azArg[0]); in lintDotCommand()
24850 eputz("Where sub-commands are:\n"); in lintDotCommand()
24851 eputz(" fkey-indexes\n"); in lintDotCommand()
24863 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); in shellPrepare()
24872 ** Create a prepared statement using printf-style arguments for the SQL.
24920 ** depending on compile-time options. By omitting the "static", we avoid
24948 u8 bVerbose; /* True if --verbose */
24950 u8 bDryRun; /* True if --dry-run */
24951 u8 bAppend; /* True if --append */
24952 u8 bGlob; /* True if --glob */
24953 u8 fromCmdLine; /* Run from -A instead of .archive */
24956 const char *zFile; /* --file argument, or NULL */
24957 const char *zDir; /* --directory argument, or NULL */
24982 if( pAr->fromCmdLine ){ in arErrorMsg()
24983 eputz("Use \"-A\" for more help\n"); in arErrorMsg()
24985 eputz("Use \".archive --help\" for more help\n"); in arErrorMsg()
25003 ** Other (non-command) switches.
25021 if( pAr->eCmd ){ in arProcessSwitch()
25024 pAr->eCmd = eSwitch; in arProcessSwitch()
25028 pAr->bDryRun = 1; in arProcessSwitch()
25031 pAr->bGlob = 1; in arProcessSwitch()
25034 pAr->bVerbose = 1; in arProcessSwitch()
25037 pAr->bAppend = 1; in arProcessSwitch()
25040 pAr->zFile = zArg; in arProcessSwitch()
25043 pAr->zDir = zArg; in arProcessSwitch()
25089 if( z[0]!='-' ){ in arParseCommand()
25097 if( z[i]==pOpt->cShort ) break; in arParseCommand()
25102 if( pOpt->bArg ){ in arParseCommand()
25108 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; in arParseCommand()
25110 pAr->nArg = nArg-iArg; in arParseCommand()
25111 if( pAr->nArg>0 ){ in arParseCommand()
25112 pAr->azArg = &azArg[iArg]; in arParseCommand()
25115 /* Non-traditional invocation */ in arParseCommand()
25120 if( z[0]!='-' ){ in arParseCommand()
25122 pAr->azArg = &azArg[iArg]; in arParseCommand()
25123 pAr->nArg = nArg-iArg; in arParseCommand()
25128 if( z[1]!='-' ){ in arParseCommand()
25135 if( z[i]==pOpt->cShort ) break; in arParseCommand()
25140 if( pOpt->bArg ){ in arParseCommand()
25141 if( i<(n-1) ){ in arParseCommand()
25145 if( iArg>=(nArg-1) ){ in arParseCommand()
25152 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; in arParseCommand()
25155 /* A -- option, indicating that all remaining command line words in arParseCommand()
25157 pAr->azArg = &azArg[iArg+1]; in arParseCommand()
25158 pAr->nArg = nArg-iArg-1; in arParseCommand()
25166 const char *zLong = pOpt->zLong; in arParseCommand()
25167 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){ in arParseCommand()
25179 if( pMatch->bArg ){ in arParseCommand()
25180 if( iArg>=(nArg-1) ){ in arParseCommand()
25185 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR; in arParseCommand()
25190 if( pAr->eCmd==0 ){ in arParseCommand()
25199 ** array refer to archive members, as for the --extract, --list or --remove
25204 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
25205 ** when pAr->bGlob is true.
25213 if( pAr->nArg ){ in arCheckEntries()
25216 const char *zSel = (pAr->bGlob) in arCheckEntries()
25220 shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable); in arCheckEntries()
25222 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ in arCheckEntries()
25223 char *z = pAr->azArg[i]; in arCheckEntries()
25226 while( n>0 && z[n-1]=='/' ) n--; in arCheckEntries()
25228 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC); in arCheckEntries()
25248 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
25249 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
25257 const char *zSameOp = (pAr->bGlob)? "GLOB" : "="; in arWhereClause()
25259 if( pAr->nArg==0 ){ in arWhereClause()
25264 for(i=0; i<pAr->nArg; i++){ in arWhereClause()
25265 const char *z = pAr->azArg[i]; in arWhereClause()
25298 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose], in arListCommand()
25299 pAr->zSrcTable, zWhere); in arListCommand()
25300 if( pAr->bDryRun ){ in arListCommand()
25304 if( pAr->bVerbose ){ in arListCommand()
25326 if( pAr->nArg ){ in arRemoveCommand()
25334 pAr->zSrcTable, zWhere); in arRemoveCommand()
25335 if( pAr->bDryRun ){ in arRemoveCommand()
25339 rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0); in arRemoveCommand()
25341 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); in arRemoveCommand()
25343 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); in arRemoveCommand()
25345 rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0); in arRemoveCommand()
25388 if( pAr->zDir ){ in arExtractCommand()
25389 zDir = sqlite3_mprintf("%s/", pAr->zDir); in arExtractCommand()
25396 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, in arExtractCommand()
25397 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere in arExtractCommand()
25402 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC); in arExtractCommand()
25412 if( pAr->bDryRun ){ in arExtractCommand()
25416 if( i==0 && pAr->bVerbose ){ in arExtractCommand()
25432 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
25436 if( pAr->bDryRun ){ in arExecSql()
25441 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); in arExecSql()
25454 ** create -> Create a new SQL archive
25455 ** insert -> Insert or reinsert all files listed
25456 ** update -> Insert files that have changed or that were not
25461 ** are added recursively. If argument bVerbose is non-zero, a message is
25466 ** always overwrites every file named on the command-line, where as
25471 int bUpdate, /* true for a --create. */ in arCreateOrUpdateCommand()
25476 " name TEXT PRIMARY KEY, -- name of the file\n" in arCreateOrUpdateCommand()
25477 " mode INT, -- access permissions\n" in arCreateOrUpdateCommand()
25478 " mtime INT, -- last modification time\n" in arCreateOrUpdateCommand()
25479 " sz INT, -- original file size\n" in arCreateOrUpdateCommand()
25480 " data BLOB -- compressed content\n" in arCreateOrUpdateCommand()
25490 " WHEN '-' THEN length(data)\n" in arCreateOrUpdateCommand()
25492 " ELSE -1 END,\n" in arCreateOrUpdateCommand()
25517 if( pAr->bZip ){ in arCreateOrUpdateCommand()
25519 if( pAr->zFile ){ in arCreateOrUpdateCommand()
25526 zTab, pAr->zFile in arCreateOrUpdateCommand()
25553 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ in arCreateOrUpdateCommand()
25554 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab, in arCreateOrUpdateCommand()
25555 pAr->bVerbose ? "shell_putsnl(name)" : "name", in arCreateOrUpdateCommand()
25556 pAr->azArg[i], pAr->zDir, zExists); in arCreateOrUpdateCommand()
25562 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); in arCreateOrUpdateCommand()
25565 if( pAr->bZip && pAr->zFile ){ in arCreateOrUpdateCommand()
25580 int fromCmdLine, /* True if -A command-line option, not .ar cmd */ in arDotCommand()
25592 cmd.db = pState->db; in arDotCommand()
25596 eDbType = pState->openMode; in arDotCommand()
25618 oputf("-- open database '%s'%s\n", cmd.zFile, in arDotCommand()
25658 arUsage(pState->out); in arDotCommand()
25676 if( cmd.db!=pState->db ){ in arDotCommand()
25695 sputf(pState->out, "%s;\n", zSql); in recoverSqlCb()
25702 ** on stream pState->out.
25708 int bFreelist = 1; /* 0 if --ignore-freelist is specified */ in recoverDatabaseCmd()
25709 int bRowids = 1; /* 0 if --no-rowids */ in recoverDatabaseCmd()
25716 if( z[0]=='-' && z[1]=='-' ) z++; in recoverDatabaseCmd()
25718 if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){ in recoverDatabaseCmd()
25721 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){ in recoverDatabaseCmd()
25722 /* This option determines the name of the ATTACH-ed database used in recoverDatabaseCmd()
25730 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){ in recoverDatabaseCmd()
25734 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){ in recoverDatabaseCmd()
25739 showHelp(pState->out, azArg[0]); in recoverDatabaseCmd()
25745 pState->db, "main", recoverSqlCb, (void*)pState in recoverDatabaseCmd()
25771 rc = sqlite3_intck_open(pState->db, "main", &p); in intckDatabaseCmd()
25808 * pointer is non-zero, its referent will be set to a summary of renames
25858 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\ in zAutoColumn()
25866 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\ in zAutoColumn()
25874 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\ in zAutoColumn()
25932 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\ in zAutoColumn()
25935 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \ in zAutoColumn()
25940 " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff))," in zAutoColumn()
25961 rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0); in zAutoColumn()
25963 rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0); in zAutoColumn()
25983 rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0); in zAutoColumn()
25991 rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0); in zAutoColumn()
26003 if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0) in zAutoColumn()
26028 shellPreparePrintf(p->db, &rc, &pStmt, in outputDumpWarning()
26042 ** Fault-Simulator state and logic.
26045 int iId; /* ID that triggers a simulated fault. -1 means "any" */
26053 } faultsim_state = {-1, 0, 0, 0, 0, 0, 0, 0};
26056 ** This is the fault-sim callback
26063 if( faultsim_state.iCnt>0 ) faultsim_state.iCnt--; in faultsim_callback()
26065 oputf("FAULT-SIM id=%d no-fault (cnt=%d)\n", iArg, faultsim_state.iCnt); in faultsim_callback()
26070 oputf("FAULT-SIM id=%d returns %d\n", iArg, faultsim_state.iErr); in faultsim_callback()
26075 faultsim_state.iCnt = -1; in faultsim_callback()
26094 if( p->expert.pExpert ){ in do_meta_command()
26101 while( zLine[h] && nArg<ArraySize(azArg)-1 ){ in do_meta_command()
26114 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]); in do_meta_command()
26139 sqlite3_set_authorizer(p->db, shellAuth, p); in do_meta_command()
26140 }else if( p->bSafeModePersist ){ in do_meta_command()
26141 sqlite3_set_authorizer(p->db, safeModeAuth, p); in do_meta_command()
26143 sqlite3_set_authorizer(p->db, 0, 0); in do_meta_command()
26171 if( z[0]=='-' ){ in do_meta_command()
26172 if( z[1]=='-' ) z++; in do_meta_command()
26173 if( cli_strcmp(z, "-append")==0 ){ in do_meta_command()
26176 if( cli_strcmp(z, "-async")==0 ){ in do_meta_command()
26210 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb); in do_meta_command()
26241 setBinaryMode(p->out, 1); in do_meta_command()
26243 setTextMode(p->out, 1); in do_meta_command()
26252 /* The undocumented ".breakpoint" command causes a call to the no-op in do_meta_command()
26292 ** Then read the content of the testcase-out.txt file and compare against in do_meta_command()
26299 eputz("Usage: .check GLOB-PATTERN\n"); in do_meta_command()
26301 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){ in do_meta_command()
26304 eputf("testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n", in do_meta_command()
26305 p->zTestcase, azArg[1], zRes); in do_meta_command()
26308 oputf("testcase-%s ok\n", p->zTestcase); in do_meta_command()
26309 p->nCheck++; in do_meta_command()
26331 for(i=0; i<ArraySize(p->aAuxDb); i++){ in do_meta_command()
26332 const char *zFile = p->aAuxDb[i].zDbFilename; in do_meta_command()
26333 if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){ in do_meta_command()
26338 zFile = "(temporary-file)"; in do_meta_command()
26340 if( p->pAuxDb == &p->aAuxDb[i] ){ in do_meta_command()
26342 }else if( p->aAuxDb[i].db!=0 ){ in do_meta_command()
26347 int i = azArg[1][0] - '0'; in do_meta_command()
26348 if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){ in do_meta_command()
26349 p->pAuxDb->db = p->db; in do_meta_command()
26350 p->pAuxDb = &p->aAuxDb[i]; in do_meta_command()
26351 globalDb = p->db = p->pAuxDb->db; in do_meta_command()
26352 p->pAuxDb->db = 0; in do_meta_command()
26356 int i = azArg[2][0] - '0'; in do_meta_command()
26357 if( i<0 || i>=ArraySize(p->aAuxDb) ){ in do_meta_command()
26358 /* No-op */ in do_meta_command()
26359 }else if( p->pAuxDb == &p->aAuxDb[i] ){ in do_meta_command()
26362 }else if( p->aAuxDb[i].db ){ in do_meta_command()
26364 close_db(p->aAuxDb[i].db); in do_meta_command()
26365 p->aAuxDb[i].db = 0; in do_meta_command()
26368 eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n"); in do_meta_command()
26376 setTextMode(p->out, 1); in do_meta_command()
26378 setBinaryMode(p->out, 1); in do_meta_command()
26382 eputz("The \".crnl\" is a no-op on non-Windows machines.\n"); in do_meta_command()
26395 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); in do_meta_command()
26397 eputf("Error: %s\n", sqlite3_errmsg(p->db)); in do_meta_command()
26413 int eTxn = sqlite3_txn_state(p->db, azName[i*2]); in do_meta_command()
26414 int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]); in do_meta_command()
26419 eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn"); in do_meta_command()
26455 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0); in do_meta_command()
26457 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v); in do_meta_command()
26482 int savedShowHeader = p->showHeader; in do_meta_command()
26483 int savedShellFlags = p->shellFlgs; in do_meta_command()
26488 if( azArg[i][0]=='-' ){ in do_meta_command()
26490 if( z[0]=='-' ) z++; in do_meta_command()
26491 if( cli_strcmp(z,"preserve-rowids")==0 ){ in do_meta_command()
26493 eputz("The --preserve-rowids option is not compatible" in do_meta_command()
26505 if( cli_strcmp(z,"data-only")==0 ){ in do_meta_command()
26543 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ in do_meta_command()
26546 ** So disable foreign-key constraint enforcement to prevent problems. */ in do_meta_command()
26550 p->writableSchema = 0; in do_meta_command()
26551 p->showHeader = 0; in do_meta_command()
26555 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); in do_meta_command()
26556 p->nErr = 0; in do_meta_command()
26567 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ in do_meta_command()
26579 if( p->writableSchema ){ in do_meta_command()
26581 p->writableSchema = 0; in do_meta_command()
26583 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); in do_meta_command()
26584 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); in do_meta_command()
26585 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ in do_meta_command()
26586 oputz(p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n"); in do_meta_command()
26588 p->showHeader = savedShowHeader; in do_meta_command()
26589 p->shellFlgs = savedShellFlags; in do_meta_command()
26603 p->autoEQPtest = 0; in do_meta_command()
26604 if( p->autoEQPtrace ){ in do_meta_command()
26605 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0); in do_meta_command()
26606 p->autoEQPtrace = 0; in do_meta_command()
26609 p->autoEQP = AUTOEQP_full; in do_meta_command()
26611 p->autoEQP = AUTOEQP_trigger; in do_meta_command()
26614 p->autoEQP = AUTOEQP_on; in do_meta_command()
26615 p->autoEQPtest = 1; in do_meta_command()
26617 p->autoEQP = AUTOEQP_full; in do_meta_command()
26618 p->autoEQPtrace = 1; in do_meta_command()
26620 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0); in do_meta_command()
26621 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0); in do_meta_command()
26624 p->autoEQP = (u8)booleanValue(azArg[1]); in do_meta_command()
26650 if( val==1 && p->mode!=MODE_Explain ){ in do_meta_command()
26651 p->normalMode = p->mode; in do_meta_command()
26652 p->mode = MODE_Explain; in do_meta_command()
26653 p->autoExplain = 0; in do_meta_command()
26655 if( p->mode==MODE_Explain ) p->mode = p->normalMode; in do_meta_command()
26656 p->autoExplain = 0; in do_meta_command()
26658 if( p->mode==MODE_Explain ) p->mode = p->normalMode; in do_meta_command()
26659 p->autoExplain = 1; in do_meta_command()
26665 if( p->bSafeMode ){ in do_meta_command()
26678 const char *zCtrlName; /* Name of a test-control option */ in do_meta_command()
26694 int filectrl = -1; in do_meta_command()
26695 int iCtrl = -1; in do_meta_command()
26697 int isOk = 0; /* 0: usage 1: %lld 2: no-result */ in do_meta_command()
26705 if( zCmd[0]=='-' in do_meta_command()
26706 && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0) in do_meta_command()
26710 for(i=3; i<nArg; i++) azArg[i-2] = azArg[i]; in do_meta_command()
26711 nArg -= 2; in do_meta_command()
26715 /* The argument can optionally begin with "-" or "--" */ in do_meta_command()
26716 if( zCmd[0]=='-' && zCmd[1] ){ in do_meta_command()
26718 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; in do_meta_command()
26721 /* --help lists all file-controls */ in do_meta_command()
26723 oputz("Available file-controls:\n"); in do_meta_command()
26740 eputf("Error: ambiguous file-control: \"%s\"\n" in do_meta_command()
26741 "Use \".filectrl --help\" for help\n", zCmd); in do_meta_command()
26748 eputf("Error: unknown file-control: %s\n" in do_meta_command()
26749 "Use \".filectrl --help\" for help\n", zCmd); in do_meta_command()
26754 iRes = nArg==3 ? integerValue(azArg[2]) : -1; in do_meta_command()
26755 sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes); in do_meta_command()
26764 sqlite3_file_control(p->db, zSchema, filectrl, &x); in do_meta_command()
26772 x = nArg==3 ? booleanValue(azArg[2]) : -1; in do_meta_command()
26773 sqlite3_file_control(p->db, zSchema, filectrl, &x); in do_meta_command()
26782 sqlite3_file_control(p->db, zSchema, filectrl, &x); in do_meta_command()
26790 sqlite3_file_control(p->db, zSchema, filectrl, &z); in do_meta_command()
26802 sqlite3_file_control(p->db, zSchema, filectrl, &x); in do_meta_command()
26804 x = -1; in do_meta_command()
26805 sqlite3_file_control(p->db, zSchema, filectrl, &x); in do_meta_command()
26833 eputz("Usage: .fullschema ?--indent?\n"); in do_meta_command()
26838 rc = sqlite3_exec(p->db, in do_meta_command()
26849 rc = sqlite3_prepare_v2(p->db, in do_meta_command()
26852 -1, &pStmt, 0); in do_meta_command()
26873 p->showHeader = booleanValue(azArg[1]); in do_meta_command()
26874 p->shellFlgs |= SHFLG_HeaderSet; in do_meta_command()
26883 n = showHelp(p->out, azArg[1]); in do_meta_command()
26888 showHelp(p->out, 0); in do_meta_command()
26902 int nSep; /* Number of bytes in p->colSeparator[] */ in do_meta_command()
26913 if( p->mode==MODE_Ascii ){ in do_meta_command()
26921 if( z[0]=='-' && z[1]=='-' ) z++; in do_meta_command()
26922 if( z[0]!='-' ){ in do_meta_command()
26929 showHelp(p->out, "import"); in do_meta_command()
26932 }else if( cli_strcmp(z,"-v")==0 ){ in do_meta_command()
26934 }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){ in do_meta_command()
26936 }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){ in do_meta_command()
26938 }else if( cli_strcmp(z,"-ascii")==0 ){ in do_meta_command()
26943 }else if( cli_strcmp(z,"-csv")==0 ){ in do_meta_command()
26950 showHelp(p->out, "import"); in do_meta_command()
26957 showHelp(p->out, "import"); in do_meta_command()
26963 /* If neither the --csv or --ascii options are specified, then set in do_meta_command()
26965 nSep = strlen30(p->colSeparator); in do_meta_command()
26967 eputz("Error: non-null column separator required for import\n"); in do_meta_command()
26971 eputz("Error: multi-character column separators not allowed" in do_meta_command()
26975 nSep = strlen30(p->rowSeparator); in do_meta_command()
26977 eputz("Error: non-null row separator required for import\n"); in do_meta_command()
26980 if( nSep==2 && p->mode==MODE_Csv in do_meta_command()
26981 && cli_strcmp(p->rowSeparator,SEP_CrLf)==0 in do_meta_command()
26987 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
26988 nSep = strlen30(p->rowSeparator); in do_meta_command()
26991 eputz("Error: multi-character row separators not allowed" in do_meta_command()
26995 sCtx.cColSep = (u8)p->colSeparator[0]; in do_meta_command()
26996 sCtx.cRowSep = (u8)p->rowSeparator[0]; in do_meta_command()
27034 while( (nSkip--)>0 ){ in do_meta_command()
27038 if( sqlite3_table_column_metadata(p->db, zSchema, zTable,0,0,0,0,0,0) ){ in do_meta_command()
27051 sputf((stdin_is_interactive && p->in==stdin)? p->out : stderr, in do_meta_command()
27071 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); in do_meta_command()
27075 eputf("%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db)); in do_meta_command()
27087 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
27092 eputf("Error: %s\n", sqlite3_errmsg(p->db)); in do_meta_command()
27132 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
27136 eputf("Error: %s\n", sqlite3_errmsg(p->db)); in do_meta_command()
27142 needCommit = sqlite3_get_autocommit(p->db); in do_meta_command()
27143 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); in do_meta_command()
27149 ** Did we reach end-of-file before finding any columns? in do_meta_command()
27154 ** Did we reach end-of-file OR end-of-line before finding any in do_meta_command()
27158 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; in do_meta_command()
27161 ** record terminator but only for last field of multi-field row. in do_meta_command()
27164 if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){ in do_meta_command()
27167 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); in do_meta_command()
27168 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){ in do_meta_command()
27170 " - filling the rest with NULL\n", in do_meta_command()
27181 eputf("%s:%d: expected %d columns but found %d - extras ignored\n", in do_meta_command()
27189 sCtx.zFile, startLine, sqlite3_errmsg(p->db)); in do_meta_command()
27199 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); in do_meta_command()
27202 sCtx.nRow, sCtx.nErr, sCtx.nLine-1); in do_meta_command()
27217 eputf(".%s unavailable without --unsafe-testing\n", in do_meta_command()
27237 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1); in do_meta_command()
27249 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
27257 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
27265 if( sqlite3_column_int(pStmt,1)==-1 ){ in do_meta_command()
27293 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum); in do_meta_command()
27295 rc = sqlite3_exec(p->db, zSql, 0, 0, 0); in do_meta_command()
27296 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0); in do_meta_command()
27298 eputf("Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db)); in do_meta_command()
27316 if( iArg==0 ) iArg = -1; in do_meta_command()
27334 }else if( cli_strcmp(azArg[1], "-")==0 ){ in do_meta_command()
27373 sqlite3_limit(p->db, aLimit[i].limitCode, -1)); in do_meta_command()
27376 eputz("Usage: .limit NAME ?NEW-VALUE?\n"); in do_meta_command()
27380 int iLimit = -1; in do_meta_command()
27401 sqlite3_limit(p->db, aLimit[iLimit].limitCode, in do_meta_command()
27405 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); in do_meta_command()
27420 /* Must have a non-empty FILE. (Will not load self.) */ in do_meta_command()
27428 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); in do_meta_command()
27443 if( p->bSafeMode in do_meta_command()
27451 output_file_close(p->pLog); in do_meta_command()
27453 p->pLog = output_file_open(zFile, 0); in do_meta_command()
27476 /* Apply defaults for qbox pseudo-mode. If that in do_meta_command()
27477 * overwrites already-set values, user was informed of this. in do_meta_command()
27486 }else if( z[0]=='-' ){ in do_meta_command()
27489 " --noquote\n" in do_meta_command()
27490 " --quote\n" in do_meta_command()
27491 " --wordwrap on/off\n" in do_meta_command()
27492 " --wrap N\n" in do_meta_command()
27493 " --ww\n"); in do_meta_command()
27503 if( p->mode==MODE_Column in do_meta_command()
27504 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box) in do_meta_command()
27506 oputf("current output mode: %s --wrap %d --wordwrap %s --%squote\n", in do_meta_command()
27507 modeDescr[p->mode], p->cmOpts.iWrap, in do_meta_command()
27508 p->cmOpts.bWordWrap ? "on" : "off", in do_meta_command()
27509 p->cmOpts.bQuote ? "" : "no"); in do_meta_command()
27511 oputf("current output mode: %s\n", modeDescr[p->mode]); in do_meta_command()
27513 zMode = modeDescr[p->mode]; in do_meta_command()
27517 p->mode = MODE_Line; in do_meta_command()
27518 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
27520 p->mode = MODE_Column; in do_meta_command()
27521 if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){ in do_meta_command()
27522 p->showHeader = 1; in do_meta_command()
27524 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
27525 p->cmOpts = cmOpts; in do_meta_command()
27527 p->mode = MODE_List; in do_meta_command()
27528 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column); in do_meta_command()
27529 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
27531 p->mode = MODE_Html; in do_meta_command()
27533 p->mode = MODE_Tcl; in do_meta_command()
27534 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space); in do_meta_command()
27535 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
27537 p->mode = MODE_Csv; in do_meta_command()
27538 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); in do_meta_command()
27539 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); in do_meta_command()
27541 p->mode = MODE_List; in do_meta_command()
27542 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab); in do_meta_command()
27544 p->mode = MODE_Insert; in do_meta_command()
27547 p->mode = MODE_Quote; in do_meta_command()
27548 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); in do_meta_command()
27549 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
27551 p->mode = MODE_Ascii; in do_meta_command()
27552 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit); in do_meta_command()
27553 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record); in do_meta_command()
27555 p->mode = MODE_Markdown; in do_meta_command()
27556 p->cmOpts = cmOpts; in do_meta_command()
27558 p->mode = MODE_Table; in do_meta_command()
27559 p->cmOpts = cmOpts; in do_meta_command()
27561 p->mode = MODE_Box; in do_meta_command()
27562 p->cmOpts = cmOpts; in do_meta_command()
27564 p->mode = MODE_Count; in do_meta_command()
27566 p->mode = MODE_Off; in do_meta_command()
27568 p->mode = MODE_Json; in do_meta_command()
27575 p->cMode = p->mode; in do_meta_command()
27583 }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){ in do_meta_command()
27585 p->lineno, azArg[1]); in do_meta_command()
27588 p->bSafeMode = 0; in do_meta_command()
27597 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue, in do_meta_command()
27598 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]); in do_meta_command()
27612 /* Check for command-line arguments */ in do_meta_command()
27627 p->openFlags |= SQLITE_OPEN_NOFOLLOW; in do_meta_command()
27634 p->szMax = integerValue(azArg[++iName]); in do_meta_command()
27638 if( z[0]=='-' ){ in do_meta_command()
27652 session_close_all(p, -1); in do_meta_command()
27653 close_db(p->db); in do_meta_command()
27654 p->db = 0; in do_meta_command()
27655 p->pAuxDb->zDbFilename = 0; in do_meta_command()
27656 sqlite3_free(p->pAuxDb->zFreeOnClose); in do_meta_command()
27657 p->pAuxDb->zFreeOnClose = 0; in do_meta_command()
27658 p->openMode = openMode; in do_meta_command()
27659 p->openFlags = 0; in do_meta_command()
27660 p->szMax = 0; in do_meta_command()
27663 if( zFN || p->openMode==SHELL_OPEN_HEXDB ){ in do_meta_command()
27664 if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN); in do_meta_command()
27666 if( p->bSafeMode in do_meta_command()
27667 && p->openMode!=SHELL_OPEN_HEXDB in do_meta_command()
27671 failIfSafeMode(p, "cannot open disk-based database files in safe mode"); in do_meta_command()
27674 /* WASM mode has its own sandboxed pseudo-filesystem. */ in do_meta_command()
27682 p->pAuxDb->zDbFilename = zNewFilename; in do_meta_command()
27684 if( p->db==0 ){ in do_meta_command()
27688 p->pAuxDb->zFreeOnClose = zNewFilename; in do_meta_command()
27691 if( p->db==0 ){ in do_meta_command()
27692 /* As a fall-back open a TEMP database */ in do_meta_command()
27693 p->pAuxDb->zDbFilename = 0; in do_meta_command()
27721 if( z[0]=='-' ){ in do_meta_command()
27722 if( z[1]=='-' ) z++; in do_meta_command()
27723 if( cli_strcmp(z,"-bom")==0 ){ in do_meta_command()
27725 }else if( c!='e' && cli_strcmp(z,"-x")==0 ){ in do_meta_command()
27727 }else if( c!='e' && cli_strcmp(z,"-e")==0 ){ in do_meta_command()
27731 showHelp(p->out, azArg[0]); in do_meta_command()
27743 showHelp(p->out, azArg[0]); in do_meta_command()
27753 p->outCount = 2; in do_meta_command()
27755 p->outCount = 0; in do_meta_command()
27760 p->doXdgOpen = 1; in do_meta_command()
27766 p->mode = MODE_Csv; in do_meta_command()
27767 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); in do_meta_command()
27768 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); in do_meta_command()
27775 zFile = sqlite3_mprintf("%s", p->zTempFile); in do_meta_command()
27792 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); in do_meta_command()
27805 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); in do_meta_command()
27820 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;", in do_meta_command()
27831 rx = sqlite3_prepare_v2(p->db, in do_meta_command()
27833 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); in do_meta_command()
27841 rx = sqlite3_prepare_v2(p->db, in do_meta_command()
27843 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); in do_meta_command()
27845 oputf("%-*s %s\n", len, sqlite3_column_text(pStmt,0), in do_meta_command()
27878 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
27887 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
27890 oputf("Error: %s\n", sqlite3_errmsg(p->db)); in do_meta_command()
27908 sqlite3_exec(p->db, zSql, 0, 0, 0); in do_meta_command()
27913 showHelp(p->out, "parameter"); in do_meta_command()
27929 p->flgProgress = 0; in do_meta_command()
27930 p->mxProgress = 0; in do_meta_command()
27931 p->nProgress = 0; in do_meta_command()
27934 if( z[0]=='-' ){ in do_meta_command()
27936 if( z[0]=='-' ) z++; in do_meta_command()
27938 p->flgProgress |= SHELL_PROGRESS_QUIET; in do_meta_command()
27942 p->flgProgress |= SHELL_PROGRESS_RESET; in do_meta_command()
27946 p->flgProgress |= SHELL_PROGRESS_ONCE; in do_meta_command()
27951 eputz("Error: missing argument on --limit\n"); in do_meta_command()
27955 p->mxProgress = (int)integerValue(azArg[++i]); in do_meta_command()
27967 sqlite3_progress_handler(p->db, nn, progress_handler, p); in do_meta_command()
27973 shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); in do_meta_command()
27976 shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); in do_meta_command()
27988 FILE *inSaved = p->in; in do_meta_command()
27989 int savedLineno = p->lineno; in do_meta_command()
28000 p->out = stdout; in do_meta_command()
28002 p->in = popen(azArg[1]+1, "r"); in do_meta_command()
28003 if( p->in==0 ){ in do_meta_command()
28008 pclose(p->in); in do_meta_command()
28011 }else if( (p->in = openChrSource(azArg[1]))==0 ){ in do_meta_command()
28016 fclose(p->in); in do_meta_command()
28018 p->in = inSaved; in do_meta_command()
28019 p->lineno = savedLineno; in do_meta_command()
28050 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); in do_meta_command()
28052 eputf("Error: %s\n", sqlite3_errmsg(p->db)); in do_meta_command()
28070 eputf("Error: %s\n", sqlite3_errmsg(p->db)); in do_meta_command()
28080 p->scanstatsOn = 3; in do_meta_command()
28083 p->scanstatsOn = 2; in do_meta_command()
28085 p->scanstatsOn = (u8)booleanValue(azArg[1]); in do_meta_command()
28089 p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0 in do_meta_command()
28094 if( p->scanstatsOn==3 ){ in do_meta_command()
28127 }else if( azArg[ii][0]=='-' ){ in do_meta_command()
28134 eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n"); in do_meta_command()
28164 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list", in do_meta_command()
28165 -1, &pStmt, 0); in do_meta_command()
28167 eputf("Error: %s\n", sqlite3_errmsg(p->db)); in do_meta_command()
28231 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg); in do_meta_command()
28256 struct AuxDb *pAuxDb = p->pAuxDb; in do_meta_command()
28257 OpenSession *pSession = &pAuxDb->aSession[0]; in do_meta_command()
28260 int nCmd = nArg - 1; in do_meta_command()
28265 for(iSes=0; iSes<pAuxDb->nSession; iSes++){ in do_meta_command()
28266 if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break; in do_meta_command()
28268 if( iSes<pAuxDb->nSession ){ in do_meta_command()
28269 pSession = &pAuxDb->aSession[iSes]; in do_meta_command()
28271 nCmd--; in do_meta_command()
28273 pSession = &pAuxDb->aSession[0]; in do_meta_command()
28284 if( pSession->p==0 ){ in do_meta_command()
28288 rc = sqlite3session_attach(pSession->p, azCmd[1]); in do_meta_command()
28306 if( pSession->p==0 ) goto session_not_open; in do_meta_command()
28315 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); in do_meta_command()
28317 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); in do_meta_command()
28325 eputf("ERROR: Failed to write entire %d-byte output\n", szChng); in do_meta_command()
28337 if( pAuxDb->nSession ){ in do_meta_command()
28339 pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession]; in do_meta_command()
28349 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); in do_meta_command()
28350 if( pAuxDb->nSession ){ in do_meta_command()
28351 ii = sqlite3session_enable(pSession->p, ii); in do_meta_command()
28352 oputf("session %s enable flag = %d\n", pSession->zName, ii); in do_meta_command()
28362 if( pAuxDb->nSession ){ in do_meta_command()
28363 for(ii=0; ii<pSession->nFilter; ii++){ in do_meta_command()
28364 sqlite3_free(pSession->azFilter[ii]); in do_meta_command()
28366 sqlite3_free(pSession->azFilter); in do_meta_command()
28367 nByte = sizeof(pSession->azFilter[0])*(nCmd-1); in do_meta_command()
28368 pSession->azFilter = sqlite3_malloc( nByte ); in do_meta_command()
28369 shell_check_oom( pSession->azFilter ); in do_meta_command()
28371 char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); in do_meta_command()
28374 pSession->nFilter = ii-1; in do_meta_command()
28384 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); in do_meta_command()
28385 if( pAuxDb->nSession ){ in do_meta_command()
28386 ii = sqlite3session_indirect(pSession->p, ii); in do_meta_command()
28387 oputf("session %s indirect flag = %d\n", pSession->zName, ii); in do_meta_command()
28397 if( pAuxDb->nSession ){ in do_meta_command()
28398 ii = sqlite3session_isempty(pSession->p); in do_meta_command()
28399 oputf("session %s isempty flag = %d\n", pSession->zName, ii); in do_meta_command()
28407 for(i=0; i<pAuxDb->nSession; i++){ in do_meta_command()
28408 oputf("%d %s\n", i, pAuxDb->aSession[i].zName); in do_meta_command()
28421 for(i=0; i<pAuxDb->nSession; i++){ in do_meta_command()
28422 if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){ in do_meta_command()
28427 if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){ in do_meta_command()
28428 eputf("Maximum of %d sessions\n", ArraySize(pAuxDb->aSession)); in do_meta_command()
28431 pSession = &pAuxDb->aSession[pAuxDb->nSession]; in do_meta_command()
28432 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); in do_meta_command()
28438 pSession->nFilter = 0; in do_meta_command()
28439 sqlite3session_table_filter(pSession->p, session_filter, pSession); in do_meta_command()
28440 pAuxDb->nSession++; in do_meta_command()
28441 pSession->zName = sqlite3_mprintf("%s", zName); in do_meta_command()
28442 shell_check_oom(pSession->zName); in do_meta_command()
28446 showHelp(p->out, "session"); in do_meta_command()
28453 if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){ in do_meta_command()
28454 if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){ in do_meta_command()
28461 if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){ in do_meta_command()
28486 if( z[0]=='-' && z[1]=='-' ) z++; in do_meta_command()
28487 if( cli_strcmp(z,"-init")==0 ){ in do_meta_command()
28490 if( cli_strcmp(z,"-v")==0 ){ in do_meta_command()
28495 eputz("Should be one of: --init -v\n"); in do_meta_command()
28500 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0) in do_meta_command()
28512 for(k=bSelftestExists; k>=0; k--){ in do_meta_command()
28514 rc = sqlite3_prepare_v2(p->db, in do_meta_command()
28516 -1, &pStmt, 0); in do_meta_command()
28518 rc = sqlite3_prepare_v2(p->db, in do_meta_command()
28519 "VALUES(0,'memo','Missing SELFTEST table - default checks only','')," in do_meta_command()
28521 -1, &pStmt, 0); in do_meta_command()
28549 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg); in do_meta_command()
28557 oputf("%d: error-code-%d: %s\n", tno, rc, zErrMsg); in do_meta_command()
28584 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, in do_meta_command()
28585 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]); in do_meta_command()
28588 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, in do_meta_command()
28589 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]); in do_meta_command()
28608 if( z[0]=='-' ){ in do_meta_command()
28610 if( z[0]=='-' ) z++; in do_meta_command()
28614 if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0 in do_meta_command()
28615 || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0 in do_meta_command()
28624 showHelp(p->out, azArg[0]); in do_meta_command()
28629 eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n"); in do_meta_command()
28649 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
28708 char *zRevText = /* Query for reversible to-blob-to-text check */ in do_meta_command()
28715 /* lower-case query is first run, producing upper-case query. */ in do_meta_command()
28732 lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0); in do_meta_command()
28738 if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC); in do_meta_command()
28743 lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0); in do_meta_command()
28805 oputf("%12.12s: %s\n","eqp", azBool[p->autoEQP&3]); in do_meta_command()
28807 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off"); in do_meta_command()
28808 oputf("%12.12s: %s\n","headers", azBool[p->showHeader!=0]); in do_meta_command()
28809 if( p->mode==MODE_Column in do_meta_command()
28810 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box) in do_meta_command()
28812 oputf("%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode", in do_meta_command()
28813 modeDescr[p->mode], p->cmOpts.iWrap, in do_meta_command()
28814 p->cmOpts.bWordWrap ? "on" : "off", in do_meta_command()
28815 p->cmOpts.bQuote ? "" : "no"); in do_meta_command()
28817 oputf("%12.12s: %s\n","mode", modeDescr[p->mode]); in do_meta_command()
28820 output_c_string(p->nullValue); in do_meta_command()
28823 strlen30(p->outfile) ? p->outfile : "stdout"); in do_meta_command()
28825 output_c_string(p->colSeparator); in do_meta_command()
28828 output_c_string(p->rowSeparator); in do_meta_command()
28830 switch( p->statsOn ){ in do_meta_command()
28838 for (i=0;i<p->nWidth;i++) { in do_meta_command()
28839 oputf("%d ", p->colWidth[i]); in do_meta_command()
28843 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : ""); in do_meta_command()
28849 p->statsOn = 2; in do_meta_command()
28851 p->statsOn = 3; in do_meta_command()
28853 p->statsOn = (u8)booleanValue(azArg[1]); in do_meta_command()
28856 display_stats(p->db, p, 0); in do_meta_command()
28874 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); in do_meta_command()
28877 return shellDatabaseError(p->db); in do_meta_command()
28884 eputz("Usage: .indexes ?LIKE-PATTERN?\n"); in do_meta_command()
28914 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0); in do_meta_command()
28917 if( rc ) return shellDatabaseError(p->db); in do_meta_command()
28920 ** as an array of nul-terminated strings in azResult[]. */ in do_meta_command()
28924 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); in do_meta_command()
28926 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); in do_meta_command()
28942 rc = shellDatabaseError(p->db); in do_meta_command()
28945 /* Pretty-print the contents of array azResult[] to the output */ in do_meta_command()
28956 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; in do_meta_command()
28960 oputf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j]:""); in do_meta_command()
28971 /* Begin redirecting output to the file "testcase-out.txt" */ in do_meta_command()
28974 p->out = output_file_open("testcase-out.txt", 0); in do_meta_command()
28975 if( p->out==0 ){ in do_meta_command()
28976 eputz("Error: cannot open 'testcase-out.txt'\n"); in do_meta_command()
28979 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]); in do_meta_command()
28981 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?"); in do_meta_command()
28989 const char *zCtrlName; /* Name of a test-control option */ in do_meta_command()
28991 int unSafe; /* Not valid unless --unsafe-testing */ in do_meta_command()
29007 {"optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK" }, in do_meta_command()
29020 int testctrl = -1; in do_meta_command()
29021 int iCtrl = -1; in do_meta_command()
29022 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */ in do_meta_command()
29030 /* The argument can optionally begin with "-" or "--" */ in do_meta_command()
29031 if( zCmd[0]=='-' && zCmd[1] ){ in do_meta_command()
29033 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; in do_meta_command()
29036 /* --help lists all test-controls */ in do_meta_command()
29038 oputz("Available test-controls:\n"); in do_meta_command()
29058 eputf("Error: ambiguous test-control: \"%s\"\n" in do_meta_command()
29059 "Use \".testctrl --help\" for help\n", zCmd); in do_meta_command()
29066 eputf("Error: unknown test-control: %s\n" in do_meta_command()
29067 "Use \".testctrl --help\" for help\n", zCmd); in do_meta_command()
29076 rc2 = sqlite3_test_control(testctrl, p->db, opt); in do_meta_command()
29107 sputf(stdout, "-- random seed: %d\n", ii); in do_meta_command()
29112 db = p->db; in do_meta_command()
29143 int opt = -1; in do_meta_command()
29158 rc2 = sqlite3_test_control(testctrl, p->db); in do_meta_command()
29164 rc2 = sqlite3_test_control(testctrl, p->db, in do_meta_command()
29174 rc2 = sqlite3_test_control(testctrl, p->db, &x); in do_meta_command()
29183 sqlite3_test_control(testctrl, p->out); in do_meta_command()
29198 sqlite3_test_control(testctrl, -id, &rc2); in do_meta_command()
29204 rc2 = sqlite3_test_control(testctrl, -id, &val); in do_meta_command()
29219 rc2 = sqlite3_test_control(testctrl, p->db, opt); in do_meta_command()
29225 rc2 = -1; in do_meta_command()
29239 if( z[0]=='-' && z[1]=='-' ) z++; in do_meta_command()
29260 }else if( cli_strcmp(z,"-v")==0 ){ in do_meta_command()
29262 }else if( cli_strcmp(z,"-q")==0 ){ in do_meta_command()
29263 if( faultsim_state.eVerbose>0 ) faultsim_state.eVerbose--; in do_meta_command()
29264 }else if( cli_strcmp(z,"-id")==0 && kk+1<nArg ){ in do_meta_command()
29266 }else if( cli_strcmp(z,"-errcode")==0 && kk+1<nArg ){ in do_meta_command()
29268 }else if( cli_strcmp(z,"-interval")==0 && kk+1<nArg ){ in do_meta_command()
29270 }else if( cli_strcmp(z,"-repeat")==0 && kk+1<nArg ){ in do_meta_command()
29272 }else if( cli_strcmp(z,"-skip")==0 && kk+1<nArg ){ in do_meta_command()
29274 }else if( cli_strcmp(z,"-?")==0 || sqlite3_strglob("*help*",z)==0){ in do_meta_command()
29292 " -v Increase verbosity\n" in do_meta_command()
29293 " -q Decrease verbosity\n" in do_meta_command()
29294 " --errcode N When triggered, return N as error code\n" in do_meta_command()
29295 " --id ID Trigger only for the ID specified\n" in do_meta_command()
29296 " --interval N Trigger only after every N-th call\n" in do_meta_command()
29297 " --repeat N Turn off after N hits. 0 means never\n" in do_meta_command()
29298 " --skip N Skip the first N encounters\n" in do_meta_command()
29318 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); in do_meta_command()
29341 if( z[0]=='-' ){ in do_meta_command()
29343 p->eTraceType = SHELL_TRACE_EXPANDED; in do_meta_command()
29347 p->eTraceType = SHELL_TRACE_NORMALIZED; in do_meta_command()
29351 p->eTraceType = SHELL_TRACE_PLAIN; in do_meta_command()
29371 output_file_close(p->traceOut); in do_meta_command()
29372 p->traceOut = output_file_open(z, 0); in do_meta_command()
29375 if( p->traceOut==0 ){ in do_meta_command()
29376 sqlite3_trace_v2(p->db, 0, 0, 0); in do_meta_command()
29379 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p); in do_meta_command()
29390 eputz("Usage: .unmodule [--allexcept] NAME ...\n"); in do_meta_command()
29396 if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++; in do_meta_command()
29398 if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){ in do_meta_command()
29400 sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0); in do_meta_command()
29403 sqlite3_create_module(p->db, azArg[ii], 0, 0); in do_meta_command()
29423 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], in do_meta_command()
29435 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]), in do_meta_command()
29438 eputf("User-Add failed: %d\n", rc); in do_meta_command()
29447 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]), in do_meta_command()
29450 eputf("User-Edit failed: %d\n", rc); in do_meta_command()
29459 rc = sqlite3_user_delete(p->db, azArg[2]); in do_meta_command()
29461 eputf("User-Delete failed: %d\n", rc); in do_meta_command()
29473 char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit"; in do_meta_command()
29474 oputf("SQLite %s %s\n" /*extra-version-info*/, in do_meta_command()
29482 oputf("clang-" CTIMEOPT_VAL(__clang_major__) "." in do_meta_command()
29486 oputf("msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz); in do_meta_command()
29488 oputf("gcc-" __VERSION__ " (%s)\n", zPtrSz); in do_meta_command()
29495 if( p->db ){ in do_meta_command()
29496 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); in do_meta_command()
29498 oputf("vfs.zName = \"%s\"\n", pVfs->zName); in do_meta_command()
29499 oputf("vfs.iVersion = %d\n", pVfs->iVersion); in do_meta_command()
29500 oputf("vfs.szOsFile = %d\n", pVfs->szOsFile); in do_meta_command()
29501 oputf("vfs.mxPathname = %d\n", pVfs->mxPathname); in do_meta_command()
29509 if( p->db ){ in do_meta_command()
29510 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); in do_meta_command()
29512 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ in do_meta_command()
29513 oputf("vfs.zName = \"%s\"%s\n", pVfs->zName, in do_meta_command()
29514 pVfs==pCurrent ? " <--- CURRENT" : ""); in do_meta_command()
29515 oputf("vfs.iVersion = %d\n", pVfs->iVersion); in do_meta_command()
29516 oputf("vfs.szOsFile = %d\n", pVfs->szOsFile); in do_meta_command()
29517 oputf("vfs.mxPathname = %d\n", pVfs->mxPathname); in do_meta_command()
29518 if( pVfs->pNext ){ in do_meta_command()
29519 oputz("-----------------------------------\n"); in do_meta_command()
29527 if( p->db ){ in do_meta_command()
29528 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); in do_meta_command()
29544 p->nWidth = nArg-1; in do_meta_command()
29545 p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2); in do_meta_command()
29546 if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory(); in do_meta_command()
29547 if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth]; in do_meta_command()
29549 p->colWidth[j-1] = (int)integerValue(azArg[j]); in do_meta_command()
29560 if( p->outCount ){ in do_meta_command()
29561 p->outCount--; in do_meta_command()
29562 if( p->outCount==0 ) output_reset(p); in do_meta_command()
29564 p->bSafeMode = p->bSafeModePersist; in do_meta_command()
29575 QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
29600 case '-': in quickscan()
29601 if( *zLine!='-' ) in quickscan()
29631 CONTINUE_PAREN_INCR(pst, -1); in quickscan()
29653 /* Swallow doubled end-delimiter.*/ in quickscan()
29673 ** than a semi-colon. The SQL Server style "go" command is understood
29697 ** ends in the middle of a string literal or C-style comment.
29717 ** 4. The shell is not running in --safe mode.
29723 ** 2-6: Currently running .dump transaction. If the "2" bit is set,
29725 ** 7: Nothing left to do. This function becomes a no-op.
29730 if( p->eRestoreState<7 ){ in doAutoDetectRestore()
29731 switch( p->eRestoreState ){ in doAutoDetectRestore()
29735 if( p->bSafeMode==0 && memcmp(zSql, zExpect, 25)==0 ){ in doAutoDetectRestore()
29736 p->eRestoreState = 1; in doAutoDetectRestore()
29738 p->eRestoreState = 7; in doAutoDetectRestore()
29753 shellPrepare(p->db, &rc, zQuery, &pStmt); in doAutoDetectRestore()
29762 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense); in doAutoDetectRestore()
29763 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl); in doAutoDetectRestore()
29764 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0); in doAutoDetectRestore()
29765 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, 0); in doAutoDetectRestore()
29766 p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0); in doAutoDetectRestore()
29768 p->eRestoreState = 7; in doAutoDetectRestore()
29774 if( sqlite3_get_autocommit(p->db) ){ in doAutoDetectRestore()
29775 if( (p->eRestoreState & 2) ){ in doAutoDetectRestore()
29776 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, 0); in doAutoDetectRestore()
29778 if( (p->eRestoreState & 4) ){ in doAutoDetectRestore()
29779 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, 0); in doAutoDetectRestore()
29781 p->eRestoreState = 7; in doAutoDetectRestore()
29800 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; in runOneSqlLine()
29810 zErrorTail = sqlite3_errmsg(p->db); in runOneSqlLine()
29835 sqlite3_changes64(p->db), sqlite3_total_changes64(p->db)); in runOneSqlLine()
29868 if(nZ>0 && '\r'==zBegin[nZ-1]){ in one_input_line()
29869 --nZ; in one_input_line()
29882 ** is interactive - the user is typing it it. Otherwise, input
29900 if( p->inputNesting==MAX_INPUT_NESTING ){ in process_input()
29903 " Check recursion.\n", MAX_INPUT_NESTING, p->lineno); in process_input()
29906 ++p->inputNesting; in process_input()
29907 p->lineno = 0; in process_input()
29909 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){ in process_input()
29910 fflush(p->out); in process_input()
29911 zLine = one_input_line(p->in, zLine, nSql>0); in process_input()
29914 if( p->in==0 && stdin_is_interactive ) oputz("\n"); in process_input()
29918 if( p->in!=0 ) break; in process_input()
29921 p->lineno++; in process_input()
29929 /* Just swallow single-line whitespace */ in process_input()
29948 /* No single-line dispositions remain; accumulate line(s). */ in process_input()
29951 /* Grow buffer by half-again increments when big. */ in process_input()
29960 memcpy(zSql, zLine+i, nLine+1-i); in process_input()
29961 startline = p->lineno; in process_input()
29962 nSql = nLine-i; in process_input()
29970 errCnt += runOneSqlLine(p, zSql, p->in, startline); in process_input()
29973 if( p->outCount ){ in process_input()
29975 p->outCount = 0; in process_input()
29979 p->bSafeMode = p->bSafeModePersist; in process_input()
29990 errCnt += runOneSqlLine(p, zSql, p->in, startline); in process_input()
29995 --p->inputNesting; in process_input()
30018 home_dir = pwent->pw_dir; in find_home_dir()
30024 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() in find_home_dir()
30069 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
30115 FILE *inSaved = p->in; in process_sqliterc()
30116 int savedLineno = p->lineno; in process_sqliterc()
30124 eputz("-- warning: cannot find home directory;" in process_sqliterc()
30132 p->in = fopen(sqliterc,"rb"); in process_sqliterc()
30133 if( p->in ){ in process_sqliterc()
30135 eputf("-- Loading resources from %s\n", sqliterc); in process_sqliterc()
30138 fclose(p->in); in process_sqliterc()
30143 p->in = inSaved; in process_sqliterc()
30144 p->lineno = savedLineno; in process_sqliterc()
30152 " -- treat no subsequent arguments as options\n"
30154 " -A ARGS... run \".archive ARGS\" and exit\n"
30156 " -append append the database to the end of the file\n"
30157 " -ascii set output mode to 'ascii'\n"
30158 " -bail stop after hitting an error\n"
30159 " -batch force batch I/O\n"
30160 " -box set output mode to 'box'\n"
30161 " -column set output mode to 'column'\n"
30162 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
30163 " -csv set output mode to 'csv'\n"
30165 " -deserialize open the database using sqlite3_deserialize()\n"
30167 " -echo print inputs before execution\n"
30168 " -init FILENAME read/process named file\n"
30169 " -[no]header turn headers on or off\n"
30171 " -heap SIZE Size of heap for memsys3 or memsys5\n"
30173 " -help show this message\n"
30174 " -html set output mode to HTML\n"
30175 " -interactive force interactive I/O\n"
30176 " -json set output mode to 'json'\n"
30177 " -line set output mode to 'line'\n"
30178 " -list set output mode to 'list'\n"
30179 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
30180 " -markdown set output mode to 'markdown'\n"
30182 " -maxsize N maximum size for a --deserialize database\n"
30184 " -memtrace trace all memory allocations and deallocations\n"
30185 " -mmap N default mmap size set to N\n"
30187 " -multiplex enable the multiplexor VFS\n"
30189 " -newline SEP set output row separator. Default: '\\n'\n"
30190 " -nofollow refuse to open symbolic links to database files\n"
30191 " -nonce STRING set the safe-mode escape nonce\n"
30192 " -no-rowid-in-view Disable rowid-in-view using sqlite3_config()\n"
30193 " -nullvalue TEXT set text string for NULL values. Default ''\n"
30194 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
30195 " -pcachetrace trace all page cache operations\n"
30196 " -quote set output mode to 'quote'\n"
30197 " -readonly open the database read-only\n"
30198 " -safe enable safe-mode\n"
30199 " -separator SEP set output column separator. Default: '|'\n"
30201 " -sorterref SIZE sorter references threshold size\n"
30203 " -stats print memory stats before each finalize\n"
30204 " -table set output mode to 'table'\n"
30205 " -tabs set output mode to 'tabs'\n"
30206 " -unsafe-testing allow unsafe commands and modes for testing\n"
30207 " -version show SQLite version\n"
30208 " -vfs NAME use NAME as the default VFS\n"
30210 " -vfstrace enable tracing of all VFS calls\n"
30213 " -zip open the file as a ZIP Archive\n"
30223 eputz("Use the -help option for additional information\n"); in usage()
30233 if( sqlite3_config(-1)==SQLITE_MISUSE ){ in verify_uninitialized()
30244 data->normalMode = data->cMode = data->mode = MODE_List; in main_init()
30245 data->autoExplain = 1; in main_init()
30246 data->pAuxDb = &data->aAuxDb[0]; in main_init()
30247 memcpy(data->colSeparator,SEP_Column, 2); in main_init()
30248 memcpy(data->rowSeparator,SEP_Row, 2); in main_init()
30249 data->showHeader = 0; in main_init()
30250 data->shellFlgs = SHFLG_Lookaside; in main_init()
30286 ** Get the argument to an --option. Throw an error and die if no argument
30291 eputf("%s: Error: missing argument to %s\n", argv[0], argv[argc-1]); in cmdline_option_value()
30338 const char *zVfs = 0; /* Value of -vfs command-line option */
30396 /* On Windows, we must translate command-line arguments into UTF-8.
30428 ** of a C-function that will provide the name of the database file. Use
30429 ** this compile-time option to embed this shell program in larger
30432 SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
30437 /* Do an initial pass through the command-line argument to locate
30448 if( z[0]!='-' || i>nOptsEnd ){
30449 if( data.aAuxDb->zDbFilename==0 ){
30450 data.aAuxDb->zDbFilename = z;
30452 /* Excess arguments are interpreted as SQL (or dot-commands) and
30458 azCmd[nCmd-1] = z;
30462 if( z[1]=='-' ) z++;
30463 if( cli_strcmp(z, "-")==0 ){
30466 }else if( cli_strcmp(z,"-separator")==0
30467 || cli_strcmp(z,"-nullvalue")==0
30468 || cli_strcmp(z,"-newline")==0
30469 || cli_strcmp(z,"-cmd")==0
30472 }else if( cli_strcmp(z,"-init")==0 ){
30474 }else if( cli_strcmp(z,"-interactive")==0 ){
30475 }else if( cli_strcmp(z,"-batch")==0 ){
30481 }else if( cli_strcmp(z,"-utf8")==0 ){
30482 }else if( cli_strcmp(z,"-no-utf8")==0 ){
30483 }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
30487 }else if( cli_strcmp(z,"-heap")==0 ){
30500 }else if( cli_strcmp(z,"-pagecache")==0 ){
30513 }else if( cli_strcmp(z,"-lookaside")==0 ){
30522 }else if( cli_strcmp(z,"-threadsafe")==0 ){
30532 }else if( cli_strcmp(z,"-vfstrace")==0 ){
30543 }else if( cli_strcmp(z,"-multiplex")==0 ){
30547 }else if( cli_strcmp(z,"-mmap")==0 ){
30552 }else if( cli_strcmp(z,"-sorterref")==0 ){
30557 }else if( cli_strcmp(z,"-vfs")==0 ){
30560 }else if( cli_strcmp(z,"-zip")==0 ){
30563 }else if( cli_strcmp(z,"-append")==0 ){
30566 }else if( cli_strcmp(z,"-deserialize")==0 ){
30568 }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
30571 }else if( cli_strcmp(z,"-readonly")==0 ){
30573 }else if( cli_strcmp(z,"-nofollow")==0 ){
30576 }else if( cli_strncmp(z, "-A",2)==0 ){
30577 /* All remaining command-line arguments are passed to the ".archive"
30581 }else if( cli_strcmp(z, "-memtrace")==0 ){
30583 }else if( cli_strcmp(z, "-pcachetrace")==0 ){
30585 }else if( cli_strcmp(z,"-bail")==0 ){
30587 }else if( cli_strcmp(z,"-nonce")==0 ){
30590 }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
30592 }else if( cli_strcmp(z,"-safe")==0 ){
30593 /* no-op - catch this on the second pass */
30604 ** of a C-function that will perform initialization actions on SQLite that
30605 ** occur just before or after sqlite3_initialize(). Use this compile-time
30612 ** to call sqlite3_initialize() and process any command line -vfs option. */
30626 if( data.pAuxDb->zDbFilename==0 ){
30628 data.pAuxDb->zDbFilename = ":memory:";
30643 ** to the sqlite command-line tool.
30645 if( access(data.pAuxDb->zDbFilename, 0)==0 ){
30649 /* Process the initialization file if there is one. If no -init option
30655 /* Make a second pass through the command-line argument and set
30657 ** file is processed so that the command-line arguments will override
30662 if( z[0]!='-' || i>=nOptsEnd ) continue;
30663 if( z[1]=='-' ){ z++; }
30664 if( cli_strcmp(z,"-init")==0 ){
30666 }else if( cli_strcmp(z,"-html")==0 ){
30668 }else if( cli_strcmp(z,"-list")==0 ){
30670 }else if( cli_strcmp(z,"-quote")==0 ){
30674 }else if( cli_strcmp(z,"-line")==0 ){
30676 }else if( cli_strcmp(z,"-column")==0 ){
30678 }else if( cli_strcmp(z,"-json")==0 ){
30680 }else if( cli_strcmp(z,"-markdown")==0 ){
30682 }else if( cli_strcmp(z,"-table")==0 ){
30684 }else if( cli_strcmp(z,"-box")==0 ){
30686 }else if( cli_strcmp(z,"-csv")==0 ){
30690 }else if( cli_strcmp(z,"-zip")==0 ){
30693 }else if( cli_strcmp(z,"-append")==0 ){
30696 }else if( cli_strcmp(z,"-deserialize")==0 ){
30698 }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
30701 }else if( cli_strcmp(z,"-readonly")==0 ){
30703 }else if( cli_strcmp(z,"-nofollow")==0 ){
30705 }else if( cli_strcmp(z,"-ascii")==0 ){
30709 }else if( cli_strcmp(z,"-tabs")==0 ){
30713 }else if( cli_strcmp(z,"-separator")==0 ){
30716 }else if( cli_strcmp(z,"-newline")==0 ){
30719 }else if( cli_strcmp(z,"-nullvalue")==0 ){
30722 }else if( cli_strcmp(z,"-header")==0 ){
30725 }else if( cli_strcmp(z,"-noheader")==0 ){
30728 }else if( cli_strcmp(z,"-echo")==0 ){
30730 }else if( cli_strcmp(z,"-eqp")==0 ){
30732 }else if( cli_strcmp(z,"-eqpfull")==0 ){
30734 }else if( cli_strcmp(z,"-stats")==0 ){
30736 }else if( cli_strcmp(z,"-scanstats")==0 ){
30738 }else if( cli_strcmp(z,"-backslash")==0 ){
30739 /* Undocumented command-line option: -backslash
30740 ** Causes C-style backslash escapes to be evaluated in SQL statements
30745 }else if( cli_strcmp(z,"-bail")==0 ){
30746 /* No-op. The bail_on_error flag should already be set. */
30747 }else if( cli_strcmp(z,"-version")==0 ){
30748 sputf(stdout, "%s %s (%d-bit)\n",
30751 }else if( cli_strcmp(z,"-interactive")==0 ){
30756 }else if( cli_strcmp(z,"-batch")==0 ){
30758 }else if( cli_strcmp(z,"-utf8")==0 ){
30760 }else if( cli_strcmp(z,"-no-utf8")==0 ){
30762 }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
30764 }else if( cli_strcmp(z,"-heap")==0 ){
30766 }else if( cli_strcmp(z,"-pagecache")==0 ){
30768 }else if( cli_strcmp(z,"-lookaside")==0 ){
30770 }else if( cli_strcmp(z,"-threadsafe")==0 ){
30772 }else if( cli_strcmp(z,"-nonce")==0 ){
30774 }else if( cli_strcmp(z,"-mmap")==0 ){
30776 }else if( cli_strcmp(z,"-memtrace")==0 ){
30778 }else if( cli_strcmp(z,"-pcachetrace")==0 ){
30781 }else if( cli_strcmp(z,"-sorterref")==0 ){
30784 }else if( cli_strcmp(z,"-vfs")==0 ){
30787 }else if( cli_strcmp(z,"-vfstrace")==0 ){
30791 }else if( cli_strcmp(z,"-multiplex")==0 ){
30794 }else if( cli_strcmp(z,"-help")==0 ){
30796 }else if( cli_strcmp(z,"-cmd")==0 ){
30797 /* Run commands that follow -cmd first and separately from commands
30798 ** that simply appear on the command-line. This seems goofy. It would
30801 if( i==argc-1 ) break;
30818 }else if( cli_strncmp(z, "-A", 2)==0 ){
30820 eputf("Error: cannot mix regular SQL or dot-commands"
30827 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
30829 arDotCommand(&data, 1, argv+i, argc-i);
30834 }else if( cli_strcmp(z,"-safe")==0 ){
30836 }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
30840 eputz("Use -help for a list of options.\n");
30847 /* Run all arguments that do not begin with '-' as if they were separate
30848 ** command-line inputs, except for the argToSkip argument which contains
30882 # define SHELL_CIO_CHAR_SET (stdout_is_console? " (UTF-16 console I/O)" : "")
30886 sputf(stdout, "SQLite version %s %.19s%s\n" /*extra-version-info*/
30891 printBold("transient in-memory database");
30933 session_close_all(&data, -1);
30959 (unsigned int)(sqlite3_memory_used()-mem_main_enter));
31021 ** Completely wipes out the contents of the currently-opened database
31033 oputz("Rolling back in-progress transaction.\n");
31046 ** on success, non-0 on error. This function returns 0 on success,
31047 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
31048 ** code from the callback. Note that this is not thread-friendly: it
31063 rc = pFile->pMethods->xFileSize(pFile, &nSize);
31075 rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);