Lines Matching +full:d3 +full:- +full:hierarchy
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.
238 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
240 * overridden with the -batch command line option.
286 ** by the SQLite project command-line tools. These interfaces are used
289 ** "single-source" forms or separate compilation then linking.
329 ** Returns the bit-wise OR of SAC_{In,Out,Err}Console values,
333 ** the given streams. As a side-effect, the given inputs are
359 ** Undo any side-effects left by consoleClassifySetup(...).
409 ** console and translation from UTF-8 is necessary, perform
411 ** to the provided stream almost as-is, possibly with newline
422 ** console and translation from UTF-8 is necessary, perform
424 ** provided stream almost as-is, possibly with newline
472 ** An additional side-effect is that if the stream is one passed
493 ** line-editing library or simple console interaction.
505 ** SHELL_ADD_HISTORY(T) as record-worthy input is taken;
525 ** This function may call upon services of a line-editing
534 ** completion candidates for use by the line-editor.
537 ** that does this. Yet, getting line-editing melded into
538 ** console I/O is desirable because a line-editing library
544 /* Skip over as much z[] input char sequence as is valid UTF-8,
547 ** sequence z:return (inclusive:exclusive) is validated UTF-8.
569 ** by the SQLite project command-line tools, as explained in console_io.h .
608 /* Character used to represent a known-incomplete UTF-8 char group (�) */
634 /* Define NULL-like value for things which can validly be 0. */
650 return (ppst->hx != INVALID_HANDLE_VALUE); in pstReachesConsole()
658 if( pstReachesConsole(ppst) ) SetConsoleMode(ppst->hx, ppst->consMode); in restoreConsoleArb()
670 ppst->pf = pf; in streamOfConsole()
674 ppst->hx = (rv)? fh : INVALID_HANDLE_VALUE; in streamOfConsole()
675 ppst->consMode = dwCM; in streamOfConsole()
678 ppst->pf = pf; in streamOfConsole()
679 ppst->reachesConsole = ( (short)isatty(fileno(pf)) ); in streamOfConsole()
680 return ppst->reachesConsole; in streamOfConsole()
700 return (ppst->pf != SHELL_INVALID_FILE_PTR); in isValidStreamInfo()
715 SetConsoleMode(ppst->hx, cm); in maybeSetupAsConsole()
727 &consoleInfo.pstSetup[ix] : &consoleInfo.pstDesignated[ix-3]; in consoleRenewSetup()
739 for( ix = 2; ix >= 0; --ix ){ in consoleClassifySetup()
755 if( pci->sacSetup ){ in consoleRestore()
758 if( pci->sacSetup & (SAC_InConsole<<ix) ){ in consoleRestore()
759 PerStreamTags *ppst = &pci->pstSetup[ix]; in consoleRestore()
760 SetConsoleMode(ppst->hx, ppst->consMode); in consoleRestore()
780 if( apst[ix]->pf == pf ) break; in isKnownReadable()
799 if( apst[ix]->pf == pf ) break; in isKnownWritable()
864 /* Translation from UTF-8 to UTF-16, then WCHARs out. */ in conZstrEmit()
865 if( WriteConsoleW(ppst->hx, zw,nwc, 0, NULL) ){ in conZstrEmit()
900 ** In either case, ppst references a caller-owned PerStreamTags
914 pfEmit = ppst->pf; in getEmitStreamInfo()
915 }else pfEmit = ppstTry->pf; in getEmitStreamInfo()
996 if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst); in fPrintfUtf8()
1020 if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst); in fPutsUtf8()
1071 /* Skip over as much z[] input char sequence as is valid UTF-8,
1074 ** sequence z:return (inclusive:exclusive) is validated UTF-8.
1079 int ng = (nAccept<0)? -nAccept : 0; in zSkipValidUtf8()
1082 while( (pcLimit)? (z<pcLimit) : (ng-- != 0) ){ in zSkipValidUtf8()
1094 if( ct==0 || (zt-z)>4 || (ct & 0xC0)!=0x80 ){ in zSkipValidUtf8()
1120 if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst); in fPutbUtf8()
1179 while( noc < ncMax-8-1 && !lend ){ in fGetsUtf8()
1180 /* There is room for at least 2 more characters and a 0-terminator. */ in fGetsUtf8()
1181 int na = (ncMax > SHELL_GULP*4+1 + noc)? SHELL_GULP : (ncMax-1 - noc)/4; in fGetsUtf8()
1185 if( bRC && nbr>0 && (wcBuf[nbr-1]&0xF800)==0xD800 ){ in fGetsUtf8()
1186 /* Last WHAR read is first of a UTF-16 surrogate pair. Grab its mate. */ in fGetsUtf8()
1198 /* Fixup line-ends as coded by Windows for CR (or "Enter".) in fGetsUtf8()
1203 if( cBuf[noc-1]=='\n' ){ in fGetsUtf8()
1205 if( noc > 1 && cBuf[noc-2]=='\r' ) cBuf[--noc-1] = '\n'; in fGetsUtf8()
1220 /* If got nothing, (after ^Z chop), must be at end-of-file. */ in fGetsUtf8()
1244 * sputz(s, z) => emit 0-terminated string z to given stream s
1246 * oputz(z) => emit 0-terminated string z to default stream
1248 * eputz(z) => emit 0-terminated string z to error stream
1250 * oputb(b, n) => emit char buffer b[0..n-1] to default stream
1255 * For the stand-alone CLI, it is stdout with no .output redirect.
1290 /* Return the current wall-clock time */
1296 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){ in timeOfDay()
1297 clockVfs->xCurrentTimeInt64(clockVfs, &t); in timeOfDay()
1300 clockVfs->xCurrentTime(clockVfs, &r); in timeOfDay()
1321 static sqlite3_int64 iBegin; /* Wall-clock time at start */
1335 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + in timeDiff()
1336 (double)(pEnd->tv_sec - pStart->tv_sec); in timeDiff()
1348 (iEnd - iBegin)*0.001, in endTimer()
1415 return (double) ((i64End - i64Start) / 10000000.0); in timeDiff()
1427 (ftWallEnd - ftWallBegin)*0.001, in endTimer()
1467 ** in order to show that UTF-16 translation is done in the sign-on
1480 ** True if an interrupt (Control-C) has been received.
1500 /* This is variant of the standard-library strncpy() routine with the
1501 ** one change that the destination string is always zero-terminated, even
1502 ** if there is no zero-terminator in the first n-1 characters of the source
1507 for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i]; in shell_strncpy()
1515 ** or open parentheses level if non-zero, or continuation prompt as set.
1551 p->inParenLevel += ni; in trackParenLevel()
1552 if( ni==0 ) p->inParenLevel = 0; in trackParenLevel()
1553 p->zScannerAwaits = 0; in trackParenLevel()
1559 p->zScannerAwaits = s; in setLexemeOpen()
1560 p->acAwait[0] = 0; in setLexemeOpen()
1562 p->acAwait[0] = c; in setLexemeOpen()
1563 p->zScannerAwaits = p->acAwait; in setLexemeOpen()
1576 if( ndp > ncp-3 ) return continuePrompt; in dynamicContinuePrompt()
1580 PROMPT_LEN_MAX-4); in dynamicContinuePrompt()
1591 PROMPT_LEN_MAX-4); in dynamicContinuePrompt()
1598 /* Indicate out-of-memory and exit. */
1605 ** out-of-memory error.
1639 ** then right-justify the text. W is the width in UTF-8 characters, not
1646 int aw = w<0 ? -w : w; in utf8_width_print()
1660 oputf("%*s%s", aw-n, "", zUtf); in utf8_width_print()
1662 oputf("%s%*s", zUtf, aw-n, ""); in utf8_width_print()
1671 if( *z=='-' || *z=='+' ) z++; in isNumber()
1686 if( *z=='+' || *z=='-' ) z++; in isNumber()
1696 ** lower 30 bits of a 32-bit signed integer.
1701 return 0x3fffffff & (int)(z2 - z); in strlen30()
1769 if( fgets(&zLine[n], nLine - n, in)==0 ){ in local_getline()
1778 if( n>0 && zLine[n-1]=='\n' ){ in local_getline()
1779 n--; in local_getline()
1780 if( n>0 && zLine[n-1]=='\r' ) n--; in local_getline()
1836 ** Return the value of a hexadecimal digit. Return -1 if the input
1840 if( c>='0' && c<='9' ) return c - '0'; in hexDigitValue()
1841 if( c>='a' && c<='f' ) return c - 'a' + 10; in hexDigitValue()
1842 if( c>='A' && c<='F' ) return c - 'A' + 10; in hexDigitValue()
1843 return -1; in hexDigitValue()
1864 if( zArg[0]=='-' ){ in integerValue()
1879 v = v*10 + zArg[0] - '0'; in integerValue()
1889 return isNeg? -v : v; in integerValue()
1909 free(p->z); in freeText()
1913 /* zIn is either a pointer to a NULL-terminated string in memory obtained
1926 len = nAppend+p->n+1; in appendText()
1934 if( p->z==0 || p->n+len>=p->nAlloc ){ in appendText()
1935 p->nAlloc = p->nAlloc*2 + len + 20; in appendText()
1936 p->z = realloc(p->z, p->nAlloc); in appendText()
1937 shell_check_oom(p->z); in appendText()
1941 char *zCsr = p->z+p->n; in appendText()
1948 p->n = (int)(zCsr - p->z); in appendText()
1951 memcpy(p->z+p->n, zAppend, nAppend); in appendText()
1952 p->n += nAppend; in appendText()
1953 p->z[p->n] = '\0'; in appendText()
1959 ** because it contains non-alphanumeric characters, or because it is an
1994 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); in shellFakeSchema()
2026 ** Use the C-library strtod() function to convert string X into a double.
2027 ** Used for comparing the accuracy of SQLite's internal text-to-float conversion
2028 ** routines against the C-library.
2044 ** Use the C-library printf() function to convert real value X into a string.
2045 ** Used for comparing the accuracy of SQLite's internal float-to-text conversion
2046 ** routines against the C-library.
2059 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); in shellDtostr()
2066 ** Return a fake schema for the table-valued function or eponymous virtual
2081 -1, sqlite3_free); in shellModuleSchema()
2092 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
2150 sqlite3_result_text(pCtx, z, -1, sqlite3_free); in shellAddSchemaName()
2160 ** The source code for several run-time loadable extensions is inserted
2271 # define BAD_INTPTR_T ((intptr_t)(-1))
2313 ** function. This function is not thread-safe.
2352 ** This function is not thread-safe.
2365 ** The function call to GetEnvironmentVariableA() failed -OR- in windirent_getenv()
2372 ** -AND- the buffer contains the entire value. in windirent_getenv()
2391 /* TODO: Remove this if Unix-style root paths are not used. */ in opendir()
2398 dirp->d_handle = _findfirst(data.name, &data); in opendir()
2400 if( dirp->d_handle==BAD_INTPTR_T ){ in opendir()
2410 if( _findnext(dirp->d_handle, &data)==-1 ){ in opendir()
2419 dirp->d_first.d_attributes = data.attrib; in opendir()
2420 strncpy(dirp->d_first.d_name, data.name, NAME_MAX); in opendir()
2421 dirp->d_first.d_name[NAME_MAX] = '\0'; in opendir()
2436 if( dirp->d_first.d_ino==0 ){ in readdir()
2437 dirp->d_first.d_ino++; in readdir()
2438 dirp->d_next.d_ino++; in readdir()
2440 return &dirp->d_first; in readdir()
2446 if( _findnext(dirp->d_handle, &data)==-1 ) return NULL; in readdir()
2451 dirp->d_next.d_ino++; in readdir()
2452 dirp->d_next.d_attributes = data.attrib; in readdir()
2453 strncpy(dirp->d_next.d_name, data.name, NAME_MAX); in readdir()
2454 dirp->d_next.d_name[NAME_MAX] = '\0'; in readdir()
2456 return &dirp->d_next; in readdir()
2471 if( dirp->d_first.d_ino==0 ){ in readdir_r()
2472 dirp->d_first.d_ino++; in readdir_r()
2473 dirp->d_next.d_ino++; in readdir_r()
2475 entry->d_ino = dirp->d_first.d_ino; in readdir_r()
2476 entry->d_attributes = dirp->d_first.d_attributes; in readdir_r()
2477 strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX); in readdir_r()
2478 entry->d_name[NAME_MAX] = '\0'; in readdir_r()
2487 if( _findnext(dirp->d_handle, &data)==-1 ){ in readdir_r()
2495 entry->d_ino = (ino_t)-1; /* not available */ in readdir_r()
2496 entry->d_attributes = data.attrib; in readdir_r()
2497 strncpy(entry->d_name, data.name, NAME_MAX); in readdir_r()
2498 entry->d_name[NAME_MAX] = '\0'; in readdir_r()
2514 if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){ in closedir()
2515 result = _findclose(dirp->d_handle); in closedir()
2529 ** 2019-01-21
2548 ** This extension is used to implement the --memtrace option of the
2549 ** command-line shell.
2581 fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n", in memtraceRealloc()
2640 ** 2023-06-21
2659 ** This extension is used to implement the --pcachetrace option of the
2660 ** command-line shell.
2678 fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p) -> %d\n", pArg, nRes); in pcachetraceInit()
2696 fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d) -> %p\n", in pcachetraceCreate()
2714 fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p) -> %d\n", p, nRes); in pcachetracePagecount()
2729 fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d) -> %p\n", in pcachetraceFetch()
2822 ** 2017-03-08
2834 ** in the way described by the (U.S.) NIST FIPS 202 SHA-3 Standard.
2846 ** The SIZE argument is optional. If omitted, the SHA3-256 hash algorithm
2865 ** and whether or not that determination is run-time or compile-time.
2867 ** For best performance, an attempt is made to guess at the byte-order
2868 ** using C-preprocessor macros. If that is unsuccessful, or if
2869 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
2870 ** at run-time.
2901 ** A single step of the Keccak mixing function for a 1600-bit state
2907 u64 d0, d1, d2, d3, d4; in KeccakF1600Step() local
2922 # define a00 (p->u.s[0]) in KeccakF1600Step()
2923 # define a01 (p->u.s[1]) in KeccakF1600Step()
2924 # define a02 (p->u.s[2]) in KeccakF1600Step()
2925 # define a03 (p->u.s[3]) in KeccakF1600Step()
2926 # define a04 (p->u.s[4]) in KeccakF1600Step()
2927 # define a10 (p->u.s[5]) in KeccakF1600Step()
2928 # define a11 (p->u.s[6]) in KeccakF1600Step()
2929 # define a12 (p->u.s[7]) in KeccakF1600Step()
2930 # define a13 (p->u.s[8]) in KeccakF1600Step()
2931 # define a14 (p->u.s[9]) in KeccakF1600Step()
2932 # define a20 (p->u.s[10]) in KeccakF1600Step()
2933 # define a21 (p->u.s[11]) in KeccakF1600Step()
2934 # define a22 (p->u.s[12]) in KeccakF1600Step()
2935 # define a23 (p->u.s[13]) in KeccakF1600Step()
2936 # define a24 (p->u.s[14]) in KeccakF1600Step()
2937 # define a30 (p->u.s[15]) in KeccakF1600Step()
2938 # define a31 (p->u.s[16]) in KeccakF1600Step()
2939 # define a32 (p->u.s[17]) in KeccakF1600Step()
2940 # define a33 (p->u.s[18]) in KeccakF1600Step()
2941 # define a34 (p->u.s[19]) in KeccakF1600Step()
2942 # define a40 (p->u.s[20]) in KeccakF1600Step()
2943 # define a41 (p->u.s[21]) in KeccakF1600Step()
2944 # define a42 (p->u.s[22]) in KeccakF1600Step()
2945 # define a43 (p->u.s[23]) in KeccakF1600Step()
2946 # define a44 (p->u.s[24]) in KeccakF1600Step()
2947 # define ROL64(a,x) ((a<<x)|(a>>(64-x))) in KeccakF1600Step()
2958 d3 = c2^ROL64(c4, 1); in KeccakF1600Step()
2964 b3 = ROL64((a33^d3), 21); in KeccakF1600Step()
2976 b0 = ROL64((a03^d3), 28); in KeccakF1600Step()
2987 b2 = ROL64((a23^d3), 25); in KeccakF1600Step()
2998 b4 = ROL64((a43^d3), 56); in KeccakF1600Step()
3009 b1 = ROL64((a13^d3), 55); in KeccakF1600Step()
3025 d3 = c2^ROL64(c4, 1); in KeccakF1600Step()
3031 b3 = ROL64((a43^d3), 21); in KeccakF1600Step()
3043 b0 = ROL64((a33^d3), 28); in KeccakF1600Step()
3054 b2 = ROL64((a23^d3), 25); in KeccakF1600Step()
3065 b4 = ROL64((a13^d3), 56); in KeccakF1600Step()
3076 b1 = ROL64((a03^d3), 55); in KeccakF1600Step()
3092 d3 = c2^ROL64(c4, 1); in KeccakF1600Step()
3098 b3 = ROL64((a13^d3), 21); in KeccakF1600Step()
3110 b0 = ROL64((a43^d3), 28); in KeccakF1600Step()
3121 b2 = ROL64((a23^d3), 25); in KeccakF1600Step()
3132 b4 = ROL64((a03^d3), 56); in KeccakF1600Step()
3143 b1 = ROL64((a33^d3), 55); in KeccakF1600Step()
3159 d3 = c2^ROL64(c4, 1); in KeccakF1600Step()
3165 b3 = ROL64((a03^d3), 21); in KeccakF1600Step()
3177 b0 = ROL64((a13^d3), 28); in KeccakF1600Step()
3188 b2 = ROL64((a23^d3), 25); in KeccakF1600Step()
3199 b4 = ROL64((a33^d3), 56); in KeccakF1600Step()
3210 b1 = ROL64((a43^d3), 55); in KeccakF1600Step()
3228 p->nRate = (1600 - ((iSize + 31)&~31)*2)/8; in SHA3Init()
3230 p->nRate = (1600 - 2*256)/8; in SHA3Init()
3233 /* Known to be little-endian at compile-time. No-op */ in SHA3Init()
3235 p->ixMask = 7; /* Big-endian */ in SHA3Init()
3241 p->ixMask = 0; in SHA3Init()
3244 p->ixMask = 7; in SHA3Init()
3262 if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){ in SHA3Update()
3264 p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i]; in SHA3Update()
3265 p->nLoaded += 8; in SHA3Update()
3266 if( p->nLoaded>=p->nRate ){ in SHA3Update()
3268 p->nLoaded = 0; in SHA3Update()
3275 p->u.x[p->nLoaded] ^= aData[i]; in SHA3Update()
3277 p->u.x[p->nLoaded^0x07] ^= aData[i]; in SHA3Update()
3279 p->u.x[p->nLoaded^p->ixMask] ^= aData[i]; in SHA3Update()
3281 p->nLoaded++; in SHA3Update()
3282 if( p->nLoaded==p->nRate ){ in SHA3Update()
3284 p->nLoaded = 0; in SHA3Update()
3296 if( p->nLoaded==p->nRate-1 ){ in SHA3Final()
3303 p->nLoaded = p->nRate - 1; in SHA3Final()
3306 for(i=0; i<p->nRate; i++){ in SHA3Final()
3307 p->u.x[i+p->nRate] = p->u.x[i^p->ixMask]; in SHA3Final()
3309 return &p->u.x[p->nRate]; in SHA3Final()
3317 ** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
3319 ** For all other non-NULL types of input, X is converted into a UTF-8 string
3338 "384 512", -1); in sha3Func()
3374 ** argument. The results are hashed using a SIZE-bit SHA3. The default
3383 ** F<ieee-float>
3388 ** the size of that text. The SQL text is UTF-8. A single R character
3390 ** I mean an 8-byte little-endian integer <int>. F is a floating point
3391 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
3393 ** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
3424 "384 512", -1); in sha3QueryFunc()
3431 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql); in sha3QueryFunc()
3436 sqlite3_result_error(context, zMsg, -1); in sha3QueryFunc()
3441 char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt)); in sha3QueryFunc()
3443 sqlite3_result_error(context, zMsg, -1); in sha3QueryFunc()
3470 for(j=8; j>=1; j--){ in sha3QueryFunc()
3484 for(j=8; j>=1; j--){ in sha3QueryFunc()
3550 ** 2020-04-14
3576 ** 64-bit machine integer.
3598 x = zA[i] - zB[j]; in uintCollFunc()
3612 return -1; in uintCollFunc()
3626 return (nKey1 - i) - (nKey2 - j); in uintCollFunc()
3645 ** 2020-06-22
3656 ** Routines to implement arbitrary-precision decimal math.
3690 sqlite3_free(p->a); in decimal_clear()
3714 p->sign = 0; in decimalNewFromText()
3715 p->oom = 0; in decimalNewFromText()
3716 p->isInit = 1; in decimalNewFromText()
3717 p->isNull = 0; in decimalNewFromText()
3718 p->nDigit = 0; in decimalNewFromText()
3719 p->nFrac = 0; in decimalNewFromText()
3720 p->a = sqlite3_malloc64( n+1 ); in decimalNewFromText()
3721 if( p->a==0 ) goto new_from_text_failed; in decimalNewFromText()
3723 if( zIn[i]=='-' ){ in decimalNewFromText()
3724 p->sign = 1; in decimalNewFromText()
3733 p->a[p->nDigit++] = c - '0'; in decimalNewFromText()
3735 p->nFrac = p->nDigit + 1; in decimalNewFromText()
3740 if( zIn[j]=='-' ){ in decimalNewFromText()
3748 iExp = iExp*10 + zIn[j] - '0'; in decimalNewFromText()
3752 if( neg ) iExp = -iExp; in decimalNewFromText()
3757 if( p->nFrac ){ in decimalNewFromText()
3758 p->nFrac = p->nDigit - (p->nFrac - 1); in decimalNewFromText()
3761 if( p->nFrac>0 ){ in decimalNewFromText()
3762 if( iExp<=p->nFrac ){ in decimalNewFromText()
3763 p->nFrac -= iExp; in decimalNewFromText()
3766 iExp -= p->nFrac; in decimalNewFromText()
3767 p->nFrac = 0; in decimalNewFromText()
3771 p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 ); in decimalNewFromText()
3772 if( p->a==0 ) goto new_from_text_failed; in decimalNewFromText()
3773 memset(p->a+p->nDigit, 0, iExp); in decimalNewFromText()
3774 p->nDigit += iExp; in decimalNewFromText()
3778 iExp = -iExp; in decimalNewFromText()
3779 nExtra = p->nDigit - p->nFrac - 1; in decimalNewFromText()
3782 p->nFrac += iExp; in decimalNewFromText()
3785 iExp -= nExtra; in decimalNewFromText()
3786 p->nFrac = p->nDigit - 1; in decimalNewFromText()
3790 p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 ); in decimalNewFromText()
3791 if( p->a==0 ) goto new_from_text_failed; in decimalNewFromText()
3792 memmove(p->a+iExp, p->a, p->nDigit); in decimalNewFromText()
3793 memset(p->a, 0, iExp); in decimalNewFromText()
3794 p->nDigit += iExp; in decimalNewFromText()
3795 p->nFrac += iExp; in decimalNewFromText()
3802 if( p->a ) sqlite3_free(p->a); in decimalNewFromText()
3882 if( p==0 || p->oom ){ in decimal_result()
3886 if( p->isNull ){ in decimal_result()
3890 z = sqlite3_malloc( p->nDigit+4 ); in decimal_result()
3896 if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){ in decimal_result()
3897 p->sign = 0; in decimal_result()
3899 if( p->sign ){ in decimal_result()
3900 z[0] = '-'; in decimal_result()
3903 n = p->nDigit - p->nFrac; in decimal_result()
3908 while( n>1 && p->a[j]==0 ){ in decimal_result()
3910 n--; in decimal_result()
3913 z[i++] = p->a[j] + '0'; in decimal_result()
3915 n--; in decimal_result()
3917 if( p->nFrac ){ in decimal_result()
3920 z[i++] = p->a[j] + '0'; in decimal_result()
3922 }while( j<p->nDigit ); in decimal_result()
3943 if( p==0 || p->oom ){ in decimal_result_sci()
3947 if( p->isNull ){ in decimal_result_sci()
3951 for(nDigit=p->nDigit; nDigit>0 && p->a[nDigit-1]==0; nDigit--){} in decimal_result_sci()
3952 for(nZero=0; nZero<nDigit && p->a[nZero]==0; nZero++){} in decimal_result_sci()
3953 nFrac = p->nFrac + (nDigit - p->nDigit); in decimal_result_sci()
3954 nDigit -= nZero; in decimal_result_sci()
3966 a = &p->a[nZero]; in decimal_result_sci()
3968 if( p->sign && nDigit>0 ){ in decimal_result_sci()
3969 z[0] = '-'; in decimal_result_sci()
3984 exp = nDigit - nFrac - 1; in decimal_result_sci()
3985 sqlite3_snprintf(nDigit+20-i, &z[i], "e%+03d", exp); in decimal_result_sci()
3986 sqlite3_result_text(pCtx, z, -1, sqlite3_free); in decimal_result_sci()
3996 ** pA->isNull==0
3998 ** pB->isNull==0
4002 if( pA->sign!=pB->sign ){ in decimal_cmp()
4003 return pA->sign ? -1 : +1; in decimal_cmp()
4005 if( pA->sign ){ in decimal_cmp()
4010 nASig = pA->nDigit - pA->nFrac; in decimal_cmp()
4011 nBSig = pB->nDigit - pB->nFrac; in decimal_cmp()
4013 return nASig - nBSig; in decimal_cmp()
4015 n = pA->nDigit; in decimal_cmp()
4016 if( n>pB->nDigit ) n = pB->nDigit; in decimal_cmp()
4017 rc = memcmp(pA->a, pB->a, n); in decimal_cmp()
4019 rc = pA->nDigit - pB->nDigit; in decimal_cmp()
4040 if( pA==0 || pA->isNull ) goto cmp_done; in decimalCmpFunc()
4042 if( pB==0 || pB->isNull ) goto cmp_done; in decimalCmpFunc()
4044 if( rc<0 ) rc = -1; in decimalCmpFunc()
4060 nAddFrac = nFrac - p->nFrac; in decimal_expand()
4061 nAddSig = (nDigit - p->nDigit) - nAddFrac; in decimal_expand()
4063 p->a = sqlite3_realloc64(p->a, nDigit+1); in decimal_expand()
4064 if( p->a==0 ){ in decimal_expand()
4065 p->oom = 1; in decimal_expand()
4069 memmove(p->a+nAddSig, p->a, p->nDigit); in decimal_expand()
4070 memset(p->a, 0, nAddSig); in decimal_expand()
4071 p->nDigit += nAddSig; in decimal_expand()
4074 memset(p->a+p->nDigit, 0, nAddFrac); in decimal_expand()
4075 p->nDigit += nAddFrac; in decimal_expand()
4076 p->nFrac += nAddFrac; in decimal_expand()
4091 if( pA->oom || pB==0 || pB->oom ){ in decimal_add()
4092 pA->oom = 1; in decimal_add()
4095 if( pA->isNull || pB->isNull ){ in decimal_add()
4096 pA->isNull = 1; in decimal_add()
4099 nSig = pA->nDigit - pA->nFrac; in decimal_add()
4100 if( nSig && pA->a[0]==0 ) nSig--; in decimal_add()
4101 if( nSig<pB->nDigit-pB->nFrac ){ in decimal_add()
4102 nSig = pB->nDigit - pB->nFrac; in decimal_add()
4104 nFrac = pA->nFrac; in decimal_add()
4105 if( nFrac<pB->nFrac ) nFrac = pB->nFrac; in decimal_add()
4109 if( pA->oom || pB->oom ){ in decimal_add()
4110 pA->oom = 1; in decimal_add()
4112 if( pA->sign==pB->sign ){ in decimal_add()
4114 for(i=nDigit-1; i>=0; i--){ in decimal_add()
4115 int x = pA->a[i] + pB->a[i] + carry; in decimal_add()
4118 pA->a[i] = x - 10; in decimal_add()
4121 pA->a[i] = x; in decimal_add()
4127 rc = memcmp(pA->a, pB->a, nDigit); in decimal_add()
4129 aA = pB->a; in decimal_add()
4130 aB = pA->a; in decimal_add()
4131 pA->sign = !pA->sign; in decimal_add()
4133 aA = pA->a; in decimal_add()
4134 aB = pB->a; in decimal_add()
4136 for(i=nDigit-1; i>=0; i--){ in decimal_add()
4137 int x = aA[i] - aB[i] - borrow; in decimal_add()
4139 pA->a[i] = x+10; in decimal_add()
4142 pA->a[i] = x; in decimal_add()
4163 if( pA==0 || pA->oom || pA->isNull in decimalMul()
4164 || pB==0 || pB->oom || pB->isNull in decimalMul()
4168 acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 ); in decimalMul()
4170 pA->oom = 1; in decimalMul()
4173 memset(acc, 0, pA->nDigit + pB->nDigit + 2); in decimalMul()
4174 minFrac = pA->nFrac; in decimalMul()
4175 if( pB->nFrac<minFrac ) minFrac = pB->nFrac; in decimalMul()
4176 for(i=pA->nDigit-1; i>=0; i--){ in decimalMul()
4177 signed char f = pA->a[i]; in decimalMul()
4179 for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){ in decimalMul()
4180 x = acc[k] + f*pB->a[j] + carry; in decimalMul()
4186 acc[k-1] += x/10; in decimalMul()
4188 sqlite3_free(pA->a); in decimalMul()
4189 pA->a = acc; in decimalMul()
4191 pA->nDigit += pB->nDigit + 2; in decimalMul()
4192 pA->nFrac += pB->nFrac; in decimalMul()
4193 pA->sign ^= pB->sign; in decimalMul()
4194 while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){ in decimalMul()
4195 pA->nFrac--; in decimalMul()
4196 pA->nDigit--; in decimalMul()
4209 if( N<-20000 || N>20000 ) goto pow2_fault; in decimalPow2()
4211 if( pA==0 || pA->oom ) goto pow2_fault; in decimalPow2()
4216 N = -N; in decimalPow2()
4219 if( pX==0 || pX->oom ) goto pow2_fault; in decimalPow2()
4223 if( pA->oom ) goto pow2_fault; in decimalPow2()
4250 r = -r; in decimalFromDouble()
4260 m = a & ((((sqlite3_int64)1)<<52)-1); in decimalFromDouble()
4270 if( isNeg ) m = -m; in decimalFromDouble()
4271 e = e - 1075; in decimalFromDouble()
4293 ** point value is done. Or if X is an 8-byte blob, it is interpreted
4369 pB->sign = !pB->sign; in decimalSubFunc()
4392 if( !p->isInit ){ in decimalSumStep()
4393 p->isInit = 1; in decimalSumStep()
4394 p->a = sqlite3_malloc(2); in decimalSumStep()
4395 if( p->a==0 ){ in decimalSumStep()
4396 p->oom = 1; in decimalSumStep()
4398 p->a[0] = 0; in decimalSumStep()
4400 p->nDigit = 1; in decimalSumStep()
4401 p->nFrac = 0; in decimalSumStep()
4420 if( pArg ) pArg->sign = !pArg->sign; in decimalSumInverse()
4449 if( pA==0 || pA->oom || pA->isNull in decimalMulFunc()
4450 || pB==0 || pB->oom || pB->isNull in decimalMulFunc()
4455 if( pA->oom ){ in decimalMulFunc()
4468 ** Return the N-th power of 2. N must be an integer.
4534 ** 2022-11-18
4548 ** written as TCL brace-enclosed literals or SQL string literals,
4549 ** and can be used unmodified in XML-like documents.
4556 ** C source specifies that line-feeds are included in the encoded
4558 ** terminate any encoded blob having non-zero length.
4563 ** Generated base64 sequences, with their line-feeds included,
4572 ** This code relies on UTF-8 encoding only with respect to the
4573 ** meaning of the first 128 (7-bit) codes matching that of USASCII.
4575 ** Because it is table-driven, it could be enhanced to handle that,
4580 ** *Nix: gcc -O2 -shared -I$SQDIR -fPIC -o base64.so base64.c
4581 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o base64.dylib base64.c
4582 ** Win32: gcc -O2 -shared -I%SQDIR% -o base64.dll base64.c
4583 ** Win32: cl /Os -I%SQDIR% base64.c -link -dll -out:base64.dll
4603 #define ND 0x82 /* Not above or digit-value */
4611 /* Decoding table, ASCII (7-bit) value to base 64 digit value or other */
4649 /* Do the bit-shuffle, exploiting unsigned input to avoid masking. */ in toBase64()
4655 nbIn -= 3; in toBase64()
4670 for( nbe=3; nbe>=0; --nbe ){ in toBase64()
4685 while( nc-- > 0 && (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s; in skipNonB64()
4691 if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn; in fromBase64()
4697 ncIn -= (pUse - pIn); in fromBase64()
4700 ncIn -= nti; in fromBase64()
4708 /* Treat dark non-digits as pad, but they terminate decode too. */ in fromBase64()
4717 --nbo; in fromBase64()
4741 SQLITE_LIMIT_LENGTH, -1); in base64()
4749 nc += (nc+(B64_DARK_MAX-1))/B64_DARK_MAX + 1; /* LFs and a 0-terminator */ in base64()
4751 sqlite3_result_error(context, "blob expanded to base64 too big", -1); in base64()
4759 sqlite3_result_text(context,"",-1,SQLITE_STATIC); in base64()
4764 nc = (int)(toBase64(bBuf, nb, cBuf) - cBuf); in base64()
4771 sqlite3_result_error(context, "blob from base64 may be too big", -1); in base64()
4786 nb = (int)(fromBase64(cBuf, nc, bBuf) - bBuf); in base64()
4790 sqlite3_result_error(context, "base64 accepts only blob or text", -1); in base64()
4795 sqlite3_result_error(context, "base64 OOM", -1); in base64()
4832 ** 2022-11-16
4843 ** This is a utility for converting binary to base85 or vice-versa.
4848 ** written as TCL brace-enclosed literals or SQL string literals.
4849 ** It is not suited for unmodified use in XML-like documents.
4857 ** Base85 numerals are taken from the set of 7-bit USASCII codes,
4861 ** Groups of 4 bytes, interpreted as big-endian 32-bit values,
4862 ** are represented as 5-digit base85 numbers with MS to LS digit
4863 ** order. Groups of 1-3 bytes are represented with 2-4 digits,
4864 ** still big-endian but 8-24 bit values. (Using big-endian yields
4866 ** These byte groups can also be considered base-256 numbers.)
4867 ** Groups of 0 bytes are represented with 0 digits and vice-versa.
4869 ** (aka "group") length maps 1-to-1 to the decoded binary length.
4873 ** size, newline is used to separate it into sub-sequences of no
4880 ** a non-base85 character; the conversion to binary will then
4896 ** and variable OPTS to -DOMIT_BASE85_CHECKER if is_base85() unwanted.
4897 ** *Nix: gcc -O2 -shared -I$SQDIR $OPTS -fPIC -o base85.so base85.c
4898 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR $OPTS -o base85.dylib base85.c
4899 ** Win32: gcc -O2 -shared -I%SQDIR% %OPTS% -o base85.dll base85.c
4900 ** Win32: cl /Os -I%SQDIR% %OPTS% base85.c -link -dll -out:base85.dll
4903 ** *Nix or OSX: gcc -O2 -DBASE85_STANDALONE base85.c -o base85
4904 ** Win32: gcc -O2 -DBASE85_STANDALONE -o base85.exe base85.c
4905 ** Win32: cl /Os /MD -DBASE85_STANDALONE base85.c
4933 " <dirFlag> is either -r to read or -w to write <binFile>,\n"
4936 " Or, the name '-' refers to the stdin or stdout stream.\n"
4955 static u8 b85_cOffset[] = { 0, '#', 0, '*'-4, 0 };
4963 u8 dv = (u8)(c - '#');
4965 return (dv > 3)? dv-3 : dv;
4975 while( nc-- > 0 && (c = *s) && !IS_B85(c) ) ++s; in skipNonB85()
4980 * Do not use the macro form with argument expression having a side-effect.*/
4983 return (b < 4)? (char)(b + '#') : (char)(b - 4 + '*');
4987 ((char)(((dn) < 4)? (char)((dn) + '#') : (char)((dn) - 4 + '*')))
5008 unsigned char dv = qbv - 85UL*nqv; in toBase85()
5010 pOut[--nco] = base85Numeral(dv); in toBase85()
5012 nbIn -= 4; in toBase85()
5031 pOut[--nco] = base85Numeral(dv); in toBase85()
5042 if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn; in fromBase85()
5048 ncIn -= (pUse - pIn); in fromBase85()
5056 --ncIn; in fromBase85()
5058 qv = 85 * qv + (c - cdo); in fromBase85()
5059 --nti; in fromBase85()
5061 nbo -= nti; /* Adjust for early (non-digit) end of group. */ in fromBase85()
5082 while( len-- > 0 && (c = *p++) != 0 ){ in allBase85()
5107 sqlite3_result_error(context, "is_base85 accepts only text or NULL", -1); in is_base85()
5117 SQLITE_LIMIT_LENGTH, -1); in base85()
5127 sqlite3_result_error(context, "blob expanded to base85 too big", -1); in base85()
5135 sqlite3_result_text(context,"",-1,SQLITE_STATIC); in base85()
5140 nc = (int)(toBase85(bBuf, nb, cBuf, "\n") - cBuf); in base85()
5147 sqlite3_result_error(context, "blob from base85 may be too big", -1); in base85()
5162 nb = (int)(fromBase85(cBuf, nc, bBuf) - bBuf); in base85()
5166 sqlite3_result_error(context, "base85 accepts only blob or text.", -1); in base85()
5171 sqlite3_result_error(context, "base85 OOM", -1); in base85()
5225 if( na < 3 || av[1][0]!='-' || (rw = av[1][1])==0 || (rw!='r' && rw!='w') ){ in main()
5230 if( av[2][0]=='-' && av[2][1]==0 ){ in main()
5259 size_t nbo = fromBase85( cBuf, nc, bBuf ) - bBuf; in main()
5274 fprintf(stderr, "Base85 input had non-base85 dark or control content.\n"); in main()
5285 ** 2013-04-17
5297 ** and input of IEEE754 Binary64 floating-point numbers.
5302 ** In the first form, the value X should be a floating-point number.
5307 ** base-2 exponent of a new floating point number. The function returns
5308 ** a floating-point value equal to Y*pow(2,Z).
5312 ** ieee754(2.0) -> 'ieee754(2,0)'
5313 ** ieee754(45.25) -> 'ieee754(181,-2)'
5314 ** ieee754(2, 0) -> 2.0
5315 ** ieee754(181, -2) -> 45.25
5317 ** Two additional functions break apart the one-argument ieee754()
5320 ** ieee754_mantissa(45.25) -> 181
5321 ** ieee754_exponent(45.25) -> -2
5325 ** ieee754_from_blob(x'3ff0000000000000') -> 1.0
5326 ** ieee754_to_blob(1.0) -> x'3ff0000000000000'
5328 ** In all single-argument functions, if the argument is an 8-byte blob
5329 ** then that blob is interpreted as a big-endian binary64 value.
5333 ** -----------------------------------------------
5346 ** VALUES(-1,'0.5')
5348 ** SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
5355 ** ---------------^^^^^---- Replace with whatever you want
5412 r = -r; in ieee754func()
5422 m = a & ((((sqlite3_int64)1)<<52)-1); in ieee754func()
5432 if( isNeg ) m = -m; in ieee754func()
5437 m, e-1075); in ieee754func()
5438 sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT); in ieee754func()
5444 sqlite3_result_int(context, e-1075); in ieee754func()
5454 /* Limit the range of e. Ticket 22dea1cfdb9151e4 2021-03-02 */ in ieee754func()
5457 }else if( e<-10000 ){ in ieee754func()
5458 e = -10000; in ieee754func()
5463 m = -m; in ieee754func()
5465 }else if( m==0 && e>-1000 && e<1000 ){ in ieee754func()
5475 e--; in ieee754func()
5480 if( 1-e >= 64 ){ in ieee754func()
5483 m >>= 1-e; in ieee754func()
5489 a = m & ((((sqlite3_int64)1)<<52)-1); in ieee754func()
5535 a[sizeof(r)-i] = v&0xff; in ieee754func_to_blob()
5548 ** Behind the scenes: this routine merely casts r into a 64-bit unsigned
5612 ** 2015-08-18, 2023-04-28
5623 ** This file demonstrates how to create a table-valued-function using
5626 ** within the limitation that its arguments are signed 64-bit integers.
5630 ** ( V[n] == start + n * step && sgn(V[n] - stop) * sgn(step) >= 0 )
5635 ** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
5653 ** SELECT * FROM generate_series(0,-100,-5);
5655 ** Integers 0 -5 -10 ... -100.
5657 ** SELECT * FROM generate_series(0,-1);
5702 ** series are well-defined.
5712 ** Return that member of a generate_series(...) sequence whose 0-based
5721 ix -= (sqlite3_uint64)LLONG_MAX; in genSeqMember()
5725 smBase += (LLONG_MAX - LLONG_MAX/2) * smStep; in genSeqMember()
5732 ix -= ix2; in genSeqMember()
5757 pss->uSeqIndexMax = 0; in setupSequence()
5758 pss->isNotEOF = 0; in setupSequence()
5759 bSameSigns = (pss->iBase < 0)==(pss->iTerm < 0); in setupSequence()
5760 if( pss->iTerm < pss->iBase ){ in setupSequence()
5763 nuspan = (sqlite3_uint64)(pss->iBase - pss->iTerm); in setupSequence()
5768 nuspan += pss->iBase; in setupSequence()
5769 nuspan += -(pss->iTerm+1); in setupSequence()
5771 if( pss->iStep<0 ){ in setupSequence()
5772 pss->isNotEOF = 1; in setupSequence()
5774 pss->uSeqIndexMax = ( pss->iStep>LLONG_MIN )? nuspan/-pss->iStep : 1; in setupSequence()
5775 }else if( pss->iStep>LLONG_MIN ){ in setupSequence()
5776 pss->uSeqIndexMax = nuspan/-pss->iStep; in setupSequence()
5779 }else if( pss->iTerm > pss->iBase ){ in setupSequence()
5782 puspan = (sqlite3_uint64)(pss->iTerm - pss->iBase); in setupSequence()
5787 puspan += pss->iTerm; in setupSequence()
5788 puspan += -(pss->iBase+1); in setupSequence()
5790 if( pss->iStep>0 ){ in setupSequence()
5791 pss->isNotEOF = 1; in setupSequence()
5792 pss->uSeqIndexMax = puspan/pss->iStep; in setupSequence()
5794 }else if( pss->iTerm == pss->iBase ){ in setupSequence()
5795 pss->isNotEOF = 1; in setupSequence()
5796 pss->uSeqIndexMax = 0; in setupSequence()
5798 pss->uSeqIndexNow = (pss->isReversing)? pss->uSeqIndexMax : 0; in setupSequence()
5799 pss->iValueNow = (pss->isReversing) in setupSequence()
5800 ? genSeqMember(pss->iBase, pss->iStep, pss->uSeqIndexMax) in setupSequence()
5801 : pss->iBase; in setupSequence()
5810 if( !pss->isNotEOF ) return 0; in progressSequence()
5811 if( pss->isReversing ){ in progressSequence()
5812 if( pss->uSeqIndexNow > 0 ){ in progressSequence()
5813 pss->uSeqIndexNow--; in progressSequence()
5814 pss->iValueNow -= pss->iStep; in progressSequence()
5816 pss->isNotEOF = 0; in progressSequence()
5819 if( pss->uSeqIndexNow < pss->uSeqIndexMax ){ in progressSequence()
5820 pss->uSeqIndexNow++; in progressSequence()
5821 pss->iValueNow += pss->iStep; in progressSequence()
5823 pss->isNotEOF = 0; in progressSequence()
5826 return pss->isNotEOF; in progressSequence()
5835 sqlite3_vtab_cursor base; /* Base class - must be first */
5900 *ppCursor = &pCur->base; in seriesOpen()
5918 progressSequence( & pCur->ss ); in seriesNext()
5934 case SERIES_COLUMN_START: x = pCur->ss.iBase; break; in seriesColumn()
5935 case SERIES_COLUMN_STOP: x = pCur->ss.iTerm; break; in seriesColumn()
5936 case SERIES_COLUMN_STEP: x = pCur->ss.iStep; break; in seriesColumn()
5937 default: x = pCur->ss.iValueNow; break; in seriesColumn()
5953 sqlite3_uint64 n = pCur->ss.uSeqIndexNow; in seriesRowid()
5964 return !pCur->ss.isNotEOF; in seriesEof()
5967 /* True to cause run-time checking of the start=, stop=, and/or step=
6006 pCur->ss.iBase = sqlite3_value_int64(argv[i++]); in seriesFilter()
6008 pCur->ss.iBase = 0; in seriesFilter()
6011 pCur->ss.iTerm = sqlite3_value_int64(argv[i++]); in seriesFilter()
6013 pCur->ss.iTerm = 0xffffffff; in seriesFilter()
6016 pCur->ss.iStep = sqlite3_value_int64(argv[i++]); in seriesFilter()
6017 if( pCur->ss.iStep==0 ){ in seriesFilter()
6018 pCur->ss.iStep = 1; in seriesFilter()
6019 }else if( pCur->ss.iStep<0 ){ in seriesFilter()
6023 pCur->ss.iStep = 1; in seriesFilter()
6029 pCur->ss.iBase = 1; in seriesFilter()
6030 pCur->ss.iTerm = 0; in seriesFilter()
6031 pCur->ss.iStep = 1; in seriesFilter()
6036 pCur->ss.isReversing = pCur->ss.iStep > 0; in seriesFilter()
6038 pCur->ss.isReversing = pCur->ss.iStep < 0; in seriesFilter()
6040 setupSequence( &pCur->ss ); in seriesFilter()
6055 ** (1) start = $value -- constraint exists
6056 ** (2) stop = $value -- constraint exists
6057 ** (4) step = $value -- constraint exists
6077 aIdx[0] = aIdx[1] = aIdx[2] = -1; in seriesBestIndex()
6078 pConstraint = pIdxInfo->aConstraint; in seriesBestIndex()
6079 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ in seriesBestIndex()
6082 if( pConstraint->iColumn<SERIES_COLUMN_START ) continue; in seriesBestIndex()
6083 iCol = pConstraint->iColumn - SERIES_COLUMN_START; in seriesBestIndex()
6087 if( pConstraint->usable==0 ){ in seriesBestIndex()
6090 }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){ in seriesBestIndex()
6097 pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg; in seriesBestIndex()
6098 pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY; in seriesBestIndex()
6103 ** first argument was omitted. Compile with -DZERO_ARGUMENT_GENERATE_SERIES in seriesBestIndex()
6107 sqlite3_free(pVTab->zErrMsg); in seriesBestIndex()
6108 pVTab->zErrMsg = sqlite3_mprintf( in seriesBestIndex()
6122 pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0)); in seriesBestIndex()
6123 pIdxInfo->estimatedRows = 1000; in seriesBestIndex()
6124 if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){ in seriesBestIndex()
6125 if( pIdxInfo->aOrderBy[0].desc ){ in seriesBestIndex()
6130 pIdxInfo->orderByConsumed = 1; in seriesBestIndex()
6136 pIdxInfo->estimatedRows = 2147483647; in seriesBestIndex()
6138 pIdxInfo->idxNum = idxNum; in seriesBestIndex()
6153 seriesOpen, /* xOpen - open a cursor */
6154 seriesClose, /* xClose - close a cursor */
6155 seriesFilter, /* xFilter - configure scan constraints */
6156 seriesNext, /* xNext - advance a cursor */
6157 seriesEof, /* xEof - check for end of scan */
6158 seriesColumn, /* xColumn - read data */
6159 seriesRowid, /* xRowid - read data */
6200 ** 2012-11-13
6212 ** efficient regular-expression matcher for posix extended regular
6234 ** \c C-language escapes for c in afnrtv. ex: \t or \n
6239 ** [a-z] Any single character in the range a-z
6240 ** [^a-z] Any single character not in the range a-z
6242 ** \w Word character. [A-Za-z0-9_]
6243 ** \W Non-word character
6245 ** \D Non-digit
6247 ** \S Non-whitespace character
6253 ** to p copies of X following by q-p copies of X? and that the size of the
6264 ** this file to prevent name collisions with C-library functions of the
6271 /* The end-of-input character */
6273 #define RE_START 0xfffffff /* Start of input - larger than an UTF-8 */
6288 #define RE_OP_WORD 11 /* Perl word character [A-Za-z0-9_] */
6290 #define RE_OP_DIGIT 13 /* digit: [0-9] */
6294 #define RE_OP_BOUNDARY 17 /* Boundary between word and non-word */
6364 for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return; in re_add_state()
6365 pSet->aState[pSet->nState++] = (ReStateNumber)newState; in re_add_state()
6375 if( p->i>=p->mx ) return 0; in re_next_char()
6376 c = p->z[p->i++]; in re_next_char()
6378 if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){ in re_next_char()
6379 c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f); in re_next_char()
6381 }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80 in re_next_char()
6382 && (p->z[p->i+1]&0xc0)==0x80 ){ in re_next_char()
6383 c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f); in re_next_char()
6384 p->i += 2; in re_next_char()
6386 }else if( (c&0xf8)==0xf0 && p->i+2<p->mx && (p->z[p->i]&0xc0)==0x80 in re_next_char()
6387 && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){ in re_next_char()
6388 c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6) in re_next_char()
6389 | (p->z[p->i+2]&0x3f); in re_next_char()
6390 p->i += 3; in re_next_char()
6400 if( c>='A' && c<='Z' ) c += 'a' - 'A'; in re_next_char_nocase()
6404 /* Return true if c is a perl "word" character: [A-Za-z0-9_] */
6410 /* Return true if c is a "digit" character: [0-9] */
6420 /* Run a compiled regular expression on the zero-terminated input
6439 if( pRe->nInit ){ in re_match()
6440 unsigned char x = pRe->zInit[0]; in re_match()
6441 while( in.i+pRe->nInit<=in.mx in re_match()
6443 strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0) in re_match()
6447 if( in.i+pRe->nInit>in.mx ) return 0; in re_match()
6448 c = RE_START-1; in re_match()
6451 if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){ in re_match()
6455 pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState ); in re_match()
6456 if( pToFree==0 ) return -1; in re_match()
6459 aStateSet[1].aState = &aStateSet[0].aState[pRe->nState]; in re_match()
6461 pNext->nState = 0; in re_match()
6463 while( c!=RE_EOF && pNext->nState>0 ){ in re_match()
6465 c = pRe->xNextChar(&in); in re_match()
6468 iSwap = 1 - iSwap; in re_match()
6469 pNext->nState = 0; in re_match()
6470 for(i=0; i<pThis->nState; i++){ in re_match()
6471 int x = pThis->aState[i]; in re_match()
6472 switch( pRe->aOp[x] ){ in re_match()
6474 if( pRe->aArg[x]==c ) re_add_state(pNext, x+1); in re_match()
6519 re_add_state(pThis, x+pRe->aArg[x]); in re_match()
6524 re_add_state(pThis, x+pRe->aArg[x]); in re_match()
6533 /* fall-through */ goto re_op_cc_inc; in re_match()
6537 int n = pRe->aArg[x]; in re_match()
6540 if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){ in re_match()
6541 if( pRe->aArg[x+j]==c ){ in re_match()
6543 j = -1; in re_match()
6546 if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){ in re_match()
6548 j = -1; in re_match()
6554 if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit; in re_match()
6561 for(i=0; i<pNext->nState; i++){ in re_match()
6562 int x = pNext->aState[i]; in re_match()
6563 while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x]; in re_match()
6564 if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; } in re_match()
6576 aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0])); in re_resize()
6578 p->aOp = aOp; in re_resize()
6579 aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0])); in re_resize()
6581 p->aArg = aArg; in re_resize()
6582 p->nAlloc = N; in re_resize()
6591 if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0; in re_insert()
6592 for(i=p->nState; i>iBefore; i--){ in re_insert()
6593 p->aOp[i] = p->aOp[i-1]; in re_insert()
6594 p->aArg[i] = p->aArg[i-1]; in re_insert()
6596 p->nState++; in re_insert()
6597 p->aOp[iBefore] = (char)op; in re_insert()
6598 p->aArg[iBefore] = arg; in re_insert()
6605 return re_insert(p, p->nState, op, arg); in re_append()
6612 if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return; in re_copy()
6613 memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0])); in re_copy()
6614 memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0])); in re_copy()
6615 p->nState += N; in re_copy()
6618 /* Return true if c is a hexadecimal digit character: [0-9a-fA-F]
6624 c -= '0'; in re_hex()
6626 c -= 'a' - 10; in re_hex()
6628 c -= 'A' - 10; in re_hex()
6644 if( p->sIn.i>=p->sIn.mx ) return 0; in re_esc_char()
6645 c = p->sIn.z[p->sIn.i]; in re_esc_char()
6646 if( c=='u' && p->sIn.i+4<p->sIn.mx ){ in re_esc_char()
6647 const unsigned char *zIn = p->sIn.z + p->sIn.i; in re_esc_char()
6653 p->sIn.i += 5; in re_esc_char()
6657 if( c=='x' && p->sIn.i+2<p->sIn.mx ){ in re_esc_char()
6658 const unsigned char *zIn = p->sIn.z + p->sIn.i; in re_esc_char()
6662 p->sIn.i += 3; in re_esc_char()
6669 p->sIn.i++; in re_esc_char()
6671 p->zErr = "unknown \\ escape"; in re_esc_char()
6681 return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0; in rePeek()
6691 iStart = p->nState; in re_subcompile_re()
6695 iEnd = p->nState; in re_subcompile_re()
6696 re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart); in re_subcompile_re()
6698 p->sIn.i++; in re_subcompile_re()
6701 p->aArg[iGoto] = p->nState - iGoto; in re_subcompile_re()
6711 int iPrev = -1; in re_subcompile_string()
6715 while( (c = p->xNextChar(&p->sIn))!=0 ){ in re_subcompile_string()
6716 iStart = p->nState; in re_subcompile_string()
6720 p->sIn.i--; in re_subcompile_string()
6727 p->sIn.i++; in re_subcompile_string()
6733 p->sIn.i++; in re_subcompile_string()
6741 re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1); in re_subcompile_string()
6742 re_append(p, RE_OP_FORK, iPrev - p->nState + 1); in re_subcompile_string()
6747 re_append(p, RE_OP_FORK, iPrev - p->nState); in re_subcompile_string()
6752 re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1); in re_subcompile_string()
6767 while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; } in re_subcompile_string()
6770 p->sIn.i++; in re_subcompile_string()
6772 while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; } in re_subcompile_string()
6776 p->sIn.i++; in re_subcompile_string()
6777 sz = p->nState - iPrev; in re_subcompile_string()
6782 n--; in re_subcompile_string()
6791 re_append(p, RE_OP_FORK, -sz); in re_subcompile_string()
6796 unsigned int iFirst = p->nState; in re_subcompile_string()
6799 p->sIn.i++; in re_subcompile_string()
6803 while( (c = p->xNextChar(&p->sIn))!=0 ){ in re_subcompile_string()
6808 if( rePeek(p)=='-' ){ in re_subcompile_string()
6810 p->sIn.i++; in re_subcompile_string()
6811 c = p->xNextChar(&p->sIn); in re_subcompile_string()
6817 if( rePeek(p)==']' ){ p->sIn.i++; break; } in re_subcompile_string()
6820 if( p->nState>iFirst ) p->aArg[iFirst] = p->nState - iFirst; in re_subcompile_string()
6835 p->sIn.i++; in re_subcompile_string()
6859 sqlite3_free(pRe->aOp); in re_free()
6860 sqlite3_free(pRe->aArg); in re_free()
6882 pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char; in re_compile()
6892 pRe->sIn.z = (unsigned char*)zIn; in re_compile()
6893 pRe->sIn.i = 0; in re_compile()
6894 pRe->sIn.mx = (int)strlen(zIn); in re_compile()
6900 if( pRe->sIn.i>=pRe->sIn.mx ){ in re_compile()
6914 ** unicode characters beyond plane 0 - those are very rare and this is in re_compile()
6916 if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){ in re_compile()
6917 for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){ in re_compile()
6918 unsigned x = pRe->aArg[i]; in re_compile()
6920 pRe->zInit[j++] = (unsigned char)x; in re_compile()
6922 pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6)); in re_compile()
6923 pRe->zInit[j++] = 0x80 | (x&0x3f); in re_compile()
6925 pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12)); in re_compile()
6926 pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f); in re_compile()
6927 pRe->zInit[j++] = 0x80 | (x&0x3f); in re_compile()
6932 if( j>0 && pRe->zInit[j-1]==0 ) j--; in re_compile()
6933 pRe->nInit = j; in re_compile()
6935 return pRe->zErr; in re_compile()
6940 ** the build-in REGEXP operator. The first argument to the function is the
6966 sqlite3_result_error(context, zErr, -1); in re_sql_func()
6977 sqlite3_result_int(context, re_match(pRe, zStr, -1)); in re_sql_func()
6987 ** if the SQLITE_DEBUG compile-time option is used.
7011 sqlite3_result_error(context, zErr, -1); in re_bytecode_func()
7020 if( pRe->nInit>0 ){ in re_bytecode_func()
7022 for(i=0; i<pRe->nInit; i++){ in re_bytecode_func()
7023 sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]); in re_bytecode_func()
7027 for(i=0; (unsigned)i<pRe->nState; i++){ in re_bytecode_func()
7028 sqlite3_str_appendf(pStr, "%-8s %4d\n", in re_bytecode_func()
7029 ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]); in re_bytecode_func()
7036 sqlite3_result_text(context, z, n-1, sqlite3_free); in re_bytecode_func()
7065 /* The regexpi(PATTERN,STRING) function is a case-insensitive version in sqlite3_regexp_init()
7085 ** 2014-06-13
7105 ** If the first option argument - MODE - is present, then it must
7122 ** as an integer - the number of seconds since the unix epoch. The
7123 ** modification-time of the target file is set to this value before
7143 ** file within the hierarchy rooted at $path.
7154 ** If a non-NULL value is specified for the optional $dir parameter and
7161 ** symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone
7198 ** Structure of the fsdir() table-valued function
7237 mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1); in readFileContents()
7284 sqlite3_result_error(ctx, zMsg, -1); in ctxErrorMsg()
7292 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
7310 fileIntervals.LowPart = pFileTime->dwLowDateTime; in fileTimeToUnixTime()
7311 fileIntervals.HighPart = pFileTime->dwHighDateTime; in fileTimeToUnixTime()
7313 return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000; in fileTimeToUnixTime()
7323 int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0); in utf8_to_utf16()
7325 if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) ) in utf8_to_utf16()
7350 pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime); in statTimesToUtc()
7351 pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime); in statTimesToUtc()
7352 pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime); in statTimesToUtc()
7452 sqlite3_int64 mtime /* MTIME parameter (or -1 to not set time) */ in writeFile()
7465 ** be an error though - if there is already a directory at the same in writeFile()
7570 sqlite3_int64 mtime = -1; in writefileFunc()
7574 "wrong number of arguments to function writefile()", -1 in writefileFunc()
7609 ** Given a numberic st_mode from stat(), convert it into a human-readable
7610 ** text string in the style of "ls -l".
7624 z[0] = '-'; in lsModeFunc()
7631 int m = (iMode >> ((2-i)*3)); in lsModeFunc()
7633 a[0] = (m & 0x4) ? 'r' : '-'; in lsModeFunc()
7634 a[1] = (m & 0x2) ? 'w' : '-'; in lsModeFunc()
7635 a[2] = (m & 0x1) ? 'x' : '-'; in lsModeFunc()
7638 sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT); in lsModeFunc()
7651 char *zDir; /* Name of directory (nul-terminated) */
7655 sqlite3_vtab_cursor base; /* Base class - must be first */
7659 FsdirLevel *aLvl; /* Hierarchy of directories being traversed */
7671 sqlite3_vtab base; /* Base class - must be first */
7718 pCur->iLvl = -1; in fsdirOpen()
7719 *ppCursor = &pCur->base; in fsdirOpen()
7729 for(i=0; i<=pCur->iLvl; i++){ in fsdirResetCursor()
7730 FsdirLevel *pLvl = &pCur->aLvl[i]; in fsdirResetCursor()
7731 if( pLvl->pDir ) closedir(pLvl->pDir); in fsdirResetCursor()
7732 sqlite3_free(pLvl->zDir); in fsdirResetCursor()
7734 sqlite3_free(pCur->zPath); in fsdirResetCursor()
7735 sqlite3_free(pCur->aLvl); in fsdirResetCursor()
7736 pCur->aLvl = 0; in fsdirResetCursor()
7737 pCur->zPath = 0; in fsdirResetCursor()
7738 pCur->zBase = 0; in fsdirResetCursor()
7739 pCur->nBase = 0; in fsdirResetCursor()
7740 pCur->nLvl = 0; in fsdirResetCursor()
7741 pCur->iLvl = -1; in fsdirResetCursor()
7742 pCur->iRowid = 1; in fsdirResetCursor()
7763 pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); in fsdirSetErrmsg()
7773 mode_t m = pCur->sStat.st_mode; in fsdirNext()
7775 pCur->iRowid++; in fsdirNext()
7778 int iNew = pCur->iLvl + 1; in fsdirNext()
7780 if( iNew>=pCur->nLvl ){ in fsdirNext()
7783 FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte); in fsdirNext()
7785 memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl)); in fsdirNext()
7786 pCur->aLvl = aNew; in fsdirNext()
7787 pCur->nLvl = nNew; in fsdirNext()
7789 pCur->iLvl = iNew; in fsdirNext()
7790 pLvl = &pCur->aLvl[iNew]; in fsdirNext()
7792 pLvl->zDir = pCur->zPath; in fsdirNext()
7793 pCur->zPath = 0; in fsdirNext()
7794 pLvl->pDir = opendir(pLvl->zDir); in fsdirNext()
7795 if( pLvl->pDir==0 ){ in fsdirNext()
7796 fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath); in fsdirNext()
7801 while( pCur->iLvl>=0 ){ in fsdirNext()
7802 FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl]; in fsdirNext()
7803 struct dirent *pEntry = readdir(pLvl->pDir); in fsdirNext()
7805 if( pEntry->d_name[0]=='.' ){ in fsdirNext()
7806 if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue; in fsdirNext()
7807 if( pEntry->d_name[1]=='\0' ) continue; in fsdirNext()
7809 sqlite3_free(pCur->zPath); in fsdirNext()
7810 pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name); in fsdirNext()
7811 if( pCur->zPath==0 ) return SQLITE_NOMEM; in fsdirNext()
7812 if( fileLinkStat(pCur->zPath, &pCur->sStat) ){ in fsdirNext()
7813 fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath); in fsdirNext()
7818 closedir(pLvl->pDir); in fsdirNext()
7819 sqlite3_free(pLvl->zDir); in fsdirNext()
7820 pLvl->pDir = 0; in fsdirNext()
7821 pLvl->zDir = 0; in fsdirNext()
7822 pCur->iLvl--; in fsdirNext()
7826 sqlite3_free(pCur->zPath); in fsdirNext()
7827 pCur->zPath = 0; in fsdirNext()
7843 sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT); in fsdirColumn()
7848 sqlite3_result_int64(ctx, pCur->sStat.st_mode); in fsdirColumn()
7852 sqlite3_result_int64(ctx, pCur->sStat.st_mtime); in fsdirColumn()
7856 mode_t m = pCur->sStat.st_mode; in fsdirColumn()
7867 n = readlink(pCur->zPath, aBuf, nBuf); in fsdirColumn()
7882 readFileContents(ctx, pCur->zPath); in fsdirColumn()
7902 *pRowid = pCur->iRowid; in fsdirRowid()
7912 return (pCur->zPath==0); in fsdirEof()
7939 fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument"); in fsdirFilter()
7943 pCur->zBase = (const char*)sqlite3_value_text(argv[1]); in fsdirFilter()
7945 if( pCur->zBase ){ in fsdirFilter()
7946 pCur->nBase = (int)strlen(pCur->zBase)+1; in fsdirFilter()
7947 pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir); in fsdirFilter()
7949 pCur->zPath = sqlite3_mprintf("%s", zDir); in fsdirFilter()
7952 if( pCur->zPath==0 ){ in fsdirFilter()
7955 if( fileLinkStat(pCur->zPath, &pCur->sStat) ){ in fsdirFilter()
7956 fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath); in fsdirFilter()
7982 int idxPath = -1; /* Index in pIdxInfo->aConstraint of PATH= */ in fsdirBestIndex()
7983 int idxDir = -1; /* Index in pIdxInfo->aConstraint of DIR= */ in fsdirBestIndex()
7989 pConstraint = pIdxInfo->aConstraint; in fsdirBestIndex()
7990 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ in fsdirBestIndex()
7991 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; in fsdirBestIndex()
7992 switch( pConstraint->iColumn ){ in fsdirBestIndex()
7994 if( pConstraint->usable ){ in fsdirBestIndex()
8003 if( pConstraint->usable ){ in fsdirBestIndex()
8019 pIdxInfo->idxNum = 0; in fsdirBestIndex()
8020 /* The pIdxInfo->estimatedCost should have been initialized to a huge in fsdirBestIndex()
8022 pIdxInfo->estimatedRows = 0x7fffffff; in fsdirBestIndex()
8024 pIdxInfo->aConstraintUsage[idxPath].omit = 1; in fsdirBestIndex()
8025 pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1; in fsdirBestIndex()
8027 pIdxInfo->aConstraintUsage[idxDir].omit = 1; in fsdirBestIndex()
8028 pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2; in fsdirBestIndex()
8029 pIdxInfo->idxNum = 2; in fsdirBestIndex()
8030 pIdxInfo->estimatedCost = 10.0; in fsdirBestIndex()
8032 pIdxInfo->idxNum = 1; in fsdirBestIndex()
8033 pIdxInfo->estimatedCost = 100.0; in fsdirBestIndex()
8051 fsdirOpen, /* xOpen - open a cursor */ in fsdirRegister()
8052 fsdirClose, /* xClose - close a cursor */ in fsdirRegister()
8053 fsdirFilter, /* xFilter - configure scan constraints */ in fsdirRegister()
8054 fsdirNext, /* xNext - advance a cursor */ in fsdirRegister()
8055 fsdirEof, /* xEof - check for end of scan */ in fsdirRegister()
8056 fsdirColumn, /* xColumn - read data */ in fsdirRegister()
8057 fsdirRowid, /* xRowid - read data */ in fsdirRegister()
8094 rc = sqlite3_create_function(db, "writefile", -1, in sqlite3_fileio_init()
8119 ** 2017-07-10
8166 sqlite3_vtab base; /* Base class - must be first */
8176 sqlite3_vtab_cursor base; /* Base class - must be first */
8186 int j; /* inter-phase counter */
8236 #define COMPLETION_COLUMN_PHASE 3 /* ePhase - used for debugging only */ in completionConnect()
8251 pNew->db = db; in completionConnect()
8272 pCur->db = ((completion_vtab*)p)->db; in completionOpen()
8273 *ppCursor = &pCur->base; in completionOpen()
8281 sqlite3_free(pCur->zPrefix); pCur->zPrefix = 0; pCur->nPrefix = 0; in completionCursorReset()
8282 sqlite3_free(pCur->zLine); pCur->zLine = 0; pCur->nLine = 0; in completionCursorReset()
8283 sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0; in completionCursorReset()
8284 pCur->j = 0; in completionCursorReset()
8299 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
8300 ** record the current state of the scan. This routine sets ->zCurrentRow
8302 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
8313 int iCol = -1; /* If >=0, step pCur->pStmt and use the i-th column */ in completionNext()
8314 pCur->iRowid++; in completionNext()
8315 while( pCur->ePhase!=COMPLETION_EOF ){ in completionNext()
8316 switch( pCur->ePhase ){ in completionNext()
8318 if( pCur->j >= sqlite3_keyword_count() ){ in completionNext()
8319 pCur->zCurrentRow = 0; in completionNext()
8320 pCur->ePhase = COMPLETION_DATABASES; in completionNext()
8322 sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow); in completionNext()
8324 iCol = -1; in completionNext()
8328 if( pCur->pStmt==0 ){ in completionNext()
8329 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, in completionNext()
8330 &pCur->pStmt, 0); in completionNext()
8337 if( pCur->pStmt==0 ){ in completionNext()
8341 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0); in completionNext()
8353 sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0); in completionNext()
8361 if( pCur->pStmt==0 ){ in completionNext()
8365 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0); in completionNext()
8379 sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0); in completionNext()
8389 if( pCur->zCurrentRow==0 ) continue; in completionNext()
8391 if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){ in completionNext()
8393 pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol); in completionNext()
8394 pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol); in completionNext()
8397 sqlite3_finalize(pCur->pStmt); in completionNext()
8398 pCur->pStmt = 0; in completionNext()
8399 pCur->ePhase = eNextPhase; in completionNext()
8403 if( pCur->nPrefix==0 ) break; in completionNext()
8404 if( pCur->nPrefix<=pCur->szRow in completionNext()
8405 && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0 in completionNext()
8426 sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT); in completionColumn()
8430 sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT); in completionColumn()
8434 sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT); in completionColumn()
8438 sqlite3_result_int(ctx, pCur->ePhase); in completionColumn()
8451 *pRowid = pCur->iRowid; in completionRowid()
8461 return pCur->ePhase >= COMPLETION_EOF; in completionEof()
8481 pCur->nPrefix = sqlite3_value_bytes(argv[iArg]); in completionFilter()
8482 if( pCur->nPrefix>0 ){ in completionFilter()
8483 pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg])); in completionFilter()
8484 if( pCur->zPrefix==0 ) return SQLITE_NOMEM; in completionFilter()
8489 pCur->nLine = sqlite3_value_bytes(argv[iArg]); in completionFilter()
8490 if( pCur->nLine>0 ){ in completionFilter()
8491 pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg])); in completionFilter()
8492 if( pCur->zLine==0 ) return SQLITE_NOMEM; in completionFilter()
8495 if( pCur->zLine!=0 && pCur->zPrefix==0 ){ in completionFilter()
8496 int i = pCur->nLine; in completionFilter()
8497 while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){ in completionFilter()
8498 i--; in completionFilter()
8500 pCur->nPrefix = pCur->nLine - i; in completionFilter()
8501 if( pCur->nPrefix>0 ){ in completionFilter()
8502 pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i); in completionFilter()
8503 if( pCur->zPrefix==0 ) return SQLITE_NOMEM; in completionFilter()
8506 pCur->iRowid = 0; in completionFilter()
8507 pCur->ePhase = COMPLETION_FIRST_PHASE; in completionFilter()
8517 ** There are two hidden parameters that act as arguments to the table-valued
8527 int prefixIdx = -1; /* Index of the start= constraint, or -1 if none */ in completionBestIndex()
8528 int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */ in completionBestIndex()
8533 pConstraint = pIdxInfo->aConstraint; in completionBestIndex()
8534 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ in completionBestIndex()
8535 if( pConstraint->usable==0 ) continue; in completionBestIndex()
8536 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; in completionBestIndex()
8537 switch( pConstraint->iColumn ){ in completionBestIndex()
8549 pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg; in completionBestIndex()
8550 pIdxInfo->aConstraintUsage[prefixIdx].omit = 1; in completionBestIndex()
8553 pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg; in completionBestIndex()
8554 pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1; in completionBestIndex()
8556 pIdxInfo->idxNum = idxNum; in completionBestIndex()
8557 pIdxInfo->estimatedCost = (double)5000 - 1000*nArg; in completionBestIndex()
8558 pIdxInfo->estimatedRows = 500 - 100*nArg; in completionBestIndex()
8573 completionOpen, /* xOpen - open a cursor */
8574 completionClose, /* xClose - close a cursor */
8575 completionFilter, /* xFilter - configure scan constraints */
8576 completionNext, /* xNext - advance a cursor */
8577 completionEof, /* xEof - check for end of scan */
8578 completionColumn, /* xColumn - read data */
8579 completionRowid, /* xRowid - read data */
8624 ** 2017-10-20
8652 ** "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
8669 ** this shim is a pass-through into the default underlying VFS. (rule 3)
8678 ** Start-Of-SQLite3-NNNNNNNN
8681 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
8684 #define APND_MARK_PREFIX "Start-Of-SQLite3-"
8690 ** Maximum size of the combined prefix + database + append-mark. This
8701 #define APND_ALIGN_MASK ((sqlite3_int64)(APND_ROUNDUP-1))
8710 /* Access to a lower-level VFS that (might) implement dynamic loading,
8713 #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
8722 ** append-mark.
8726 ** +-------------+---------+----------+-------------+
8727 ** | prefix-file | padding | database | append-mark |
8728 ** +-------------+---------+----------+-------------+
8734 ** "prefix file" - file onto which the database has been appended.
8735 ** "padding" - zero or more bytes inserted so that "database"
8737 ** "database" - The SQLite database file
8738 ** "append-mark" - The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
8739 ** the offset from the start of prefix-file to the start
8742 ** The size of the database is iMark - iPgOne.
8744 ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
8745 ** of iPgOne stored as a big-ending 64-bit integer.
8748 ** Or, iMark is -1 to indicate that it has not yet been written.
8753 sqlite3_int64 iMark; /* Offset of the append mark. -1 if unwritten */
8847 ** Close an apnd-file.
8851 return pFile->pMethods->xClose(pFile); in apndClose()
8855 ** Read data from an apnd-file.
8865 return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst); in apndRead()
8869 ** Add the append-mark onto what should become the end of the file.
8871 * Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
8878 sqlite_int64 iPgOne = paf->iPgOne; in apndWriteMark()
8884 while( --i >= 0 ){ in apndWriteMark()
8888 iWriteEnd += paf->iPgOne; in apndWriteMark()
8889 if( SQLITE_OK==(rc = pFile->pMethods->xWrite in apndWriteMark()
8891 paf->iMark = iWriteEnd; in apndWriteMark()
8897 ** Write data to an apnd-file.
8909 /* If append-mark is absent or will be overwritten, write it. */ in apndWrite()
8910 if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){ in apndWrite()
8914 return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst); in apndWrite()
8918 ** Truncate an apnd-file.
8926 return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE); in apndTruncate()
8930 ** Sync an apnd-file.
8934 return pFile->pMethods->xSync(pFile, flags); in apndSync()
8938 ** Return the current file-size of an apnd-file.
8939 ** If the append mark is not yet there, the file-size is 0.
8943 *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0; in apndFileSize()
8948 ** Lock an apnd-file.
8952 return pFile->pMethods->xLock(pFile, eLock); in apndLock()
8956 ** Unlock an apnd-file.
8960 return pFile->pMethods->xUnlock(pFile, eLock); in apndUnlock()
8964 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
8968 return pFile->pMethods->xCheckReservedLock(pFile, pResOut); in apndCheckReservedLock()
8972 ** File control method. For custom operations on an apnd-file.
8978 if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne; in apndFileControl()
8979 rc = pFile->pMethods->xFileControl(pFile, op, pArg); in apndFileControl()
8981 *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg); in apndFileControl()
8987 ** Return the sector-size in bytes for an apnd-file.
8991 return pFile->pMethods->xSectorSize(pFile); in apndSectorSize()
8995 ** Return the device characteristic flags supported by an apnd-file.
8999 return pFile->pMethods->xDeviceCharacteristics(pFile); in apndDeviceCharacteristics()
9011 return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp); in apndShmMap()
9014 /* Perform locking on a shared-memory segment */
9017 return pFile->pMethods->xShmLock(pFile,offset,n,flags); in apndShmLock()
9023 pFile->pMethods->xShmBarrier(pFile); in apndShmBarrier()
9029 return pFile->pMethods->xShmUnmap(pFile,deleteFlag); in apndShmUnmap()
9032 /* Fetch a page of a memory-mapped file */
9040 if( p->iMark < 0 || iOfst+iAmt > p->iMark ){ in apndFetch()
9044 return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp); in apndFetch()
9047 /* Release a memory-mapped page */
9051 return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage); in apndUnfetch()
9055 ** Try to read the append-mark off the end of a file. Return the
9056 ** start of the appended database if the append-mark is present.
9057 ** If there is no valid append-mark, return -1;
9059 ** An append-mark is only valid if the NNNNNNNN start-of-database offset
9061 ** start-of-database value must be a multiple of 512.
9066 int msbs = 8 * (APND_MARK_FOS_SZ-1); in apndReadMark()
9069 if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1; in apndReadMark()
9070 rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE); in apndReadMark()
9071 if( rc ) return -1; in apndReadMark()
9072 if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1; in apndReadMark()
9075 msbs -= 8; in apndReadMark()
9078 if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1; in apndReadMark()
9079 if( iMark & 0x1ff ) return -1; in apndReadMark()
9093 /* If file has the correct end-marker, the expected odd size, and the in apndIsAppendvfsDatabase()
9094 ** SQLite DB type marker where the end-marker puts it, then it in apndIsAppendvfsDatabase()
9097 rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark); in apndIsAppendvfsDatabase()
9117 || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0) in apndIsOrdinaryDatabaseFile()
9146 return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags); in apndOpen()
9149 pFile->pMethods = &apnd_io_methods; in apndOpen()
9150 pApndFile->iMark = -1; /* Append mark not yet written */ in apndOpen()
9152 rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags); in apndOpen()
9154 rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz); in apndOpen()
9156 pBaseFile->pMethods->xClose(pBaseFile); in apndOpen()
9160 pFile->pMethods = 0; in apndOpen()
9165 ** the base dispatch-table so this instance mimics the base VFS. in apndOpen()
9167 memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile); in apndOpen()
9170 pApndFile->iPgOne = apndReadMark(sz, pFile); in apndOpen()
9171 if( pApndFile->iPgOne>=0 ){ in apndOpen()
9172 pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */ in apndOpen()
9176 pBaseFile->pMethods->xClose(pBaseFile); in apndOpen()
9178 pFile->pMethods = 0; in apndOpen()
9183 ** Until then, paf->iMark value indicates it is not yet written. in apndOpen()
9185 pApndFile->iPgOne = APND_START_ROUNDUP(sz); in apndOpen()
9197 return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync); in apndDelete()
9201 ** All other VFS methods are pass-thrus.
9209 return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut); in apndAccess()
9217 return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut); in apndFullPathname()
9220 return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath); in apndDlOpen()
9223 ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg); in apndDlError()
9226 return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym); in apndDlSym()
9229 ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle); in apndDlClose()
9232 return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut); in apndRandomness()
9235 return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro); in apndSleep()
9238 return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut); in apndCurrentTime()
9241 return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b); in apndGetLastError()
9244 return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p); in apndCurrentTimeInt64()
9251 return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall); in apndSetSystemCall()
9257 return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName); in apndGetSystemCall()
9260 return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName); in apndNextSystemCall()
9283 apnd_vfs.iVersion = pOrig->iVersion; in sqlite3_appendvfs_init()
9285 apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile); in sqlite3_appendvfs_init()
9301 ** 2017-12-26
9355 /* typedef UINT32_TYPE u32; // 4-byte unsigned integer // */
9356 /* typedef UINT16_TYPE u16; // 2-byte unsigned integer // */
9414 ** Use this value for the "version-made-by" field in new zip file
9417 ** This is what info-zip seems to do.
9420 ** Value for "version-required-to-extract" field of new entries.
9424 ** Value for "general-purpose-bit-flags" field of new entries. Bit
9425 ** 11 means "utf-8 filename and comment".
9445 ** The sizes of the fixed-size part of each of the three main data
9492 *** crc-32 4 bytes
9533 *** crc-32 4 bytes
9561 ZipfileEntry *pNext; /* Next element in in-memory CDS */
9569 sqlite3_vtab_cursor base; /* Base class - must be first */
9572 u8 bNoop; /* If next xNext() call is no-op */
9586 sqlite3_vtab base; /* Base class - must be first */
9611 sqlite3_result_error(ctx, zMsg, -1); in zipfileCtxErrorMsg()
9638 ** argv[0] -> module name ("zipfile")
9639 ** argv[1] -> database name
9640 ** argv[2] -> table name
9641 ** argv[...] -> "column name" and other module argument fields.
9682 pNew->db = db; in zipfileConnect()
9683 pNew->aBuffer = (u8*)&pNew[1]; in zipfileConnect()
9685 pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE]; in zipfileConnect()
9686 memcpy(pNew->zFile, zFile, nFile); in zipfileConnect()
9687 zipfileDequote(pNew->zFile); in zipfileConnect()
9700 sqlite3_free(p->cds.zFile); in zipfileEntryFree()
9713 if( pTab->pWriteFd ){ in zipfileCleanupTransaction()
9714 fclose(pTab->pWriteFd); in zipfileCleanupTransaction()
9715 pTab->pWriteFd = 0; in zipfileCleanupTransaction()
9717 for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){ in zipfileCleanupTransaction()
9718 pNext = pEntry->pNext; in zipfileCleanupTransaction()
9721 pTab->pFirstEntry = 0; in zipfileCleanupTransaction()
9722 pTab->pLastEntry = 0; in zipfileCleanupTransaction()
9723 pTab->szCurrent = 0; in zipfileCleanupTransaction()
9724 pTab->szOrig = 0; in zipfileCleanupTransaction()
9748 pCsr->iId = ++pTab->iNextCsrid; in zipfileOpen()
9749 pCsr->pCsrNext = pTab->pCsrList; in zipfileOpen()
9750 pTab->pCsrList = pCsr; in zipfileOpen()
9762 pCsr->bEof = 0; in zipfileResetCursor()
9763 if( pCsr->pFile ){ in zipfileResetCursor()
9764 fclose(pCsr->pFile); in zipfileResetCursor()
9765 pCsr->pFile = 0; in zipfileResetCursor()
9766 zipfileEntryFree(pCsr->pCurrent); in zipfileResetCursor()
9767 pCsr->pCurrent = 0; in zipfileResetCursor()
9770 for(p=pCsr->pFreeEntry; p; p=pNext){ in zipfileResetCursor()
9771 pNext = p->pNext; in zipfileResetCursor()
9781 ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab); in zipfileClose()
9786 for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext)); in zipfileClose()
9787 *pp = pCsr->pCsrNext; in zipfileClose()
9800 sqlite3_free(pTab->base.zErrMsg); in zipfileTableErr()
9801 pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap); in zipfileTableErr()
9807 sqlite3_free(pCsr->base.pVtab->zErrMsg); in zipfileCursorErr()
9808 pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); in zipfileCursorErr()
9846 fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET); in zipfileAppendData()
9847 n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd); in zipfileAppendData()
9849 pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()"); in zipfileAppendData()
9852 pTab->szCurrent += nWrite; in zipfileAppendData()
9858 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
9865 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
9876 ** Write a 16-bit little endiate integer into buffer aBuf.
9884 ** Write a 32-bit little endiate integer into buffer aBuf.
9893 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
9894 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
9907 ** if the record is not well-formed, or SQLITE_OK otherwise.
9916 pCDS->iVersionMadeBy = zipfileRead16(aRead); in zipfileReadCDS()
9917 pCDS->iVersionExtract = zipfileRead16(aRead); in zipfileReadCDS()
9918 pCDS->flags = zipfileRead16(aRead); in zipfileReadCDS()
9919 pCDS->iCompression = zipfileRead16(aRead); in zipfileReadCDS()
9920 pCDS->mTime = zipfileRead16(aRead); in zipfileReadCDS()
9921 pCDS->mDate = zipfileRead16(aRead); in zipfileReadCDS()
9922 pCDS->crc32 = zipfileRead32(aRead); in zipfileReadCDS()
9923 pCDS->szCompressed = zipfileRead32(aRead); in zipfileReadCDS()
9924 pCDS->szUncompressed = zipfileRead32(aRead); in zipfileReadCDS()
9926 pCDS->nFile = zipfileRead16(aRead); in zipfileReadCDS()
9927 pCDS->nExtra = zipfileRead16(aRead); in zipfileReadCDS()
9928 pCDS->nComment = zipfileRead16(aRead); in zipfileReadCDS()
9929 pCDS->iDiskStart = zipfileRead16(aRead); in zipfileReadCDS()
9930 pCDS->iInternalAttr = zipfileRead16(aRead); in zipfileReadCDS()
9931 pCDS->iExternalAttr = zipfileRead32(aRead); in zipfileReadCDS()
9932 pCDS->iOffset = zipfileRead32(aRead); in zipfileReadCDS()
9941 ** if the record is not well-formed, or SQLITE_OK otherwise.
9954 pLFH->iVersionExtract = zipfileRead16(aRead); in zipfileReadLFH()
9955 pLFH->flags = zipfileRead16(aRead); in zipfileReadLFH()
9956 pLFH->iCompression = zipfileRead16(aRead); in zipfileReadLFH()
9957 pLFH->mTime = zipfileRead16(aRead); in zipfileReadLFH()
9958 pLFH->mDate = zipfileRead16(aRead); in zipfileReadLFH()
9959 pLFH->crc32 = zipfileRead32(aRead); in zipfileReadLFH()
9960 pLFH->szCompressed = zipfileRead32(aRead); in zipfileReadLFH()
9961 pLFH->szUncompressed = zipfileRead32(aRead); in zipfileReadLFH()
9962 pLFH->nFile = zipfileRead16(aRead); in zipfileReadLFH()
9963 pLFH->nExtra = zipfileRead16(aRead); in zipfileReadLFH()
9971 ** Scan through this buffer to find an "extra-timestamp" field. If one
9972 ** exists, extract the 32-bit modification-timestamp from it and store
9975 ** Zero is returned if no extra-timestamp record could be found (and so
9976 ** *pmTime is left unchanged), or non-zero otherwise.
9996 if( b & 0x01 ){ /* 0x01 -> modtime is present */ in zipfileScanExtra()
10010 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
10011 ** fields of the CDS structure passed as the only argument to a 32-bit
10012 ** UNIX seconds-since-the-epoch timestamp. Return the result.
10014 ** "Standard" MS-DOS time format:
10017 ** Bits 00-04: seconds divided by 2
10018 ** Bits 05-10: minute
10019 ** Bits 11-15: hour
10021 ** Bits 00-04: day
10022 ** Bits 05-08: month (1-12)
10023 ** Bits 09-15: years from 1980
10025 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
10030 Y = (1980 + ((pCDS->mDate >> 9) & 0x7F)); in zipfileMtime()
10031 M = ((pCDS->mDate >> 5) & 0x0F); in zipfileMtime()
10032 D = (pCDS->mDate & 0x1F); in zipfileMtime()
10033 sec = (pCDS->mTime & 0x1F)*2; in zipfileMtime()
10034 min = (pCDS->mTime >> 5) & 0x3F; in zipfileMtime()
10035 hr = (pCDS->mTime >> 11) & 0x1F; in zipfileMtime()
10037 Y--; in zipfileMtime()
10043 B = 2 - A + (A/4); in zipfileMtime()
10044 JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec; in zipfileMtime()
10045 return (u32)(JDsec - (i64)24405875*(i64)8640); in zipfileMtime()
10061 A = (int)((JD - 1867216.25)/36524.25); in zipfileMtimeToDos()
10062 A = (int)(JD + 1 + A - (A/4)); in zipfileMtimeToDos()
10064 C = (int)((B - 122.1)/365.25); in zipfileMtimeToDos()
10066 E = (int)((B-D)/30.6001); in zipfileMtimeToDos()
10068 day = B - D - (int)(30.6001*E); in zipfileMtimeToDos()
10069 mon = (E<14 ? E-1 : E-13); in zipfileMtimeToDos()
10070 yr = mon>2 ? C-4716 : C-4715; in zipfileMtimeToDos()
10077 pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9)); in zipfileMtimeToDos()
10078 pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11)); in zipfileMtimeToDos()
10080 pCds->mDate = pCds->mTime = 0; in zipfileMtimeToDos()
10085 || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) in zipfileMtimeToDos()
10093 ** then pFile is a file-handle open on a zip file. In either case, this
10103 const u8 *aBlob, /* Pointer to in-memory file image */ in zipfileGetEntry()
10110 char **pzErr = &pTab->base.zErrMsg; in zipfileGetEntry()
10115 aRead = pTab->aBuffer; in zipfileGetEntry()
10139 rc = zipfileReadCDS(aRead, &pNew->cds); in zipfileGetEntry()
10152 u32 *pt = &pNew->mUnixTime; in zipfileGetEntry()
10153 pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead); in zipfileGetEntry()
10154 pNew->aExtra = (u8*)&pNew[1]; in zipfileGetEntry()
10155 memcpy(pNew->aExtra, &aRead[nFile], nExtra); in zipfileGetEntry()
10156 if( pNew->cds.zFile==0 ){ in zipfileGetEntry()
10158 }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){ in zipfileGetEntry()
10159 pNew->mUnixTime = zipfileMtime(&pNew->cds); in zipfileGetEntry()
10167 rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr); in zipfileGetEntry()
10169 aRead = (u8*)&aBlob[pNew->cds.iOffset]; in zipfileGetEntry()
10174 pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ; in zipfileGetEntry()
10175 pNew->iDataOff += lfh.nFile + lfh.nExtra; in zipfileGetEntry()
10176 if( aBlob && pNew->cds.szCompressed ){ in zipfileGetEntry()
10177 pNew->aData = &pNew->aExtra[nExtra]; in zipfileGetEntry()
10178 memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed); in zipfileGetEntry()
10182 (int)pNew->cds.iOffset in zipfileGetEntry()
10204 if( pCsr->pFile ){ in zipfileNext()
10205 i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize; in zipfileNext()
10206 zipfileEntryFree(pCsr->pCurrent); in zipfileNext()
10207 pCsr->pCurrent = 0; in zipfileNext()
10208 if( pCsr->iNextOff>=iEof ){ in zipfileNext()
10209 pCsr->bEof = 1; in zipfileNext()
10212 ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab); in zipfileNext()
10213 rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p); in zipfileNext()
10215 pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ; in zipfileNext()
10216 pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment; in zipfileNext()
10218 pCsr->pCurrent = p; in zipfileNext()
10221 if( !pCsr->bNoop ){ in zipfileNext()
10222 pCsr->pCurrent = pCsr->pCurrent->pNext; in zipfileNext()
10224 if( pCsr->pCurrent==0 ){ in zipfileNext()
10225 pCsr->bEof = 1; in zipfileNext()
10229 pCsr->bNoop = 0; in zipfileNext()
10263 err = inflateInit2(&str, -15); in zipfileInflate()
10288 ** code is returned and an error message left in virtual-table handle
10305 deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); in zipfileDeflate()
10341 ZipfileCDS *pCDS = &pCsr->pCurrent->cds; in zipfileColumn()
10345 sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT); in zipfileColumn()
10350 sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16); in zipfileColumn()
10353 sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime); in zipfileColumn()
10358 sqlite3_result_int64(ctx, pCDS->szUncompressed); in zipfileColumn()
10365 if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){ in zipfileColumn()
10366 int sz = pCDS->szCompressed; in zipfileColumn()
10367 int szFinal = pCDS->szUncompressed; in zipfileColumn()
10371 if( pCsr->pCurrent->aData ){ in zipfileColumn()
10372 aBuf = pCsr->pCurrent->aData; in zipfileColumn()
10378 FILE *pFile = pCsr->pFile; in zipfileColumn()
10380 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd; in zipfileColumn()
10382 rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff, in zipfileColumn()
10383 &pCsr->base.pVtab->zErrMsg in zipfileColumn()
10388 if( i==5 && pCDS->iCompression ){ in zipfileColumn()
10396 /* Figure out if this is a directory or a zero-sized file. Consider in zipfileColumn()
10399 u32 mode = pCDS->iExternalAttr >> 16; in zipfileColumn()
10401 && pCDS->nFile>=1 in zipfileColumn()
10402 && pCDS->zFile[pCDS->nFile-1]!='/' in zipfileColumn()
10411 sqlite3_result_int(ctx, pCDS->iCompression); in zipfileColumn()
10415 sqlite3_result_int64(ctx, pCsr->iId); in zipfileColumn()
10427 return pCsr->bEof; in zipfileEof()
10433 ** is guaranteed to be a file-handle open on a zip file.
10438 ** an English language error message may be left in virtual-table pTab.
10442 const u8 *aBlob, /* Pointer to in-memory file image */ in zipfileReadEOCD()
10447 u8 *aRead = pTab->aBuffer; /* Temporary buffer */ in zipfileReadEOCD()
10461 iOff = szFile - nRead; in zipfileReadEOCD()
10462 rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg); in zipfileReadEOCD()
10465 aRead = (u8*)&aBlob[nBlob-nRead]; in zipfileReadEOCD()
10472 for(i=nRead-20; i>=0; i--){ in zipfileReadEOCD()
10480 pTab->base.zErrMsg = sqlite3_mprintf( in zipfileReadEOCD()
10487 pEOCD->iDisk = zipfileRead16(aRead); in zipfileReadEOCD()
10488 pEOCD->iFirstDisk = zipfileRead16(aRead); in zipfileReadEOCD()
10489 pEOCD->nEntry = zipfileRead16(aRead); in zipfileReadEOCD()
10490 pEOCD->nEntryTotal = zipfileRead16(aRead); in zipfileReadEOCD()
10491 pEOCD->nSize = zipfileRead32(aRead); in zipfileReadEOCD()
10492 pEOCD->iOffset = zipfileRead32(aRead); in zipfileReadEOCD()
10509 assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) ); in zipfileAddEntry()
10510 assert( pNew->pNext==0 ); in zipfileAddEntry()
10512 if( pTab->pFirstEntry==0 ){ in zipfileAddEntry()
10513 pTab->pFirstEntry = pTab->pLastEntry = pNew; in zipfileAddEntry()
10515 assert( pTab->pLastEntry->pNext==0 ); in zipfileAddEntry()
10516 pTab->pLastEntry->pNext = pNew; in zipfileAddEntry()
10517 pTab->pLastEntry = pNew; in zipfileAddEntry()
10521 for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext)); in zipfileAddEntry()
10522 pNew->pNext = pBefore; in zipfileAddEntry()
10533 rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd); in zipfileLoadDirectory()
10537 rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew); in zipfileLoadDirectory()
10542 iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment; in zipfileLoadDirectory()
10556 ZipfileTab *pTab = (ZipfileTab*)cur->pVtab; in zipfileFilter()
10560 int bInMemory = 0; /* True for an in-memory zipfile */ in zipfileFilter()
10567 if( pTab->zFile ){ in zipfileFilter()
10568 zFile = pTab->zFile; in zipfileFilter()
10576 assert( pTab->pFirstEntry==0 ); in zipfileFilter()
10582 pCsr->pFreeEntry = pTab->pFirstEntry; in zipfileFilter()
10583 pTab->pFirstEntry = pTab->pLastEntry = 0; in zipfileFilter()
10590 if( 0==pTab->pWriteFd && 0==bInMemory ){ in zipfileFilter()
10591 pCsr->pFile = zFile ? fopen(zFile, "rb") : 0; in zipfileFilter()
10592 if( pCsr->pFile==0 ){ in zipfileFilter()
10596 rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd); in zipfileFilter()
10598 if( pCsr->eocd.nEntry==0 ){ in zipfileFilter()
10599 pCsr->bEof = 1; in zipfileFilter()
10601 pCsr->iNextOff = pCsr->eocd.iOffset; in zipfileFilter()
10607 pCsr->bNoop = 1; in zipfileFilter()
10608 pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry; in zipfileFilter()
10623 int idx = -1; in zipfileBestIndex()
10627 for(i=0; i<pIdxInfo->nConstraint; i++){ in zipfileBestIndex()
10628 const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; in zipfileBestIndex()
10629 if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue; in zipfileBestIndex()
10630 if( pCons->usable==0 ){ in zipfileBestIndex()
10632 }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ in zipfileBestIndex()
10636 pIdxInfo->estimatedCost = 1000.0; in zipfileBestIndex()
10638 pIdxInfo->aConstraintUsage[idx].argvIndex = 1; in zipfileBestIndex()
10639 pIdxInfo->aConstraintUsage[idx].omit = 1; in zipfileBestIndex()
10640 pIdxInfo->idxNum = 1; in zipfileBestIndex()
10652 pNew->cds.zFile = sqlite3_mprintf("%s", zPath); in zipfileNewEntry()
10653 if( pNew->cds.zFile==0 ){ in zipfileNewEntry()
10662 ZipfileCDS *pCds = &pEntry->cds; in zipfileSerializeLFH()
10665 pCds->nExtra = 9; in zipfileSerializeLFH()
10669 zipfileWrite16(a, pCds->iVersionExtract); in zipfileSerializeLFH()
10670 zipfileWrite16(a, pCds->flags); in zipfileSerializeLFH()
10671 zipfileWrite16(a, pCds->iCompression); in zipfileSerializeLFH()
10672 zipfileWrite16(a, pCds->mTime); in zipfileSerializeLFH()
10673 zipfileWrite16(a, pCds->mDate); in zipfileSerializeLFH()
10674 zipfileWrite32(a, pCds->crc32); in zipfileSerializeLFH()
10675 zipfileWrite32(a, pCds->szCompressed); in zipfileSerializeLFH()
10676 zipfileWrite32(a, pCds->szUncompressed); in zipfileSerializeLFH()
10677 zipfileWrite16(a, (u16)pCds->nFile); in zipfileSerializeLFH()
10678 zipfileWrite16(a, pCds->nExtra); in zipfileSerializeLFH()
10682 memcpy(a, pCds->zFile, (int)pCds->nFile); in zipfileSerializeLFH()
10683 a += (int)pCds->nFile; in zipfileSerializeLFH()
10689 zipfileWrite32(a, pEntry->mUnixTime); in zipfileSerializeLFH()
10691 return a-aBuf; in zipfileSerializeLFH()
10700 u8 *aBuf = pTab->aBuffer; in zipfileAppendEntry()
10707 pEntry->iDataOff = pTab->szCurrent; in zipfileAppendEntry()
10727 const char zTemplate[11] = "-rwxrwxrwx"; in zipfileGetMode()
10731 case '-': mode |= S_IFREG; break; in zipfileGetMode()
10737 if( z[i]==zTemplate[i] ) mode |= 1 << (9-i); in zipfileGetMode()
10738 else if( z[i]!='-' ) goto parse_error; in zipfileGetMode()
10743 ** Or vice-versa - no data but "mode" is a file or symlink. */ in zipfileGetMode()
10756 ** Both (const char*) arguments point to nul-terminated strings. Argument
10761 if( nA>0 && zA[nA-1]=='/' ) nA--; in zipfileComparePath()
10762 if( nB>0 && zB[nB-1]=='/' ) nB--; in zipfileComparePath()
10771 assert( pTab->pWriteFd==0 ); in zipfileBegin()
10772 if( pTab->zFile==0 || pTab->zFile[0]==0 ){ in zipfileBegin()
10773 pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename"); in zipfileBegin()
10780 ** in main-memory until the transaction is committed. */ in zipfileBegin()
10781 pTab->pWriteFd = fopen(pTab->zFile, "ab+"); in zipfileBegin()
10782 if( pTab->pWriteFd==0 ){ in zipfileBegin()
10783 pTab->base.zErrMsg = sqlite3_mprintf( in zipfileBegin()
10784 "zipfile: failed to open file %s for writing", pTab->zFile in zipfileBegin()
10788 fseek(pTab->pWriteFd, 0, SEEK_END); in zipfileBegin()
10789 pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd); in zipfileBegin()
10801 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
10808 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ in zipfileTime()
10810 pVfs->xCurrentTimeInt64(pVfs, &ms); in zipfileTime()
10811 ret = (u32)((ms/1000) - ((i64)24405875 * 8640)); in zipfileTime()
10814 pVfs->xCurrentTime(pVfs, &day); in zipfileTime()
10815 ret = (u32)((day - 2440587.5) * 86400); in zipfileTime()
10821 ** Return a 32-bit timestamp in UNIX epoch format.
10825 ** cast to a 32-bit unsigned integer.
10835 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
10840 if( pTab->pFirstEntry==pOld ){ in zipfileRemoveEntryFromList()
10841 pTab->pFirstEntry = pOld->pNext; in zipfileRemoveEntryFromList()
10842 if( pTab->pLastEntry==pOld ) pTab->pLastEntry = 0; in zipfileRemoveEntryFromList()
10845 for(p=pTab->pFirstEntry; p; p=p->pNext){ in zipfileRemoveEntryFromList()
10846 if( p->pNext==pOld ){ in zipfileRemoveEntryFromList()
10847 p->pNext = pOld->pNext; in zipfileRemoveEntryFromList()
10848 if( pTab->pLastEntry==pOld ) pTab->pLastEntry = p; in zipfileRemoveEntryFromList()
10868 ZipfileEntry *pNew = 0; /* New in-memory CDS entry */ in zipfileUpdate()
10888 if( pTab->pWriteFd==0 ){ in zipfileUpdate()
10903 for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){ in zipfileUpdate()
10904 if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){ in zipfileUpdate()
10907 assert( pOld->pNext ); in zipfileUpdate()
10943 rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg); in zipfileUpdate()
10958 rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg); in zipfileUpdate()
10970 ** '/'. This appears to be required for compatibility with info-zip in zipfileUpdate()
10973 if( nPath<=0 || zPath[nPath-1]!='/' ){ in zipfileUpdate()
10985 /* Check that we're not inserting a duplicate entry -OR- updating an in zipfileUpdate()
10989 for(p=pTab->pFirstEntry; p; p=p->pNext){ in zipfileUpdate()
10990 if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){ in zipfileUpdate()
10991 switch( sqlite3_vtab_on_conflict(pTab->db) ){ in zipfileUpdate()
11016 pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; in zipfileUpdate()
11017 pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; in zipfileUpdate()
11018 pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS; in zipfileUpdate()
11019 pNew->cds.iCompression = (u16)iMethod; in zipfileUpdate()
11020 zipfileMtimeToDos(&pNew->cds, mTime); in zipfileUpdate()
11021 pNew->cds.crc32 = iCrc32; in zipfileUpdate()
11022 pNew->cds.szCompressed = nData; in zipfileUpdate()
11023 pNew->cds.szUncompressed = (u32)sz; in zipfileUpdate()
11024 pNew->cds.iExternalAttr = (mode<<16); in zipfileUpdate()
11025 pNew->cds.iOffset = (u32)pTab->szCurrent; in zipfileUpdate()
11026 pNew->cds.nFile = (u16)nPath; in zipfileUpdate()
11027 pNew->mUnixTime = (u32)mTime; in zipfileUpdate()
11036 for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ in zipfileUpdate()
11037 if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){ in zipfileUpdate()
11038 pCsr->pCurrent = pCsr->pCurrent->pNext; in zipfileUpdate()
11039 pCsr->bNoop = 1; in zipfileUpdate()
11056 zipfileWrite16(a, p->iDisk); in zipfileSerializeEOCD()
11057 zipfileWrite16(a, p->iFirstDisk); in zipfileSerializeEOCD()
11058 zipfileWrite16(a, p->nEntry); in zipfileSerializeEOCD()
11059 zipfileWrite16(a, p->nEntryTotal); in zipfileSerializeEOCD()
11060 zipfileWrite32(a, p->nSize); in zipfileSerializeEOCD()
11061 zipfileWrite32(a, p->iOffset); in zipfileSerializeEOCD()
11064 return a-aBuf; in zipfileSerializeEOCD()
11068 int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer); in zipfileAppendEOCD()
11070 return zipfileAppendData(pTab, pTab->aBuffer, nBuf); in zipfileAppendEOCD()
11079 ZipfileCDS *pCDS = &pEntry->cds; in zipfileSerializeCDS()
11081 if( pEntry->aExtra==0 ){ in zipfileSerializeCDS()
11082 pCDS->nExtra = 9; in zipfileSerializeCDS()
11086 zipfileWrite16(a, pCDS->iVersionMadeBy); in zipfileSerializeCDS()
11087 zipfileWrite16(a, pCDS->iVersionExtract); in zipfileSerializeCDS()
11088 zipfileWrite16(a, pCDS->flags); in zipfileSerializeCDS()
11089 zipfileWrite16(a, pCDS->iCompression); in zipfileSerializeCDS()
11090 zipfileWrite16(a, pCDS->mTime); in zipfileSerializeCDS()
11091 zipfileWrite16(a, pCDS->mDate); in zipfileSerializeCDS()
11092 zipfileWrite32(a, pCDS->crc32); in zipfileSerializeCDS()
11093 zipfileWrite32(a, pCDS->szCompressed); in zipfileSerializeCDS()
11094 zipfileWrite32(a, pCDS->szUncompressed); in zipfileSerializeCDS()
11096 zipfileWrite16(a, pCDS->nFile); in zipfileSerializeCDS()
11097 zipfileWrite16(a, pCDS->nExtra); in zipfileSerializeCDS()
11098 zipfileWrite16(a, pCDS->nComment); in zipfileSerializeCDS()
11099 zipfileWrite16(a, pCDS->iDiskStart); in zipfileSerializeCDS()
11100 zipfileWrite16(a, pCDS->iInternalAttr); in zipfileSerializeCDS()
11101 zipfileWrite32(a, pCDS->iExternalAttr); in zipfileSerializeCDS()
11102 zipfileWrite32(a, pCDS->iOffset); in zipfileSerializeCDS()
11104 memcpy(a, pCDS->zFile, pCDS->nFile); in zipfileSerializeCDS()
11105 a += pCDS->nFile; in zipfileSerializeCDS()
11107 if( pEntry->aExtra ){ in zipfileSerializeCDS()
11108 int n = (int)pCDS->nExtra + (int)pCDS->nComment; in zipfileSerializeCDS()
11109 memcpy(a, pEntry->aExtra, n); in zipfileSerializeCDS()
11112 assert( pCDS->nExtra==9 ); in zipfileSerializeCDS()
11116 zipfileWrite32(a, pEntry->mUnixTime); in zipfileSerializeCDS()
11119 return a-aBuf; in zipfileSerializeCDS()
11125 if( pTab->pWriteFd ){ in zipfileCommit()
11126 i64 iOffset = pTab->szCurrent; in zipfileCommit()
11132 for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){ in zipfileCommit()
11133 int n = zipfileSerializeCDS(p, pTab->aBuffer); in zipfileCommit()
11134 rc = zipfileAppendData(pTab, pTab->aBuffer, n); in zipfileCommit()
11143 eocd.nSize = (u32)(pTab->szCurrent - iOffset); in zipfileCommit()
11158 for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ in zipfileFindCursor()
11159 if( iId==pCsr->iId ) break; in zipfileFindCursor()
11175 ZipfileCDS *p = &pCsr->pCurrent->cds; in zipfileFunctionCds()
11177 "\"version-made-by\" : %u, " in zipfileFunctionCds()
11178 "\"version-to-extract\" : %u, " in zipfileFunctionCds()
11184 "\"compressed-size\" : %u, " in zipfileFunctionCds()
11185 "\"uncompressed-size\" : %u, " in zipfileFunctionCds()
11186 "\"file-name-length\" : %u, " in zipfileFunctionCds()
11187 "\"extra-field-length\" : %u, " in zipfileFunctionCds()
11188 "\"file-comment-length\" : %u, " in zipfileFunctionCds()
11189 "\"disk-number-start\" : %u, " in zipfileFunctionCds()
11190 "\"internal-attr\" : %u, " in zipfileFunctionCds()
11191 "\"external-attr\" : %u, " in zipfileFunctionCds()
11193 (u32)p->iVersionMadeBy, (u32)p->iVersionExtract, in zipfileFunctionCds()
11194 (u32)p->flags, (u32)p->iCompression, in zipfileFunctionCds()
11195 (u32)p->mTime, (u32)p->mDate, in zipfileFunctionCds()
11196 (u32)p->crc32, (u32)p->szCompressed, in zipfileFunctionCds()
11197 (u32)p->szUncompressed, (u32)p->nFile, in zipfileFunctionCds()
11198 (u32)p->nExtra, (u32)p->nComment, in zipfileFunctionCds()
11199 (u32)p->iDiskStart, (u32)p->iInternalAttr, in zipfileFunctionCds()
11200 (u32)p->iExternalAttr, (u32)p->iOffset in zipfileFunctionCds()
11206 sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT); in zipfileFunctionCds()
11246 if( pBuf->n+nByte>pBuf->nAlloc ){ in zipfileBufferGrow()
11248 sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512; in zipfileBufferGrow()
11249 int nReq = pBuf->n + nByte; in zipfileBufferGrow()
11252 aNew = sqlite3_realloc64(pBuf->a, nNew); in zipfileBufferGrow()
11254 pBuf->a = aNew; in zipfileBufferGrow()
11255 pBuf->nAlloc = (int)nNew; in zipfileBufferGrow()
11283 int iMethod = -1; /* Compression method to use (0 or 8) */ in zipfileStep()
11322 zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL"); in zipfileStep()
11375 if( nName>0 && zName[nName-1]=='/' ){ in zipfileStep()
11376 zErr = sqlite3_mprintf("non-directory name must not end with /"); in zipfileStep()
11381 if( nName==0 || zName[nName-1]!='/' ){ in zipfileStep()
11389 while( nName>1 && zName[nName-2]=='/' ) nName--; in zipfileStep()
11403 e.cds.iOffset = p->body.n; in zipfileStep()
11409 if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out; in zipfileStep()
11410 p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]); in zipfileStep()
11414 if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out; in zipfileStep()
11415 memcpy(&p->body.a[p->body.n], aData, nData); in zipfileStep()
11416 p->body.n += nData; in zipfileStep()
11421 if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out; in zipfileStep()
11422 p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]); in zipfileStep()
11425 p->nEntry++; in zipfileStep()
11432 sqlite3_result_error(pCtx, zErr, -1); in zipfileStep()
11451 if( p->nEntry>0 ){ in zipfileFinal()
11453 eocd.nEntry = (u16)p->nEntry; in zipfileFinal()
11454 eocd.nEntryTotal = (u16)p->nEntry; in zipfileFinal()
11455 eocd.nSize = p->cds.n; in zipfileFinal()
11456 eocd.iOffset = p->body.n; in zipfileFinal()
11458 nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ; in zipfileFinal()
11463 memcpy(aZip, p->body.a, p->body.n); in zipfileFinal()
11464 memcpy(&aZip[p->body.n], p->cds.a, p->cds.n); in zipfileFinal()
11465 zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]); in zipfileFinal()
11470 sqlite3_free(p->body.a); in zipfileFinal()
11471 sqlite3_free(p->cds.a); in zipfileFinal()
11486 zipfileOpen, /* xOpen - open a cursor */ in zipfileRegister()
11487 zipfileClose, /* xClose - close a cursor */ in zipfileRegister()
11488 zipfileFilter, /* xFilter - configure scan constraints */ in zipfileRegister()
11489 zipfileNext, /* xNext - advance a cursor */ in zipfileRegister()
11490 zipfileEof, /* xEof - check for end of scan */ in zipfileRegister()
11491 zipfileColumn, /* xColumn - read data */ in zipfileRegister()
11492 0, /* xRowid - read data */ in zipfileRegister()
11508 if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1); in zipfileRegister()
11510 rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0, in zipfileRegister()
11540 ** 2017-12-17
11552 ** for working with sqlar archives and used by the shell tool's built-in
11568 ** contains a two-byte identification header and a four-byte checksum at
11593 sqlite3_result_error(context, "error in compress()", -1); in sqlarCompressFunc()
11635 sqlite3_result_error(context, "error in uncompress()", -1); in sqlarUncompressFunc()
11691 ** an English-language error message. In this case it is the responsibility
11711 ** the analysis - indexes are recommended based on the database schema only.
11735 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
11736 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
11771 ** possible to add further SQL statements to the object or to re-attempt
11789 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
11797 ** If an out-of-range value (less than zero or equal to or greater than the
11831 ** sqlite3-expert_new().
11896 ** any other type of single-ended range constraint on a column).
11942 ** An object of the following type is created for each unique table/write-op
11943 ** seen. The objects are stored in a singly-linked list beginning at
11978 char *zKey; /* nul-terminated key */
11979 char *zVal; /* nul-terminated value string */
11980 char *zVal2; /* nul-terminated value string 2 */
11995 sqlite3 *dbm; /* In-memory db for this analysis */
12041 for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){ in idxHashClear()
12042 pNext = pEntry->pHashNext; in idxHashClear()
12043 sqlite3_free(pEntry->zVal2); in idxHashClear()
12064 ** If zKey is already present in the hash table, return non-zero and do
12079 for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){ in idxHashAdd()
12080 if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){ in idxHashAdd()
12086 pEntry->zKey = (char*)&pEntry[1]; in idxHashAdd()
12087 memcpy(pEntry->zKey, zKey, nKey); in idxHashAdd()
12089 pEntry->zVal = &pEntry->zKey[nKey+1]; in idxHashAdd()
12090 memcpy(pEntry->zVal, zVal, nVal); in idxHashAdd()
12092 pEntry->pHashNext = pHash->aHash[iHash]; in idxHashAdd()
12093 pHash->aHash[iHash] = pEntry; in idxHashAdd()
12095 pEntry->pNext = pHash->pFirst; in idxHashAdd()
12096 pHash->pFirst = pEntry; in idxHashAdd()
12103 ** hash-entry object.
12111 for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){ in idxHashFind()
12112 if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){ in idxHashFind()
12127 if( pEntry ) return pEntry->zVal; in idxHashSearch()
12133 ** variable to point to a copy of nul-terminated string zColl.
12142 pNew->zColl = (char*)&pNew[1]; in idxNewConstraint()
12143 memcpy(pNew->zColl, zColl, nColl+1); in idxNewConstraint()
12168 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); in idxPrepareStmt()
12223 assert( zIn[n-1]=='\'' ); in expertDequote()
12228 for(iIn=1; iIn<(n-1); iIn++){ in expertDequote()
12243 ** methods of the r-tree virtual table.
12245 ** argv[0] -> module name
12246 ** argv[1] -> database name
12247 ** argv[2] -> table name
12248 ** argv[...] -> column names...
12272 p->pExpert = pExpert; in expertConnect()
12273 p->pTab = pExpert->pTable; in expertConnect()
12274 assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 ); in expertConnect()
12307 pScan->pTab = p->pTab; in expertBestIndex()
12308 pScan->pNextScan = p->pExpert->pScan; in expertBestIndex()
12309 p->pExpert->pScan = pScan; in expertBestIndex()
12312 for(i=0; i<pIdxInfo->nConstraint; i++){ in expertBestIndex()
12313 struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; in expertBestIndex()
12314 if( pCons->usable in expertBestIndex()
12315 && pCons->iColumn>=0 in expertBestIndex()
12316 && p->pTab->aCol[pCons->iColumn].iPk==0 in expertBestIndex()
12317 && (pCons->op & opmask) in expertBestIndex()
12323 pNew->iCol = pCons->iColumn; in expertBestIndex()
12324 if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ in expertBestIndex()
12325 pNew->pNext = pScan->pEq; in expertBestIndex()
12326 pScan->pEq = pNew; in expertBestIndex()
12328 pNew->bRange = 1; in expertBestIndex()
12329 pNew->pNext = pScan->pRange; in expertBestIndex()
12330 pScan->pRange = pNew; in expertBestIndex()
12334 pIdxInfo->aConstraintUsage[i].argvIndex = n; in expertBestIndex()
12339 for(i=pIdxInfo->nOrderBy-1; i>=0; i--){ in expertBestIndex()
12340 int iCol = pIdxInfo->aOrderBy[i].iColumn; in expertBestIndex()
12342 IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl); in expertBestIndex()
12344 pNew->iCol = iCol; in expertBestIndex()
12345 pNew->bDesc = pIdxInfo->aOrderBy[i].desc; in expertBestIndex()
12346 pNew->pNext = pScan->pOrder; in expertBestIndex()
12347 pNew->pLink = pScan->pOrder; in expertBestIndex()
12348 pScan->pOrder = pNew; in expertBestIndex()
12355 pIdxInfo->estimatedCost = 1000000.0 / (n+1); in expertBestIndex()
12389 sqlite3_finalize(pCsr->pData); in expertClose()
12397 ** Return non-zero if the cursor does not currently point to a valid
12402 return pCsr->pData==0; in expertEof()
12412 assert( pCsr->pData ); in expertNext()
12413 rc = sqlite3_step(pCsr->pData); in expertNext()
12415 rc = sqlite3_finalize(pCsr->pData); in expertNext()
12416 pCsr->pData = 0; in expertNext()
12439 pVal = sqlite3_column_value(pCsr->pData, i); in expertColumn()
12455 ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab); in expertFilter()
12456 sqlite3expert *pExpert = pVtab->pExpert; in expertFilter()
12463 rc = sqlite3_finalize(pCsr->pData); in expertFilter()
12464 pCsr->pData = 0; in expertFilter()
12466 rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg, in expertFilter()
12467 "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName in expertFilter()
12480 expertConnect, /* xCreate - create a table */ in idxRegisterVtab()
12481 expertConnect, /* xConnect - connect to an existing table */ in idxRegisterVtab()
12482 expertBestIndex, /* xBestIndex - Determine search strategy */ in idxRegisterVtab()
12483 expertDisconnect, /* xDisconnect - Disconnect from a table */ in idxRegisterVtab()
12484 expertDisconnect, /* xDestroy - Drop a table */ in idxRegisterVtab()
12485 expertOpen, /* xOpen - open a cursor */ in idxRegisterVtab()
12486 expertClose, /* xClose - close a cursor */ in idxRegisterVtab()
12487 expertFilter, /* xFilter - configure scan constraints */ in idxRegisterVtab()
12488 expertNext, /* xNext - advance a cursor */ in idxRegisterVtab()
12490 expertColumn, /* xColumn - read data */ in idxRegisterVtab()
12491 expertRowid, /* xRowid - read data */ in idxRegisterVtab()
12492 expertUpdate, /* xUpdate - write data */ in idxRegisterVtab()
12493 0, /* xBegin - begin transaction */ in idxRegisterVtab()
12494 0, /* xSync - sync transaction */ in idxRegisterVtab()
12495 0, /* xCommit - commit transaction */ in idxRegisterVtab()
12496 0, /* xRollback - rollback transaction */ in idxRegisterVtab()
12497 0, /* xFindFunction - function overloading */ in idxRegisterVtab()
12498 0, /* xRename - rename the table */ in idxRegisterVtab()
12506 return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p); in idxRegisterVtab()
12575 pNew->aCol = (IdxColumn*)&pNew[1]; in idxGetTableInfo()
12576 pNew->nCol = nCol; in idxGetTableInfo()
12577 pCsr = (char*)&pNew->aCol[nCol]; in idxGetTableInfo()
12587 pNew->aCol[nCol].zName = pCsr; in idxGetTableInfo()
12588 pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1); in idxGetTableInfo()
12598 pNew->aCol[nCol].zColl = pCsr; in idxGetTableInfo()
12611 pNew->zName = pCsr; in idxGetTableInfo()
12612 if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1); in idxGetTableInfo()
12620 ** This function is a no-op if *pRc is set to anything other than
12689 IdxColumn *p = &pTab->aCol[pCons->iCol]; in idxAppendColDefn()
12692 if( idxIdentifierRequiresQuotes(p->zName) ){ in idxAppendColDefn()
12693 zRet = idxAppendText(pRc, zRet, "%Q", p->zName); in idxAppendColDefn()
12695 zRet = idxAppendText(pRc, zRet, "%s", p->zName); in idxAppendColDefn()
12698 if( sqlite3_stricmp(p->zColl, pCons->zColl) ){ in idxAppendColDefn()
12699 if( idxIdentifierRequiresQuotes(pCons->zColl) ){ in idxAppendColDefn()
12700 zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl); in idxAppendColDefn()
12702 zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl); in idxAppendColDefn()
12706 if( pCons->bDesc ){ in idxAppendColDefn()
12715 ** such an index is found, return non-zero. Or, if no such index is found,
12727 const char *zTbl = pScan->pTab->zName; in idxFindCompatible()
12734 for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++; in idxFindCompatible()
12745 for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0; in idxFindCompatible()
12754 for(pIter=pEq; pIter; pIter=pIter->pLink){ in idxFindCompatible()
12755 if( pIter->bFlag ) continue; in idxFindCompatible()
12756 if( pIter->iCol!=iCol ) continue; in idxFindCompatible()
12757 if( sqlite3_stricmp(pIter->zColl, zColl) ) continue; in idxFindCompatible()
12758 pIter->bFlag = 1; in idxFindCompatible()
12767 if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){ in idxFindCompatible()
12771 pT = pT->pLink; in idxFindCompatible()
12807 sqlite3 *dbm = p->dbm; in idxCreateFromCons()
12810 IdxTable *pTab = pScan->pTab; in idxCreateFromCons()
12817 for(pCons=pEq; pCons; pCons=pCons->pLink){ in idxCreateFromCons()
12820 for(pCons=pTail; pCons; pCons=pCons->pLink){ in idxCreateFromCons()
12826 const char *zTable = pScan->pTab->zName; in idxCreateFromCons()
12868 rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg); in idxCreateFromCons()
12872 idxHashAdd(&rc, &p->hIdx, zName, zIdx); in idxCreateFromCons()
12891 for(pCmp=pList; pCmp; pCmp=pCmp->pLink){ in idxFindConstraint()
12892 if( p->iCol==pCmp->iCol ) return 1; in idxFindConstraint()
12907 for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){ in idxCreateFromWhere()
12909 pCon->pLink = p1; in idxCreateFromWhere()
12921 for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){ in idxCreateFromWhere()
12922 assert( pCon->pLink==0 ); in idxCreateFromWhere()
12934 ** linked-list pScan.
12940 for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){ in idxCreateCandidates()
12942 if( rc==SQLITE_OK && pIter->pOrder ){ in idxCreateCandidates()
12943 rc = idxCreateFromWhere(p, pIter, pIter->pOrder); in idxCreateCandidates()
12958 pNext = p->pNext; in idxConstraintFree()
12971 pNext = p->pNextScan; in idxScanFree()
12972 idxConstraintFree(p->pOrder); in idxScanFree()
12973 idxConstraintFree(p->pEq); in idxScanFree()
12974 idxConstraintFree(p->pRange); in idxScanFree()
12987 pNext = p->pNext; in idxStatementFree()
12988 sqlite3_free(p->zEQP); in idxStatementFree()
12989 sqlite3_free(p->zIdx); in idxStatementFree()
13001 pNext = pIter->pNext; in idxTableFree()
13013 pNext = pIter->pNext; in idxWriteFree()
13030 sqlite3 *dbm = p->dbm; in idxFindIndexes()
13036 for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){ in idxFindIndexes()
13041 "EXPLAIN QUERY PLAN %s", pStmt->zSql in idxFindIndexes()
13069 zSql = idxHashSearch(&p->hIdx, zIdx, nIdx); in idxFindIndexes()
13078 if( zDetail[0]!='-' ){ in idxFindIndexes()
13079 pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail); in idxFindIndexes()
13083 for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){ in idxFindIndexes()
13084 pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey); in idxFindIndexes()
13110 for(pTab=p->pTable; pTab; pTab=pTab->pNext){ in idxAuthCallback()
13111 if( 0==sqlite3_stricmp(z3, pTab->zName) ) break; in idxAuthCallback()
13115 for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){ in idxAuthCallback()
13116 if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break; in idxAuthCallback()
13121 pWrite->pTab = pTab; in idxAuthCallback()
13122 pWrite->eOp = eOp; in idxAuthCallback()
13123 pWrite->pNext = p->pWrite; in idxAuthCallback()
13124 p->pWrite = pWrite; in idxAuthCallback()
13140 IdxTable *pTab = pWrite->pTab; in idxProcessOneTrigger()
13141 const char *zTab = pTab->zName; in idxProcessOneTrigger()
13151 rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab); in idxProcessOneTrigger()
13155 rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr); in idxProcessOneTrigger()
13165 rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr); in idxProcessOneTrigger()
13170 switch( pWrite->eOp ){ in idxProcessOneTrigger()
13174 for(i=0; i<pTab->nCol; i++){ in idxProcessOneTrigger()
13183 for(i=0; i<pTab->nCol; i++){ in idxProcessOneTrigger()
13185 pTab->aCol[i].zName in idxProcessOneTrigger()
13191 assert( pWrite->eOp==SQLITE_DELETE ); in idxProcessOneTrigger()
13201 rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0); in idxProcessOneTrigger()
13204 idxDatabaseError(p->dbv, pzErr); in idxProcessOneTrigger()
13210 rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr); in idxProcessOneTrigger()
13219 IdxWrite *pFirst = p->pWrite; in idxProcessTriggers()
13223 for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){ in idxProcessTriggers()
13227 pFirst = p->pWrite; in idxProcessTriggers()
13240 ** 1) Add an entry to the p->pTable list, and in idxCreateVtabSchema()
13243 rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg, in idxCreateVtabSchema()
13259 if( zSql ) rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg); in idxCreateVtabSchema()
13262 rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg); in idxCreateVtabSchema()
13267 pTab->pNext = p->pTable; in idxCreateVtabSchema()
13268 p->pTable = pTab; in idxCreateVtabSchema()
13272 for(i=0; i<pTab->nCol; i++){ in idxCreateVtabSchema()
13274 (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl in idxCreateVtabSchema()
13284 rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg); in idxCreateVtabSchema()
13312 if( p->nRow==0.0 ){ in idxSampleFunc()
13315 bRet = (p->nRet / p->nRow) <= p->target; in idxSampleFunc()
13319 bRet = ((int)rnd % 100) <= p->iTarget; in idxSampleFunc()
13324 p->nRow += 1.0; in idxSampleFunc()
13325 p->nRet += (double)bRet; in idxSampleFunc()
13354 assert( iSlot<=p->nSlot ); in idxRemFunc()
13355 pSlot = &p->aSlot[iSlot]; in idxRemFunc()
13357 switch( pSlot->eType ){ in idxRemFunc()
13359 /* no-op */ in idxRemFunc()
13363 sqlite3_result_int64(pCtx, pSlot->iVal); in idxRemFunc()
13367 sqlite3_result_double(pCtx, pSlot->rVal); in idxRemFunc()
13371 sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT); in idxRemFunc()
13375 sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT); in idxRemFunc()
13379 pSlot->eType = sqlite3_value_type(argv[1]); in idxRemFunc()
13380 switch( pSlot->eType ){ in idxRemFunc()
13382 /* no-op */ in idxRemFunc()
13386 pSlot->iVal = sqlite3_value_int64(argv[1]); in idxRemFunc()
13390 pSlot->rVal = sqlite3_value_double(argv[1]); in idxRemFunc()
13397 if( nByte>pSlot->nByte ){ in idxRemFunc()
13398 char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2); in idxRemFunc()
13403 pSlot->nByte = nByte*2; in idxRemFunc()
13404 pSlot->z = zNew; in idxRemFunc()
13406 pSlot->n = nByte; in idxRemFunc()
13407 if( pSlot->eType==SQLITE_BLOB ){ in idxRemFunc()
13409 if( pData ) memcpy(pSlot->z, pData, nByte); in idxRemFunc()
13412 memcpy(pSlot->z, pData, nByte); in idxRemFunc()
13456 assert( p->iSample>0 ); in idxPopulateOneStat1()
13459 sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC); in idxPopulateOneStat1()
13471 if( p->iSample==100 ){ in idxPopulateOneStat1()
13486 sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv); in idxPopulateOneStat1()
13503 for(/*no-op*/; i<nCol; i++){ in idxPopulateOneStat1()
13518 sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC); in idxPopulateOneStat1()
13519 sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC); in idxPopulateOneStat1()
13520 sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC); in idxPopulateOneStat1()
13525 pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx)); in idxPopulateOneStat1()
13527 assert( pEntry->zVal2==0 ); in idxPopulateOneStat1()
13528 pEntry->zVal2 = zStat; in idxPopulateOneStat1()
13543 rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0); in idxBuildSampleTable()
13550 rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0); in idxBuildSampleTable()
13569 i64 iPrev = -100000; in idxPopulateStat1()
13584 if( p->iSample==0 ) return SQLITE_OK; in idxPopulateStat1()
13586 rc = idxLargestIndex(p->dbm, &nMax, pzErr); in idxPopulateStat1()
13589 rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0); in idxPopulateStat1()
13597 sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv); in idxPopulateStat1()
13604 p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0 in idxPopulateStat1()
13609 pCtx->nSlot = nMax+1; in idxPopulateStat1()
13610 rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex); in idxPopulateStat1()
13613 rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo); in idxPopulateStat1()
13616 rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite); in idxPopulateStat1()
13624 if( p->iSample<100 && iPrev!=iRowid ){ in idxPopulateStat1()
13625 samplectx.target = (double)p->iSample / 100.0; in idxPopulateStat1()
13626 samplectx.iTarget = p->iSample; in idxPopulateStat1()
13635 if( rc==SQLITE_OK && p->iSample<100 ){ in idxPopulateStat1()
13636 rc = sqlite3_exec(p->dbv, in idxPopulateStat1()
13646 for(i=0; i<pCtx->nSlot; i++){ in idxPopulateStat1()
13647 sqlite3_free(pCtx->aSlot[i].z); in idxPopulateStat1()
13653 rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0); in idxPopulateStat1()
13656 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0); in idxPopulateStat1()
13682 ** dummy functions for no-op implementation of UDFs during expert's work
13703 "WHERE builtin==0", -1, &pStmt, 0); in registerUDFs()
13712 /* no-op. Only happens on OOM */ in registerUDFs()
13751 /* Open two in-memory databases to work with. The "vtab database" (dbv) in sqlite3_expert_new()
13758 pNew->db = db; in sqlite3_expert_new()
13759 pNew->iSample = 100; in sqlite3_expert_new()
13760 rc = sqlite3_open(":memory:", &pNew->dbv); in sqlite3_expert_new()
13763 rc = sqlite3_open(":memory:", &pNew->dbm); in sqlite3_expert_new()
13765 sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0); in sqlite3_expert_new()
13770 if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbm,0,useDummyCS); in sqlite3_expert_new()
13771 if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbv,0,useDummyCS); in sqlite3_expert_new()
13777 rc = registerUDFs(pNew->db, pNew->dbm); in sqlite3_expert_new()
13780 rc = registerUDFs(pNew->db, pNew->dbv); in sqlite3_expert_new()
13787 rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg, in sqlite3_expert_new()
13793 if( zSql ) rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg); in sqlite3_expert_new()
13805 sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew); in sqlite3_expert_new()
13829 p->iSample = iVal; in sqlite3_expert_config()
13849 IdxScan *pScanOrig = p->pScan; in sqlite3_expert_sql()
13850 IdxStatement *pStmtOrig = p->pStatement; in sqlite3_expert_sql()
13854 if( p->bRun ) return SQLITE_MISUSE; in sqlite3_expert_sql()
13859 rc = idxPrepareStmt(p->db, &pStmt, pzErr, zStmt); in sqlite3_expert_sql()
13862 rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt); in sqlite3_expert_sql()
13870 pNew->zSql = (char*)&pNew[1]; in sqlite3_expert_sql()
13871 memcpy(pNew->zSql, z, n+1); in sqlite3_expert_sql()
13872 pNew->pNext = p->pStatement; in sqlite3_expert_sql()
13873 if( p->pStatement ) pNew->iId = p->pStatement->iId+1; in sqlite3_expert_sql()
13874 p->pStatement = pNew; in sqlite3_expert_sql()
13879 idxDatabaseError(p->dbv, pzErr); in sqlite3_expert_sql()
13884 idxScanFree(p->pScan, pScanOrig); in sqlite3_expert_sql()
13885 idxStatementFree(p->pStatement, pStmtOrig); in sqlite3_expert_sql()
13886 p->pScan = pScanOrig; in sqlite3_expert_sql()
13887 p->pStatement = pStmtOrig; in sqlite3_expert_sql()
13900 /* Create candidate indexes within the in-memory database file */ in sqlite3_expert_analyze()
13915 for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){ in sqlite3_expert_analyze()
13916 p->zCandidates = idxAppendText(&rc, p->zCandidates, in sqlite3_expert_analyze()
13917 "%s;%s%s\n", pEntry->zVal, in sqlite3_expert_analyze()
13918 pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2 in sqlite3_expert_analyze()
13929 p->bRun = 1; in sqlite3_expert_analyze()
13940 if( p->pStatement ) nRet = p->pStatement->iId+1; in sqlite3_expert_count()
13951 if( p->bRun==0 ) return 0; in sqlite3_expert_report()
13952 for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext); in sqlite3_expert_report()
13955 if( pStmt ) zRet = pStmt->zSql; in sqlite3_expert_report()
13958 if( pStmt ) zRet = pStmt->zIdx; in sqlite3_expert_report()
13961 if( pStmt ) zRet = pStmt->zEQP; in sqlite3_expert_report()
13964 zRet = p->zCandidates; in sqlite3_expert_report()
13975 sqlite3_close(p->dbm); in sqlite3_expert_destroy()
13976 sqlite3_close(p->dbv); in sqlite3_expert_destroy()
13977 idxScanFree(p->pScan, 0); in sqlite3_expert_destroy()
13978 idxStatementFree(p->pStatement, 0); in sqlite3_expert_destroy()
13979 idxTableFree(p->pTable); in sqlite3_expert_destroy()
13980 idxWriteFree(p->pWrite); in sqlite3_expert_destroy()
13981 idxHashClear(&p->hIdx); in sqlite3_expert_destroy()
13982 sqlite3_free(p->zCandidates); in sqlite3_expert_destroy()
13999 ** 2022-08-27
14010 ** This file contains the public interface to the "recover" extension -
14030 ** error. If it returns some other non-SQLITE_OK value, then an error
14099 ** nul-terminated buffer containing the SQL statement formated as UTF-8 as
14104 ** If an out-of-memory error occurs, NULL may be returned instead of
14139 ** of a "lost-and-found" table in the output database, or NULL. If
14140 ** the argument is non-NULL and the database contains seemingly
14143 ** pages to add to the lost-and-found table.
14148 ** (argument is 1) and a lost-and-found table has been configured using
14168 ** module creates and populates non-UNIQUE indexes right at the end of the
14169 ** recovery operation - after all recoverable data has been inserted
14174 ** Or, if this option is set (argument is 1), then non-UNIQUE indexes
14198 ** all further such calls on the same recover handle are no-ops that return
14199 ** the same non-SQLITE_OK value.
14217 ** the error. If no error message is available, or if an out-of memory
14252 ** 2019-04-17
14268 ** sqlite_dbdata is used to extract data directly from a database b-tree
14269 ** page and its associated overflow pages, bypassing the b-tree layer.
14281 ** FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
14285 ** a b-tree page, or if it is a b-tree page containing 0 entries, the
14288 ** each cell on the page. For intkey b-trees, the key value is stored in
14289 ** field -1.
14293 ** CREATE TABLE t1(a, b); -- root page is page 2
14301 ** (2, 0, -1, 5 ),
14304 ** (2, 1, -1, 10 ),
14321 ** It contains one entry for each b-tree pointer between a parent and
14426 pTab->db = db; in dbdataConnect()
14427 pTab->bPtr = (pAux!=0); in dbdataConnect()
14441 sqlite3_finalize(pTab->pStmt); in dbdataDisconnect()
14463 int iSchema = -1; in dbdataBestIndex()
14464 int iPgno = -1; in dbdataBestIndex()
14465 int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA); in dbdataBestIndex()
14467 for(i=0; i<pIdx->nConstraint; i++){ in dbdataBestIndex()
14468 struct sqlite3_index_constraint *p = &pIdx->aConstraint[i]; in dbdataBestIndex()
14469 if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ in dbdataBestIndex()
14470 if( p->iColumn==colSchema ){ in dbdataBestIndex()
14471 if( p->usable==0 ) return SQLITE_CONSTRAINT; in dbdataBestIndex()
14474 if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){ in dbdataBestIndex()
14481 pIdx->aConstraintUsage[iSchema].argvIndex = 1; in dbdataBestIndex()
14482 pIdx->aConstraintUsage[iSchema].omit = 1; in dbdataBestIndex()
14485 pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0); in dbdataBestIndex()
14486 pIdx->aConstraintUsage[iPgno].omit = 1; in dbdataBestIndex()
14487 pIdx->estimatedCost = 100; in dbdataBestIndex()
14488 pIdx->estimatedRows = 50; in dbdataBestIndex()
14490 if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){ in dbdataBestIndex()
14491 int iCol = pIdx->aOrderBy[0].iColumn; in dbdataBestIndex()
14492 if( pIdx->nOrderBy==1 ){ in dbdataBestIndex()
14493 pIdx->orderByConsumed = (iCol==0 || iCol==1); in dbdataBestIndex()
14494 }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){ in dbdataBestIndex()
14495 pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1); in dbdataBestIndex()
14500 pIdx->estimatedCost = 100000000; in dbdataBestIndex()
14501 pIdx->estimatedRows = 1000000000; in dbdataBestIndex()
14503 pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00); in dbdataBestIndex()
14518 pCsr->base.pVtab = pVTab; in dbdataOpen()
14530 DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab); in dbdataResetCursor()
14531 if( pTab->pStmt==0 ){ in dbdataResetCursor()
14532 pTab->pStmt = pCsr->pStmt; in dbdataResetCursor()
14534 sqlite3_finalize(pCsr->pStmt); in dbdataResetCursor()
14536 pCsr->pStmt = 0; in dbdataResetCursor()
14537 pCsr->iPgno = 1; in dbdataResetCursor()
14538 pCsr->iCell = 0; in dbdataResetCursor()
14539 pCsr->iField = 0; in dbdataResetCursor()
14540 pCsr->bOnePage = 0; in dbdataResetCursor()
14541 sqlite3_free(pCsr->aPage); in dbdataResetCursor()
14542 sqlite3_free(pCsr->pRec); in dbdataResetCursor()
14543 pCsr->pRec = 0; in dbdataResetCursor()
14544 pCsr->aPage = 0; in dbdataResetCursor()
14558 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
14588 sqlite3_stmt *pStmt = pCsr->pStmt; in dbdataLoadPage()
14669 return ((eType-12) / 2); in dbdataValueBytes()
14724 int n = ((eType-12) / 2); in dbdataValue()
14752 DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; in dbdataNext()
14754 pCsr->iRowid++; in dbdataNext()
14757 int iOff = (pCsr->iPgno==1 ? 100 : 0); in dbdataNext()
14760 if( pCsr->aPage==0 ){ in dbdataNext()
14762 if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK; in dbdataNext()
14763 rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage); in dbdataNext()
14765 if( pCsr->aPage && pCsr->nPage>=256 ) break; in dbdataNext()
14766 sqlite3_free(pCsr->aPage); in dbdataNext()
14767 pCsr->aPage = 0; in dbdataNext()
14768 if( pCsr->bOnePage ) return SQLITE_OK; in dbdataNext()
14769 pCsr->iPgno++; in dbdataNext()
14772 assert( iOff+3+2<=pCsr->nPage ); in dbdataNext()
14773 pCsr->iCell = pTab->bPtr ? -2 : 0; in dbdataNext()
14774 pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]); in dbdataNext()
14777 if( pTab->bPtr ){ in dbdataNext()
14778 if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){ in dbdataNext()
14779 pCsr->iCell = pCsr->nCell; in dbdataNext()
14781 pCsr->iCell++; in dbdataNext()
14782 if( pCsr->iCell>=pCsr->nCell ){ in dbdataNext()
14783 sqlite3_free(pCsr->aPage); in dbdataNext()
14784 pCsr->aPage = 0; in dbdataNext()
14785 if( pCsr->bOnePage ) return SQLITE_OK; in dbdataNext()
14786 pCsr->iPgno++; in dbdataNext()
14792 if( pCsr->pRec==0 ){ in dbdataNext()
14801 switch( pCsr->aPage[iOff] ){ in dbdataNext()
14811 /* This is not a b-tree page with records on it. Continue. */ in dbdataNext()
14812 pCsr->iCell = pCsr->nCell; in dbdataNext()
14816 if( pCsr->iCell>=pCsr->nCell ){ in dbdataNext()
14820 iOff += 8 + nPointer + pCsr->iCell*2; in dbdataNext()
14821 if( iOff>pCsr->nPage ){ in dbdataNext()
14824 iOff = get_uint16(&pCsr->aPage[iOff]); in dbdataNext()
14827 /* For an interior node cell, skip past the child-page number */ in dbdataNext()
14831 if( bNextPage || iOff>pCsr->nPage ){ in dbdataNext()
14834 iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload); in dbdataNext()
14838 if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){ in dbdataNext()
14839 iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey); in dbdataNext()
14843 U = pCsr->nPage; in dbdataNext()
14845 X = U-35; in dbdataNext()
14847 X = ((U-12)*64/255)-23; in dbdataNext()
14853 M = ((U-12)*32/255)-23; in dbdataNext()
14854 K = M+((nPayload-M)%(U-4)); in dbdataNext()
14862 if( bNextPage || nLocal+iOff>pCsr->nPage ){ in dbdataNext()
14869 pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES); in dbdataNext()
14870 if( pCsr->pRec==0 ) return SQLITE_NOMEM; in dbdataNext()
14871 memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES); in dbdataNext()
14872 pCsr->nRec = nPayload; in dbdataNext()
14875 memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal); in dbdataNext()
14880 sqlite3_int64 nRem = nPayload - nLocal; in dbdataNext()
14881 u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]); in dbdataNext()
14887 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage ); in dbdataNext()
14891 nCopy = U-4; in dbdataNext()
14893 memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy); in dbdataNext()
14894 nRem -= nCopy; in dbdataNext()
14901 iHdr = dbdataGetVarintU32(pCsr->pRec, &nHdr); in dbdataNext()
14903 pCsr->nHdr = nHdr; in dbdataNext()
14904 pCsr->pHdrPtr = &pCsr->pRec[iHdr]; in dbdataNext()
14905 pCsr->pPtr = &pCsr->pRec[pCsr->nHdr]; in dbdataNext()
14906 pCsr->iField = (bHasRowid ? -1 : 0); in dbdataNext()
14910 pCsr->iField++; in dbdataNext()
14911 if( pCsr->iField>0 ){ in dbdataNext()
14913 if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){ in dbdataNext()
14917 pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType); in dbdataNext()
14919 if( (pCsr->nRec - (pCsr->pPtr - pCsr->pRec))<szField ){ in dbdataNext()
14920 pCsr->pPtr = &pCsr->pRec[pCsr->nRec]; in dbdataNext()
14922 pCsr->pPtr += szField; in dbdataNext()
14929 sqlite3_free(pCsr->aPage); in dbdataNext()
14930 sqlite3_free(pCsr->pRec); in dbdataNext()
14931 pCsr->aPage = 0; in dbdataNext()
14932 pCsr->pRec = 0; in dbdataNext()
14933 if( pCsr->bOnePage ) return SQLITE_OK; in dbdataNext()
14934 pCsr->iPgno++; in dbdataNext()
14936 if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){ in dbdataNext()
14942 sqlite3_free(pCsr->pRec); in dbdataNext()
14943 pCsr->pRec = 0; in dbdataNext()
14944 pCsr->iCell++; in dbdataNext()
14958 return pCsr->aPage==0; in dbdataEof()
14962 ** Return true if nul-terminated string zSchema ends in "()". Or false
14967 if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){ in dbdataIsFunction()
14968 return (int)n-2; in dbdataIsFunction()
14976 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
14980 DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab; in dbdataDbsize()
14993 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0); in dbdataDbsize()
14996 pCsr->szDb = sqlite3_column_int(pStmt, 0); in dbdataDbsize()
15005 ** and inspecting the header field. If successful, set the pCsr->enc variable
15014 pCsr->enc = get_uint32(&aPg1[56]); in dbdataGetEncoding()
15030 DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; in dbdataFilter()
15037 assert( pCsr->iPgno==1 ); in dbdataFilter()
15043 pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]); in dbdataFilter()
15044 pCsr->bOnePage = 1; in dbdataFilter()
15051 if( pTab->pStmt ){ in dbdataFilter()
15052 pCsr->pStmt = pTab->pStmt; in dbdataFilter()
15053 pTab->pStmt = 0; in dbdataFilter()
15059 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0); in dbdataFilter()
15063 rc = sqlite3_prepare_v2(pTab->db, in dbdataFilter()
15064 "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1, in dbdataFilter()
15065 &pCsr->pStmt, 0 in dbdataFilter()
15070 rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT); in dbdataFilter()
15080 pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db)); in dbdataFilter()
15098 DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; in dbdataColumn()
15099 if( pTab->bPtr ){ in dbdataColumn()
15102 sqlite3_result_int64(ctx, pCsr->iPgno); in dbdataColumn()
15105 int iOff = pCsr->iPgno==1 ? 100 : 0; in dbdataColumn()
15106 if( pCsr->iCell<0 ){ in dbdataColumn()
15109 iOff += 12 + pCsr->iCell*2; in dbdataColumn()
15110 if( iOff>pCsr->nPage ) return SQLITE_OK; in dbdataColumn()
15111 iOff = get_uint16(&pCsr->aPage[iOff]); in dbdataColumn()
15113 if( iOff<=pCsr->nPage ){ in dbdataColumn()
15114 sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff])); in dbdataColumn()
15122 sqlite3_result_int64(ctx, pCsr->iPgno); in dbdataColumn()
15125 sqlite3_result_int(ctx, pCsr->iCell); in dbdataColumn()
15128 sqlite3_result_int(ctx, pCsr->iField); in dbdataColumn()
15131 if( pCsr->iField<0 ){ in dbdataColumn()
15132 sqlite3_result_int64(ctx, pCsr->iIntkey); in dbdataColumn()
15133 }else if( &pCsr->pRec[pCsr->nRec] >= pCsr->pPtr ){ in dbdataColumn()
15135 dbdataGetVarintU32(pCsr->pHdrPtr, &iType); in dbdataColumn()
15137 ctx, pCsr->enc, iType, pCsr->pPtr, in dbdataColumn()
15138 &pCsr->pRec[pCsr->nRec] - pCsr->pPtr in dbdataColumn()
15153 *pRowid = pCsr->iRowid; in dbdataRowid()
15169 dbdataOpen, /* xOpen - open a cursor */ in sqlite3DbdataRegister()
15170 dbdataClose, /* xClose - close a cursor */ in sqlite3DbdataRegister()
15171 dbdataFilter, /* xFilter - configure scan constraints */ in sqlite3DbdataRegister()
15172 dbdataNext, /* xNext - advance a cursor */ in sqlite3DbdataRegister()
15173 dbdataEof, /* xEof - check for end of scan */ in sqlite3DbdataRegister()
15174 dbdataColumn, /* xColumn - read data */ in sqlite3DbdataRegister()
15175 dbdataRowid, /* xRowid - read data */ in sqlite3DbdataRegister()
15211 ** 2022-08-27
15273 ** Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
15280 ** the output database, before any non-schema data are recovered. They
15281 ** are then stored in a singly-linked list linked by this variable beginning
15299 ** The index of the associated field within database records. Or -1 if
15352 u32 aElem[1]; /* Array of 32-bit bitmasks */
15411 char *zLostAndFound; /* Name of lost-and-found table (or NULL) */
15456 ** Populate the recovery.map table - used to figure out a "root" page
15461 ** Populate the lost-and-found table itself.
15497 ** recoverEnterMutex() - Enter the recovery mutex
15498 ** recoverLeaveMutex() - Leave the recovery mutex
15499 ** recoverAssertMutexHeld() - Assert that the recovery mutex is held
15530 ** This function is a no-op if the recover handle passed as the first
15531 ** argument already contains an error (if p->errCode!=SQLITE_OK).
15536 ** (p->errCode) set to SQLITE_NOMEM.
15541 if( p->errCode==SQLITE_OK ){ in recoverMalloc()
15546 p->errCode = SQLITE_NOMEM; in recoverMalloc()
15577 sqlite3_free(p->zErrMsg); in recoverError()
15578 p->zErrMsg = z; in recoverError()
15579 p->errCode = errCode; in recoverError()
15585 ** This function is a no-op if p->errCode is initially other than SQLITE_OK.
15598 pRet->nPg = nPg; in recoverBitmapAlloc()
15614 if( iPg<=pMap->nPg ){ in recoverBitmapSet()
15617 pMap->aElem[iElem] |= (((u32)1) << iBit); in recoverBitmapSet()
15627 if( iPg<=pMap->nPg && iPg>0 ){ in recoverBitmapQuery()
15630 ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0; in recoverBitmapQuery()
15645 ** This function is a no-op if recover handle p already contains an error
15646 ** (if p->errCode!=SQLITE_OK).
15659 if( p->errCode==SQLITE_OK ){ in recoverPrepare()
15660 if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){ in recoverPrepare()
15668 ** This function is a no-op if recover handle p already contains an error
15669 ** (if p->errCode!=SQLITE_OK).
15674 ** the statment handle returned. Or, if an error occurs - either during
15675 ** the printf() formatting or when preparing the resulting SQL - an
15684 if( p->errCode==SQLITE_OK ){ in recoverPreparePrintf()
15691 p->errCode = SQLITE_NOMEM; in recoverPreparePrintf()
15711 if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){ in recoverReset()
15726 if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){ in recoverFinalize()
15732 ** This function is a no-op if recover handle p already contains an error
15733 ** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this
15741 if( p->errCode==SQLITE_OK ){ in recoverExec()
15747 return p->errCode; in recoverExec()
15761 if( p->errCode==SQLITE_OK ){ in recoverBindValue()
15768 ** This function is a no-op if recover handle p already contains an error
15769 ** (if p->errCode!=SQLITE_OK). NULL is returned in this case.
15787 if( p->errCode==SQLITE_OK ){ in recoverMPrintf()
15788 if( z==0 ) p->errCode = SQLITE_NOMEM; in recoverMPrintf()
15797 ** This function is a no-op if recover handle p already contains an error
15798 ** (if p->errCode!=SQLITE_OK). Zero is returned in this case.
15807 if( p->errCode==SQLITE_OK ){ in recoverPageCount()
15809 pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb); in recoverPageCount()
15821 ** this function must be a blob. The second a non-negative integer. This
15822 ** function reads and returns a 32-bit big-endian integer from byte
15854 ** lost-and-found table, and it depends on those routines having populated
15857 ** The only argument to this function is a page-number. It returns true
15871 sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno)); in recoverPageIsUsed()
15875 ** The implementation of a user-defined SQL function invoked by the
15885 ** SELECT getpage(0); -- return number of pages in db
15886 ** SELECT getpage(4); -- return page 4 of db as a blob of data
15903 if( p->pGetPage==0 ){ in recoverGetPage()
15904 pStmt = p->pGetPage = recoverPreparePrintf( in recoverGetPage()
15905 p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb in recoverGetPage()
15907 }else if( p->errCode==SQLITE_OK ){ in recoverGetPage()
15908 pStmt = p->pGetPage; in recoverGetPage()
15916 assert( p->errCode==SQLITE_OK ); in recoverGetPage()
15919 if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){ in recoverGetPage()
15920 aPg = p->pPage1Disk; in recoverGetPage()
15922 sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT); in recoverGetPage()
15928 if( p->errCode ){ in recoverGetPage()
15929 if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1); in recoverGetPage()
15930 sqlite3_result_error_code(pCtx, p->errCode); in recoverGetPage()
15957 ** this function is the output of built-in function quote(). If the first
16046 ** This function is a no-op if recover handle p already contains an error
16047 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
16059 return recoverExec(p, p->dbOut, in recoverCacheSchema()
16080 ** this function is a no-op. Otherwise, issue a callback with SQL statement
16083 ** If the callback returns non-zero, set the recover handle error code to
16087 if( p->errCode==SQLITE_OK && p->xSql ){ in recoverSqlCallback()
16088 int res = p->xSql(p->pSqlCtx, zSql); in recoverSqlCallback()
16090 recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res); in recoverSqlCallback()
16099 ** + page-size,
16100 ** + auto-vacuum settings,
16102 ** + user-version (PRAGMA user_version), and
16103 ** + application-id (PRAGMA application_id), and
16118 if( p->errCode==SQLITE_OK ){ in recoverTransferSettings()
16129 p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag); in recoverTransferSettings()
16130 if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){ in recoverTransferSettings()
16144 if( p->errCode==SQLITE_OK ){ in recoverTransferSettings()
16145 sqlite3 *db = p->dbOut; in recoverTransferSettings()
16148 sqlite3_backup_step(pBackup, -1); in recoverTransferSettings()
16149 p->errCode = sqlite3_backup_finish(pBackup); in recoverTransferSettings()
16160 ** This function is a no-op if recover handle p already contains an error
16161 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
16189 assert( p->dbOut==0 ); in recoverOpenOutput()
16191 if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){ in recoverOpenOutput()
16196 ** These two are registered with the output database handle - this in recoverOpenOutput()
16199 if( p->errCode==SQLITE_OK ){ in recoverOpenOutput()
16200 p->errCode = sqlite3_dbdata_init(db, 0, 0); in recoverOpenOutput()
16203 /* Register the custom user-functions with the output handle. */ in recoverOpenOutput()
16205 p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0])); in recoverOpenOutput()
16207 p->errCode = sqlite3_create_function(db, aFunc[ii].zName, in recoverOpenOutput()
16212 p->dbOut = db; in recoverOpenOutput()
16213 return p->errCode; in recoverOpenOutput()
16222 char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb); in recoverOpenRecovery()
16223 recoverExec(p, p->dbOut, zSql); in recoverOpenRecovery()
16224 recoverExec(p, p->dbOut, in recoverOpenRecovery()
16234 ** This function is a no-op if recover handle p already contains an error
16235 ** (if p->errCode!=SQLITE_OK).
16251 sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut, in recoverAddTable()
16256 int iPk = -1; in recoverAddTable()
16274 pNew->aCol = (RecoverColumn*)&pNew[1]; in recoverAddTable()
16275 pNew->zTab = csr = (char*)&pNew->aCol[nCol]; in recoverAddTable()
16276 pNew->nCol = nCol; in recoverAddTable()
16277 pNew->iRoot = iRoot; in recoverAddTable()
16288 if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i; in recoverAddTable()
16289 if( iPKF>1 ) iPk = -2; in recoverAddTable()
16290 pNew->aCol[i].zCol = csr; in recoverAddTable()
16291 pNew->aCol[i].eHidden = eHidden; in recoverAddTable()
16293 pNew->aCol[i].iField = -1; in recoverAddTable()
16295 pNew->aCol[i].iField = iField++; in recoverAddTable()
16300 pNew->aCol[i].iBind = iBind++; in recoverAddTable()
16306 pNew->pNext = p->pTblList; in recoverAddTable()
16307 p->pTblList = pNew; in recoverAddTable()
16308 pNew->bIntkey = 1; in recoverAddTable()
16313 pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName); in recoverAddTable()
16318 assert( iCol<pNew->nCol ); in recoverAddTable()
16319 pNew->aCol[iCol].iField = iField; in recoverAddTable()
16321 pNew->bIntkey = 0; in recoverAddTable()
16322 iPk = -2; in recoverAddTable()
16326 if( p->errCode==SQLITE_OK ){ in recoverAddTable()
16328 pNew->aCol[iPk].bIPK = 1; in recoverAddTable()
16329 }else if( pNew->bIntkey ){ in recoverAddTable()
16330 pNew->iRowidBind = iBind++; in recoverAddTable()
16359 pSelect = recoverPrepare(p, p->dbOut, in recoverWriteSchema1()
16373 pTblname = recoverPrepare(p, p->dbOut, in recoverWriteSchema1()
16379 sqlite3_bind_int(pSelect, 1, p->bSlowIndexes); in recoverWriteSchema1()
16395 rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0); in recoverWriteSchema1()
16406 recoverDbError(p, p->dbOut); in recoverWriteSchema1()
16414 return p->errCode; in recoverWriteSchema1()
16420 ** database by recoverWriteSchema1() - everything except for tables and
16425 ** * non-UNIQUE indexes.
16433 pSelect = recoverPrepare(p, p->dbOut, in recoverWriteSchema2()
16434 p->bSlowIndexes ? in recoverWriteSchema2()
16445 int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0); in recoverWriteSchema2()
16449 recoverDbError(p, p->dbOut); in recoverWriteSchema2()
16455 return p->errCode; in recoverWriteSchema2()
16459 ** This function is a no-op if recover handle p already contains an error
16460 ** (if p->errCode!=SQLITE_OK). In this case it returns NULL.
16482 ** a single text value - itself an SQL statement similar to the above,
16505 int bSql = p->xSql ? 1 : 0; in recoverInsertStmt()
16509 assert( nField<=pTab->nCol ); in recoverInsertStmt()
16511 zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab); in recoverInsertStmt()
16513 if( pTab->iRowidBind ){ in recoverInsertStmt()
16514 assert( pTab->bIntkey ); in recoverInsertStmt()
16517 zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind); in recoverInsertStmt()
16519 zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind); in recoverInsertStmt()
16526 int eHidden = pTab->aCol[ii].eHidden; in recoverInsertStmt()
16530 assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 ); in recoverInsertStmt()
16531 zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol); in recoverInsertStmt()
16535 "%z%sescape_crnl(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind in recoverInsertStmt()
16539 zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind); in recoverInsertStmt()
16553 pRet = recoverPrepare(p, p->dbOut, zFinal); in recoverInsertStmt()
16563 ** Search the list of RecoverTable objects at p->pTblList for one that
16569 for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext); in recoverFindTable()
16590 pProbe = recoverPrepare(p, p->dbOut, in recoverLostAndFoundCreate()
16593 for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){ in recoverLostAndFoundCreate()
16596 zTbl = recoverMPrintf(p, "%s", p->zLostAndFound); in recoverLostAndFoundCreate()
16598 zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii); in recoverLostAndFoundCreate()
16601 if( p->errCode==SQLITE_OK ){ in recoverLostAndFoundCreate()
16602 sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC); in recoverLostAndFoundCreate()
16623 for(ii=0; p->errCode==SQLITE_OK && ii<nField; ii++){ in recoverLostAndFoundCreate()
16631 recoverExec(p, p->dbOut, zSql); in recoverLostAndFoundCreate()
16634 }else if( p->errCode==SQLITE_OK ){ in recoverLostAndFoundCreate()
16636 p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound in recoverLostAndFoundCreate()
16658 if( p->xSql==0 ){ in recoverLostAndFoundInsert()
16663 p, p->dbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind in recoverLostAndFoundInsert()
16672 p, p->dbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind in recoverLostAndFoundInsert()
16682 ** lost-and-found table of the output database. This function attempts
16694 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFoundFindRoot()
16696 if( pLaf->pFindRoot==0 ){ in recoverLostAndFoundFindRoot()
16697 pLaf->pFindRoot = recoverPrepare(p, p->dbOut, in recoverLostAndFoundFindRoot()
16707 if( p->errCode==SQLITE_OK ){ in recoverLostAndFoundFindRoot()
16708 sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg); in recoverLostAndFoundFindRoot()
16709 if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){ in recoverLostAndFoundFindRoot()
16710 *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0); in recoverLostAndFoundFindRoot()
16714 recoverReset(p, pLaf->pFindRoot); in recoverLostAndFoundFindRoot()
16716 return p->errCode; in recoverLostAndFoundFindRoot()
16721 ** the lost-and-found table in the output database.
16724 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFoundOnePage()
16725 sqlite3_value **apVal = pLaf->apVal; in recoverLostAndFoundOnePage()
16726 sqlite3_stmt *pPageData = pLaf->pPageData; in recoverLostAndFoundOnePage()
16727 sqlite3_stmt *pInsert = pLaf->pInsert; in recoverLostAndFoundOnePage()
16729 int nVal = -1; in recoverLostAndFoundOnePage()
16738 while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){ in recoverLostAndFoundOnePage()
16765 nVal = -1; in recoverLostAndFoundOnePage()
16771 assert( nVal==-1 ); in recoverLostAndFoundOnePage()
16775 }else if( iField<pLaf->nMaxField ){ in recoverLostAndFoundOnePage()
16778 assert( iField==nVal || (nVal==-1 && iField==0) ); in recoverLostAndFoundOnePage()
16798 ** RECOVER_STATE_LOSTANDFOUND3 state - during which the lost-and-found
16803 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound3Step()
16804 if( p->errCode==SQLITE_OK ){ in recoverLostAndFound3Step()
16805 if( pLaf->pInsert==0 ){ in recoverLostAndFound3Step()
16808 if( p->errCode==SQLITE_OK ){ in recoverLostAndFound3Step()
16809 int res = sqlite3_step(pLaf->pAllPage); in recoverLostAndFound3Step()
16811 i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0); in recoverLostAndFound3Step()
16812 if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){ in recoverLostAndFound3Step()
16816 recoverReset(p, pLaf->pAllPage); in recoverLostAndFound3Step()
16827 ** state - during which the lost-and-found table of the output database
16832 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound3Init()
16834 if( pLaf->nMaxField>0 ){ in recoverLostAndFound3Init()
16837 zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField); in recoverLostAndFound3Init()
16838 pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField); in recoverLostAndFound3Init()
16841 pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut, in recoverLostAndFound3Init()
16845 "SELECT ii FROM seq" , p->laf.nPg in recoverLostAndFound3Init()
16847 pLaf->pPageData = recoverPrepare(p, p->dbOut, in recoverLostAndFound3Init()
16851 "SELECT -1, -1, -1" in recoverLostAndFound3Init()
16854 pLaf->apVal = (sqlite3_value**)recoverMalloc(p, in recoverLostAndFound3Init()
16855 pLaf->nMaxField*sizeof(sqlite3_value*) in recoverLostAndFound3Init()
16861 ** Initialize resources required in RECOVER_STATE_WRITING state - during which
16866 RecoverStateW1 *p1 = &p->w1; in recoverWriteDataInit()
16871 assert( p1->nMax==0 ); in recoverWriteDataInit()
16872 for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){ in recoverWriteDataInit()
16873 if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol; in recoverWriteDataInit()
16878 nByte = sizeof(sqlite3_value*) * (p1->nMax+1); in recoverWriteDataInit()
16879 p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte); in recoverWriteDataInit()
16880 if( p1->apVal==0 ) return p->errCode; in recoverWriteDataInit()
16884 p1->pTbls = recoverPrepare(p, p->dbOut, in recoverWriteDataInit()
16889 p1->pSel = recoverPrepare(p, p->dbOut, in recoverWriteDataInit()
16902 return p->errCode; in recoverWriteDataInit()
16910 RecoverStateW1 *p1 = &p->w1; in recoverWriteDataCleanup()
16912 for(ii=0; ii<p1->nVal; ii++){ in recoverWriteDataCleanup()
16913 sqlite3_value_free(p1->apVal[ii]); in recoverWriteDataCleanup()
16915 sqlite3_free(p1->apVal); in recoverWriteDataCleanup()
16916 recoverFinalize(p, p1->pInsert); in recoverWriteDataCleanup()
16917 recoverFinalize(p, p1->pTbls); in recoverWriteDataCleanup()
16918 recoverFinalize(p, p1->pSel); in recoverWriteDataCleanup()
16925 ** RECOVER_STATE_WRITING state - during which tables recovered from the
16929 RecoverStateW1 *p1 = &p->w1; in recoverWriteDataStep()
16930 sqlite3_stmt *pSel = p1->pSel; in recoverWriteDataStep()
16931 sqlite3_value **apVal = p1->apVal; in recoverWriteDataStep()
16933 if( p->errCode==SQLITE_OK && p1->pTab==0 ){ in recoverWriteDataStep()
16934 if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){ in recoverWriteDataStep()
16935 i64 iRoot = sqlite3_column_int64(p1->pTbls, 0); in recoverWriteDataStep()
16936 p1->pTab = recoverFindTable(p, iRoot); in recoverWriteDataStep()
16938 recoverFinalize(p, p1->pInsert); in recoverWriteDataStep()
16939 p1->pInsert = 0; in recoverWriteDataStep()
16943 if( p1->pTab==0 ) return p->errCode; in recoverWriteDataStep()
16947 ** keys before recovering its contents. The p1->pTbls SELECT statement in recoverWriteDataStep()
16950 if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){ in recoverWriteDataStep()
16951 recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence"); in recoverWriteDataStep()
16956 ** SELECT statement p1->pSel. The SELECT statement will then iterate in recoverWriteDataStep()
16960 p1->nVal = 0; in recoverWriteDataStep()
16961 p1->bHaveRowid = 0; in recoverWriteDataStep()
16962 p1->iPrevPage = -1; in recoverWriteDataStep()
16963 p1->iPrevCell = -1; in recoverWriteDataStep()
16968 assert( p->errCode!=SQLITE_OK || p1->pTab ); in recoverWriteDataStep()
16970 if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){ in recoverWriteDataStep()
16971 RecoverTable *pTab = p1->pTab; in recoverWriteDataStep()
16977 int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell); in recoverWriteDataStep()
16979 assert( bNewCell==0 || (iField==-1 || iField==0) ); in recoverWriteDataStep()
16980 assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol ); in recoverWriteDataStep()
16984 if( p1->nVal>=0 ){ in recoverWriteDataStep()
16985 if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){ in recoverWriteDataStep()
16986 recoverFinalize(p, p1->pInsert); in recoverWriteDataStep()
16987 p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal); in recoverWriteDataStep()
16988 p1->nInsert = p1->nVal; in recoverWriteDataStep()
16990 if( p1->nVal>0 ){ in recoverWriteDataStep()
16991 sqlite3_stmt *pInsert = p1->pInsert; in recoverWriteDataStep()
16992 for(ii=0; ii<pTab->nCol; ii++){ in recoverWriteDataStep()
16993 RecoverColumn *pCol = &pTab->aCol[ii]; in recoverWriteDataStep()
16994 int iBind = pCol->iBind; in recoverWriteDataStep()
16996 if( pCol->bIPK ){ in recoverWriteDataStep()
16997 sqlite3_bind_int64(pInsert, iBind, p1->iRowid); in recoverWriteDataStep()
16998 }else if( pCol->iField<p1->nVal ){ in recoverWriteDataStep()
16999 recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]); in recoverWriteDataStep()
17003 if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){ in recoverWriteDataStep()
17004 sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid); in recoverWriteDataStep()
17011 assert( p->errCode || pInsert ); in recoverWriteDataStep()
17016 for(ii=0; ii<p1->nVal; ii++){ in recoverWriteDataStep()
17020 p1->nVal = -1; in recoverWriteDataStep()
17021 p1->bHaveRowid = 0; in recoverWriteDataStep()
17026 p1->iRowid = sqlite3_column_int64(pSel, 3); in recoverWriteDataStep()
17027 assert( p1->nVal==-1 ); in recoverWriteDataStep()
17028 p1->nVal = 0; in recoverWriteDataStep()
17029 p1->bHaveRowid = 1; in recoverWriteDataStep()
17030 }else if( iField<pTab->nCol ){ in recoverWriteDataStep()
17036 p1->nVal = iField+1; in recoverWriteDataStep()
17038 p1->iPrevCell = iCell; in recoverWriteDataStep()
17039 p1->iPrevPage = iPage; in recoverWriteDataStep()
17043 p1->pTab = 0; in recoverWriteDataStep()
17046 return p->errCode; in recoverWriteDataStep()
17051 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
17055 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound1Init()
17058 assert( p->laf.pUsed==0 ); in recoverLostAndFound1Init()
17059 pLaf->nPg = recoverPageCount(p); in recoverLostAndFound1Init()
17060 pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg); in recoverLostAndFound1Init()
17064 ** if !p->bFreelistCorrupt, add all pages that appear to be part of the in recoverLostAndFound1Init()
17067 p, p->dbOut, in recoverLostAndFound1Init()
17077 " SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata" in recoverLostAndFound1Init()
17079 " SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0" in recoverLostAndFound1Init()
17096 if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt); in recoverLostAndFound1Init()
17097 pLaf->pUsedPages = pStmt; in recoverLostAndFound1Init()
17103 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
17107 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound1Step()
17108 int rc = p->errCode; in recoverLostAndFound1Step()
17110 rc = sqlite3_step(pLaf->pUsedPages); in recoverLostAndFound1Step()
17112 i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0); in recoverLostAndFound1Step()
17113 recoverBitmapSet(pLaf->pUsed, iPg); in recoverLostAndFound1Step()
17116 recoverFinalize(p, pLaf->pUsedPages); in recoverLostAndFound1Step()
17117 pLaf->pUsedPages = 0; in recoverLostAndFound1Step()
17125 ** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1
17129 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound2Init()
17131 assert( p->laf.pAllAndParent==0 ); in recoverLostAndFound2Init()
17132 assert( p->laf.pMapInsert==0 ); in recoverLostAndFound2Init()
17133 assert( p->laf.pMaxField==0 ); in recoverLostAndFound2Init()
17134 assert( p->laf.nMaxField==0 ); in recoverLostAndFound2Init()
17136 pLaf->pMapInsert = recoverPrepare(p, p->dbOut, in recoverLostAndFound2Init()
17139 pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut, in recoverLostAndFound2Init()
17145 "SELECT NULL, ii FROM seq", p->laf.nPg in recoverLostAndFound2Init()
17147 pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut, in recoverLostAndFound2Init()
17155 ** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified
17160 RecoverStateLAF *pLaf = &p->laf; in recoverLostAndFound2Step()
17161 if( p->errCode==SQLITE_OK ){ in recoverLostAndFound2Step()
17162 int res = sqlite3_step(pLaf->pAllAndParent); in recoverLostAndFound2Step()
17164 i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1); in recoverLostAndFound2Step()
17165 if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){ in recoverLostAndFound2Step()
17166 sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild); in recoverLostAndFound2Step()
17167 sqlite3_bind_value(pLaf->pMapInsert, 2, in recoverLostAndFound2Step()
17168 sqlite3_column_value(pLaf->pAllAndParent, 0) in recoverLostAndFound2Step()
17170 sqlite3_step(pLaf->pMapInsert); in recoverLostAndFound2Step()
17171 recoverReset(p, pLaf->pMapInsert); in recoverLostAndFound2Step()
17172 sqlite3_bind_int64(pLaf->pMaxField, 1, iChild); in recoverLostAndFound2Step()
17173 if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){ in recoverLostAndFound2Step()
17174 int nMax = sqlite3_column_int(pLaf->pMaxField, 0); in recoverLostAndFound2Step()
17175 if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax; in recoverLostAndFound2Step()
17177 recoverReset(p, pLaf->pMaxField); in recoverLostAndFound2Step()
17180 recoverFinalize(p, pLaf->pAllAndParent); in recoverLostAndFound2Step()
17181 pLaf->pAllAndParent =0; in recoverLostAndFound2Step()
17185 return p->errCode; in recoverLostAndFound2Step()
17193 recoverBitmapFree(p->laf.pUsed); in recoverLostAndFoundCleanup()
17194 p->laf.pUsed = 0; in recoverLostAndFoundCleanup()
17195 sqlite3_finalize(p->laf.pUsedPages); in recoverLostAndFoundCleanup()
17196 sqlite3_finalize(p->laf.pAllAndParent); in recoverLostAndFoundCleanup()
17197 sqlite3_finalize(p->laf.pMapInsert); in recoverLostAndFoundCleanup()
17198 sqlite3_finalize(p->laf.pMaxField); in recoverLostAndFoundCleanup()
17199 sqlite3_finalize(p->laf.pFindRoot); in recoverLostAndFoundCleanup()
17200 sqlite3_finalize(p->laf.pInsert); in recoverLostAndFoundCleanup()
17201 sqlite3_finalize(p->laf.pAllPage); in recoverLostAndFoundCleanup()
17202 sqlite3_finalize(p->laf.pPageData); in recoverLostAndFoundCleanup()
17203 p->laf.pUsedPages = 0; in recoverLostAndFoundCleanup()
17204 p->laf.pAllAndParent = 0; in recoverLostAndFoundCleanup()
17205 p->laf.pMapInsert = 0; in recoverLostAndFoundCleanup()
17206 p->laf.pMaxField = 0; in recoverLostAndFoundCleanup()
17207 p->laf.pFindRoot = 0; in recoverLostAndFoundCleanup()
17208 p->laf.pInsert = 0; in recoverLostAndFoundCleanup()
17209 p->laf.pAllPage = 0; in recoverLostAndFoundCleanup()
17210 p->laf.pPageData = 0; in recoverLostAndFoundCleanup()
17211 sqlite3_free(p->laf.apVal); in recoverLostAndFoundCleanup()
17212 p->laf.apVal = 0; in recoverLostAndFoundCleanup()
17225 for(pTab=p->pTblList; pTab; pTab=pNext){ in recoverFinalCleanup()
17226 pNext = pTab->pNext; in recoverFinalCleanup()
17229 p->pTblList = 0; in recoverFinalCleanup()
17230 sqlite3_finalize(p->pGetPage); in recoverFinalCleanup()
17231 p->pGetPage = 0; in recoverFinalCleanup()
17232 sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0); in recoverFinalCleanup()
17238 sqlite3_close(p->dbOut); in recoverFinalCleanup()
17241 p->dbOut = 0; in recoverFinalCleanup()
17245 ** Decode and return an unsigned 16-bit big-endian integer value from
17253 ** Decode and return an unsigned 32-bit big-endian integer value from
17278 ** or a prefix thereof appears to contain a well-formed SQLite b-tree page,
17279 ** return the page-size in bytes. Otherwise, if the buffer does not
17280 ** appear to contain a well-formed b-tree page, return 0.
17307 /* Follow the free-list. This is the same format for all b-tree pages. */ in recoverIsValidPage()
17312 if( iFree>(n-4) ) return 0; in recoverIsValidPage()
17343 int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23); in recoverIsValidPage()
17344 int M = ((n-12)*32/255)-23; in recoverIsValidPage()
17345 int K = M+((nPayload-M)%(n-4)); in recoverIsValidPage()
17417 assert( pFd->pMethods!=&recover_methods ); in recoverVfsClose()
17418 return pFd->pMethods->xClose(pFd); in recoverVfsClose()
17422 ** Write value v to buffer a[] as a 16-bit big-endian unsigned integer.
17430 ** Write value v to buffer a[] as a 32-bit big-endian unsigned integer.
17440 ** Detect the page-size of the database opened by file-handle pFd by
17441 ** searching the first part of the file for a well-formed SQLite b-tree
17442 ** page. If parameter nReserve is non-zero, then as well as searching for
17443 ** a b-tree page with zero reserved bytes, this function searches for one
17446 ** If successful, set variable p->detected_pgsz to the detected page-size
17448 ** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or,
17450 ** is returned. The final value of p->detected_pgsz is undefined in this
17455 sqlite3_file *pFd, /* File-handle open on input database */ in recoverVfsDetectPagesize()
17473 nBlk = (nSz+nMax-1)/nMax; in recoverVfsDetectPagesize()
17480 rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax); in recoverVfsDetectPagesize()
17486 if( recoverIsValidPage(aTmp, &aPg[iOff], pgsz2-nReserve) ){ in recoverVfsDetectPagesize()
17494 if( pgsz>(u32)p->detected_pgsz ){ in recoverVfsDetectPagesize()
17495 p->detected_pgsz = pgsz; in recoverVfsDetectPagesize()
17496 p->nReserve = nReserve; in recoverVfsDetectPagesize()
17502 p->detected_pgsz = pgsz; in recoverVfsDetectPagesize()
17513 if( pFd->pMethods==&recover_methods ){ in recoverVfsRead()
17514 pFd->pMethods = recover_g.pMethods; in recoverVfsRead()
17515 rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff); in recoverVfsRead()
17523 ** + Database page size (16-bits at offset 16) in recoverVfsRead()
17524 ** + Size of db in pages (32-bits at offset 28) in recoverVfsRead()
17525 ** + Database encoding (32-bits at offset 56) in recoverVfsRead()
17529 ** + first freelist page (32-bits at offset 32) in recoverVfsRead()
17530 ** + size of freelist (32-bits at offset 36) in recoverVfsRead()
17531 ** + the wal-mode flags (16-bits at offset 18) in recoverVfsRead()
17533 ** We also try to preserve the auto-vacuum, incr-value, user-version in recoverVfsRead()
17534 ** and application-id fields - all 32 bit quantities at offsets in recoverVfsRead()
17537 ** Byte offset 105 should also contain the page-size as a 16-bit in recoverVfsRead()
17569 rc = pFd->pMethods->xFileSize(pFd, &dbFileSize); in recoverVfsRead()
17571 if( rc==SQLITE_OK && p->detected_pgsz==0 ){ in recoverVfsRead()
17574 if( p->detected_pgsz ){ in recoverVfsRead()
17575 pgsz = p->detected_pgsz; in recoverVfsRead()
17576 nReserve = p->nReserve; in recoverVfsRead()
17586 sqlite3_free(p->pPage1Cache); in recoverVfsRead()
17587 p->pPage1Cache = 0; in recoverVfsRead()
17588 p->pPage1Disk = 0; in recoverVfsRead()
17590 p->pgsz = nByte; in recoverVfsRead()
17591 p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2); in recoverVfsRead()
17592 if( p->pPage1Cache ){ in recoverVfsRead()
17593 p->pPage1Disk = &p->pPage1Cache[nByte]; in recoverVfsRead()
17594 memcpy(p->pPage1Disk, aBuf, nByte); in recoverVfsRead()
17599 recoverPutU16(&aHdr[105], pgsz-nReserve); in recoverVfsRead()
17607 memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr)); in recoverVfsRead()
17609 memcpy(p->pPage1Cache, aBuf, nByte); in recoverVfsRead()
17611 rc = p->errCode; in recoverVfsRead()
17615 pFd->pMethods = &recover_methods; in recoverVfsRead()
17617 rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff); in recoverVfsRead()
17627 if( pFd->pMethods==&recover_methods ){ \
17628 pFd->pMethods = recover_g.pMethods; \
17630 pFd->pMethods = &recover_methods; \
17646 pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff) in recoverVfsWrite()
17651 pFd->pMethods->xTruncate(pFd, size) in recoverVfsTruncate()
17656 pFd->pMethods->xSync(pFd, flags) in recoverVfsSync()
17661 pFd->pMethods->xFileSize(pFd, pSize) in recoverVfsFileSize()
17666 pFd->pMethods->xLock(pFd, eLock) in recoverVfsLock()
17671 pFd->pMethods->xUnlock(pFd, eLock) in recoverVfsUnlock()
17676 pFd->pMethods->xCheckReservedLock(pFd, pResOut) in recoverVfsCheckReservedLock()
17681 (pFd->pMethods ? pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND) in recoverVfsFileControl()
17686 pFd->pMethods->xSectorSize(pFd) in recoverVfsSectorSize()
17691 pFd->pMethods->xDeviceCharacteristics(pFd) in recoverVfsDeviceCharacteristics()
17698 pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp) in recoverVfsShmMap()
17703 pFd->pMethods->xShmLock(pFd, offset, n, flags) in recoverVfsShmLock()
17707 if( pFd->pMethods==&recover_methods ){ in recoverVfsShmBarrier()
17708 pFd->pMethods = recover_g.pMethods; in recoverVfsShmBarrier()
17709 pFd->pMethods->xShmBarrier(pFd); in recoverVfsShmBarrier()
17710 pFd->pMethods = &recover_methods; in recoverVfsShmBarrier()
17712 pFd->pMethods->xShmBarrier(pFd); in recoverVfsShmBarrier()
17717 pFd->pMethods->xShmUnmap(pFd, deleteFlag) in recoverVfsShmUnmap()
17741 ** Install the VFS wrapper around the file-descriptor open on the input
17749 sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd); in recoverInstallWrapper()
17750 assert( pFd==0 || pFd->pMethods!=&recover_methods ); in recoverInstallWrapper()
17751 if( pFd && pFd->pMethods ){ in recoverInstallWrapper()
17752 int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0); in recoverInstallWrapper()
17753 recover_g.pMethods = pFd->pMethods; in recoverInstallWrapper()
17756 pFd->pMethods = &recover_methods; in recoverInstallWrapper()
17761 ** Uninstall the VFS wrapper that was installed around the file-descriptor open
17768 sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd); in recoverUninstallWrapper()
17769 if( pFd && pFd->pMethods ){ in recoverUninstallWrapper()
17770 pFd->pMethods = recover_g.pMethods; in recoverUninstallWrapper()
17782 assert( p && p->errCode==SQLITE_OK ); in recoverStep()
17783 switch( p->eState ){ in recoverStep()
17798 sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0); in recoverStep()
17799 recoverExec(p, p->dbIn, "PRAGMA writable_schema = on"); in recoverStep()
17800 recoverExec(p, p->dbIn, "BEGIN"); in recoverStep()
17801 if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1; in recoverStep()
17802 recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema"); in recoverStep()
17810 recoverExec(p, p->dbOut, "BEGIN"); in recoverStep()
17813 p->eState = RECOVER_STATE_WRITING; in recoverStep()
17817 if( p->w1.pTbls==0 ){ in recoverStep()
17822 if( p->zLostAndFound ){ in recoverStep()
17823 p->eState = RECOVER_STATE_LOSTANDFOUND1; in recoverStep()
17825 p->eState = RECOVER_STATE_SCHEMA2; in recoverStep()
17832 if( p->laf.pUsed==0 ){ in recoverStep()
17836 p->eState = RECOVER_STATE_LOSTANDFOUND2; in recoverStep()
17841 if( p->laf.pAllAndParent==0 ){ in recoverStep()
17845 p->eState = RECOVER_STATE_LOSTANDFOUND3; in recoverStep()
17851 if( p->laf.pInsert==0 ){ in recoverStep()
17855 p->eState = RECOVER_STATE_SCHEMA2; in recoverStep()
17864 p->eState = RECOVER_STATE_DONE; in recoverStep()
17869 recoverExec(p, p->dbOut, "COMMIT"); in recoverStep()
17870 rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0); in recoverStep()
17871 if( p->errCode==SQLITE_OK ) p->errCode = rc; in recoverStep()
17875 p->eState = RECOVER_STATE_DONE; in recoverStep()
17881 /* no-op */ in recoverStep()
17920 pRet->dbIn = db; in recoverInit()
17921 pRet->zDb = (char*)&pRet[1]; in recoverInit()
17922 pRet->zUri = &pRet->zDb[nDb+1]; in recoverInit()
17923 memcpy(pRet->zDb, zDb, nDb); in recoverInit()
17924 if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri); in recoverInit()
17925 pRet->xSql = xSql; in recoverInit()
17926 pRet->pSqlCtx = pSqlCtx; in recoverInit()
17927 pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT; in recoverInit()
17962 return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory"; in sqlite3_recover_errmsg()
17969 return p ? p->errCode : SQLITE_NOMEM; in sqlite3_recover_errcode()
17979 }else if( p->eState!=RECOVER_STATE_INIT ){ in sqlite3_recover_config()
17985 ** name of the auxiliary database that is ATTACH-ed to the database in sqlite3_recover_config()
17989 sqlite3_free(p->zStateDb); in sqlite3_recover_config()
17990 p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg); in sqlite3_recover_config()
17995 sqlite3_free(p->zLostAndFound); in sqlite3_recover_config()
17997 p->zLostAndFound = recoverMPrintf(p, "%s", zArg); in sqlite3_recover_config()
17999 p->zLostAndFound = 0; in sqlite3_recover_config()
18005 p->bFreelistCorrupt = *(int*)pArg; in sqlite3_recover_config()
18009 p->bRecoverRowid = *(int*)pArg; in sqlite3_recover_config()
18013 p->bSlowIndexes = *(int*)pArg; in sqlite3_recover_config()
18033 if( p->errCode==SQLITE_OK ) recoverStep(p); in sqlite3_recover_step()
18034 if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){ in sqlite3_recover_step()
18037 return p->errCode; in sqlite3_recover_step()
18065 if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){ in sqlite3_recover_finish()
18066 rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0); in sqlite3_recover_finish()
18067 if( p->errCode==SQLITE_OK ) p->errCode = rc; in sqlite3_recover_finish()
18069 rc = p->errCode; in sqlite3_recover_finish()
18070 sqlite3_free(p->zErrMsg); in sqlite3_recover_finish()
18071 sqlite3_free(p->zStateDb); in sqlite3_recover_finish()
18072 sqlite3_free(p->zLostAndFound); in sqlite3_recover_finish()
18073 sqlite3_free(p->pPage1Cache); in sqlite3_recover_finish()
18146 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
18150 u8 bSafeModePersist; /* The long-term value of bSafeMode */
18175 sqlite3_int64 szMax; /* --maxsize argument to .open */
18204 char *zNonce; /* Nonce for temporary safe-mode escapes */
18230 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
18234 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
18248 ** top-level SQL statement */
18249 #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
18254 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
18256 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
18258 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
18260 #define SHFLG_Echo 0x00000040 /* .echo on/off, or --echo setting */
18269 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
18270 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
18271 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
18283 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
18287 #define MODE_Pretty 11 /* Pretty-print schemas */
18291 #define MODE_Table 15 /* MySQL-style table formatting */
18292 #define MODE_Box 16 /* Unicode box-drawing characters */
18343 if( p->pLog==0 ) return; in shellLog()
18344 sputf(p->pLog, "(%d) %s\n", iErrCode, zMsg); in shellLog()
18345 fflush(p->pLog); in shellLog()
18374 if( p->bSafeMode ){ in failIfSafeMode()
18380 eputf("line %d: %s\n", p->lineno, zMsg); in failIfSafeMode()
18399 ** Also throw an error if the EDITOR program returns a non-zero exit code.
18425 sqlite3_result_error(context, "no editor for edit()", -1); in editFunc()
18429 sqlite3_result_error(context, "NULL input to edit()", -1); in editFunc()
18449 sqlite3_result_error(context, "edit() cannot open temp file", -1); in editFunc()
18464 sqlite3_result_error(context, "edit() could not write the whole file", -1); in editFunc()
18475 sqlite3_result_error(context, "EDITOR returned non-zero", -1); in editFunc()
18481 "edit() cannot reopen temp file after edit", -1); in editFunc()
18496 sqlite3_result_error(context, "could not read back the whole file", -1); in editFunc()
18533 p->modePrior = p->mode; in outputModePush()
18534 p->priorShFlgs = p->shellFlgs; in outputModePush()
18535 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator)); in outputModePush()
18536 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator)); in outputModePush()
18539 p->mode = p->modePrior; in outputModePop()
18540 p->shellFlgs = p->priorShFlgs; in outputModePop()
18541 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator)); in outputModePop()
18542 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator)); in outputModePop()
18546 ** Output the given string as a hex-encoded blob (eg. X'1234' )
18636 ** get corrupted by end-of-line translation facilities in some operating
18709 ** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
18718 ns = pcFirst - s; in anyOfInStr()
18731 static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */ in output_c_string()
18739 if( pcEnd > z ) oputb(z, (int)(pcEnd-z)); in output_c_string()
18782 const char *pcDQBS = anyOfInStr(z, zDQBS, pcLimit-z); in output_json_string()
18783 const char *pcPast = zSkipValidUtf8(z, (int)(pcLimit-z), ctrlMask); in output_json_string()
18786 oputb(z, (int)(pcEnd-z)); in output_json_string()
18874 ** Output a single term of CSV. Actually, p->colSeparator is used for
18875 ** the separator, which may or may not be a comma. p->nullValue is
18881 oputf("%s",p->nullValue); in output_csv()
18890 if( i==0 || strstr(z, p->colSeparator)!=0 ){ in output_csv()
18900 oputz(p->colSeparator); in output_csv()
18905 ** This routine runs when the user presses Ctrl-C
18915 ** This routine runs for console events (e.g. Ctrl-C) on Win32
19018 if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4); in shellAuth()
19029 ** If the schema statement in z[] contains a start-of-comment and if
19037 if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){ in printSchemaLine()
19046 zNew[n-1] = 0; in printSchemaLine()
19077 if( z[i]=='-' && z[i+1]=='-' ) return 1; in wsToEol()
19091 if( p->autoEQPtest ){ in eqp_append()
19096 pNew->iEqpId = iEqpId; in eqp_append()
19097 pNew->iParentId = p2; in eqp_append()
19098 memcpy(pNew->zText, zText, nText+1); in eqp_append()
19099 pNew->pNext = 0; in eqp_append()
19100 if( p->sGraph.pLast ){ in eqp_append()
19101 p->sGraph.pLast->pNext = pNew; in eqp_append()
19103 p->sGraph.pRow = pNew; in eqp_append()
19105 p->sGraph.pLast = pNew; in eqp_append()
19110 ** in p->sGraph.
19114 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){ in eqp_reset()
19115 pNext = pRow->pNext; in eqp_reset()
19118 memset(&p->sGraph, 0, sizeof(p->sGraph)); in eqp_reset()
19125 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow; in eqp_next_row()
19126 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext; in eqp_next_row()
19135 i64 n = strlen(p->sGraph.zPrefix); in eqp_render_level()
19139 z = pRow->zText; in eqp_render_level()
19140 oputf("%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z); in eqp_render_level()
19141 if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){ in eqp_render_level()
19142 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4); in eqp_render_level()
19143 eqp_render_level(p, pRow->iEqpId); in eqp_render_level()
19144 p->sGraph.zPrefix[n] = 0; in eqp_render_level()
19153 EQPGraphRow *pRow = p->sGraph.pRow; in eqp_render()
19155 if( pRow->zText[0]=='-' ){ in eqp_render()
19156 if( pRow->pNext==0 ){ in eqp_render()
19160 oputf("%s\n", pRow->zText+3); in eqp_render()
19161 p->sGraph.pRow = pRow->pNext; in eqp_render()
19168 p->sGraph.zPrefix[0] = 0; in eqp_render()
19180 p->nProgress++; in progress_handler()
19181 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){ in progress_handler()
19182 oputf("Progress limit reached (%u)\n", p->nProgress); in progress_handler()
19183 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; in progress_handler()
19184 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0; in progress_handler()
19187 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){ in progress_handler()
19188 oputf("Progress %u\n", p->nProgress); in progress_handler()
19198 const char zDash[] = "--------------------------------------------------"; in print_dashes()
19199 const int nDash = sizeof(zDash) - 1; in print_dashes()
19202 N -= nDash; in print_dashes()
19208 ** Print a markdown or table-style row separator using ascii-art
19218 print_dashes(p->actualWidth[0]+2); in print_row_separator()
19221 print_dashes(p->actualWidth[i]+2); in print_row_separator()
19243 switch( p->cMode ){ in shell_callback()
19255 if( p->cnt++>0 ) oputz(p->rowSeparator); in shell_callback()
19258 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator); in shell_callback()
19274 if( p->cMode==MODE_ScanExp ){ in shell_callback()
19283 if( p->cnt++==0 ){ in shell_callback()
19286 oputz(i==nArg-1 ? "\n" : " "); in shell_callback()
19290 oputz(i==nArg-1 ? "\n" : " "); in shell_callback()
19301 if( i==nArg-1 ) w = 0; in shell_callback()
19306 if( i==iIndent && p->aiIndent && p->pStmt ){ in shell_callback()
19307 if( p->iIndent<p->nIndent ){ in shell_callback()
19308 oputf("%*.s", p->aiIndent[p->iIndent], ""); in shell_callback()
19310 p->iIndent++; in shell_callback()
19312 utf8_width_print(w, zVal ? zVal : p->nullValue); in shell_callback()
19313 oputz(i==nArg-1 ? "\n" : zSep); in shell_callback()
19321 case MODE_Pretty: { /* .schema and .fullschema with --indent */ in shell_callback()
19342 if( z[j-1]=='\r' ) z[j-1] = '\n'; in shell_callback()
19343 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue; in shell_callback()
19344 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){ in shell_callback()
19345 j--; in shell_callback()
19349 while( j>0 && IsSpace(z[j-1]) ){ j--; } in shell_callback()
19359 }else if( c=='-' && z[i+1]=='-' ){ in shell_callback()
19364 nParen--; in shell_callback()
19374 if( c=='\n' ) j--; in shell_callback()
19388 if( p->cnt++==0 && p->showHeader ){ in shell_callback()
19390 oputf("%s%s",azCol[i], i==nArg-1 ? p->rowSeparator : p->colSeparator); in shell_callback()
19396 if( z==0 ) z = p->nullValue; in shell_callback()
19398 oputz((i<nArg-1)? p->colSeparator : p->rowSeparator); in shell_callback()
19403 if( p->cnt++==0 && p->showHeader ){ in shell_callback()
19416 output_html_string(azArg[i] ? azArg[i] : p->nullValue); in shell_callback()
19423 if( p->cnt++==0 && p->showHeader ){ in shell_callback()
19426 if(i<nArg-1) oputz(p->colSeparator); in shell_callback()
19428 oputz(p->rowSeparator); in shell_callback()
19432 output_c_string(azArg[i] ? azArg[i] : p->nullValue); in shell_callback()
19433 if(i<nArg-1) oputz(p->colSeparator); in shell_callback()
19435 oputz(p->rowSeparator); in shell_callback()
19439 setBinaryMode(p->out, 1); in shell_callback()
19440 if( p->cnt++==0 && p->showHeader ){ in shell_callback()
19442 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1); in shell_callback()
19444 oputz(p->rowSeparator); in shell_callback()
19448 output_csv(p, azArg[i], i<nArg-1); in shell_callback()
19450 oputz(p->rowSeparator); in shell_callback()
19452 setTextMode(p->out, 1); in shell_callback()
19457 oputf("INSERT INTO %s",p->zDestTable); in shell_callback()
19458 if( p->showHeader ){ in shell_callback()
19473 p->cnt++; in shell_callback()
19488 double r = sqlite3_column_double(p->pStmt, i); in shell_callback()
19494 oputz("-9.0e+999"); in shell_callback()
19504 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ in shell_callback()
19505 const void *pBlob = sqlite3_column_blob(p->pStmt, i); in shell_callback()
19506 int nBlob = sqlite3_column_bytes(p->pStmt, i); in shell_callback()
19521 if( p->cnt==0 ){ in shell_callback()
19522 fputs("[{", p->out); in shell_callback()
19524 fputs(",\n{", p->out); in shell_callback()
19526 p->cnt++; in shell_callback()
19528 output_json_string(azCol[i], -1); in shell_callback()
19534 double r = sqlite3_column_double(p->pStmt, i); in shell_callback()
19540 oputz("-9.0e+999"); in shell_callback()
19545 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ in shell_callback()
19546 const void *pBlob = sqlite3_column_blob(p->pStmt, i); in shell_callback()
19547 int nBlob = sqlite3_column_bytes(p->pStmt, i); in shell_callback()
19550 output_json_string(azArg[i], -1); in shell_callback()
19554 if( i<nArg-1 ){ in shell_callback()
19563 if( p->cnt==0 && p->showHeader ){ in shell_callback()
19565 if( i>0 ) fputs(p->colSeparator, p->out); in shell_callback()
19568 fputs(p->rowSeparator, p->out); in shell_callback()
19570 p->cnt++; in shell_callback()
19572 if( i>0 ) fputs(p->colSeparator, p->out); in shell_callback()
19581 double r = sqlite3_column_double(p->pStmt, i); in shell_callback()
19584 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ in shell_callback()
19585 const void *pBlob = sqlite3_column_blob(p->pStmt, i); in shell_callback()
19586 int nBlob = sqlite3_column_bytes(p->pStmt, i); in shell_callback()
19594 fputs(p->rowSeparator, p->out); in shell_callback()
19598 if( p->cnt++==0 && p->showHeader ){ in shell_callback()
19600 if( i>0 ) oputz(p->colSeparator); in shell_callback()
19603 oputz(p->rowSeparator); in shell_callback()
19607 if( i>0 ) oputz(p->colSeparator); in shell_callback()
19608 oputz(azArg[i] ? azArg[i] : p->nullValue); in shell_callback()
19610 oputz(p->rowSeparator); in shell_callback()
19639 if( p->n ) appendText(p, "|", 0); in captureOutputCallback()
19652 sqlite3_exec(p->db, in createSelftestTable()
19663 " 'memo','Tests generated by --init');\n" in createSelftestTable()
19692 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0); in createSelftestTable()
19706 if( p->zDestTable ){ in set_table_name()
19707 free(p->zDestTable); in set_table_name()
19708 p->zDestTable = 0; in set_table_name()
19714 z = p->zDestTable = malloc( n+1 ); in set_table_name()
19749 iOffset--; in shell_error_context()
19751 while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; } in shell_error_context()
19756 while( len>0 && (zSql[len]&0xc0)==0x80 ) len--; in shell_error_context()
19762 zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode,iOffset,""); in shell_error_context()
19764 zMsg = sqlite3_mprintf("\n %z\n %*serror here ---^", zCode,iOffset-14,""); in shell_error_context()
19772 ** the result columns, comma-separated, on a line and then add a
19775 ** If the number of columns is 1 and that column contains text "--"
19777 ** "--" comment occurs at the end of the statement, the comment
19789 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); in run_table_dump_query()
19791 char *zContext = shell_error_context(zSelect, p->db); in run_table_dump_query()
19793 rc, sqlite3_errmsg(p->db), zContext); in run_table_dump_query()
19795 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; in run_table_dump_query()
19807 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; in run_table_dump_query()
19817 oputf("/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); in run_table_dump_query()
19818 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; in run_table_dump_query()
19876 oputf("%-36s %s", aTrans[i].zDesc, &z[n]); in displayLinuxIoStats()
19886 ** Display a single line of status using 64-bit values.
19894 sqlite3_int64 iCur = -1; in displayStatLine()
19895 sqlite3_int64 iHiwtr = -1; in displayStatLine()
19907 oputf("%-36s %s\n", zLabel, zLine); in displayStatLine()
19920 if( pArg==0 || pArg->out==0 ) return 0; in display_stats()
19922 if( pArg->pStmt && pArg->statsOn==2 ){ in display_stats()
19924 sqlite3_stmt *pStmt = pArg->pStmt; in display_stats()
19927 oputf("%-36s %d\n", "Number of output columns:", nCol); in display_stats()
19930 oputf("%-36s %s\n", z, sqlite3_column_name(pStmt,i)); in display_stats()
19933 oputf("%-36s %s\n", z, sqlite3_column_decltype(pStmt, i)); in display_stats()
19937 oputf("%-36s %s\n", z, sqlite3_column_database_name(pStmt,i)); in display_stats()
19939 oputf("%-36s %s\n", z, sqlite3_column_table_name(pStmt,i)); in display_stats()
19941 oputf("%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i)); in display_stats()
19946 if( pArg->statsOn==3 ){ in display_stats()
19947 if( pArg->pStmt ){ in display_stats()
19948 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset); in display_stats()
19949 oputf("VM-steps: %d\n", iCur); in display_stats()
19958 if( pArg->shellFlgs & SHFLG_Pagecache ){ in display_stats()
19974 if( pArg->shellFlgs & SHFLG_Lookaside ){ in display_stats()
19975 iHiwtr = iCur = -1; in display_stats()
19989 iHiwtr = iCur = -1; in display_stats()
19992 iHiwtr = iCur = -1; in display_stats()
19995 iHiwtr = iCur = -1; in display_stats()
19998 iHiwtr = iCur = -1; in display_stats()
20001 iHiwtr = iCur = -1; in display_stats()
20004 iHiwtr = iCur = -1; in display_stats()
20007 iHiwtr = iCur = -1; in display_stats()
20012 if( pArg->pStmt ){ in display_stats()
20014 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, in display_stats()
20017 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); in display_stats()
20019 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); in display_stats()
20021 iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, in display_stats()
20023 iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, in display_stats()
20028 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); in display_stats()
20030 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset); in display_stats()
20032 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset); in display_stats()
20034 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset); in display_stats()
20042 /* Do not remove this machine readable comment: extra-stats-output-here */ in display_stats()
20082 sqlite3_stmt *p = pArg->pStmt; in display_explain_scanstats()
20099 sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal); in display_explain_scanstats()
20137 if( zName && pArg->scanstatsOn>1 ){ in display_explain_scanstats()
20143 "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z in display_explain_scanstats()
20157 ** Parameter azArray points to a zero-terminated array of strings. zStr
20158 ** points to a single nul-terminated string. Return non-zero if zStr
20182 ** See tag-20220407a in wherecode.c and vdbe.c.
20193 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ in explain_data_prepare()
20194 int iOp; /* Index of operation in p->aiIndent[] */ in explain_data_prepare()
20221 ** different if the current instruction is part of a sub-program generated in explain_data_prepare()
20223 int p2op = (p2 + (iOp-iAddr)); in explain_data_prepare()
20225 /* Grow the p->aiIndent array as required */ in explain_data_prepare()
20228 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int)); in explain_data_prepare()
20229 shell_check_oom(p->aiIndent); in explain_data_prepare()
20235 p->aiIndent[iOp] = 0; in explain_data_prepare()
20236 p->nIndent = iOp+1; in explain_data_prepare()
20238 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; in explain_data_prepare()
20241 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; in explain_data_prepare()
20245 p->iIndent = 0; in explain_data_prepare()
20254 sqlite3_free(p->aiIndent); in explain_data_delete()
20255 p->aiIndent = 0; in explain_data_delete()
20256 p->nIndent = 0; in explain_data_delete()
20257 p->iIndent = 0; in explain_data_delete()
20273 if( pArg->scanstatsOn==3 ){ in display_scanstats()
20281 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); in display_scanstats()
20283 sqlite3_stmt *pSave = pArg->pStmt; in display_scanstats()
20284 pArg->pStmt = pStmt; in display_scanstats()
20285 sqlite3_bind_pointer(pStmt, 1, pSave, "stmt-pointer", 0); in display_scanstats()
20287 pArg->cnt = 0; in display_scanstats()
20288 pArg->cMode = MODE_ScanExp; in display_scanstats()
20294 pArg->pStmt = pSave; in display_scanstats()
20323 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode); in bind_table_init()
20324 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0); in bind_table_init()
20325 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema); in bind_table_init()
20326 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0); in bind_table_init()
20327 sqlite3_exec(p->db, in bind_table_init()
20333 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0); in bind_table_init()
20334 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0); in bind_table_init()
20357 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters", in bind_prepared_stmt()
20362 rc = sqlite3_prepare_v2(pArg->db, in bind_prepared_stmt()
20364 " WHERE key=?1", -1, &pQ, 0); in bind_prepared_stmt()
20373 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC); in bind_prepared_stmt()
20393 ** UTF8 box-drawing characters. Imagine box lines like this:
20397 ** 4 --+-- 2
20405 #define BOX_24 "\342\224\200" /* U+2500 --- */
20407 #define BOX_23 "\342\224\214" /* U+250c ,- */
20408 #define BOX_34 "\342\224\220" /* U+2510 -, */
20409 #define BOX_12 "\342\224\224" /* U+2514 '- */
20410 #define BOX_14 "\342\224\230" /* U+2518 -' */
20411 #define BOX_123 "\342\224\234" /* U+251c |- */
20412 #define BOX_134 "\342\224\244" /* U+2524 -| */
20413 #define BOX_234 "\342\224\254" /* U+252c -,- */
20414 #define BOX_124 "\342\224\264" /* U+2534 -'- */
20415 #define BOX_1234 "\342\224\274" /* U+253c -|- */
20424 const int nDash = sizeof(zDash) - 1; in print_box_line()
20428 N -= nDash; in print_box_line()
20446 print_box_line(p->actualWidth[0]+2); in print_box_row_separator()
20449 print_box_line(p->actualWidth[i]+2); in print_box_row_separator()
20471 u8 bWordWrap /* If true, avoid breaking mid-word */ in translateForDisplayAndDup()
20483 if( mxWidth<0 ) mxWidth = -mxWidth; in translateForDisplayAndDup()
20504 for(k=i; k>i/2; k--){ in translateForDisplayAndDup()
20505 if( isspace(z[k-1]) ) break; in translateForDisplayAndDup()
20508 for(k=i; k>i/2; k--){ in translateForDisplayAndDup()
20509 if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break; in translateForDisplayAndDup()
20553 /* Extract the value of the i-th current column for pStmt as an SQL literal
20587 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
20615 int bw = p->cmOpts.bWordWrap; in exec_prepared_stmt_columnar()
20617 const char *zShowNull = p->nullValue; in exec_prepared_stmt_columnar()
20629 if( p->cmOpts.bQuote ){ in exec_prepared_stmt_columnar()
20636 if( nColumn>p->nWidth ){ in exec_prepared_stmt_columnar()
20637 p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int)); in exec_prepared_stmt_columnar()
20638 shell_check_oom(p->colWidth); in exec_prepared_stmt_columnar()
20639 for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0; in exec_prepared_stmt_columnar()
20640 p->nWidth = nColumn; in exec_prepared_stmt_columnar()
20641 p->actualWidth = &p->colWidth[nColumn]; in exec_prepared_stmt_columnar()
20643 memset(p->actualWidth, 0, nColumn*sizeof(int)); in exec_prepared_stmt_columnar()
20645 w = p->colWidth[i]; in exec_prepared_stmt_columnar()
20646 if( w<0 ) w = -w; in exec_prepared_stmt_columnar()
20647 p->actualWidth[i] = w; in exec_prepared_stmt_columnar()
20651 int wx = p->colWidth[i]; in exec_prepared_stmt_columnar()
20653 wx = p->cmOpts.iWrap; in exec_prepared_stmt_columnar()
20655 if( wx<0 ) wx = -wx; in exec_prepared_stmt_columnar()
20673 int wx = p->colWidth[i]; in exec_prepared_stmt_columnar()
20675 wx = p->cmOpts.iWrap; in exec_prepared_stmt_columnar()
20677 if( wx<0 ) wx = -wx; in exec_prepared_stmt_columnar()
20681 }else if( p->cmOpts.bQuote ){ in exec_prepared_stmt_columnar()
20693 abRowDiv[nRow-1] = 0; in exec_prepared_stmt_columnar()
20704 if( n>p->actualWidth[j] ) p->actualWidth[j] = n; in exec_prepared_stmt_columnar()
20708 switch( p->cMode ){ in exec_prepared_stmt_columnar()
20712 if( p->showHeader ){ in exec_prepared_stmt_columnar()
20714 w = p->actualWidth[i]; in exec_prepared_stmt_columnar()
20715 if( p->colWidth[i]<0 ) w = -w; in exec_prepared_stmt_columnar()
20717 fputs(i==nColumn-1?"\n":" ", p->out); in exec_prepared_stmt_columnar()
20720 print_dashes(p->actualWidth[i]); in exec_prepared_stmt_columnar()
20721 fputs(i==nColumn-1?"\n":" ", p->out); in exec_prepared_stmt_columnar()
20730 fputs("| ", p->out); in exec_prepared_stmt_columnar()
20732 w = p->actualWidth[i]; in exec_prepared_stmt_columnar()
20734 oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, ""); in exec_prepared_stmt_columnar()
20735 oputz(i==nColumn-1?" |\n":" | "); in exec_prepared_stmt_columnar()
20743 fputs("| ", p->out); in exec_prepared_stmt_columnar()
20745 w = p->actualWidth[i]; in exec_prepared_stmt_columnar()
20747 oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, ""); in exec_prepared_stmt_columnar()
20748 oputz(i==nColumn-1?" |\n":" | "); in exec_prepared_stmt_columnar()
20759 w = p->actualWidth[i]; in exec_prepared_stmt_columnar()
20762 (w-n)/2, "", azData[i], (w-n+1)/2, "", in exec_prepared_stmt_columnar()
20763 i==nColumn-1?" "BOX_13"\n":" "BOX_13" "); in exec_prepared_stmt_columnar()
20770 if( j==0 && p->cMode!=MODE_Column ){ in exec_prepared_stmt_columnar()
20771 oputz(p->cMode==MODE_Box?BOX_13" ":"| "); in exec_prepared_stmt_columnar()
20774 if( z==0 ) z = p->nullValue; in exec_prepared_stmt_columnar()
20775 w = p->actualWidth[j]; in exec_prepared_stmt_columnar()
20776 if( p->colWidth[j]<0 ) w = -w; in exec_prepared_stmt_columnar()
20778 if( j==nColumn-1 ){ in exec_prepared_stmt_columnar()
20780 if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){ in exec_prepared_stmt_columnar()
20781 if( p->cMode==MODE_Table ){ in exec_prepared_stmt_columnar()
20783 }else if( p->cMode==MODE_Box ){ in exec_prepared_stmt_columnar()
20785 }else if( p->cMode==MODE_Column ){ in exec_prepared_stmt_columnar()
20789 j = -1; in exec_prepared_stmt_columnar()
20795 if( p->cMode==MODE_Table ){ in exec_prepared_stmt_columnar()
20797 }else if( p->cMode==MODE_Box ){ in exec_prepared_stmt_columnar()
20828 if( pArg->cMode==MODE_Column in exec_prepared_stmt()
20829 || pArg->cMode==MODE_Table in exec_prepared_stmt()
20830 || pArg->cMode==MODE_Box in exec_prepared_stmt()
20831 || pArg->cMode==MODE_Markdown in exec_prepared_stmt()
20865 && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote) in exec_prepared_stmt()
20888 if( pArg->cMode==MODE_Json ){ in exec_prepared_stmt()
20889 fputs("]\n", pArg->out); in exec_prepared_stmt()
20890 }else if( pArg->cMode==MODE_Count ){ in exec_prepared_stmt()
20916 assert( pState->expert.pExpert ); in expertHandleSQL()
20918 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr); in expertHandleSQL()
20937 sqlite3expert *p = pState->expert.pExpert; in expertFinish()
20941 int bVerbose = pState->expert.bVerbose; in expertFinish()
20950 oputz("-- Candidates -----------------------------\n"); in expertFinish()
20959 oputf("-- Query %d --------------------------------\n",i+1); in expertFinish()
20968 pState->expert.pExpert = 0; in expertFinish()
20985 assert( pState->expert.pExpert==0 ); in expertDotCommand()
20986 memset(&pState->expert, 0, sizeof(ExpertInfo)); in expertDotCommand()
20991 if( z[0]=='-' && z[1]=='-' ) z++; in expertDotCommand()
20993 if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){ in expertDotCommand()
20994 pState->expert.bVerbose = 1; in expertDotCommand()
20996 else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){ in expertDotCommand()
20997 if( i==(nArg-1) ){ in expertDotCommand()
21015 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr); in expertDotCommand()
21016 if( pState->expert.pExpert==0 ){ in expertDotCommand()
21021 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample in expertDotCommand()
21036 ** This is very similar to SQLite's built-in sqlite3_exec()
21049 sqlite3 *db = pArg->db; in shell_exec()
21056 if( pArg->expert.pExpert ){ in shell_exec()
21064 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); in shell_exec()
21071 /* this happens for a comment or white-space */ in shell_exec()
21082 pArg->pStmt = pStmt; in shell_exec()
21083 pArg->cnt = 0; in shell_exec()
21087 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){ in shell_exec()
21091 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP); in shell_exec()
21092 if( pArg->autoEQP>=AUTOEQP_trigger ){ in shell_exec()
21104 if( zEQPLine[0]=='-' ) eqp_render(pArg, 0); in shell_exec()
21109 if( pArg->autoEQP>=AUTOEQP_full ){ in shell_exec()
21114 pArg->cMode = MODE_Explain; in shell_exec()
21121 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){ in shell_exec()
21131 pArg->cMode = pArg->mode; in shell_exec()
21132 if( pArg->autoExplain ){ in shell_exec()
21134 pArg->cMode = MODE_Explain; in shell_exec()
21137 pArg->cMode = MODE_EQP; in shell_exec()
21143 if( pArg->cMode==MODE_Explain && bIsExplain ){ in shell_exec()
21154 if( pArg && pArg->statsOn ){ in shell_exec()
21158 /* print loop-counters if required */ in shell_exec()
21159 if( pArg && pArg->scanstatsOn ){ in shell_exec()
21177 pArg->pStmt = NULL; in shell_exec()
21223 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in tableColumnList()
21227 if( nCol>=nAlloc-2 ){ in tableColumnList()
21268 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in tableColumnList()
21292 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0); in tableColumnList()
21308 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0); in toggleSelectOrder()
21340 dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0; in dump_callback()
21341 noSys = (p->shellFlgs & SHFLG_DumpNoSys)!=0; in dump_callback()
21350 /* no-op */ in dump_callback()
21353 if( !p->writableSchema ){ in dump_callback()
21355 p->writableSchema = 1; in dump_callback()
21379 p->nErr++; in dump_callback()
21418 savedDestTable = p->zDestTable; in dump_callback()
21419 savedMode = p->mode; in dump_callback()
21420 p->zDestTable = sTable.z; in dump_callback()
21421 p->mode = p->cMode = MODE_Insert; in dump_callback()
21425 toggleSelectOrder(p->db); in dump_callback()
21427 toggleSelectOrder(p->db); in dump_callback()
21429 p->zDestTable = savedDestTable; in dump_callback()
21430 p->mode = savedMode; in dump_callback()
21433 if( rc ) p->nErr++; in dump_callback()
21451 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); in run_schema_dump_query()
21464 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); in run_schema_dump_query()
21490 " -c, --create Create a new archive",
21491 " -u, --update Add or update files with changed mtime",
21492 " -i, --insert Like -u but always add even if unchanged",
21493 " -r, --remove Remove files from archive",
21494 " -t, --list List contents of archive",
21495 " -x, --extract Extract files from archive",
21497 " -v, --verbose Print each filename as it is processed",
21498 " -f FILE, --file FILE Use archive FILE (default is current db)",
21499 " -a FILE, --append FILE Open FILE using the apndvfs VFS",
21500 " -C DIR, --directory DIR Read/extract files from directory DIR",
21501 " -g, --glob Use glob matching for names in archive",
21502 " -n, --dryrun Show the SQL that would have occurred",
21504 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
21505 " .ar -tf ARCHIVE # List members of ARCHIVE",
21506 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
21516 " --append Use the appendvfs",
21517 " --async Write to FILE without journal and fsync()",
21539 " --data-only Output only INSERT statements",
21540 " --newlines Allow unescaped newline characters in output",
21541 " --nosys Omit system tables (ex: \"sqlite_stat1\")",
21542 " --preserve-rowids Include ROWID values in the output",
21555 " --bom Put a UTF8 byte-order mark on intermediate file",
21558 ".exit ?CODE? Exit this program with return-code CODE",
21563 " --schema SCHEMA Use SCHEMA instead of \"main\"",
21564 " --help Show CMD details",
21565 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
21567 ".help ?-all? ?PATTERN? Show help text for PATTERN",
21571 " --ascii Use \\037 and \\036 as column and row separators",
21572 " --csv Use , and \\n as column and row separators",
21573 " --skip N Skip the first N rows of input",
21574 " --schema S Target table to be S.TABLE",
21575 " -v \"Verbose\" - increase auxiliary output",
21579 " * If neither --csv or --ascii are used, the input mode is derived",
21596 " fkey-indexes Find missing foreign key indexes",
21608 " box Tables using unicode box-drawing characters",
21609 " csv Comma-separated values",
21617 " qbox Shorthand for \"box --wrap 60 --quote\"",
21619 " table ASCII-art table",
21620 " tabs Tab-separated values",
21623 " --wrap N Wrap output lines to no longer than N characters",
21624 " --wordwrap B Wrap or not at word boundaries per B (on/off)",
21625 " --ww Shorthand for \"--wordwrap 1\"",
21626 " --quote Quote output text as SQL literals",
21627 " --noquote Do not quote output text",
21636 " --bom Put a UTF8 byte-order mark at the beginning",
21637 " -e Send output to the system text editor",
21638 " -x Send output as CSV to a spreadsheet (same as \".excel\")",
21644 " --append Use appendvfs to append database to the end of FILE",
21647 " --deserialize Load into memory using sqlite3_deserialize()",
21648 " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
21649 " --maxsize N Maximum size for --hexdb or --deserialized database",
21651 " --new Initialize FILE to an empty database",
21652 " --nofollow Do not follow symbolic links",
21653 " --readonly Open FILE readonly",
21654 " --zip FILE is a ZIP archive",
21659 " --bom Prefix output with a UTF8 byte-order mark",
21660 " -e Send output to the system text editor",
21661 " -x Send output as CSV to a spreadsheet",
21673 " --limit N Interrupt after N progress callbacks",
21674 " --once Do no more than one progress interrupt",
21675 " --quiet|-q No output except at interrupts",
21676 " --reset Reset the count for each input and interrupt",
21686 " --ignore-freelist Ignore pages that appear to be on db freelist",
21687 " --lost-and-found TABLE Alternative name for the lost-and-found table",
21688 " --no-rowids Do not attempt to recover rowid values",
21698 " --indent Try to pretty-print the schema",
21699 " --nosys Omit objects whose names start with \"sqlite_\"",
21702 " --init Create a new SELFTEST table",
21703 " -v Verbose output",
21722 " --schema Also hash the sqlite_schema table",
21723 " --sha3-224 Use the sha3-224 algorithm",
21724 " --sha3-256 Use the sha3-256 algorithm (default)",
21725 " --sha3-384 Use the sha3-384 algorithm",
21726 " --sha3-512 Use the sha3-512 algorithm",
21742 ",testcase NAME Begin redirecting output to 'testcase-out.txt'",
21754 " --expanded Expand query parameters",
21756 " --normalized Normal the SQL statements",
21758 " --plain Show SQL as it is input",
21759 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
21760 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
21761 " --row Trace each row (SQLITE_TRACE_ROW)",
21762 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
21766 " --allexcept Unregister everything except those named",
21769 ".vfsinfo ?AUX? Information about the top-level VFS",
21773 " Negative values right-justify",
21780 ** If zPattern is NULL, then show all commands, but only give a one-line
21792 || cli_strcmp(zPattern,"-a")==0 in showHelp()
21793 || cli_strcmp(zPattern,"-all")==0 in showHelp()
21794 || cli_strcmp(zPattern,"--all")==0 in showHelp()
21845 while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){ in showHelp()
21858 while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i; in showHelp()
21864 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){ in showHelp()
21888 ** For convenience, a nul-terminator byte is always appended to the data read
21935 sqlite3session_delete(pSession->p); in session_close()
21936 sqlite3_free(pSession->zName); in session_close()
21937 for(i=0; i<pSession->nFilter; i++){ in session_close()
21938 sqlite3_free(pSession->azFilter[i]); in session_close()
21940 sqlite3_free(pSession->azFilter); in session_close()
21951 struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i]; in session_close_all()
21952 for(j=0; j<pAuxDb->nSession; j++){ in session_close_all()
21953 session_close(&pAuxDb->aSession[j]); in session_close_all()
21955 pAuxDb->nSession = 0; in session_close_all()
21969 for(i=0; i<pSession->nFilter; i++){ in session_filter()
21970 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0; in session_filter()
22002 fseek(f, -25, SEEK_END); in deduceDatabaseType()
22004 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){ in deduceDatabaseType()
22007 fseek(f, -22, SEEK_END); in deduceDatabaseType()
22022 ** Reconstruct an in-memory database using the output from the "dbtotxt"
22023 ** program. Read content from the file in p->aAuxDb[].zDbFilename.
22024 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
22035 const char *zDbFilename = p->pAuxDb->zDbFilename; in readHexDb()
22046 in = p->in; in readHexDb()
22047 nLine = p->lineno; in readHexDb()
22056 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error; in readHexDb()
22057 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */ in readHexDb()
22061 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){ in readHexDb()
22086 if( in!=p->in ){ in readHexDb()
22089 p->lineno = nLine; in readHexDb()
22094 if( in!=p->in ){ in readHexDb()
22097 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){ in readHexDb()
22101 p->lineno = nLine; in readHexDb()
22104 eputf("Error on line %d of --hexdb input\n", nLine); in readHexDb()
22141 if( p->db==0 ){ in open_db()
22142 const char *zDbFilename = p->pAuxDb->zDbFilename; in open_db()
22143 if( p->openMode==SHELL_OPEN_UNSPEC ){ in open_db()
22145 p->openMode = SHELL_OPEN_NORMAL; in open_db()
22147 p->openMode = (u8)deduceDatabaseType(zDbFilename, in open_db()
22151 switch( p->openMode ){ in open_db()
22153 sqlite3_open_v2(zDbFilename, &p->db, in open_db()
22154 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs"); in open_db()
22159 sqlite3_open(0, &p->db); in open_db()
22163 sqlite3_open(":memory:", &p->db); in open_db()
22167 sqlite3_open_v2(zDbFilename, &p->db, in open_db()
22168 SQLITE_OPEN_READONLY|p->openFlags, 0); in open_db()
22173 sqlite3_open_v2(zDbFilename, &p->db, in open_db()
22174 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0); in open_db()
22178 globalDb = p->db; in open_db()
22179 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ in open_db()
22181 zDbFilename, sqlite3_errmsg(p->db)); in open_db()
22185 sqlite3_close(p->db); in open_db()
22186 sqlite3_open(":memory:", &p->db); in open_db()
22187 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ in open_db()
22188 eputz("Also: unable to open substitute in-memory database.\n"); in open_db()
22191 eputf("Notice: using substitute in-memory database instead of \"%s\"\n", in open_db()
22195 sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0); in open_db()
22197 /* Reflect the use or absence of --unsafe-testing invocation. */ in open_db()
22200 sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0); in open_db()
22201 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0); in open_db()
22205 sqlite3_enable_load_extension(p->db, 1); in open_db()
22207 sqlite3_shathree_init(p->db, 0, 0); in open_db()
22208 sqlite3_uint_init(p->db, 0, 0); in open_db()
22209 sqlite3_decimal_init(p->db, 0, 0); in open_db()
22210 sqlite3_base64_init(p->db, 0, 0); in open_db()
22211 sqlite3_base85_init(p->db, 0, 0); in open_db()
22212 sqlite3_regexp_init(p->db, 0, 0); in open_db()
22213 sqlite3_ieee_init(p->db, 0, 0); in open_db()
22214 sqlite3_series_init(p->db, 0, 0); in open_db()
22216 sqlite3_fileio_init(p->db, 0, 0); in open_db()
22217 sqlite3_completion_init(p->db, 0, 0); in open_db()
22220 if( !p->bSafeModePersist ){ in open_db()
22221 sqlite3_zipfile_init(p->db, 0, 0); in open_db()
22222 sqlite3_sqlar_init(p->db, 0, 0); in open_db()
22228 * This is a short-span macro. See further below for usage. in open_db()
22232 /* Let custom-included extensions get their ..._init() called. in open_db()
22238 int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db); in open_db()
22239 /* Let custom-included extensions expose their functionality. in open_db()
22246 SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0); in open_db()
22253 sqlite3_create_function(p->db, "strtod", 1, SQLITE_UTF8, 0, in open_db()
22255 sqlite3_create_function(p->db, "dtostr", 1, SQLITE_UTF8, 0, in open_db()
22257 sqlite3_create_function(p->db, "dtostr", 2, SQLITE_UTF8, 0, in open_db()
22259 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0, in open_db()
22261 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0, in open_db()
22263 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p, in open_db()
22265 sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0, in open_db()
22268 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0, in open_db()
22270 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0, in open_db()
22276 int err = register_localized_collators(p->db, "en_US", 0); in open_db()
22281 err = register_android_functions(p->db, 0); in open_db()
22289 if( p->openMode==SHELL_OPEN_ZIPFILE ){ in open_db()
22293 sqlite3_exec(p->db, zSql, 0, 0, 0); in open_db()
22298 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){ in open_db()
22302 if( p->openMode==SHELL_OPEN_DESERIALIZE ){ in open_db()
22310 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData, in open_db()
22316 if( p->szMax>0 ){ in open_db()
22317 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax); in open_db()
22322 if( p->db!=0 ){ in open_db()
22323 if( p->bSafeModePersist ){ in open_db()
22324 sqlite3_set_authorizer(p->db, safeModeAuth, p); in open_db()
22327 p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0 in open_db()
22355 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); in readline_completion_generator()
22386 if( nLine>(i64)sizeof(zBuf)-30 ) return; in linenoise_completion()
22388 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){} in linenoise_completion()
22389 if( i==nLine-1 ) return; in linenoise_completion()
22396 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); in linenoise_completion()
22402 if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){ in linenoise_completion()
22412 ** Do C-language style dequoting.
22414 ** \a -> alarm
22415 ** \b -> backspace
22416 ** \t -> tab
22417 ** \n -> newline
22418 ** \v -> vertical tab
22419 ** \f -> form feed
22420 ** \r -> carriage return
22421 ** \s -> space
22422 ** \" -> "
22423 ** \' -> '
22424 ** \\ -> backslash
22425 ** \NNN -> ascii character NNN in octal
22426 ** \xHH -> ascii character HH in hexadecimal
22465 c -= '0'; in resolve_backslashes()
22468 c = (c<<3) + z[i] - '0'; in resolve_backslashes()
22471 c = (c<<3) + z[i] - '0'; in resolve_backslashes()
22557 if( p->traceOut==0 ) return 0; in sql_trace_callback()
22559 sputz(p->traceOut, "-- closing database connection\n"); in sql_trace_callback()
22562 if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){ in sql_trace_callback()
22566 switch( p->eTraceType ){ in sql_trace_callback()
22586 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; } in sql_trace_callback()
22590 sputf(p->traceOut, "%.*s;\n", (int)nSql, zSql); in sql_trace_callback()
22595 sputf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec); in sql_trace_callback()
22604 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
22637 if( p->in!=0 && p->xCloser!=0 ){ in import_cleanup()
22638 p->xCloser(p->in); in import_cleanup()
22639 p->in = 0; in import_cleanup()
22641 sqlite3_free(p->z); in import_cleanup()
22642 p->z = 0; in import_cleanup()
22647 if( p->n+1>=p->nAlloc ){ in import_append_char()
22648 p->nAlloc += p->nAlloc + 100; in import_append_char()
22649 p->z = sqlite3_realloc64(p->z, p->nAlloc); in import_append_char()
22650 shell_check_oom(p->z); in import_append_char()
22652 p->z[p->n++] = (char)c; in import_append_char()
22658 ** + Input comes from p->in.
22659 ** + Store results in p->z of length p->n. Space to hold p->z comes
22661 ** + Use p->cSep as the column separator. The default is ",".
22662 ** + Use p->rSep as the row separator. The default is "\n".
22663 ** + Keep track of the line number in p->nLine.
22664 ** + Store the character that terminates the field in p->cTerm. Store
22665 ** EOF on end-of-file.
22670 int cSep = (u8)p->cColSep; in csv_read_one_field()
22671 int rSep = (u8)p->cRowSep; in csv_read_one_field()
22672 p->n = 0; in csv_read_one_field()
22673 c = fgetc(p->in); in csv_read_one_field()
22675 p->cTerm = EOF; in csv_read_one_field()
22680 int startLine = p->nLine; in csv_read_one_field()
22684 c = fgetc(p->in); in csv_read_one_field()
22685 if( c==rSep ) p->nLine++; in csv_read_one_field()
22697 do{ p->n--; }while( p->z[p->n]!=cQuote ); in csv_read_one_field()
22698 p->cTerm = c; in csv_read_one_field()
22702 eputf("%s:%d: unescaped %c character\n", p->zFile, p->nLine, cQuote); in csv_read_one_field()
22705 eputf("%s:%d: unterminated %c-quoted field\n", in csv_read_one_field()
22706 p->zFile, startLine, cQuote); in csv_read_one_field()
22707 p->cTerm = c; in csv_read_one_field()
22716 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ in csv_read_one_field()
22717 if( (c&0xff)==0xef && p->bNotFirst==0 ){ in csv_read_one_field()
22719 c = fgetc(p->in); in csv_read_one_field()
22722 c = fgetc(p->in); in csv_read_one_field()
22724 p->bNotFirst = 1; in csv_read_one_field()
22725 p->n = 0; in csv_read_one_field()
22732 c = fgetc(p->in); in csv_read_one_field()
22735 p->nLine++; in csv_read_one_field()
22736 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; in csv_read_one_field()
22738 p->cTerm = c; in csv_read_one_field()
22740 if( p->z ) p->z[p->n] = 0; in csv_read_one_field()
22741 p->bNotFirst = 1; in csv_read_one_field()
22742 return p->z; in csv_read_one_field()
22747 ** + Input comes from p->in.
22748 ** + Store results in p->z of length p->n. Space to hold p->z comes
22750 ** + Use p->cSep as the column separator. The default is "\x1F".
22751 ** + Use p->rSep as the row separator. The default is "\x1E".
22752 ** + Keep track of the row number in p->nLine.
22753 ** + Store the character that terminates the field in p->cTerm. Store
22754 ** EOF on end-of-file.
22759 int cSep = (u8)p->cColSep; in ascii_read_one_field()
22760 int rSep = (u8)p->cRowSep; in ascii_read_one_field()
22761 p->n = 0; in ascii_read_one_field()
22762 c = fgetc(p->in); in ascii_read_one_field()
22764 p->cTerm = EOF; in ascii_read_one_field()
22769 c = fgetc(p->in); in ascii_read_one_field()
22772 p->nLine++; in ascii_read_one_field()
22774 p->cTerm = c; in ascii_read_one_field()
22775 if( p->z ) p->z[p->n] = 0; in ascii_read_one_field()
22776 return p->z; in ascii_read_one_field()
22802 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); in tryToCloneData()
22805 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery); in tryToCloneData()
22819 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0); in tryToCloneData()
22844 -1, SQLITE_STATIC); in tryToCloneData()
22863 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]); in tryToCloneData()
22873 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); in tryToCloneData()
22910 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); in tryToCloneSchema()
22912 eputf("Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db), in tryToCloneSchema()
22913 sqlite3_errmsg(p->db), zQuery); in tryToCloneSchema()
22940 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); in tryToCloneSchema()
22943 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery); in tryToCloneSchema()
22985 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); in tryToClone()
22990 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); in tryToClone()
23000 if( p->out != stdout ) eputz("Output already redirected.\n"); in output_redir()
23002 p->out = pfNew; in output_redir()
23010 ** If the p->doXdgOpen flag is set, that means the output was being
23011 ** redirected to a temporary file named by p->zTempFile. In that case,
23012 ** launch start/open/xdg-open on that temporary file.
23015 if( p->outfile[0]=='|' ){ in output_reset()
23017 pclose(p->out); in output_reset()
23020 output_file_close(p->out); in output_reset()
23022 if( p->doXdgOpen ){ in output_reset()
23029 "xdg-open"; in output_reset()
23032 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile); in output_reset()
23036 /* Give the start/open/xdg-open command some time to get in output_reset()
23038 ** p->zTempFile data file out from under it */ in output_reset()
23043 p->doXdgOpen = 0; in output_reset()
23047 p->outfile[0] = 0; in output_reset()
23048 p->out = stdout; in output_reset()
23062 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); in db_int()
23072 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
23120 if( p->db==0 ) return 1; in shell_dbinfo_command()
23121 rc = sqlite3_prepare_v2(p->db, in shell_dbinfo_command()
23123 -1, &pStmt, 0); in shell_dbinfo_command()
23125 eputf("error: %s\n", sqlite3_errmsg(p->db)); in shell_dbinfo_command()
23129 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC); in shell_dbinfo_command()
23144 oputf("%-20s %d\n", "database page size:", i); in shell_dbinfo_command()
23145 oputf("%-20s %d\n", "write format:", aHdr[18]); in shell_dbinfo_command()
23146 oputf("%-20s %d\n", "read format:", aHdr[19]); in shell_dbinfo_command()
23147 oputf("%-20s %d\n", "reserved bytes:", aHdr[20]); in shell_dbinfo_command()
23151 oputf("%-20s %u", aField[i].zName, val); in shell_dbinfo_command()
23170 int val = db_int(p->db, zSql); in shell_dbinfo_command()
23172 oputf("%-20s %d\n", aQuery[i].zName, val); in shell_dbinfo_command()
23175 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion); in shell_dbinfo_command()
23176 oputf("%-20s %u\n", "data version", iDataVersion); in shell_dbinfo_command()
23206 ** optional + or - sign in front
23230 while( *z && testcase_glob(zGlob-1,z)==0 ){ in testcase_glob()
23261 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ in testcase_glob()
23275 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++; in testcase_glob()
23289 ** Compare the string as a command-line option with either one or two
23290 ** initial "-" characters.
23293 if( zStr[0]!='-' ) return 0; in optionMatch()
23295 if( zStr[0]=='-' ) zStr++; in optionMatch()
23319 if( p->zTempFile==0 ) return; in clearTempFile()
23320 if( p->doXdgOpen ) return; in clearTempFile()
23321 if( shellDeleteFile(p->zTempFile) ) return; in clearTempFile()
23322 sqlite3_free(p->zTempFile); in clearTempFile()
23323 p->zTempFile = 0; in clearTempFile()
23331 sqlite3_free(p->zTempFile); in newTempFile()
23332 p->zTempFile = 0; in newTempFile()
23333 if( p->db ){ in newTempFile()
23334 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile); in newTempFile()
23336 if( p->zTempFile==0 ){ in newTempFile()
23337 /* If p->db is an in-memory database then the TEMPFILENAME file-control in newTempFile()
23351 p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix); in newTempFile()
23353 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix); in newTempFile()
23355 shell_check_oom(p->zTempFile); in newTempFile()
23361 ** by the ".lint fkey-indexes" command. This scalar function is always
23362 ** called with four arguments - the parent table name, the parent column name,
23365 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
23371 ** function returns the string " COLLATE <parent-collation>", where
23372 ** <parent-collation> is the default collation sequence of the parent column.
23385 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */ in shellFkeyCollateClause()
23394 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); in shellFkeyCollateClause()
23406 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); in shellFkeyCollateClause()
23413 ** The implementation of dot-command ".lint fkey-indexes".
23420 sqlite3 *db = pState->db; /* Database handle to query "main" db of */ in lintFkeyIndexes()
23421 int bVerbose = 0; /* If -verbose is present */ in lintFkeyIndexes()
23422 int bGroupByParent = 0; /* If -groupbyparent is present */ in lintFkeyIndexes()
23486 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) " in lintFkeyIndexes()
23494 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){ in lintFkeyIndexes()
23497 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){ in lintFkeyIndexes()
23502 eputf("Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1]); in lintFkeyIndexes()
23514 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); in lintFkeyIndexes()
23524 int res = -1; in lintFkeyIndexes()
23535 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); in lintFkeyIndexes()
23553 oputf("-- Parent table %s\n", zParent); in lintFkeyIndexes()
23559 oputf("%s%s --> %s\n", zIndent, zCI, zTarget); in lintFkeyIndexes()
23561 oputf("%s/* no extra indexes required for %s -> %s */\n", in lintFkeyIndexes()
23595 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage; in lintDotCommand()
23599 eputf("Usage %s sub-command ?switches...?\n", azArg[0]); in lintDotCommand()
23600 eputz("Where sub-commands are:\n"); in lintDotCommand()
23601 eputz(" fkey-indexes\n"); in lintDotCommand()
23614 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); in shellPrepare()
23623 ** Create a prepared statement using printf-style arguments for the SQL.
23626 ** depending on compile-time options. By omitting the "static", we avoid
23655 ** depending on compile-time options. By omitting the "static", we avoid
23677 ** depending on compile-time options. By omitting the "static", we avoid
23705 u8 bVerbose; /* True if --verbose */
23707 u8 bDryRun; /* True if --dry-run */
23708 u8 bAppend; /* True if --append */
23709 u8 bGlob; /* True if --glob */
23710 u8 fromCmdLine; /* Run from -A instead of .archive */
23713 const char *zFile; /* --file argument, or NULL */
23714 const char *zDir; /* --directory argument, or NULL */
23739 if( pAr->fromCmdLine ){ in arErrorMsg()
23740 eputz("Use \"-A\" for more help\n"); in arErrorMsg()
23742 eputz("Use \".archive --help\" for more help\n"); in arErrorMsg()
23760 ** Other (non-command) switches.
23778 if( pAr->eCmd ){ in arProcessSwitch()
23781 pAr->eCmd = eSwitch; in arProcessSwitch()
23785 pAr->bDryRun = 1; in arProcessSwitch()
23788 pAr->bGlob = 1; in arProcessSwitch()
23791 pAr->bVerbose = 1; in arProcessSwitch()
23794 pAr->bAppend = 1; in arProcessSwitch()
23797 pAr->zFile = zArg; in arProcessSwitch()
23800 pAr->zDir = zArg; in arProcessSwitch()
23846 if( z[0]!='-' ){ in arParseCommand()
23854 if( z[i]==pOpt->cShort ) break; in arParseCommand()
23859 if( pOpt->bArg ){ in arParseCommand()
23865 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; in arParseCommand()
23867 pAr->nArg = nArg-iArg; in arParseCommand()
23868 if( pAr->nArg>0 ){ in arParseCommand()
23869 pAr->azArg = &azArg[iArg]; in arParseCommand()
23872 /* Non-traditional invocation */ in arParseCommand()
23877 if( z[0]!='-' ){ in arParseCommand()
23879 pAr->azArg = &azArg[iArg]; in arParseCommand()
23880 pAr->nArg = nArg-iArg; in arParseCommand()
23885 if( z[1]!='-' ){ in arParseCommand()
23892 if( z[i]==pOpt->cShort ) break; in arParseCommand()
23897 if( pOpt->bArg ){ in arParseCommand()
23898 if( i<(n-1) ){ in arParseCommand()
23902 if( iArg>=(nArg-1) ){ in arParseCommand()
23909 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; in arParseCommand()
23912 /* A -- option, indicating that all remaining command line words in arParseCommand()
23914 pAr->azArg = &azArg[iArg+1]; in arParseCommand()
23915 pAr->nArg = nArg-iArg-1; in arParseCommand()
23923 const char *zLong = pOpt->zLong; in arParseCommand()
23924 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){ in arParseCommand()
23936 if( pMatch->bArg ){ in arParseCommand()
23937 if( iArg>=(nArg-1) ){ in arParseCommand()
23942 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR; in arParseCommand()
23947 if( pAr->eCmd==0 ){ in arParseCommand()
23956 ** array refer to archive members, as for the --extract, --list or --remove
23961 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
23962 ** when pAr->bGlob is true.
23970 if( pAr->nArg ){ in arCheckEntries()
23973 const char *zSel = (pAr->bGlob) in arCheckEntries()
23977 shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable); in arCheckEntries()
23979 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ in arCheckEntries()
23980 char *z = pAr->azArg[i]; in arCheckEntries()
23983 while( n>0 && z[n-1]=='/' ) n--; in arCheckEntries()
23985 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC); in arCheckEntries()
24005 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
24006 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
24014 const char *zSameOp = (pAr->bGlob)? "GLOB" : "="; in arWhereClause()
24016 if( pAr->nArg==0 ){ in arWhereClause()
24021 for(i=0; i<pAr->nArg; i++){ in arWhereClause()
24022 const char *z = pAr->azArg[i]; in arWhereClause()
24055 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose], in arListCommand()
24056 pAr->zSrcTable, zWhere); in arListCommand()
24057 if( pAr->bDryRun ){ in arListCommand()
24061 if( pAr->bVerbose ){ in arListCommand()
24083 if( pAr->nArg ){ in arRemoveCommand()
24091 pAr->zSrcTable, zWhere); in arRemoveCommand()
24092 if( pAr->bDryRun ){ in arRemoveCommand()
24096 rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0); in arRemoveCommand()
24098 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); in arRemoveCommand()
24100 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); in arRemoveCommand()
24102 rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0); in arRemoveCommand()
24145 if( pAr->zDir ){ in arExtractCommand()
24146 zDir = sqlite3_mprintf("%s/", pAr->zDir); in arExtractCommand()
24153 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, in arExtractCommand()
24154 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere in arExtractCommand()
24159 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC); in arExtractCommand()
24169 if( pAr->bDryRun ){ in arExtractCommand()
24173 if( i==0 && pAr->bVerbose ){ in arExtractCommand()
24189 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
24193 if( pAr->bDryRun ){ in arExecSql()
24198 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); in arExecSql()
24211 ** create -> Create a new SQL archive
24212 ** insert -> Insert or reinsert all files listed
24213 ** update -> Insert files that have changed or that were not
24218 ** are added recursively. If argument bVerbose is non-zero, a message is
24223 ** always overwrites every file named on the command-line, where as
24228 int bUpdate, /* true for a --create. */ in arCreateOrUpdateCommand()
24233 " name TEXT PRIMARY KEY, -- name of the file\n" in arCreateOrUpdateCommand()
24234 " mode INT, -- access permissions\n" in arCreateOrUpdateCommand()
24235 " mtime INT, -- last modification time\n" in arCreateOrUpdateCommand()
24236 " sz INT, -- original file size\n" in arCreateOrUpdateCommand()
24237 " data BLOB -- compressed content\n" in arCreateOrUpdateCommand()
24247 " WHEN '-' THEN length(data)\n" in arCreateOrUpdateCommand()
24249 " ELSE -1 END,\n" in arCreateOrUpdateCommand()
24274 if( pAr->bZip ){ in arCreateOrUpdateCommand()
24276 if( pAr->zFile ){ in arCreateOrUpdateCommand()
24283 zTab, pAr->zFile in arCreateOrUpdateCommand()
24310 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ in arCreateOrUpdateCommand()
24311 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab, in arCreateOrUpdateCommand()
24312 pAr->bVerbose ? "shell_putsnl(name)" : "name", in arCreateOrUpdateCommand()
24313 pAr->azArg[i], pAr->zDir, zExists); in arCreateOrUpdateCommand()
24319 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); in arCreateOrUpdateCommand()
24322 if( pAr->bZip && pAr->zFile ){ in arCreateOrUpdateCommand()
24337 int fromCmdLine, /* True if -A command-line option, not .ar cmd */ in arDotCommand()
24349 cmd.db = pState->db; in arDotCommand()
24353 eDbType = pState->openMode; in arDotCommand()
24375 oputf("-- open database '%s'%s\n", cmd.zFile, in arDotCommand()
24415 arUsage(pState->out); in arDotCommand()
24433 if( cmd.db!=pState->db ){ in arDotCommand()
24452 sputf(pState->out, "%s;\n", zSql); in recoverSqlCb()
24459 ** on stream pState->out.
24465 int bFreelist = 1; /* 0 if --ignore-freelist is specified */ in recoverDatabaseCmd()
24466 int bRowids = 1; /* 0 if --no-rowids */ in recoverDatabaseCmd()
24473 if( z[0]=='-' && z[1]=='-' ) z++; in recoverDatabaseCmd()
24475 if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){ in recoverDatabaseCmd()
24478 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){ in recoverDatabaseCmd()
24479 /* This option determines the name of the ATTACH-ed database used in recoverDatabaseCmd()
24487 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){ in recoverDatabaseCmd()
24491 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){ in recoverDatabaseCmd()
24496 showHelp(pState->out, azArg[0]); in recoverDatabaseCmd()
24502 pState->db, "main", recoverSqlCb, (void*)pState in recoverDatabaseCmd()
24531 * pointer is non-zero, its referent will be set to a summary of renames
24581 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\ in zAutoColumn()
24589 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\ in zAutoColumn()
24597 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\ in zAutoColumn()
24655 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\ in zAutoColumn()
24658 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \ in zAutoColumn()
24663 " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff))," in zAutoColumn()
24684 rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0); in zAutoColumn()
24686 rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0); in zAutoColumn()
24706 rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0); in zAutoColumn()
24714 rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0); in zAutoColumn()
24726 if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0) in zAutoColumn()
24754 if( p->expert.pExpert ){ in do_meta_command()
24761 while( zLine[h] && nArg<ArraySize(azArg)-1 ){ in do_meta_command()
24774 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]); in do_meta_command()
24799 sqlite3_set_authorizer(p->db, shellAuth, p); in do_meta_command()
24800 }else if( p->bSafeModePersist ){ in do_meta_command()
24801 sqlite3_set_authorizer(p->db, safeModeAuth, p); in do_meta_command()
24803 sqlite3_set_authorizer(p->db, 0, 0); in do_meta_command()
24831 if( z[0]=='-' ){ in do_meta_command()
24832 if( z[1]=='-' ) z++; in do_meta_command()
24833 if( cli_strcmp(z, "-append")==0 ){ in do_meta_command()
24836 if( cli_strcmp(z, "-async")==0 ){ in do_meta_command()
24870 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb); in do_meta_command()
24901 setBinaryMode(p->out, 1); in do_meta_command()
24903 setTextMode(p->out, 1); in do_meta_command()
24912 /* The undocumented ".breakpoint" command causes a call to the no-op in do_meta_command()
24952 ** Then read the content of the testcase-out.txt file and compare against in do_meta_command()
24959 eputz("Usage: .check GLOB-PATTERN\n"); in do_meta_command()
24961 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){ in do_meta_command()
24964 eputf("testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n", in do_meta_command()
24965 p->zTestcase, azArg[1], zRes); in do_meta_command()
24968 oputf("testcase-%s ok\n", p->zTestcase); in do_meta_command()
24969 p->nCheck++; in do_meta_command()
24991 for(i=0; i<ArraySize(p->aAuxDb); i++){ in do_meta_command()
24992 const char *zFile = p->aAuxDb[i].zDbFilename; in do_meta_command()
24993 if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){ in do_meta_command()
24998 zFile = "(temporary-file)"; in do_meta_command()
25000 if( p->pAuxDb == &p->aAuxDb[i] ){ in do_meta_command()
25002 }else if( p->aAuxDb[i].db!=0 ){ in do_meta_command()
25007 int i = azArg[1][0] - '0'; in do_meta_command()
25008 if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){ in do_meta_command()
25009 p->pAuxDb->db = p->db; in do_meta_command()
25010 p->pAuxDb = &p->aAuxDb[i]; in do_meta_command()
25011 globalDb = p->db = p->pAuxDb->db; in do_meta_command()
25012 p->pAuxDb->db = 0; in do_meta_command()
25016 int i = azArg[2][0] - '0'; in do_meta_command()
25017 if( i<0 || i>=ArraySize(p->aAuxDb) ){ in do_meta_command()
25018 /* No-op */ in do_meta_command()
25019 }else if( p->pAuxDb == &p->aAuxDb[i] ){ in do_meta_command()
25022 }else if( p->aAuxDb[i].db ){ in do_meta_command()
25024 close_db(p->aAuxDb[i].db); in do_meta_command()
25025 p->aAuxDb[i].db = 0; in do_meta_command()
25028 eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n"); in do_meta_command()
25036 setTextMode(p->out, 1); in do_meta_command()
25038 setBinaryMode(p->out, 1); in do_meta_command()
25042 eputz("The \".crnl\" is a no-op on non-Windows machines.\n"); in do_meta_command()
25055 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); in do_meta_command()
25057 eputf("Error: %s\n", sqlite3_errmsg(p->db)); in do_meta_command()
25073 int eTxn = sqlite3_txn_state(p->db, azName[i*2]); in do_meta_command()
25074 int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]); in do_meta_command()
25079 eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn"); in do_meta_command()
25115 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0); in do_meta_command()
25117 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v); in do_meta_command()
25142 int savedShowHeader = p->showHeader; in do_meta_command()
25143 int savedShellFlags = p->shellFlgs; in do_meta_command()
25148 if( azArg[i][0]=='-' ){ in do_meta_command()
25150 if( z[0]=='-' ) z++; in do_meta_command()
25151 if( cli_strcmp(z,"preserve-rowids")==0 ){ in do_meta_command()
25153 eputz("The --preserve-rowids option is not compatible" in do_meta_command()
25165 if( cli_strcmp(z,"data-only")==0 ){ in do_meta_command()
25202 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ in do_meta_command()
25205 ** So disable foreign-key constraint enforcement to prevent problems. */ in do_meta_command()
25209 p->writableSchema = 0; in do_meta_command()
25210 p->showHeader = 0; in do_meta_command()
25214 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); in do_meta_command()
25215 p->nErr = 0; in do_meta_command()
25226 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ in do_meta_command()
25237 if( p->writableSchema ){ in do_meta_command()
25239 p->writableSchema = 0; in do_meta_command()
25241 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); in do_meta_command()
25242 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); in do_meta_command()
25243 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ in do_meta_command()
25244 oputz(p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n"); in do_meta_command()
25246 p->showHeader = savedShowHeader; in do_meta_command()
25247 p->shellFlgs = savedShellFlags; in do_meta_command()
25261 p->autoEQPtest = 0; in do_meta_command()
25262 if( p->autoEQPtrace ){ in do_meta_command()
25263 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0); in do_meta_command()
25264 p->autoEQPtrace = 0; in do_meta_command()
25267 p->autoEQP = AUTOEQP_full; in do_meta_command()
25269 p->autoEQP = AUTOEQP_trigger; in do_meta_command()
25272 p->autoEQP = AUTOEQP_on; in do_meta_command()
25273 p->autoEQPtest = 1; in do_meta_command()
25275 p->autoEQP = AUTOEQP_full; in do_meta_command()
25276 p->autoEQPtrace = 1; in do_meta_command()
25278 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0); in do_meta_command()
25279 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0); in do_meta_command()
25282 p->autoEQP = (u8)booleanValue(azArg[1]); in do_meta_command()
25308 if( val==1 && p->mode!=MODE_Explain ){ in do_meta_command()
25309 p->normalMode = p->mode; in do_meta_command()
25310 p->mode = MODE_Explain; in do_meta_command()
25311 p->autoExplain = 0; in do_meta_command()
25313 if( p->mode==MODE_Explain ) p->mode = p->normalMode; in do_meta_command()
25314 p->autoExplain = 0; in do_meta_command()
25316 if( p->mode==MODE_Explain ) p->mode = p->normalMode; in do_meta_command()
25317 p->autoExplain = 1; in do_meta_command()
25323 if( p->bSafeMode ){ in do_meta_command()
25336 const char *zCtrlName; /* Name of a test-control option */ in do_meta_command()
25352 int filectrl = -1; in do_meta_command()
25353 int iCtrl = -1; in do_meta_command()
25355 int isOk = 0; /* 0: usage 1: %lld 2: no-result */ in do_meta_command()
25363 if( zCmd[0]=='-' in do_meta_command()
25364 && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0) in do_meta_command()
25368 for(i=3; i<nArg; i++) azArg[i-2] = azArg[i]; in do_meta_command()
25369 nArg -= 2; in do_meta_command()
25373 /* The argument can optionally begin with "-" or "--" */ in do_meta_command()
25374 if( zCmd[0]=='-' && zCmd[1] ){ in do_meta_command()
25376 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; in do_meta_command()
25379 /* --help lists all file-controls */ in do_meta_command()
25381 oputz("Available file-controls:\n"); in do_meta_command()
25398 eputf("Error: ambiguous file-control: \"%s\"\n" in do_meta_command()
25399 "Use \".filectrl --help\" for help\n", zCmd); in do_meta_command()
25406 eputf("Error: unknown file-control: %s\n" in do_meta_command()
25407 "Use \".filectrl --help\" for help\n", zCmd); in do_meta_command()
25412 iRes = nArg==3 ? integerValue(azArg[2]) : -1; in do_meta_command()
25413 sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes); in do_meta_command()
25422 sqlite3_file_control(p->db, zSchema, filectrl, &x); in do_meta_command()
25430 x = nArg==3 ? booleanValue(azArg[2]) : -1; in do_meta_command()
25431 sqlite3_file_control(p->db, zSchema, filectrl, &x); in do_meta_command()
25440 sqlite3_file_control(p->db, zSchema, filectrl, &x); in do_meta_command()
25448 sqlite3_file_control(p->db, zSchema, filectrl, &z); in do_meta_command()
25460 sqlite3_file_control(p->db, zSchema, filectrl, &x); in do_meta_command()
25462 x = -1; in do_meta_command()
25463 sqlite3_file_control(p->db, zSchema, filectrl, &x); in do_meta_command()
25491 eputz("Usage: .fullschema ?--indent?\n"); in do_meta_command()
25496 rc = sqlite3_exec(p->db, in do_meta_command()
25507 rc = sqlite3_prepare_v2(p->db, in do_meta_command()
25510 -1, &pStmt, 0); in do_meta_command()
25531 p->showHeader = booleanValue(azArg[1]); in do_meta_command()
25532 p->shellFlgs |= SHFLG_HeaderSet; in do_meta_command()
25541 n = showHelp(p->out, azArg[1]); in do_meta_command()
25546 showHelp(p->out, 0); in do_meta_command()
25560 int nSep; /* Number of bytes in p->colSeparator[] */ in do_meta_command()
25572 if( p->mode==MODE_Ascii ){ in do_meta_command()
25580 if( z[0]=='-' && z[1]=='-' ) z++; in do_meta_command()
25581 if( z[0]!='-' ){ in do_meta_command()
25588 showHelp(p->out, "import"); in do_meta_command()
25591 }else if( cli_strcmp(z,"-v")==0 ){ in do_meta_command()
25593 }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){ in do_meta_command()
25595 }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){ in do_meta_command()
25597 }else if( cli_strcmp(z,"-ascii")==0 ){ in do_meta_command()
25602 }else if( cli_strcmp(z,"-csv")==0 ){ in do_meta_command()
25609 showHelp(p->out, "import"); in do_meta_command()
25616 showHelp(p->out, "import"); in do_meta_command()
25622 /* If neither the --csv or --ascii options are specified, then set in do_meta_command()
25624 nSep = strlen30(p->colSeparator); in do_meta_command()
25626 eputz("Error: non-null column separator required for import\n"); in do_meta_command()
25630 eputz("Error: multi-character column separators not allowed" in do_meta_command()
25634 nSep = strlen30(p->rowSeparator); in do_meta_command()
25636 eputz("Error: non-null row separator required for import\n"); in do_meta_command()
25639 if( nSep==2 && p->mode==MODE_Csv in do_meta_command()
25640 && cli_strcmp(p->rowSeparator,SEP_CrLf)==0 in do_meta_command()
25646 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
25647 nSep = strlen30(p->rowSeparator); in do_meta_command()
25650 eputz("Error: multi-character row separators not allowed" in do_meta_command()
25654 sCtx.cColSep = (u8)p->colSeparator[0]; in do_meta_command()
25655 sCtx.cRowSep = (u8)p->rowSeparator[0]; in do_meta_command()
25693 while( (nSkip--)>0 ){ in do_meta_command()
25707 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
25709 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){ in do_meta_command()
25720 sputf((stdin_is_interactive && p->in==stdin)? p->out : stderr, in do_meta_command()
25740 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); in do_meta_command()
25742 eputf("%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db)); in do_meta_command()
25747 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
25751 eputf("Error: %s\n", sqlite3_errmsg(p->db)); in do_meta_command()
25775 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
25777 eputf("Error: %s\n", sqlite3_errmsg(p->db)); in do_meta_command()
25783 needCommit = sqlite3_get_autocommit(p->db); in do_meta_command()
25784 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); in do_meta_command()
25790 ** Did we reach end-of-file before finding any columns? in do_meta_command()
25795 ** Did we reach end-of-file OR end-of-line before finding any in do_meta_command()
25799 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; in do_meta_command()
25802 ** record terminator but only for last field of multi-field row. in do_meta_command()
25805 if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){ in do_meta_command()
25808 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); in do_meta_command()
25809 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){ in do_meta_command()
25811 " - filling the rest with NULL\n", in do_meta_command()
25822 eputf("%s:%d: expected %d columns but found %d - extras ignored\n", in do_meta_command()
25830 sCtx.zFile, startLine, sqlite3_errmsg(p->db)); in do_meta_command()
25840 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); in do_meta_command()
25843 sCtx.nRow, sCtx.nErr, sCtx.nLine-1); in do_meta_command()
25858 eputf(".%s unavailable without --unsafe-testing\n", in do_meta_command()
25878 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1); in do_meta_command()
25890 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
25898 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
25906 if( sqlite3_column_int(pStmt,1)==-1 ){ in do_meta_command()
25934 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum); in do_meta_command()
25936 rc = sqlite3_exec(p->db, zSql, 0, 0, 0); in do_meta_command()
25937 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0); in do_meta_command()
25939 eputf("Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db)); in do_meta_command()
25960 }else if( cli_strcmp(azArg[1], "-")==0 ){ in do_meta_command()
25999 sqlite3_limit(p->db, aLimit[i].limitCode, -1)); in do_meta_command()
26002 eputz("Usage: .limit NAME ?NEW-VALUE?\n"); in do_meta_command()
26006 int iLimit = -1; in do_meta_command()
26027 sqlite3_limit(p->db, aLimit[iLimit].limitCode, in do_meta_command()
26031 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); in do_meta_command()
26046 /* Must have a non-empty FILE. (Will not load self.) */ in do_meta_command()
26054 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); in do_meta_command()
26069 if( p->bSafeMode in do_meta_command()
26077 output_file_close(p->pLog); in do_meta_command()
26079 p->pLog = output_file_open(zFile, 0); in do_meta_command()
26102 /* Apply defaults for qbox pseudo-mode. If that in do_meta_command()
26103 * overwrites already-set values, user was informed of this. in do_meta_command()
26112 }else if( z[0]=='-' ){ in do_meta_command()
26115 " --noquote\n" in do_meta_command()
26116 " --quote\n" in do_meta_command()
26117 " --wordwrap on/off\n" in do_meta_command()
26118 " --wrap N\n" in do_meta_command()
26119 " --ww\n"); in do_meta_command()
26129 if( p->mode==MODE_Column in do_meta_command()
26130 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box) in do_meta_command()
26132 oputf("current output mode: %s --wrap %d --wordwrap %s --%squote\n", in do_meta_command()
26133 modeDescr[p->mode], p->cmOpts.iWrap, in do_meta_command()
26134 p->cmOpts.bWordWrap ? "on" : "off", in do_meta_command()
26135 p->cmOpts.bQuote ? "" : "no"); in do_meta_command()
26137 oputf("current output mode: %s\n", modeDescr[p->mode]); in do_meta_command()
26139 zMode = modeDescr[p->mode]; in do_meta_command()
26143 p->mode = MODE_Line; in do_meta_command()
26144 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
26146 p->mode = MODE_Column; in do_meta_command()
26147 if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){ in do_meta_command()
26148 p->showHeader = 1; in do_meta_command()
26150 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
26151 p->cmOpts = cmOpts; in do_meta_command()
26153 p->mode = MODE_List; in do_meta_command()
26154 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column); in do_meta_command()
26155 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
26157 p->mode = MODE_Html; in do_meta_command()
26159 p->mode = MODE_Tcl; in do_meta_command()
26160 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space); in do_meta_command()
26161 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
26163 p->mode = MODE_Csv; in do_meta_command()
26164 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); in do_meta_command()
26165 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); in do_meta_command()
26167 p->mode = MODE_List; in do_meta_command()
26168 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab); in do_meta_command()
26170 p->mode = MODE_Insert; in do_meta_command()
26173 p->mode = MODE_Quote; in do_meta_command()
26174 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); in do_meta_command()
26175 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); in do_meta_command()
26177 p->mode = MODE_Ascii; in do_meta_command()
26178 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit); in do_meta_command()
26179 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record); in do_meta_command()
26181 p->mode = MODE_Markdown; in do_meta_command()
26182 p->cmOpts = cmOpts; in do_meta_command()
26184 p->mode = MODE_Table; in do_meta_command()
26185 p->cmOpts = cmOpts; in do_meta_command()
26187 p->mode = MODE_Box; in do_meta_command()
26188 p->cmOpts = cmOpts; in do_meta_command()
26190 p->mode = MODE_Count; in do_meta_command()
26192 p->mode = MODE_Off; in do_meta_command()
26194 p->mode = MODE_Json; in do_meta_command()
26201 p->cMode = p->mode; in do_meta_command()
26209 }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){ in do_meta_command()
26211 p->lineno, azArg[1]); in do_meta_command()
26214 p->bSafeMode = 0; in do_meta_command()
26223 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue, in do_meta_command()
26224 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]); in do_meta_command()
26238 /* Check for command-line arguments */ in do_meta_command()
26253 p->openFlags |= SQLITE_OPEN_NOFOLLOW; in do_meta_command()
26260 p->szMax = integerValue(azArg[++iName]); in do_meta_command()
26264 if( z[0]=='-' ){ in do_meta_command()
26278 session_close_all(p, -1); in do_meta_command()
26279 close_db(p->db); in do_meta_command()
26280 p->db = 0; in do_meta_command()
26281 p->pAuxDb->zDbFilename = 0; in do_meta_command()
26282 sqlite3_free(p->pAuxDb->zFreeOnClose); in do_meta_command()
26283 p->pAuxDb->zFreeOnClose = 0; in do_meta_command()
26284 p->openMode = openMode; in do_meta_command()
26285 p->openFlags = 0; in do_meta_command()
26286 p->szMax = 0; in do_meta_command()
26289 if( zFN || p->openMode==SHELL_OPEN_HEXDB ){ in do_meta_command()
26290 if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN); in do_meta_command()
26292 if( p->bSafeMode in do_meta_command()
26293 && p->openMode!=SHELL_OPEN_HEXDB in do_meta_command()
26297 failIfSafeMode(p, "cannot open disk-based database files in safe mode"); in do_meta_command()
26300 /* WASM mode has its own sandboxed pseudo-filesystem. */ in do_meta_command()
26308 p->pAuxDb->zDbFilename = zNewFilename; in do_meta_command()
26310 if( p->db==0 ){ in do_meta_command()
26314 p->pAuxDb->zFreeOnClose = zNewFilename; in do_meta_command()
26317 if( p->db==0 ){ in do_meta_command()
26318 /* As a fall-back open a TEMP database */ in do_meta_command()
26319 p->pAuxDb->zDbFilename = 0; in do_meta_command()
26347 if( z[0]=='-' ){ in do_meta_command()
26348 if( z[1]=='-' ) z++; in do_meta_command()
26349 if( cli_strcmp(z,"-bom")==0 ){ in do_meta_command()
26351 }else if( c!='e' && cli_strcmp(z,"-x")==0 ){ in do_meta_command()
26353 }else if( c!='e' && cli_strcmp(z,"-e")==0 ){ in do_meta_command()
26357 showHelp(p->out, azArg[0]); in do_meta_command()
26369 showHelp(p->out, azArg[0]); in do_meta_command()
26379 p->outCount = 2; in do_meta_command()
26381 p->outCount = 0; in do_meta_command()
26386 p->doXdgOpen = 1; in do_meta_command()
26392 p->mode = MODE_Csv; in do_meta_command()
26393 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); in do_meta_command()
26394 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); in do_meta_command()
26401 zFile = sqlite3_mprintf("%s", p->zTempFile); in do_meta_command()
26418 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); in do_meta_command()
26431 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); in do_meta_command()
26446 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;", in do_meta_command()
26457 rx = sqlite3_prepare_v2(p->db, in do_meta_command()
26459 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); in do_meta_command()
26467 rx = sqlite3_prepare_v2(p->db, in do_meta_command()
26469 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); in do_meta_command()
26471 oputf("%-*s %s\n", len, sqlite3_column_text(pStmt,0), in do_meta_command()
26504 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
26513 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
26516 oputf("Error: %s\n", sqlite3_errmsg(p->db)); in do_meta_command()
26534 sqlite3_exec(p->db, zSql, 0, 0, 0); in do_meta_command()
26539 showHelp(p->out, "parameter"); in do_meta_command()
26555 p->flgProgress = 0; in do_meta_command()
26556 p->mxProgress = 0; in do_meta_command()
26557 p->nProgress = 0; in do_meta_command()
26560 if( z[0]=='-' ){ in do_meta_command()
26562 if( z[0]=='-' ) z++; in do_meta_command()
26564 p->flgProgress |= SHELL_PROGRESS_QUIET; in do_meta_command()
26568 p->flgProgress |= SHELL_PROGRESS_RESET; in do_meta_command()
26572 p->flgProgress |= SHELL_PROGRESS_ONCE; in do_meta_command()
26577 eputz("Error: missing argument on --limit\n"); in do_meta_command()
26581 p->mxProgress = (int)integerValue(azArg[++i]); in do_meta_command()
26593 sqlite3_progress_handler(p->db, nn, progress_handler, p); in do_meta_command()
26599 shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); in do_meta_command()
26602 shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); in do_meta_command()
26614 FILE *inSaved = p->in; in do_meta_command()
26615 int savedLineno = p->lineno; in do_meta_command()
26626 p->out = stdout; in do_meta_command()
26628 p->in = popen(azArg[1]+1, "r"); in do_meta_command()
26629 if( p->in==0 ){ in do_meta_command()
26634 pclose(p->in); in do_meta_command()
26637 }else if( (p->in = openChrSource(azArg[1]))==0 ){ in do_meta_command()
26642 fclose(p->in); in do_meta_command()
26644 p->in = inSaved; in do_meta_command()
26645 p->lineno = savedLineno; in do_meta_command()
26676 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); in do_meta_command()
26678 eputf("Error: %s\n", sqlite3_errmsg(p->db)); in do_meta_command()
26696 eputf("Error: %s\n", sqlite3_errmsg(p->db)); in do_meta_command()
26706 p->scanstatsOn = 3; in do_meta_command()
26709 p->scanstatsOn = 2; in do_meta_command()
26711 p->scanstatsOn = (u8)booleanValue(azArg[1]); in do_meta_command()
26715 p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0 in do_meta_command()
26720 if( p->scanstatsOn==3 ){ in do_meta_command()
26753 }else if( azArg[ii][0]=='-' ){ in do_meta_command()
26760 eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n"); in do_meta_command()
26790 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list", in do_meta_command()
26791 -1, &pStmt, 0); in do_meta_command()
26793 eputf("Error: %s\n", sqlite3_errmsg(p->db)); in do_meta_command()
26857 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg); in do_meta_command()
26882 struct AuxDb *pAuxDb = p->pAuxDb; in do_meta_command()
26883 OpenSession *pSession = &pAuxDb->aSession[0]; in do_meta_command()
26886 int nCmd = nArg - 1; in do_meta_command()
26891 for(iSes=0; iSes<pAuxDb->nSession; iSes++){ in do_meta_command()
26892 if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break; in do_meta_command()
26894 if( iSes<pAuxDb->nSession ){ in do_meta_command()
26895 pSession = &pAuxDb->aSession[iSes]; in do_meta_command()
26897 nCmd--; in do_meta_command()
26899 pSession = &pAuxDb->aSession[0]; in do_meta_command()
26910 if( pSession->p==0 ){ in do_meta_command()
26914 rc = sqlite3session_attach(pSession->p, azCmd[1]); in do_meta_command()
26932 if( pSession->p==0 ) goto session_not_open; in do_meta_command()
26941 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); in do_meta_command()
26943 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); in do_meta_command()
26951 eputf("ERROR: Failed to write entire %d-byte output\n", szChng); in do_meta_command()
26963 if( pAuxDb->nSession ){ in do_meta_command()
26965 pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession]; in do_meta_command()
26975 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); in do_meta_command()
26976 if( pAuxDb->nSession ){ in do_meta_command()
26977 ii = sqlite3session_enable(pSession->p, ii); in do_meta_command()
26978 oputf("session %s enable flag = %d\n", pSession->zName, ii); in do_meta_command()
26988 if( pAuxDb->nSession ){ in do_meta_command()
26989 for(ii=0; ii<pSession->nFilter; ii++){ in do_meta_command()
26990 sqlite3_free(pSession->azFilter[ii]); in do_meta_command()
26992 sqlite3_free(pSession->azFilter); in do_meta_command()
26993 nByte = sizeof(pSession->azFilter[0])*(nCmd-1); in do_meta_command()
26994 pSession->azFilter = sqlite3_malloc( nByte ); in do_meta_command()
26995 shell_check_oom( pSession->azFilter ); in do_meta_command()
26997 char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); in do_meta_command()
27000 pSession->nFilter = ii-1; in do_meta_command()
27010 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); in do_meta_command()
27011 if( pAuxDb->nSession ){ in do_meta_command()
27012 ii = sqlite3session_indirect(pSession->p, ii); in do_meta_command()
27013 oputf("session %s indirect flag = %d\n", pSession->zName, ii); in do_meta_command()
27023 if( pAuxDb->nSession ){ in do_meta_command()
27024 ii = sqlite3session_isempty(pSession->p); in do_meta_command()
27025 oputf("session %s isempty flag = %d\n", pSession->zName, ii); in do_meta_command()
27033 for(i=0; i<pAuxDb->nSession; i++){ in do_meta_command()
27034 oputf("%d %s\n", i, pAuxDb->aSession[i].zName); in do_meta_command()
27047 for(i=0; i<pAuxDb->nSession; i++){ in do_meta_command()
27048 if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){ in do_meta_command()
27053 if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){ in do_meta_command()
27054 eputf("Maximum of %d sessions\n", ArraySize(pAuxDb->aSession)); in do_meta_command()
27057 pSession = &pAuxDb->aSession[pAuxDb->nSession]; in do_meta_command()
27058 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); in do_meta_command()
27064 pSession->nFilter = 0; in do_meta_command()
27065 sqlite3session_table_filter(pSession->p, session_filter, pSession); in do_meta_command()
27066 pAuxDb->nSession++; in do_meta_command()
27067 pSession->zName = sqlite3_mprintf("%s", zName); in do_meta_command()
27068 shell_check_oom(pSession->zName); in do_meta_command()
27072 showHelp(p->out, "session"); in do_meta_command()
27079 if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){ in do_meta_command()
27080 if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){ in do_meta_command()
27087 if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){ in do_meta_command()
27112 if( z[0]=='-' && z[1]=='-' ) z++; in do_meta_command()
27113 if( cli_strcmp(z,"-init")==0 ){ in do_meta_command()
27116 if( cli_strcmp(z,"-v")==0 ){ in do_meta_command()
27121 eputz("Should be one of: --init -v\n"); in do_meta_command()
27126 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0) in do_meta_command()
27138 for(k=bSelftestExists; k>=0; k--){ in do_meta_command()
27140 rc = sqlite3_prepare_v2(p->db, in do_meta_command()
27142 -1, &pStmt, 0); in do_meta_command()
27144 rc = sqlite3_prepare_v2(p->db, in do_meta_command()
27145 "VALUES(0,'memo','Missing SELFTEST table - default checks only','')," in do_meta_command()
27147 -1, &pStmt, 0); in do_meta_command()
27175 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg); in do_meta_command()
27183 oputf("%d: error-code-%d: %s\n", tno, rc, zErrMsg); in do_meta_command()
27210 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, in do_meta_command()
27211 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]); in do_meta_command()
27214 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, in do_meta_command()
27215 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]); in do_meta_command()
27234 if( z[0]=='-' ){ in do_meta_command()
27236 if( z[0]=='-' ) z++; in do_meta_command()
27240 if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0 in do_meta_command()
27241 || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0 in do_meta_command()
27250 showHelp(p->out, azArg[0]); in do_meta_command()
27255 eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n"); in do_meta_command()
27275 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); in do_meta_command()
27334 char *zRevText = /* Query for reversible to-blob-to-text check */ in do_meta_command()
27341 /* lower-case query is first run, producing upper-case query. */ in do_meta_command()
27358 lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0); in do_meta_command()
27364 if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC); in do_meta_command()
27369 lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0); in do_meta_command()
27431 oputf("%12.12s: %s\n","eqp", azBool[p->autoEQP&3]); in do_meta_command()
27433 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off"); in do_meta_command()
27434 oputf("%12.12s: %s\n","headers", azBool[p->showHeader!=0]); in do_meta_command()
27435 if( p->mode==MODE_Column in do_meta_command()
27436 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box) in do_meta_command()
27438 oputf("%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode", in do_meta_command()
27439 modeDescr[p->mode], p->cmOpts.iWrap, in do_meta_command()
27440 p->cmOpts.bWordWrap ? "on" : "off", in do_meta_command()
27441 p->cmOpts.bQuote ? "" : "no"); in do_meta_command()
27443 oputf("%12.12s: %s\n","mode", modeDescr[p->mode]); in do_meta_command()
27446 output_c_string(p->nullValue); in do_meta_command()
27449 strlen30(p->outfile) ? p->outfile : "stdout"); in do_meta_command()
27451 output_c_string(p->colSeparator); in do_meta_command()
27454 output_c_string(p->rowSeparator); in do_meta_command()
27456 switch( p->statsOn ){ in do_meta_command()
27464 for (i=0;i<p->nWidth;i++) { in do_meta_command()
27465 oputf("%d ", p->colWidth[i]); in do_meta_command()
27469 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : ""); in do_meta_command()
27475 p->statsOn = 2; in do_meta_command()
27477 p->statsOn = 3; in do_meta_command()
27479 p->statsOn = (u8)booleanValue(azArg[1]); in do_meta_command()
27482 display_stats(p->db, p, 0); in do_meta_command()
27500 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); in do_meta_command()
27503 return shellDatabaseError(p->db); in do_meta_command()
27510 eputz("Usage: .indexes ?LIKE-PATTERN?\n"); in do_meta_command()
27540 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0); in do_meta_command()
27543 if( rc ) return shellDatabaseError(p->db); in do_meta_command()
27546 ** as an array of nul-terminated strings in azResult[]. */ in do_meta_command()
27550 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); in do_meta_command()
27552 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); in do_meta_command()
27568 rc = shellDatabaseError(p->db); in do_meta_command()
27571 /* Pretty-print the contents of array azResult[] to the output */ in do_meta_command()
27582 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; in do_meta_command()
27586 oputf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j]:""); in do_meta_command()
27597 /* Begin redirecting output to the file "testcase-out.txt" */ in do_meta_command()
27600 p->out = output_file_open("testcase-out.txt", 0); in do_meta_command()
27601 if( p->out==0 ){ in do_meta_command()
27602 eputz("Error: cannot open 'testcase-out.txt'\n"); in do_meta_command()
27605 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]); in do_meta_command()
27607 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?"); in do_meta_command()
27615 const char *zCtrlName; /* Name of a test-control option */ in do_meta_command()
27617 int unSafe; /* Not valid unless --unsafe-testing */ in do_meta_command()
27632 {"optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK" }, in do_meta_command()
27645 int testctrl = -1; in do_meta_command()
27646 int iCtrl = -1; in do_meta_command()
27647 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */ in do_meta_command()
27655 /* The argument can optionally begin with "-" or "--" */ in do_meta_command()
27656 if( zCmd[0]=='-' && zCmd[1] ){ in do_meta_command()
27658 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; in do_meta_command()
27661 /* --help lists all test-controls */ in do_meta_command()
27663 oputz("Available test-controls:\n"); in do_meta_command()
27683 eputf("Error: ambiguous test-control: \"%s\"\n" in do_meta_command()
27684 "Use \".testctrl --help\" for help\n", zCmd); in do_meta_command()
27691 eputf("Error: unknown test-control: %s\n" in do_meta_command()
27692 "Use \".testctrl --help\" for help\n", zCmd); in do_meta_command()
27701 rc2 = sqlite3_test_control(testctrl, p->db, opt); in do_meta_command()
27732 sputf(stdout, "-- random seed: %d\n", ii); in do_meta_command()
27737 db = p->db; in do_meta_command()
27768 int opt = -1; in do_meta_command()
27783 rc2 = sqlite3_test_control(testctrl, p->db); in do_meta_command()
27789 rc2 = sqlite3_test_control(testctrl, p->db, in do_meta_command()
27799 rc2 = sqlite3_test_control(testctrl, p->db, &x); in do_meta_command()
27808 sqlite3_test_control(testctrl, p->out); in do_meta_command()
27823 sqlite3_test_control(testctrl, -id, &rc2); in do_meta_command()
27829 rc2 = sqlite3_test_control(testctrl, -id, &val); in do_meta_command()
27844 rc2 = sqlite3_test_control(testctrl, p->db, opt); in do_meta_command()
27863 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); in do_meta_command()
27886 if( z[0]=='-' ){ in do_meta_command()
27888 p->eTraceType = SHELL_TRACE_EXPANDED; in do_meta_command()
27892 p->eTraceType = SHELL_TRACE_NORMALIZED; in do_meta_command()
27896 p->eTraceType = SHELL_TRACE_PLAIN; in do_meta_command()
27916 output_file_close(p->traceOut); in do_meta_command()
27917 p->traceOut = output_file_open(z, 0); in do_meta_command()
27920 if( p->traceOut==0 ){ in do_meta_command()
27921 sqlite3_trace_v2(p->db, 0, 0, 0); in do_meta_command()
27924 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p); in do_meta_command()
27935 eputz("Usage: .unmodule [--allexcept] NAME ...\n"); in do_meta_command()
27941 if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++; in do_meta_command()
27943 if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){ in do_meta_command()
27945 sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0); in do_meta_command()
27948 sqlite3_create_module(p->db, azArg[ii], 0, 0); in do_meta_command()
27968 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], in do_meta_command()
27980 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]), in do_meta_command()
27983 eputf("User-Add failed: %d\n", rc); in do_meta_command()
27992 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]), in do_meta_command()
27995 eputf("User-Edit failed: %d\n", rc); in do_meta_command()
28004 rc = sqlite3_user_delete(p->db, azArg[2]); in do_meta_command()
28006 eputf("User-Delete failed: %d\n", rc); in do_meta_command()
28018 char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit"; in do_meta_command()
28019 oputf("SQLite %s %s\n" /*extra-version-info*/, in do_meta_command()
28027 oputf("clang-" CTIMEOPT_VAL(__clang_major__) "." in do_meta_command()
28031 oputf("msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz); in do_meta_command()
28033 oputf("gcc-" __VERSION__ " (%s)\n", zPtrSz); in do_meta_command()
28040 if( p->db ){ in do_meta_command()
28041 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); in do_meta_command()
28043 oputf("vfs.zName = \"%s\"\n", pVfs->zName); in do_meta_command()
28044 oputf("vfs.iVersion = %d\n", pVfs->iVersion); in do_meta_command()
28045 oputf("vfs.szOsFile = %d\n", pVfs->szOsFile); in do_meta_command()
28046 oputf("vfs.mxPathname = %d\n", pVfs->mxPathname); in do_meta_command()
28054 if( p->db ){ in do_meta_command()
28055 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); in do_meta_command()
28057 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ in do_meta_command()
28058 oputf("vfs.zName = \"%s\"%s\n", pVfs->zName, in do_meta_command()
28059 pVfs==pCurrent ? " <--- CURRENT" : ""); in do_meta_command()
28060 oputf("vfs.iVersion = %d\n", pVfs->iVersion); in do_meta_command()
28061 oputf("vfs.szOsFile = %d\n", pVfs->szOsFile); in do_meta_command()
28062 oputf("vfs.mxPathname = %d\n", pVfs->mxPathname); in do_meta_command()
28063 if( pVfs->pNext ){ in do_meta_command()
28064 oputz("-----------------------------------\n"); in do_meta_command()
28072 if( p->db ){ in do_meta_command()
28073 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); in do_meta_command()
28089 p->nWidth = nArg-1; in do_meta_command()
28090 p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2); in do_meta_command()
28091 if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory(); in do_meta_command()
28092 if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth]; in do_meta_command()
28094 p->colWidth[j-1] = (int)integerValue(azArg[j]); in do_meta_command()
28105 if( p->outCount ){ in do_meta_command()
28106 p->outCount--; in do_meta_command()
28107 if( p->outCount==0 ) output_reset(p); in do_meta_command()
28109 p->bSafeMode = p->bSafeModePersist; in do_meta_command()
28120 QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
28145 case '-': in quickscan()
28146 if( *zLine!='-' ) in quickscan()
28176 CONTINUE_PAREN_INCR(pst, -1); in quickscan()
28198 /* Swallow doubled end-delimiter.*/ in quickscan()
28218 ** than a semi-colon. The SQL Server style "go" command is understood
28242 ** ends in the middle of a string literal or C-style comment.
28263 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; in runOneSqlLine()
28273 zErrorTail = sqlite3_errmsg(p->db); in runOneSqlLine()
28298 sqlite3_changes64(p->db), sqlite3_total_changes64(p->db)); in runOneSqlLine()
28329 if(nZ>0 && '\r'==zBegin[nZ-1]){ in one_input_line()
28330 --nZ; in one_input_line()
28343 ** is interactive - the user is typing it it. Otherwise, input
28361 if( p->inputNesting==MAX_INPUT_NESTING ){ in process_input()
28364 " Check recursion.\n", MAX_INPUT_NESTING, p->lineno); in process_input()
28367 ++p->inputNesting; in process_input()
28368 p->lineno = 0; in process_input()
28370 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){ in process_input()
28371 fflush(p->out); in process_input()
28372 zLine = one_input_line(p->in, zLine, nSql>0); in process_input()
28375 if( p->in==0 && stdin_is_interactive ) oputz("\n"); in process_input()
28379 if( p->in!=0 ) break; in process_input()
28382 p->lineno++; in process_input()
28390 /* Just swallow single-line whitespace */ in process_input()
28409 /* No single-line dispositions remain; accumulate line(s). */ in process_input()
28412 /* Grow buffer by half-again increments when big. */ in process_input()
28421 memcpy(zSql, zLine+i, nLine+1-i); in process_input()
28422 startline = p->lineno; in process_input()
28423 nSql = nLine-i; in process_input()
28431 errCnt += runOneSqlLine(p, zSql, p->in, startline); in process_input()
28434 if( p->outCount ){ in process_input()
28436 p->outCount = 0; in process_input()
28440 p->bSafeMode = p->bSafeModePersist; in process_input()
28451 errCnt += runOneSqlLine(p, zSql, p->in, startline); in process_input()
28456 --p->inputNesting; in process_input()
28479 home_dir = pwent->pw_dir; in find_home_dir()
28485 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() in find_home_dir()
28530 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
28576 FILE *inSaved = p->in; in process_sqliterc()
28577 int savedLineno = p->lineno; in process_sqliterc()
28585 eputz("-- warning: cannot find home directory;" in process_sqliterc()
28593 p->in = fopen(sqliterc,"rb"); in process_sqliterc()
28594 if( p->in ){ in process_sqliterc()
28596 eputf("-- Loading resources from %s\n", sqliterc); in process_sqliterc()
28599 fclose(p->in); in process_sqliterc()
28604 p->in = inSaved; in process_sqliterc()
28605 p->lineno = savedLineno; in process_sqliterc()
28613 " -- treat no subsequent arguments as options\n"
28615 " -A ARGS... run \".archive ARGS\" and exit\n"
28617 " -append append the database to the end of the file\n"
28618 " -ascii set output mode to 'ascii'\n"
28619 " -bail stop after hitting an error\n"
28620 " -batch force batch I/O\n"
28621 " -box set output mode to 'box'\n"
28622 " -column set output mode to 'column'\n"
28623 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
28624 " -csv set output mode to 'csv'\n"
28626 " -deserialize open the database using sqlite3_deserialize()\n"
28628 " -echo print inputs before execution\n"
28629 " -init FILENAME read/process named file\n"
28630 " -[no]header turn headers on or off\n"
28632 " -heap SIZE Size of heap for memsys3 or memsys5\n"
28634 " -help show this message\n"
28635 " -html set output mode to HTML\n"
28636 " -interactive force interactive I/O\n"
28637 " -json set output mode to 'json'\n"
28638 " -line set output mode to 'line'\n"
28639 " -list set output mode to 'list'\n"
28640 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
28641 " -markdown set output mode to 'markdown'\n"
28643 " -maxsize N maximum size for a --deserialize database\n"
28645 " -memtrace trace all memory allocations and deallocations\n"
28646 " -mmap N default mmap size set to N\n"
28648 " -multiplex enable the multiplexor VFS\n"
28650 " -newline SEP set output row separator. Default: '\\n'\n"
28651 " -nofollow refuse to open symbolic links to database files\n"
28652 " -nonce STRING set the safe-mode escape nonce\n"
28653 " -no-rowid-in-view Disable rowid-in-view using sqlite3_config()\n"
28654 " -nullvalue TEXT set text string for NULL values. Default ''\n"
28655 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
28656 " -pcachetrace trace all page cache operations\n"
28657 " -quote set output mode to 'quote'\n"
28658 " -readonly open the database read-only\n"
28659 " -safe enable safe-mode\n"
28660 " -separator SEP set output column separator. Default: '|'\n"
28662 " -sorterref SIZE sorter references threshold size\n"
28664 " -stats print memory stats before each finalize\n"
28665 " -table set output mode to 'table'\n"
28666 " -tabs set output mode to 'tabs'\n"
28667 " -unsafe-testing allow unsafe commands and modes for testing\n"
28668 " -version show SQLite version\n"
28669 " -vfs NAME use NAME as the default VFS\n"
28671 " -vfstrace enable tracing of all VFS calls\n"
28674 " -zip open the file as a ZIP Archive\n"
28684 eputz("Use the -help option for additional information\n"); in usage()
28694 if( sqlite3_config(-1)==SQLITE_MISUSE ){ in verify_uninitialized()
28705 data->normalMode = data->cMode = data->mode = MODE_List; in main_init()
28706 data->autoExplain = 1; in main_init()
28707 data->pAuxDb = &data->aAuxDb[0]; in main_init()
28708 memcpy(data->colSeparator,SEP_Column, 2); in main_init()
28709 memcpy(data->rowSeparator,SEP_Row, 2); in main_init()
28710 data->showHeader = 0; in main_init()
28711 data->shellFlgs = SHFLG_Lookaside; in main_init()
28747 ** Get the argument to an --option. Throw an error and die if no argument
28752 eputf("%s: Error: missing argument to %s\n", argv[0], argv[argc-1]); in cmdline_option_value()
28799 const char *zVfs = 0; /* Value of -vfs command-line option */
28857 /* On Windows, we must translate command-line arguments into UTF-8.
28889 ** of a C-function that will provide the name of the database file. Use
28890 ** this compile-time option to embed this shell program in larger
28893 SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
28898 /* Do an initial pass through the command-line argument to locate
28909 if( z[0]!='-' || i>nOptsEnd ){
28910 if( data.aAuxDb->zDbFilename==0 ){
28911 data.aAuxDb->zDbFilename = z;
28913 /* Excess arguments are interpreted as SQL (or dot-commands) and
28919 azCmd[nCmd-1] = z;
28923 if( z[1]=='-' ) z++;
28924 if( cli_strcmp(z, "-")==0 ){
28927 }else if( cli_strcmp(z,"-separator")==0
28928 || cli_strcmp(z,"-nullvalue")==0
28929 || cli_strcmp(z,"-newline")==0
28930 || cli_strcmp(z,"-cmd")==0
28933 }else if( cli_strcmp(z,"-init")==0 ){
28935 }else if( cli_strcmp(z,"-interactive")==0 ){
28940 }else if( cli_strcmp(z,"-batch")==0 ){
28946 }else if( cli_strcmp(z,"-utf8")==0 ){
28947 }else if( cli_strcmp(z,"-no-utf8")==0 ){
28948 }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
28952 }else if( cli_strcmp(z,"-heap")==0 ){
28965 }else if( cli_strcmp(z,"-pagecache")==0 ){
28978 }else if( cli_strcmp(z,"-lookaside")==0 ){
28987 }else if( cli_strcmp(z,"-threadsafe")==0 ){
28997 }else if( cli_strcmp(z,"-vfstrace")==0 ){
29008 }else if( cli_strcmp(z,"-multiplex")==0 ){
29012 }else if( cli_strcmp(z,"-mmap")==0 ){
29017 }else if( cli_strcmp(z,"-sorterref")==0 ){
29022 }else if( cli_strcmp(z,"-vfs")==0 ){
29025 }else if( cli_strcmp(z,"-zip")==0 ){
29028 }else if( cli_strcmp(z,"-append")==0 ){
29031 }else if( cli_strcmp(z,"-deserialize")==0 ){
29033 }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
29036 }else if( cli_strcmp(z,"-readonly")==0 ){
29038 }else if( cli_strcmp(z,"-nofollow")==0 ){
29041 }else if( cli_strncmp(z, "-A",2)==0 ){
29042 /* All remaining command-line arguments are passed to the ".archive"
29046 }else if( cli_strcmp(z, "-memtrace")==0 ){
29048 }else if( cli_strcmp(z, "-pcachetrace")==0 ){
29050 }else if( cli_strcmp(z,"-bail")==0 ){
29052 }else if( cli_strcmp(z,"-nonce")==0 ){
29055 }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
29057 }else if( cli_strcmp(z,"-safe")==0 ){
29058 /* no-op - catch this on the second pass */
29069 ** of a C-function that will perform initialization actions on SQLite that
29070 ** occur just before or after sqlite3_initialize(). Use this compile-time
29077 ** to call sqlite3_initialize() and process any command line -vfs option. */
29091 if( data.pAuxDb->zDbFilename==0 ){
29093 data.pAuxDb->zDbFilename = ":memory:";
29108 ** to the sqlite command-line tool.
29110 if( access(data.pAuxDb->zDbFilename, 0)==0 ){
29114 /* Process the initialization file if there is one. If no -init option
29120 /* Make a second pass through the command-line argument and set
29122 ** file is processed so that the command-line arguments will override
29127 if( z[0]!='-' || i>=nOptsEnd ) continue;
29128 if( z[1]=='-' ){ z++; }
29129 if( cli_strcmp(z,"-init")==0 ){
29131 }else if( cli_strcmp(z,"-html")==0 ){
29133 }else if( cli_strcmp(z,"-list")==0 ){
29135 }else if( cli_strcmp(z,"-quote")==0 ){
29139 }else if( cli_strcmp(z,"-line")==0 ){
29141 }else if( cli_strcmp(z,"-column")==0 ){
29143 }else if( cli_strcmp(z,"-json")==0 ){
29145 }else if( cli_strcmp(z,"-markdown")==0 ){
29147 }else if( cli_strcmp(z,"-table")==0 ){
29149 }else if( cli_strcmp(z,"-box")==0 ){
29151 }else if( cli_strcmp(z,"-csv")==0 ){
29155 }else if( cli_strcmp(z,"-zip")==0 ){
29158 }else if( cli_strcmp(z,"-append")==0 ){
29161 }else if( cli_strcmp(z,"-deserialize")==0 ){
29163 }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
29166 }else if( cli_strcmp(z,"-readonly")==0 ){
29168 }else if( cli_strcmp(z,"-nofollow")==0 ){
29170 }else if( cli_strcmp(z,"-ascii")==0 ){
29174 }else if( cli_strcmp(z,"-tabs")==0 ){
29178 }else if( cli_strcmp(z,"-separator")==0 ){
29181 }else if( cli_strcmp(z,"-newline")==0 ){
29184 }else if( cli_strcmp(z,"-nullvalue")==0 ){
29187 }else if( cli_strcmp(z,"-header")==0 ){
29190 }else if( cli_strcmp(z,"-noheader")==0 ){
29193 }else if( cli_strcmp(z,"-echo")==0 ){
29195 }else if( cli_strcmp(z,"-eqp")==0 ){
29197 }else if( cli_strcmp(z,"-eqpfull")==0 ){
29199 }else if( cli_strcmp(z,"-stats")==0 ){
29201 }else if( cli_strcmp(z,"-scanstats")==0 ){
29203 }else if( cli_strcmp(z,"-backslash")==0 ){
29204 /* Undocumented command-line option: -backslash
29205 ** Causes C-style backslash escapes to be evaluated in SQL statements
29210 }else if( cli_strcmp(z,"-bail")==0 ){
29211 /* No-op. The bail_on_error flag should already be set. */
29212 }else if( cli_strcmp(z,"-version")==0 ){
29213 oputf("%s %s (%d-bit)\n", sqlite3_libversion(), sqlite3_sourceid(),
29216 }else if( cli_strcmp(z,"-interactive")==0 ){
29218 }else if( cli_strcmp(z,"-batch")==0 ){
29220 }else if( cli_strcmp(z,"-utf8")==0 ){
29222 }else if( cli_strcmp(z,"-no-utf8")==0 ){
29224 }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
29226 }else if( cli_strcmp(z,"-heap")==0 ){
29228 }else if( cli_strcmp(z,"-pagecache")==0 ){
29230 }else if( cli_strcmp(z,"-lookaside")==0 ){
29232 }else if( cli_strcmp(z,"-threadsafe")==0 ){
29234 }else if( cli_strcmp(z,"-nonce")==0 ){
29236 }else if( cli_strcmp(z,"-mmap")==0 ){
29238 }else if( cli_strcmp(z,"-memtrace")==0 ){
29240 }else if( cli_strcmp(z,"-pcachetrace")==0 ){
29243 }else if( cli_strcmp(z,"-sorterref")==0 ){
29246 }else if( cli_strcmp(z,"-vfs")==0 ){
29249 }else if( cli_strcmp(z,"-vfstrace")==0 ){
29253 }else if( cli_strcmp(z,"-multiplex")==0 ){
29256 }else if( cli_strcmp(z,"-help")==0 ){
29258 }else if( cli_strcmp(z,"-cmd")==0 ){
29259 /* Run commands that follow -cmd first and separately from commands
29260 ** that simply appear on the command-line. This seems goofy. It would
29263 if( i==argc-1 ) break;
29280 }else if( cli_strncmp(z, "-A", 2)==0 ){
29282 eputf("Error: cannot mix regular SQL or dot-commands"
29289 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
29291 arDotCommand(&data, 1, argv+i, argc-i);
29296 }else if( cli_strcmp(z,"-safe")==0 ){
29298 }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
29302 eputz("Use -help for a list of options.\n");
29309 /* Run all arguments that do not begin with '-' as if they were separate
29310 ** command-line inputs, except for the argToSkip argument which contains
29344 # define SHELL_CIO_CHAR_SET (stdout_is_console? " (UTF-16 console I/O)" : "")
29348 oputf("SQLite version %s %.19s%s\n" /*extra-version-info*/
29353 printBold("transient in-memory database");
29390 session_close_all(&data, -1);
29416 (unsigned int)(sqlite3_memory_used()-mem_main_enter));
29478 ** Completely wipes out the contents of the currently-opened database
29493 ** on success, non-0 on error. This function returns 0 on success,
29494 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
29495 ** code from the callback. Note that this is not thread-friendly: it
29510 rc = pFile->pMethods->xFileSize(pFile, &nSize);
29522 rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);