sqlite
[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.
Brought by drakestapleton
| 1 | /* |
| 2 | ** 2001 September 15 |
| 3 | ** |
| 4 | ** The author disclaims copyright to this source code. In place of |
| 5 | ** a legal notice, here is a blessing: |
| 6 | ** |
| 7 | ** May you do good and not evil. |
| 8 | ** May you find forgiveness for yourself and forgive others. |
| 9 | ** May you share freely, never taking more than you give. |
| 10 | ** |
| 11 | ************************************************************************* |
| 12 | ** This file contains code to implement the "sqlite3" command line |
| 13 | ** utility for accessing SQLite databases. |
| 14 | */ |
| 15 | #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS) |
| 16 | /* This needs to come before any includes for MSVC compiler */ |
| 17 | #define _CRT_SECURE_NO_WARNINGS |
| 18 | #endif |
| 19 | typedef unsigned int u32; |
| 20 | typedef unsigned short int u16; |
| 21 | |
| 22 | /* |
| 23 | ** Limit input nesting via .read or any other input redirect. |
| 24 | ** It's not too expensive, so a generous allowance can be made. |
| 25 | */ |
| 26 | #define MAX_INPUT_NESTING 25 |
| 27 | |
| 28 | /* |
| 29 | ** Used to prevent warnings about unused parameters |
| 30 | */ |
| 31 | #define UNUSED_PARAMETER(x) (void)(x) |
| 32 | |
| 33 | /* |
| 34 | ** Number of elements in an array |
| 35 | */ |
| 36 | #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0])) |
| 37 | |
| 38 | /* |
| 39 | ** Optionally #include a user-defined header, whereby compilation options |
| 40 | ** may be set prior to where they take effect, but after platform setup. |
| 41 | ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include |
| 42 | ** file. Note that this macro has a like effect on sqlite3.c compilation. |
| 43 | */ |
| 44 | # define SHELL_STRINGIFY_(f) #f |
| 45 | # define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f) |
| 46 | #ifdef SQLITE_CUSTOM_INCLUDE |
| 47 | # include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE) |
| 48 | #endif |
| 49 | |
| 50 | /* |
| 51 | ** If SQLITE_SHELL_FIDDLE is defined then the shell is modified |
| 52 | ** somewhat for use as a WASM module in a web browser. This flag |
| 53 | ** should only be used when building the "fiddle" web application, as |
| 54 | ** the browser-mode build has much different user input requirements |
| 55 | ** and this build mode rewires the user input subsystem to account for |
| 56 | ** that. |
| 57 | */ |
| 58 | #if defined(SQLITE_SHELL_FIDDLE) |
| 59 | # undef SQLITE_OMIT_LOAD_EXTENSION |
| 60 | # define SQLITE_OMIT_LOAD_EXTENSION 1 |
| 61 | #endif |
| 62 | |
| 63 | /* |
| 64 | ** Warning pragmas copied from msvc.h in the core. |
| 65 | */ |
| 66 | #if defined(_MSC_VER) |
| 67 | #pragma warning(disable : 4054) |
| 68 | #pragma warning(disable : 4055) |
| 69 | #pragma warning(disable : 4100) |
| 70 | #pragma warning(disable : 4127) |
| 71 | #pragma warning(disable : 4130) |
| 72 | #pragma warning(disable : 4152) |
| 73 | #pragma warning(disable : 4189) |
| 74 | #pragma warning(disable : 4206) |
| 75 | #pragma warning(disable : 4210) |
| 76 | #pragma warning(disable : 4232) |
| 77 | #pragma warning(disable : 4244) |
| 78 | #pragma warning(disable : 4305) |
| 79 | #pragma warning(disable : 4306) |
| 80 | #pragma warning(disable : 4702) |
| 81 | #pragma warning(disable : 4706) |
| 82 | #endif /* defined(_MSC_VER) */ |
| 83 | |
| 84 | /* |
| 85 | ** No support for loadable extensions in VxWorks. |
| 86 | */ |
| 87 | #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION |
| 88 | # define SQLITE_OMIT_LOAD_EXTENSION 1 |
| 89 | #endif |
| 90 | |
| 91 | /* |
| 92 | ** Enable large-file support for fopen() and friends on unix. |
| 93 | */ |
| 94 | #ifndef SQLITE_DISABLE_LFS |
| 95 | # define _LARGE_FILE 1 |
| 96 | # ifndef _FILE_OFFSET_BITS |
| 97 | # define _FILE_OFFSET_BITS 64 |
| 98 | # endif |
| 99 | # define _LARGEFILE_SOURCE 1 |
| 100 | #endif |
| 101 | |
| 102 | #if defined(SQLITE_SHELL_FIDDLE) && !defined(_POSIX_SOURCE) |
| 103 | /* |
| 104 | ** emcc requires _POSIX_SOURCE (or one of several similar defines) |
| 105 | ** to expose strdup(). |
| 106 | */ |
| 107 | # define _POSIX_SOURCE |
| 108 | #endif |
| 109 | |
| 110 | #include <stdlib.h> |
| 111 | #include <string.h> |
| 112 | #include <stdio.h> |
| 113 | #include <assert.h> |
| 114 | #include <math.h> |
| 115 | #include <stdint.h> |
| 116 | #include <time.h> |
| 117 | #include "sqlite3.h" |
| 118 | typedef sqlite3_int64 i64; |
| 119 | typedef sqlite3_uint64 u64; |
| 120 | typedef unsigned char u8; |
| 121 | #include <ctype.h> |
| 122 | #include <stdarg.h> |
| 123 | #ifndef _WIN32 |
| 124 | # include <sys/time.h> |
| 125 | # include <sys/ioctl.h> |
| 126 | #endif |
| 127 | |
| 128 | #if !defined(_WIN32) && !defined(WIN32) |
| 129 | # include <signal.h> |
| 130 | # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI) |
| 131 | # include <pwd.h> |
| 132 | # endif |
| 133 | #endif |
| 134 | #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__) |
| 135 | # include <unistd.h> |
| 136 | # include <dirent.h> |
| 137 | # define GETPID getpid |
| 138 | # if defined(__MINGW32__) |
| 139 | # define DIRENT dirent |
| 140 | # ifndef S_ISLNK |
| 141 | # define S_ISLNK(mode) (0) |
| 142 | # endif |
| 143 | # endif |
| 144 | #else |
| 145 | # define GETPID (int)GetCurrentProcessId |
| 146 | #endif |
| 147 | #include <sys/types.h> |
| 148 | #include <sys/stat.h> |
| 149 | |
| 150 | #if HAVE_READLINE |
| 151 | # include <readline/readline.h> |
| 152 | # include <readline/history.h> |
| 153 | #elif HAVE_EDITLINE |
| 154 | /* If both HAVE_READLINE and HAVE_EDITLINE are true, assume that this |
| 155 | ** libedit installation does not have its own headers, instead using |
| 156 | ** those from libreadline. */ |
| 157 | # include <editline/readline.h> |
| 158 | #endif |
| 159 | |
| 160 | #if HAVE_EDITLINE || HAVE_READLINE |
| 161 | |
| 162 | # define shell_add_history(X) add_history(X) |
| 163 | # define shell_read_history(X) read_history(X) |
| 164 | # define shell_write_history(X) write_history(X) |
| 165 | # define shell_stifle_history(X) stifle_history(X) |
| 166 | # define shell_readline(X) readline(X) |
| 167 | # define SHELL_CMDLINE_EDIT_AVAILABLE 1 /* command-line editing available */ |
| 168 | |
| 169 | #elif HAVE_LINENOISE |
| 170 | |
| 171 | # include "linenoise.h" |
| 172 | # define shell_add_history(X) linenoiseHistoryAdd(X) |
| 173 | # define shell_read_history(X) linenoiseHistoryLoad(X) |
| 174 | # define shell_write_history(X) linenoiseHistorySave(X) |
| 175 | # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X) |
| 176 | # define shell_readline(X) linenoise(X) |
| 177 | # define SHELL_CMDLINE_EDIT_AVAILABLE 1 /* command-line editing available */ |
| 178 | |
| 179 | #else |
| 180 | |
| 181 | # define shell_read_history(X) |
| 182 | # define shell_write_history(X) |
| 183 | # define shell_stifle_history(X) |
| 184 | # define SHELL_CMDLINE_EDIT_AVAILABLE 0 /* command-line editing not available */ |
| 185 | #endif |
| 186 | |
| 187 | /* |
| 188 | ** Global variable shellCmdLineEdit determines whether or not command-line |
| 189 | ** editing is enabled. It defaults to 1 if the CLI is linked against a |
| 190 | ** command-line editing library (linenoise, readline, or editline) and |
| 191 | ** to 0 if no command-line editing library is available. The |
| 192 | ** "--cmdline-edit off" command-line option will change this value to 0. |
| 193 | */ |
| 194 | static int shellCmdLineEdit = SHELL_CMDLINE_EDIT_AVAILABLE; |
| 195 | |
| 196 | #ifndef deliberate_fall_through |
| 197 | /* Quiet some compilers about some of our intentional code. */ |
| 198 | # if defined(GCC_VERSION) && GCC_VERSION>=7000000 |
| 199 | # define deliberate_fall_through __attribute__((fallthrough)); |
| 200 | # else |
| 201 | # define deliberate_fall_through |
| 202 | # endif |
| 203 | #endif |
| 204 | |
| 205 | #if defined(_WIN32) || defined(WIN32) |
| 206 | # include <io.h> |
| 207 | # include <fcntl.h> |
| 208 | # define isatty(h) _isatty(h) |
| 209 | # ifndef access |
| 210 | # define access(f,m) _access((f),(m)) |
| 211 | # endif |
| 212 | # ifndef unlink |
| 213 | # define unlink _unlink |
| 214 | # endif |
| 215 | # ifndef strdup |
| 216 | # define strdup _strdup |
| 217 | # endif |
| 218 | # undef pclose |
| 219 | # define pclose _pclose |
| 220 | #else |
| 221 | /* Make sure isatty() has a prototype. */ |
| 222 | extern int isatty(int); |
| 223 | |
| 224 | # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI) |
| 225 | /* popen and pclose are not C89 functions and so are |
| 226 | ** sometimes omitted from the <stdio.h> header */ |
| 227 | extern FILE *popen(const char*,const char*); |
| 228 | extern int pclose(FILE*); |
| 229 | # else |
| 230 | # define SQLITE_OMIT_POPEN 1 |
| 231 | # endif |
| 232 | #endif |
| 233 | |
| 234 | #if defined(_WIN32_WCE) |
| 235 | /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty() |
| 236 | * thus we always assume that we have a console. That can be |
| 237 | * overridden with the -batch command line option. |
| 238 | */ |
| 239 | #define isatty(x) 1 |
| 240 | #endif |
| 241 | |
| 242 | /* ctype macros that work with signed characters */ |
| 243 | #define IsSpace(X) isspace((unsigned char)X) |
| 244 | #define IsDigit(X) isdigit((unsigned char)X) |
| 245 | #define ToLower(X) (char)tolower((unsigned char)X) |
| 246 | #define IsAlnum(X) isalnum((unsigned char)X) |
| 247 | #define IsAlpha(X) isalpha((unsigned char)X) |
| 248 | |
| 249 | #if defined(_WIN32) || defined(WIN32) |
| 250 | #undef WIN32_LEAN_AND_MEAN |
| 251 | #define WIN32_LEAN_AND_MEAN |
| 252 | #include <windows.h> |
| 253 | |
| 254 | /* string conversion routines only needed on Win32 */ |
| 255 | extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR); |
| 256 | extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText); |
| 257 | #endif |
| 258 | |
| 259 | INCLUDE ../ext/misc/sqlite3_stdio.h |
| 260 | INCLUDE ../ext/misc/sqlite3_stdio.c |
| 261 | INCLUDE ../ext/qrf/qrf.h |
| 262 | INCLUDE ../ext/qrf/qrf.c |
| 263 | |
| 264 | /* Use console I/O package as a direct INCLUDE. */ |
| 265 | #define SQLITE_INTERNAL_LINKAGE static |
| 266 | |
| 267 | #ifdef SQLITE_SHELL_FIDDLE |
| 268 | /* Deselect most features from the console I/O package for Fiddle. */ |
| 269 | # define SQLITE_CIO_NO_REDIRECT |
| 270 | # define SQLITE_CIO_NO_CLASSIFY |
| 271 | # define SQLITE_CIO_NO_TRANSLATE |
| 272 | # define SQLITE_CIO_NO_SETMODE |
| 273 | # define SQLITE_CIO_NO_FLUSH |
| 274 | #endif |
| 275 | |
| 276 | /* |
| 277 | ** The source code for several run-time loadable extensions is inserted |
| 278 | ** below by the ../tool/mkshellc.tcl script. Before processing that included |
| 279 | ** code, we need to override some macros to make the included program code |
| 280 | ** work here in the middle of this regular program. |
| 281 | */ |
| 282 | #define SQLITE_EXTENSION_INIT1 |
| 283 | #define SQLITE_EXTENSION_INIT2(X) (void)(X) |
| 284 | |
| 285 | INCLUDE ../ext/misc/windirent.h |
| 286 | INCLUDE ../ext/misc/memtrace.c |
| 287 | INCLUDE ../ext/misc/pcachetrace.c |
| 288 | INCLUDE ../ext/misc/shathree.c |
| 289 | INCLUDE ../ext/misc/sha1.c |
| 290 | INCLUDE ../ext/misc/uint.c |
| 291 | INCLUDE ../ext/misc/decimal.c |
| 292 | INCLUDE ../ext/misc/base64.c |
| 293 | INCLUDE ../ext/misc/base85.c |
| 294 | INCLUDE ../ext/misc/optname.c |
| 295 | INCLUDE ../ext/misc/ieee754.c |
| 296 | INCLUDE ../ext/misc/series.c |
| 297 | INCLUDE ../ext/misc/regexp.c |
| 298 | #ifndef SQLITE_SHELL_FIDDLE |
| 299 | INCLUDE ../ext/misc/fileio.c |
| 300 | INCLUDE ../ext/misc/completion.c |
| 301 | INCLUDE ../ext/misc/appendvfs.c |
| 302 | #endif |
| 303 | #ifdef SQLITE_HAVE_ZLIB |
| 304 | INCLUDE ../ext/misc/zipfile.c |
| 305 | INCLUDE ../ext/misc/sqlar.c |
| 306 | #endif |
| 307 | #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION) |
| 308 | INCLUDE ../ext/expert/sqlite3expert.h |
| 309 | INCLUDE ../ext/expert/sqlite3expert.c |
| 310 | #endif |
| 311 | INCLUDE ../ext/intck/sqlite3intck.h |
| 312 | INCLUDE ../ext/intck/sqlite3intck.c |
| 313 | INCLUDE ../ext/misc/stmtrand.c |
| 314 | INCLUDE ../ext/misc/vfstrace.c |
| 315 | INCLUDE ../ext/misc/diskused.c |
| 316 | INCLUDE ../ext/misc/strdup.c |
| 317 | |
| 318 | #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) |
| 319 | #define SQLITE_SHELL_HAVE_RECOVER 1 |
| 320 | #else |
| 321 | #define SQLITE_SHELL_HAVE_RECOVER 0 |
| 322 | #endif |
| 323 | #if SQLITE_SHELL_HAVE_RECOVER |
| 324 | INCLUDE ../ext/recover/sqlite3recover.h |
| 325 | # ifndef SQLITE_HAVE_SQLITE3R |
| 326 | INCLUDE ../ext/recover/dbdata.c |
| 327 | INCLUDE ../ext/recover/sqlite3recover.c |
| 328 | # endif /* SQLITE_HAVE_SQLITE3R */ |
| 329 | #endif |
| 330 | #ifdef SQLITE_SHELL_EXTSRC |
| 331 | # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC) |
| 332 | #endif |
| 333 | |
| 334 | /* |
| 335 | ** Set the SQLITE_SHELL_EDITION to a YYYYMMDD date string and the |
| 336 | ** code will attempt to use defaults for the prompt and for the |
| 337 | ** initial output mode (and maybe other feature) that were for |
| 338 | ** the most recent version not newer than the specified date. |
| 339 | */ |
| 340 | #ifndef SQLITE_SHELL_EDITION |
| 341 | # define SQLITE_SHELL_EDITION 99991231 /* Use the latest if unspecified */ |
| 342 | #endif |
| 343 | |
| 344 | #if defined(SQLITE_ENABLE_SESSION) |
| 345 | /* |
| 346 | ** State information for a single open session |
| 347 | */ |
| 348 | typedef struct OpenSession OpenSession; |
| 349 | struct OpenSession { |
| 350 | char *zName; /* Symbolic name for this session */ |
| 351 | int nFilter; /* Number of xFilter rejection GLOB patterns */ |
| 352 | char **azFilter; /* Array of xFilter rejection GLOB patterns */ |
| 353 | sqlite3_session *p; /* The open session */ |
| 354 | }; |
| 355 | #endif |
| 356 | |
| 357 | #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION) |
| 358 | typedef struct ExpertInfo ExpertInfo; |
| 359 | struct ExpertInfo { |
| 360 | sqlite3expert *pExpert; |
| 361 | int bVerbose; |
| 362 | }; |
| 363 | #endif |
| 364 | |
| 365 | /* All the parameters that determine how to render query results. |
| 366 | */ |
| 367 | typedef struct Mode { |
| 368 | u8 autoExplain; /* Automatically turn on .explain mode */ |
| 369 | u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */ |
| 370 | u8 scanstatsOn; /* True to display scan stats before each finalize */ |
| 371 | u8 bAutoScreenWidth; /* Using the TTY to determine screen width */ |
| 372 | u8 mFlags; /* MFLG_ECHO, MFLG_CRLF, etc. */ |
| 373 | u8 eMode; /* One of the MODE_ values */ |
| 374 | char zIFmt[24]; /* Space to hold the --ifmt value */ |
| 375 | char zFpFmt[24]; /* Space to hold the --fpfmt value */ |
| 376 | sqlite3_qrf_spec spec; /* Spec to be passed into QRF */ |
| 377 | } Mode; |
| 378 | |
| 379 | /* Flags for Mode.mFlags */ |
| 380 | #define MFLG_ECHO 0x01 /* Echo inputs to output */ |
| 381 | #define MFLG_CRLF 0x02 /* Use CR/LF output line endings */ |
| 382 | #define MFLG_HDR 0x04 /* .header used to change headers on/off */ |
| 383 | |
| 384 | /* Bit values for ShellState.mStats |
| 385 | */ |
| 386 | #define CLISTAT_VMSTEP 0x01 /* Show vmsteps */ |
| 387 | #define CLISTAT_STMT 0x02 /* Stats for each statement */ |
| 388 | #define CLISTAT_MEM 0x04 /* Memory stats */ |
| 389 | #define CLISTAT_XSTMT 0x08 /* Extra statement stats */ |
| 390 | #define CLISTAT_XMEM 0x10 /* Extra memory stats */ |
| 391 | #define CLISTAT_IO 0x20 /* I/O stats (Linux only) */ |
| 392 | #define CLISTAT_ZIPVFS 0x40 /* ZIPVFS stats */ |
| 393 | #define CLISTAT_ON 0x17 /* Usual stats */ |
| 394 | #define CLISTAT_ALL 0x7f /* All stats */ |
| 395 | #define CLISTAT_RESET 0x80 /* Reset stat counters each time */ |
| 396 | |
| 397 | |
| 398 | /* A file that needs to be deleted, but only after a delay. |
| 399 | */ |
| 400 | typedef struct Unlink { |
| 401 | sqlite3_int64 tm; /* Unlink after this time */ |
| 402 | char *zFN; /* Name of file. Space from sqlite3_malloc() */ |
| 403 | } Unlink; |
| 404 | |
| 405 | /* |
| 406 | ** Maximum nested depth for .if statements. |
| 407 | */ |
| 408 | #define MX_IF 10 |
| 409 | |
| 410 | /* |
| 411 | ** State information about the database connection is contained in an |
| 412 | ** instance of the following structure. |
| 413 | */ |
| 414 | typedef struct ShellState ShellState; |
| 415 | struct ShellState { |
| 416 | sqlite3 *db; /* The database */ |
| 417 | u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */ |
| 418 | u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */ |
| 419 | u8 nEqpLevel; /* Depth of the EQP output graph */ |
| 420 | u8 eTraceType; /* SHELL_TRACE_* value for type of trace */ |
| 421 | u8 bSafeMode; /* True to prohibit unsafe operations */ |
| 422 | u8 bSafeModePersist; /* The long-term value of bSafeMode */ |
| 423 | u8 eRestoreState; /* See comments above doAutoDetectRestore() */ |
| 424 | u8 mStats; /* Which stats to display (if any) */ |
| 425 | unsigned mEqpLines; /* Mask of vertical lines in the EQP output graph */ |
| 426 | u8 nPopOutput; /* Revert .output settings when reaching zero */ |
| 427 | u8 nPopMode; /* Revert .mode settings when reaching zero */ |
| 428 | u8 enableTimer; /* Enable the timer. 2: permanently 1: only once */ |
| 429 | u8 bDelimitNonprint; /* Add \001...\002 around non-printing in prompts */ |
| 430 | u8 bTestParse; /* Undocumented --test-parse flags */ |
| 431 | int inputNesting; /* Track nesting level of .read and other redirects */ |
| 432 | double prevTimer; /* Last reported timer value */ |
| 433 | double tmProgress; /* --timeout option for .progress */ |
| 434 | i64 lineno; /* Line number of last line read from in */ |
| 435 | const char *zInFile; /* Name of the input file */ |
| 436 | int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */ |
| 437 | FILE *in; /* Read commands from this stream */ |
| 438 | FILE *out; /* Write results here */ |
| 439 | FILE *traceOut; /* Output for sqlite3_trace() */ |
| 440 | char *zEqpFile; /* Append .eqp output to this file, if not NULL */ |
| 441 | int nErr; /* Number of errors seen */ |
| 442 | int writableSchema; /* True if PRAGMA writable_schema=ON */ |
| 443 | int nCheck; /* Number of ".check" commands run */ |
| 444 | unsigned nProgress; /* Number of progress callbacks encountered */ |
| 445 | unsigned mxProgress; /* Maximum progress callbacks before failing */ |
| 446 | unsigned flgProgress; /* Flags for the progress callback */ |
| 447 | unsigned shellFlgs; /* Various flags */ |
| 448 | unsigned nTestRun; /* Number of test cases run */ |
| 449 | unsigned nTestErr; /* Number of test cases that failed */ |
| 450 | sqlite3_int64 szMax; /* --maxsize argument to .open */ |
| 451 | char *zInput; /* Simulated inputs */ |
| 452 | i64 nInputUsed; /* Simulated input read so far */ |
| 453 | char *zDestTable; /* Name of destination table when MODE_Insert */ |
| 454 | char *zTempFile; /* Temporary file that might need deleting */ |
| 455 | char *zErrPrefix; /* Alternative error message prefix */ |
| 456 | char *zAuthIgnore; /* Authorizer returns SQLITE_IGNORE for glob matches */ |
| 457 | char *zAuthDeny; /* Authorizer returns SQLITE_DENY for glob matches */ |
| 458 | sqlite3_stmt *pStmt; /* Current statement if any. */ |
| 459 | FILE *pLog; /* Write log output here */ |
| 460 | char *azPrompt[2]; /* Main and continuation prompt strings */ |
| 461 | Mode mode; /* Current display mode */ |
| 462 | Mode *aModeStack; /* Backups */ |
| 463 | unsigned nModeStack; /* Number of entries in aModeStack[] */ |
| 464 | unsigned nUnlink; /* Number of entries in aDelayUnlink[] */ |
| 465 | Unlink *aUnlink; /* Temp files to unlink after a delay */ |
| 466 | struct SavedMode { /* Ability to define custom mode configurations */ |
| 467 | char *zTag; /* Name of this saved mode */ |
| 468 | Mode mode; /* The saved mode */ |
| 469 | } *aSavedModes; /* Array of saved .mode settings. system malloc() */ |
| 470 | int nSavedModes; /* Number of saved .mode settings */ |
| 471 | struct AuxDb { /* Storage space for auxiliary database connections */ |
| 472 | sqlite3 *db; /* Connection pointer */ |
| 473 | const char *zDbFilename; /* Filename used to open the connection */ |
| 474 | char *zFreeOnClose; /* Free this memory allocation on close */ |
| 475 | int mFlgs; /* 0x001: Use zDbFilenaem for prompt */ |
| 476 | #if defined(SQLITE_ENABLE_SESSION) |
| 477 | int nSession; /* Number of active sessions */ |
| 478 | OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */ |
| 479 | #endif |
| 480 | } aAuxDb[5], /* Array of all database connections */ |
| 481 | *pAuxDb; /* Currently active database connection */ |
| 482 | char *zNonce; /* Nonce for temporary safe-mode escapes */ |
| 483 | #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION) |
| 484 | ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */ |
| 485 | #endif |
| 486 | struct DotCmdLine { /* Info about arguments to a dot-command */ |
| 487 | const char *zOrig; /* Original text of the dot-command */ |
| 488 | char *zCopy; /* Copy of zOrig, from malloc() */ |
| 489 | int nAlloc; /* Size of allocates for arrays below */ |
| 490 | int nArg; /* Number of argument slots actually used */ |
| 491 | char **azArg; /* Pointer to each argument, dequoted */ |
| 492 | int *aiOfst; /* Offset into zOrig[] for start of each arg */ |
| 493 | char *abQuot; /* True if the argment was originally quoted */ |
| 494 | } dot; |
| 495 | u32 mIf; /* Mask of false if conditions */ |
| 496 | u32 mElse; /* An else seen at this level */ |
| 497 | u32 mIfHasBeenTrue; /* True branch seen in if-elseif-elseif-else chain */ |
| 498 | int nIfLevel; /* Current number of if levels */ |
| 499 | int nIfAtStart; /* If level at start of current script */ |
| 500 | i64 lnIf[MX_IF]; /* Line number starting an if */ |
| 501 | i64 lnElse[MX_IF]; /* Line number of the else */ |
| 502 | #ifdef SQLITE_SHELL_FIDDLE |
| 503 | struct { |
| 504 | const char * zInput; /* Input string from wasm/JS proxy */ |
| 505 | const char * zPos; /* Cursor pos into zInput */ |
| 506 | const char * zDefaultDbName; /* Default name for db file */ |
| 507 | } wasm; |
| 508 | #endif |
| 509 | char zTestcase[30]; /* Name of current test case */ |
| 510 | char outfile[FILENAME_MAX]; /* Filename for *out */ |
| 511 | }; |
| 512 | |
| 513 | #ifdef SQLITE_SHELL_FIDDLE |
| 514 | static ShellState shellState; |
| 515 | #endif |
| 516 | |
| 517 | |
| 518 | /* Allowed values for ShellState.mode.autoEQP |
| 519 | */ |
| 520 | #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */ |
| 521 | #define AUTOEQP_on 1 /* Automatic EQP is on */ |
| 522 | #define AUTOEQP_trigger 2 /* On and also show plans for triggers */ |
| 523 | #define AUTOEQP_full 3 /* Show full EXPLAIN */ |
| 524 | |
| 525 | /* Allowed values for ShellState.openMode |
| 526 | */ |
| 527 | #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */ |
| 528 | #define SHELL_OPEN_NORMAL 1 /* Normal database file */ |
| 529 | #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */ |
| 530 | #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */ |
| 531 | #define SHELL_OPEN_DESERIALIZE 4 /* Open using sqlite3_deserialize() */ |
| 532 | #define SHELL_OPEN_HEXDB 5 /* Use "dbtotxt" output as data source */ |
| 533 | |
| 534 | /* Allowed values for ShellState.eTraceType |
| 535 | */ |
| 536 | #define SHELL_TRACE_PLAIN 0 /* Show input SQL text */ |
| 537 | #define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */ |
| 538 | #define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */ |
| 539 | |
| 540 | /* Bits in the ShellState.flgProgress variable */ |
| 541 | #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */ |
| 542 | #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progress |
| 543 | ** callback limit is reached, and for each |
| 544 | ** top-level SQL statement */ |
| 545 | #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */ |
| 546 | #define SHELL_PROGRESS_TMOUT 0x08 /* Stop after tmProgress seconds */ |
| 547 | |
| 548 | /* Names of values for Mode.spec.eEsc and Mode.spec.eText |
| 549 | */ |
| 550 | static const char *qrfEscNames[] = { "auto", "off", "ascii", "symbol" }; |
| 551 | static const char *qrfQuoteNames[] = |
| 552 | { "off","off","sql","csv","html","tcl","json","relaxed"}; |
| 553 | |
| 554 | /* |
| 555 | ** These are the allowed shellFlgs values |
| 556 | */ |
| 557 | #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */ |
| 558 | #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */ |
| 559 | #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */ |
| 560 | #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */ |
| 561 | #define SHFLG_NoErrLineno 0x00000010 /* Omit line numbers from error msgs */ |
| 562 | #define SHFLG_CountChanges 0x00000020 /* .changes setting */ |
| 563 | #define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */ |
| 564 | #define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */ |
| 565 | #define SHFLG_TestingMode 0x00000400 /* allow unsafe testing features */ |
| 566 | |
| 567 | /* |
| 568 | ** Macros for testing and setting shellFlgs |
| 569 | */ |
| 570 | #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0) |
| 571 | #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X)) |
| 572 | #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X))) |
| 573 | |
| 574 | /* |
| 575 | ** These are the allowed values for Mode.eMode. There is a lot of overlap |
| 576 | ** between these values and the Mode.spec.eStyle values, but they are not |
| 577 | ** one-to-one, and thus need to be tracked separately. |
| 578 | */ |
| 579 | #define MODE_Ascii 0 /* Use ASCII unit and record separators (0x1F/0x1E) */ |
| 580 | #define MODE_Box 1 /* Unicode box-drawing characters */ |
| 581 | #define MODE_C 2 /* Comma-separated list of C-strings */ |
| 582 | #define MODE_Column 3 /* One record per line in neat columns */ |
| 583 | #define MODE_Count 4 /* Output only a count of the rows of output */ |
| 584 | #define MODE_Csv 5 /* Quote strings, numbers are plain */ |
| 585 | #define MODE_Html 6 /* Generate an XHTML table */ |
| 586 | #define MODE_Insert 7 /* Generate SQL "insert" statements */ |
| 587 | #define MODE_JAtom 8 /* Comma-separated list of JSON atoms */ |
| 588 | #define MODE_JObject 9 /* One JSON object per row */ |
| 589 | #define MODE_Json 10 /* Output JSON */ |
| 590 | #define MODE_Line 11 /* One column per line. Blank line between records */ |
| 591 | #define MODE_List 12 /* One record per line with a separator */ |
| 592 | #define MODE_Markdown 13 /* Markdown formatting */ |
| 593 | #define MODE_Off 14 /* No query output shown */ |
| 594 | #define MODE_Psql 15 /* Similar to psql */ |
| 595 | #define MODE_QBox 16 /* BOX with SQL-quoted content */ |
| 596 | #define MODE_Quote 17 /* Quote values as for SQL */ |
| 597 | #define MODE_Split 18 /* Split-column mode */ |
| 598 | #define MODE_Table 19 /* MySQL-style table formatting */ |
| 599 | #define MODE_Tabs 20 /* Tab-separated values */ |
| 600 | #define MODE_Tcl 21 /* Space-separated list of TCL strings */ |
| 601 | #define MODE_Test 22 /* list -colsep , -quote on <-- for testing */ |
| 602 | #define MODE_Www 23 /* Full web-page output */ |
| 603 | |
| 604 | #define MODE_BUILTIN 23 /* Maximum built-in mode */ |
| 605 | #define MODE_BATCH 50 /* Default mode for batch processing */ |
| 606 | #define MODE_TTY 51 /* Default mode for interactive processing */ |
| 607 | #define MODE_USER 75 /* First user-defined mode */ |
| 608 | #define MODE_N_USER 25 /* Maximum number of user-defined modes */ |
| 609 | |
| 610 | /* |
| 611 | ** Information about built-in display modes |
| 612 | */ |
| 613 | typedef struct ModeInfo ModeInfo; |
| 614 | struct ModeInfo { |
| 615 | char zName[9]; /* Symbolic name of the mode */ |
| 616 | unsigned char eCSep; /* Column separator */ |
| 617 | unsigned char eRSep; /* Row separator */ |
| 618 | unsigned char eNull; /* Null representation */ |
| 619 | unsigned char eText; /* Default text encoding */ |
| 620 | unsigned char eHdr; /* Default header encoding. */ |
| 621 | unsigned char eBlob; /* Default blob encoding. */ |
| 622 | unsigned char bHdr; /* Show headers by default. 0: n/a, 1: no 2: yes */ |
| 623 | unsigned char eStyle; /* Underlying QRF style */ |
| 624 | unsigned char eCx; /* 0: other, 1: line, 2: columnar */ |
| 625 | unsigned char mFlg; /* Flags. 1=border-off 2=split-column 4=rowcount */ |
| 626 | }; |
| 627 | |
| 628 | /* String constants used by built-in modes */ |
| 629 | static const char *aModeStr[] = |
| 630 | /* 0 1 2 3 4 5 6 7 8 */ |
| 631 | { 0, "\n", "|", " ", ",", "\r\n", "\036", "\037", "\t", |
| 632 | "", "NULL", "null", "\"\"", ": ", }; |
| 633 | /* 9 10 11 12 13 */ |
| 634 | |
| 635 | static const ModeInfo aModeInfo[] = { |
| 636 | /* zName eCSep eRSep eNull eText eHdr eBlob bHdr eStyle eCx mFlg */ |
| 637 | { "ascii", 7, 6, 9, 1, 1, 0, 1, 12, 0, 0 }, |
| 638 | { "box", 0, 0, 9, 1, 1, 0, 3, 1, 2, 0 }, |
| 639 | { "c", 4, 1, 10, 5, 5, 4, 1, 12, 0, 0 }, |
| 640 | { "column", 0, 0, 9, 1, 1, 0, 3, 2, 2, 0 }, |
| 641 | { "count", 0, 0, 0, 0, 0, 0, 0, 3, 0, 0 }, |
| 642 | { "csv", 4, 5, 9, 3, 3, 0, 1, 12, 0, 0 }, |
| 643 | { "html", 0, 0, 11, 4, 4, 0, 3, 7, 0, 0 }, |
| 644 | { "insert", 0, 0, 10, 2, 2, 0, 1, 8, 0, 0 }, |
| 645 | { "jatom", 4, 1, 11, 6, 6, 0, 1, 12, 0, 0 }, |
| 646 | { "jobject", 0, 1, 11, 6, 6, 0, 0, 10, 0, 0 }, |
| 647 | { "json", 0, 0, 11, 6, 6, 0, 0, 9, 0, 0 }, |
| 648 | { "line", 13, 1, 9, 1, 1, 0, 0, 11, 1, 0 }, |
| 649 | { "list", 2, 1, 9, 1, 1, 0, 1, 12, 0, 0 }, |
| 650 | { "markdown", 0, 0, 9, 1, 1, 0, 3, 13, 2, 0 }, |
| 651 | { "off", 0, 0, 0, 0, 0, 0, 0, 14, 0, 0 }, |
| 652 | { "psql", 0, 0, 9, 1, 1, 0, 3, 19, 2, 5 }, |
| 653 | { "qbox", 0, 0, 10, 2, 1, 0, 3, 1, 2, 0 }, |
| 654 | { "quote", 4, 1, 10, 2, 2, 0, 1, 12, 0, 0 }, |
| 655 | { "split", 0, 0, 9, 1, 1, 0, 1, 2, 2, 2 }, |
| 656 | { "table", 0, 0, 9, 1, 1, 0, 3, 19, 2, 0 }, |
| 657 | { "tabs", 8, 1, 9, 3, 3, 0, 1, 12, 0, 0 }, |
| 658 | { "tcl", 3, 1, 12, 5, 5, 4, 1, 12, 0, 0 }, |
| 659 | { "www", 0, 0, 11, 4, 4, 0, 3, 7, 0, 0 } |
| 660 | }; /* | / / | / / | | / \____ |
| 661 | ** | / / | / / | | / | |
| 662 | ** Index into aModeStr[] | / / | | 2: columnar | |
| 663 | ** | / / | | 1: line | |
| 664 | ** | / / | | 0: other | |
| 665 | ** text encoding |/ | show | | | |
| 666 | ** v-------------------' | hdrs? | The QRF style | |
| 667 | ** 0: n/a blob | v-----' / |
| 668 | ** 1: plain v----------' 0: n/a _________/ |
| 669 | ** 2: sql 0: auto 1: no | |
| 670 | ** 3: csv 1: as-text 2: yes 1: border-off |
| 671 | ** 4: html 2: sql 3: always 2: split-column |
| 672 | ** 5: c 3: hex 4: rowcount |
| 673 | ** 6: json 4: c |
| 674 | ** 5: json |
| 675 | ** 6: size |
| 676 | ******************************************************************/ |
| 677 | |
| 678 | /* |
| 679 | ** Default values for the various QRF limits |
| 680 | */ |
| 681 | #ifndef DFLT_CHAR_LIMIT |
| 682 | # define DFLT_CHAR_LIMIT 300 |
| 683 | #endif |
| 684 | #ifndef DFLT_LINE_LIMIT |
| 685 | # define DFLT_LINE_LIMIT 5 |
| 686 | #endif |
| 687 | #ifndef DFLT_TITLE_LIMIT |
| 688 | # define DFLT_TITLE_LIMIT 20 |
| 689 | #endif |
| 690 | #ifndef DFLT_MULTI_INSERT |
| 691 | # define DFLT_MULTI_INSERT 3000 |
| 692 | #endif |
| 693 | |
| 694 | /* |
| 695 | ** If the following flag is set, then command execution stops |
| 696 | ** at an error if we are not interactive. |
| 697 | */ |
| 698 | static int bail_on_error = 0; |
| 699 | |
| 700 | /* |
| 701 | ** Treat stdin as an interactive input if the following variable |
| 702 | ** is true. Otherwise, assume stdin is connected to a file or pipe. |
| 703 | */ |
| 704 | static int stdin_is_interactive = 1; |
| 705 | |
| 706 | /* |
| 707 | ** Treat stdout like a TTY if true. |
| 708 | */ |
| 709 | static int stdout_is_console = 1; |
| 710 | |
| 711 | /* |
| 712 | ** Use this value as the width of the output device. Or, figure it |
| 713 | ** out at runtime if the value is negative. Or use a default width |
| 714 | ** if this value is zero. |
| 715 | */ |
| 716 | static int stdout_tty_width = -1; |
| 717 | |
| 718 | /* |
| 719 | ** The following is the open SQLite database. We make a pointer |
| 720 | ** to this database a static variable so that it can be accessed |
| 721 | ** by the SIGINT handler to interrupt database processing. |
| 722 | */ |
| 723 | static sqlite3 *globalDb = 0; |
| 724 | |
| 725 | /* |
| 726 | ** This is a global pointer to the main ShellState variable. This |
| 727 | ** exists so that the atexit() callback can access the ShellState |
| 728 | ** object to do some cleanup. |
| 729 | */ |
| 730 | static struct ShellState *globalShellState = 0; |
| 731 | |
| 732 | /* |
| 733 | ** True if an interrupt (Control-C) has been received. |
| 734 | */ |
| 735 | static volatile int seenInterrupt = 0; |
| 736 | |
| 737 | /* |
| 738 | ** This is the name of our program. It is set in main(), used |
| 739 | ** in a number of other places, mostly for error messages. |
| 740 | */ |
| 741 | static char *Argv0; |
| 742 | |
| 743 | /* |
| 744 | ** Write I/O traces to the following stream. |
| 745 | */ |
| 746 | #ifdef SQLITE_ENABLE_IOTRACE |
| 747 | static FILE *iotrace = 0; |
| 748 | #endif |
| 749 | |
| 750 | /* |
| 751 | ** Output routines that are able to redirect to memory rather than |
| 752 | ** doing actually I/O. |
| 753 | ** Works like. |
| 754 | ** -------------- |
| 755 | ** cli_printf(FILE*, const char*, ...); fprintf() |
| 756 | ** cli_write(FILE*, const char*, int); write() |
| 757 | ** cli_puts(const char*, FILE*); fputs() |
| 758 | ** cli_vprintf(FILE*, const char*, va_list); vfprintf() |
| 759 | ** |
| 760 | ** These are just thin wrappers with the following added semantics: |
| 761 | ** If the file-scope variable cli_output_capture is not NULL, and |
| 762 | ** if the FILE* argument is stdout or stderr, then rather than |
| 763 | ** writing to stdout/stdout, append the text to the cli_output_capture |
| 764 | ** variable. |
| 765 | ** |
| 766 | ** The cli_exit(int) routine works like exit() except that it |
| 767 | ** first dumps any capture output to stdout. |
| 768 | */ |
| 769 | static sqlite3_str *cli_output_capture = 0; |
| 770 | static int cli_printf(FILE *out, const char *zFormat, ...){ |
| 771 | va_list ap; |
| 772 | int rc; |
| 773 | va_start(ap,zFormat); |
| 774 | if( cli_output_capture && (out==stdout || out==stderr) ){ |
| 775 | sqlite3_str_vappendf(cli_output_capture, zFormat, ap); |
| 776 | rc = 1; |
| 777 | }else{ |
| 778 | rc = sqlite3_vfprintf(out, zFormat, ap); |
| 779 | } |
| 780 | va_end(ap); |
| 781 | return rc; |
| 782 | } |
| 783 | static int cli_write(FILE *out, const char *zData, int nData){ |
| 784 | if( cli_output_capture && (out==stdout || out==stderr) ){ |
| 785 | sqlite3_str_append(cli_output_capture, zData, nData); |
| 786 | #ifdef _WIN32 |
| 787 | }else if( out==stdout || out==stderr ){ |
| 788 | nData = sqlite3_fprintf(out, "%.*s", nData, zData); |
| 789 | #endif |
| 790 | }else{ |
| 791 | nData = (int)fwrite(zData, 1, nData, out); |
| 792 | } |
| 793 | return nData; |
| 794 | } |
| 795 | static int cli_puts(const char *zText, FILE *out){ |
| 796 | if( cli_output_capture && (out==stdout || out==stderr) ){ |
| 797 | sqlite3_str_appendall(cli_output_capture, zText); |
| 798 | return 1; |
| 799 | } |
| 800 | return sqlite3_fputs(zText, out); |
| 801 | } |
| 802 | #if 0 /* Not currently used - available if we need it later */ |
| 803 | static int cli_vprintf(FILE *out, const char *zFormat, va_list ap){ |
| 804 | if( cli_output_capture && (out==stdout || out==stderr) ){ |
| 805 | sqlite3_str_vappendf(cli_output_capture, zFormat, ap); |
| 806 | return 1; |
| 807 | }else{ |
| 808 | return sqlite3_vfprintf(out, zFormat, ap); |
| 809 | } |
| 810 | } |
| 811 | #endif |
| 812 | static void cli_exit(int rc){ |
| 813 | if( cli_output_capture ){ |
| 814 | char *z = sqlite3_str_finish(cli_output_capture); |
| 815 | sqlite3_fputs(z ? z : "", stdout); |
| 816 | fflush(stdout); |
| 817 | } |
| 818 | exit(rc); |
| 819 | } |
| 820 | |
| 821 | |
| 822 | #define eputz(z) cli_puts(z,stderr) |
| 823 | #define sputz(fp,z) cli_puts(z,fp) |
| 824 | |
| 825 | /* A version of strcmp() that works with NULL values */ |
| 826 | static int cli_strcmp(const char *a, const char *b){ |
| 827 | if( a==0 ) a = ""; |
| 828 | if( b==0 ) b = ""; |
| 829 | return strcmp(a,b); |
| 830 | } |
| 831 | static int cli_strncmp(const char *a, const char *b, size_t n){ |
| 832 | if( a==0 ) a = ""; |
| 833 | if( b==0 ) b = ""; |
| 834 | return strncmp(a,b,n); |
| 835 | } |
| 836 | |
| 837 | /* Return the current wall-clock time in microseconds since the |
| 838 | ** Unix epoch (1970-01-01T00:00:00Z) |
| 839 | */ |
| 840 | static sqlite3_int64 timeOfDay(void){ |
| 841 | #if defined(_WIN64) && _WIN32_WINNT >= _WIN32_WINNT_WIN8 |
| 842 | sqlite3_uint64 t; |
| 843 | FILETIME tm; |
| 844 | GetSystemTimePreciseAsFileTime(&tm); |
| 845 | t = ((u64)tm.dwHighDateTime<<32) | (u64)tm.dwLowDateTime; |
| 846 | t += 116444736000000000LL; |
| 847 | t /= 10; |
| 848 | return t; |
| 849 | #elif defined(_WIN32) |
| 850 | static sqlite3_vfs *clockVfs = 0; |
| 851 | sqlite3_int64 t; |
| 852 | if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0); |
| 853 | if( clockVfs==0 ) return 0; /* Never actually happens */ |
| 854 | if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){ |
| 855 | clockVfs->xCurrentTimeInt64(clockVfs, &t); |
| 856 | }else{ |
| 857 | double r; |
| 858 | clockVfs->xCurrentTime(clockVfs, &r); |
| 859 | t = (sqlite3_int64)(r*86400000.0); |
| 860 | } |
| 861 | return t*1000; |
| 862 | #else |
| 863 | struct timeval sNow; |
| 864 | (void)gettimeofday(&sNow,0); |
| 865 | return ((i64)sNow.tv_sec)*1000000 + sNow.tv_usec; |
| 866 | #endif |
| 867 | } |
| 868 | |
| 869 | /* Indicate out-of-memory and exit. */ |
| 870 | static void shell_out_of_memory(void){ |
| 871 | eputz("Error: out of memory\n"); |
| 872 | cli_exit(1); |
| 873 | } |
| 874 | |
| 875 | /* Check a pointer to see if it is NULL. If it is NULL, exit with an |
| 876 | ** out-of-memory error. |
| 877 | */ |
| 878 | static void shell_check_oom(const void *p){ |
| 879 | if( p==0 ) shell_out_of_memory(); |
| 880 | } |
| 881 | |
| 882 | /* |
| 883 | ** This routine works like printf in that its first argument is a |
| 884 | ** format string and subsequent arguments are values to be substituted |
| 885 | ** in place of % fields. The result of formatting this string |
| 886 | ** is written to iotrace. |
| 887 | */ |
| 888 | #ifdef SQLITE_ENABLE_IOTRACE |
| 889 | static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){ |
| 890 | va_list ap; |
| 891 | char *z; |
| 892 | if( iotrace==0 ) return; |
| 893 | va_start(ap, zFormat); |
| 894 | z = sqlite3_vmprintf(zFormat, ap); |
| 895 | va_end(ap); |
| 896 | cli_printf(iotrace, "%s", z); |
| 897 | sqlite3_free(z); |
| 898 | } |
| 899 | #endif |
| 900 | |
| 901 | /* |
| 902 | ** Compute a string length that is limited to what can be stored in |
| 903 | ** lower 30 bits of a 32-bit signed integer. |
| 904 | */ |
| 905 | static int strlen30(const char *z){ |
| 906 | size_t n; |
| 907 | if( z==0 ) return 0; |
| 908 | n = strlen(z); |
| 909 | return n>0x3fffffff ? 0x3fffffff : (int)n; |
| 910 | } |
| 911 | |
| 912 | /* |
| 913 | ** Return open FILE * if zFile exists, can be opened for read |
| 914 | ** and is an ordinary file or a character stream source. |
| 915 | ** Otherwise return 0. |
| 916 | */ |
| 917 | static FILE * openChrSource(const char *zFile){ |
| 918 | #if defined(_WIN32) || defined(WIN32) |
| 919 | struct __stat64 x = {0}; |
| 920 | # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0) |
| 921 | /* On Windows, open first, then check the stream nature. This order |
| 922 | ** is necessary because _stat() and sibs, when checking a named pipe, |
| 923 | ** effectively break the pipe as its supplier sees it. */ |
| 924 | FILE *rv = sqlite3_fopen(zFile, "rb"); |
| 925 | if( rv==0 ) return 0; |
| 926 | if( _fstat64(_fileno(rv), &x) != 0 |
| 927 | || !STAT_CHR_SRC(x.st_mode)){ |
| 928 | fclose(rv); |
| 929 | rv = 0; |
| 930 | } |
| 931 | return rv; |
| 932 | #else |
| 933 | struct stat x = {0}; |
| 934 | int rc = stat(zFile, &x); |
| 935 | # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode)) |
| 936 | if( rc!=0 ) return 0; |
| 937 | if( STAT_CHR_SRC(x.st_mode) ){ |
| 938 | return sqlite3_fopen(zFile, "rb"); |
| 939 | }else{ |
| 940 | return 0; |
| 941 | } |
| 942 | #endif |
| 943 | #undef STAT_CHR_SRC |
| 944 | } |
| 945 | |
| 946 | /* |
| 947 | ** Works like fgets except that if "in" really points to p->zInput |
| 948 | ** then text is read out of the p->zInput buffer. |
| 949 | */ |
| 950 | static char *shell_fgets(ShellState *p, char *zOut, int nOut, FILE *in){ |
| 951 | int i, j; |
| 952 | char *zIn; |
| 953 | if( p==0 || in!=(FILE*)&p->zInput ){ |
| 954 | return sqlite3_fgets(zOut, nOut, in); |
| 955 | } |
| 956 | zIn = p->zInput; |
| 957 | for(i=0, j=p->nInputUsed; i<nOut-1 && zIn[j] && zIn[j]!='\n'; i++, j++){} |
| 958 | if( zIn[j] ){ i++; } |
| 959 | memcpy(zOut, &zIn[p->nInputUsed], i); |
| 960 | zOut[i] = 0; |
| 961 | p->nInputUsed += i; |
| 962 | return i>0 ? zOut : 0; |
| 963 | } |
| 964 | |
| 965 | /* |
| 966 | ** This routine reads a line of text from FILE in, stores |
| 967 | ** the text in memory obtained from malloc() and returns a pointer |
| 968 | ** to the text. NULL is returned at end of file, or if malloc() |
| 969 | ** fails, or if the length of the line is longer than about a gigabyte. |
| 970 | ** |
| 971 | ** If zLine is not NULL then it is a malloced buffer returned from |
| 972 | ** a previous call to this routine that may be reused. |
| 973 | */ |
| 974 | static char *local_getline(ShellState *p, char *zLine, FILE *in){ |
| 975 | int nLine = zLine==0 ? 0 : 100; |
| 976 | int n = 0; |
| 977 | |
| 978 | while( seenInterrupt<2 ){ |
| 979 | if( n+100>nLine ){ |
| 980 | if( nLine>=1073741773 ){ |
| 981 | free(zLine); |
| 982 | return 0; |
| 983 | } |
| 984 | nLine = nLine*2 + 100; |
| 985 | zLine = realloc(zLine, nLine); |
| 986 | shell_check_oom(zLine); |
| 987 | } |
| 988 | if( shell_fgets(p, &zLine[n], nLine - n, in)==0 ){ |
| 989 | if( n==0 ){ |
| 990 | free(zLine); |
| 991 | return 0; |
| 992 | } |
| 993 | zLine[n] = 0; |
| 994 | break; |
| 995 | } |
| 996 | while( zLine[n] ) n++; |
| 997 | if( n>0 && zLine[n-1]=='\n' ){ |
| 998 | n--; |
| 999 | if( n>0 && zLine[n-1]=='\r' ) n--; |
| 1000 | zLine[n] = 0; |
| 1001 | break; |
| 1002 | } |
| 1003 | } |
| 1004 | return zLine; |
| 1005 | } |
| 1006 | |
| 1007 | /* |
| 1008 | ** Return true if either the SQLITE_NO_COLOR compile-time option is used |
| 1009 | ** or if the NO_COLOR environment variable exists |
| 1010 | */ |
| 1011 | static int shellNoColor(void){ |
| 1012 | #if defined(SQLITE_NO_COLOR) || defined(SQLITE_SHELL_FIDDLE) |
| 1013 | return 1; |
| 1014 | #else |
| 1015 | return getenv("NO_COLOR")!=0; |
| 1016 | #endif |
| 1017 | } |
| 1018 | |
| 1019 | /* |
| 1020 | ** The SQLITE_PS_APPDEF macro should be set to the name of a function |
| 1021 | ** that accepts a single "int" argument and returns a "const char *" |
| 1022 | ** that is guaranteed to be non-NULL. The value returned depends on the |
| 1023 | ** argument: |
| 1024 | ** |
| 1025 | ** 1 Default main prompt. |
| 1026 | ** 2 Default continuation prompt. |
| 1027 | ** 3 Environment variable to override main prompt ("SQLITE_PS1") |
| 1028 | ** 4 Environment variable to override continuatio ("SQLITE_PS2") |
| 1029 | ** 'A' The name of the application. (Nominally "SQLite") |
| 1030 | ** 'V' Version number including patch. (ex: "3.54.1") |
| 1031 | ** 'v' Version number without patch. (ex: "3.54") |
| 1032 | ** |
| 1033 | */ |
| 1034 | #ifdef SQLITE_PS_APPDEF |
| 1035 | extern const char *SQLITE_PS_APPDEF(int); |
| 1036 | #else |
| 1037 | # define SQLITE_PS_APPDEF shellPromptAppDef |
| 1038 | static const char *shellPromptAppDef(int c){ |
| 1039 | switch( c ){ |
| 1040 | /* The default main prompt string */ |
| 1041 | case 1: |
| 1042 | #if SQLITE_SHELL_EDITION<20260423 |
| 1043 | return "sqlite> "; /* Legacy prompt for backwards compatibility */ |
| 1044 | #elif defined(SQLITE_PS1) |
| 1045 | return SQLITE_PS1; |
| 1046 | #else |
| 1047 | if( shellNoColor() ){ |
| 1048 | return "/A-/v /f-> "; |
| 1049 | }else{ |
| 1050 | return "/e[1;32m/A-/v /e[1;/x33/:36/;m/m/e[3m/;/f/;/e[0m-> "; |
| 1051 | } |
| 1052 | #endif |
| 1053 | |
| 1054 | /* The default continuation prompt string */ |
| 1055 | case 2: |
| 1056 | #if SQLITE_SHELL_EDITION<20260423 |
| 1057 | return " ...> "; /* Legacy continuation prompt */ |
| 1058 | #elif defined(SQLITE_PS2) |
| 1059 | return SQLITE_PS2; |
| 1060 | #else |
| 1061 | if( shellNoColor() ){ |
| 1062 | return "/B/C-> "; |
| 1063 | }else{ |
| 1064 | return "/B/e[1;/x33/:36/;m/C/e[0m-> "; |
| 1065 | } |
| 1066 | #endif |
| 1067 | |
| 1068 | /* Name of environment variables that override the prompt strings |
| 1069 | ** of cases 1 and 2 */ |
| 1070 | case 3: return "SQLITE_PS1"; |
| 1071 | case 4: return "SQLITE_PS2"; |
| 1072 | |
| 1073 | /* Name of the application */ |
| 1074 | #ifndef SQLITE_CLI_APPNAME |
| 1075 | case 'A': return "SQLite"; |
| 1076 | #else |
| 1077 | case 'A': return SHELL_STRINGIFY(SQLITE_CLI_APPNAME); |
| 1078 | #endif |
| 1079 | |
| 1080 | /* Full version number of the application, including patch level */ |
| 1081 | case 'V': return sqlite3_libversion(); |
| 1082 | |
| 1083 | /* Version number without the patch level */ |
| 1084 | case 'v': { |
| 1085 | static char zRel[16]; |
| 1086 | const char *zF = sqlite3_libversion(); |
| 1087 | const char *zD = strrchr(zF,'.'); |
| 1088 | if( zD && (size_t)(zD-zF)<sizeof(zRel)-1 ){ |
| 1089 | memcpy(zRel,zF,(size_t)(zD-zF)); |
| 1090 | zRel[(size_t)(zD-zF)] = 0; |
| 1091 | return zRel; |
| 1092 | }else{ |
| 1093 | return zF; |
| 1094 | } |
| 1095 | } |
| 1096 | } |
| 1097 | return ""; |
| 1098 | } |
| 1099 | #endif /* !defined(SQLITE_PS_APPDEF) */ |
| 1100 | |
| 1101 | #ifdef SQLITE_DEBUG |
| 1102 | /* |
| 1103 | ** SQL function: sqlite3_incomplete(TEXT) |
| 1104 | ** |
| 1105 | ** For use internally and for debugging and testing only. This function |
| 1106 | ** is subject to change or removal in future versions. |
| 1107 | ** |
| 1108 | ** Invoke the sqlite3_incomplete() interface and return its result. |
| 1109 | */ |
| 1110 | static void shellIncompleteFunc( |
| 1111 | sqlite3_context *pCtx, |
| 1112 | int nVal, |
| 1113 | sqlite3_value **apVal |
| 1114 | ){ |
| 1115 | const char *zSql = (const char*)sqlite3_value_text(apVal[0]); |
| 1116 | sqlite3_result_int64(pCtx, zSql?sqlite3_incomplete(zSql):SQLITE_MISUSE); |
| 1117 | } |
| 1118 | #endif /* SQLITE_DEBUG */ |
| 1119 | |
| 1120 | /* |
| 1121 | ** Return the raw (unexpanded) prompt string. This will be the |
| 1122 | ** first of the following that exist: |
| 1123 | ** |
| 1124 | ** * The prompt string specified by the ".prompt" command. |
| 1125 | ** * The value of the SQLITE_PS1 (or SQLITE_PS2) environment variable. |
| 1126 | ** * The default prompt string. |
| 1127 | ** |
| 1128 | ** The main prompt is returned if the argument is zero and the |
| 1129 | ** continuation prompt is returned if the argument is 1. |
| 1130 | */ |
| 1131 | static const char *prompt_string(ShellState *p, int bContinue){ |
| 1132 | const char *zPS; |
| 1133 | assert( bContinue==0 || bContinue==1 ); |
| 1134 | if( p->azPrompt[bContinue] ){ |
| 1135 | return p->azPrompt[bContinue]; |
| 1136 | } |
| 1137 | #ifndef SQLITE_SHELL_FIDDLE |
| 1138 | zPS = getenv(SQLITE_PS_APPDEF(3+bContinue)); |
| 1139 | if( zPS ) return zPS; |
| 1140 | #endif |
| 1141 | return SQLITE_PS_APPDEF(1+bContinue); |
| 1142 | } |
| 1143 | |
| 1144 | /* |
| 1145 | ** Return the name of the open database file, to be used for prompt |
| 1146 | ** expansion purposes. |
| 1147 | */ |
| 1148 | static const char *prompt_filename(ShellState *p, const char *zMemoryName){ |
| 1149 | sqlite3_filename pFN; |
| 1150 | const char *zFN = 0; |
| 1151 | if( p->pAuxDb->mFlgs & 0x01 ){ |
| 1152 | zFN = p->pAuxDb->zDbFilename; |
| 1153 | }else if( p->db && (pFN = sqlite3_db_filename(p->db,0))!=0 ){ |
| 1154 | zFN = sqlite3_filename_database(pFN); |
| 1155 | } |
| 1156 | if( zFN==0 || zFN[0]==0 ){ |
| 1157 | zFN = p->pAuxDb->zDbFilename; |
| 1158 | } |
| 1159 | if( zFN==0 || zFN[0]==0 || cli_strcmp(zFN,":memory:")==0 ){ |
| 1160 | zFN = zMemoryName; |
| 1161 | } |
| 1162 | return zFN; |
| 1163 | } |
| 1164 | |
| 1165 | /* |
| 1166 | ** Return the name of the computer on which we are running. |
| 1167 | */ |
| 1168 | static const char *prompt_hostname(int bFull){ |
| 1169 | #ifdef _WIN32 |
| 1170 | const char *z = getenv("COMPUTERNAME"); |
| 1171 | if( z==0 || z[0]==0 ) z = "?"; |
| 1172 | return z; |
| 1173 | #else |
| 1174 | static char zHost[256]; |
| 1175 | if( gethostname(zHost, sizeof(zHost)) ){ |
| 1176 | zHost[0] = '?'; |
| 1177 | zHost[1] = 0; |
| 1178 | } |
| 1179 | if( !bFull ){ |
| 1180 | char *p = strchr(zHost,'.'); |
| 1181 | if( p ) p[0] = 0; |
| 1182 | } |
| 1183 | return zHost; |
| 1184 | #endif |
| 1185 | } |
| 1186 | |
| 1187 | /* |
| 1188 | ** Return the username. This is taken from an environment variable |
| 1189 | ** and can thus be forged. Do not depend on it. |
| 1190 | */ |
| 1191 | static const char *prompt_user(void){ |
| 1192 | const char *z; |
| 1193 | #ifdef _WIN32 |
| 1194 | z = getenv("USERNAME"); |
| 1195 | if( z==0 || z[0]==0 ) z = "?"; |
| 1196 | #else |
| 1197 | z = getenv("USER"); |
| 1198 | if( z==0 || z[0]==0 ) z = getenv("LOGNAME"); |
| 1199 | if( z==0 || z[0]==0 ) z = "?"; |
| 1200 | #endif |
| 1201 | return z; |
| 1202 | } |
| 1203 | |
| 1204 | /* If z[] begins with one or more ANSI X3.64 (VT100) escape sequences |
| 1205 | ** return the number of bytes in all such escape sequences. Return |
| 1206 | ** zero if there are no valid escape sequences. |
| 1207 | */ |
| 1208 | static int nAnsiEscape(const char *z){ |
| 1209 | int i = 0; |
| 1210 | while( z[i]=='\033' && z[i+1]=='[' ){ |
| 1211 | int k = i+2; |
| 1212 | while( z[k]>=0x30 && z[k]<=0x3f ){ k++; } |
| 1213 | while( z[k]>=0x20 && z[k]<=0x2f ){ k++; } |
| 1214 | if( z[k]<0x40 || z[k]>0x7e ) break; |
| 1215 | i = k+1; |
| 1216 | } |
| 1217 | return i; |
| 1218 | } |
| 1219 | |
| 1220 | /* |
| 1221 | ** Append text on pOut that is sufficient to complete the statement zBase |
| 1222 | ** (according to sqlite3_complete()). eFlags: |
| 1223 | ** |
| 1224 | ** 0x01 Include the final ";" if needed |
| 1225 | ** 0x04 Assume zBase ends with '\n' |
| 1226 | */ |
| 1227 | static void appendCompletion( |
| 1228 | sqlite3_str *pOut, /* Append the completion here */ |
| 1229 | const char *zBase, /* Existing SQL text */ |
| 1230 | int eFlags /* 0x01: Include ";", 0x04: Assume '\n' */ |
| 1231 | ){ |
| 1232 | sqlite3_int64 R = zBase ? sqlite3_incomplete(zBase) : 0; |
| 1233 | int cc = (R>>16)&0xff; |
| 1234 | int nParen = R>>32; |
| 1235 | int eSemi = (R>>8)&0xff; |
| 1236 | int eStat = R&0xff; |
| 1237 | int bSemi = (eFlags & 0x01)!=0; |
| 1238 | if( cc==0 ){ |
| 1239 | /* no-op */ |
| 1240 | }else if( cc=='-' ){ |
| 1241 | if( (eFlags & 0x04)==0 ) sqlite3_str_appendchar(pOut, 1, '\n'); |
| 1242 | }else if( cc=='/' ){ |
| 1243 | sqlite3_str_append(pOut,"*/",2); |
| 1244 | }else{ |
| 1245 | sqlite3_str_appendchar(pOut, 1, cc); |
| 1246 | } |
| 1247 | if( nParen>0 ){ |
| 1248 | sqlite3_str_appendf(pOut, "%.*c",nParen,')'); |
| 1249 | } |
| 1250 | if( eStat==SQLITE_OK || eStat==SQLITE_EMPTY ){ |
| 1251 | /* Nothing to add */ |
| 1252 | }else if( eSemi==1 ){ |
| 1253 | if( bSemi ) sqlite3_str_append(pOut, ";", 1); |
| 1254 | }else if( eSemi==2 ){ |
| 1255 | sqlite3_str_append(pOut, "END;", 3+(bSemi!=0)); |
| 1256 | }else if( eSemi==3 ){ |
| 1257 | sqlite3_str_append(pOut, ";END;", 4+(bSemi!=0)); |
| 1258 | } |
| 1259 | } |
| 1260 | |
| 1261 | /* |
| 1262 | ** SQL function: shell_complete_sql(SQL) |
| 1263 | ** shell_complete_sql(SQL, FLAGS) |
| 1264 | ** |
| 1265 | ** For use internally and for debugging and testing only. This function |
| 1266 | ** is subject to change or removal in future versions. |
| 1267 | ** |
| 1268 | ** If the SQL input is a string, return a new string which is the same |
| 1269 | ** text with all pending quotes and comments finish, so that the |
| 1270 | ** SQL is ready to receive its final semicolon. The optional FLAGS |
| 1271 | ** parameter can be an integer where bits mean: |
| 1272 | ** |
| 1273 | ** 0x01 Include the final semicolon |
| 1274 | ** 0x02 Only return the completion text. Omit the original SQL. |
| 1275 | ** 0x04 Assume that SQL has a \n at the end. |
| 1276 | ** |
| 1277 | ** The /C substitution in the CLI prompt is computed using the |
| 1278 | ** equivalent of shell_complete_sql(SQL,3); |
| 1279 | */ |
| 1280 | static void shell_complete_sql( |
| 1281 | sqlite3_context *pCtx, |
| 1282 | int nVal, |
| 1283 | sqlite3_value **apVal |
| 1284 | ){ |
| 1285 | const char *zSql; /* Input SQL text */ |
| 1286 | sqlite3_str *pOut; /* Completed SQL */ |
| 1287 | int flags; |
| 1288 | |
| 1289 | if( nVal!=1 && nVal!=2 ) return; |
| 1290 | if( nVal==2 ){ |
| 1291 | flags = 0x7 & sqlite3_value_int64(apVal[1]); |
| 1292 | }else{ |
| 1293 | flags = 0; |
| 1294 | } |
| 1295 | zSql = (const char*)sqlite3_value_text(apVal[0]); |
| 1296 | if( zSql==0 ) return; |
| 1297 | pOut = sqlite3_str_new(sqlite3_context_db_handle(pCtx)); |
| 1298 | if( (flags & 0x02)==0 ) sqlite3_str_appendall(pOut, zSql); |
| 1299 | appendCompletion(pOut, zSql, flags & 0x05); |
| 1300 | sqlite3_result_str(pCtx, pOut, SQLITE_FINISH); |
| 1301 | } |
| 1302 | |
| 1303 | /* |
| 1304 | ** Expand escapes in the given input prompt string. Return the |
| 1305 | ** expanded prompt in memory obtained from sqlite3_malloc(). The |
| 1306 | ** caller is responsible for freeing the memory. |
| 1307 | ** |
| 1308 | ** Early prototypes use U+005c '\\' as the escape character. But |
| 1309 | ** that is an escape character for shells and C and many other languages, |
| 1310 | ** which can lead to nested quoting problems and confusion. The |
| 1311 | ** U+0025 '%' character was also tried, and that works pretty well on |
| 1312 | ** unix, but % is special to many formats on Windows. So now we |
| 1313 | ** use a forward-slash, U+002f '/', which seems to pass through |
| 1314 | ** every shell and "make" without issue. |
| 1315 | */ |
| 1316 | static char *expand_prompt( |
| 1317 | ShellState *p, /* The current shell state */ |
| 1318 | const char *zPrior, /* Prior input lines not yet processed */ |
| 1319 | const char *zPrompt /* Prompt string to be expanded */ |
| 1320 | ){ |
| 1321 | sqlite3_str *pOut = sqlite3_str_new(0); |
| 1322 | int i; |
| 1323 | char c; |
| 1324 | unsigned int mOff = 0; /* Bitmask of FALSE for if/then/else */ |
| 1325 | int idxSpace = -1; |
| 1326 | int iDate = -1; |
| 1327 | for(i=0; zPrompt[i]; i++){ |
| 1328 | if( zPrompt[i]!='/' ) continue; |
| 1329 | if( i>0 ){ |
| 1330 | if( !mOff ) sqlite3_str_append(pOut, zPrompt, i); |
| 1331 | zPrompt += i; |
| 1332 | i = 0; |
| 1333 | } |
| 1334 | /* At this point zPrompt[0] is a / character and all prior |
| 1335 | ** characters have already been loaded into pOut. Process the |
| 1336 | ** escape sequence that zPrompt points to. */ |
| 1337 | c = zPrompt[1]; |
| 1338 | if( c==0 ){ |
| 1339 | /* / at the end of a line is silently ignored */ |
| 1340 | break; |
| 1341 | } |
| 1342 | if( c=='/' ){ |
| 1343 | /* // maps into a single / */ |
| 1344 | zPrompt++; |
| 1345 | continue; |
| 1346 | } |
| 1347 | if( c>='0' && c<='7' ){ |
| 1348 | /* /nnn becomes a single byte given by octal nnn */ |
| 1349 | int v = c - '0'; |
| 1350 | i++; |
| 1351 | while( i<=2 && zPrompt[i+1]>='0' && zPrompt[i+1]<='7' ){ |
| 1352 | v = v*8 + zPrompt[++i] - '0'; |
| 1353 | } |
| 1354 | if( !mOff ) sqlite3_str_appendchar(pOut, 1, v); |
| 1355 | zPrompt += i+1; |
| 1356 | i = -1; |
| 1357 | continue; |
| 1358 | } |
| 1359 | if( c=='e' ){ |
| 1360 | /* /e is shorthand for /033 which is U+001B "Escape" */ |
| 1361 | if( !mOff ) sqlite3_str_append(pOut, "\033", 1); |
| 1362 | zPrompt += 2; |
| 1363 | i = -1; |
| 1364 | continue; |
| 1365 | } |
| 1366 | if( c=='A' || c=='V' || c=='v' ){ |
| 1367 | /* /A expands to the application name */ |
| 1368 | /* /V expands to the version number with patch level */ |
| 1369 | /* /v expands to the version number without the patch level */ |
| 1370 | if( !mOff ) sqlite3_str_appendall(pOut, SQLITE_PS_APPDEF(c)); |
| 1371 | zPrompt += 2; |
| 1372 | i = -1; |
| 1373 | continue; |
| 1374 | } |
| 1375 | |
| 1376 | /* The intent of the following codes it to provide alternative |
| 1377 | ** text displays depending on whether or not the connection is |
| 1378 | ** currently in a transaction. Example 1: Show a "*" before the ">" |
| 1379 | ** like psql: (Note: We encode the "*" as /052 to avoid closing |
| 1380 | ** out this comment.) |
| 1381 | ** |
| 1382 | ** .prompt 'sqlite/x/052/;> ' |
| 1383 | ** |
| 1384 | ** Example 2: Show database filename is blue if not in a transaction, |
| 1385 | ** or red if within a transaction: |
| 1386 | ** |
| 1387 | ** .prompt '/e[1;/x31/:34/;m~f>/e[0m ' |
| 1388 | */ |
| 1389 | if( c==':' ){ |
| 1390 | /* ELSE: toggle display on/off */ |
| 1391 | mOff ^= 1; |
| 1392 | zPrompt += 2; |
| 1393 | i = -1; |
| 1394 | continue; |
| 1395 | } |
| 1396 | if( c==';' ){ |
| 1397 | /* ENDIF: Turn display on */ |
| 1398 | mOff >>= 1; |
| 1399 | zPrompt += 2; |
| 1400 | i = -1; |
| 1401 | continue; |
| 1402 | } |
| 1403 | if( c=='x' ){ |
| 1404 | /* /x turns display off not in a transaction, on if in txn */ |
| 1405 | mOff = (mOff<<1) | (p->db==0 || sqlite3_get_autocommit(p->db)!=0); |
| 1406 | zPrompt += 2; |
| 1407 | i = -1; |
| 1408 | continue; |
| 1409 | } |
| 1410 | if( c=='r' ){ |
| 1411 | /* /r turns display off if database is read/write, on if read-only */ |
| 1412 | mOff = (mOff<<1) | (p->db==0 || sqlite3_db_readonly(p->db,0)==0); |
| 1413 | zPrompt += 2; |
| 1414 | i = -1; |
| 1415 | continue; |
| 1416 | } |
| 1417 | if( c=='m' ){ |
| 1418 | /* /m turns display on for an in-memory database and off for persistent */ |
| 1419 | mOff = (mOff<<1) | (p->db && prompt_filename(p,0)!=0); |
| 1420 | zPrompt += 2; |
| 1421 | i = -1; |
| 1422 | continue; |
| 1423 | } |
| 1424 | |
| 1425 | if( c=='f' || c=='F' || c=='~' ){ |
| 1426 | /* /f becomes the tail of the database filename */ |
| 1427 | /* /F becomes the full pathname */ |
| 1428 | /* /~ becomes the full pathname relative to $HOME */ |
| 1429 | if( !mOff ){ |
| 1430 | const char *zFN = prompt_filename(p,"memory"); |
| 1431 | if( c=='f' ){ |
| 1432 | #ifdef _WIN32 |
| 1433 | const char *zTail = strrchr(zFN,'\\'); |
| 1434 | #else |
| 1435 | const char *zTail = strrchr(zFN,'/'); |
| 1436 | #endif |
| 1437 | if( zTail && zTail[1] ) zFN = &zTail[1]; |
| 1438 | }else if( c=='~' ){ |
| 1439 | const char *zHOME = getenv("HOME"); |
| 1440 | size_t nHOME = zHOME ? strlen(zHOME) : 0; |
| 1441 | if( nHOME<strlen(zFN) |
| 1442 | && zHOME!=0 && zFN!=0 /* <--- these silence compiler warnings */ |
| 1443 | && memcmp(zHOME,zFN,nHOME)==0 |
| 1444 | ){ |
| 1445 | sqlite3_str_append(pOut,"~",1); |
| 1446 | zFN += nHOME; |
| 1447 | } |
| 1448 | } |
| 1449 | sqlite3_str_appendall(pOut, zFN); |
| 1450 | } |
| 1451 | zPrompt += 2; |
| 1452 | i = -1; |
| 1453 | continue; |
| 1454 | } |
| 1455 | |
| 1456 | if( c=='h' || c=='H' ){ |
| 1457 | /* /h becomes hostname up to the first '.' */ |
| 1458 | /* /H is the full hostname */ |
| 1459 | if( !mOff ){ |
| 1460 | sqlite3_str_appendall(pOut, prompt_hostname(c=='H')); |
| 1461 | } |
| 1462 | zPrompt += 2; |
| 1463 | i = -1; |
| 1464 | continue; |
| 1465 | } |
| 1466 | if( c=='u' ){ |
| 1467 | /* /u becomes the username (taken from environment variables) */ |
| 1468 | if( !mOff ){ |
| 1469 | sqlite3_str_appendall(pOut, prompt_user()); |
| 1470 | } |
| 1471 | zPrompt += 2; |
| 1472 | i = -1; |
| 1473 | continue; |
| 1474 | } |
| 1475 | |
| 1476 | if( c=='C' ){ |
| 1477 | /* /C becomes text needed to terminate current input */ |
| 1478 | if( !mOff ){ |
| 1479 | appendCompletion(pOut, zPrior, 0x5); |
| 1480 | } |
| 1481 | zPrompt += 2; |
| 1482 | i = -1; |
| 1483 | continue; |
| 1484 | } |
| 1485 | |
| 1486 | if( c=='B' ){ |
| 1487 | /* /B is a no-op for the main prompt. For the continuation prompt, |
| 1488 | ** /B expands to zero or more spaces to make the continuation prompt |
| 1489 | ** at least as wide as the main prompt. */ |
| 1490 | if( !mOff ) idxSpace = sqlite3_str_length(pOut); |
| 1491 | zPrompt += 2; |
| 1492 | i = -1; |
| 1493 | continue; |
| 1494 | } |
| 1495 | |
| 1496 | if( c=='D' ){ |
| 1497 | /* /D.../D replaces all of the text between the two /D escapes with |
| 1498 | ** the result from strftime(). */ |
| 1499 | if( iDate<0 ){ |
| 1500 | iDate = sqlite3_str_length(pOut); |
| 1501 | }else{ |
| 1502 | if( !mOff ){ |
| 1503 | time_t now; |
| 1504 | char zBuf[200]; |
| 1505 | zBuf[0] = 0; |
| 1506 | time(&now); |
| 1507 | strftime(zBuf, sizeof(zBuf)-1, sqlite3_str_value(pOut)+iDate, |
| 1508 | localtime(&now)); |
| 1509 | zBuf[199] = 0; |
| 1510 | sqlite3_str_truncate(pOut, iDate); |
| 1511 | sqlite3_str_appendall(pOut, zBuf); |
| 1512 | } |
| 1513 | iDate = -1; |
| 1514 | } |
| 1515 | zPrompt += 2; |
| 1516 | i = -1; |
| 1517 | continue; |
| 1518 | } |
| 1519 | |
| 1520 | /* No match to a known escape. Generate an error. The mOff flag |
| 1521 | ** is ignored for this output, so that errors appear even if they |
| 1522 | ** are in an unused branch. */ |
| 1523 | sqlite3_str_appendf(pOut,"UNKNOWN(\"/%c\")",c); |
| 1524 | zPrompt += 2; |
| 1525 | i = -1; |
| 1526 | } |
| 1527 | if( i>0 && !mOff ){ |
| 1528 | sqlite3_str_append(pOut, zPrompt, i); |
| 1529 | } |
| 1530 | |
| 1531 | /* Expand the /B, if there is one and if this is a continuation prompt */ |
| 1532 | if( idxSpace>=0 && zPrior!=0 && zPrior[0]!=0 ){ |
| 1533 | char *zOther = expand_prompt(p, 0, prompt_string(p,0)); |
| 1534 | size_t wOther = sqlite3_qrf_wcswidth(zOther); |
| 1535 | size_t wThis = sqlite3_qrf_wcswidth(sqlite3_str_value(pOut)); |
| 1536 | sqlite3_free(zOther); |
| 1537 | if( wOther>wThis ){ |
| 1538 | char *z; |
| 1539 | int len; |
| 1540 | size_t nNew = wOther - wThis; |
| 1541 | assert( nNew>0 && nNew<0x7fffffff ); |
| 1542 | sqlite3_str_appendchar(pOut, (int)nNew, ' '); |
| 1543 | len = sqlite3_str_length(pOut); |
| 1544 | if( len>idxSpace ){ |
| 1545 | z = sqlite3_str_value(pOut); |
| 1546 | memmove(z+idxSpace+nNew, z+idxSpace, len-nNew-idxSpace); |
| 1547 | memset(z+idxSpace, ' ', nNew); |
| 1548 | } |
| 1549 | } |
| 1550 | } |
| 1551 | if( 0==sqlite3_str_length(pOut) ){ |
| 1552 | /* Avoid a bogus OOM */ |
| 1553 | sqlite3_str_appendchar(pOut, 1, '\0'); |
| 1554 | } |
| 1555 | |
| 1556 | /* Editline does not recognize ANSI X3.64 escape sequences. So we have |
| 1557 | ** to find them all and enclose them inside '\001'...'\002' delimiters. |
| 1558 | ** Some versions of readline also require this, but others do not. |
| 1559 | */ |
| 1560 | if( p->bDelimitNonprint && strstr(sqlite3_str_value(pOut),"\033[")!=0 ){ |
| 1561 | char *zOrig = sqlite3_str_finish(pOut); |
| 1562 | int n; |
| 1563 | pOut = sqlite3_str_new(0); |
| 1564 | for(i=0; zOrig[i]; i++){ |
| 1565 | if( zOrig[i]=='\033' && (n = nAnsiEscape(zOrig+i))>0 ){ |
| 1566 | sqlite3_str_appendchar(pOut, 1, 1); |
| 1567 | sqlite3_str_append(pOut, &zOrig[i], n); |
| 1568 | sqlite3_str_appendchar(pOut, 1, 2); |
| 1569 | i += n-1; |
| 1570 | }else{ |
| 1571 | sqlite3_str_appendchar(pOut, 1, zOrig[i]); |
| 1572 | } |
| 1573 | } |
| 1574 | sqlite3_free(zOrig); |
| 1575 | } |
| 1576 | |
| 1577 | return sqlite3_str_finish(pOut); |
| 1578 | } |
| 1579 | |
| 1580 | /* |
| 1581 | ** Retrieve a single line of input text. |
| 1582 | ** |
| 1583 | ** If in==0 then read from standard input and prompt before each line. |
| 1584 | ** If bContinue is true, then a continuation prompt is appropriate. |
| 1585 | ** If bContinue is zero, then the main prompt should be used. |
| 1586 | ** |
| 1587 | ** If zPrior is not NULL then it is a buffer from a prior call to this |
| 1588 | ** routine that can be reused. |
| 1589 | ** |
| 1590 | ** The result is stored in space obtained from malloc() and must either |
| 1591 | ** be freed by the caller or else passed back into this routine via the |
| 1592 | ** zPrior argument for reuse. |
| 1593 | */ |
| 1594 | #ifndef SQLITE_SHELL_FIDDLE |
| 1595 | static char *one_input_line( |
| 1596 | ShellState *p, /* Shell state */ |
| 1597 | char *zPrior, /* Just the previous line */ |
| 1598 | const char *zAll, /* All statement text accumulated so far */ |
| 1599 | int bContinue /* True for a continuation prompt */ |
| 1600 | ){ |
| 1601 | char *zResult; |
| 1602 | if( p->in!=0 ){ |
| 1603 | zResult = local_getline(p, zPrior, p->in); |
| 1604 | }else{ |
| 1605 | const char *zBase = prompt_string(p, bContinue!=0); |
| 1606 | char *zPrompt = expand_prompt(p, zAll, zBase); |
| 1607 | shell_check_oom(zPrompt); |
| 1608 | #if SHELL_CMDLINE_EDIT_AVAILABLE |
| 1609 | if( shellCmdLineEdit ){ |
| 1610 | free(zPrior); |
| 1611 | zResult = shell_readline(zPrompt); |
| 1612 | while( zResult==0 ){ |
| 1613 | /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */ |
| 1614 | sqlite3_sleep(50); |
| 1615 | if( seenInterrupt==0 ) break; |
| 1616 | zResult = shell_readline(""); |
| 1617 | } |
| 1618 | if( zResult && *zResult ) shell_add_history(zResult); |
| 1619 | }else |
| 1620 | #endif |
| 1621 | { |
| 1622 | sputz(stdout, zPrompt); |
| 1623 | fflush(stdout); |
| 1624 | do{ |
| 1625 | zResult = local_getline(p, zPrior, stdin); |
| 1626 | zPrior = 0; |
| 1627 | /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */ |
| 1628 | if( zResult==0 ) sqlite3_sleep(50); |
| 1629 | }while( zResult==0 && seenInterrupt>0 ); |
| 1630 | } |
| 1631 | sqlite3_free(zPrompt); |
| 1632 | } |
| 1633 | return zResult; |
| 1634 | } |
| 1635 | #endif /* !SQLITE_SHELL_FIDDLE */ |
| 1636 | |
| 1637 | /* |
| 1638 | ** Return the value of a hexadecimal digit. Return -1 if the input |
| 1639 | ** is not a hex digit. |
| 1640 | */ |
| 1641 | static int hexDigitValue(char c){ |
| 1642 | if( c>='0' && c<='9' ) return c - '0'; |
| 1643 | if( c>='a' && c<='f' ) return c - 'a' + 10; |
| 1644 | if( c>='A' && c<='F' ) return c - 'A' + 10; |
| 1645 | return -1; |
| 1646 | } |
| 1647 | |
| 1648 | /* |
| 1649 | ** Interpret zArg as an integer value, possibly with suffixes. |
| 1650 | ** |
| 1651 | ** If the value specified by zArg is outside the range of values that |
| 1652 | ** can be represented using a 64-bit twos-complement integer, then return |
| 1653 | ** the nearest representable value. |
| 1654 | */ |
| 1655 | static sqlite3_int64 integerValue(const char *zArg){ |
| 1656 | sqlite3_uint64 v = 0; |
| 1657 | static const struct { char *zSuffix; unsigned int iMult; } aMult[] = { |
| 1658 | { "KiB", 1024 }, |
| 1659 | { "MiB", 1024*1024 }, |
| 1660 | { "GiB", 1024*1024*1024 }, |
| 1661 | { "KB", 1000 }, |
| 1662 | { "MB", 1000000 }, |
| 1663 | { "GB", 1000000000 }, |
| 1664 | { "K", 1000 }, |
| 1665 | { "M", 1000000 }, |
| 1666 | { "G", 1000000000 }, |
| 1667 | }; |
| 1668 | int i; |
| 1669 | int isNeg = 0; |
| 1670 | if( zArg[0]=='-' ){ |
| 1671 | isNeg = 1; |
| 1672 | zArg++; |
| 1673 | }else if( zArg[0]=='+' ){ |
| 1674 | zArg++; |
| 1675 | } |
| 1676 | if( zArg[0]=='0' && zArg[1]=='x' ){ |
| 1677 | int x; |
| 1678 | zArg += 2; |
| 1679 | while( (x = hexDigitValue(zArg[0]))>=0 ){ |
| 1680 | if( v > 0x0fffffffffffffffULL ) goto integer_overflow; |
| 1681 | v = (v<<4) + x; |
| 1682 | zArg++; |
| 1683 | } |
| 1684 | }else{ |
| 1685 | while( IsDigit(zArg[0]) ){ |
| 1686 | if( v>=922337203685477580LL ){ |
| 1687 | if( v>922337203685477580LL || zArg[0]>='8' ) goto integer_overflow; |
| 1688 | } |
| 1689 | v = v*10 + (zArg[0] - '0'); |
| 1690 | zArg++; |
| 1691 | } |
| 1692 | } |
| 1693 | for(i=0; i<ArraySize(aMult); i++){ |
| 1694 | if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){ |
| 1695 | if( 0x7fffffffffffffffULL/aMult[i].iMult < v ) goto integer_overflow; |
| 1696 | v *= aMult[i].iMult; |
| 1697 | break; |
| 1698 | } |
| 1699 | } |
| 1700 | if( isNeg && v>0x7fffffffffffffffULL ) goto integer_overflow; |
| 1701 | return isNeg? -(sqlite3_int64)v : (sqlite3_int64)v; |
| 1702 | integer_overflow: |
| 1703 | return isNeg ? (i64)0x8000000000000000LL : 0x7fffffffffffffffLL; |
| 1704 | } |
| 1705 | |
| 1706 | /* |
| 1707 | ** A variable length string to which one can append text. |
| 1708 | */ |
| 1709 | typedef struct ShellText ShellText; |
| 1710 | struct ShellText { |
| 1711 | char *zTxt; /* The text */ |
| 1712 | i64 n; /* Number of bytes of zTxt[] actually used */ |
| 1713 | i64 nAlloc; /* Number of bytes allocated for zTxt[] */ |
| 1714 | }; |
| 1715 | |
| 1716 | /* |
| 1717 | ** Initialize and destroy a ShellText object |
| 1718 | */ |
| 1719 | static void initText(ShellText *p){ |
| 1720 | memset(p, 0, sizeof(*p)); |
| 1721 | } |
| 1722 | static void freeText(ShellText *p){ |
| 1723 | sqlite3_free(p->zTxt); |
| 1724 | initText(p); |
| 1725 | } |
| 1726 | |
| 1727 | /* zIn is either a pointer to a NULL-terminated string in memory obtained |
| 1728 | ** from malloc(), or a NULL pointer. The string pointed to by zAppend is |
| 1729 | ** added to zIn, and the result returned in memory obtained from malloc(). |
| 1730 | ** zIn, if it was not NULL, is freed. |
| 1731 | ** |
| 1732 | ** If the third argument, quote, is not '\0', then it is used as a |
| 1733 | ** quote character for zAppend. |
| 1734 | */ |
| 1735 | static void appendText(ShellText *p, const char *zAppend, char quote){ |
| 1736 | i64 len; |
| 1737 | i64 i; |
| 1738 | i64 nAppend = strlen30(zAppend); |
| 1739 | |
| 1740 | len = nAppend+p->n+1; |
| 1741 | if( quote ){ |
| 1742 | len += 2; |
| 1743 | for(i=0; i<nAppend; i++){ |
| 1744 | if( zAppend[i]==quote ) len++; |
| 1745 | } |
| 1746 | } |
| 1747 | |
| 1748 | if( p->zTxt==0 || p->n+len>=p->nAlloc ){ |
| 1749 | p->nAlloc = p->nAlloc*2 + len + 20; |
| 1750 | p->zTxt = sqlite3_realloc64(p->zTxt, p->nAlloc); |
| 1751 | shell_check_oom(p->zTxt); |
| 1752 | } |
| 1753 | |
| 1754 | if( quote ){ |
| 1755 | char *zCsr = p->zTxt+p->n; |
| 1756 | *zCsr++ = quote; |
| 1757 | for(i=0; i<nAppend; i++){ |
| 1758 | *zCsr++ = zAppend[i]; |
| 1759 | if( zAppend[i]==quote ) *zCsr++ = quote; |
| 1760 | } |
| 1761 | *zCsr++ = quote; |
| 1762 | p->n = (i64)(zCsr - p->zTxt); |
| 1763 | *zCsr = '\0'; |
| 1764 | }else{ |
| 1765 | memcpy(p->zTxt+p->n, zAppend, nAppend); |
| 1766 | p->n += nAppend; |
| 1767 | p->zTxt[p->n] = '\0'; |
| 1768 | } |
| 1769 | } |
| 1770 | |
| 1771 | /* |
| 1772 | ** Attempt to determine if identifier zName needs to be quoted, either |
| 1773 | ** because it contains non-alphanumeric characters, or because it is an |
| 1774 | ** SQLite keyword. Be conservative in this estimate: When in doubt assume |
| 1775 | ** that quoting is required. |
| 1776 | ** |
| 1777 | ** Return '"' if quoting is required. Return 0 if no quoting is required. |
| 1778 | */ |
| 1779 | static char quoteChar(const char *zName){ |
| 1780 | int i; |
| 1781 | if( zName==0 ) return '"'; |
| 1782 | if( !IsAlpha(zName[0]) && zName[0]!='_' ) return '"'; |
| 1783 | for(i=0; zName[i]; i++){ |
| 1784 | if( !IsAlnum(zName[i]) && zName[i]!='_' ) return '"'; |
| 1785 | } |
| 1786 | return sqlite3_keyword_check(zName, i) ? '"' : 0; |
| 1787 | } |
| 1788 | |
| 1789 | /* |
| 1790 | ** Construct a fake object name and column list to describe the structure |
| 1791 | ** of the view, virtual table, or table valued function zSchema.zName. |
| 1792 | ** |
| 1793 | ** The returned string comes from sqlite3_mprintf() and should be freed |
| 1794 | ** by the caller using sqlite3_free(). |
| 1795 | */ |
| 1796 | static char *shellFakeSchema( |
| 1797 | sqlite3 *db, /* The database connection containing the vtab */ |
| 1798 | const char *zSchema, /* Schema of the database holding the vtab */ |
| 1799 | const char *zName /* The name of the virtual table */ |
| 1800 | ){ |
| 1801 | sqlite3_stmt *pStmt = 0; |
| 1802 | char *zSql, *zCom; |
| 1803 | ShellText s; |
| 1804 | char cQuote; |
| 1805 | char *zDiv = "("; |
| 1806 | int nRow = 0; |
| 1807 | |
| 1808 | zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;", |
| 1809 | zSchema ? zSchema : "main", zName); |
| 1810 | shell_check_oom(zSql); |
| 1811 | sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); |
| 1812 | sqlite3_free(zSql); |
| 1813 | initText(&s); |
| 1814 | if( zSchema ){ |
| 1815 | cQuote = quoteChar(zSchema); |
| 1816 | if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0; |
| 1817 | appendText(&s, zSchema, cQuote); |
| 1818 | appendText(&s, ".", 0); |
| 1819 | } |
| 1820 | cQuote = quoteChar(zName); |
| 1821 | appendText(&s, zName, cQuote); |
| 1822 | while( sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 1823 | const char *zCol = (const char*)sqlite3_column_text(pStmt, 1); |
| 1824 | nRow++; |
| 1825 | appendText(&s, zDiv, 0); |
| 1826 | zDiv = ","; |
| 1827 | if( zCol==0 ) zCol = ""; |
| 1828 | cQuote = quoteChar(zCol); |
| 1829 | appendText(&s, zCol, cQuote); |
| 1830 | } |
| 1831 | appendText(&s, ")", 0); |
| 1832 | sqlite3_finalize(pStmt); |
| 1833 | if( nRow==0 ){ |
| 1834 | freeText(&s); |
| 1835 | s.zTxt = 0; |
| 1836 | }else{ |
| 1837 | while( s.zTxt && (zCom = strstr(s.zTxt,"*/"))!=0 ){ zCom[1] = '*'; } |
| 1838 | } |
| 1839 | return s.zTxt; |
| 1840 | } |
| 1841 | |
| 1842 | /* |
| 1843 | ** SQL function: capable(X) |
| 1844 | ** |
| 1845 | ** Return true if the current build has capability X. Return 0 |
| 1846 | ** if X is not a capability or NULL if X is NULL. |
| 1847 | ** |
| 1848 | ** A build has capability X if any of the following are true: |
| 1849 | ** |
| 1850 | ** (1) A function named X exists. |
| 1851 | ** (2) A module named X exists. |
| 1852 | ** (3) A compile-time option X is used for the build. |
| 1853 | ** |
| 1854 | ** Comparison between X and the various items above is done |
| 1855 | ** without to case. So capable('generate_series') and |
| 1856 | ** capable('GENERATE_SERIES') and capable('Generate_Series') |
| 1857 | ** all work the same. |
| 1858 | ** |
| 1859 | ** There are also special names "vtab", "fkey", and "load_ext" |
| 1860 | ** that return true as long as compile-time options |
| 1861 | ** SQLITE_OMIT_VIRTUALTABLE, SQLITE_OMIT_FOREIGN_KEY, and |
| 1862 | ** SQLITE_OMIT_LOAD_EXTENSION are omitted from the build, |
| 1863 | ** respectively. New special names may be added in the future. |
| 1864 | ** Thus, for example, "capable('vtab')" means that the build |
| 1865 | ** lacks SQLITE_OMIT_VIRTUALTABLE and hence does support |
| 1866 | ** virtual tables. |
| 1867 | ** |
| 1868 | ** For other "OMIT" options (besides the three special ones noted |
| 1869 | ** in the previous paragraph) you have to say something like |
| 1870 | ** "capable('OMIT_EXPLAIN')". And that function returns true |
| 1871 | ** if the EXPLAIN capability is omitted. It works like a |
| 1872 | ** double-negative. This is a bit confusing (hence the special |
| 1873 | ** names for the common cases mentioned above) but it servicable |
| 1874 | ** for the rare cases when it is needed. |
| 1875 | ** |
| 1876 | ** This function is intended to be used with the ".if" command |
| 1877 | ** to bypass test cases that use features that are not part of |
| 1878 | ** the build. Examples: |
| 1879 | ** |
| 1880 | ** .if capable('fts5') |
| 1881 | ** # do tests that require the FTS5 extension |
| 1882 | ** .endif |
| 1883 | ** |
| 1884 | ** .if capable('generate_series') |
| 1885 | ** # do tests that require the generate_series() table-valued functions |
| 1886 | ** .endif |
| 1887 | */ |
| 1888 | static void shellCapable( |
| 1889 | sqlite3_context *pCtx, |
| 1890 | int nVal, |
| 1891 | sqlite3_value **apVal |
| 1892 | ){ |
| 1893 | ShellState *p = (ShellState*)sqlite3_user_data(pCtx); |
| 1894 | const char *z = (const char*)sqlite3_value_text(apVal[0]); |
| 1895 | static const char *azSql[] = { |
| 1896 | "PRAGMA compile_options", |
| 1897 | "PRAGMA module_list", |
| 1898 | "PRAGMA function_list" |
| 1899 | }; |
| 1900 | static const char *azInversions[] = { |
| 1901 | "vtab", "OMIT_VIRTUALTABLE", |
| 1902 | "fkey", "OMIT_FOREIGN_KEY", |
| 1903 | "load_ext", "OMIT_LOAD_EXTENSION", |
| 1904 | }; |
| 1905 | size_t i; |
| 1906 | int invert = 0; |
| 1907 | int res = 0; |
| 1908 | |
| 1909 | UNUSED_PARAMETER(nVal); |
| 1910 | if( z==0 ) return; |
| 1911 | for(i=0; i<sizeof(azInversions)/sizeof(azInversions[0])-1; i+=2){ |
| 1912 | if( sqlite3_stricmp(z, azInversions[i])==0 ){ |
| 1913 | z = azInversions[i+1]; |
| 1914 | invert = 1; |
| 1915 | break; |
| 1916 | } |
| 1917 | } |
| 1918 | for(i=0; i<sizeof(azSql)/sizeof(azSql[0]); i++){ |
| 1919 | sqlite3_stmt *pStmt = 0; |
| 1920 | sqlite3_prepare_v2(p->db, azSql[i], -1, &pStmt, 0); |
| 1921 | while( sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 1922 | const char *zRow = (const char*)sqlite3_column_text(pStmt, 0); |
| 1923 | if( sqlite3_stricmp(zRow, z)==0 ){ |
| 1924 | res = 1; |
| 1925 | break; |
| 1926 | } |
| 1927 | } |
| 1928 | sqlite3_finalize(pStmt); |
| 1929 | if( res ) break; |
| 1930 | } |
| 1931 | if( invert ) res = !res; |
| 1932 | sqlite3_result_int(pCtx, res); |
| 1933 | } |
| 1934 | |
| 1935 | |
| 1936 | /* |
| 1937 | ** SQL function: strtod(X) |
| 1938 | ** |
| 1939 | ** For use internally and for debugging and testing only. This function |
| 1940 | ** is subject to change or removal in future versions. |
| 1941 | ** |
| 1942 | ** Use the C-library strtod() function to convert string X into a double. |
| 1943 | ** Used for comparing the accuracy of SQLite's internal text-to-float conversion |
| 1944 | ** routines against the C-library. |
| 1945 | */ |
| 1946 | static void shellStrtod( |
| 1947 | sqlite3_context *pCtx, |
| 1948 | int nVal, |
| 1949 | sqlite3_value **apVal |
| 1950 | ){ |
| 1951 | char *z = (char*)sqlite3_value_text(apVal[0]); |
| 1952 | UNUSED_PARAMETER(nVal); |
| 1953 | if( z==0 ) return; |
| 1954 | sqlite3_result_double(pCtx, strtod(z,0)); |
| 1955 | } |
| 1956 | |
| 1957 | /* |
| 1958 | ** SQL function: dtostr(X) |
| 1959 | ** |
| 1960 | ** For use internally and for debugging and testing only. This function |
| 1961 | ** is subject to change or removal in future versions. |
| 1962 | ** |
| 1963 | ** Use the C-library printf() function to convert real value X into a string. |
| 1964 | ** Used for comparing the accuracy of SQLite's internal float-to-text conversion |
| 1965 | ** routines against the C-library. |
| 1966 | */ |
| 1967 | static void shellDtostr( |
| 1968 | sqlite3_context *pCtx, |
| 1969 | int nVal, |
| 1970 | sqlite3_value **apVal |
| 1971 | ){ |
| 1972 | double r = sqlite3_value_double(apVal[0]); |
| 1973 | i64 nn = nVal>=2 ? sqlite3_value_int64(apVal[1]) : 26; |
| 1974 | int n; |
| 1975 | char z[400]; |
| 1976 | if( nn<1 ){ |
| 1977 | n = 1; |
| 1978 | }else if( nn>350 ){ |
| 1979 | n = 350; |
| 1980 | }else{ |
| 1981 | n = (int)nn; |
| 1982 | } |
| 1983 | z[sizeof(z)-1] = 0; |
| 1984 | snprintf(z, sizeof(z)-1, "%#+.*e", n, r); |
| 1985 | sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); |
| 1986 | } |
| 1987 | |
| 1988 | /* |
| 1989 | ** SQL function: shell_add_schema(S,X,N) |
| 1990 | ** |
| 1991 | ** For use internally and for debugging and testing only. This function |
| 1992 | ** is subject to change or removal in future versions. |
| 1993 | ** |
| 1994 | ** Add the schema X to the CREATE statement in S for table N and return |
| 1995 | ** the result. |
| 1996 | ** |
| 1997 | ** Examples: |
| 1998 | ** |
| 1999 | ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x); |
| 2000 | ** |
| 2001 | ** Also works on |
| 2002 | ** |
| 2003 | ** CREATE INDEX |
| 2004 | ** CREATE UNIQUE INDEX |
| 2005 | ** CREATE VIEW |
| 2006 | ** CREATE TRIGGER |
| 2007 | ** CREATE VIRTUAL TABLE |
| 2008 | ** |
| 2009 | ** This UDF is used by the .schema command to insert the schema name of |
| 2010 | ** attached databases into the middle of the sqlite_schema.sql field. |
| 2011 | */ |
| 2012 | static void shellAddSchemaName( |
| 2013 | sqlite3_context *pCtx, |
| 2014 | int nVal, |
| 2015 | sqlite3_value **apVal |
| 2016 | ){ |
| 2017 | static const char *aPrefix[] = { |
| 2018 | "TABLE", |
| 2019 | "INDEX", |
| 2020 | "UNIQUE INDEX", |
| 2021 | "VIEW", |
| 2022 | "TRIGGER", |
| 2023 | "VIRTUAL TABLE" |
| 2024 | }; |
| 2025 | int i = 0; |
| 2026 | const char *zIn = (const char*)sqlite3_value_text(apVal[0]); |
| 2027 | const char *zSchema = (const char*)sqlite3_value_text(apVal[1]); |
| 2028 | const char *zName = (const char*)sqlite3_value_text(apVal[2]); |
| 2029 | sqlite3 *db = sqlite3_context_db_handle(pCtx); |
| 2030 | UNUSED_PARAMETER(nVal); |
| 2031 | if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){ |
| 2032 | for(i=0; i<ArraySize(aPrefix); i++){ |
| 2033 | int n = strlen30(aPrefix[i]); |
| 2034 | if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){ |
| 2035 | sqlite3_str *pOut = sqlite3_str_new(db); |
| 2036 | char *zFake = 0; |
| 2037 | if( zSchema ){ |
| 2038 | char cQuote = quoteChar(zSchema); |
| 2039 | if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){ |
| 2040 | sqlite3_str_appendf(pOut, "%.*s \"%w\".%s", n+7,zIn,zSchema,zIn+n+8); |
| 2041 | }else{ |
| 2042 | sqlite3_str_appendf(pOut, "%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8); |
| 2043 | } |
| 2044 | }else{ |
| 2045 | sqlite3_str_appendall(pOut, zIn); |
| 2046 | } |
| 2047 | appendCompletion(pOut, sqlite3_str_value(pOut), 1); |
| 2048 | if( zName |
| 2049 | && aPrefix[i][0]=='V' |
| 2050 | && (zFake = shellFakeSchema(db, zSchema, zName))!=0 |
| 2051 | ){ |
| 2052 | assert( strstr(zFake,"*/")==0 ); |
| 2053 | sqlite3_str_appendf(pOut, "\n/* %z */", zFake); |
| 2054 | } |
| 2055 | sqlite3_result_str(pCtx, pOut, SQLITE_FINISH); |
| 2056 | return; |
| 2057 | } |
| 2058 | } |
| 2059 | } |
| 2060 | sqlite3_result_value(pCtx, apVal[0]); |
| 2061 | } |
| 2062 | |
| 2063 | /* |
| 2064 | ** SQL function: shell_prompt_test(PROMPT,PRIOR,FILENAME,FLAGS) |
| 2065 | ** |
| 2066 | ** For use internally and for debugging and testing only. This function |
| 2067 | ** is subject to change or removal in future versions. |
| 2068 | ** |
| 2069 | ** Return the shell prompt, with escapes expanded, for testing purposes. |
| 2070 | ** The first argument is the raw (unexpanded) prompt string. Or if the |
| 2071 | ** first argument is NULL, then use whatever prompt string is currently |
| 2072 | ** configured. If the second argument exists and is not NULL, then the |
| 2073 | ** second argument is understood to be prior incomplete text and a |
| 2074 | ** continuation prompt is generated. If a third argument is provided, |
| 2075 | ** it is assumed to be the full pathname of the database file. The |
| 2076 | ** fourth argument, if provided, is an integer of flags: |
| 2077 | ** |
| 2078 | ** 0x0001 Always insert \001..\002 delimiters around ANSI escapes |
| 2079 | ** 0x0002 Never insert \001..\002 delimiters |
| 2080 | ** |
| 2081 | ** This function is for testing purposes only. The interface may change. |
| 2082 | ** The function itself might be renamed or removed in future releases. Do |
| 2083 | ** not use this function in applications. |
| 2084 | */ |
| 2085 | static void shellExpandPrompt( |
| 2086 | sqlite3_context *pCtx, |
| 2087 | int nVal, |
| 2088 | sqlite3_value **apVal |
| 2089 | ){ |
| 2090 | ShellState *p = (ShellState*)sqlite3_user_data(pCtx); |
| 2091 | const char *zPrompt; |
| 2092 | const char *zPrior; |
| 2093 | const char *zSavedDbFile; |
| 2094 | int mSavedFlgs; |
| 2095 | const char *zFName; |
| 2096 | char *zRes; |
| 2097 | int mFlags; |
| 2098 | char bSavedDelimit = p->bDelimitNonprint; |
| 2099 | |
| 2100 | if( nVal<1 ) return; |
| 2101 | if( nVal<2 |
| 2102 | || (zPrior = (const char*)sqlite3_value_text(apVal[1]))==0 |
| 2103 | || zPrior[0]==0 |
| 2104 | ){ |
| 2105 | zPrior = 0; |
| 2106 | } |
| 2107 | zPrompt = (const char*)sqlite3_value_text(apVal[0]); |
| 2108 | if( zPrompt==0 ){ |
| 2109 | zPrompt = prompt_string(p, zPrior!=0); |
| 2110 | } |
| 2111 | zSavedDbFile = p->pAuxDb->zDbFilename; |
| 2112 | mSavedFlgs = p->pAuxDb->mFlgs; |
| 2113 | if( nVal>=3 && (zFName = (const char*)sqlite3_value_text(apVal[2]))!=0 ){ |
| 2114 | p->pAuxDb->zDbFilename = zFName; |
| 2115 | p->pAuxDb->mFlgs |= 0x001; |
| 2116 | } |
| 2117 | mFlags = nVal>=4 ? sqlite3_value_int(apVal[3]) : 0; |
| 2118 | if( mFlags & 0x0001 ){ |
| 2119 | p->bDelimitNonprint = 1; |
| 2120 | }else if( mFlags & 0x0002 ){ |
| 2121 | p->bDelimitNonprint = 0; |
| 2122 | } |
| 2123 | zRes = expand_prompt(p, zPrior, zPrompt); |
| 2124 | p->bDelimitNonprint = bSavedDelimit; |
| 2125 | p->pAuxDb->zDbFilename = zSavedDbFile; |
| 2126 | p->pAuxDb->mFlgs = mSavedFlgs; |
| 2127 | sqlite3_result_text(pCtx, zRes, -1, SQLITE_TRANSIENT); |
| 2128 | sqlite3_free(zRes); |
| 2129 | } |
| 2130 | |
| 2131 | |
| 2132 | /************************* BEGIN PERFORMANCE TIMER *****************************/ |
| 2133 | #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux) |
| 2134 | #include <sys/time.h> |
| 2135 | #include <sys/resource.h> |
| 2136 | /* VxWorks does not support getrusage() as far as we can determine */ |
| 2137 | #if defined(_WRS_KERNEL) || defined(__RTP__) |
| 2138 | struct rusage { |
| 2139 | struct timeval ru_utime; /* user CPU time used */ |
| 2140 | struct timeval ru_stime; /* system CPU time used */ |
| 2141 | }; |
| 2142 | #define getrusage(A,B) memset(B,0,sizeof(*B)) |
| 2143 | #endif |
| 2144 | |
| 2145 | /* Saved resource information for the beginning of an operation */ |
| 2146 | static struct rusage sBegin; /* CPU time at start */ |
| 2147 | static sqlite3_int64 iBegin; /* Wall-clock time at start */ |
| 2148 | |
| 2149 | /* |
| 2150 | ** Begin timing an operation |
| 2151 | */ |
| 2152 | static void beginTimer(ShellState *p){ |
| 2153 | if( p->enableTimer || (p->flgProgress & SHELL_PROGRESS_TMOUT)!=0 ){ |
| 2154 | getrusage(RUSAGE_SELF, &sBegin); |
| 2155 | iBegin = timeOfDay(); |
| 2156 | } |
| 2157 | } |
| 2158 | |
| 2159 | /* Return the difference of two time_structs in seconds */ |
| 2160 | static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ |
| 2161 | return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + |
| 2162 | (double)(pEnd->tv_sec - pStart->tv_sec); |
| 2163 | } |
| 2164 | |
| 2165 | #ifndef SQLITE_OMIT_PROGRESS_CALLBACK |
| 2166 | /* Return the time since the start of the timer in |
| 2167 | ** seconds. */ |
| 2168 | static double elapseTime(ShellState *NotUsed){ |
| 2169 | (void)NotUsed; |
| 2170 | if( iBegin==0 ) return 0.0; |
| 2171 | return (timeOfDay() - iBegin)*0.000001; |
| 2172 | } |
| 2173 | #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ |
| 2174 | |
| 2175 | /* |
| 2176 | ** Print the timing results. |
| 2177 | */ |
| 2178 | static void endTimer(ShellState *p){ |
| 2179 | if( p->enableTimer ){ |
| 2180 | sqlite3_int64 iEnd = timeOfDay(); |
| 2181 | struct rusage sEnd; |
| 2182 | getrusage(RUSAGE_SELF, &sEnd); |
| 2183 | p->prevTimer = (iEnd - iBegin)*0.000001; |
| 2184 | cli_printf(p->out, "Run Time: real %.6f user %.6f sys %.6f\n", |
| 2185 | p->prevTimer, |
| 2186 | timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), |
| 2187 | timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); |
| 2188 | if( p->enableTimer==1 ) p->enableTimer = 0; |
| 2189 | iBegin = 0; |
| 2190 | } |
| 2191 | } |
| 2192 | |
| 2193 | #define BEGIN_TIMER(X) beginTimer(X) |
| 2194 | #define END_TIMER(X) endTimer(X) |
| 2195 | #define ELAPSE_TIME(X) elapseTime(X) |
| 2196 | #define HAS_TIMER 1 |
| 2197 | |
| 2198 | #elif (defined(_WIN32) || defined(WIN32)) |
| 2199 | |
| 2200 | /* Saved resource information for the beginning of an operation */ |
| 2201 | static HANDLE hProcess; |
| 2202 | static FILETIME ftKernelBegin; |
| 2203 | static FILETIME ftUserBegin; |
| 2204 | static sqlite3_int64 ftWallBegin; |
| 2205 | typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, |
| 2206 | LPFILETIME, LPFILETIME); |
| 2207 | static GETPROCTIMES getProcessTimesAddr = NULL; |
| 2208 | |
| 2209 | /* |
| 2210 | ** Check to see if we have timer support. Return 1 if necessary |
| 2211 | ** support found (or found previously). |
| 2212 | */ |
| 2213 | static int hasTimer(void){ |
| 2214 | if( getProcessTimesAddr ){ |
| 2215 | return 1; |
| 2216 | } else { |
| 2217 | /* GetProcessTimes() isn't supported in WIN95 and some other Windows |
| 2218 | ** versions. See if the version we are running on has it, and if it |
| 2219 | ** does, save off a pointer to it and the current process handle. |
| 2220 | */ |
| 2221 | hProcess = GetCurrentProcess(); |
| 2222 | if( hProcess ){ |
| 2223 | HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll")); |
| 2224 | if( NULL != hinstLib ){ |
| 2225 | getProcessTimesAddr = |
| 2226 | (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes"); |
| 2227 | if( NULL != getProcessTimesAddr ){ |
| 2228 | return 1; |
| 2229 | } |
| 2230 | FreeLibrary(hinstLib); |
| 2231 | } |
| 2232 | } |
| 2233 | } |
| 2234 | return 0; |
| 2235 | } |
| 2236 | |
| 2237 | /* |
| 2238 | ** Begin timing an operation |
| 2239 | */ |
| 2240 | static void beginTimer(ShellState *p){ |
| 2241 | if( (p->enableTimer || (p->flgProgress & SHELL_PROGRESS_TMOUT)!=0) |
| 2242 | && getProcessTimesAddr |
| 2243 | ){ |
| 2244 | FILETIME ftCreation, ftExit; |
| 2245 | getProcessTimesAddr(hProcess,&ftCreation,&ftExit, |
| 2246 | &ftKernelBegin,&ftUserBegin); |
| 2247 | ftWallBegin = timeOfDay(); |
| 2248 | } |
| 2249 | } |
| 2250 | |
| 2251 | /* Return the difference of two FILETIME structs in seconds */ |
| 2252 | static double timeDiff(FILETIME *pStart, FILETIME *pEnd){ |
| 2253 | sqlite_int64 i64Start = *((sqlite_int64 *) pStart); |
| 2254 | sqlite_int64 i64End = *((sqlite_int64 *) pEnd); |
| 2255 | return (double) ((i64End - i64Start) / 10000000.0); |
| 2256 | } |
| 2257 | |
| 2258 | #ifndef SQLITE_OMIT_PROGRESS_CALLBACK |
| 2259 | /* Return the time since the start of the timer in |
| 2260 | ** seconds. */ |
| 2261 | static double elapseTime(ShellState *NotUsed){ |
| 2262 | (void)NotUsed; |
| 2263 | if( ftWallBegin==0 ) return 0.0; |
| 2264 | return (timeOfDay() - ftWallBegin)*0.000001; |
| 2265 | } |
| 2266 | #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ |
| 2267 | |
| 2268 | /* |
| 2269 | ** Print the timing results. |
| 2270 | */ |
| 2271 | static void endTimer(ShellState *p){ |
| 2272 | if( p->enableTimer && getProcessTimesAddr){ |
| 2273 | FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd; |
| 2274 | sqlite3_int64 ftWallEnd = timeOfDay(); |
| 2275 | getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd); |
| 2276 | p->prevTimer = (ftWallEnd - ftWallBegin)*0.000001; |
| 2277 | #ifdef _WIN64 |
| 2278 | /* microsecond precision on 64-bit windows */ |
| 2279 | cli_printf(p->out, "Run Time: real %.6f user %f sys %f\n", |
| 2280 | p->prevTimer, |
| 2281 | timeDiff(&ftUserBegin, &ftUserEnd), |
| 2282 | timeDiff(&ftKernelBegin, &ftKernelEnd)); |
| 2283 | #else |
| 2284 | /* millisecond precisino on 32-bit windows */ |
| 2285 | cli_printf(p->out, "Run Time: real %.3f user %.3f sys %.3f\n", |
| 2286 | p->prevTimer, |
| 2287 | timeDiff(&ftUserBegin, &ftUserEnd), |
| 2288 | timeDiff(&ftKernelBegin, &ftKernelEnd)); |
| 2289 | #endif |
| 2290 | if( p->enableTimer==1 ) p->enableTimer = 0; |
| 2291 | ftWallBegin = 0; |
| 2292 | } |
| 2293 | } |
| 2294 | |
| 2295 | #define BEGIN_TIMER(X) beginTimer(X) |
| 2296 | #define ELAPSE_TIME(X) elapseTime(X) |
| 2297 | #define END_TIMER(X) endTimer(X) |
| 2298 | #define HAS_TIMER hasTimer() |
| 2299 | |
| 2300 | #else |
| 2301 | #define BEGIN_TIMER(X) /* no-op */ |
| 2302 | #define ELAPSE_TIME(X) 0.0 |
| 2303 | #define END_TIMER(X) /*no-op*/ |
| 2304 | #define HAS_TIMER 0 |
| 2305 | #endif |
| 2306 | /************************* END PERFORMANCE TIMER ******************************/ |
| 2307 | |
| 2308 | /* |
| 2309 | ** Clear a display mode, freeing any allocated memory that it |
| 2310 | ** contains. |
| 2311 | */ |
| 2312 | static void modeFree(Mode *p){ |
| 2313 | u8 autoExplain = p->autoExplain; |
| 2314 | free(p->spec.aWidth); |
| 2315 | free(p->spec.aAlign); |
| 2316 | free(p->spec.zColumnSep); |
| 2317 | free(p->spec.zRowSep); |
| 2318 | free(p->spec.zTableName); |
| 2319 | free(p->spec.zNull); |
| 2320 | memset(p, 0, sizeof(*p)); |
| 2321 | p->spec.iVersion = 2; |
| 2322 | p->autoExplain = autoExplain; |
| 2323 | } |
| 2324 | |
| 2325 | /* |
| 2326 | ** Duplicate Mode pSrc into pDest. pDest is assumed to be |
| 2327 | ** uninitialized prior to invoking this routine. |
| 2328 | */ |
| 2329 | static void modeDup(Mode *pDest, Mode *pSrc){ |
| 2330 | memcpy(pDest, pSrc, sizeof(*pDest)); |
| 2331 | if( pDest->spec.aWidth ){ |
| 2332 | size_t sz = sizeof(pSrc->spec.aWidth[0]) * pSrc->spec.nWidth; |
| 2333 | pDest->spec.aWidth = malloc( sz ); |
| 2334 | if( pDest->spec.aWidth ){ |
| 2335 | memcpy(pDest->spec.aWidth, pSrc->spec.aWidth, sz); |
| 2336 | }else{ |
| 2337 | pDest->spec.nWidth = 0; |
| 2338 | } |
| 2339 | } |
| 2340 | if( pDest->spec.aAlign ){ |
| 2341 | size_t sz = sizeof(pSrc->spec.aAlign[0]) * pSrc->spec.nAlign; |
| 2342 | pDest->spec.aAlign = malloc( sz ); |
| 2343 | if( pDest->spec.aAlign ){ |
| 2344 | memcpy(pDest->spec.aAlign, pSrc->spec.aAlign, sz); |
| 2345 | }else{ |
| 2346 | pDest->spec.nAlign = 0; |
| 2347 | } |
| 2348 | } |
| 2349 | if( pDest->spec.zColumnSep ){ |
| 2350 | pDest->spec.zColumnSep = strdup(pSrc->spec.zColumnSep); |
| 2351 | } |
| 2352 | if( pDest->spec.zRowSep ){ |
| 2353 | pDest->spec.zRowSep = strdup(pSrc->spec.zRowSep); |
| 2354 | } |
| 2355 | if( pDest->spec.zTableName ){ |
| 2356 | pDest->spec.zTableName = strdup(pSrc->spec.zTableName); |
| 2357 | } |
| 2358 | if( pDest->spec.zNull ){ |
| 2359 | pDest->spec.zNull = strdup(pSrc->spec.zNull); |
| 2360 | } |
| 2361 | if( pDest->spec.zFpFmt ){ |
| 2362 | assert( pDest->spec.zFpFmt==pSrc->zFpFmt ); |
| 2363 | pDest->spec.zFpFmt = pDest->zFpFmt; |
| 2364 | } |
| 2365 | if( pDest->spec.zIFmt ){ |
| 2366 | assert( pDest->spec.zIFmt==pSrc->zIFmt ); |
| 2367 | pDest->spec.zIFmt = pDest->zIFmt; |
| 2368 | } |
| 2369 | } |
| 2370 | |
| 2371 | /* |
| 2372 | ** Set a string value to a copy of the zNew string in memory |
| 2373 | ** obtained from system malloc(). |
| 2374 | */ |
| 2375 | static void modeSetStr(char **az, const char *zNew){ |
| 2376 | free(*az); |
| 2377 | if( zNew==0 ){ |
| 2378 | *az = 0; |
| 2379 | }else{ |
| 2380 | size_t n = strlen(zNew); |
| 2381 | *az = malloc( n+1 ); |
| 2382 | if( *az ){ |
| 2383 | memcpy(*az, zNew, n+1 ); |
| 2384 | } |
| 2385 | } |
| 2386 | } |
| 2387 | |
| 2388 | /* Forward reference */ |
| 2389 | static int pickStr(const char *zArg, char **pzErr, ...); |
| 2390 | |
| 2391 | /* |
| 2392 | ** Clamp a user-supplied value into the range 0..32767 or |
| 2393 | ** 0..2147483647 |
| 2394 | */ |
| 2395 | static short int modeClamp16(i64 x){ |
| 2396 | if( x<0 ) x = 0; |
| 2397 | if( x>0x7fff ) x = 0x7fff; |
| 2398 | return (short int)x; |
| 2399 | } |
| 2400 | static int modeClamp32(i64 x){ |
| 2401 | if( x<0 ) x = 0; |
| 2402 | if( x>0x7fffffff ) x = 0x7fffffff; |
| 2403 | return (int)x; |
| 2404 | } |
| 2405 | |
| 2406 | /* |
| 2407 | ** Change the limits on the display mode. Return 0 on |
| 2408 | ** success. Return non-zero if zArg is mis-formatted. |
| 2409 | ** |
| 2410 | ** Valid arguments: |
| 2411 | ** |
| 2412 | ** "on" Default limits |
| 2413 | ** "off" All limits turned off |
| 2414 | ** L,C Line and Characters limits set |
| 2415 | ** L,C,T Line, Character, and Title limits set |
| 2416 | ** |
| 2417 | ** Anything else returns non-zero |
| 2418 | */ |
| 2419 | static int modeSetLimit(ShellState *p, const char *zArg){ |
| 2420 | int k = zArg==0 ? 1 : pickStr(zArg,0,"on","off",""); |
| 2421 | if( k==0 ){ |
| 2422 | p->mode.spec.nLineLimit = DFLT_LINE_LIMIT; |
| 2423 | p->mode.spec.nCharLimit = DFLT_CHAR_LIMIT; |
| 2424 | p->mode.spec.nTitleLimit = DFLT_TITLE_LIMIT; |
| 2425 | }else if( k==1 ){ |
| 2426 | p->mode.spec.nLineLimit = 0; |
| 2427 | p->mode.spec.nCharLimit = 0; |
| 2428 | p->mode.spec.nTitleLimit = 0; |
| 2429 | }else{ |
| 2430 | int L, C, T = 0; |
| 2431 | int nNum = sscanf(zArg, "%d,%d,%d", &L, &C, &T); |
| 2432 | if( nNum<2 || L<0 || C<0 || T<0) return 1; |
| 2433 | p->mode.spec.nLineLimit = modeClamp16(L); |
| 2434 | p->mode.spec.nCharLimit = C; |
| 2435 | if( nNum==3 ) p->mode.spec.nTitleLimit = modeClamp16(T); |
| 2436 | } |
| 2437 | return 0; |
| 2438 | } |
| 2439 | |
| 2440 | /* |
| 2441 | ** Change the mode to eMode |
| 2442 | */ |
| 2443 | static void modeChange(ShellState *p, unsigned char eMode){ |
| 2444 | const ModeInfo *pI; |
| 2445 | if( eMode<ArraySize(aModeInfo) ){ |
| 2446 | Mode *pM = &p->mode; |
| 2447 | pI = &aModeInfo[eMode]; |
| 2448 | pM->eMode = eMode; |
| 2449 | if( pI->eCSep ) modeSetStr(&pM->spec.zColumnSep, aModeStr[pI->eCSep]); |
| 2450 | if( pI->eRSep ) modeSetStr(&pM->spec.zRowSep, aModeStr[pI->eRSep]); |
| 2451 | if( pI->eNull ) modeSetStr(&pM->spec.zNull, aModeStr[pI->eNull]); |
| 2452 | pM->spec.eText = pI->eText; |
| 2453 | pM->spec.eBlob = pI->eBlob; |
| 2454 | if( (pM->mFlags & MFLG_HDR)==0 ){ |
| 2455 | pM->spec.bTitles = pI->bHdr; |
| 2456 | } |
| 2457 | pM->spec.eTitle = pI->eHdr; |
| 2458 | if( pI->mFlg & 0x01 ){ |
| 2459 | pM->spec.bBorder = QRF_No; |
| 2460 | }else{ |
| 2461 | pM->spec.bBorder = QRF_Auto; |
| 2462 | } |
| 2463 | if( pI->mFlg & 0x02 ){ |
| 2464 | pM->spec.bSplitColumn = QRF_Yes; |
| 2465 | pM->bAutoScreenWidth = 1; |
| 2466 | }else{ |
| 2467 | pM->spec.bSplitColumn = QRF_No; |
| 2468 | } |
| 2469 | if( pI->mFlg & 0x04 ){ |
| 2470 | pM->spec.bRowCount = QRF_Yes; |
| 2471 | }else{ |
| 2472 | pM->spec.bRowCount = QRF_No; |
| 2473 | } |
| 2474 | }else if( eMode>=MODE_USER && eMode-MODE_USER<p->nSavedModes ){ |
| 2475 | modeFree(&p->mode); |
| 2476 | modeDup(&p->mode, &p->aSavedModes[eMode-MODE_USER].mode); |
| 2477 | }else if( eMode==MODE_BATCH ){ |
| 2478 | u8 mFlags = p->mode.mFlags; |
| 2479 | modeFree(&p->mode); |
| 2480 | modeChange(p, MODE_List); |
| 2481 | modeSetLimit(p, "off"); |
| 2482 | p->mode.mFlags = mFlags; |
| 2483 | }else if( eMode==MODE_TTY ){ |
| 2484 | u8 mFlags = p->mode.mFlags; |
| 2485 | modeFree(&p->mode); |
| 2486 | modeChange(p, MODE_QBox); |
| 2487 | p->mode.bAutoScreenWidth = 1; |
| 2488 | p->mode.spec.eText = QRF_TEXT_Relaxed; |
| 2489 | p->mode.spec.nCharLimit = DFLT_CHAR_LIMIT; |
| 2490 | p->mode.spec.nLineLimit = DFLT_LINE_LIMIT; |
| 2491 | p->mode.spec.bTextJsonb = QRF_Yes; |
| 2492 | p->mode.spec.nTitleLimit = DFLT_TITLE_LIMIT; |
| 2493 | p->mode.spec.nMultiInsert = DFLT_MULTI_INSERT; |
| 2494 | p->mode.mFlags = mFlags; |
| 2495 | } |
| 2496 | } |
| 2497 | |
| 2498 | /* |
| 2499 | ** Set the mode to the default. It assumed that the mode has |
| 2500 | ** already been freed and zeroed prior to calling this routine. |
| 2501 | */ |
| 2502 | static void modeDefault(ShellState *p){ |
| 2503 | p->mode.spec.iVersion = 2; |
| 2504 | p->mode.autoExplain = 1; |
| 2505 | if( (stdin_is_interactive || stdout_is_console) |
| 2506 | && SQLITE_SHELL_EDITION>=20260409 |
| 2507 | ){ |
| 2508 | modeChange(p, MODE_TTY); |
| 2509 | }else{ |
| 2510 | modeChange(p, MODE_BATCH); |
| 2511 | } |
| 2512 | } |
| 2513 | |
| 2514 | /* |
| 2515 | ** Find the number of a display mode given its name. Return -1 if |
| 2516 | ** the name does not match any mode. |
| 2517 | ** |
| 2518 | ** Saved modes are also searched if p!=NULL. The number returned |
| 2519 | ** for a saved mode is the index into the p->aSavedModes[] array |
| 2520 | ** plus MODE_USER. |
| 2521 | ** |
| 2522 | ** Two special mode names are also available: "batch" and "tty". |
| 2523 | ** evaluate to the default mode for batch operation and interactive |
| 2524 | ** operation on a TTY, respectively. |
| 2525 | */ |
| 2526 | static int modeFind(ShellState *p, const char *zName){ |
| 2527 | int i; |
| 2528 | for(i=0; i<ArraySize(aModeInfo); i++){ |
| 2529 | if( cli_strcmp(aModeInfo[i].zName,zName)==0 ) return i; |
| 2530 | } |
| 2531 | for(i=0; i<p->nSavedModes; i++){ |
| 2532 | if( cli_strcmp(p->aSavedModes[i].zTag,zName)==0 ) return i+MODE_USER; |
| 2533 | } |
| 2534 | if( strcmp(zName,"batch")==0 ) return MODE_BATCH; |
| 2535 | if( strcmp(zName,"tty")==0 ) return MODE_TTY; |
| 2536 | return -1; |
| 2537 | } |
| 2538 | |
| 2539 | /* |
| 2540 | ** Save or restore the current output mode |
| 2541 | */ |
| 2542 | static void modePush(ShellState *p){ |
| 2543 | p->aModeStack = realloc(p->aModeStack, sizeof(Mode)*(1+p->nModeStack)); |
| 2544 | shell_check_oom(p->aModeStack); |
| 2545 | modeDup(&p->aModeStack[p->nModeStack], &p->mode); |
| 2546 | p->nModeStack++; |
| 2547 | } |
| 2548 | static void modePop(ShellState *p){ |
| 2549 | if( p->nModeStack ){ |
| 2550 | modeFree(&p->mode); |
| 2551 | p->nModeStack--; |
| 2552 | memcpy(&p->mode, &p->aModeStack[p->nModeStack], sizeof(Mode)); |
| 2553 | memset(&p->aModeStack[p->nModeStack], 0, sizeof(Mode)); |
| 2554 | } |
| 2555 | } |
| 2556 | |
| 2557 | /* |
| 2558 | ** A callback for the sqlite3_log() interface. |
| 2559 | */ |
| 2560 | static void shellLog(void *pArg, int iErrCode, const char *zMsg){ |
| 2561 | ShellState *p = (ShellState*)pArg; |
| 2562 | if( p->pLog==0 ) return; |
| 2563 | cli_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg); |
| 2564 | fflush(p->pLog); |
| 2565 | } |
| 2566 | |
| 2567 | /* |
| 2568 | ** SQL function: shell_putsnl(X) |
| 2569 | ** |
| 2570 | ** For use internally and for debugging and testing only. This function |
| 2571 | ** is subject to change or removal in future versions. |
| 2572 | ** |
| 2573 | ** Write the text X to the screen (or whatever output is being directed) |
| 2574 | ** adding a newline at the end, and then return X. |
| 2575 | */ |
| 2576 | static void shellPutsFunc( |
| 2577 | sqlite3_context *pCtx, |
| 2578 | int nVal, |
| 2579 | sqlite3_value **apVal |
| 2580 | ){ |
| 2581 | ShellState *p = (ShellState*)sqlite3_user_data(pCtx); |
| 2582 | (void)nVal; |
| 2583 | cli_printf(p->out, "%s\n", sqlite3_value_text(apVal[0])); |
| 2584 | sqlite3_result_value(pCtx, apVal[0]); |
| 2585 | } |
| 2586 | |
| 2587 | /* |
| 2588 | ** Compute the name of the location of an input error in memory |
| 2589 | ** obtained from sqlite3_malloc(). |
| 2590 | */ |
| 2591 | static char *shellErrorLocation(ShellState *p){ |
| 2592 | char *zLoc; |
| 2593 | if( p->zErrPrefix ){ |
| 2594 | zLoc = sqlite3_mprintf("%s", p->zErrPrefix); |
| 2595 | }else if( p->zInFile==0 || strcmp(p->zInFile,"<stdin>")==0){ |
| 2596 | zLoc = sqlite3_mprintf("line %lld:", p->lineno); |
| 2597 | }else{ |
| 2598 | zLoc = sqlite3_mprintf("%s:%lld:", p->zInFile, p->lineno); |
| 2599 | } |
| 2600 | return zLoc; |
| 2601 | } |
| 2602 | |
| 2603 | /* |
| 2604 | ** If in safe mode, print an error message described by the arguments |
| 2605 | ** and exit immediately. |
| 2606 | */ |
| 2607 | static void failIfSafeMode( |
| 2608 | ShellState *p, |
| 2609 | const char *zErrMsg, |
| 2610 | ... |
| 2611 | ){ |
| 2612 | if( p->bSafeMode ){ |
| 2613 | va_list ap; |
| 2614 | char *zMsg; |
| 2615 | char *zLoc = shellErrorLocation(p); |
| 2616 | va_start(ap, zErrMsg); |
| 2617 | zMsg = sqlite3_vmprintf(zErrMsg, ap); |
| 2618 | va_end(ap); |
| 2619 | cli_printf(stderr, "%s %s\n", zLoc, zMsg); |
| 2620 | cli_exit(1); |
| 2621 | } |
| 2622 | } |
| 2623 | |
| 2624 | /* |
| 2625 | ** Issue an error message from a dot-command. |
| 2626 | */ |
| 2627 | static void dotCmdError( |
| 2628 | ShellState *p, /* Shell state */ |
| 2629 | int iArg, /* Index of argument on which error occurred */ |
| 2630 | const char *zBrief, /* Brief (<20 character) error description */ |
| 2631 | const char *zDetail, /* Error details */ |
| 2632 | ... |
| 2633 | ){ |
| 2634 | FILE *out = stderr; |
| 2635 | char *zLoc = shellErrorLocation(p); |
| 2636 | if( zBrief!=0 && iArg>=0 && iArg<p->dot.nArg ){ |
| 2637 | int i = p->dot.aiOfst[iArg]; |
| 2638 | int nPrompt = strlen30(zBrief) + 5; |
| 2639 | cli_printf(out, "%s %s\n", zLoc, p->dot.zOrig); |
| 2640 | if( i > nPrompt ){ |
| 2641 | cli_printf(out, "%s %*s%s ---^\n", zLoc, 1+i-nPrompt, "", zBrief); |
| 2642 | }else{ |
| 2643 | cli_printf(out, "%s %*s^--- %s\n", zLoc, i, "", zBrief); |
| 2644 | } |
| 2645 | } |
| 2646 | if( zDetail ){ |
| 2647 | char *zMsg; |
| 2648 | va_list ap; |
| 2649 | va_start(ap, zDetail); |
| 2650 | zMsg = sqlite3_vmprintf(zDetail,ap); |
| 2651 | va_end(ap); |
| 2652 | cli_printf(out,"%s %s\n", zLoc, zMsg); |
| 2653 | sqlite3_free(zMsg); |
| 2654 | } |
| 2655 | sqlite3_free(zLoc); |
| 2656 | } |
| 2657 | |
| 2658 | |
| 2659 | /* |
| 2660 | ** SQL function: edit(VALUE) |
| 2661 | ** edit(VALUE,EDITOR) |
| 2662 | ** |
| 2663 | ** These steps: |
| 2664 | ** |
| 2665 | ** (1) Write VALUE into a temporary file. |
| 2666 | ** (2) Run program EDITOR on that temporary file. |
| 2667 | ** (3) Read the temporary file back and return its content as the result. |
| 2668 | ** (4) Delete the temporary file |
| 2669 | ** |
| 2670 | ** If the EDITOR argument is omitted, use the value in the VISUAL |
| 2671 | ** environment variable. If still there is no EDITOR, throw an error. |
| 2672 | ** |
| 2673 | ** Also throw an error if the EDITOR program returns a non-zero exit code. |
| 2674 | */ |
| 2675 | #ifndef SQLITE_NOHAVE_SYSTEM |
| 2676 | static void editFunc( |
| 2677 | sqlite3_context *context, |
| 2678 | int argc, |
| 2679 | sqlite3_value **argv |
| 2680 | ){ |
| 2681 | const char *zEditor; |
| 2682 | char *zTempFile = 0; |
| 2683 | sqlite3 *db; |
| 2684 | char *zCmd = 0; |
| 2685 | int bBin; |
| 2686 | int rc; |
| 2687 | int hasCRLF = 0; |
| 2688 | FILE *f = 0; |
| 2689 | sqlite3_int64 sz; |
| 2690 | sqlite3_int64 x; |
| 2691 | unsigned char *p = 0; |
| 2692 | |
| 2693 | if( argc==2 ){ |
| 2694 | zEditor = (const char*)sqlite3_value_text(argv[1]); |
| 2695 | }else{ |
| 2696 | zEditor = getenv("VISUAL"); |
| 2697 | } |
| 2698 | if( zEditor==0 ){ |
| 2699 | sqlite3_result_error(context, "no editor for edit()", -1); |
| 2700 | return; |
| 2701 | } |
| 2702 | if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ |
| 2703 | sqlite3_result_error(context, "NULL input to edit()", -1); |
| 2704 | return; |
| 2705 | } |
| 2706 | db = sqlite3_context_db_handle(context); |
| 2707 | zTempFile = 0; |
| 2708 | sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile); |
| 2709 | if( zTempFile==0 ){ |
| 2710 | sqlite3_uint64 r = 0; |
| 2711 | sqlite3_randomness(sizeof(r), &r); |
| 2712 | zTempFile = sqlite3_mprintf("temp%llx", r); |
| 2713 | if( zTempFile==0 ){ |
| 2714 | sqlite3_result_error_nomem(context); |
| 2715 | return; |
| 2716 | } |
| 2717 | } |
| 2718 | bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB; |
| 2719 | /* When writing the file to be edited, do \n to \r\n conversions on systems |
| 2720 | ** that want \r\n line endings */ |
| 2721 | f = sqlite3_fopen(zTempFile, bBin ? "wb" : "w"); |
| 2722 | if( f==0 ){ |
| 2723 | sqlite3_result_error(context, "edit() cannot open temp file", -1); |
| 2724 | goto edit_func_end; |
| 2725 | } |
| 2726 | sz = sqlite3_value_bytes(argv[0]); |
| 2727 | if( bBin ){ |
| 2728 | x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f); |
| 2729 | }else{ |
| 2730 | const char *z = (const char*)sqlite3_value_text(argv[0]); |
| 2731 | /* Remember whether or not the value originally contained \r\n */ |
| 2732 | if( z && strstr(z,"\r\n")!=0 ) hasCRLF = 1; |
| 2733 | x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f); |
| 2734 | } |
| 2735 | fclose(f); |
| 2736 | f = 0; |
| 2737 | if( x!=sz ){ |
| 2738 | sqlite3_result_error(context, "edit() could not write the whole file", -1); |
| 2739 | goto edit_func_end; |
| 2740 | } |
| 2741 | zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile); |
| 2742 | if( zCmd==0 ){ |
| 2743 | sqlite3_result_error_nomem(context); |
| 2744 | goto edit_func_end; |
| 2745 | } |
| 2746 | rc = system(zCmd); |
| 2747 | sqlite3_free(zCmd); |
| 2748 | if( rc ){ |
| 2749 | sqlite3_result_error(context, "EDITOR returned non-zero", -1); |
| 2750 | goto edit_func_end; |
| 2751 | } |
| 2752 | f = sqlite3_fopen(zTempFile, "rb"); |
| 2753 | if( f==0 ){ |
| 2754 | sqlite3_result_error(context, |
| 2755 | "edit() cannot reopen temp file after edit", -1); |
| 2756 | goto edit_func_end; |
| 2757 | } |
| 2758 | fseek(f, 0, SEEK_END); |
| 2759 | sz = ftell(f); |
| 2760 | rewind(f); |
| 2761 | p = sqlite3_malloc64( sz+1 ); |
| 2762 | if( p==0 ){ |
| 2763 | sqlite3_result_error_nomem(context); |
| 2764 | goto edit_func_end; |
| 2765 | } |
| 2766 | x = fread(p, 1, (size_t)sz, f); |
| 2767 | fclose(f); |
| 2768 | f = 0; |
| 2769 | if( x!=sz ){ |
| 2770 | sqlite3_result_error(context, "could not read back the whole file", -1); |
| 2771 | goto edit_func_end; |
| 2772 | } |
| 2773 | if( bBin ){ |
| 2774 | sqlite3_result_blob64(context, p, sz, sqlite3_free); |
| 2775 | }else{ |
| 2776 | sqlite3_int64 i, j; |
| 2777 | if( hasCRLF ){ |
| 2778 | /* If the original contains \r\n then do no conversions back to \n */ |
| 2779 | }else{ |
| 2780 | /* If the file did not originally contain \r\n then convert any new |
| 2781 | ** \r\n back into \n */ |
| 2782 | p[sz] = 0; |
| 2783 | for(i=j=0; i<sz; i++){ |
| 2784 | if( p[i]=='\r' && p[i+1]=='\n' ) i++; |
| 2785 | p[j++] = p[i]; |
| 2786 | } |
| 2787 | sz = j; |
| 2788 | p[sz] = 0; |
| 2789 | } |
| 2790 | sqlite3_result_text64(context, (const char*)p, sz, |
| 2791 | sqlite3_free, SQLITE_UTF8); |
| 2792 | } |
| 2793 | p = 0; |
| 2794 | |
| 2795 | edit_func_end: |
| 2796 | if( f ) fclose(f); |
| 2797 | unlink(zTempFile); |
| 2798 | sqlite3_free(zTempFile); |
| 2799 | sqlite3_free(p); |
| 2800 | } |
| 2801 | #endif /* SQLITE_NOHAVE_SYSTEM */ |
| 2802 | |
| 2803 | /* |
| 2804 | ** Set output mode to text or binary for Windows. |
| 2805 | */ |
| 2806 | static void setCrlfMode(ShellState *p){ |
| 2807 | #ifdef _WIN32 |
| 2808 | if( p->mode.mFlags & MFLG_CRLF ){ |
| 2809 | sqlite3_fsetmode(p->out, _O_TEXT); |
| 2810 | }else{ |
| 2811 | sqlite3_fsetmode(p->out, _O_BINARY); |
| 2812 | } |
| 2813 | #else |
| 2814 | UNUSED_PARAMETER(p); |
| 2815 | #endif |
| 2816 | } |
| 2817 | |
| 2818 | /* |
| 2819 | ** Find earliest of chars within s specified in zAny. |
| 2820 | ** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated. |
| 2821 | */ |
| 2822 | static const char *anyOfInStr(const char *s, const char *zAny, size_t ns){ |
| 2823 | const char *pcFirst = 0; |
| 2824 | if( ns == ~(size_t)0 ) ns = strlen(s); |
| 2825 | while(*zAny){ |
| 2826 | const char *pc = (const char*)memchr(s, *zAny&0xff, ns); |
| 2827 | if( pc ){ |
| 2828 | pcFirst = pc; |
| 2829 | ns = pcFirst - s; |
| 2830 | } |
| 2831 | ++zAny; |
| 2832 | } |
| 2833 | return pcFirst; |
| 2834 | } |
| 2835 | |
| 2836 | /* Skip over as much z[] input char sequence as is valid UTF-8, |
| 2837 | ** limited per nAccept char's or whole characters and containing |
| 2838 | ** no char cn such that ((1<<cn) & ccm)!=0. On return, the |
| 2839 | ** sequence z:return (inclusive:exclusive) is validated UTF-8. |
| 2840 | ** Limit: nAccept>=0 => char count, nAccept<0 => character |
| 2841 | */ |
| 2842 | const char *zSkipValidUtf8(const char *z, int nAccept, long ccm){ |
| 2843 | int ng = (nAccept<0)? -nAccept : 0; |
| 2844 | const char *pcLimit = (nAccept>=0)? z+nAccept : 0; |
| 2845 | assert(z!=0); |
| 2846 | while( (pcLimit)? (z<pcLimit) : (ng-- != 0) ){ |
| 2847 | unsigned char c = *(u8*)z; |
| 2848 | if( c<0x7f ){ |
| 2849 | if( ccm != 0L && c < 0x20 && ((1L<<c) & ccm) != 0 ) return z; |
| 2850 | ++z; /* ASCII */ |
| 2851 | }else if( (c & 0xC0) != 0xC0 ) return z; /* not a lead byte */ |
| 2852 | else{ |
| 2853 | const char *zt = z+1; /* Got lead byte, look at trail bytes.*/ |
| 2854 | do{ |
| 2855 | if( pcLimit && zt >= pcLimit ) return z; |
| 2856 | else{ |
| 2857 | char ct = *zt++; |
| 2858 | if( ct==0 || (zt-z)>4 || (ct & 0xC0)!=0x80 ){ |
| 2859 | /* Trailing bytes are too few, too many, or invalid. */ |
| 2860 | return z; |
| 2861 | } |
| 2862 | } |
| 2863 | } while( ((c <<= 1) & 0x40) == 0x40 ); /* Eat lead byte's count. */ |
| 2864 | z = zt; |
| 2865 | } |
| 2866 | } |
| 2867 | return z; |
| 2868 | } |
| 2869 | |
| 2870 | |
| 2871 | /* |
| 2872 | ** Output the given string as a quoted according to C or TCL quoting rules. |
| 2873 | */ |
| 2874 | static void output_c_string(FILE *out, const char *z){ |
| 2875 | char c; |
| 2876 | static const char *zq = "\""; |
| 2877 | static long ctrlMask = ~0L; |
| 2878 | static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */ |
| 2879 | char ace[3] = "\\?"; |
| 2880 | char cbsSay; |
| 2881 | cli_puts(zq, out); |
| 2882 | if( z==0 ) z = ""; |
| 2883 | while( *z!=0 ){ |
| 2884 | const char *pcDQBSRO = anyOfInStr(z, zDQBSRO, ~(size_t)0); |
| 2885 | const char *pcPast = zSkipValidUtf8(z, INT_MAX, ctrlMask); |
| 2886 | const char *pcEnd = (pcDQBSRO && pcDQBSRO < pcPast)? pcDQBSRO : pcPast; |
| 2887 | if( pcEnd > z ){ |
| 2888 | cli_printf(out, "%.*s", (int)(pcEnd-z), z); |
| 2889 | } |
| 2890 | if( (c = *pcEnd)==0 ) break; |
| 2891 | ++pcEnd; |
| 2892 | switch( c ){ |
| 2893 | case '\\': case '"': |
| 2894 | cbsSay = (char)c; |
| 2895 | break; |
| 2896 | case '\t': cbsSay = 't'; break; |
| 2897 | case '\n': cbsSay = 'n'; break; |
| 2898 | case '\r': cbsSay = 'r'; break; |
| 2899 | case '\f': cbsSay = 'f'; break; |
| 2900 | default: cbsSay = 0; break; |
| 2901 | } |
| 2902 | if( cbsSay ){ |
| 2903 | ace[1] = cbsSay; |
| 2904 | cli_puts(ace, out); |
| 2905 | }else if( !isprint(c&0xff) ){ |
| 2906 | cli_printf(out, "\\%03o", c&0xff); |
| 2907 | }else{ |
| 2908 | ace[1] = (char)c; |
| 2909 | cli_puts(ace+1, out); |
| 2910 | } |
| 2911 | z = pcEnd; |
| 2912 | } |
| 2913 | cli_puts(zq, out); |
| 2914 | } |
| 2915 | |
| 2916 | /* Encode input string z[] as a C-language string literal and |
| 2917 | ** append it to the sqlite3_str. If z is NULL render and empty string. |
| 2918 | */ |
| 2919 | static void append_c_string(sqlite3_str *out, const char *z){ |
| 2920 | char c; |
| 2921 | static const char *zq = "\""; |
| 2922 | static long ctrlMask = ~0L; |
| 2923 | static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */ |
| 2924 | char ace[3] = "\\?"; |
| 2925 | char cbsSay; |
| 2926 | if( z==0 ) z = ""; |
| 2927 | sqlite3_str_appendall(out,zq); |
| 2928 | while( *z!=0 ){ |
| 2929 | const char *pcDQBSRO = anyOfInStr(z, zDQBSRO, ~(size_t)0); |
| 2930 | const char *pcPast = zSkipValidUtf8(z, INT_MAX, ctrlMask); |
| 2931 | const char *pcEnd = (pcDQBSRO && pcDQBSRO < pcPast)? pcDQBSRO : pcPast; |
| 2932 | if( pcEnd > z ){ |
| 2933 | sqlite3_str_appendf(out, "%.*s", (int)(pcEnd-z), z); |
| 2934 | } |
| 2935 | if( (c = *pcEnd)==0 ) break; |
| 2936 | ++pcEnd; |
| 2937 | switch( c ){ |
| 2938 | case '\\': case '"': |
| 2939 | cbsSay = (char)c; |
| 2940 | break; |
| 2941 | case '\t': cbsSay = 't'; break; |
| 2942 | case '\n': cbsSay = 'n'; break; |
| 2943 | case '\r': cbsSay = 'r'; break; |
| 2944 | case '\f': cbsSay = 'f'; break; |
| 2945 | default: cbsSay = 0; break; |
| 2946 | } |
| 2947 | if( cbsSay ){ |
| 2948 | ace[1] = cbsSay; |
| 2949 | sqlite3_str_appendall(out,ace); |
| 2950 | }else if( !isprint(c&0xff) ){ |
| 2951 | sqlite3_str_appendf(out, "\\%03o", c&0xff); |
| 2952 | }else{ |
| 2953 | ace[1] = (char)c; |
| 2954 | sqlite3_str_appendall(out, ace+1); |
| 2955 | } |
| 2956 | z = pcEnd; |
| 2957 | } |
| 2958 | sqlite3_str_appendall(out, zq); |
| 2959 | } |
| 2960 | |
| 2961 | /* |
| 2962 | ** This routine runs when the user presses Ctrl-C |
| 2963 | */ |
| 2964 | static void interrupt_handler(int NotUsed){ |
| 2965 | UNUSED_PARAMETER(NotUsed); |
| 2966 | if( ++seenInterrupt>1 ) cli_exit(1); |
| 2967 | if( globalDb ) sqlite3_interrupt(globalDb); |
| 2968 | } |
| 2969 | /* No-masking interrupts (SIGTERM or SIGHUP) */ |
| 2970 | static void sigterm_handler(int NotUsed){ |
| 2971 | UNUSED_PARAMETER(NotUsed); |
| 2972 | cli_exit(1); |
| 2973 | } |
| 2974 | |
| 2975 | /* Try to determine the screen width. Use the default if unable. |
| 2976 | */ |
| 2977 | int shellScreenWidth(void){ |
| 2978 | if( stdout_tty_width>0 ){ |
| 2979 | return stdout_tty_width; |
| 2980 | }else{ |
| 2981 | #if defined(TIOCGSIZE) |
| 2982 | struct ttysize ts; |
| 2983 | if( ioctl(STDIN_FILENO, TIOCGSIZE, &ts)>=0 |
| 2984 | || ioctl(STDOUT_FILENO, TIOCGSIZE, &ts)>=0 |
| 2985 | || ioctl(STDERR_FILENO, TIOCGSIZE, &ts)>=0 |
| 2986 | ){ |
| 2987 | return ts.ts_cols; |
| 2988 | } |
| 2989 | #elif defined(TIOCGWINSZ) |
| 2990 | struct winsize ws; |
| 2991 | if( ioctl(STDIN_FILENO, TIOCGWINSZ, &ws)>=0 |
| 2992 | || ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws)>=0 |
| 2993 | || ioctl(STDERR_FILENO, TIOCGWINSZ, &ws)>=0 |
| 2994 | ){ |
| 2995 | return ws.ws_col; |
| 2996 | } |
| 2997 | #elif defined(_WIN32) |
| 2998 | CONSOLE_SCREEN_BUFFER_INFO csbi; |
| 2999 | if( GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi) |
| 3000 | || GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi) |
| 3001 | || GetConsoleScreenBufferInfo(GetStdHandle(STD_INPUT_HANDLE), &csbi) |
| 3002 | ){ |
| 3003 | return csbi.srWindow.Right - csbi.srWindow.Left + 1; |
| 3004 | } |
| 3005 | #endif |
| 3006 | #define DEFAULT_SCREEN_WIDTH 80 |
| 3007 | return DEFAULT_SCREEN_WIDTH; |
| 3008 | } |
| 3009 | } |
| 3010 | |
| 3011 | #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) |
| 3012 | /* |
| 3013 | ** This routine runs for console events (e.g. Ctrl-C) on Win32 |
| 3014 | */ |
| 3015 | static BOOL WINAPI ConsoleCtrlHandler( |
| 3016 | DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */ |
| 3017 | ){ |
| 3018 | if( dwCtrlType==CTRL_C_EVENT ){ |
| 3019 | interrupt_handler(0); |
| 3020 | return TRUE; |
| 3021 | } |
| 3022 | return FALSE; |
| 3023 | } |
| 3024 | #endif |
| 3025 | |
| 3026 | #ifndef SQLITE_OMIT_AUTHORIZATION |
| 3027 | /* |
| 3028 | ** This authorizer runs in safe mode. |
| 3029 | */ |
| 3030 | static int safeModeAuth( |
| 3031 | void *pClientData, |
| 3032 | int op, |
| 3033 | const char *zA1, |
| 3034 | const char *zA2, |
| 3035 | const char *zA3, |
| 3036 | const char *zA4 |
| 3037 | ){ |
| 3038 | ShellState *p = (ShellState*)pClientData; |
| 3039 | static const char *azProhibitedFunctions[] = { |
| 3040 | "edit", |
| 3041 | "fts3_tokenizer", |
| 3042 | "load_extension", |
| 3043 | "readfile", |
| 3044 | "realpath", |
| 3045 | "writefile", |
| 3046 | "zipfile", |
| 3047 | "zipfile_cds", |
| 3048 | }; |
| 3049 | UNUSED_PARAMETER(zA1); |
| 3050 | UNUSED_PARAMETER(zA3); |
| 3051 | UNUSED_PARAMETER(zA4); |
| 3052 | switch( op ){ |
| 3053 | case SQLITE_ATTACH: { |
| 3054 | #ifndef SQLITE_SHELL_FIDDLE |
| 3055 | /* In WASM builds the filesystem is a virtual sandbox, so |
| 3056 | ** there's no harm in using ATTACH. */ |
| 3057 | failIfSafeMode(p, "cannot run ATTACH in safe mode"); |
| 3058 | #endif |
| 3059 | break; |
| 3060 | } |
| 3061 | case SQLITE_FUNCTION: { |
| 3062 | int i; |
| 3063 | for(i=0; i<ArraySize(azProhibitedFunctions); i++){ |
| 3064 | if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){ |
| 3065 | failIfSafeMode(p, "cannot use the %s() function in safe mode", |
| 3066 | azProhibitedFunctions[i]); |
| 3067 | } |
| 3068 | } |
| 3069 | break; |
| 3070 | } |
| 3071 | } |
| 3072 | return SQLITE_OK; |
| 3073 | } |
| 3074 | |
| 3075 | /* |
| 3076 | ** When the ".auth ON" is set, the following authorizer callback is |
| 3077 | ** invoked. It always returns SQLITE_OK. |
| 3078 | */ |
| 3079 | static int shellAuth( |
| 3080 | void *pClientData, |
| 3081 | int op, |
| 3082 | const char *zA1, |
| 3083 | const char *zA2, |
| 3084 | const char *zA3, |
| 3085 | const char *zA4 |
| 3086 | ){ |
| 3087 | ShellState *p = (ShellState*)pClientData; |
| 3088 | static const char *azAction[] = { 0, |
| 3089 | "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX", |
| 3090 | "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW", |
| 3091 | "CREATE_TRIGGER", "CREATE_VIEW", "DELETE", |
| 3092 | "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX", |
| 3093 | "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW", |
| 3094 | "DROP_TRIGGER", "DROP_VIEW", "INSERT", |
| 3095 | "PRAGMA", "READ", "SELECT", |
| 3096 | "TRANSACTION", "UPDATE", "ATTACH", |
| 3097 | "DETACH", "ALTER_TABLE", "REINDEX", |
| 3098 | "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE", |
| 3099 | "FUNCTION", "SAVEPOINT", "RECURSIVE" |
| 3100 | }; |
| 3101 | char *zResult = "OK"; |
| 3102 | int rc = SQLITE_OK; |
| 3103 | char *zMsg = sqlite3_mprintf("%s %Q %Q %Q %Q", azAction[op],zA1,zA2,zA3,zA4); |
| 3104 | if( p->zAuthDeny && sqlite3_strglob(p->zAuthDeny, zMsg)==0 ){ |
| 3105 | zResult = "DENY"; |
| 3106 | rc = SQLITE_DENY; |
| 3107 | }else if( p->zAuthIgnore && sqlite3_strglob(p->zAuthIgnore, zMsg)==0 ){ |
| 3108 | zResult = "IGNORE"; |
| 3109 | rc = SQLITE_IGNORE; |
| 3110 | } |
| 3111 | cli_printf(p->out, "authorizer: %s -> %s\n", zMsg, zResult); |
| 3112 | sqlite3_free(zMsg); |
| 3113 | if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4); |
| 3114 | return rc; |
| 3115 | } |
| 3116 | #endif |
| 3117 | |
| 3118 | /* |
| 3119 | ** Print a schema statement. This is a helper routine to dump_callback(). |
| 3120 | ** |
| 3121 | ** This routine converts some CREATE TABLE statements for shadow tables |
| 3122 | ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements. |
| 3123 | ** |
| 3124 | ** If the schema statement in z[] contains a start-of-comment and if |
| 3125 | ** sqlite3_complete() returns false, try to terminate the comment before |
| 3126 | ** printing the result. https://sqlite.org/forum/forumpost/d7be961c5c |
| 3127 | */ |
| 3128 | static void printSchemaLine(FILE *out, const char *z, const char *zTail){ |
| 3129 | if( z==0 ) return; |
| 3130 | if( zTail==0 ) return; |
| 3131 | if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){ |
| 3132 | cli_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail); |
| 3133 | }else{ |
| 3134 | cli_printf(out, "%s%s", z, zTail); |
| 3135 | } |
| 3136 | } |
| 3137 | |
| 3138 | /* |
| 3139 | ** Return true if string z[] has nothing but whitespace and comments to the |
| 3140 | ** end of the first line. |
| 3141 | */ |
| 3142 | static int wsToEol(const char *z){ |
| 3143 | int i; |
| 3144 | for(i=0; z[i]; i++){ |
| 3145 | if( z[i]=='\n' ) return 1; |
| 3146 | if( IsSpace(z[i]) ) continue; |
| 3147 | if( z[i]=='-' && z[i+1]=='-' ) return 1; |
| 3148 | return 0; |
| 3149 | } |
| 3150 | return 1; |
| 3151 | } |
| 3152 | |
| 3153 | /* |
| 3154 | ** SQL Function: shell_format_schema(SQL,FLAGS) |
| 3155 | ** |
| 3156 | ** For use internally and for debugging and testing only. This function |
| 3157 | ** is subject to change or removal in future versions. |
| 3158 | ** |
| 3159 | ** This function is internally by the CLI to assist with the |
| 3160 | ** ".schema", ".fullschema", and ".dump" commands. The first |
| 3161 | ** argument is the value from sqlite_schema.sql. The value returned |
| 3162 | ** is a modification of the input that can actually be run as SQL |
| 3163 | ** to recreate the schema object. |
| 3164 | ** |
| 3165 | ** When FLAGS is zero, this routine is a no-op. If the |
| 3166 | ** 0x01 bit of FLAGS is set, then transformations are made to implement |
| 3167 | ** ".schema --indent". |
| 3168 | */ |
| 3169 | static void shellFormatSchema( |
| 3170 | sqlite3_context *pCtx, |
| 3171 | int nVal, |
| 3172 | sqlite3_value **apVal |
| 3173 | ){ |
| 3174 | int flags; /* Value of 2nd parameter */ |
| 3175 | const char *zSql; /* Value of 1st parameter */ |
| 3176 | sqlite3_str *pOut; /* Output buffer */ |
| 3177 | char *z; /* Writable copy of zSql */ |
| 3178 | int i, j; /* Loop counters */ |
| 3179 | int nParen = 0; |
| 3180 | char cEnd = 0; |
| 3181 | char c; |
| 3182 | int nLine = 0; |
| 3183 | int isIndex; |
| 3184 | int isWhere = 0; |
| 3185 | |
| 3186 | assert( nVal==2 ); |
| 3187 | flags = sqlite3_value_int(apVal[1]); |
| 3188 | if( (flags & 0x01)==0 ){ |
| 3189 | sqlite3_result_value(pCtx, apVal[0]); |
| 3190 | return; |
| 3191 | } |
| 3192 | zSql = (const char*)sqlite3_value_text(apVal[0]); |
| 3193 | if( zSql==0 || zSql[0]==0 ){ |
| 3194 | sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); |
| 3195 | return; |
| 3196 | } |
| 3197 | if( sqlite3_strlike("CREATE VIEW%", zSql, 0)==0 |
| 3198 | || sqlite3_strlike("CREATE TRIG%", zSql, 0)==0 |
| 3199 | ){ |
| 3200 | sqlite3_result_value(pCtx, apVal[0]); |
| 3201 | return; |
| 3202 | } |
| 3203 | pOut = sqlite3_str_new(sqlite3_context_db_handle(pCtx)); |
| 3204 | isIndex = sqlite3_strlike("CREATE INDEX%", zSql, 0)==0 |
| 3205 | || sqlite3_strlike("CREATE UNIQUE INDEX%", zSql, 0)==0; |
| 3206 | z = sqlite3_mprintf("%s", zSql); |
| 3207 | if( z==0 ){ |
| 3208 | sqlite3_str_free(pOut); |
| 3209 | sqlite3_result_error_nomem(pCtx); |
| 3210 | return; |
| 3211 | } |
| 3212 | j = 0; |
| 3213 | for(i=0; IsSpace(z[i]); i++){} |
| 3214 | for(; (c = z[i])!=0; i++){ |
| 3215 | if( IsSpace(c) ){ |
| 3216 | if( z[j-1]=='\r' ) z[j-1] = '\n'; |
| 3217 | if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue; |
| 3218 | }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){ |
| 3219 | j--; |
| 3220 | } |
| 3221 | z[j++] = c; |
| 3222 | } |
| 3223 | while( j>0 && IsSpace(z[j-1]) ){ j--; } |
| 3224 | z[j] = 0; |
| 3225 | if( strlen30(z)>=79 ){ |
| 3226 | for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */ |
| 3227 | if( c==cEnd ){ |
| 3228 | cEnd = 0; |
| 3229 | }else if( cEnd!=0){ |
| 3230 | /* No-op */ |
| 3231 | }else if( c=='"' || c=='\'' || c=='`' ){ |
| 3232 | cEnd = c; |
| 3233 | }else if( c=='[' ){ |
| 3234 | cEnd = ']'; |
| 3235 | }else if( c=='-' && z[i+1]=='-' ){ |
| 3236 | cEnd = '\n'; |
| 3237 | }else if( c=='(' ){ |
| 3238 | nParen++; |
| 3239 | }else if( c==')' ){ |
| 3240 | nParen--; |
| 3241 | if( nLine>0 && nParen==0 && j>0 && !isWhere ){ |
| 3242 | sqlite3_str_append(pOut, z, j); |
| 3243 | sqlite3_str_append(pOut, "\n", 1); |
| 3244 | j = 0; |
| 3245 | } |
| 3246 | }else if( (c=='w' || c=='W') |
| 3247 | && nParen==0 && isIndex |
| 3248 | && sqlite3_strnicmp("WHERE",&z[i],5)==0 |
| 3249 | && !IsAlnum(z[i+5]) && z[i+5]!='_' ){ |
| 3250 | isWhere = 1; |
| 3251 | }else if( isWhere && (c=='A' || c=='a') |
| 3252 | && nParen==0 |
| 3253 | && sqlite3_strnicmp("AND",&z[i],3)==0 |
| 3254 | && !IsAlnum(z[i+3]) && z[i+3]!='_' ){ |
| 3255 | sqlite3_str_append(pOut, z, j); |
| 3256 | sqlite3_str_append(pOut, "\n ", 5); |
| 3257 | j = 0; |
| 3258 | } |
| 3259 | z[j++] = c; |
| 3260 | if( nParen==1 && cEnd==0 |
| 3261 | && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1))) |
| 3262 | && !isWhere |
| 3263 | ){ |
| 3264 | if( c=='\n' ) j--; |
| 3265 | sqlite3_str_append(pOut, z, j); |
| 3266 | sqlite3_str_append(pOut, "\n ", 3); |
| 3267 | j = 0; |
| 3268 | nLine++; |
| 3269 | while( IsSpace(z[i+1]) ){ i++; } |
| 3270 | } |
| 3271 | } |
| 3272 | z[j] = 0; |
| 3273 | } |
| 3274 | sqlite3_str_appendall(pOut, z); |
| 3275 | sqlite3_free(z); |
| 3276 | sqlite3_result_text(pCtx, sqlite3_str_finish(pOut), -1, sqlite3_free); |
| 3277 | } |
| 3278 | |
| 3279 | #ifndef SQLITE_OMIT_PROGRESS_CALLBACK |
| 3280 | /* |
| 3281 | ** Progress handler callback. |
| 3282 | */ |
| 3283 | static int progress_handler(void *pClientData) { |
| 3284 | ShellState *p = (ShellState*)pClientData; |
| 3285 | p->nProgress++; |
| 3286 | if( (p->flgProgress & SHELL_PROGRESS_TMOUT)!=0 |
| 3287 | && ELAPSE_TIME(p)>=p->tmProgress |
| 3288 | ){ |
| 3289 | cli_printf(p->out, "Progress timeout after %.6f seconds\n", |
| 3290 | ELAPSE_TIME(p)); |
| 3291 | return 1; |
| 3292 | } |
| 3293 | if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){ |
| 3294 | cli_printf(p->out, "Progress limit reached (%u)\n", p->nProgress); |
| 3295 | if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; |
| 3296 | if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0; |
| 3297 | return 1; |
| 3298 | } |
| 3299 | if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){ |
| 3300 | cli_printf(p->out, "Progress %u\n", p->nProgress); |
| 3301 | } |
| 3302 | return 0; |
| 3303 | } |
| 3304 | #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ |
| 3305 | |
| 3306 | /* |
| 3307 | ** This is the callback routine from sqlite3_exec() that appends all |
| 3308 | ** output onto the end of a ShellText object. |
| 3309 | */ |
| 3310 | static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){ |
| 3311 | ShellText *p = (ShellText*)pArg; |
| 3312 | int i; |
| 3313 | UNUSED_PARAMETER(az); |
| 3314 | if( azArg==0 ) return 0; |
| 3315 | if( p->n ) appendText(p, "|", 0); |
| 3316 | for(i=0; i<nArg; i++){ |
| 3317 | if( i ) appendText(p, ",", 0); |
| 3318 | if( azArg[i] ) appendText(p, azArg[i], 0); |
| 3319 | } |
| 3320 | return 0; |
| 3321 | } |
| 3322 | |
| 3323 | /* |
| 3324 | ** Generate an appropriate SELFTEST table in the main database. |
| 3325 | */ |
| 3326 | static void createSelftestTable(ShellState *p){ |
| 3327 | char *zErrMsg = 0; |
| 3328 | sqlite3_exec(p->db, |
| 3329 | "SAVEPOINT selftest_init;\n" |
| 3330 | "CREATE TABLE IF NOT EXISTS selftest(\n" |
| 3331 | " tno INTEGER PRIMARY KEY,\n" /* Test number */ |
| 3332 | " op TEXT,\n" /* Operator: memo run */ |
| 3333 | " cmd TEXT,\n" /* Command text */ |
| 3334 | " ans TEXT\n" /* Desired answer */ |
| 3335 | ");" |
| 3336 | "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n" |
| 3337 | "INSERT INTO [_shell$self](rowid,op,cmd)\n" |
| 3338 | " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n" |
| 3339 | " 'memo','Tests generated by --init');\n" |
| 3340 | "INSERT INTO [_shell$self]\n" |
| 3341 | " SELECT 'run',\n" |
| 3342 | " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql " |
| 3343 | "FROM sqlite_schema ORDER BY 2'',224))',\n" |
| 3344 | " hex(sha3_query('SELECT type,name,tbl_name,sql " |
| 3345 | "FROM sqlite_schema ORDER BY 2',224));\n" |
| 3346 | "INSERT INTO [_shell$self]\n" |
| 3347 | " SELECT 'run'," |
| 3348 | " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||" |
| 3349 | " printf('%w',name) || '\" NOT INDEXED'',224))',\n" |
| 3350 | " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n" |
| 3351 | " FROM (\n" |
| 3352 | " SELECT name FROM sqlite_schema\n" |
| 3353 | " WHERE type='table'\n" |
| 3354 | " AND name<>'selftest'\n" |
| 3355 | " AND coalesce(rootpage,0)>0\n" |
| 3356 | " )\n" |
| 3357 | " ORDER BY name;\n" |
| 3358 | "INSERT INTO [_shell$self]\n" |
| 3359 | " VALUES('run','PRAGMA integrity_check','ok');\n" |
| 3360 | "INSERT INTO selftest(tno,op,cmd,ans)" |
| 3361 | " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n" |
| 3362 | "DROP TABLE [_shell$self];" |
| 3363 | ,0,0,&zErrMsg); |
| 3364 | if( zErrMsg ){ |
| 3365 | cli_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg); |
| 3366 | sqlite3_free(zErrMsg); |
| 3367 | } |
| 3368 | sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0); |
| 3369 | } |
| 3370 | |
| 3371 | |
| 3372 | /* |
| 3373 | ** Set the destination table field of the ShellState structure to |
| 3374 | ** the name of the table given. Escape any quote characters in the |
| 3375 | ** table name. |
| 3376 | */ |
| 3377 | static void set_table_name(ShellState *p, const char *zName){ |
| 3378 | if( p->zDestTable ){ |
| 3379 | sqlite3_free(p->zDestTable); |
| 3380 | p->zDestTable = 0; |
| 3381 | } |
| 3382 | if( zName==0 ) return; |
| 3383 | p->zDestTable = sqlite3_mprintf("%s", zName); |
| 3384 | shell_check_oom(p->zDestTable); |
| 3385 | } |
| 3386 | |
| 3387 | /* |
| 3388 | ** Return a copy of the text z, obtained from sqlite3_malloc(), that is safe |
| 3389 | ** to embed inside of a C-style comment in a script of SQL statements and |
| 3390 | ** dot-commands. Newlines and other control characters are changed to spaces, |
| 3391 | ** and any end-of-comment sequence is broken up. Otherwise, text taken from |
| 3392 | ** an untrusted database (for example, a table name in an error message) |
| 3393 | ** could terminate the comment and put arbitrary SQL, or a line that begins |
| 3394 | ** with "." and so is interpreted as a dot-command, into the output. |
| 3395 | */ |
| 3396 | static char *shellSafeCommentText(const char *z){ |
| 3397 | char *zOut = sqlite3_mprintf("%s", z ? z : ""); |
| 3398 | int i; |
| 3399 | if( zOut==0 ) return 0; |
| 3400 | for(i=0; zOut[i]; i++){ |
| 3401 | unsigned char c = (unsigned char)zOut[i]; |
| 3402 | if( c<' ' || c==0x7f ){ |
| 3403 | zOut[i] = ' '; |
| 3404 | }else if( c=='/' && i>0 && zOut[i-1]=='*' ){ |
| 3405 | zOut[i] = ' '; |
| 3406 | } |
| 3407 | } |
| 3408 | return zOut; |
| 3409 | } |
| 3410 | |
| 3411 | /* |
| 3412 | ** Maybe construct two lines of text that point out the position of a |
| 3413 | ** syntax error. Return a pointer to the text, in memory obtained from |
| 3414 | ** sqlite3_malloc(). Or, if the most recent error does not involve a |
| 3415 | ** specific token that we can point to, return an empty string. |
| 3416 | ** |
| 3417 | ** In all cases, the memory returned is obtained from sqlite3_malloc64() |
| 3418 | ** and should be released by the caller invoking sqlite3_free(). |
| 3419 | */ |
| 3420 | static char *shell_error_context(const char *zSql, sqlite3 *db){ |
| 3421 | int iOffset; |
| 3422 | size_t len; |
| 3423 | char *zCode; |
| 3424 | char *zMsg; |
| 3425 | int i; |
| 3426 | if( db==0 |
| 3427 | || zSql==0 |
| 3428 | || (iOffset = sqlite3_error_offset(db))<0 |
| 3429 | || iOffset>=(int)strlen(zSql) |
| 3430 | ){ |
| 3431 | return sqlite3_mprintf(""); |
| 3432 | } |
| 3433 | while( iOffset>50 ){ |
| 3434 | iOffset--; |
| 3435 | zSql++; |
| 3436 | while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; } |
| 3437 | } |
| 3438 | len = strlen(zSql); |
| 3439 | if( len>78 ){ |
| 3440 | len = 78; |
| 3441 | while( len>0 && (zSql[len]&0xc0)==0x80 ) len--; |
| 3442 | } |
| 3443 | zCode = sqlite3_mprintf("%.*s", (int)len, zSql); |
| 3444 | shell_check_oom(zCode); |
| 3445 | for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; } |
| 3446 | if( iOffset<25 ){ |
| 3447 | zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode,iOffset,""); |
| 3448 | }else{ |
| 3449 | zMsg = sqlite3_mprintf("\n %z\n %*serror here ---^", zCode,iOffset-14,""); |
| 3450 | } |
| 3451 | return zMsg; |
| 3452 | } |
| 3453 | |
| 3454 | |
| 3455 | /* |
| 3456 | ** Execute a query statement that will generate SQL output. Print |
| 3457 | ** the result columns, comma-separated, on a line and then add a |
| 3458 | ** semicolon terminator to the end of that line. |
| 3459 | ** |
| 3460 | ** If the number of columns is 1 and that column contains text "--" |
| 3461 | ** then write the semicolon on a separate line. That way, if a |
| 3462 | ** "--" comment occurs at the end of the statement, the comment |
| 3463 | ** won't consume the semicolon terminator. |
| 3464 | */ |
| 3465 | static int run_table_dump_query( |
| 3466 | ShellState *p, /* Query context */ |
| 3467 | const char *zSelect /* SELECT statement to extract content */ |
| 3468 | ){ |
| 3469 | sqlite3_stmt *pSelect; |
| 3470 | int rc; |
| 3471 | int nResult; |
| 3472 | int i; |
| 3473 | const char *z; |
| 3474 | rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); |
| 3475 | if( rc!=SQLITE_OK || !pSelect ){ |
| 3476 | char *zContext = shell_error_context(zSelect, p->db); |
| 3477 | char *zMsg = shellSafeCommentText(sqlite3_errmsg(p->db)); |
| 3478 | cli_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", |
| 3479 | rc, zMsg, zContext); |
| 3480 | sqlite3_free(zMsg); |
| 3481 | sqlite3_free(zContext); |
| 3482 | if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; |
| 3483 | return rc; |
| 3484 | } |
| 3485 | rc = sqlite3_step(pSelect); |
| 3486 | nResult = sqlite3_column_count(pSelect); |
| 3487 | while( rc==SQLITE_ROW ){ |
| 3488 | z = (const char*)sqlite3_column_text(pSelect, 0); |
| 3489 | cli_printf(p->out, "%s", z); |
| 3490 | for(i=1; i<nResult; i++){ |
| 3491 | cli_printf(p->out, ",%s", sqlite3_column_text(pSelect, i)); |
| 3492 | } |
| 3493 | if( z==0 ) z = ""; |
| 3494 | while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; |
| 3495 | if( z[0] ){ |
| 3496 | cli_puts("\n;\n", p->out); |
| 3497 | }else{ |
| 3498 | cli_puts(";\n", p->out); |
| 3499 | } |
| 3500 | rc = sqlite3_step(pSelect); |
| 3501 | } |
| 3502 | rc = sqlite3_finalize(pSelect); |
| 3503 | if( rc!=SQLITE_OK ){ |
| 3504 | char *zMsg = shellSafeCommentText(sqlite3_errmsg(p->db)); |
| 3505 | cli_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, zMsg); |
| 3506 | sqlite3_free(zMsg); |
| 3507 | if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; |
| 3508 | } |
| 3509 | return rc; |
| 3510 | } |
| 3511 | |
| 3512 | /* |
| 3513 | ** Allocate space and save off string indicating current error. |
| 3514 | */ |
| 3515 | static char *save_err_msg( |
| 3516 | sqlite3 *db, /* Database to query */ |
| 3517 | const char *zPhase, /* When the error occurs */ |
| 3518 | int rc, /* Error code returned from API */ |
| 3519 | const char *zSql /* SQL string, or NULL */ |
| 3520 | ){ |
| 3521 | char *zErr; |
| 3522 | char *zContext; |
| 3523 | sqlite3_str *pStr = sqlite3_str_new(0); |
| 3524 | sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db)); |
| 3525 | if( rc>1 ){ |
| 3526 | sqlite3_str_appendf(pStr, " (%d)", rc); |
| 3527 | } |
| 3528 | zContext = shell_error_context(zSql, db); |
| 3529 | if( zContext ){ |
| 3530 | sqlite3_str_appendall(pStr, zContext); |
| 3531 | sqlite3_free(zContext); |
| 3532 | } |
| 3533 | zErr = sqlite3_str_finish(pStr); |
| 3534 | shell_check_oom(zErr); |
| 3535 | return zErr; |
| 3536 | } |
| 3537 | |
| 3538 | #ifdef __linux__ |
| 3539 | /* |
| 3540 | ** Attempt to display I/O stats on Linux using /proc/PID/io |
| 3541 | */ |
| 3542 | static void displayLinuxIoStats(FILE *out){ |
| 3543 | FILE *in; |
| 3544 | char z[200]; |
| 3545 | sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid()); |
| 3546 | in = sqlite3_fopen(z, "rb"); |
| 3547 | if( in==0 ) return; |
| 3548 | while( sqlite3_fgets(z, sizeof(z), in)!=0 ){ |
| 3549 | static const struct { |
| 3550 | const char *zPattern; |
| 3551 | const char *zDesc; |
| 3552 | } aTrans[] = { |
| 3553 | { "rchar: ", "Bytes received by read():" }, |
| 3554 | { "wchar: ", "Bytes sent to write():" }, |
| 3555 | { "syscr: ", "Read() system calls:" }, |
| 3556 | { "syscw: ", "Write() system calls:" }, |
| 3557 | { "read_bytes: ", "Bytes read from storage:" }, |
| 3558 | { "write_bytes: ", "Bytes written to storage:" }, |
| 3559 | { "cancelled_write_bytes: ", "Cancelled write bytes:" }, |
| 3560 | }; |
| 3561 | int i; |
| 3562 | for(i=0; i<ArraySize(aTrans); i++){ |
| 3563 | int n = strlen30(aTrans[i].zPattern); |
| 3564 | if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){ |
| 3565 | cli_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]); |
| 3566 | break; |
| 3567 | } |
| 3568 | } |
| 3569 | } |
| 3570 | fclose(in); |
| 3571 | } |
| 3572 | #endif |
| 3573 | |
| 3574 | /* |
| 3575 | ** Display a single line of status using 64-bit values. |
| 3576 | */ |
| 3577 | static void displayStatLine( |
| 3578 | FILE *out, /* Write to this channel */ |
| 3579 | char *zLabel, /* Label for this one line */ |
| 3580 | char *zFormat, /* Format for the result */ |
| 3581 | int iStatusCtrl, /* Which status to display */ |
| 3582 | int bReset /* True to reset the stats */ |
| 3583 | ){ |
| 3584 | sqlite3_int64 iCur = -1; |
| 3585 | sqlite3_int64 iHiwtr = -1; |
| 3586 | int i, nPercent; |
| 3587 | char zLine[200]; |
| 3588 | sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset); |
| 3589 | for(i=0, nPercent=0; zFormat[i]; i++){ |
| 3590 | if( zFormat[i]=='%' ) nPercent++; |
| 3591 | } |
| 3592 | if( nPercent>1 ){ |
| 3593 | sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr); |
| 3594 | }else{ |
| 3595 | sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr); |
| 3596 | } |
| 3597 | cli_printf(out, "%-36s %s\n", zLabel, zLine); |
| 3598 | } |
| 3599 | |
| 3600 | /* |
| 3601 | ** Display memory stats. |
| 3602 | */ |
| 3603 | static int display_stats( |
| 3604 | sqlite3 *db, /* Database to query */ |
| 3605 | ShellState *pArg /* Pointer to ShellState */ |
| 3606 | ){ |
| 3607 | int iCur, iHiwtr; |
| 3608 | sqlite3_int64 iCur64, iHiwtr64; |
| 3609 | FILE *out; |
| 3610 | int bReset; |
| 3611 | |
| 3612 | if( pArg==0 || pArg->out==0 ) return 0; |
| 3613 | out = pArg->out; |
| 3614 | bReset = (pArg->mStats & CLISTAT_RESET)!=0; |
| 3615 | |
| 3616 | if( pArg->pStmt && (pArg->mStats & CLISTAT_XSTMT)!=0 ){ |
| 3617 | int nCol, i, x; |
| 3618 | sqlite3_stmt *pStmt = pArg->pStmt; |
| 3619 | char z[100]; |
| 3620 | nCol = sqlite3_column_count(pStmt); |
| 3621 | cli_printf(out, "%-36s %d\n", "Number of output columns:", nCol); |
| 3622 | for(i=0; i<nCol; i++){ |
| 3623 | sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x); |
| 3624 | cli_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i)); |
| 3625 | #ifndef SQLITE_OMIT_DECLTYPE |
| 3626 | sqlite3_snprintf(30, z+x, "declared type:"); |
| 3627 | cli_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i)); |
| 3628 | #endif |
| 3629 | #ifdef SQLITE_ENABLE_COLUMN_METADATA |
| 3630 | sqlite3_snprintf(30, z+x, "database name:"); |
| 3631 | cli_printf(out, "%-36s %s\n", z, |
| 3632 | sqlite3_column_database_name(pStmt,i)); |
| 3633 | sqlite3_snprintf(30, z+x, "table name:"); |
| 3634 | cli_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i)); |
| 3635 | sqlite3_snprintf(30, z+x, "origin name:"); |
| 3636 | cli_printf(out, "%-36s %s\n", z,sqlite3_column_origin_name(pStmt,i)); |
| 3637 | #endif |
| 3638 | } |
| 3639 | } |
| 3640 | |
| 3641 | if( pArg->pStmt && (pArg->mStats & CLISTAT_VMSTEP)!=0 ){ |
| 3642 | iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset); |
| 3643 | cli_printf(out, "VM-steps: %d\n", iCur); |
| 3644 | } |
| 3645 | |
| 3646 | if( (pArg->mStats & CLISTAT_MEM)!=0 ){ |
| 3647 | displayStatLine(out, "Memory Used:", |
| 3648 | "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset); |
| 3649 | displayStatLine(out, "Number of Outstanding Allocations:", |
| 3650 | "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset); |
| 3651 | } |
| 3652 | if( (pArg->mStats & CLISTAT_XMEM)!=0 ){ |
| 3653 | if( pArg->shellFlgs & SHFLG_Pagecache ){ |
| 3654 | displayStatLine(out, "Number of Pcache Pages Used:", |
| 3655 | "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset); |
| 3656 | } |
| 3657 | displayStatLine(out, "Number of Pcache Overflow Bytes:", |
| 3658 | "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset); |
| 3659 | displayStatLine(out, "Largest Allocation:", |
| 3660 | "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset); |
| 3661 | displayStatLine(out, "Largest Pcache Allocation:", |
| 3662 | "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset); |
| 3663 | #ifdef YYTRACKMAXSTACKDEPTH |
| 3664 | displayStatLine(out, "Deepest Parser Stack:", |
| 3665 | "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset); |
| 3666 | #endif |
| 3667 | |
| 3668 | if( db ){ |
| 3669 | if( pArg->shellFlgs & SHFLG_Lookaside ){ |
| 3670 | iHiwtr = iCur = -1; |
| 3671 | sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, |
| 3672 | &iCur, &iHiwtr, bReset); |
| 3673 | cli_printf(out, |
| 3674 | "Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr); |
| 3675 | sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, |
| 3676 | &iCur, &iHiwtr, bReset); |
| 3677 | cli_printf(out, |
| 3678 | "Successful lookaside attempts: %d\n", iHiwtr); |
| 3679 | sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, |
| 3680 | &iCur, &iHiwtr, bReset); |
| 3681 | cli_printf(out, |
| 3682 | "Lookaside failures due to size: %d\n", iHiwtr); |
| 3683 | sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, |
| 3684 | &iCur, &iHiwtr, bReset); |
| 3685 | cli_printf(out, |
| 3686 | "Lookaside failures due to OOM: %d\n", iHiwtr); |
| 3687 | } |
| 3688 | iHiwtr = iCur = -1; |
| 3689 | sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); |
| 3690 | cli_printf(out, |
| 3691 | "Pager Heap Usage: %d bytes\n", iCur); |
| 3692 | iHiwtr = iCur = -1; |
| 3693 | sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); |
| 3694 | cli_printf(out, |
| 3695 | "Page cache hits: %d\n", iCur); |
| 3696 | iHiwtr = iCur = -1; |
| 3697 | sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); |
| 3698 | cli_printf(out, |
| 3699 | "Page cache misses: %d\n", iCur); |
| 3700 | iHiwtr64 = iCur64 = -1; |
| 3701 | sqlite3_db_status64(db, SQLITE_DBSTATUS_TEMPBUF_SPILL, &iCur64, &iHiwtr64, |
| 3702 | 0); |
| 3703 | iHiwtr = iCur = -1; |
| 3704 | sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); |
| 3705 | cli_printf(out, |
| 3706 | "Page cache writes: %d\n", iCur); |
| 3707 | iHiwtr = iCur = -1; |
| 3708 | sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1); |
| 3709 | cli_printf(out, |
| 3710 | "Page cache spills: %d\n", iCur); |
| 3711 | cli_printf(out, |
| 3712 | "Temporary data spilled to disk: %lld\n", iCur64); |
| 3713 | sqlite3_db_status64(db, SQLITE_DBSTATUS_TEMPBUF_SPILL, &iCur64, &iHiwtr64, |
| 3714 | 1); |
| 3715 | iHiwtr = iCur = -1; |
| 3716 | sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); |
| 3717 | cli_printf(out, |
| 3718 | "Schema Heap Usage: %d bytes\n", iCur); |
| 3719 | iHiwtr = iCur = -1; |
| 3720 | sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); |
| 3721 | cli_printf(out, |
| 3722 | "Statement Heap/Lookaside Usage: %d bytes\n", iCur); |
| 3723 | } |
| 3724 | } |
| 3725 | |
| 3726 | if( pArg->pStmt && (pArg->mStats & CLISTAT_STMT)!=0 ){ |
| 3727 | int iHit, iMiss; |
| 3728 | iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, |
| 3729 | bReset); |
| 3730 | cli_printf(out, |
| 3731 | "Fullscan Steps: %d\n", iCur); |
| 3732 | iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); |
| 3733 | cli_printf(out, |
| 3734 | "Sort Operations: %d\n", iCur); |
| 3735 | iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); |
| 3736 | cli_printf(out, |
| 3737 | "Autoindex Inserts: %d\n", iCur); |
| 3738 | iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, |
| 3739 | bReset); |
| 3740 | iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, |
| 3741 | bReset); |
| 3742 | if( iHit || iMiss ){ |
| 3743 | cli_printf(out, |
| 3744 | "Bloom filter bypass taken: %d/%d\n", iHit, iHit+iMiss); |
| 3745 | } |
| 3746 | iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset); |
| 3747 | cli_printf(out, |
| 3748 | "Reprepare operations: %d\n", iCur); |
| 3749 | iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset); |
| 3750 | cli_printf(out, |
| 3751 | "Number of times run: %d\n", iCur); |
| 3752 | iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset); |
| 3753 | cli_printf(out, |
| 3754 | "Memory used by prepared stmt: %d\n", iCur); |
| 3755 | } |
| 3756 | |
| 3757 | #ifdef __linux__ |
| 3758 | if( (pArg->mStats & CLISTAT_IO)!=0 ){ |
| 3759 | displayLinuxIoStats(pArg->out); |
| 3760 | } |
| 3761 | #endif |
| 3762 | |
| 3763 | #ifdef SQLITE_ENABLE_ZIPVFS_VTAB |
| 3764 | if( (pArg->mStats & CLISTAT_ZIPVFS)!=0 ){ |
| 3765 | /* Do not remove this machine readable comment: extra-stats-output-here */ |
| 3766 | } |
| 3767 | #endif |
| 3768 | |
| 3769 | return 0; |
| 3770 | } |
| 3771 | |
| 3772 | /* |
| 3773 | ** Disable and restore .wheretrace and .treetrace/.selecttrace settings. |
| 3774 | */ |
| 3775 | static unsigned int savedSelectTrace; |
| 3776 | static unsigned int savedWhereTrace; |
| 3777 | static void disable_debug_trace_modes(void){ |
| 3778 | unsigned int zero = 0; |
| 3779 | sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace); |
| 3780 | sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero); |
| 3781 | sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace); |
| 3782 | sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero); |
| 3783 | } |
| 3784 | static void restore_debug_trace_modes(void){ |
| 3785 | sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace); |
| 3786 | sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace); |
| 3787 | } |
| 3788 | |
| 3789 | /* Create the TEMP table used to store parameter bindings */ |
| 3790 | static void bind_table_init(ShellState *p){ |
| 3791 | int wrSchema = 0; |
| 3792 | int defensiveMode = 0; |
| 3793 | sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode); |
| 3794 | sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, (int*)0); |
| 3795 | sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema); |
| 3796 | sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, (int*)0); |
| 3797 | sqlite3_exec(p->db, |
| 3798 | "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n" |
| 3799 | " key TEXT PRIMARY KEY,\n" |
| 3800 | " value\n" |
| 3801 | ") WITHOUT ROWID;", |
| 3802 | 0, 0, 0); |
| 3803 | sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, (int*)0); |
| 3804 | sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, (int*)0); |
| 3805 | } |
| 3806 | |
| 3807 | /* |
| 3808 | ** Bind parameters on a prepared statement. |
| 3809 | ** |
| 3810 | ** Parameter bindings are taken from a TEMP table of the form: |
| 3811 | ** |
| 3812 | ** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value) |
| 3813 | ** WITHOUT ROWID; |
| 3814 | ** |
| 3815 | ** No bindings occur if this table does not exist. The name of the table |
| 3816 | ** begins with "sqlite_" so that it will not collide with ordinary application |
| 3817 | ** tables. The table must be in the TEMP schema. |
| 3818 | */ |
| 3819 | static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){ |
| 3820 | int nVar; |
| 3821 | int i; |
| 3822 | int rc; |
| 3823 | sqlite3_stmt *pQ = 0; |
| 3824 | int inTrace = 0; |
| 3825 | |
| 3826 | nVar = sqlite3_bind_parameter_count(pStmt); |
| 3827 | if( nVar==0 ) return; /* Nothing to do */ |
| 3828 | sqlite3_db_config(pArg->db, SQLITE_DBCONFIG_VDBE_TRACE, -1, &inTrace); |
| 3829 | sqlite3_db_config(pArg->db, SQLITE_DBCONFIG_VDBE_TRACE, 0, (int*)0); |
| 3830 | if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters", |
| 3831 | "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){ |
| 3832 | rc = SQLITE_NOTFOUND; |
| 3833 | pQ = 0; |
| 3834 | }else{ |
| 3835 | rc = sqlite3_prepare_v2(pArg->db, |
| 3836 | "SELECT value FROM temp.sqlite_parameters" |
| 3837 | " WHERE key=?1", -1, &pQ, 0); |
| 3838 | } |
| 3839 | for(i=1; i<=nVar; i++){ |
| 3840 | char zNum[30]; |
| 3841 | const char *zVar = sqlite3_bind_parameter_name(pStmt, i); |
| 3842 | if( zVar==0 ){ |
| 3843 | sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i); |
| 3844 | zVar = zNum; |
| 3845 | } |
| 3846 | if( inTrace ) cli_printf(pArg->out, "BIND: %s\n", zVar); |
| 3847 | sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC); |
| 3848 | if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){ |
| 3849 | sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0)); |
| 3850 | #ifdef NAN |
| 3851 | }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){ |
| 3852 | sqlite3_bind_double(pStmt, i, NAN); |
| 3853 | #endif |
| 3854 | #ifdef INFINITY |
| 3855 | }else if( sqlite3_strlike("_INF", zVar, 0)==0 ){ |
| 3856 | sqlite3_bind_double(pStmt, i, INFINITY); |
| 3857 | #endif |
| 3858 | }else if( strncmp(zVar, "$int_", 5)==0 ){ |
| 3859 | sqlite3_bind_int(pStmt, i, atoi(&zVar[5])); |
| 3860 | }else if( strncmp(zVar, "$text_", 6)==0 ){ |
| 3861 | size_t szVar = strlen(zVar); |
| 3862 | char *zBuf = sqlite3_malloc64( szVar-5 ); |
| 3863 | if( zBuf ){ |
| 3864 | memcpy(zBuf, &zVar[6], szVar-5); |
| 3865 | sqlite3_bind_text64(pStmt, i, zBuf, szVar-6, sqlite3_free, SQLITE_UTF8); |
| 3866 | } |
| 3867 | }else if( strcmp(zVar, "$TIMER")==0 ){ |
| 3868 | sqlite3_bind_double(pStmt, i, pArg->prevTimer); |
| 3869 | #ifdef SQLITE_ENABLE_CARRAY |
| 3870 | }else if( strncmp(zVar, "$carray_", 8)==0 ){ |
| 3871 | static char *azColorNames[] = { |
| 3872 | "azure", "black", "blue", "brown", "cyan", "fuchsia", "gold", |
| 3873 | "gray", "green", "indigo", "khaki", "lime", "magenta", "maroon", |
| 3874 | "navy", "olive", "orange", "pink", "purple", "red", "silver", |
| 3875 | "tan", "teal", "violet", "white", "yellow" |
| 3876 | }; |
| 3877 | static int aPrimes[] = { |
| 3878 | 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, |
| 3879 | 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 |
| 3880 | }; |
| 3881 | /* Special bindings: carray($carray_clr), carray($carray_primes) |
| 3882 | ** with --unsafe-testing: carray($carray_clr_p,26,'char*'), |
| 3883 | ** carray($carray_primes_p,26,'int32') |
| 3884 | */ |
| 3885 | if( strcmp(zVar+8,"clr")==0 ){ |
| 3886 | sqlite3_carray_bind(pStmt,i,azColorNames,26,SQLITE_CARRAY_TEXT,0); |
| 3887 | }else if( strcmp(zVar+8,"primes")==0 ){ |
| 3888 | sqlite3_carray_bind(pStmt,i,aPrimes,26,SQLITE_CARRAY_INT32,0); |
| 3889 | }else if( strcmp(zVar+8,"clr_p")==0 |
| 3890 | && ShellHasFlag(pArg,SHFLG_TestingMode) ){ |
| 3891 | sqlite3_bind_pointer(pStmt,i,azColorNames,"carray",0); |
| 3892 | }else if( strcmp(zVar+8,"primes_p")==0 |
| 3893 | && ShellHasFlag(pArg,SHFLG_TestingMode) ){ |
| 3894 | sqlite3_bind_pointer(pStmt,i,aPrimes,"carray",0); |
| 3895 | }else{ |
| 3896 | sqlite3_bind_null(pStmt, i); |
| 3897 | } |
| 3898 | #endif |
| 3899 | }else{ |
| 3900 | sqlite3_bind_null(pStmt, i); |
| 3901 | } |
| 3902 | sqlite3_reset(pQ); |
| 3903 | } |
| 3904 | sqlite3_finalize(pQ); |
| 3905 | sqlite3_db_config(pArg->db, SQLITE_DBCONFIG_VDBE_TRACE, inTrace, (int*)0); |
| 3906 | } |
| 3907 | |
| 3908 | #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION) |
| 3909 | /* |
| 3910 | ** This function is called to process SQL if the previous shell command |
| 3911 | ** was ".expert". It passes the SQL in the second argument directly to |
| 3912 | ** the sqlite3expert object. |
| 3913 | ** |
| 3914 | ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error |
| 3915 | ** code. In this case, (*pzErr) may be set to point to a buffer containing |
| 3916 | ** an English language error message. It is the responsibility of the |
| 3917 | ** caller to eventually free this buffer using sqlite3_free(). |
| 3918 | */ |
| 3919 | static int expertHandleSQL( |
| 3920 | ShellState *pState, |
| 3921 | const char *zSql, |
| 3922 | char **pzErr |
| 3923 | ){ |
| 3924 | assert( pState->expert.pExpert ); |
| 3925 | assert( pzErr==0 || *pzErr==0 ); |
| 3926 | return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr); |
| 3927 | } |
| 3928 | |
| 3929 | /* |
| 3930 | ** This function is called either to silently clean up the object |
| 3931 | ** created by the ".expert" command (if bCancel==1), or to generate a |
| 3932 | ** report from it and then clean it up (if bCancel==0). |
| 3933 | ** |
| 3934 | ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error |
| 3935 | ** code. In this case, (*pzErr) may be set to point to a buffer containing |
| 3936 | ** an English language error message. It is the responsibility of the |
| 3937 | ** caller to eventually free this buffer using sqlite3_free(). |
| 3938 | */ |
| 3939 | static int expertFinish( |
| 3940 | ShellState *pState, |
| 3941 | int bCancel, |
| 3942 | char **pzErr |
| 3943 | ){ |
| 3944 | int rc = SQLITE_OK; |
| 3945 | sqlite3expert *p = pState->expert.pExpert; |
| 3946 | FILE *out = pState->out; |
| 3947 | assert( p ); |
| 3948 | assert( bCancel || pzErr==0 || *pzErr==0 ); |
| 3949 | if( bCancel==0 ){ |
| 3950 | int bVerbose = pState->expert.bVerbose; |
| 3951 | |
| 3952 | rc = sqlite3_expert_analyze(p, pzErr); |
| 3953 | if( rc==SQLITE_OK ){ |
| 3954 | int nQuery = sqlite3_expert_count(p); |
| 3955 | int i; |
| 3956 | |
| 3957 | if( bVerbose ){ |
| 3958 | const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES); |
| 3959 | cli_puts("-- Candidates -----------------------------\n", out); |
| 3960 | cli_printf(out, "%s\n", zCand); |
| 3961 | } |
| 3962 | for(i=0; i<nQuery; i++){ |
| 3963 | const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL); |
| 3964 | const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES); |
| 3965 | const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN); |
| 3966 | if( zIdx==0 ) zIdx = "(no new indexes)\n"; |
| 3967 | if( bVerbose ){ |
| 3968 | cli_printf(out, |
| 3969 | "-- Query %d --------------------------------\n" |
| 3970 | "%s\n\n" |
| 3971 | ,i+1, zSql); |
| 3972 | } |
| 3973 | cli_printf(out, "%s\n%s\n", zIdx, zEQP); |
| 3974 | } |
| 3975 | } |
| 3976 | } |
| 3977 | sqlite3_expert_destroy(p); |
| 3978 | pState->expert.pExpert = 0; |
| 3979 | return rc; |
| 3980 | } |
| 3981 | |
| 3982 | /* |
| 3983 | ** Implementation of ".expert" dot command. |
| 3984 | */ |
| 3985 | static int expertDotCommand( |
| 3986 | ShellState *pState, /* Current shell tool state */ |
| 3987 | char **azArg, /* Array of arguments passed to dot command */ |
| 3988 | int nArg /* Number of entries in azArg[] */ |
| 3989 | ){ |
| 3990 | int rc = SQLITE_OK; |
| 3991 | char *zErr = 0; |
| 3992 | int i; |
| 3993 | int iSample = 0; |
| 3994 | |
| 3995 | assert( pState->expert.pExpert==0 ); |
| 3996 | memset(&pState->expert, 0, sizeof(ExpertInfo)); |
| 3997 | |
| 3998 | for(i=1; rc==SQLITE_OK && i<nArg; i++){ |
| 3999 | char *z = azArg[i]; |
| 4000 | int n; |
| 4001 | if( z[0]=='-' && z[1]=='-' ) z++; |
| 4002 | n = strlen30(z); |
| 4003 | if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){ |
| 4004 | pState->expert.bVerbose = 1; |
| 4005 | } |
| 4006 | else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){ |
| 4007 | if( i==(nArg-1) ){ |
| 4008 | cli_printf(stderr, "option requires an argument: %s\n", z); |
| 4009 | rc = SQLITE_ERROR; |
| 4010 | }else{ |
| 4011 | iSample = (int)integerValue(azArg[++i]); |
| 4012 | if( iSample<0 || iSample>100 ){ |
| 4013 | cli_printf(stderr,"value out of range: %s\n", azArg[i]); |
| 4014 | rc = SQLITE_ERROR; |
| 4015 | } |
| 4016 | } |
| 4017 | } |
| 4018 | else{ |
| 4019 | cli_printf(stderr,"unknown option: %s\n", z); |
| 4020 | rc = SQLITE_ERROR; |
| 4021 | } |
| 4022 | } |
| 4023 | |
| 4024 | if( rc==SQLITE_OK ){ |
| 4025 | pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr); |
| 4026 | if( pState->expert.pExpert==0 ){ |
| 4027 | cli_printf(stderr, |
| 4028 | "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory"); |
| 4029 | rc = SQLITE_ERROR; |
| 4030 | }else{ |
| 4031 | sqlite3_expert_config( |
| 4032 | pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample |
| 4033 | ); |
| 4034 | } |
| 4035 | } |
| 4036 | sqlite3_free(zErr); |
| 4037 | |
| 4038 | return rc; |
| 4039 | } |
| 4040 | #endif /* !SQLITE_OMIT_VIRTUALTABLE && !SQLITE_OMIT_AUTHORIZATION */ |
| 4041 | |
| 4042 | /* |
| 4043 | ** QRF write callback |
| 4044 | */ |
| 4045 | static int shellWriteQR(void *pX, const char *z, sqlite3_int64 n){ |
| 4046 | ShellState *pArg = (ShellState*)pX; |
| 4047 | cli_write(pArg->out, z, (int)n); |
| 4048 | return SQLITE_OK; |
| 4049 | } |
| 4050 | |
| 4051 | /* |
| 4052 | ** Execute a statement or set of statements. Print |
| 4053 | ** any result rows/columns depending on the current mode |
| 4054 | ** set via the supplied callback. |
| 4055 | ** |
| 4056 | ** This is very similar to SQLite's built-in sqlite3_exec() |
| 4057 | ** function except it takes a slightly different callback |
| 4058 | ** and callback data argument. |
| 4059 | */ |
| 4060 | static int shell_exec( |
| 4061 | ShellState *pArg, /* Pointer to ShellState */ |
| 4062 | const char *zSql, /* SQL to be evaluated */ |
| 4063 | char **pzErrMsg /* Error msg written here */ |
| 4064 | ){ |
| 4065 | sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ |
| 4066 | int rc = SQLITE_OK; /* Return Code */ |
| 4067 | int rc2; |
| 4068 | const char *zLeftover; /* Tail of unprocessed SQL */ |
| 4069 | sqlite3 *db = pArg->db; |
| 4070 | unsigned char eStyle; |
| 4071 | sqlite3_qrf_spec spec; |
| 4072 | |
| 4073 | if( pzErrMsg ){ |
| 4074 | *pzErrMsg = NULL; |
| 4075 | } |
| 4076 | memcpy(&spec, &pArg->mode.spec, sizeof(spec)); |
| 4077 | spec.xWrite = shellWriteQR; |
| 4078 | spec.pWriteArg = (void*)pArg; |
| 4079 | if( pArg->mode.eMode==MODE_Insert && ShellHasFlag(pArg,SHFLG_PreserveRowid) ){ |
| 4080 | spec.bTitles = QRF_SW_On; |
| 4081 | } |
| 4082 | /* ,- This is true, but it is omitted |
| 4083 | ** vvvvvvvvvvvvvvvvvvv ----- to avoid compiler warnings. */ |
| 4084 | assert( /*pArg->mode.eMode>=0 &&*/ pArg->mode.eMode<ArraySize(aModeInfo) ); |
| 4085 | eStyle = aModeInfo[pArg->mode.eMode].eStyle; |
| 4086 | if( pArg->mode.bAutoScreenWidth ){ |
| 4087 | spec.nScreenWidth = shellScreenWidth(); |
| 4088 | } |
| 4089 | if( spec.eBlob==QRF_BLOB_Auto ){ |
| 4090 | switch( spec.eText ){ |
| 4091 | case QRF_TEXT_Relaxed: /* fall through */ |
| 4092 | case QRF_TEXT_Sql: spec.eBlob = QRF_BLOB_Sql; break; |
| 4093 | case QRF_TEXT_Json: spec.eBlob = QRF_BLOB_Json; break; |
| 4094 | default: spec.eBlob = QRF_BLOB_Text; break; |
| 4095 | } |
| 4096 | } |
| 4097 | |
| 4098 | #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION) |
| 4099 | if( pArg->expert.pExpert ){ |
| 4100 | rc = expertHandleSQL(pArg, zSql, pzErrMsg); |
| 4101 | return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg); |
| 4102 | } |
| 4103 | #endif |
| 4104 | |
| 4105 | while( zSql && zSql[0] && (SQLITE_OK == rc) ){ |
| 4106 | static const char *zStmtSql; |
| 4107 | rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); |
| 4108 | if( SQLITE_OK != rc ){ |
| 4109 | if( pzErrMsg ){ |
| 4110 | *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql); |
| 4111 | } |
| 4112 | }else{ |
| 4113 | int isExplain; |
| 4114 | if( !pStmt ){ |
| 4115 | /* this happens for a comment or white-space */ |
| 4116 | zSql = zLeftover; |
| 4117 | while( IsSpace(zSql[0]) ) zSql++; |
| 4118 | continue; |
| 4119 | } |
| 4120 | zStmtSql = sqlite3_sql(pStmt); |
| 4121 | if( zStmtSql==0 ) zStmtSql = ""; |
| 4122 | while( IsSpace(zStmtSql[0]) ) zStmtSql++; |
| 4123 | |
| 4124 | /* save off the prepared statement handle */ |
| 4125 | if( pArg ){ |
| 4126 | pArg->pStmt = pStmt; |
| 4127 | } |
| 4128 | |
| 4129 | /* Show the EXPLAIN QUERY PLAN if .eqp is on */ |
| 4130 | bind_prepared_stmt(pArg, pStmt); |
| 4131 | isExplain = sqlite3_stmt_isexplain(pStmt); |
| 4132 | if( pArg && pArg->mode.autoEQP && isExplain==0 && pArg->dot.nArg==0 ){ |
| 4133 | int triggerEQP = 0; |
| 4134 | u8 savedEnableTimer = pArg->enableTimer; |
| 4135 | FILE *savedOut = pArg->out; |
| 4136 | pArg->enableTimer = 0; |
| 4137 | disable_debug_trace_modes(); |
| 4138 | sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP); |
| 4139 | if( pArg->mode.autoEQP>=AUTOEQP_trigger ){ |
| 4140 | sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0); |
| 4141 | } |
| 4142 | sqlite3_reset(pStmt); |
| 4143 | spec.eStyle = QRF_STYLE_Auto; |
| 4144 | sqlite3_stmt_explain(pStmt, 2); |
| 4145 | if( pArg->zEqpFile ){ |
| 4146 | pArg->out = sqlite3_fopen(pArg->zEqpFile, "ab"); |
| 4147 | if( pArg->out==0 ){ |
| 4148 | cli_printf(savedOut, "cannot open .eqp output file \"%s\"\n", |
| 4149 | pArg->zEqpFile); |
| 4150 | pArg->out = savedOut; |
| 4151 | } |
| 4152 | } |
| 4153 | sqlite3_format_query_result(pStmt, &spec, 0); |
| 4154 | if( pArg->mode.autoEQP>=AUTOEQP_full ){ |
| 4155 | sqlite3_reset(pStmt); |
| 4156 | sqlite3_stmt_explain(pStmt, 1); |
| 4157 | sqlite3_format_query_result(pStmt, &spec, 0); |
| 4158 | } |
| 4159 | |
| 4160 | if( pArg->mode.autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){ |
| 4161 | sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, (int*)0); |
| 4162 | } |
| 4163 | sqlite3_reset(pStmt); |
| 4164 | sqlite3_stmt_explain(pStmt, 0); |
| 4165 | if( pArg->out!=savedOut ){ |
| 4166 | fclose(pArg->out); |
| 4167 | pArg->out = savedOut; |
| 4168 | } |
| 4169 | restore_debug_trace_modes(); |
| 4170 | pArg->enableTimer = savedEnableTimer; |
| 4171 | } |
| 4172 | |
| 4173 | if( isExplain && pArg->mode.autoExplain ){ |
| 4174 | spec.eStyle = isExplain==1 ? QRF_STYLE_Explain : QRF_STYLE_Eqp; |
| 4175 | rc = sqlite3_format_query_result(pStmt, &spec, pzErrMsg); |
| 4176 | }else if( pArg->mode.eMode==MODE_Www ){ |
| 4177 | cli_printf(pArg->out, |
| 4178 | "</PRE>\n" |
| 4179 | "<TABLE border='1' cellspacing='0' cellpadding='2'>\n"); |
| 4180 | spec.eStyle = QRF_STYLE_Html; |
| 4181 | sqlite3_format_query_result(pStmt, &spec, pzErrMsg); |
| 4182 | cli_printf(pArg->out, |
| 4183 | "</TABLE>\n" |
| 4184 | "<PRE>"); |
| 4185 | }else{ |
| 4186 | spec.eStyle = eStyle; |
| 4187 | rc = sqlite3_format_query_result(pStmt, &spec, pzErrMsg); |
| 4188 | } |
| 4189 | |
| 4190 | /* print usage stats if stats on */ |
| 4191 | if( pArg && pArg->mStats!=0 ){ |
| 4192 | display_stats(db, pArg); |
| 4193 | } |
| 4194 | |
| 4195 | /* print loop-counters if required */ |
| 4196 | if( pArg && pArg->mode.scanstatsOn ){ |
| 4197 | char *zErr = 0; |
| 4198 | switch( pArg->mode.scanstatsOn ){ |
| 4199 | case 1: spec.eStyle = QRF_STYLE_Stats; break; |
| 4200 | case 2: spec.eStyle = QRF_STYLE_StatsEst; break; |
| 4201 | default: spec.eStyle = QRF_STYLE_StatsVm; break; |
| 4202 | } |
| 4203 | sqlite3_reset(pStmt); |
| 4204 | rc = sqlite3_format_query_result(pStmt, &spec, &zErr); |
| 4205 | if( rc ){ |
| 4206 | cli_printf(stderr, "Stats query failed: %s\n", zErr); |
| 4207 | sqlite3_free(zErr); |
| 4208 | } |
| 4209 | } |
| 4210 | |
| 4211 | /* Finalize the statement just executed. If this fails, save a |
| 4212 | ** copy of the error message. Otherwise, set zSql to point to the |
| 4213 | ** next statement to execute. */ |
| 4214 | rc2 = sqlite3_finalize(pStmt); |
| 4215 | if( rc2 && rc!=SQLITE_NOMEM ) rc = rc2; |
| 4216 | if( rc==SQLITE_OK ){ |
| 4217 | zSql = zLeftover; |
| 4218 | while( IsSpace(zSql[0]) ) zSql++; |
| 4219 | }else if( pzErrMsg && pzErrMsg[0]==0 ){ |
| 4220 | *pzErrMsg = save_err_msg(db, "stepping", rc, 0); |
| 4221 | } |
| 4222 | |
| 4223 | /* clear saved stmt handle */ |
| 4224 | if( pArg ){ |
| 4225 | pArg->pStmt = NULL; |
| 4226 | } |
| 4227 | } |
| 4228 | } /* end while */ |
| 4229 | |
| 4230 | return rc; |
| 4231 | } |
| 4232 | |
| 4233 | /* |
| 4234 | ** Release memory previously allocated by tableColumnList(). |
| 4235 | */ |
| 4236 | static void freeColumnList(char **azCol){ |
| 4237 | int i; |
| 4238 | for(i=1; azCol[i]; i++){ |
| 4239 | sqlite3_free(azCol[i]); |
| 4240 | } |
| 4241 | /* azCol[0] is a static string */ |
| 4242 | sqlite3_free(azCol); |
| 4243 | } |
| 4244 | |
| 4245 | /* |
| 4246 | ** Return a list of pointers to strings which are the names of all |
| 4247 | ** columns in table zTab. The memory to hold the names is dynamically |
| 4248 | ** allocated and must be released by the caller using a subsequent call |
| 4249 | ** to freeColumnList(). |
| 4250 | ** |
| 4251 | ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid |
| 4252 | ** value that needs to be preserved, then azCol[0] is filled in with the |
| 4253 | ** name of the rowid column. |
| 4254 | ** |
| 4255 | ** The first regular column in the table is azCol[1]. The list is terminated |
| 4256 | ** by an entry with azCol[i]==0. |
| 4257 | */ |
| 4258 | static char **tableColumnList(ShellState *p, const char *zTab){ |
| 4259 | char **azCol = 0; |
| 4260 | sqlite3_stmt *pStmt; |
| 4261 | char *zSql; |
| 4262 | int nCol = 0; |
| 4263 | i64 nAlloc = 0; |
| 4264 | int nPK = 0; /* Number of PRIMARY KEY columns seen */ |
| 4265 | int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */ |
| 4266 | int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid); |
| 4267 | int rc; |
| 4268 | |
| 4269 | zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab); |
| 4270 | shell_check_oom(zSql); |
| 4271 | rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); |
| 4272 | sqlite3_free(zSql); |
| 4273 | if( rc ) return 0; |
| 4274 | while( sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 4275 | if( nCol>=nAlloc-2 ){ |
| 4276 | nAlloc = nAlloc*2 + nCol + 10; |
| 4277 | azCol = sqlite3_realloc64(azCol, nAlloc*sizeof(azCol[0])); |
| 4278 | shell_check_oom(azCol); |
| 4279 | } |
| 4280 | azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1)); |
| 4281 | shell_check_oom(azCol[nCol]); |
| 4282 | if( sqlite3_column_int(pStmt, 5) ){ |
| 4283 | nPK++; |
| 4284 | if( nPK==1 |
| 4285 | && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2), |
| 4286 | "INTEGER")==0 |
| 4287 | ){ |
| 4288 | isIPK = 1; |
| 4289 | }else{ |
| 4290 | isIPK = 0; |
| 4291 | } |
| 4292 | } |
| 4293 | } |
| 4294 | sqlite3_finalize(pStmt); |
| 4295 | if( azCol==0 ) return 0; |
| 4296 | azCol[0] = 0; |
| 4297 | azCol[nCol+1] = 0; |
| 4298 | |
| 4299 | /* The decision of whether or not a rowid really needs to be preserved |
| 4300 | ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table |
| 4301 | ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve |
| 4302 | ** rowids on tables where the rowid is inaccessible because there are other |
| 4303 | ** columns in the table named "rowid", "_rowid_", and "oid". |
| 4304 | */ |
| 4305 | if( preserveRowid && isIPK ){ |
| 4306 | /* If a single PRIMARY KEY column with type INTEGER was seen, then it |
| 4307 | ** might be an alias for the ROWID. But it might also be a WITHOUT ROWID |
| 4308 | ** table or a INTEGER PRIMARY KEY DESC column, neither of which are |
| 4309 | ** ROWID aliases. To distinguish these cases, check to see if |
| 4310 | ** there is a "pk" entry in "PRAGMA index_list". There will be |
| 4311 | ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID. |
| 4312 | */ |
| 4313 | zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)" |
| 4314 | " WHERE origin='pk'", zTab); |
| 4315 | shell_check_oom(zSql); |
| 4316 | rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); |
| 4317 | sqlite3_free(zSql); |
| 4318 | if( rc ){ |
| 4319 | freeColumnList(azCol); |
| 4320 | return 0; |
| 4321 | } |
| 4322 | rc = sqlite3_step(pStmt); |
| 4323 | sqlite3_finalize(pStmt); |
| 4324 | preserveRowid = rc==SQLITE_ROW; |
| 4325 | } |
| 4326 | if( preserveRowid ){ |
| 4327 | /* Only preserve the rowid if we can find a name to use for the |
| 4328 | ** rowid */ |
| 4329 | static char *azRowid[] = { "rowid", "_rowid_", "oid" }; |
| 4330 | int i, j; |
| 4331 | for(j=0; j<3; j++){ |
| 4332 | for(i=1; i<=nCol; i++){ |
| 4333 | if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break; |
| 4334 | } |
| 4335 | if( i>nCol ){ |
| 4336 | /* At this point, we know that azRowid[j] is not the name of any |
| 4337 | ** ordinary column in the table. Verify that azRowid[j] is a valid |
| 4338 | ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID |
| 4339 | ** tables will fail this last check */ |
| 4340 | rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0); |
| 4341 | if( rc==SQLITE_OK ) azCol[0] = azRowid[j]; |
| 4342 | break; |
| 4343 | } |
| 4344 | } |
| 4345 | } |
| 4346 | return azCol; |
| 4347 | } |
| 4348 | |
| 4349 | /* |
| 4350 | ** Toggle the reverse_unordered_selects setting. |
| 4351 | */ |
| 4352 | static void toggleSelectOrder(sqlite3 *db){ |
| 4353 | sqlite3_stmt *pStmt = 0; |
| 4354 | int iSetting = 0; |
| 4355 | char zStmt[100]; |
| 4356 | sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0); |
| 4357 | if( sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 4358 | iSetting = sqlite3_column_int(pStmt, 0); |
| 4359 | } |
| 4360 | sqlite3_finalize(pStmt); |
| 4361 | sqlite3_snprintf(sizeof(zStmt), zStmt, |
| 4362 | "PRAGMA reverse_unordered_selects(%d)", !iSetting); |
| 4363 | sqlite3_exec(db, zStmt, 0, 0, 0); |
| 4364 | } |
| 4365 | |
| 4366 | /* Forward reference */ |
| 4367 | static int db_int(sqlite3 *db, const char *zSql, ...); |
| 4368 | |
| 4369 | /* |
| 4370 | ** This is a different callback routine used for dumping the database. |
| 4371 | ** Each row received by this callback consists of a table name, |
| 4372 | ** the table type ("index" or "table") and SQL to create the table. |
| 4373 | ** This routine should print text sufficient to recreate the table. |
| 4374 | */ |
| 4375 | static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){ |
| 4376 | int rc; |
| 4377 | const char *zTable; |
| 4378 | const char *zType; |
| 4379 | const char *zSql; |
| 4380 | ShellState *p = (ShellState *)pArg; |
| 4381 | int dataOnly; |
| 4382 | int noSys; |
| 4383 | |
| 4384 | UNUSED_PARAMETER(azNotUsed); |
| 4385 | if( nArg!=3 || azArg==0 ) return 0; |
| 4386 | zTable = azArg[0]; |
| 4387 | zType = azArg[1]; |
| 4388 | zSql = azArg[2]; |
| 4389 | if( zTable==0 ) return 0; |
| 4390 | if( zType==0 ) return 0; |
| 4391 | dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0; |
| 4392 | noSys = (p->shellFlgs & SHFLG_DumpNoSys)!=0; |
| 4393 | |
| 4394 | if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){ |
| 4395 | /* The sqlite_sequence table is repopulated last. Delete content |
| 4396 | ** in the sqlite_sequence table added by prior repopulations prior to |
| 4397 | ** repopulating sqlite_sequence itself. But only do this if the |
| 4398 | ** table is non-empty, because if it is empty the table might not |
| 4399 | ** have been recreated by prior repopulations. See forum posts: |
| 4400 | ** 2024-10-13T17:10:01z and 2025-10-29T19:38:43z |
| 4401 | */ |
| 4402 | if( db_int(p->db, "SELECT count(*) FROM sqlite_sequence")>0 ){ |
| 4403 | if( !p->writableSchema ){ |
| 4404 | cli_puts("PRAGMA writable_schema=ON;\n", p->out); |
| 4405 | p->writableSchema = 1; |
| 4406 | } |
| 4407 | cli_puts("CREATE TABLE IF NOT EXISTS sqlite_sequence(name,seq);\n" |
| 4408 | "DELETE FROM sqlite_sequence;\n", p->out); |
| 4409 | } |
| 4410 | }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){ |
| 4411 | if( !dataOnly ) cli_puts("ANALYZE sqlite_schema;\n", p->out); |
| 4412 | }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){ |
| 4413 | return 0; |
| 4414 | }else if( dataOnly ){ |
| 4415 | /* no-op */ |
| 4416 | }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ |
| 4417 | char *zIns; |
| 4418 | if( !p->writableSchema ){ |
| 4419 | cli_puts("PRAGMA writable_schema=ON;\n", p->out); |
| 4420 | p->writableSchema = 1; |
| 4421 | } |
| 4422 | zIns = sqlite3_mprintf( |
| 4423 | "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" |
| 4424 | "VALUES('table','%q','%q',0,'%q');", |
| 4425 | zTable, zTable, zSql); |
| 4426 | shell_check_oom(zIns); |
| 4427 | cli_printf(p->out, "%s\n", zIns); |
| 4428 | sqlite3_free(zIns); |
| 4429 | return 0; |
| 4430 | }else{ |
| 4431 | printSchemaLine(p->out, zSql, ";\n"); |
| 4432 | } |
| 4433 | |
| 4434 | if( cli_strcmp(zType, "table")==0 ){ |
| 4435 | ShellText sSelect; |
| 4436 | ShellText sTable; |
| 4437 | char **azCol; |
| 4438 | int i; |
| 4439 | Mode savedMode; |
| 4440 | |
| 4441 | azCol = tableColumnList(p, zTable); |
| 4442 | if( azCol==0 ){ |
| 4443 | p->nErr++; |
| 4444 | return 0; |
| 4445 | } |
| 4446 | |
| 4447 | /* Always quote the table name, even if it appears to be pure ascii, |
| 4448 | ** in case it is a keyword. Ex: INSERT INTO "table" ... */ |
| 4449 | initText(&sTable); |
| 4450 | appendText(&sTable, zTable, quoteChar(zTable)); |
| 4451 | /* If preserving the rowid, add a column list after the table name. |
| 4452 | ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)" |
| 4453 | ** instead of the usual "INSERT INTO tab VALUES(...)". |
| 4454 | */ |
| 4455 | if( azCol[0] ){ |
| 4456 | appendText(&sTable, "(", 0); |
| 4457 | appendText(&sTable, azCol[0], 0); |
| 4458 | for(i=1; azCol[i]; i++){ |
| 4459 | appendText(&sTable, ",", 0); |
| 4460 | appendText(&sTable, azCol[i], quoteChar(azCol[i])); |
| 4461 | } |
| 4462 | appendText(&sTable, ")", 0); |
| 4463 | } |
| 4464 | |
| 4465 | /* Build an appropriate SELECT statement */ |
| 4466 | initText(&sSelect); |
| 4467 | appendText(&sSelect, "SELECT ", 0); |
| 4468 | if( azCol[0] ){ |
| 4469 | appendText(&sSelect, azCol[0], 0); |
| 4470 | appendText(&sSelect, " AS ", 0); |
| 4471 | appendText(&sSelect, azCol[0], 0); |
| 4472 | appendText(&sSelect, ",", 0); |
| 4473 | } |
| 4474 | for(i=1; azCol[i]; i++){ |
| 4475 | appendText(&sSelect, azCol[i], quoteChar(azCol[i])); |
| 4476 | if( azCol[i+1] ){ |
| 4477 | appendText(&sSelect, ",", 0); |
| 4478 | } |
| 4479 | } |
| 4480 | freeColumnList(azCol); |
| 4481 | appendText(&sSelect, " FROM ", 0); |
| 4482 | appendText(&sSelect, zTable, quoteChar(zTable)); |
| 4483 | |
| 4484 | |
| 4485 | savedMode = p->mode; |
| 4486 | p->mode.spec.zTableName = (char*)zTable; |
| 4487 | p->mode.eMode = MODE_Insert; |
| 4488 | p->mode.spec.eText = QRF_TEXT_Sql; |
| 4489 | p->mode.spec.eBlob = QRF_BLOB_Sql; |
| 4490 | p->mode.spec.bTitles = QRF_No; |
| 4491 | p->mode.spec.nCharLimit = 0; |
| 4492 | p->mode.spec.bTextJsonb = QRF_No; |
| 4493 | p->mode.spec.zIFmt = 0; |
| 4494 | p->mode.spec.zFpFmt = 0; |
| 4495 | rc = shell_exec(p, sSelect.zTxt, 0); |
| 4496 | if( (rc&0xff)==SQLITE_CORRUPT ){ |
| 4497 | cli_puts("/****** CORRUPTION ERROR *******/\n", p->out); |
| 4498 | toggleSelectOrder(p->db); |
| 4499 | shell_exec(p, sSelect.zTxt, 0); |
| 4500 | toggleSelectOrder(p->db); |
| 4501 | } |
| 4502 | p->mode = savedMode; |
| 4503 | freeText(&sTable); |
| 4504 | freeText(&sSelect); |
| 4505 | if( rc ) p->nErr++; |
| 4506 | } |
| 4507 | return 0; |
| 4508 | } |
| 4509 | |
| 4510 | /* |
| 4511 | ** Run zQuery. Use dump_callback() as the callback routine so that |
| 4512 | ** the contents of the query are output as SQL statements. |
| 4513 | ** |
| 4514 | ** If we get a SQLITE_CORRUPT error, rerun the query after appending |
| 4515 | ** "ORDER BY rowid DESC" to the end. |
| 4516 | */ |
| 4517 | static int run_schema_dump_query( |
| 4518 | ShellState *p, |
| 4519 | const char *zQuery |
| 4520 | ){ |
| 4521 | int rc; |
| 4522 | char *zErr = 0; |
| 4523 | rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); |
| 4524 | if( rc==SQLITE_CORRUPT ){ |
| 4525 | char *zQ2; |
| 4526 | int len = strlen30(zQuery); |
| 4527 | cli_puts("/****** CORRUPTION ERROR *******/\n", p->out); |
| 4528 | if( zErr ){ |
| 4529 | char *zMsg = shellSafeCommentText(zErr); |
| 4530 | cli_printf(p->out, "/****** %s ******/\n", zMsg); |
| 4531 | sqlite3_free(zMsg); |
| 4532 | sqlite3_free(zErr); |
| 4533 | zErr = 0; |
| 4534 | } |
| 4535 | zQ2 = malloc( len+100 ); |
| 4536 | if( zQ2==0 ) return rc; |
| 4537 | sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); |
| 4538 | rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); |
| 4539 | if( rc ){ |
| 4540 | char *zMsg = shellSafeCommentText(zErr); |
| 4541 | cli_printf(p->out, "/****** ERROR: %s ******/\n", zMsg); |
| 4542 | sqlite3_free(zMsg); |
| 4543 | }else{ |
| 4544 | rc = SQLITE_CORRUPT; |
| 4545 | } |
| 4546 | free(zQ2); |
| 4547 | } |
| 4548 | sqlite3_free(zErr); |
| 4549 | return rc; |
| 4550 | } |
| 4551 | |
| 4552 | /* |
| 4553 | ** Text of help messages. |
| 4554 | ** |
| 4555 | ** The help text for each individual command begins with a line that starts |
| 4556 | ** with ".". Subsequent lines are supplemental information. |
| 4557 | ** |
| 4558 | ** There must be two or more spaces between the end of the command and the |
| 4559 | ** start of the description of what that command does. |
| 4560 | */ |
| 4561 | static const char *(azHelp[]) = { |
| 4562 | #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \ |
| 4563 | && !defined(SQLITE_SHELL_FIDDLE) |
| 4564 | ".archive ... Manage SQL archives", |
| 4565 | " Each command must have exactly one of the following options:", |
| 4566 | " -c, --create Create a new archive", |
| 4567 | " -u, --update Add or update files with changed mtime", |
| 4568 | " -i, --insert Like -u but always add even if unchanged", |
| 4569 | " -r, --remove Remove files from archive", |
| 4570 | " -t, --list List contents of archive", |
| 4571 | " -x, --extract Extract files from archive", |
| 4572 | " Optional arguments:", |
| 4573 | " -v, --verbose Print each filename as it is processed", |
| 4574 | " -f FILE, --file FILE Use archive FILE (default is current db)", |
| 4575 | " -a FILE, --append FILE Open FILE using the apndvfs VFS", |
| 4576 | " -C DIR, --directory DIR Read/extract files from directory DIR", |
| 4577 | " -g, --glob Use glob matching for names in archive", |
| 4578 | " -n, --dryrun Show the SQL that would have occurred", |
| 4579 | " Examples:", |
| 4580 | " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar", |
| 4581 | " .ar -tf ARCHIVE # List members of ARCHIVE", |
| 4582 | " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE", |
| 4583 | " See also:", |
| 4584 | " http://sqlite.org/cli.html#sqlite_archive_support", |
| 4585 | #endif |
| 4586 | #ifndef SQLITE_OMIT_AUTHORIZATION |
| 4587 | ".auth ON|OFF Show authorizer callbacks", |
| 4588 | " Options:", |
| 4589 | " --deny GLOB Return SQLITE_DENY if pattern matches", |
| 4590 | " --ignore GLOB Return SQLITE_IGNORE if pattern matches", |
| 4591 | #endif |
| 4592 | #ifndef SQLITE_SHELL_FIDDLE |
| 4593 | ".backup ?DB? FILE Backup DB (default \"main\") to FILE", |
| 4594 | " Options:", |
| 4595 | " --append Use the appendvfs", |
| 4596 | " --async Write to FILE without journal and fsync()", |
| 4597 | #endif |
| 4598 | ".bail on|off Stop after hitting an error. Default OFF", |
| 4599 | #ifndef SQLITE_SHELL_FIDDLE |
| 4600 | ".cd DIRECTORY Change the working directory to DIRECTORY", |
| 4601 | #endif |
| 4602 | ".changes on|off Show number of rows changed by SQL", |
| 4603 | ".check OPTIONS ... Verify the results of a .testcase", |
| 4604 | #ifndef SQLITE_SHELL_FIDDLE |
| 4605 | ".clone NEWDB Clone data into NEWDB from the existing database", |
| 4606 | #endif |
| 4607 | ".connection [close] [#] Open or close an auxiliary database connection", |
| 4608 | ".crlf ?on|off? Whether or not to use \\r\\n line endings", |
| 4609 | ".databases List names and files of attached databases", |
| 4610 | ".dbconfig ?op? ?val? List or change sqlite3_db_config() options", |
| 4611 | #if SQLITE_SHELL_HAVE_RECOVER |
| 4612 | ".dbinfo ?DB? Show status information about the database", |
| 4613 | #endif |
| 4614 | ".dbtotxt Hex dump of the database file", |
| 4615 | ".diskused ?SCHEMA? Report database space and size stats", |
| 4616 | ".dump ?OBJECTS? Render database content as SQL", |
| 4617 | " Options:", |
| 4618 | " --data-only Output only INSERT statements", |
| 4619 | " --newlines Allow unescaped newline characters in output", |
| 4620 | " --nosys Omit system tables (ex: \"sqlite_stat1\")", |
| 4621 | " --preserve-rowids Include ROWID values in the output", |
| 4622 | " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump", |
| 4623 | " Additional LIKE patterns can be given in subsequent arguments", |
| 4624 | ".echo on|off Turn command echo on or off", |
| 4625 | ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN", |
| 4626 | " Other Modes:", |
| 4627 | #ifdef SQLITE_DEBUG |
| 4628 | " test Show raw EXPLAIN QUERY PLAN output", |
| 4629 | " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"", |
| 4630 | #endif |
| 4631 | " trigger Like \"full\" but also show trigger bytecode", |
| 4632 | #ifndef SQLITE_SHELL_FIDDLE |
| 4633 | ".excel Display the output of next command in spreadsheet", |
| 4634 | " --bom Put a UTF8 byte-order mark on intermediate file", |
| 4635 | #endif |
| 4636 | #ifndef SQLITE_SHELL_FIDDLE |
| 4637 | ".exit ?CODE? Exit this program with return-code CODE", |
| 4638 | #endif |
| 4639 | #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION) |
| 4640 | ".expert EXPERIMENTAL. Suggest indexes for queries", |
| 4641 | #endif |
| 4642 | ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto", |
| 4643 | ".filectrl CMD ... Run various sqlite3_file_control() operations", |
| 4644 | " --schema SCHEMA Use SCHEMA instead of \"main\"", |
| 4645 | " --help Show CMD details", |
| 4646 | ".fullschema ?--indent? Show schema and the content of sqlite_stat tables", |
| 4647 | ".headers on|off Turn display of headers on or off", |
| 4648 | ".help ?-all? ?PATTERN? Show help text for PATTERN", |
| 4649 | #ifndef SQLITE_SHELL_FIDDLE |
| 4650 | ".import FILE TABLE Import data from FILE into TABLE", |
| 4651 | #endif |
| 4652 | #ifndef SQLITE_OMIT_TEST_CONTROL |
| 4653 | ".imposter INDEX TABLE Create imposter table TABLE on index INDEX", |
| 4654 | #endif |
| 4655 | ".indexes ?PATTERN? Show names of indexes matching PATTERN", |
| 4656 | " -a|--all Also show system-generated indexes", |
| 4657 | " --expr Show only expression indexes", |
| 4658 | " --sys Show only system-generated indexes", |
| 4659 | ".intck ?STEPS? Run an incremental integrity check on the db", |
| 4660 | #ifdef SQLITE_ENABLE_IOTRACE |
| 4661 | ",iotrace FILE Enable I/O diagnostic logging to FILE", |
| 4662 | #endif |
| 4663 | ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT", |
| 4664 | ".lint OPTIONS Report potential schema issues.", |
| 4665 | " Options:", |
| 4666 | " fkey-indexes Find missing foreign key indexes", |
| 4667 | #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE) |
| 4668 | ".load FILE ?ENTRY? Load an extension library", |
| 4669 | #endif |
| 4670 | #if !defined(SQLITE_SHELL_FIDDLE) |
| 4671 | ".log FILE|on|off Turn logging on or off. FILE can be stderr/stdout", |
| 4672 | #else |
| 4673 | ".log on|off Turn logging on or off.", |
| 4674 | #endif |
| 4675 | ".mode ?MODE? ?OPTIONS? Set output mode", |
| 4676 | #ifndef SQLITE_SHELL_FIDDLE |
| 4677 | ".nonce STRING Suspend safe mode for one command if nonce matches", |
| 4678 | #endif |
| 4679 | ".nullvalue STRING Use STRING in place of NULL values", |
| 4680 | #ifndef SQLITE_SHELL_FIDDLE |
| 4681 | ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE", |
| 4682 | /* Note that .open is (partially) available in WASM builds but is |
| 4683 | ** currently only intended to be used by the fiddle tool, not |
| 4684 | ** end users, so is "undocumented." */ |
| 4685 | ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE", |
| 4686 | " Options:", |
| 4687 | " --append Use appendvfs to append database to the end of FILE", |
| 4688 | #endif |
| 4689 | #ifndef SQLITE_OMIT_DESERIALIZE |
| 4690 | " --deserialize Load into memory using sqlite3_deserialize()", |
| 4691 | #endif |
| 4692 | /*" --exclusive Set the SQLITE_OPEN_EXCLUSIVE flag", UNDOCUMENTED */ |
| 4693 | #ifndef SQLITE_OMIT_DESERIALIZE |
| 4694 | " --hexdb Load the output of \"dbtotxt\" as an in-memory db", |
| 4695 | #endif |
| 4696 | " --ifexist Only open if FILE already exists", |
| 4697 | #ifndef SQLITE_OMIT_DESERIALIZE |
| 4698 | " --maxsize N Maximum size for --hexdb or --deserialized database", |
| 4699 | #endif |
| 4700 | " --new Initialize FILE to an empty database", |
| 4701 | " --normal FILE is an ordinary SQLite database", |
| 4702 | " --nofollow Do not follow symbolic links", |
| 4703 | " --readonly Open FILE readonly", |
| 4704 | " --zip FILE is a ZIP archive", |
| 4705 | #ifndef SQLITE_SHELL_FIDDLE |
| 4706 | ".output ?FILE? Send output to FILE or stdout if FILE is omitted", |
| 4707 | #endif |
| 4708 | ".parameter CMD ... Manage SQL parameter bindings", |
| 4709 | " clear Erase all bindings", |
| 4710 | " init Initialize the TEMP table that holds bindings", |
| 4711 | " list List the current parameter bindings", |
| 4712 | " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE", |
| 4713 | " PARAMETER should start with one of: $ : @ ?", |
| 4714 | " unset PARAMETER Remove PARAMETER from the binding table", |
| 4715 | ".print STRING... Print literal STRING", |
| 4716 | #ifndef SQLITE_OMIT_PROGRESS_CALLBACK |
| 4717 | ".progress N Invoke progress handler after every N opcodes", |
| 4718 | " --limit N Interrupt after N progress callbacks", |
| 4719 | " --once Do no more than one progress interrupt", |
| 4720 | " --quiet|-q No output except at interrupts", |
| 4721 | " --reset Reset the count for each input and interrupt", |
| 4722 | " --timeout S Halt after running for S seconds", |
| 4723 | #endif |
| 4724 | ".prompt MAIN CONTINUE Replace the standard prompts", |
| 4725 | " --hard-reset Unset SQLITE_PS1/2 and then --reset", |
| 4726 | #ifndef SQLITE_NO_COLOR |
| 4727 | " --no-color Disable color prompts. Use --color to re-enable", |
| 4728 | #endif |
| 4729 | " --reset Revert to default prompts", |
| 4730 | " --show Show the current prompt strings", |
| 4731 | " -- No more options. Subsequent args are prompts", |
| 4732 | #ifndef SQLITE_SHELL_FIDDLE |
| 4733 | ".quit Stop interpreting input stream, exit if primary.", |
| 4734 | ".read FILE Read input from FILE or command output", |
| 4735 | " If FILE begins with \"|\", it is a command that generates the input.", |
| 4736 | #endif |
| 4737 | #if SQLITE_SHELL_HAVE_RECOVER |
| 4738 | ".recover Recover as much data as possible from corrupt db.", |
| 4739 | " --ignore-freelist Ignore pages that appear to be on db freelist", |
| 4740 | " --lost-and-found TABLE Alternative name for the lost-and-found table", |
| 4741 | " --no-rowids Do not attempt to recover rowid values", |
| 4742 | " that are not also INTEGER PRIMARY KEYs", |
| 4743 | " --unsafe Do not issue the \".safe\" command in output", |
| 4744 | #endif |
| 4745 | #ifndef SQLITE_SHELL_FIDDLE |
| 4746 | ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE", |
| 4747 | #endif |
| 4748 | ".safe Put the CLI into \"safe mode\"", |
| 4749 | #ifndef SQLITE_SHELL_FIDDLE |
| 4750 | ".save ?OPTIONS? FILE Write database to FILE (an alias for .backup ...)", |
| 4751 | #endif |
| 4752 | ".scanstats on|off|est Turn sqlite3_stmt_scanstatus() metrics on or off", |
| 4753 | ".schema ?PATTERN? Show the CREATE statements matching PATTERN", |
| 4754 | " Options:", |
| 4755 | " --indent Try to pretty-print the schema", |
| 4756 | " --nosys Omit objects whose names start with \"sqlite_\"", |
| 4757 | ",selftest ?OPTIONS? Run tests defined in the SELFTEST table", |
| 4758 | " Options:", |
| 4759 | " --init Create a new SELFTEST table", |
| 4760 | " -v Verbose output", |
| 4761 | ",separator COL ?ROW? Change the column and row separators", |
| 4762 | #if defined(SQLITE_ENABLE_SESSION) |
| 4763 | ".session ?NAME? CMD ... Create or control sessions", |
| 4764 | " Subcommands:", |
| 4765 | " attach TABLE Attach TABLE", |
| 4766 | " changeset FILE Write a changeset into FILE", |
| 4767 | " close Close one session", |
| 4768 | " enable ?BOOLEAN? Set or query the enable bit", |
| 4769 | " filter GLOB... Reject tables matching GLOBs", |
| 4770 | " indirect ?BOOLEAN? Mark or query the indirect status", |
| 4771 | " isempty Query whether the session is empty", |
| 4772 | " list List currently open session names", |
| 4773 | " open DB NAME Open a new session on DB", |
| 4774 | " patchset FILE Write a patchset into FILE", |
| 4775 | " If ?NAME? is omitted, the first defined session is used.", |
| 4776 | #endif |
| 4777 | ".sha3sum ... Compute a SHA3 hash of database content", |
| 4778 | " Options:", |
| 4779 | " --schema Also hash the sqlite_schema table", |
| 4780 | " --sha3-224 Use the sha3-224 algorithm", |
| 4781 | " --sha3-256 Use the sha3-256 algorithm (default)", |
| 4782 | " --sha3-384 Use the sha3-384 algorithm", |
| 4783 | " --sha3-512 Use the sha3-512 algorithm", |
| 4784 | " Any other argument is a LIKE pattern for tables to hash", |
| 4785 | #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) |
| 4786 | ".shell CMD ARGS... Run CMD ARGS... in a system shell", |
| 4787 | #endif |
| 4788 | ",show Show the current values for various settings", |
| 4789 | ".stats ?ARG? Show stats or turn stats on or off", |
| 4790 | " off Turn off automatic stat display", |
| 4791 | " on Turn on automatic stat display", |
| 4792 | " stmt Show statement stats", |
| 4793 | " vmstep Show the virtual machine step count only", |
| 4794 | #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) |
| 4795 | ".system CMD ARGS... Run CMD ARGS... in a system shell", |
| 4796 | #endif |
| 4797 | ".tables ?TABLE? List names of tables matching LIKE pattern TABLE", |
| 4798 | ".testcase NAME Begin a test case.", |
| 4799 | ",testctrl CMD ... Run various sqlite3_test_control() operations", |
| 4800 | " Run \".testctrl\" with no arguments for details", |
| 4801 | ".timeout MS Try opening locked tables for MS milliseconds", |
| 4802 | ".timer on|off|once Turn SQL timer on or off.", |
| 4803 | #ifndef SQLITE_OMIT_TRACE |
| 4804 | ".trace ?OPTIONS? Output each SQL statement as it is run", |
| 4805 | " FILE Send output to FILE", |
| 4806 | " stdout Send output to stdout", |
| 4807 | " stderr Send output to stderr", |
| 4808 | " off Disable tracing", |
| 4809 | " --expanded Expand query parameters", |
| 4810 | #ifdef SQLITE_ENABLE_NORMALIZE |
| 4811 | " --normalized Normal the SQL statements", |
| 4812 | #endif |
| 4813 | " --plain Show SQL as it is input", |
| 4814 | " --stmt Trace statement execution (SQLITE_TRACE_STMT)", |
| 4815 | " --profile Profile statements (SQLITE_TRACE_PROFILE)", |
| 4816 | " --row Trace each row (SQLITE_TRACE_ROW)", |
| 4817 | " --close Trace connection close (SQLITE_TRACE_CLOSE)", |
| 4818 | #endif /* SQLITE_OMIT_TRACE */ |
| 4819 | #ifdef SQLITE_DEBUG |
| 4820 | ".unmodule NAME ... Unregister virtual table modules", |
| 4821 | " --allexcept Unregister everything except those named", |
| 4822 | #endif |
| 4823 | ".version Show source, library and compiler versions", |
| 4824 | ".vfsinfo ?AUX? Information about the top-level VFS", |
| 4825 | ".vfslist List all available VFSes", |
| 4826 | ".vfsname ?AUX? Print the name of the VFS stack", |
| 4827 | ",width NUM1 NUM2 ... Set minimum column widths for columnar output", |
| 4828 | " Negative values right-justify", |
| 4829 | #ifndef SQLITE_SHELL_FIDDLE |
| 4830 | ".www Display output of the next command in web browser", |
| 4831 | " --plain Show results as text/plain, not as HTML", |
| 4832 | #endif |
| 4833 | }; |
| 4834 | |
| 4835 | INSERT-USAGE-TEXT-HERE |
| 4836 | |
| 4837 | /* |
| 4838 | ** Return a pointer to usage text for zCmd, or NULL if none exists. |
| 4839 | */ |
| 4840 | static const char *findUsage(const char *zCmd){ |
| 4841 | int i; |
| 4842 | for(i=0; i<ArraySize(aUsage); i++){ |
| 4843 | if( sqlite3_strglob(zCmd, aUsage[i].zCmd)==0 ) return aUsage[i].zUsage; |
| 4844 | } |
| 4845 | return 0; |
| 4846 | } |
| 4847 | |
| 4848 | /* |
| 4849 | ** Output help text for commands that match zPattern. |
| 4850 | ** |
| 4851 | ** * If zPattern is NULL, then show all documented commands, but |
| 4852 | ** only give a one-line summary of each. |
| 4853 | ** |
| 4854 | ** * If zPattern is "-a" or "-all" or "--all" then show all help text |
| 4855 | ** for all commands except undocumented commands. |
| 4856 | ** |
| 4857 | ** * If zPattern is "0" then show all help for undocumented commands. |
| 4858 | ** Undocumented commands begin with "," instead of "." in the azHelp[] |
| 4859 | ** array. |
| 4860 | ** |
| 4861 | ** * If zPattern is a prefix for one or more documented commands, then |
| 4862 | ** show help for those commands. If only a single command matches the |
| 4863 | ** prefix, show the full text of the help. If multiple commands match, |
| 4864 | ** Only show just the first line of each. |
| 4865 | ** |
| 4866 | ** * Otherwise, show the complete text of any documented command for which |
| 4867 | ** zPattern is a LIKE match for any text within that command help |
| 4868 | ** text. |
| 4869 | ** |
| 4870 | ** Return the number commands that match zPattern. |
| 4871 | */ |
| 4872 | static int showHelp(FILE *out, const char *zPattern){ |
| 4873 | int i = 0; |
| 4874 | int j = 0; |
| 4875 | int n = 0; |
| 4876 | char *zPat; |
| 4877 | const char *zHit = 0; |
| 4878 | if( zPattern==0 ){ |
| 4879 | /* Show just the first line for all help topics */ |
| 4880 | zPattern = "[a-z]"; |
| 4881 | }else if( cli_strcmp(zPattern,"-a")==0 |
| 4882 | || cli_strcmp(zPattern,"-all")==0 |
| 4883 | || cli_strcmp(zPattern,"--all")==0 |
| 4884 | ){ |
| 4885 | /* Show everything except undocumented commands */ |
| 4886 | zPattern = "."; |
| 4887 | }else if( cli_strcmp(zPattern,"0")==0 ){ |
| 4888 | /* Show complete help text of undocumented commands */ |
| 4889 | int show = 0; |
| 4890 | for(i=0; i<ArraySize(azHelp); i++){ |
| 4891 | if( azHelp[i][0]=='.' ){ |
| 4892 | show = 0; |
| 4893 | }else if( azHelp[i][0]==',' ){ |
| 4894 | show = 1; |
| 4895 | cli_printf(out, ".%s\n", &azHelp[i][1]); |
| 4896 | n++; |
| 4897 | }else if( show ){ |
| 4898 | cli_printf(out, "%s\n", azHelp[i]); |
| 4899 | } |
| 4900 | } |
| 4901 | return n; |
| 4902 | } |
| 4903 | |
| 4904 | /* Seek documented commands for which zPattern is an exact prefix */ |
| 4905 | zPat = sqlite3_mprintf(".%s*", zPattern[0]=='.' ? &zPattern[1] : zPattern); |
| 4906 | shell_check_oom(zPat); |
| 4907 | for(i=0; i<ArraySize(azHelp); i++){ |
| 4908 | if( sqlite3_strglob(zPat, azHelp[i])==0 ){ |
| 4909 | if( zHit ) cli_printf(out, "%s\n", zHit); |
| 4910 | zHit = azHelp[i]; |
| 4911 | j = i+1; |
| 4912 | n++; |
| 4913 | } |
| 4914 | } |
| 4915 | if( n ){ |
| 4916 | if( n==1 ){ |
| 4917 | const char *zUsage = findUsage(zPat); |
| 4918 | if( zUsage ){ |
| 4919 | cli_puts(zUsage, out); |
| 4920 | }else{ |
| 4921 | /* when zPattern is a prefix of exactly one command, then include |
| 4922 | ** the details of that command, which should begin at offset j */ |
| 4923 | cli_printf(out, "%s\n", zHit); |
| 4924 | while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){ |
| 4925 | cli_printf(out, "%s\n", azHelp[j]); |
| 4926 | j++; |
| 4927 | } |
| 4928 | } |
| 4929 | }else{ |
| 4930 | cli_printf(out, "%s\n", zHit); |
| 4931 | } |
| 4932 | } |
| 4933 | sqlite3_free(zPat); |
| 4934 | if( n ) return n; |
| 4935 | |
| 4936 | /* Look for documented commands that contain zPattern anywhere. |
| 4937 | ** Show complete text of all documented commands that match. */ |
| 4938 | zPat = sqlite3_mprintf("%%%s%%", zPattern); |
| 4939 | shell_check_oom(zPat); |
| 4940 | for(i=0; i<ArraySize(azHelp); i++){ |
| 4941 | if( azHelp[i][0]==',' ){ |
| 4942 | while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i; |
| 4943 | continue; |
| 4944 | } |
| 4945 | if( azHelp[i][0]=='.' ) j = i; |
| 4946 | if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){ |
| 4947 | cli_printf(out, "%s\n", azHelp[j]); |
| 4948 | while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){ |
| 4949 | j++; |
| 4950 | cli_printf(out, "%s\n", azHelp[j]); |
| 4951 | } |
| 4952 | i = j; |
| 4953 | n++; |
| 4954 | } |
| 4955 | } |
| 4956 | sqlite3_free(zPat); |
| 4957 | return n; |
| 4958 | } |
| 4959 | |
| 4960 | /* Forward reference */ |
| 4961 | static int process_input(ShellState *p, const char*); |
| 4962 | |
| 4963 | /* |
| 4964 | ** Read the content of file zName into memory obtained from sqlite3_malloc64() |
| 4965 | ** and return a pointer to the buffer. The caller is responsible for freeing |
| 4966 | ** the memory. |
| 4967 | ** |
| 4968 | ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes |
| 4969 | ** read. |
| 4970 | ** |
| 4971 | ** For convenience, a nul-terminator byte is always appended to the data read |
| 4972 | ** from the file before the buffer is returned. This byte is not included in |
| 4973 | ** the final value of (*pnByte), if applicable. |
| 4974 | ** |
| 4975 | ** NULL is returned if any error is encountered. The final value of *pnByte |
| 4976 | ** is undefined in this case. |
| 4977 | */ |
| 4978 | static char *readFile(const char *zName, int *pnByte){ |
| 4979 | FILE *in = sqlite3_fopen(zName, "rb"); |
| 4980 | long nIn; |
| 4981 | size_t nRead; |
| 4982 | char *pBuf; |
| 4983 | int rc; |
| 4984 | if( in==0 ) return 0; |
| 4985 | rc = fseek(in, 0, SEEK_END); |
| 4986 | if( rc!=0 ){ |
| 4987 | cli_printf(stderr,"Error: '%s' not seekable\n", zName); |
| 4988 | fclose(in); |
| 4989 | return 0; |
| 4990 | } |
| 4991 | nIn = ftell(in); |
| 4992 | if( nIn<0 ){ |
| 4993 | cli_printf(stderr,"Error: cannot read '%s'\n", zName); |
| 4994 | fclose(in); |
| 4995 | return 0; |
| 4996 | } |
| 4997 | rewind(in); |
| 4998 | pBuf = sqlite3_malloc64( nIn+1 ); |
| 4999 | if( pBuf==0 ){ |
| 5000 | cli_puts("Error: out of memory\n", stderr); |
| 5001 | fclose(in); |
| 5002 | return 0; |
| 5003 | } |
| 5004 | nRead = fread(pBuf, 1, nIn, in); |
| 5005 | fclose(in); |
| 5006 | if( nRead!=(size_t)nIn ){ |
| 5007 | sqlite3_free(pBuf); |
| 5008 | cli_printf(stderr,"Error: cannot read '%s'\n", zName); |
| 5009 | return 0; |
| 5010 | } |
| 5011 | pBuf[nIn] = 0; |
| 5012 | if( pnByte ) *pnByte = nIn; |
| 5013 | return pBuf; |
| 5014 | } |
| 5015 | |
| 5016 | #if defined(SQLITE_ENABLE_SESSION) |
| 5017 | /* |
| 5018 | ** Close a single OpenSession object and release all of its associated |
| 5019 | ** resources. |
| 5020 | */ |
| 5021 | static void session_close(OpenSession *pSession){ |
| 5022 | int i; |
| 5023 | sqlite3session_delete(pSession->p); |
| 5024 | sqlite3_free(pSession->zName); |
| 5025 | for(i=0; i<pSession->nFilter; i++){ |
| 5026 | sqlite3_free(pSession->azFilter[i]); |
| 5027 | } |
| 5028 | sqlite3_free(pSession->azFilter); |
| 5029 | memset(pSession, 0, sizeof(OpenSession)); |
| 5030 | } |
| 5031 | #endif |
| 5032 | |
| 5033 | /* |
| 5034 | ** Close all OpenSession objects and release all associated resources. |
| 5035 | */ |
| 5036 | #if defined(SQLITE_ENABLE_SESSION) |
| 5037 | static void session_close_all(ShellState *p, int i){ |
| 5038 | int j; |
| 5039 | struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i]; |
| 5040 | for(j=0; j<pAuxDb->nSession; j++){ |
| 5041 | session_close(&pAuxDb->aSession[j]); |
| 5042 | } |
| 5043 | pAuxDb->nSession = 0; |
| 5044 | } |
| 5045 | #else |
| 5046 | # define session_close_all(X,Y) |
| 5047 | #endif |
| 5048 | |
| 5049 | /* |
| 5050 | ** Implementation of the xFilter function for an open session. Omit |
| 5051 | ** any tables named by ".session filter" but let all other table through. |
| 5052 | */ |
| 5053 | #if defined(SQLITE_ENABLE_SESSION) |
| 5054 | static int session_filter(void *pCtx, const char *zTab){ |
| 5055 | OpenSession *pSession = (OpenSession*)pCtx; |
| 5056 | int i; |
| 5057 | for(i=0; i<pSession->nFilter; i++){ |
| 5058 | if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0; |
| 5059 | } |
| 5060 | return 1; |
| 5061 | } |
| 5062 | #endif |
| 5063 | |
| 5064 | /* |
| 5065 | ** Return the size of the named file in bytes. Or return a negative |
| 5066 | ** number if the file does not exist. |
| 5067 | */ |
| 5068 | static sqlite3_int64 fileSize(const char *zFile){ |
| 5069 | #if defined(_WIN32) || defined(WIN32) |
| 5070 | struct _stat64 x; |
| 5071 | if( _stat64(zFile, &x)!=0 ) return -1; |
| 5072 | return (sqlite3_int64)x.st_size; |
| 5073 | #else |
| 5074 | struct stat x; |
| 5075 | if( stat(zFile, &x)!=0 ) return -1; |
| 5076 | return (sqlite3_int64)x.st_size; |
| 5077 | #endif |
| 5078 | } |
| 5079 | |
| 5080 | /* |
| 5081 | ** Return true if zFile is an SQLite database. |
| 5082 | ** |
| 5083 | ** Algorithm: |
| 5084 | ** * If the file does not exist -> return false |
| 5085 | ** * If the size of the file is not a multiple of 512 -> return false |
| 5086 | ** * If sqlite3_open() fails -> return false |
| 5087 | ** * if sqlite3_prepare() or sqlite3_step() fails -> return false |
| 5088 | ** * Otherwise -> return true |
| 5089 | */ |
| 5090 | static int isDatabaseFile(const char *zFile, int openFlags){ |
| 5091 | sqlite3 *db = 0; |
| 5092 | sqlite3_stmt *pStmt = 0; |
| 5093 | int rc; |
| 5094 | sqlite3_int64 sz = fileSize(zFile); |
| 5095 | if( sz<512 || (sz%512)!=0 ) return 0; |
| 5096 | if( sqlite3_open_v2(zFile, &db, openFlags, 0)==SQLITE_OK |
| 5097 | && sqlite3_prepare_v2(db,"SELECT count(*) FROM sqlite_schema",-1,&pStmt,0) |
| 5098 | ==SQLITE_OK |
| 5099 | && sqlite3_step(pStmt)==SQLITE_ROW |
| 5100 | ){ |
| 5101 | rc = 1; |
| 5102 | }else{ |
| 5103 | rc = 0; |
| 5104 | } |
| 5105 | sqlite3_finalize(pStmt); |
| 5106 | sqlite3_close(db); |
| 5107 | return rc; |
| 5108 | } |
| 5109 | |
| 5110 | /* |
| 5111 | ** Try to deduce the type of file for zName based on its content. Return |
| 5112 | ** one of the SHELL_OPEN_* constants. |
| 5113 | ** |
| 5114 | ** If the file does not exist or is empty but its name looks like a ZIP |
| 5115 | ** archive and the dfltZip flag is true, then assume it is a ZIP archive. |
| 5116 | ** Otherwise, assume an ordinary database regardless of the filename if |
| 5117 | ** the type cannot be determined from content. |
| 5118 | */ |
| 5119 | int deduceDatabaseType(const char *zName, int dfltZip, int openFlags){ |
| 5120 | FILE *f; |
| 5121 | size_t n; |
| 5122 | int rc = SHELL_OPEN_UNSPEC; |
| 5123 | char zBuf[100]; |
| 5124 | if( access(zName,0)!=0 ) goto database_type_by_name; |
| 5125 | if( isDatabaseFile(zName, openFlags) ){ |
| 5126 | rc = SHELL_OPEN_NORMAL; |
| 5127 | } |
| 5128 | if( rc==SHELL_OPEN_NORMAL ) return SHELL_OPEN_NORMAL; |
| 5129 | f = sqlite3_fopen(zName, "rb"); |
| 5130 | if( f==0 ) goto database_type_by_name; |
| 5131 | n = fread(zBuf, 16, 1, f); |
| 5132 | if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){ |
| 5133 | fclose(f); |
| 5134 | return SHELL_OPEN_NORMAL; |
| 5135 | } |
| 5136 | fseek(f, -25, SEEK_END); |
| 5137 | n = fread(zBuf, 25, 1, f); |
| 5138 | if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){ |
| 5139 | rc = SHELL_OPEN_APPENDVFS; |
| 5140 | }else{ |
| 5141 | fseek(f, -22, SEEK_END); |
| 5142 | n = fread(zBuf, 22, 1, f); |
| 5143 | if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05 |
| 5144 | && zBuf[3]==0x06 ){ |
| 5145 | rc = SHELL_OPEN_ZIPFILE; |
| 5146 | }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ |
| 5147 | rc = SHELL_OPEN_ZIPFILE; |
| 5148 | } |
| 5149 | } |
| 5150 | fclose(f); |
| 5151 | return rc; |
| 5152 | |
| 5153 | database_type_by_name: |
| 5154 | if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ |
| 5155 | rc = SHELL_OPEN_ZIPFILE; |
| 5156 | }else{ |
| 5157 | rc = SHELL_OPEN_NORMAL; |
| 5158 | } |
| 5159 | return rc; |
| 5160 | } |
| 5161 | |
| 5162 | /* |
| 5163 | ** If the text in z[] is the name of a readable file and that file appears |
| 5164 | ** to contain SQL text and/or dot-commands, then return true. If z[] is |
| 5165 | ** not a file, or if the file is unreadable, or if the file is a database |
| 5166 | ** or anything else that is not SQL text and dot-commands, then return false. |
| 5167 | ** |
| 5168 | ** If the bLeaveUninit flag is set, then be sure to leave SQLite in an |
| 5169 | ** uninitialized state. This means invoking sqlite3_shutdown() after any |
| 5170 | ** SQLite API is used. |
| 5171 | ** |
| 5172 | ** Some amount of guesswork is involved in this decision. |
| 5173 | */ |
| 5174 | static int isScriptFile(const char *z, int bLeaveUninit){ |
| 5175 | sqlite3_int64 sz = fileSize(z); |
| 5176 | if( sz<=0 ) return 0; |
| 5177 | if( (sz%512)==0 ){ |
| 5178 | int rc; |
| 5179 | sqlite3_initialize(); |
| 5180 | rc = isDatabaseFile(z, SQLITE_OPEN_READONLY); |
| 5181 | if( bLeaveUninit ){ |
| 5182 | sqlite3_shutdown(); |
| 5183 | } |
| 5184 | if( rc ) return 0; /* Is a database */ |
| 5185 | } |
| 5186 | if( sqlite3_strlike("%.sql",z,0)==0 ) return 1; |
| 5187 | if( sqlite3_strlike("%.txt",z,0)==0 ) return 1; |
| 5188 | if( sqlite3_strlike("%.clitest",z,0)==0 ) return 1; |
| 5189 | return 0; |
| 5190 | } |
| 5191 | |
| 5192 | #ifndef SQLITE_OMIT_DESERIALIZE |
| 5193 | /* |
| 5194 | ** Reconstruct an in-memory database using the output from the "dbtotxt" |
| 5195 | ** program. Read content from the file in p->aAuxDb[].zDbFilename. |
| 5196 | ** If p->aAuxDb[].zDbFilename is 0, then read from standard input. |
| 5197 | */ |
| 5198 | static unsigned char *readHexDb(ShellState *p, int *pnData){ |
| 5199 | unsigned char *a = 0; |
| 5200 | i64 nLine; |
| 5201 | int n = 0; /* Size of db per first line of hex dump */ |
| 5202 | i64 sz = 0; /* n rounded up to nearest page boundary */ |
| 5203 | int pgsz = 0; |
| 5204 | i64 iOffset = 0; |
| 5205 | int rc; |
| 5206 | FILE *in; |
| 5207 | const char *zDbFilename = p->pAuxDb->zDbFilename; |
| 5208 | unsigned int x[16]; |
| 5209 | char zLine[1000]; |
| 5210 | if( zDbFilename ){ |
| 5211 | in = sqlite3_fopen(zDbFilename, "r"); |
| 5212 | if( in==0 ){ |
| 5213 | cli_printf(stderr,"cannot open \"%s\" for reading\n", zDbFilename); |
| 5214 | return 0; |
| 5215 | } |
| 5216 | nLine = 0; |
| 5217 | }else{ |
| 5218 | in = p->in; |
| 5219 | nLine = p->lineno; |
| 5220 | if( in==0 ) in = stdin; |
| 5221 | } |
| 5222 | *pnData = 0; |
| 5223 | nLine++; |
| 5224 | if( shell_fgets(p, zLine, sizeof(zLine), in)==0 ) goto readHexDb_error; |
| 5225 | rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz); |
| 5226 | if( rc!=2 ) goto readHexDb_error; |
| 5227 | if( n<0 ) goto readHexDb_error; |
| 5228 | if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){ |
| 5229 | cli_puts("invalid pagesize\n", stderr); |
| 5230 | goto readHexDb_error; |
| 5231 | } |
| 5232 | sz = ((i64)n+pgsz-1)&~(pgsz-1); /* Round up to nearest multiple of pgsz */ |
| 5233 | a = sqlite3_malloc64( sz ? sz : 1 ); |
| 5234 | shell_check_oom(a); |
| 5235 | memset(a, 0, sz); |
| 5236 | for(nLine++; shell_fgets(p, zLine, sizeof(zLine), in)!=0; nLine++){ |
| 5237 | int j = 0; /* Page number from "| page" line */ |
| 5238 | int k = 0; /* Offset from "| page" line */ |
| 5239 | if( nLine>=2000000000 ){ |
| 5240 | cli_printf(stderr, "input too big\n"); |
| 5241 | goto readHexDb_error; |
| 5242 | } |
| 5243 | rc = sscanf(zLine, "| page %d offset %d", &j, &k); |
| 5244 | if( rc==2 ){ |
| 5245 | iOffset = k; |
| 5246 | continue; |
| 5247 | } |
| 5248 | if( cli_strncmp(zLine, "| end ", 6)==0 ){ |
| 5249 | break; |
| 5250 | } |
| 5251 | rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x", |
| 5252 | &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7], |
| 5253 | &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]); |
| 5254 | if( rc==17 ){ |
| 5255 | i64 iOff = iOffset+j; |
| 5256 | if( iOff+16<=sz && iOff>=0 ){ |
| 5257 | int ii; |
| 5258 | for(ii=0; ii<16; ii++) a[iOff+ii] = x[ii]&0xff; |
| 5259 | } |
| 5260 | } |
| 5261 | } |
| 5262 | *pnData = sz; |
| 5263 | if( in!=p->in ){ |
| 5264 | fclose(in); |
| 5265 | }else{ |
| 5266 | p->lineno = nLine; |
| 5267 | } |
| 5268 | return a; |
| 5269 | |
| 5270 | readHexDb_error: |
| 5271 | if( in!=p->in ){ |
| 5272 | fclose(in); |
| 5273 | }else{ |
| 5274 | while( shell_fgets(p, zLine, sizeof(zLine), p->in)!=0 ){ |
| 5275 | nLine++; |
| 5276 | if(cli_strncmp(zLine, "| end ", 6)==0 ) break; |
| 5277 | } |
| 5278 | p->lineno = nLine; |
| 5279 | } |
| 5280 | sqlite3_free(a); |
| 5281 | cli_printf(stderr,"Error on line %lld of --hexdb input\n", nLine); |
| 5282 | return 0; |
| 5283 | } |
| 5284 | #endif /* SQLITE_OMIT_DESERIALIZE */ |
| 5285 | |
| 5286 | /* |
| 5287 | ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X. |
| 5288 | */ |
| 5289 | static void shellUSleepFunc( |
| 5290 | sqlite3_context *context, |
| 5291 | int argcUnused, |
| 5292 | sqlite3_value **argv |
| 5293 | ){ |
| 5294 | int sleep = sqlite3_value_int(argv[0]); |
| 5295 | (void)argcUnused; |
| 5296 | sqlite3_sleep(sleep/1000); |
| 5297 | sqlite3_result_int(context, sleep); |
| 5298 | } |
| 5299 | |
| 5300 | /* |
| 5301 | ** SQL function: dualrep(X) |
| 5302 | ** |
| 5303 | ** Return the value X. But if X is in a numeric representation (an |
| 5304 | ** integer or a float) then return a dual-representation where the |
| 5305 | ** result is both numeric and text at the same time. This has no |
| 5306 | ** known practical application, but is useful in testing SQLite |
| 5307 | ** internals. |
| 5308 | */ |
| 5309 | static void shellDualRepFunc( |
| 5310 | sqlite3_context *context, |
| 5311 | int argcUnused, |
| 5312 | sqlite3_value **argv |
| 5313 | ){ |
| 5314 | (void)argcUnused; |
| 5315 | sqlite3_value_text(argv[0]); |
| 5316 | sqlite3_result_value(context, argv[0]); |
| 5317 | } |
| 5318 | |
| 5319 | /* |
| 5320 | ** SQL function: shell_module_schema(X) |
| 5321 | ** |
| 5322 | ** For use internally and for debugging and testing only. This function |
| 5323 | ** is subject to change or removal in future versions. |
| 5324 | ** |
| 5325 | ** Return a fake schema for the table-valued function or eponymous virtual |
| 5326 | ** table X. |
| 5327 | */ |
| 5328 | static void shellModuleSchema( |
| 5329 | sqlite3_context *pCtx, |
| 5330 | int nVal, |
| 5331 | sqlite3_value **apVal |
| 5332 | ){ |
| 5333 | const char *zName; |
| 5334 | char *zFake; |
| 5335 | ShellState *p = (ShellState*)sqlite3_user_data(pCtx); |
| 5336 | FILE *pSavedLog = p->pLog; |
| 5337 | UNUSED_PARAMETER(nVal); |
| 5338 | zName = (const char*)sqlite3_value_text(apVal[0]); |
| 5339 | |
| 5340 | /* Temporarily disable the ".log" when calling shellFakeSchema() because |
| 5341 | ** shellFakeSchema() might generate failures for some ephemeral virtual |
| 5342 | ** tables due to missing arguments. Example: fts4aux. |
| 5343 | ** https://sqlite.org/forum/forumpost/42fe6520b803be51 */ |
| 5344 | p->pLog = 0; |
| 5345 | zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0; |
| 5346 | p->pLog = pSavedLog; |
| 5347 | |
| 5348 | if( zFake ){ |
| 5349 | assert( strstr(zFake,"*/")==0 ); |
| 5350 | sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake), |
| 5351 | -1, sqlite3_free); |
| 5352 | sqlite3_free(zFake); |
| 5353 | } |
| 5354 | } |
| 5355 | |
| 5356 | /* Flags for open_db(). |
| 5357 | ** |
| 5358 | ** The default behavior of open_db() is to exit(1) if the database fails to |
| 5359 | ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error |
| 5360 | ** but still returns without calling exit. |
| 5361 | ** |
| 5362 | ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a |
| 5363 | ** ZIP archive if the file does not exist or is empty and its name matches |
| 5364 | ** the *.zip pattern. |
| 5365 | */ |
| 5366 | #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */ |
| 5367 | #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */ |
| 5368 | |
| 5369 | /* Forward reference */ |
| 5370 | static void shellTempFilenameFunc(sqlite3_context*,int,sqlite3_value**); |
| 5371 | |
| 5372 | /* |
| 5373 | ** Make sure the database is open. If it is not, then open it. If |
| 5374 | ** the database fails to open, print an error message and exit. |
| 5375 | */ |
| 5376 | static void open_db(ShellState *p, int openFlags){ |
| 5377 | if( p->db==0 ){ |
| 5378 | const char *zDbFilename = p->pAuxDb->zDbFilename; |
| 5379 | const char *zHOME; /* Value of HOME environment variable */ |
| 5380 | char *zToFree = 0; /* Filename with ~/ prefix expansion */ |
| 5381 | |
| 5382 | /* If the zDbFilename does not exist and begins with ~/ then replace |
| 5383 | ** the ~ with the home directory. |
| 5384 | */ |
| 5385 | if( zDbFilename && zDbFilename[0]=='~' |
| 5386 | #ifdef _WIN32 |
| 5387 | && (zDbFilename[1]=='/' || zDbFilename[1]=='\\') |
| 5388 | #else |
| 5389 | && zDbFilename[1]=='/' |
| 5390 | #endif |
| 5391 | && access(zDbFilename,0)!=0 |
| 5392 | && (zHOME = getenv("HOME"))!=0 && zHOME[0]!=0 |
| 5393 | ){ |
| 5394 | size_t nHOME = strlen(zHOME); |
| 5395 | size_t nFN = strlen(zDbFilename); |
| 5396 | zToFree = malloc(nHOME+nFN+1); |
| 5397 | if( zToFree ){ |
| 5398 | memcpy(zToFree, zHOME, nHOME); |
| 5399 | memcpy(zToFree+nHOME, zDbFilename+1, nFN); |
| 5400 | zDbFilename = zToFree; |
| 5401 | } |
| 5402 | } |
| 5403 | |
| 5404 | if( p->openMode==SHELL_OPEN_UNSPEC ){ |
| 5405 | if( zDbFilename==0 || zDbFilename[0]==0 ){ |
| 5406 | p->openMode = SHELL_OPEN_NORMAL; |
| 5407 | }else{ |
| 5408 | p->openMode = (u8)deduceDatabaseType(zDbFilename, |
| 5409 | (openFlags & OPEN_DB_ZIPFILE)!=0, p->openFlags); |
| 5410 | } |
| 5411 | } |
| 5412 | if( (p->openFlags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE))==0 ){ |
| 5413 | if( p->openFlags==0 ) p->openFlags = SQLITE_OPEN_CREATE; |
| 5414 | p->openFlags |= SQLITE_OPEN_READWRITE; |
| 5415 | } |
| 5416 | switch( p->openMode ){ |
| 5417 | case SHELL_OPEN_APPENDVFS: { |
| 5418 | sqlite3_open_v2(zDbFilename, &p->db, p->openFlags, "apndvfs"); |
| 5419 | break; |
| 5420 | } |
| 5421 | case SHELL_OPEN_HEXDB: |
| 5422 | case SHELL_OPEN_DESERIALIZE: { |
| 5423 | sqlite3_open(0, &p->db); |
| 5424 | break; |
| 5425 | } |
| 5426 | case SHELL_OPEN_ZIPFILE: { |
| 5427 | sqlite3_open(":memory:", &p->db); |
| 5428 | break; |
| 5429 | } |
| 5430 | case SHELL_OPEN_UNSPEC: |
| 5431 | case SHELL_OPEN_NORMAL: { |
| 5432 | sqlite3_open_v2(zDbFilename, &p->db, p->openFlags, 0); |
| 5433 | break; |
| 5434 | } |
| 5435 | } |
| 5436 | if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ |
| 5437 | cli_printf(stderr,"Error: unable to open database \"%s\": %s\n", |
| 5438 | zDbFilename, sqlite3_errmsg(p->db)); |
| 5439 | if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){ |
| 5440 | cli_exit(1); |
| 5441 | } |
| 5442 | sqlite3_close(p->db); |
| 5443 | sqlite3_open(":memory:", &p->db); |
| 5444 | if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ |
| 5445 | cli_puts("Also: unable to open substitute in-memory database.\n", |
| 5446 | stderr); |
| 5447 | cli_exit(1); |
| 5448 | }else{ |
| 5449 | cli_printf(stderr, |
| 5450 | "Notice: using substitute in-memory database instead of \"%s\"\n", |
| 5451 | zDbFilename); |
| 5452 | } |
| 5453 | } |
| 5454 | globalDb = p->db; |
| 5455 | sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0); |
| 5456 | |
| 5457 | /* Reflect the use or absence of --unsafe-testing invocation. */ |
| 5458 | { |
| 5459 | int testmode_on = ShellHasFlag(p,SHFLG_TestingMode); |
| 5460 | sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on, |
| 5461 | (int*)0); |
| 5462 | sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on, |
| 5463 | (int*)0); |
| 5464 | } |
| 5465 | |
| 5466 | #ifndef SQLITE_OMIT_LOAD_EXTENSION |
| 5467 | sqlite3_enable_load_extension(p->db, 1); |
| 5468 | #endif |
| 5469 | sqlite3_sha_init(p->db, 0, 0); |
| 5470 | sqlite3_shathree_init(p->db, 0, 0); |
| 5471 | sqlite3_uint_init(p->db, 0, 0); |
| 5472 | sqlite3_stmtrand_init(p->db, 0, 0); |
| 5473 | sqlite3_decimal_init(p->db, 0, 0); |
| 5474 | sqlite3_base64_init(p->db, 0, 0); |
| 5475 | sqlite3_base85_init(p->db, 0, 0); |
| 5476 | sqlite3_regexp_init(p->db, 0, 0); |
| 5477 | sqlite3_ieee_init(p->db, 0, 0); |
| 5478 | sqlite3_series_init(p->db, 0, 0); |
| 5479 | sqlite3_diskused_init(p->db, 0, 0); |
| 5480 | sqlite3_strdup_init(p->db, 0, 0); |
| 5481 | #ifndef SQLITE_SHELL_FIDDLE |
| 5482 | if( !p->bSafeMode ){ |
| 5483 | sqlite3_fileio_init(p->db, 0, 0); |
| 5484 | } |
| 5485 | sqlite3_completion_init(p->db, 0, 0); |
| 5486 | #endif |
| 5487 | #ifdef SQLITE_HAVE_ZLIB |
| 5488 | if( !p->bSafeModePersist ){ |
| 5489 | sqlite3_zipfile_init(p->db, 0, 0); |
| 5490 | sqlite3_sqlar_init(p->db, 0, 0); |
| 5491 | } |
| 5492 | #endif |
| 5493 | #ifdef SQLITE_SHELL_EXTFUNCS |
| 5494 | /* Create a preprocessing mechanism for extensions to make |
| 5495 | * their own provisions for being built into the shell. |
| 5496 | * This is a short-span macro. See further below for usage. |
| 5497 | */ |
| 5498 | #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant |
| 5499 | #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant) |
| 5500 | /* Let custom-included extensions get their ..._init() called. |
| 5501 | * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause |
| 5502 | * the extension's sqlite3_*_init( db, pzErrorMsg, pApi ) |
| 5503 | * initialization routine to be called. |
| 5504 | */ |
| 5505 | { |
| 5506 | int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db); |
| 5507 | /* Let custom-included extensions expose their functionality. |
| 5508 | * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause |
| 5509 | * the SQL functions, virtual tables, collating sequences or |
| 5510 | * VFS's implemented by the extension to be registered. |
| 5511 | */ |
| 5512 | if( irc==SQLITE_OK |
| 5513 | || irc==SQLITE_OK_LOAD_PERMANENTLY ){ |
| 5514 | SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0); |
| 5515 | } |
| 5516 | #undef SHELL_SUB_MACRO |
| 5517 | #undef SHELL_SUBMACRO |
| 5518 | } |
| 5519 | #endif |
| 5520 | |
| 5521 | sqlite3_create_function(p->db, "capable", 1, SQLITE_UTF8, p, |
| 5522 | shellCapable, 0, 0); |
| 5523 | sqlite3_create_function(p->db, "strtod", 1, SQLITE_UTF8, 0, |
| 5524 | shellStrtod, 0, 0); |
| 5525 | sqlite3_create_function(p->db, "dtostr", 1, SQLITE_UTF8, 0, |
| 5526 | shellDtostr, 0, 0); |
| 5527 | sqlite3_create_function(p->db, "dtostr", 2, SQLITE_UTF8, 0, |
| 5528 | shellDtostr, 0, 0); |
| 5529 | sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0, |
| 5530 | shellAddSchemaName, 0, 0); |
| 5531 | sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, p, |
| 5532 | shellModuleSchema, 0, 0); |
| 5533 | sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p, |
| 5534 | shellPutsFunc, 0, 0); |
| 5535 | sqlite3_create_function(p->db, "shell_format_schema", 2, SQLITE_UTF8, p, |
| 5536 | shellFormatSchema, 0, 0); |
| 5537 | sqlite3_create_function(p->db, "shell_complete_sql", 1, SQLITE_UTF8, p, |
| 5538 | shell_complete_sql, 0, 0); |
| 5539 | sqlite3_create_function(p->db, "shell_complete_sql", 2, SQLITE_UTF8, p, |
| 5540 | shell_complete_sql, 0, 0); |
| 5541 | sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0, |
| 5542 | shellUSleepFunc, 0, 0); |
| 5543 | sqlite3_create_function(p->db, "dualrep",1,SQLITE_UTF8,0, |
| 5544 | shellDualRepFunc, 0, 0); |
| 5545 | #ifndef SQLITE_NOHAVE_SYSTEM |
| 5546 | sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0, |
| 5547 | editFunc, 0, 0); |
| 5548 | sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0, |
| 5549 | editFunc, 0, 0); |
| 5550 | #endif |
| 5551 | sqlite3_create_function(p->db, "shell_prompt_test", -1, SQLITE_UTF8, |
| 5552 | p, shellExpandPrompt, 0, 0); |
| 5553 | sqlite3_create_function(p->db, "shell_temp_filename", 1, SQLITE_UTF8, |
| 5554 | p, shellTempFilenameFunc, 0, 0); |
| 5555 | #ifdef SQLITE_DEBUG |
| 5556 | sqlite3_create_function(p->db, "sqlite3_incomplete", 1, SQLITE_UTF8, |
| 5557 | p, shellIncompleteFunc, 0, 0); |
| 5558 | #endif |
| 5559 | |
| 5560 | |
| 5561 | if( p->openMode==SHELL_OPEN_ZIPFILE ){ |
| 5562 | char *zSql = sqlite3_mprintf( |
| 5563 | "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename); |
| 5564 | shell_check_oom(zSql); |
| 5565 | sqlite3_exec(p->db, zSql, 0, 0, 0); |
| 5566 | sqlite3_free(zSql); |
| 5567 | } |
| 5568 | #ifndef SQLITE_OMIT_DESERIALIZE |
| 5569 | else |
| 5570 | if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){ |
| 5571 | int rc; |
| 5572 | int nData = 0; |
| 5573 | unsigned char *aData; |
| 5574 | if( p->openMode==SHELL_OPEN_DESERIALIZE ){ |
| 5575 | aData = (unsigned char*)readFile(zDbFilename, &nData); |
| 5576 | }else{ |
| 5577 | aData = readHexDb(p, &nData); |
| 5578 | } |
| 5579 | if( aData==0 ){ |
| 5580 | return; |
| 5581 | } |
| 5582 | rc = sqlite3_deserialize(p->db, "main", aData, nData, nData, |
| 5583 | SQLITE_DESERIALIZE_RESIZEABLE | |
| 5584 | SQLITE_DESERIALIZE_FREEONCLOSE); |
| 5585 | if( rc ){ |
| 5586 | cli_printf(stderr,"Error: sqlite3_deserialize() returns %d\n", rc); |
| 5587 | } |
| 5588 | if( p->szMax>0 ){ |
| 5589 | sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax); |
| 5590 | } |
| 5591 | } |
| 5592 | #endif |
| 5593 | free(zToFree); |
| 5594 | } |
| 5595 | if( p->db!=0 ){ |
| 5596 | #ifndef SQLITE_OMIT_AUTHORIZATION |
| 5597 | if( p->bSafeModePersist ){ |
| 5598 | sqlite3_set_authorizer(p->db, safeModeAuth, p); |
| 5599 | } |
| 5600 | #endif |
| 5601 | sqlite3_db_config( |
| 5602 | p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->mode.scanstatsOn, (int*)0 |
| 5603 | ); |
| 5604 | } |
| 5605 | } |
| 5606 | |
| 5607 | /* |
| 5608 | ** Attempt to close the database connection. Report errors. |
| 5609 | */ |
| 5610 | void close_db(sqlite3 *db){ |
| 5611 | int rc = sqlite3_close(db); |
| 5612 | if( rc ){ |
| 5613 | cli_printf(stderr, |
| 5614 | "Error: sqlite3_close() returns %d: %s\n", rc, sqlite3_errmsg(db)); |
| 5615 | } |
| 5616 | } |
| 5617 | |
| 5618 | #if (HAVE_READLINE || HAVE_EDITLINE) \ |
| 5619 | && !defined(SQLITE_OMIT_READLINE_COMPLETION) |
| 5620 | /* |
| 5621 | ** Readline completion callbacks |
| 5622 | */ |
| 5623 | static char *readline_completion_generator(const char *text, int state){ |
| 5624 | static sqlite3_stmt *pStmt = 0; |
| 5625 | char *zRet; |
| 5626 | if( state==0 ){ |
| 5627 | char *zSql; |
| 5628 | sqlite3_finalize(pStmt); |
| 5629 | zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" |
| 5630 | " FROM completion(%Q) ORDER BY 1", text); |
| 5631 | shell_check_oom(zSql); |
| 5632 | sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); |
| 5633 | sqlite3_free(zSql); |
| 5634 | } |
| 5635 | if( sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 5636 | const char *z = (const char*)sqlite3_column_text(pStmt,0); |
| 5637 | zRet = z ? strdup(z) : 0; |
| 5638 | }else{ |
| 5639 | sqlite3_finalize(pStmt); |
| 5640 | pStmt = 0; |
| 5641 | zRet = 0; |
| 5642 | } |
| 5643 | return zRet; |
| 5644 | } |
| 5645 | static char **readline_completion(const char *zText, int iStart, int iEnd){ |
| 5646 | (void)iStart; |
| 5647 | (void)iEnd; |
| 5648 | rl_attempted_completion_over = 1; |
| 5649 | return rl_completion_matches(zText, readline_completion_generator); |
| 5650 | } |
| 5651 | |
| 5652 | #elif HAVE_LINENOISE |
| 5653 | /* |
| 5654 | ** Linenoise completion callback. Note that the 3rd argument is from |
| 5655 | ** the "msteveb" version of linenoise, not the "antirez" version. |
| 5656 | */ |
| 5657 | static void linenoise_completion( |
| 5658 | const char *zLine, |
| 5659 | linenoiseCompletions *lc |
| 5660 | #if HAVE_LINENOISE==2 |
| 5661 | ,void *pUserData |
| 5662 | #endif |
| 5663 | ){ |
| 5664 | i64 nLine = strlen(zLine); |
| 5665 | i64 i, iStart; |
| 5666 | sqlite3_stmt *pStmt = 0; |
| 5667 | char *zSql; |
| 5668 | char zBuf[1000]; |
| 5669 | |
| 5670 | #if HAVE_LINENOISE==2 |
| 5671 | UNUSED_PARAMETER(pUserData); |
| 5672 | #endif |
| 5673 | if( nLine>(i64)sizeof(zBuf)-30 ) return; |
| 5674 | if( zLine[0]=='.' || zLine[0]=='#') return; |
| 5675 | for(i=nLine-1; i>=0 && (IsAlnum(zLine[i]) || zLine[i]=='_'); i--){} |
| 5676 | if( i==nLine-1 ) return; |
| 5677 | iStart = i+1; |
| 5678 | memcpy(zBuf, zLine, iStart); |
| 5679 | zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" |
| 5680 | " FROM completion(%Q,%Q) ORDER BY 1", |
| 5681 | &zLine[iStart], zLine); |
| 5682 | shell_check_oom(zSql); |
| 5683 | sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); |
| 5684 | sqlite3_free(zSql); |
| 5685 | sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */ |
| 5686 | while( sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 5687 | const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0); |
| 5688 | int nCompletion = sqlite3_column_bytes(pStmt, 0); |
| 5689 | if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){ |
| 5690 | memcpy(zBuf+iStart, zCompletion, nCompletion+1); |
| 5691 | linenoiseAddCompletion(lc, zBuf); |
| 5692 | } |
| 5693 | } |
| 5694 | sqlite3_finalize(pStmt); |
| 5695 | } |
| 5696 | #endif |
| 5697 | |
| 5698 | /* |
| 5699 | ** Do C-language style dequoting. |
| 5700 | ** |
| 5701 | ** \a -> alarm |
| 5702 | ** \b -> backspace |
| 5703 | ** \t -> tab |
| 5704 | ** \n -> newline |
| 5705 | ** \v -> vertical tab |
| 5706 | ** \f -> form feed |
| 5707 | ** \r -> carriage return |
| 5708 | ** \s -> space |
| 5709 | ** \" -> " |
| 5710 | ** \' -> ' |
| 5711 | ** \\ -> backslash |
| 5712 | ** \NNN -> ascii character NNN in octal |
| 5713 | ** \xHH -> ascii character HH in hexadecimal |
| 5714 | */ |
| 5715 | static void resolve_backslashes(char *z){ |
| 5716 | int i, j; |
| 5717 | char c; |
| 5718 | while( *z && *z!='\\' ) z++; |
| 5719 | for(i=j=0; (c = z[i])!=0; i++, j++){ |
| 5720 | if( c=='\\' && z[i+1]!=0 ){ |
| 5721 | c = z[++i]; |
| 5722 | if( c=='a' ){ |
| 5723 | c = '\a'; |
| 5724 | }else if( c=='b' ){ |
| 5725 | c = '\b'; |
| 5726 | }else if( c=='t' ){ |
| 5727 | c = '\t'; |
| 5728 | }else if( c=='n' ){ |
| 5729 | c = '\n'; |
| 5730 | }else if( c=='v' ){ |
| 5731 | c = '\v'; |
| 5732 | }else if( c=='f' ){ |
| 5733 | c = '\f'; |
| 5734 | }else if( c=='r' ){ |
| 5735 | c = '\r'; |
| 5736 | }else if( c=='"' ){ |
| 5737 | c = '"'; |
| 5738 | }else if( c=='\'' ){ |
| 5739 | c = '\''; |
| 5740 | }else if( c=='\\' ){ |
| 5741 | c = '\\'; |
| 5742 | }else if( c=='x' ){ |
| 5743 | int nhd = 0, hdv; |
| 5744 | u8 hv = 0; |
| 5745 | while( nhd<2 && (c=z[i+1+nhd])!=0 && (hdv=hexDigitValue(c))>=0 ){ |
| 5746 | hv = (u8)((hv<<4)|hdv); |
| 5747 | ++nhd; |
| 5748 | } |
| 5749 | i += nhd; |
| 5750 | c = (u8)hv; |
| 5751 | }else if( c>='0' && c<='7' ){ |
| 5752 | c -= '0'; |
| 5753 | if( z[i+1]>='0' && z[i+1]<='7' ){ |
| 5754 | i++; |
| 5755 | c = (c<<3) + z[i] - '0'; |
| 5756 | if( z[i+1]>='0' && z[i+1]<='7' ){ |
| 5757 | i++; |
| 5758 | c = (c<<3) + z[i] - '0'; |
| 5759 | } |
| 5760 | } |
| 5761 | } |
| 5762 | } |
| 5763 | z[j] = c; |
| 5764 | } |
| 5765 | if( j<i ) z[j] = 0; |
| 5766 | } |
| 5767 | |
| 5768 | /* |
| 5769 | ** Interpret zArg as either an integer or a boolean value. Return 1 or 0 |
| 5770 | ** for TRUE and FALSE. Return the integer value if appropriate. |
| 5771 | */ |
| 5772 | static int booleanValue(const char *zArg){ |
| 5773 | int i; |
| 5774 | if( zArg[0]=='0' && zArg[1]=='x' ){ |
| 5775 | for(i=2; hexDigitValue(zArg[i])>=0; i++){} |
| 5776 | }else{ |
| 5777 | for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} |
| 5778 | } |
| 5779 | if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); |
| 5780 | if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ |
| 5781 | return 1; |
| 5782 | } |
| 5783 | if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ |
| 5784 | return 0; |
| 5785 | } |
| 5786 | cli_printf(stderr, |
| 5787 | "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", zArg); |
| 5788 | return 0; |
| 5789 | } |
| 5790 | |
| 5791 | /* |
| 5792 | ** Set or clear a shell flag according to a boolean value. |
| 5793 | */ |
| 5794 | static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){ |
| 5795 | if( booleanValue(zArg) ){ |
| 5796 | ShellSetFlag(p, mFlag); |
| 5797 | }else{ |
| 5798 | ShellClearFlag(p, mFlag); |
| 5799 | } |
| 5800 | } |
| 5801 | |
| 5802 | /* |
| 5803 | ** Close an output file, assuming it is not stderr or stdout |
| 5804 | */ |
| 5805 | static void output_file_close(FILE *f){ |
| 5806 | if( f && f!=stdout && f!=stderr ) fclose(f); |
| 5807 | } |
| 5808 | |
| 5809 | /* |
| 5810 | ** Try to open an output file. The names "stdout" and "stderr" are |
| 5811 | ** recognized and do the right thing. NULL is returned if the output |
| 5812 | ** filename is "off". |
| 5813 | */ |
| 5814 | static FILE *output_file_open(ShellState *p, const char *zFile){ |
| 5815 | FILE *f; |
| 5816 | if( cli_strcmp(zFile,"stdout")==0 ){ |
| 5817 | f = stdout; |
| 5818 | }else if( cli_strcmp(zFile, "stderr")==0 ){ |
| 5819 | f = stderr; |
| 5820 | }else if( cli_strcmp(zFile, "off")==0 || p->bSafeMode ){ |
| 5821 | f = 0; |
| 5822 | }else{ |
| 5823 | f = sqlite3_fopen(zFile, "w"); |
| 5824 | if( f==0 ){ |
| 5825 | cli_printf(stderr,"Error: cannot open \"%s\"\n", zFile); |
| 5826 | } |
| 5827 | } |
| 5828 | return f; |
| 5829 | } |
| 5830 | |
| 5831 | #ifndef SQLITE_OMIT_TRACE |
| 5832 | /* |
| 5833 | ** A routine for handling output from sqlite3_trace(). |
| 5834 | */ |
| 5835 | static int sql_trace_callback( |
| 5836 | unsigned mType, /* The trace type */ |
| 5837 | void *pArg, /* The ShellState pointer */ |
| 5838 | void *pP, /* Usually a pointer to sqlite_stmt */ |
| 5839 | void *pX /* Auxiliary output */ |
| 5840 | ){ |
| 5841 | ShellState *p = (ShellState*)pArg; |
| 5842 | sqlite3_stmt *pStmt; |
| 5843 | const char *zSql; |
| 5844 | i64 nSql; |
| 5845 | if( p->traceOut==0 ) return 0; |
| 5846 | if( mType==SQLITE_TRACE_CLOSE ){ |
| 5847 | sputz(p->traceOut, "-- closing database connection\n"); |
| 5848 | return 0; |
| 5849 | } |
| 5850 | if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){ |
| 5851 | zSql = (const char*)pX; |
| 5852 | }else{ |
| 5853 | pStmt = (sqlite3_stmt*)pP; |
| 5854 | switch( p->eTraceType ){ |
| 5855 | case SHELL_TRACE_EXPANDED: { |
| 5856 | zSql = sqlite3_expanded_sql(pStmt); |
| 5857 | break; |
| 5858 | } |
| 5859 | #ifdef SQLITE_ENABLE_NORMALIZE |
| 5860 | case SHELL_TRACE_NORMALIZED: { |
| 5861 | zSql = sqlite3_normalized_sql(pStmt); |
| 5862 | break; |
| 5863 | } |
| 5864 | #endif |
| 5865 | default: { |
| 5866 | zSql = sqlite3_sql(pStmt); |
| 5867 | break; |
| 5868 | } |
| 5869 | } |
| 5870 | } |
| 5871 | if( zSql==0 ) return 0; |
| 5872 | nSql = strlen(zSql); |
| 5873 | if( nSql>1000000000 ) nSql = 1000000000; |
| 5874 | while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; } |
| 5875 | switch( mType ){ |
| 5876 | case SQLITE_TRACE_ROW: |
| 5877 | case SQLITE_TRACE_STMT: { |
| 5878 | cli_printf(p->traceOut, "%.*s;\n", (int)nSql, zSql); |
| 5879 | break; |
| 5880 | } |
| 5881 | case SQLITE_TRACE_PROFILE: { |
| 5882 | sqlite3_int64 nNanosec = pX ? *(sqlite3_int64*)pX : 0; |
| 5883 | cli_printf(p->traceOut, |
| 5884 | "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec); |
| 5885 | break; |
| 5886 | } |
| 5887 | } |
| 5888 | return 0; |
| 5889 | } |
| 5890 | #endif |
| 5891 | |
| 5892 | /* |
| 5893 | ** A no-op routine that runs with the ".breakpoint" doc-command. This is |
| 5894 | ** a useful spot to set a debugger breakpoint. |
| 5895 | ** |
| 5896 | ** This routine does not do anything practical. The code are there simply |
| 5897 | ** to prevent the compiler from optimizing this routine out. |
| 5898 | */ |
| 5899 | static void test_breakpoint(void){ |
| 5900 | static unsigned int nCall = 0; |
| 5901 | if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n"); |
| 5902 | } |
| 5903 | |
| 5904 | /* |
| 5905 | ** An object used to read a CSV and other files for import. |
| 5906 | */ |
| 5907 | typedef struct ImportCtx ImportCtx; |
| 5908 | struct ImportCtx { |
| 5909 | const char *zFile; /* Name of the input file */ |
| 5910 | FILE *in; /* Read the CSV text from this input stream */ |
| 5911 | int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */ |
| 5912 | char *zIn; /* Input text */ |
| 5913 | char *z; /* Accumulated text for a field */ |
| 5914 | i64 nUsed; /* Bytes of zIn[] used so far */ |
| 5915 | i64 n; /* Number of bytes in z */ |
| 5916 | i64 nAlloc; /* Space allocated for z[] */ |
| 5917 | int nLine; /* Current line number */ |
| 5918 | int nRow; /* Number of rows imported */ |
| 5919 | int nErr; /* Number of errors encountered */ |
| 5920 | int bNotFirst; /* True if one or more bytes already read */ |
| 5921 | int cTerm; /* Character that terminated the most recent field */ |
| 5922 | int cColSep; /* The column separator character. (Usually ",") */ |
| 5923 | int cRowSep; /* The row separator character. (Usually "\n") */ |
| 5924 | int cQEscape; /* Escape character with "...". 0 for none */ |
| 5925 | int cUQEscape; /* Escape character not with "...". 0 for none */ |
| 5926 | }; |
| 5927 | |
| 5928 | /* Clean up resourced used by an ImportCtx */ |
| 5929 | static void import_cleanup(ImportCtx *p){ |
| 5930 | if( p->in!=0 && p->xCloser!=0 ){ |
| 5931 | p->xCloser(p->in); |
| 5932 | p->in = 0; |
| 5933 | } |
| 5934 | sqlite3_free(p->z); |
| 5935 | p->z = 0; |
| 5936 | if( p->zIn ){ |
| 5937 | sqlite3_free(p->zIn); |
| 5938 | p->zIn = 0; |
| 5939 | } |
| 5940 | } |
| 5941 | |
| 5942 | /* Read a single character of the .import input text. Return EOF |
| 5943 | ** at end-of-file. |
| 5944 | */ |
| 5945 | static int import_getc(ImportCtx *p){ |
| 5946 | if( p->in ){ |
| 5947 | return fgetc(p->in); |
| 5948 | }else if( p->zIn && p->zIn[p->nUsed]!=0 ){ |
| 5949 | return p->zIn[p->nUsed++]; |
| 5950 | }else{ |
| 5951 | return EOF; |
| 5952 | } |
| 5953 | } |
| 5954 | |
| 5955 | /* Append a single byte to the field value begin constructed |
| 5956 | ** in the p->z[] buffer |
| 5957 | */ |
| 5958 | static void import_append_char(ImportCtx *p, int c){ |
| 5959 | if( p->n+1>=p->nAlloc ){ |
| 5960 | p->nAlloc += p->nAlloc + 100; |
| 5961 | p->z = sqlite3_realloc64(p->z, p->nAlloc); |
| 5962 | shell_check_oom(p->z); |
| 5963 | } |
| 5964 | p->z[p->n++] = (char)c; |
| 5965 | } |
| 5966 | |
| 5967 | /* Read a single field of CSV text. Compatible with rfc4180 and extended |
| 5968 | ** with the option of having a separator other than ",". |
| 5969 | ** |
| 5970 | ** + Input comes from p->in. |
| 5971 | ** + Store results in p->z of length p->n. Space to hold p->z comes |
| 5972 | ** from sqlite3_malloc64(). |
| 5973 | ** + Use p->cColSep as the column separator. The default is ",". |
| 5974 | ** + Use p->cRowSep as the row separator. The default is "\n". |
| 5975 | ** + Keep track of the line number in p->nLine. |
| 5976 | ** + Store the character that terminates the field in p->cTerm. Store |
| 5977 | ** EOF on end-of-file. |
| 5978 | ** + Report syntax errors on stderr |
| 5979 | */ |
| 5980 | static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){ |
| 5981 | int c; |
| 5982 | int cSep = (u8)p->cColSep; |
| 5983 | int rSep = (u8)p->cRowSep; |
| 5984 | p->n = 0; |
| 5985 | c = import_getc(p); |
| 5986 | if( c==EOF || seenInterrupt ){ |
| 5987 | p->cTerm = EOF; |
| 5988 | return 0; |
| 5989 | } |
| 5990 | if( c=='"' ){ |
| 5991 | int pc, ppc; |
| 5992 | int startLine = p->nLine; |
| 5993 | int cQuote = c; |
| 5994 | int cEsc = (u8)p->cQEscape; |
| 5995 | pc = ppc = 0; |
| 5996 | while( 1 ){ |
| 5997 | c = import_getc(p); |
| 5998 | if( c==rSep ) p->nLine++; |
| 5999 | if( c==cEsc && cEsc!=0 ){ |
| 6000 | c = import_getc(p); |
| 6001 | import_append_char(p, c); |
| 6002 | ppc = pc = 0; |
| 6003 | continue; |
| 6004 | } |
| 6005 | if( c==cQuote ){ |
| 6006 | if( pc==cQuote ){ |
| 6007 | pc = 0; |
| 6008 | continue; |
| 6009 | } |
| 6010 | } |
| 6011 | if( (c==cSep && pc==cQuote) |
| 6012 | || (c==rSep && pc==cQuote) |
| 6013 | || (c==rSep && pc=='\r' && ppc==cQuote) |
| 6014 | || (c==EOF && pc==cQuote) |
| 6015 | ){ |
| 6016 | do{ p->n--; }while( p->z[p->n]!=cQuote ); |
| 6017 | p->cTerm = c; |
| 6018 | break; |
| 6019 | } |
| 6020 | if( pc==cQuote && c!='\r' ){ |
| 6021 | cli_printf(stderr,"%s:%d: unescaped %c character\n", |
| 6022 | p->zFile, p->nLine, cQuote); |
| 6023 | } |
| 6024 | if( c==EOF ){ |
| 6025 | cli_printf(stderr,"%s:%d: unterminated %c-quoted field\n", |
| 6026 | p->zFile, startLine, cQuote); |
| 6027 | p->cTerm = c; |
| 6028 | break; |
| 6029 | } |
| 6030 | import_append_char(p, c); |
| 6031 | ppc = pc; |
| 6032 | pc = c; |
| 6033 | } |
| 6034 | }else{ |
| 6035 | /* If this is the first field being parsed and it begins with the |
| 6036 | ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ |
| 6037 | int cEsc = p->cUQEscape; |
| 6038 | if( (c&0xff)==0xef && p->bNotFirst==0 ){ |
| 6039 | import_append_char(p, c); |
| 6040 | c = import_getc(p); |
| 6041 | if( (c&0xff)==0xbb ){ |
| 6042 | import_append_char(p, c); |
| 6043 | c = import_getc(p); |
| 6044 | if( (c&0xff)==0xbf ){ |
| 6045 | p->bNotFirst = 1; |
| 6046 | p->n = 0; |
| 6047 | return csv_read_one_field(p); |
| 6048 | } |
| 6049 | } |
| 6050 | } |
| 6051 | while( c!=EOF && c!=cSep && c!=rSep ){ |
| 6052 | if( c==cEsc && cEsc!=0 ) c = import_getc(p); |
| 6053 | import_append_char(p, c); |
| 6054 | c = import_getc(p); |
| 6055 | } |
| 6056 | if( c==rSep ){ |
| 6057 | p->nLine++; |
| 6058 | if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; |
| 6059 | } |
| 6060 | p->cTerm = c; |
| 6061 | } |
| 6062 | if( p->z ) p->z[p->n] = 0; |
| 6063 | p->bNotFirst = 1; |
| 6064 | return p->z; |
| 6065 | } |
| 6066 | |
| 6067 | /* Read a single field of ASCII delimited text. |
| 6068 | ** |
| 6069 | ** + Input comes from p->in. |
| 6070 | ** + Store results in p->z of length p->n. Space to hold p->z comes |
| 6071 | ** from sqlite3_malloc64(). |
| 6072 | ** + Use p->cColSep as the column separator. The default is "\x1F". |
| 6073 | ** + Use p->cRowSep as the row separator. The default is "\x1E". |
| 6074 | ** + Keep track of the row number in p->nLine. |
| 6075 | ** + Store the character that terminates the field in p->cTerm. Store |
| 6076 | ** EOF on end-of-file. |
| 6077 | ** + Report syntax errors on stderr |
| 6078 | */ |
| 6079 | static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){ |
| 6080 | int c; |
| 6081 | int cSep = (u8)p->cColSep; |
| 6082 | int rSep = (u8)p->cRowSep; |
| 6083 | p->n = 0; |
| 6084 | c = import_getc(p); |
| 6085 | if( c==EOF || seenInterrupt ){ |
| 6086 | p->cTerm = EOF; |
| 6087 | return 0; |
| 6088 | } |
| 6089 | while( c!=EOF && c!=cSep && c!=rSep ){ |
| 6090 | import_append_char(p, c); |
| 6091 | c = import_getc(p); |
| 6092 | } |
| 6093 | if( c==rSep ){ |
| 6094 | p->nLine++; |
| 6095 | } |
| 6096 | p->cTerm = c; |
| 6097 | if( p->z ) p->z[p->n] = 0; |
| 6098 | return p->z; |
| 6099 | } |
| 6100 | |
| 6101 | #ifndef SQLITE_SHELL_FIDDLE |
| 6102 | /* |
| 6103 | ** DOT-COMMAND: .clone |
| 6104 | ** |
| 6105 | ** USAGE: .clone FILE |
| 6106 | ** |
| 6107 | ** The original purpose of the ".clone" command (when it was first introduced |
| 6108 | ** in 2014) was to try to recover content for a corrupt database file and |
| 6109 | ** write the recovered content into a new database named FILE. However, |
| 6110 | ** the command has always been experimental and undocumented. Today, it |
| 6111 | ** does nothing more than make a copy of the main database into a new |
| 6112 | ** database named by its only argument, FILE. No repair attempts are |
| 6113 | ** made. The command is retained for legacy only. |
| 6114 | */ |
| 6115 | static int dotCmdClone(ShellState *p){ |
| 6116 | int nArg = p->dot.nArg; /* Number of arguments */ |
| 6117 | char **azArg = p->dot.azArg;/* Argument list */ |
| 6118 | char *zSql; |
| 6119 | sqlite3_stmt *pStmt = 0; |
| 6120 | int rc; |
| 6121 | |
| 6122 | failIfSafeMode(p, "cannot run .clone in safe mode"); |
| 6123 | if( nArg!=2 ){ |
| 6124 | dotCmdError(p, nArg, 0, "missing FILE argument"); |
| 6125 | return 1; |
| 6126 | } |
| 6127 | zSql = sqlite3_mprintf("VACUUM INTO %Q", azArg[1]); |
| 6128 | rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); |
| 6129 | sqlite3_free(zSql); |
| 6130 | if( rc!=SQLITE_OK || SQLITE_DONE!=sqlite3_step(pStmt) ){ |
| 6131 | cli_printf(stderr,"Error: cannot clone into \"%s\"\n", azArg[1]); |
| 6132 | sqlite3_finalize(pStmt); |
| 6133 | return 1; |
| 6134 | } |
| 6135 | sqlite3_finalize(pStmt); |
| 6136 | return 0; |
| 6137 | } |
| 6138 | #endif /* !defined(SQLITE_SHELL_FIDDLE) */ |
| 6139 | |
| 6140 | #ifndef SQLITE_SHELL_FIDDLE |
| 6141 | /* |
| 6142 | ** Change the output stream (file or pipe or console) to something else. |
| 6143 | */ |
| 6144 | static void output_redir(ShellState *p, FILE *pfNew){ |
| 6145 | if( p->out != stdout ){ |
| 6146 | cli_puts("Output already redirected.\n", stderr); |
| 6147 | }else{ |
| 6148 | p->out = pfNew; |
| 6149 | setCrlfMode(p); |
| 6150 | if( p->mode.eMode==MODE_Www ){ |
| 6151 | cli_puts( |
| 6152 | "<!DOCTYPE html>\n" |
| 6153 | "<HTML><BODY><PRE>\n", |
| 6154 | p->out |
| 6155 | ); |
| 6156 | } |
| 6157 | } |
| 6158 | } |
| 6159 | |
| 6160 | /* |
| 6161 | ** Change the output file back to stdout. |
| 6162 | ** |
| 6163 | ** If the p->doXdgOpen flag is set, that means the output was being |
| 6164 | ** redirected to a temporary file named by p->zTempFile. In that case, |
| 6165 | ** launch start/open/xdg-open on that temporary file. |
| 6166 | */ |
| 6167 | static void output_reset(ShellState *p){ |
| 6168 | if( p->outfile[0]=='|' ){ |
| 6169 | #ifndef SQLITE_OMIT_POPEN |
| 6170 | pclose(p->out); |
| 6171 | #endif |
| 6172 | }else{ |
| 6173 | if( p->mode.eMode==MODE_Www ){ |
| 6174 | cli_puts("</PRE></BODY></HTML>\n", p->out); |
| 6175 | } |
| 6176 | output_file_close(p->out); |
| 6177 | #ifndef SQLITE_NOHAVE_SYSTEM |
| 6178 | if( p->doXdgOpen ){ |
| 6179 | const char *zXdgOpenCmd = |
| 6180 | #if defined(_WIN32) |
| 6181 | "start"; |
| 6182 | #elif defined(__APPLE__) |
| 6183 | "open"; |
| 6184 | #else |
| 6185 | "xdg-open"; |
| 6186 | #endif |
| 6187 | char *zCmd; |
| 6188 | #ifdef __linux__ |
| 6189 | zCmd = sqlite3_mprintf("%s %s 2>/dev/null", zXdgOpenCmd, p->zTempFile); |
| 6190 | #else |
| 6191 | zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile); |
| 6192 | #endif |
| 6193 | if( system(zCmd) ){ |
| 6194 | cli_printf(stderr,"Failed: [%s]\n", zCmd); |
| 6195 | }else{ |
| 6196 | /* Give the start/open/xdg-open command some time to get |
| 6197 | ** going before we continue and potentially delete the |
| 6198 | ** p->zTempFile data file out from under it */ |
| 6199 | p->aUnlink = realloc(p->aUnlink, sizeof(Unlink)*(1+p->nUnlink)); |
| 6200 | shell_check_oom(p->aUnlink); |
| 6201 | p->aUnlink[p->nUnlink].tm = timeOfDay()+10000000; |
| 6202 | p->aUnlink[p->nUnlink].zFN = p->zTempFile; |
| 6203 | p->nUnlink++; |
| 6204 | p->zTempFile = 0; |
| 6205 | } |
| 6206 | sqlite3_free(zCmd); |
| 6207 | modePop(p); |
| 6208 | p->doXdgOpen = 0; |
| 6209 | } |
| 6210 | #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ |
| 6211 | } |
| 6212 | p->outfile[0] = 0; |
| 6213 | p->out = stdout; |
| 6214 | setCrlfMode(p); |
| 6215 | if( cli_output_capture ){ |
| 6216 | sqlite3_str_free(cli_output_capture); |
| 6217 | cli_output_capture = 0; |
| 6218 | } |
| 6219 | } |
| 6220 | #else |
| 6221 | # define output_redir(SS,pfO) |
| 6222 | # define output_reset(SS) |
| 6223 | #endif |
| 6224 | |
| 6225 | /* |
| 6226 | ** Run an SQL command and return the single integer result. |
| 6227 | */ |
| 6228 | static int db_int(sqlite3 *db, const char *zSql, ...){ |
| 6229 | sqlite3_stmt *pStmt; |
| 6230 | int res = 0; |
| 6231 | char *z; |
| 6232 | va_list ap; |
| 6233 | va_start(ap, zSql); |
| 6234 | z = sqlite3_vmprintf(zSql, ap); |
| 6235 | va_end(ap); |
| 6236 | sqlite3_prepare_v2(db, z, -1, &pStmt, 0); |
| 6237 | if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 6238 | res = sqlite3_column_int(pStmt,0); |
| 6239 | } |
| 6240 | sqlite3_finalize(pStmt); |
| 6241 | sqlite3_free(z); |
| 6242 | return res; |
| 6243 | } |
| 6244 | |
| 6245 | #if SQLITE_SHELL_HAVE_RECOVER |
| 6246 | /* |
| 6247 | ** Convert a 2-byte or 4-byte big-endian integer into a native integer |
| 6248 | */ |
| 6249 | static unsigned int get2byteInt(unsigned char *a){ |
| 6250 | return ((unsigned int)a[0]<<8) + (unsigned int)a[1]; |
| 6251 | } |
| 6252 | static unsigned int get4byteInt(unsigned char *a){ |
| 6253 | return ((unsigned int)a[0]<<24) |
| 6254 | + ((unsigned int)a[1]<<16) |
| 6255 | + ((unsigned int)a[2]<<8) |
| 6256 | + (unsigned int)a[3]; |
| 6257 | } |
| 6258 | |
| 6259 | /* |
| 6260 | ** Implementation of the ".dbinfo" command. |
| 6261 | ** |
| 6262 | ** Return 1 on error, 2 to exit, and 0 otherwise. |
| 6263 | */ |
| 6264 | static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){ |
| 6265 | static const struct { const char *zName; int ofst; } aField[] = { |
| 6266 | { "file change counter:", 24 }, |
| 6267 | { "database page count:", 28 }, |
| 6268 | { "freelist page count:", 36 }, |
| 6269 | { "schema cookie:", 40 }, |
| 6270 | { "schema format:", 44 }, |
| 6271 | { "default cache size:", 48 }, |
| 6272 | { "autovacuum top root:", 52 }, |
| 6273 | { "incremental vacuum:", 64 }, |
| 6274 | { "text encoding:", 56 }, |
| 6275 | { "user version:", 60 }, |
| 6276 | { "application id:", 68 }, |
| 6277 | { "software version:", 96 }, |
| 6278 | }; |
| 6279 | static const struct { const char *zName; const char *zSql; } aQuery[] = { |
| 6280 | { "number of tables:", |
| 6281 | "SELECT count(*) FROM %s WHERE type='table'" }, |
| 6282 | { "number of indexes:", |
| 6283 | "SELECT count(*) FROM %s WHERE type='index'" }, |
| 6284 | { "number of triggers:", |
| 6285 | "SELECT count(*) FROM %s WHERE type='trigger'" }, |
| 6286 | { "number of views:", |
| 6287 | "SELECT count(*) FROM %s WHERE type='view'" }, |
| 6288 | { "schema size:", |
| 6289 | "SELECT total(length(sql)) FROM %s" }, |
| 6290 | }; |
| 6291 | int i, rc; |
| 6292 | unsigned iDataVersion; |
| 6293 | char *zSchemaTab; |
| 6294 | char *zDb = nArg>=2 ? azArg[1] : "main"; |
| 6295 | sqlite3_stmt *pStmt = 0; |
| 6296 | unsigned char aHdr[100]; |
| 6297 | open_db(p, 0); |
| 6298 | if( p->db==0 ) return 1; |
| 6299 | rc = sqlite3_prepare_v2(p->db, |
| 6300 | "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1", |
| 6301 | -1, &pStmt, 0); |
| 6302 | if( rc ){ |
| 6303 | cli_printf(stderr,"error: %s\n", sqlite3_errmsg(p->db)); |
| 6304 | sqlite3_finalize(pStmt); |
| 6305 | return 1; |
| 6306 | } |
| 6307 | sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC); |
| 6308 | if( sqlite3_step(pStmt)==SQLITE_ROW |
| 6309 | && sqlite3_column_bytes(pStmt,0)>100 |
| 6310 | ){ |
| 6311 | const u8 *pb = sqlite3_column_blob(pStmt,0); |
| 6312 | shell_check_oom(pb); |
| 6313 | memcpy(aHdr, pb, 100); |
| 6314 | sqlite3_finalize(pStmt); |
| 6315 | }else{ |
| 6316 | cli_puts("unable to read database header\n", stderr); |
| 6317 | sqlite3_finalize(pStmt); |
| 6318 | return 1; |
| 6319 | } |
| 6320 | i = get2byteInt(aHdr+16); |
| 6321 | if( i==1 ) i = 65536; |
| 6322 | cli_printf(p->out, "%-20s %d\n", "database page size:", i); |
| 6323 | cli_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]); |
| 6324 | cli_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]); |
| 6325 | cli_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]); |
| 6326 | for(i=0; i<ArraySize(aField); i++){ |
| 6327 | int ofst = aField[i].ofst; |
| 6328 | unsigned int val = get4byteInt(aHdr + ofst); |
| 6329 | cli_printf(p->out, "%-20s %u", aField[i].zName, val); |
| 6330 | switch( ofst ){ |
| 6331 | case 56: { |
| 6332 | if( val==1 ) cli_puts(" (utf8)", p->out); |
| 6333 | if( val==2 ) cli_puts(" (utf16le)", p->out); |
| 6334 | if( val==3 ) cli_puts(" (utf16be)", p->out); |
| 6335 | } |
| 6336 | } |
| 6337 | cli_puts("\n", p->out); |
| 6338 | } |
| 6339 | if( zDb==0 ){ |
| 6340 | zSchemaTab = sqlite3_mprintf("main.sqlite_schema"); |
| 6341 | }else if( cli_strcmp(zDb,"temp")==0 ){ |
| 6342 | zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema"); |
| 6343 | }else{ |
| 6344 | zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb); |
| 6345 | } |
| 6346 | for(i=0; i<ArraySize(aQuery); i++){ |
| 6347 | int val = db_int(p->db, aQuery[i].zSql, zSchemaTab); |
| 6348 | cli_printf(p->out, "%-20s %d\n", aQuery[i].zName, val); |
| 6349 | } |
| 6350 | sqlite3_free(zSchemaTab); |
| 6351 | sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion); |
| 6352 | cli_printf(p->out, "%-20s %u\n", "data version", iDataVersion); |
| 6353 | return 0; |
| 6354 | } |
| 6355 | #endif /* SQLITE_SHELL_HAVE_RECOVER */ |
| 6356 | |
| 6357 | /* |
| 6358 | ** Implementation of the ".dbtotxt" command. |
| 6359 | ** |
| 6360 | ** Return 1 on error, 2 to exit, and 0 otherwise. |
| 6361 | */ |
| 6362 | static int shell_dbtotxt_command(ShellState *p, int nArg, char **azArg){ |
| 6363 | sqlite3_stmt *pStmt = 0; |
| 6364 | sqlite3_int64 nPage = 0; |
| 6365 | int pgSz = 0; |
| 6366 | const char *zTail; |
| 6367 | char *zName = 0; |
| 6368 | int rc, i, j; |
| 6369 | unsigned char bShow[256]; /* Characters ok to display */ |
| 6370 | |
| 6371 | UNUSED_PARAMETER(nArg); |
| 6372 | UNUSED_PARAMETER(azArg); |
| 6373 | memset(bShow, '.', sizeof(bShow)); |
| 6374 | for(i=' '; i<='~'; i++){ |
| 6375 | if( i!='{' && i!='}' && i!='"' && i!='\\' ) bShow[i] = (unsigned char)i; |
| 6376 | } |
| 6377 | rc = sqlite3_prepare_v2(p->db, "PRAGMA page_size", -1, &pStmt, 0); |
| 6378 | if( rc ) goto dbtotxt_error; |
| 6379 | rc = 0; |
| 6380 | if( sqlite3_step(pStmt)!=SQLITE_ROW ) goto dbtotxt_error; |
| 6381 | pgSz = sqlite3_column_int(pStmt, 0); |
| 6382 | sqlite3_finalize(pStmt); |
| 6383 | pStmt = 0; |
| 6384 | if( pgSz<512 || pgSz>65536 || (pgSz&(pgSz-1))!=0 ) goto dbtotxt_error; |
| 6385 | rc = sqlite3_prepare_v2(p->db, "PRAGMA page_count", -1, &pStmt, 0); |
| 6386 | if( rc ) goto dbtotxt_error; |
| 6387 | rc = 0; |
| 6388 | if( sqlite3_step(pStmt)!=SQLITE_ROW ) goto dbtotxt_error; |
| 6389 | nPage = sqlite3_column_int64(pStmt, 0); |
| 6390 | sqlite3_finalize(pStmt); |
| 6391 | pStmt = 0; |
| 6392 | if( nPage<1 ) goto dbtotxt_error; |
| 6393 | rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); |
| 6394 | if( rc ) goto dbtotxt_error; |
| 6395 | if( sqlite3_step(pStmt)!=SQLITE_ROW ){ |
| 6396 | zTail = "unk.db"; |
| 6397 | }else{ |
| 6398 | const char *zFilename = (const char*)sqlite3_column_text(pStmt, 2); |
| 6399 | if( zFilename==0 || zFilename[0]==0 ) zFilename = "unk.db"; |
| 6400 | zTail = strrchr(zFilename, '/'); |
| 6401 | #if defined(_WIN32) |
| 6402 | if( zTail==0 ) zTail = strrchr(zFilename, '\\'); |
| 6403 | #endif |
| 6404 | if( zTail==0 ){ |
| 6405 | zTail = zFilename; |
| 6406 | }else if( zTail[1]!=0 ){ |
| 6407 | zTail++; |
| 6408 | } |
| 6409 | } |
| 6410 | zName = strdup(zTail); |
| 6411 | shell_check_oom(zName); |
| 6412 | cli_printf(p->out, "| size %lld pagesize %d filename %s\n", |
| 6413 | nPage*pgSz, pgSz, zName); |
| 6414 | sqlite3_finalize(pStmt); |
| 6415 | pStmt = 0; |
| 6416 | rc = sqlite3_prepare_v2(p->db, |
| 6417 | "SELECT pgno, data FROM sqlite_dbpage ORDER BY pgno", -1, &pStmt, 0); |
| 6418 | if( rc ) goto dbtotxt_error; |
| 6419 | while( sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 6420 | sqlite3_int64 pgno = sqlite3_column_int64(pStmt, 0); |
| 6421 | const u8 *aData = sqlite3_column_blob(pStmt, 1); |
| 6422 | int seenPageLabel = 0; |
| 6423 | for(i=0; i<pgSz; i+=16){ |
| 6424 | const u8 *aLine = aData+i; |
| 6425 | for(j=0; j<16 && aLine[j]==0; j++){} |
| 6426 | if( j==16 ) continue; |
| 6427 | if( !seenPageLabel ){ |
| 6428 | cli_printf(p->out, "| page %lld offset %lld\n",pgno,(pgno-1)*pgSz); |
| 6429 | seenPageLabel = 1; |
| 6430 | } |
| 6431 | cli_printf(p->out, "| %5d:", i); |
| 6432 | for(j=0; j<16; j++) cli_printf(p->out, " %02x", aLine[j]); |
| 6433 | cli_printf(p->out, " "); |
| 6434 | for(j=0; j<16; j++){ |
| 6435 | unsigned char c = (unsigned char)aLine[j]; |
| 6436 | cli_printf(p->out, "%c", bShow[c]); |
| 6437 | } |
| 6438 | cli_printf(p->out, "\n"); |
| 6439 | } |
| 6440 | } |
| 6441 | sqlite3_finalize(pStmt); |
| 6442 | cli_printf(p->out, "| end %s\n", zName); |
| 6443 | free(zName); |
| 6444 | return 0; |
| 6445 | |
| 6446 | dbtotxt_error: |
| 6447 | if( rc ){ |
| 6448 | cli_printf(stderr, "ERROR: %s\n", sqlite3_errmsg(p->db)); |
| 6449 | } |
| 6450 | sqlite3_finalize(pStmt); |
| 6451 | free(zName); |
| 6452 | return 1; |
| 6453 | } |
| 6454 | |
| 6455 | /* |
| 6456 | ** Print the given string as an error message. |
| 6457 | */ |
| 6458 | static void shellEmitError(const char *zErr){ |
| 6459 | cli_printf(stderr,"Error: %s\n", zErr); |
| 6460 | } |
| 6461 | /* |
| 6462 | ** Print the current sqlite3_errmsg() value to stderr and return 1. |
| 6463 | */ |
| 6464 | static int shellDatabaseError(sqlite3 *db){ |
| 6465 | shellEmitError(sqlite3_errmsg(db)); |
| 6466 | return 1; |
| 6467 | } |
| 6468 | |
| 6469 | /* |
| 6470 | ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE |
| 6471 | ** if they match and FALSE (0) if they do not match. |
| 6472 | ** |
| 6473 | ** Globbing rules: |
| 6474 | ** |
| 6475 | ** '*' Matches any sequence of zero or more characters. |
| 6476 | ** |
| 6477 | ** '?' Matches exactly one character. |
| 6478 | ** |
| 6479 | ** [...] Matches one character from the enclosed list of |
| 6480 | ** characters. |
| 6481 | ** |
| 6482 | ** [^...] Matches one character not in the enclosed list. |
| 6483 | ** |
| 6484 | ** '#' Matches any sequence of one or more digits with an |
| 6485 | ** optional + or - sign in front |
| 6486 | ** |
| 6487 | ** ' ' Any span of whitespace matches any other span of |
| 6488 | ** whitespace. |
| 6489 | ** |
| 6490 | ** Extra whitespace at the end of z[] is ignored. |
| 6491 | */ |
| 6492 | static int testcase_glob(const char *zGlob, const char *z){ |
| 6493 | int c, c2; |
| 6494 | int invert; |
| 6495 | int seen; |
| 6496 | |
| 6497 | while( (c = (*(zGlob++)))!=0 ){ |
| 6498 | if( IsSpace(c) ){ |
| 6499 | if( !IsSpace(*z) ) return 0; |
| 6500 | while( IsSpace(*zGlob) ) zGlob++; |
| 6501 | while( IsSpace(*z) ) z++; |
| 6502 | }else if( c=='*' ){ |
| 6503 | while( (c=(*(zGlob++))) == '*' || c=='?' ){ |
| 6504 | if( c=='?' && (*(z++))==0 ) return 0; |
| 6505 | } |
| 6506 | if( c==0 ){ |
| 6507 | return 1; |
| 6508 | }else if( c=='[' || c=='#' || IsSpace(c) ){ |
| 6509 | /* The next pattern element is not a literal character. Try to |
| 6510 | ** match it at each position in the remaining text. */ |
| 6511 | while( *z && testcase_glob(zGlob-1,z)==0 ){ |
| 6512 | z++; |
| 6513 | } |
| 6514 | return (*z)!=0; |
| 6515 | } |
| 6516 | while( (c2 = (*(z++)))!=0 ){ |
| 6517 | while( c2!=c ){ |
| 6518 | c2 = *(z++); |
| 6519 | if( c2==0 ) return 0; |
| 6520 | } |
| 6521 | if( testcase_glob(zGlob,z) ) return 1; |
| 6522 | } |
| 6523 | return 0; |
| 6524 | }else if( c=='?' ){ |
| 6525 | if( (*(z++))==0 ) return 0; |
| 6526 | }else if( c=='[' ){ |
| 6527 | int prior_c = 0; |
| 6528 | seen = 0; |
| 6529 | invert = 0; |
| 6530 | c = *(z++); |
| 6531 | if( c==0 ) return 0; |
| 6532 | c2 = *(zGlob++); |
| 6533 | if( c2=='^' ){ |
| 6534 | invert = 1; |
| 6535 | c2 = *(zGlob++); |
| 6536 | } |
| 6537 | if( c2==']' ){ |
| 6538 | if( c==']' ) seen = 1; |
| 6539 | c2 = *(zGlob++); |
| 6540 | } |
| 6541 | while( c2 && c2!=']' ){ |
| 6542 | if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ |
| 6543 | c2 = *(zGlob++); |
| 6544 | if( c>=prior_c && c<=c2 ) seen = 1; |
| 6545 | prior_c = 0; |
| 6546 | }else{ |
| 6547 | if( c==c2 ){ |
| 6548 | seen = 1; |
| 6549 | } |
| 6550 | prior_c = c2; |
| 6551 | } |
| 6552 | c2 = *(zGlob++); |
| 6553 | } |
| 6554 | if( c2==0 || (seen ^ invert)==0 ) return 0; |
| 6555 | }else if( c=='#' ){ |
| 6556 | if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++; |
| 6557 | if( !IsDigit(z[0]) ) return 0; |
| 6558 | z++; |
| 6559 | while( IsDigit(z[0]) ){ z++; } |
| 6560 | }else{ |
| 6561 | if( c!=(*(z++)) ) return 0; |
| 6562 | } |
| 6563 | } |
| 6564 | while( IsSpace(*z) ){ z++; } |
| 6565 | return *z==0; |
| 6566 | } |
| 6567 | |
| 6568 | |
| 6569 | /* |
| 6570 | ** Compare the string as a command-line option with either one or two |
| 6571 | ** initial "-" characters. |
| 6572 | */ |
| 6573 | static int optionMatch(const char *zStr, const char *zOpt){ |
| 6574 | if( zStr[0]!='-' ) return 0; |
| 6575 | zStr++; |
| 6576 | if( zStr[0]=='-' ) zStr++; |
| 6577 | return cli_strcmp(zStr, zOpt)==0; |
| 6578 | } |
| 6579 | |
| 6580 | /* |
| 6581 | ** The input zFN is guaranteed to start with "file:" and is thus a URI |
| 6582 | ** filename. Extract the actual filename and return a pointer to that |
| 6583 | ** filename in spaced obtained from sqlite3_malloc(). |
| 6584 | ** |
| 6585 | ** The caller is responsible for freeing space using sqlite3_free() when |
| 6586 | ** it has finished with the filename. |
| 6587 | */ |
| 6588 | static char *shellFilenameFromUri(const char *zFN){ |
| 6589 | char *zOut; |
| 6590 | int i, j, d1, d2; |
| 6591 | |
| 6592 | assert( cli_strncmp(zFN,"file:",5)==0 ); |
| 6593 | zOut = sqlite3_mprintf("%s", zFN+5); |
| 6594 | shell_check_oom(zOut); |
| 6595 | for(i=j=0; zOut[i]!=0 && zOut[i]!='?'; i++){ |
| 6596 | if( zOut[i]!='%' ){ |
| 6597 | zOut[j++] = zOut[i]; |
| 6598 | continue; |
| 6599 | } |
| 6600 | d1 = hexDigitValue(zOut[i+1]); |
| 6601 | if( d1<0 ){ |
| 6602 | zOut[j] = 0; |
| 6603 | break; |
| 6604 | } |
| 6605 | d2 = hexDigitValue(zOut[i+2]); |
| 6606 | if( d2<0 ){ |
| 6607 | zOut[j] = 0; |
| 6608 | break; |
| 6609 | } |
| 6610 | zOut[j++] = d1*16 + d2; |
| 6611 | i += 2; |
| 6612 | } |
| 6613 | zOut[j] = 0; |
| 6614 | return zOut; |
| 6615 | } |
| 6616 | |
| 6617 | /* |
| 6618 | ** Delete a file. |
| 6619 | ** |
| 6620 | ** If unsuccessful on the first attempt and if pRetry!=NULL and pRetry[0] |
| 6621 | ** is positive, then delay for pRetry[0] milliseconds and try again. On |
| 6622 | ** a retry, pRetry[0] is set to zero. Unsuccessful unlinks usually only |
| 6623 | ** happen on Windows. It is possible (in theory) for unlink() to fail |
| 6624 | ** on Unix, but it rarely happens. |
| 6625 | ** |
| 6626 | ** Return 0 on success and non-zero if unable. |
| 6627 | */ |
| 6628 | int shellDeleteFile(const char *zFilename, int *pRetry){ |
| 6629 | int rc; |
| 6630 | for(;;){ |
| 6631 | #ifdef _WIN32 |
| 6632 | wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename); |
| 6633 | rc = _wunlink(z); |
| 6634 | if( rc && _waccess(z,0)!=0 ) rc = 0; |
| 6635 | sqlite3_free(z); |
| 6636 | #else |
| 6637 | rc = unlink(zFilename); |
| 6638 | if( rc && access(zFilename, 0)!=0 ) rc = 0; |
| 6639 | #endif |
| 6640 | if( rc && pRetry && pRetry[0] ){ |
| 6641 | sqlite3_sleep(pRetry[0]); |
| 6642 | pRetry[0] = 0; |
| 6643 | continue; |
| 6644 | }else{ |
| 6645 | break; |
| 6646 | } |
| 6647 | } |
| 6648 | return rc; |
| 6649 | } |
| 6650 | |
| 6651 | /* |
| 6652 | ** This routine does two things: |
| 6653 | ** |
| 6654 | ** (1) Delete (unlink) temporary files that are no longer needed. |
| 6655 | ** (2) Free memory used to hold the names of those temporary files. |
| 6656 | ** |
| 6657 | ** Temp filenames are stored in p->zTempName and in the p->aUnlink[] |
| 6658 | ** array. The p->zTempFile is always subject to immediate deletion. The |
| 6659 | ** temp files named in p->aUnlink[] are usually not deleted until after |
| 6660 | ** the timestamp stored in the p->aUnlink[].tm field, except if |
| 6661 | ** bForce is true, the p->aUnlink[] files will be deleted even if they |
| 6662 | ** have not reached their expiration, as long as a delay of at least |
| 6663 | ** nDelay milliseconds occurs first. |
| 6664 | ** |
| 6665 | ** If nDelay is non-zero and a deletion attempt is not successful, |
| 6666 | ** wait for nDelay milliseconds and try again before giving up. Only |
| 6667 | ** a single wait occurs, even if problems are encountered with multiple |
| 6668 | ** temp files. Only the first problem seen takes the delay. Thus |
| 6669 | ** the total delay never exceeds nDelay milliseconds. |
| 6670 | ** |
| 6671 | ** If bForce is true, deletion is attempted on p->aUnlink[] files |
| 6672 | ** even if their time has not expired. However, there is a pause |
| 6673 | ** of up to nDelay milliseconds before doing the deletion. Memory |
| 6674 | ** used to hold filenames is reclaimed regardless of whether or not |
| 6675 | ** the delete is successful. |
| 6676 | ** |
| 6677 | ** The bForce flag is used only when the process is about to exit. When |
| 6678 | ** bForce is set, that indicates that this is our last opportunity to |
| 6679 | ** clean up temporary files. |
| 6680 | */ |
| 6681 | static void clearTempFile(ShellState *p, int nDelay, int bForce){ |
| 6682 | int alwaysFree = bForce; |
| 6683 | int rc = 0; |
| 6684 | if( p->zTempFile && (!p->doXdgOpen || bForce) ){ |
| 6685 | rc = shellDeleteFile(p->zTempFile, &nDelay); |
| 6686 | if( rc==0 || alwaysFree ){ |
| 6687 | sqlite3_free(p->zTempFile); |
| 6688 | p->zTempFile = 0; |
| 6689 | } |
| 6690 | } |
| 6691 | if( p->nUnlink ){ |
| 6692 | unsigned int i; |
| 6693 | for(i=0; i<p->nUnlink; i++){ |
| 6694 | sqlite3_int64 tmToGo = p->aUnlink[i].tm - timeOfDay(); |
| 6695 | int doDelete = tmToGo<=0; |
| 6696 | if( !doDelete && alwaysFree ){ |
| 6697 | int tmSleep = nDelay; |
| 6698 | if( tmSleep > tmToGo/1000 ) tmSleep = (int)(tmToGo/1000); |
| 6699 | if( tmSleep>=1000 ){ |
| 6700 | cli_printf(p->out,"Waiting about %d.%d seconds to delete temp" |
| 6701 | " file(s)\n", tmSleep/1000, (tmSleep/100)%10); |
| 6702 | } |
| 6703 | sqlite3_sleep(tmSleep); |
| 6704 | nDelay -= tmSleep; |
| 6705 | doDelete = 1; |
| 6706 | } |
| 6707 | if( doDelete ){ |
| 6708 | char *zFN = p->aUnlink[i].zFN; |
| 6709 | rc = shellDeleteFile(zFN, &nDelay); |
| 6710 | if( rc==0 || alwaysFree ){ |
| 6711 | sqlite3_free(p->aUnlink[i].zFN); |
| 6712 | p->nUnlink--; |
| 6713 | if( i<p->nUnlink ){ |
| 6714 | p->aUnlink[i] = p->aUnlink[p->nUnlink]; |
| 6715 | memset(&p->aUnlink[p->nUnlink], 0, sizeof(Unlink)); |
| 6716 | } |
| 6717 | i--; |
| 6718 | } |
| 6719 | } |
| 6720 | } |
| 6721 | if( p->nUnlink==0 ){ |
| 6722 | free(p->aUnlink); |
| 6723 | p->aUnlink = 0; |
| 6724 | } |
| 6725 | } |
| 6726 | } |
| 6727 | |
| 6728 | /* Forward reference */ |
| 6729 | static char *find_home_dir(int clearFlag); |
| 6730 | |
| 6731 | /* |
| 6732 | ** Create a new temp file name with the given suffix. |
| 6733 | ** |
| 6734 | ** Because the classic temp folders like /tmp are no longer |
| 6735 | ** accessible to web browsers, for security reasons, create the |
| 6736 | ** temp file in the user's home directory. |
| 6737 | */ |
| 6738 | static void newTempFile(ShellState *p, const char *zSuffix){ |
| 6739 | char *zHome; /* Home directory */ |
| 6740 | int i; /* Loop counter */ |
| 6741 | sqlite3_uint64 r = 0; /* Integer with 64 bits of randomness */ |
| 6742 | char zRand[32]; /* Text string with 160 bits of randomness */ |
| 6743 | #ifdef _WIN32 |
| 6744 | const char cDirSep = '\\'; |
| 6745 | #else |
| 6746 | const char cDirSep = '/'; |
| 6747 | #endif |
| 6748 | |
| 6749 | for(i=0; i<31; i++){ |
| 6750 | if( (i%12)==0 ) sqlite3_randomness(sizeof(r),&r); |
| 6751 | zRand[i] = "0123456789abcdefghijklmnopqrstuvwxyz"[r%36]; |
| 6752 | r /= 36; |
| 6753 | } |
| 6754 | zRand[i] = 0; |
| 6755 | clearTempFile(p,10,0); |
| 6756 | sqlite3_free(p->zTempFile); |
| 6757 | p->zTempFile = 0; |
| 6758 | zHome = find_home_dir(0); |
| 6759 | p->zTempFile = sqlite3_mprintf("%s%ctemp-%s.%s", |
| 6760 | zHome,cDirSep,zRand,zSuffix); |
| 6761 | shell_check_oom(p->zTempFile); |
| 6762 | } |
| 6763 | |
| 6764 | /* |
| 6765 | ** SQL function: shell_temp_filename(SUFFIX) |
| 6766 | ** |
| 6767 | ** For use internally and for debugging and testing only. This function |
| 6768 | ** is subject to change or removal in future versions. |
| 6769 | ** |
| 6770 | ** Return a randomly generated temporary filename. |
| 6771 | */ |
| 6772 | static void shellTempFilenameFunc( |
| 6773 | sqlite3_context *pCtx, |
| 6774 | int nVal, |
| 6775 | sqlite3_value **apVal |
| 6776 | ){ |
| 6777 | ShellState *p = (ShellState*)sqlite3_user_data(pCtx); |
| 6778 | const char *zSuffix = (const char*)sqlite3_value_text(apVal[0]); |
| 6779 | (void)nVal; |
| 6780 | if( zSuffix==0 ) zSuffix = ""; |
| 6781 | newTempFile(p, zSuffix); |
| 6782 | sqlite3_result_text(pCtx, p->zTempFile, -1, SQLITE_TRANSIENT); |
| 6783 | sqlite3_free(p->zTempFile); |
| 6784 | p->zTempFile = 0; |
| 6785 | } |
| 6786 | |
| 6787 | /* |
| 6788 | ** The implementation of SQL scalar function fkey_collate_clause(), used |
| 6789 | ** by the ".lint fkey-indexes" command. This scalar function is always |
| 6790 | ** called with four arguments - the parent table name, the parent column name, |
| 6791 | ** the child table name and the child column name. |
| 6792 | ** |
| 6793 | ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col') |
| 6794 | ** |
| 6795 | ** If either of the named tables or columns do not exist, this function |
| 6796 | ** returns an empty string. An empty string is also returned if both tables |
| 6797 | ** and columns exist but have the same default collation sequence. Or, |
| 6798 | ** if both exist but the default collation sequences are different, this |
| 6799 | ** function returns the string " COLLATE <parent-collation>", where |
| 6800 | ** <parent-collation> is the default collation sequence of the parent column. |
| 6801 | */ |
| 6802 | static void shellFkeyCollateClause( |
| 6803 | sqlite3_context *pCtx, |
| 6804 | int nVal, |
| 6805 | sqlite3_value **apVal |
| 6806 | ){ |
| 6807 | sqlite3 *db = sqlite3_context_db_handle(pCtx); |
| 6808 | const char *zParent; |
| 6809 | const char *zParentCol; |
| 6810 | const char *zParentSeq; |
| 6811 | const char *zChild; |
| 6812 | const char *zChildCol; |
| 6813 | const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */ |
| 6814 | int rc; |
| 6815 | |
| 6816 | assert( nVal==4 ); |
| 6817 | zParent = (const char*)sqlite3_value_text(apVal[0]); |
| 6818 | zParentCol = (const char*)sqlite3_value_text(apVal[1]); |
| 6819 | zChild = (const char*)sqlite3_value_text(apVal[2]); |
| 6820 | zChildCol = (const char*)sqlite3_value_text(apVal[3]); |
| 6821 | |
| 6822 | sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); |
| 6823 | rc = sqlite3_table_column_metadata( |
| 6824 | db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0 |
| 6825 | ); |
| 6826 | if( rc==SQLITE_OK ){ |
| 6827 | rc = sqlite3_table_column_metadata( |
| 6828 | db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0 |
| 6829 | ); |
| 6830 | } |
| 6831 | |
| 6832 | if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){ |
| 6833 | char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq); |
| 6834 | sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); |
| 6835 | sqlite3_free(z); |
| 6836 | } |
| 6837 | } |
| 6838 | |
| 6839 | |
| 6840 | /* |
| 6841 | ** The implementation of dot-command ".lint fkey-indexes". |
| 6842 | */ |
| 6843 | static int lintFkeyIndexes( |
| 6844 | ShellState *pState, /* Current shell tool state */ |
| 6845 | char **azArg, /* Array of arguments passed to dot command */ |
| 6846 | int nArg /* Number of entries in azArg[] */ |
| 6847 | ){ |
| 6848 | sqlite3 *db = pState->db; /* Database handle to query "main" db of */ |
| 6849 | int bVerbose = 0; /* If -verbose is present */ |
| 6850 | int bGroupByParent = 0; /* If -groupbyparent is present */ |
| 6851 | int i; /* To iterate through azArg[] */ |
| 6852 | const char *zIndent = ""; /* How much to indent CREATE INDEX by */ |
| 6853 | int rc; /* Return code */ |
| 6854 | sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */ |
| 6855 | FILE *out = pState->out; /* Send output here */ |
| 6856 | |
| 6857 | /* |
| 6858 | ** This SELECT statement returns one row for each foreign key constraint |
| 6859 | ** in the schema of the main database. The column values are: |
| 6860 | ** |
| 6861 | ** 0. The text of an SQL statement similar to: |
| 6862 | ** |
| 6863 | ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?" |
| 6864 | ** |
| 6865 | ** This SELECT is similar to the one that the foreign keys implementation |
| 6866 | ** needs to run internally on child tables. If there is an index that can |
| 6867 | ** be used to optimize this query, then it can also be used by the FK |
| 6868 | ** implementation to optimize DELETE or UPDATE statements on the parent |
| 6869 | ** table. |
| 6870 | ** |
| 6871 | ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by |
| 6872 | ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema |
| 6873 | ** contains an index that can be used to optimize the query. |
| 6874 | ** |
| 6875 | ** 2. Human readable text that describes the child table and columns. e.g. |
| 6876 | ** |
| 6877 | ** "child_table(child_key1, child_key2)" |
| 6878 | ** |
| 6879 | ** 3. Human readable text that describes the parent table and columns. e.g. |
| 6880 | ** |
| 6881 | ** "parent_table(parent_key1, parent_key2)" |
| 6882 | ** |
| 6883 | ** 4. A full CREATE INDEX statement for an index that could be used to |
| 6884 | ** optimize DELETE or UPDATE statements on the parent table. e.g. |
| 6885 | ** |
| 6886 | ** "CREATE INDEX child_table_child_key ON child_table(child_key)" |
| 6887 | ** |
| 6888 | ** 5. The name of the parent table. |
| 6889 | ** |
| 6890 | ** These six values are used by the C logic below to generate the report. |
| 6891 | */ |
| 6892 | const char *zSql = |
| 6893 | "SELECT " |
| 6894 | " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '" |
| 6895 | " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' " |
| 6896 | " || fkey_collate_clause(" |
| 6897 | " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')" |
| 6898 | ", " |
| 6899 | " 'SEARCH ' || s.name || ' USING COVERING INDEX*('" |
| 6900 | " || group_concat('*=?', ' AND ') || ')'" |
| 6901 | ", " |
| 6902 | " s.name || '(' || group_concat(f.[from], ', ') || ')'" |
| 6903 | ", " |
| 6904 | " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'" |
| 6905 | ", " |
| 6906 | " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))" |
| 6907 | " || ' ON ' || quote(s.name) || '('" |
| 6908 | " || group_concat(quote(f.[from]) ||" |
| 6909 | " fkey_collate_clause(" |
| 6910 | " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')" |
| 6911 | " || ');'" |
| 6912 | ", " |
| 6913 | " f.[table] " |
| 6914 | "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f " |
| 6915 | "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) " |
| 6916 | "GROUP BY s.name, f.id " |
| 6917 | "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)" |
| 6918 | ; |
| 6919 | const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)"; |
| 6920 | |
| 6921 | for(i=2; i<nArg; i++){ |
| 6922 | int n = strlen30(azArg[i]); |
| 6923 | if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){ |
| 6924 | bVerbose = 1; |
| 6925 | } |
| 6926 | else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){ |
| 6927 | bGroupByParent = 1; |
| 6928 | zIndent = " "; |
| 6929 | } |
| 6930 | else{ |
| 6931 | cli_printf(stderr, |
| 6932 | "Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1]); |
| 6933 | return SQLITE_ERROR; |
| 6934 | } |
| 6935 | } |
| 6936 | |
| 6937 | /* Register the fkey_collate_clause() SQL function */ |
| 6938 | rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8, |
| 6939 | 0, shellFkeyCollateClause, 0, 0 |
| 6940 | ); |
| 6941 | |
| 6942 | |
| 6943 | if( rc==SQLITE_OK ){ |
| 6944 | rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); |
| 6945 | } |
| 6946 | if( rc==SQLITE_OK ){ |
| 6947 | sqlite3_bind_int(pSql, 1, bGroupByParent); |
| 6948 | } |
| 6949 | |
| 6950 | if( rc==SQLITE_OK ){ |
| 6951 | int rc2; |
| 6952 | char *zPrev = 0; |
| 6953 | while( SQLITE_ROW==sqlite3_step(pSql) ){ |
| 6954 | int res = -1; |
| 6955 | sqlite3_stmt *pExplain = 0; |
| 6956 | const char *zEQP = (const char*)sqlite3_column_text(pSql, 0); |
| 6957 | const char *zGlob = (const char*)sqlite3_column_text(pSql, 1); |
| 6958 | const char *zFrom = (const char*)sqlite3_column_text(pSql, 2); |
| 6959 | const char *zTarget = (const char*)sqlite3_column_text(pSql, 3); |
| 6960 | const char *zCI = (const char*)sqlite3_column_text(pSql, 4); |
| 6961 | const char *zParent = (const char*)sqlite3_column_text(pSql, 5); |
| 6962 | |
| 6963 | if( zEQP==0 ) continue; |
| 6964 | if( zGlob==0 ) continue; |
| 6965 | rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); |
| 6966 | if( rc!=SQLITE_OK ) break; |
| 6967 | if( SQLITE_ROW==sqlite3_step(pExplain) ){ |
| 6968 | const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3); |
| 6969 | res = zPlan!=0 && ( 0==sqlite3_strglob(zGlob, zPlan) |
| 6970 | || 0==sqlite3_strglob(zGlobIPK, zPlan)); |
| 6971 | } |
| 6972 | rc = sqlite3_finalize(pExplain); |
| 6973 | if( rc!=SQLITE_OK ) break; |
| 6974 | |
| 6975 | if( res<0 ){ |
| 6976 | cli_puts("Error: internal error", stderr); |
| 6977 | break; |
| 6978 | }else{ |
| 6979 | if( bGroupByParent |
| 6980 | && (bVerbose || res==0) |
| 6981 | && (zPrev==0 || sqlite3_stricmp(zParent, zPrev)) |
| 6982 | ){ |
| 6983 | cli_printf(out, "-- Parent table %s\n", zParent); |
| 6984 | sqlite3_free(zPrev); |
| 6985 | zPrev = sqlite3_mprintf("%s", zParent); |
| 6986 | } |
| 6987 | |
| 6988 | if( res==0 ){ |
| 6989 | if( strchr(zTarget,'\n') ) zTarget = "(REDACTED)"; |
| 6990 | cli_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget); |
| 6991 | }else if( bVerbose ){ |
| 6992 | if( strstr(zFrom,"*/") ) zFrom = "(REDACTED)"; |
| 6993 | if( strstr(zTarget,"*/") ) zTarget = "(REDACTED)"; |
| 6994 | cli_printf(out, |
| 6995 | "%s/* no extra indexes required for %s -> %s */\n", |
| 6996 | zIndent, zFrom, zTarget |
| 6997 | ); |
| 6998 | } |
| 6999 | } |
| 7000 | } |
| 7001 | sqlite3_free(zPrev); |
| 7002 | |
| 7003 | if( rc!=SQLITE_OK ){ |
| 7004 | cli_printf(stderr,"%s\n", sqlite3_errmsg(db)); |
| 7005 | } |
| 7006 | |
| 7007 | rc2 = sqlite3_finalize(pSql); |
| 7008 | if( rc==SQLITE_OK && rc2!=SQLITE_OK ){ |
| 7009 | rc = rc2; |
| 7010 | cli_printf(stderr,"%s\n", sqlite3_errmsg(db)); |
| 7011 | } |
| 7012 | }else{ |
| 7013 | cli_printf(stderr,"%s\n", sqlite3_errmsg(db)); |
| 7014 | } |
| 7015 | |
| 7016 | return rc; |
| 7017 | } |
| 7018 | |
| 7019 | /* |
| 7020 | ** Implementation of ".lint" dot command. |
| 7021 | */ |
| 7022 | static int lintDotCommand( |
| 7023 | ShellState *pState, /* Current shell tool state */ |
| 7024 | char **azArg, /* Array of arguments passed to dot command */ |
| 7025 | int nArg /* Number of entries in azArg[] */ |
| 7026 | ){ |
| 7027 | int n; |
| 7028 | n = (nArg>=2 ? strlen30(azArg[1]) : 0); |
| 7029 | if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage; |
| 7030 | return lintFkeyIndexes(pState, azArg, nArg); |
| 7031 | |
| 7032 | usage: |
| 7033 | cli_printf(stderr,"Usage %s sub-command ?switches...?\n", azArg[0]); |
| 7034 | cli_printf(stderr, "Where sub-commands are:\n"); |
| 7035 | cli_printf(stderr, " fkey-indexes\n"); |
| 7036 | return SQLITE_ERROR; |
| 7037 | } |
| 7038 | |
| 7039 | static void shellPrepare( |
| 7040 | sqlite3 *db, |
| 7041 | int *pRc, |
| 7042 | const char *zSql, |
| 7043 | sqlite3_stmt **ppStmt |
| 7044 | ){ |
| 7045 | *ppStmt = 0; |
| 7046 | if( *pRc==SQLITE_OK ){ |
| 7047 | int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); |
| 7048 | if( rc!=SQLITE_OK ){ |
| 7049 | cli_printf(stderr, |
| 7050 | "sql error: %s (%d)\n", sqlite3_errmsg(db), sqlite3_errcode(db)); |
| 7051 | *pRc = rc; |
| 7052 | } |
| 7053 | } |
| 7054 | } |
| 7055 | |
| 7056 | /* |
| 7057 | ** Create a prepared statement using printf-style arguments for the SQL. |
| 7058 | */ |
| 7059 | static void shellPreparePrintf( |
| 7060 | sqlite3 *db, |
| 7061 | int *pRc, |
| 7062 | sqlite3_stmt **ppStmt, |
| 7063 | const char *zFmt, |
| 7064 | ... |
| 7065 | ){ |
| 7066 | *ppStmt = 0; |
| 7067 | if( *pRc==SQLITE_OK ){ |
| 7068 | va_list ap; |
| 7069 | char *z; |
| 7070 | va_start(ap, zFmt); |
| 7071 | z = sqlite3_vmprintf(zFmt, ap); |
| 7072 | va_end(ap); |
| 7073 | if( z==0 ){ |
| 7074 | *pRc = SQLITE_NOMEM; |
| 7075 | }else{ |
| 7076 | shellPrepare(db, pRc, z, ppStmt); |
| 7077 | sqlite3_free(z); |
| 7078 | } |
| 7079 | } |
| 7080 | } |
| 7081 | |
| 7082 | /* |
| 7083 | ** Finalize the prepared statement created using shellPreparePrintf(). |
| 7084 | */ |
| 7085 | static void shellFinalize( |
| 7086 | int *pRc, |
| 7087 | sqlite3_stmt *pStmt |
| 7088 | ){ |
| 7089 | if( pStmt ){ |
| 7090 | sqlite3 *db = sqlite3_db_handle(pStmt); |
| 7091 | int rc = sqlite3_finalize(pStmt); |
| 7092 | if( *pRc==SQLITE_OK ){ |
| 7093 | if( rc!=SQLITE_OK ){ |
| 7094 | cli_printf(stderr,"SQL error: %s\n", sqlite3_errmsg(db)); |
| 7095 | } |
| 7096 | *pRc = rc; |
| 7097 | } |
| 7098 | } |
| 7099 | } |
| 7100 | |
| 7101 | #if !defined SQLITE_OMIT_VIRTUALTABLE |
| 7102 | /* Reset the prepared statement created using shellPreparePrintf(). |
| 7103 | ** |
| 7104 | ** This routine is could be marked "static". But it is not always used, |
| 7105 | ** depending on compile-time options. By omitting the "static", we avoid |
| 7106 | ** nuisance compiler warnings about "defined but not used". |
| 7107 | */ |
| 7108 | void shellReset( |
| 7109 | int *pRc, |
| 7110 | sqlite3_stmt *pStmt |
| 7111 | ){ |
| 7112 | int rc = sqlite3_reset(pStmt); |
| 7113 | if( *pRc==SQLITE_OK ){ |
| 7114 | if( rc!=SQLITE_OK ){ |
| 7115 | sqlite3 *db = sqlite3_db_handle(pStmt); |
| 7116 | cli_printf(stderr,"SQL error: %s\n", sqlite3_errmsg(db)); |
| 7117 | } |
| 7118 | *pRc = rc; |
| 7119 | } |
| 7120 | } |
| 7121 | #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */ |
| 7122 | |
| 7123 | #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) |
| 7124 | /****************************************************************************** |
| 7125 | ** The ".archive" or ".ar" command. |
| 7126 | */ |
| 7127 | /* |
| 7128 | ** Structure representing a single ".ar" command. |
| 7129 | */ |
| 7130 | typedef struct ArCommand ArCommand; |
| 7131 | struct ArCommand { |
| 7132 | u8 eCmd; /* An AR_CMD_* value */ |
| 7133 | u8 bVerbose; /* True if --verbose */ |
| 7134 | u8 bZip; /* True if the archive is a ZIP */ |
| 7135 | u8 bDryRun; /* 1 for --dry-run, 2 for --debug */ |
| 7136 | u8 bAppend; /* True if --append */ |
| 7137 | u8 bGlob; /* True if --glob */ |
| 7138 | u8 fromCmdLine; /* Run from -A instead of .archive */ |
| 7139 | int nArg; /* Number of command arguments */ |
| 7140 | char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */ |
| 7141 | const char *zFile; /* --file argument, or NULL */ |
| 7142 | const char *zDir; /* --directory argument, or NULL */ |
| 7143 | char **azArg; /* Array of command arguments */ |
| 7144 | ShellState *p; /* Shell state */ |
| 7145 | FILE *out; /* Output to this stream */ |
| 7146 | sqlite3 *db; /* Database containing the archive */ |
| 7147 | }; |
| 7148 | |
| 7149 | /* |
| 7150 | ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR. |
| 7151 | */ |
| 7152 | static int arUsage(FILE *f){ |
| 7153 | showHelp(f,"archive"); |
| 7154 | return SQLITE_ERROR; |
| 7155 | } |
| 7156 | |
| 7157 | /* |
| 7158 | ** Print an error message for the .ar command to stderr and return |
| 7159 | ** SQLITE_ERROR. |
| 7160 | */ |
| 7161 | static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){ |
| 7162 | va_list ap; |
| 7163 | char *z; |
| 7164 | va_start(ap, zFmt); |
| 7165 | z = sqlite3_vmprintf(zFmt, ap); |
| 7166 | va_end(ap); |
| 7167 | shellEmitError(z); |
| 7168 | if( pAr->fromCmdLine ){ |
| 7169 | cli_puts("Use \"-A\" for more help\n", stderr); |
| 7170 | }else{ |
| 7171 | cli_puts("Use \".archive --help\" for more help\n", stderr); |
| 7172 | } |
| 7173 | sqlite3_free(z); |
| 7174 | return SQLITE_ERROR; |
| 7175 | } |
| 7176 | |
| 7177 | /* |
| 7178 | ** Values for ArCommand.eCmd. |
| 7179 | */ |
| 7180 | #define AR_CMD_CREATE 1 |
| 7181 | #define AR_CMD_UPDATE 2 |
| 7182 | #define AR_CMD_INSERT 3 |
| 7183 | #define AR_CMD_EXTRACT 4 |
| 7184 | #define AR_CMD_LIST 5 |
| 7185 | #define AR_CMD_HELP 6 |
| 7186 | #define AR_CMD_REMOVE 7 |
| 7187 | |
| 7188 | /* |
| 7189 | ** Other (non-command) switches. |
| 7190 | */ |
| 7191 | #define AR_SWITCH_VERBOSE 8 |
| 7192 | #define AR_SWITCH_FILE 9 |
| 7193 | #define AR_SWITCH_DIRECTORY 10 |
| 7194 | #define AR_SWITCH_APPEND 11 |
| 7195 | #define AR_SWITCH_DRYRUN 12 |
| 7196 | #define AR_SWITCH_GLOB 13 |
| 7197 | #define AR_SWITCH_DEBUG 14 |
| 7198 | |
| 7199 | static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){ |
| 7200 | switch( eSwitch ){ |
| 7201 | case AR_CMD_CREATE: |
| 7202 | case AR_CMD_EXTRACT: |
| 7203 | case AR_CMD_LIST: |
| 7204 | case AR_CMD_REMOVE: |
| 7205 | case AR_CMD_UPDATE: |
| 7206 | case AR_CMD_INSERT: |
| 7207 | case AR_CMD_HELP: |
| 7208 | if( pAr->eCmd ){ |
| 7209 | return arErrorMsg(pAr, "multiple command options"); |
| 7210 | } |
| 7211 | pAr->eCmd = eSwitch; |
| 7212 | break; |
| 7213 | |
| 7214 | case AR_SWITCH_DRYRUN: |
| 7215 | if( pAr->bDryRun<2 ) pAr->bDryRun = 1; |
| 7216 | break; |
| 7217 | case AR_SWITCH_DEBUG: |
| 7218 | pAr->bDryRun = 2; |
| 7219 | break; |
| 7220 | case AR_SWITCH_GLOB: |
| 7221 | pAr->bGlob = 1; |
| 7222 | break; |
| 7223 | case AR_SWITCH_VERBOSE: |
| 7224 | pAr->bVerbose = 1; |
| 7225 | break; |
| 7226 | case AR_SWITCH_APPEND: |
| 7227 | pAr->bAppend = 1; |
| 7228 | deliberate_fall_through; /* FALLTHRU */ |
| 7229 | case AR_SWITCH_FILE: |
| 7230 | pAr->zFile = zArg; |
| 7231 | break; |
| 7232 | case AR_SWITCH_DIRECTORY: |
| 7233 | pAr->zDir = zArg; |
| 7234 | break; |
| 7235 | } |
| 7236 | |
| 7237 | return SQLITE_OK; |
| 7238 | } |
| 7239 | |
| 7240 | /* |
| 7241 | ** Parse the command line for an ".ar" command. The results are written into |
| 7242 | ** structure (*pAr). SQLITE_OK is returned if the command line is parsed |
| 7243 | ** successfully, otherwise an error message is written to stderr and |
| 7244 | ** SQLITE_ERROR returned. |
| 7245 | */ |
| 7246 | static int arParseCommand( |
| 7247 | char **azArg, /* Array of arguments passed to dot command */ |
| 7248 | int nArg, /* Number of entries in azArg[] */ |
| 7249 | ArCommand *pAr /* Populate this object */ |
| 7250 | ){ |
| 7251 | struct ArSwitch { |
| 7252 | const char *zLong; |
| 7253 | char cShort; |
| 7254 | u8 eSwitch; |
| 7255 | u8 bArg; |
| 7256 | } aSwitch[] = { |
| 7257 | { "create", 'c', AR_CMD_CREATE, 0 }, |
| 7258 | { "extract", 'x', AR_CMD_EXTRACT, 0 }, |
| 7259 | { "insert", 'i', AR_CMD_INSERT, 0 }, |
| 7260 | { "list", 't', AR_CMD_LIST, 0 }, |
| 7261 | { "remove", 'r', AR_CMD_REMOVE, 0 }, |
| 7262 | { "update", 'u', AR_CMD_UPDATE, 0 }, |
| 7263 | { "help", 'h', AR_CMD_HELP, 0 }, |
| 7264 | { "verbose", 'v', AR_SWITCH_VERBOSE, 0 }, |
| 7265 | { "file", 'f', AR_SWITCH_FILE, 1 }, |
| 7266 | { "append", 'a', AR_SWITCH_APPEND, 1 }, |
| 7267 | { "directory", 'C', AR_SWITCH_DIRECTORY, 1 }, |
| 7268 | { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 }, |
| 7269 | { "debug", 0, AR_SWITCH_DEBUG, 0 }, |
| 7270 | { "glob", 'g', AR_SWITCH_GLOB, 0 }, |
| 7271 | }; |
| 7272 | int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch); |
| 7273 | struct ArSwitch *pEnd = &aSwitch[nSwitch]; |
| 7274 | |
| 7275 | if( nArg<=1 ){ |
| 7276 | cli_printf(stderr, "Wrong number of arguments. Usage:\n"); |
| 7277 | return arUsage(stderr); |
| 7278 | }else{ |
| 7279 | char *z = azArg[1]; |
| 7280 | if( z[0]!='-' ){ |
| 7281 | /* Traditional style [tar] invocation */ |
| 7282 | int i; |
| 7283 | int iArg = 2; |
| 7284 | for(i=0; z[i]; i++){ |
| 7285 | const char *zArg = 0; |
| 7286 | struct ArSwitch *pOpt; |
| 7287 | for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ |
| 7288 | if( z[i]==pOpt->cShort ) break; |
| 7289 | } |
| 7290 | if( pOpt==pEnd ){ |
| 7291 | return arErrorMsg(pAr, "unrecognized option: %c", z[i]); |
| 7292 | } |
| 7293 | if( pOpt->bArg ){ |
| 7294 | if( iArg>=nArg ){ |
| 7295 | return arErrorMsg(pAr, "option requires an argument: %c",z[i]); |
| 7296 | } |
| 7297 | zArg = azArg[iArg++]; |
| 7298 | } |
| 7299 | if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; |
| 7300 | } |
| 7301 | pAr->nArg = nArg-iArg; |
| 7302 | if( pAr->nArg>0 ){ |
| 7303 | pAr->azArg = &azArg[iArg]; |
| 7304 | } |
| 7305 | }else{ |
| 7306 | /* Non-traditional invocation */ |
| 7307 | int iArg; |
| 7308 | for(iArg=1; iArg<nArg; iArg++){ |
| 7309 | int n; |
| 7310 | z = azArg[iArg]; |
| 7311 | if( z[0]!='-' ){ |
| 7312 | /* All remaining command line words are command arguments. */ |
| 7313 | pAr->azArg = &azArg[iArg]; |
| 7314 | pAr->nArg = nArg-iArg; |
| 7315 | break; |
| 7316 | } |
| 7317 | n = strlen30(z); |
| 7318 | |
| 7319 | if( z[1]!='-' ){ |
| 7320 | int i; |
| 7321 | /* One or more short options */ |
| 7322 | for(i=1; i<n; i++){ |
| 7323 | const char *zArg = 0; |
| 7324 | struct ArSwitch *pOpt; |
| 7325 | for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ |
| 7326 | if( z[i]==pOpt->cShort ) break; |
| 7327 | } |
| 7328 | if( pOpt==pEnd ){ |
| 7329 | return arErrorMsg(pAr, "unrecognized option: %c", z[i]); |
| 7330 | } |
| 7331 | if( pOpt->bArg ){ |
| 7332 | if( i<(n-1) ){ |
| 7333 | zArg = &z[i+1]; |
| 7334 | i = n; |
| 7335 | }else{ |
| 7336 | if( iArg>=(nArg-1) ){ |
| 7337 | return arErrorMsg(pAr, "option requires an argument: %c", |
| 7338 | z[i]); |
| 7339 | } |
| 7340 | zArg = azArg[++iArg]; |
| 7341 | } |
| 7342 | } |
| 7343 | if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; |
| 7344 | } |
| 7345 | }else if( z[2]=='\0' ){ |
| 7346 | /* A -- option, indicating that all remaining command line words |
| 7347 | ** are command arguments. */ |
| 7348 | pAr->azArg = &azArg[iArg+1]; |
| 7349 | pAr->nArg = nArg-iArg-1; |
| 7350 | break; |
| 7351 | }else{ |
| 7352 | /* A long option */ |
| 7353 | const char *zArg = 0; /* Argument for option, if any */ |
| 7354 | struct ArSwitch *pMatch = 0; /* Matching option */ |
| 7355 | struct ArSwitch *pOpt; /* Iterator */ |
| 7356 | for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ |
| 7357 | const char *zLong = pOpt->zLong; |
| 7358 | if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){ |
| 7359 | if( pMatch ){ |
| 7360 | return arErrorMsg(pAr, "ambiguous option: %s",z); |
| 7361 | }else{ |
| 7362 | pMatch = pOpt; |
| 7363 | } |
| 7364 | } |
| 7365 | } |
| 7366 | |
| 7367 | if( pMatch==0 ){ |
| 7368 | return arErrorMsg(pAr, "unrecognized option: %s", z); |
| 7369 | } |
| 7370 | if( pMatch->bArg ){ |
| 7371 | if( iArg>=(nArg-1) ){ |
| 7372 | return arErrorMsg(pAr, "option requires an argument: %s", z); |
| 7373 | } |
| 7374 | zArg = azArg[++iArg]; |
| 7375 | } |
| 7376 | if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR; |
| 7377 | } |
| 7378 | } |
| 7379 | } |
| 7380 | } |
| 7381 | if( pAr->eCmd==0 ){ |
| 7382 | cli_printf(stderr, "Required argument missing. Usage:\n"); |
| 7383 | return arUsage(stderr); |
| 7384 | } |
| 7385 | return SQLITE_OK; |
| 7386 | } |
| 7387 | |
| 7388 | /* |
| 7389 | ** This function assumes that all arguments within the ArCommand.azArg[] |
| 7390 | ** array refer to archive members, as for the --extract, --list or --remove |
| 7391 | ** commands. It checks that each of them are "present". If any specified |
| 7392 | ** file is not present in the archive, an error is printed to stderr and an |
| 7393 | ** error code returned. Otherwise, if all specified arguments are present |
| 7394 | ** in the archive, SQLITE_OK is returned. Here, "present" means either an |
| 7395 | ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match |
| 7396 | ** when pAr->bGlob is true. |
| 7397 | ** |
| 7398 | ** This function strips any trailing '/' characters from each argument. |
| 7399 | ** This is consistent with the way the [tar] command seems to work on |
| 7400 | ** Linux. |
| 7401 | */ |
| 7402 | static int arCheckEntries(ArCommand *pAr){ |
| 7403 | int rc = SQLITE_OK; |
| 7404 | if( pAr->nArg ){ |
| 7405 | int i, j; |
| 7406 | sqlite3_stmt *pTest = 0; |
| 7407 | const char *zSel = (pAr->bGlob) |
| 7408 | ? "SELECT name FROM %s WHERE glob($name,name)" |
| 7409 | : "SELECT name FROM %s WHERE name=$name"; |
| 7410 | |
| 7411 | shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable); |
| 7412 | j = sqlite3_bind_parameter_index(pTest, "$name"); |
| 7413 | for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ |
| 7414 | char *z = pAr->azArg[i]; |
| 7415 | int n = strlen30(z); |
| 7416 | int bOk = 0; |
| 7417 | while( n>0 && z[n-1]=='/' ) n--; |
| 7418 | z[n] = '\0'; |
| 7419 | sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC); |
| 7420 | if( SQLITE_ROW==sqlite3_step(pTest) ){ |
| 7421 | bOk = 1; |
| 7422 | } |
| 7423 | shellReset(&rc, pTest); |
| 7424 | if( rc==SQLITE_OK && bOk==0 ){ |
| 7425 | cli_printf(stderr,"not found in archive: %s\n", z); |
| 7426 | rc = SQLITE_ERROR; |
| 7427 | } |
| 7428 | } |
| 7429 | shellFinalize(&rc, pTest); |
| 7430 | } |
| 7431 | return rc; |
| 7432 | } |
| 7433 | |
| 7434 | /* |
| 7435 | ** Format a WHERE clause that can be used against the "sqlar" table to |
| 7436 | ** identify all archive members that match the command arguments held |
| 7437 | ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning. |
| 7438 | ** The caller is responsible for eventually calling sqlite3_free() on |
| 7439 | ** any non-NULL (*pzWhere) value. Here, "match" means strict equality |
| 7440 | ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true. |
| 7441 | */ |
| 7442 | static void arWhereClause( |
| 7443 | int *pRc, |
| 7444 | ArCommand *pAr, |
| 7445 | char **pzWhere /* OUT: New WHERE clause */ |
| 7446 | ){ |
| 7447 | char *zWhere = 0; |
| 7448 | if( *pRc==SQLITE_OK ){ |
| 7449 | if( pAr->nArg==0 ){ |
| 7450 | zWhere = sqlite3_mprintf("1"); |
| 7451 | }else{ |
| 7452 | char *z1 = sqlite3_mprintf(pAr->bGlob ? "" : "name IN("); |
| 7453 | char *z2 = sqlite3_mprintf(""); |
| 7454 | const char *zSep1 = ""; |
| 7455 | const char *zSep2 = ""; |
| 7456 | |
| 7457 | int i; |
| 7458 | for(i=0; i<pAr->nArg && z1 && z2; i++){ |
| 7459 | const char *z = pAr->azArg[i]; |
| 7460 | int n = strlen30(z); |
| 7461 | |
| 7462 | if( pAr->bGlob ){ |
| 7463 | z1 = sqlite3_mprintf("%z%sname GLOB '%q'", z1, zSep2, z); |
| 7464 | z2 = sqlite3_mprintf( |
| 7465 | "%z%ssubstr(name,1,%d) GLOB '%q/'", z2, zSep2, n+1,z |
| 7466 | ); |
| 7467 | }else{ |
| 7468 | z1 = sqlite3_mprintf("%z%s'%q'", z1, zSep1, z); |
| 7469 | z2 = sqlite3_mprintf("%z%ssubstr(name,1,%d) = '%q/'",z2,zSep2,n+1,z); |
| 7470 | } |
| 7471 | zSep1 = ", "; |
| 7472 | zSep2 = " OR "; |
| 7473 | } |
| 7474 | if( z1==0 || z2==0 ){ |
| 7475 | *pRc = SQLITE_NOMEM; |
| 7476 | }else{ |
| 7477 | zWhere = sqlite3_mprintf("(%s%s OR (name GLOB '*/*' AND (%s))) ", |
| 7478 | z1, pAr->bGlob==0 ? ")" : "", z2 |
| 7479 | ); |
| 7480 | } |
| 7481 | sqlite3_free(z1); |
| 7482 | sqlite3_free(z2); |
| 7483 | } |
| 7484 | } |
| 7485 | *pzWhere = zWhere; |
| 7486 | } |
| 7487 | |
| 7488 | /* |
| 7489 | ** Implementation of .ar "lisT" command. |
| 7490 | */ |
| 7491 | static int arListCommand(ArCommand *pAr){ |
| 7492 | const char *zSql = "SELECT %s FROM %s WHERE %s"; |
| 7493 | const char *azCols[] = { |
| 7494 | "name", |
| 7495 | "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name" |
| 7496 | }; |
| 7497 | |
| 7498 | char *zWhere = 0; |
| 7499 | sqlite3_stmt *pSql = 0; |
| 7500 | int rc; |
| 7501 | |
| 7502 | rc = arCheckEntries(pAr); |
| 7503 | arWhereClause(&rc, pAr, &zWhere); |
| 7504 | |
| 7505 | shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose], |
| 7506 | pAr->zSrcTable, zWhere); |
| 7507 | if( pAr->bDryRun ){ |
| 7508 | if( pSql ) cli_printf(pAr->out, "%s\n", sqlite3_sql(pSql)); |
| 7509 | }else{ |
| 7510 | while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ |
| 7511 | if( pAr->bVerbose ){ |
| 7512 | cli_printf(pAr->out, "%s % 10d %s %s\n", |
| 7513 | sqlite3_column_text(pSql, 0), sqlite3_column_int(pSql, 1), |
| 7514 | sqlite3_column_text(pSql, 2),sqlite3_column_text(pSql, 3)); |
| 7515 | }else{ |
| 7516 | cli_printf(pAr->out, "%s\n", sqlite3_column_text(pSql, 0)); |
| 7517 | } |
| 7518 | } |
| 7519 | } |
| 7520 | shellFinalize(&rc, pSql); |
| 7521 | sqlite3_free(zWhere); |
| 7522 | return rc; |
| 7523 | } |
| 7524 | |
| 7525 | /* |
| 7526 | ** Implementation of .ar "Remove" command. |
| 7527 | */ |
| 7528 | static int arRemoveCommand(ArCommand *pAr){ |
| 7529 | int rc = 0; |
| 7530 | char *zSql = 0; |
| 7531 | char *zWhere = 0; |
| 7532 | |
| 7533 | if( pAr->nArg ){ |
| 7534 | /* Verify that args actually exist within the archive before proceeding. |
| 7535 | ** And formulate a WHERE clause to match them. */ |
| 7536 | rc = arCheckEntries(pAr); |
| 7537 | arWhereClause(&rc, pAr, &zWhere); |
| 7538 | } |
| 7539 | if( rc==SQLITE_OK ){ |
| 7540 | zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;", |
| 7541 | pAr->zSrcTable, zWhere); |
| 7542 | if( pAr->bDryRun ){ |
| 7543 | cli_printf(pAr->out, "%s\n", zSql); |
| 7544 | }else{ |
| 7545 | char *zErr = 0; |
| 7546 | rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0); |
| 7547 | if( rc==SQLITE_OK ){ |
| 7548 | rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); |
| 7549 | if( rc!=SQLITE_OK ){ |
| 7550 | sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); |
| 7551 | }else{ |
| 7552 | rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0); |
| 7553 | } |
| 7554 | } |
| 7555 | if( zErr ){ |
| 7556 | cli_printf(stdout, "ERROR: %s\n", zErr); /* stdout? */ |
| 7557 | sqlite3_free(zErr); |
| 7558 | } |
| 7559 | } |
| 7560 | } |
| 7561 | sqlite3_free(zWhere); |
| 7562 | sqlite3_free(zSql); |
| 7563 | return rc; |
| 7564 | } |
| 7565 | |
| 7566 | /* |
| 7567 | ** Implementation of .ar "eXtract" command. |
| 7568 | */ |
| 7569 | static int arExtractCommand(ArCommand *pAr){ |
| 7570 | /* The zSql1[] string is a template for the query that does the |
| 7571 | ** extraction. Notes: |
| 7572 | ** |
| 7573 | ** * $dir is the directory into which the archive is to be extracted |
| 7574 | ** * $pass is the integer pass number: 0, 1, or 2 |
| 7575 | ** * The dest CTE is created so that realpath($dir) only needs |
| 7576 | ** to be called once. |
| 7577 | */ |
| 7578 | const char *zSql1 = |
| 7579 | "WITH dest(dpath,dlen) AS (\n" |
| 7580 | #ifdef _WIN32 |
| 7581 | " SELECT realpath($dir) || '\\',\n" |
| 7582 | #else |
| 7583 | " SELECT realpath($dir) || '/',\n" |
| 7584 | #endif |
| 7585 | " 1+length(realpath($dir))\n" |
| 7586 | ")\n" |
| 7587 | "SELECT\n" |
| 7588 | " ($dir || name),\n" |
| 7589 | " CASE $dryrun\n" /* vv--- azExtraArg */ |
| 7590 | " WHEN 0 THEN writefile($dir||name, %s, mode, mtime)\n" |
| 7591 | " WHEN 1 THEN 0\n" |
| 7592 | " ELSE shell_putsnl(format('writefile(%%Q,%%s,%%0o,%%d)'," |
| 7593 | "$dir||name,quote(%s),mode,mtime)) IS NULL\n" |
| 7594 | " END\n" /* ^^--- azExtraArg */ |
| 7595 | " FROM dest CROSS JOIN %s\n" |
| 7596 | " WHERE (%s)\n" /* ^^-- pAr->zSrcTable */ |
| 7597 | /* ^^--- zWhere */ |
| 7598 | " AND (CASE $pass WHEN 0 THEN (mode&0xf000)<>0xa000\n" |
| 7599 | " WHEN 1 THEN (mode&0xf000)=0xa000\n" |
| 7600 | " ELSE data IS NULL END)\n" |
| 7601 | " AND dpath=substr(realpath($dir||name),1,dlen)\n" /* No escapes */ |
| 7602 | " AND name NOT GLOB '*..[/\\]*'\n"; /* No /../ in paths */ |
| 7603 | |
| 7604 | const char *azExtraArg[] = { |
| 7605 | "sqlar_uncompress(data, sz)", |
| 7606 | "data" |
| 7607 | }; |
| 7608 | |
| 7609 | sqlite3_stmt *pSql = 0; |
| 7610 | int rc = SQLITE_OK; |
| 7611 | char *zDir = 0; |
| 7612 | char *zWhere = 0; |
| 7613 | int i, j; |
| 7614 | |
| 7615 | /* If arguments are specified, check that they actually exist within |
| 7616 | ** the archive before proceeding. And formulate a WHERE clause to |
| 7617 | ** match them. */ |
| 7618 | rc = arCheckEntries(pAr); |
| 7619 | arWhereClause(&rc, pAr, &zWhere); |
| 7620 | |
| 7621 | if( rc==SQLITE_OK ){ |
| 7622 | if( pAr->zDir ){ |
| 7623 | zDir = sqlite3_mprintf("%s/", pAr->zDir); |
| 7624 | }else{ |
| 7625 | zDir = sqlite3_mprintf(""); |
| 7626 | } |
| 7627 | if( zDir==0 ) rc = SQLITE_NOMEM; |
| 7628 | } |
| 7629 | |
| 7630 | shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, |
| 7631 | azExtraArg[pAr->bZip], |
| 7632 | azExtraArg[pAr->bZip], |
| 7633 | pAr->zSrcTable, |
| 7634 | zWhere |
| 7635 | ); |
| 7636 | |
| 7637 | if( rc==SQLITE_OK ){ |
| 7638 | j = sqlite3_bind_parameter_index(pSql, "$dir"); |
| 7639 | sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC); |
| 7640 | j = sqlite3_bind_parameter_index(pSql, "$dryrun"); |
| 7641 | sqlite3_bind_int(pSql, j, pAr->bDryRun); |
| 7642 | |
| 7643 | /* Run the SELECT statement twice |
| 7644 | ** (0) writefile() files and directories |
| 7645 | ** (1) writefile() symlinks |
| 7646 | ** (2) writefile() for directory again |
| 7647 | ** The third pass is so that the timestamps for extracted directories |
| 7648 | ** will be reset to the value in the archive, since populating them |
| 7649 | ** in the first pass will have changed the timestamp. */ |
| 7650 | for(i=0; i<3; i++){ |
| 7651 | if( pAr->bDryRun>=2 ){ |
| 7652 | cli_printf(pAr->out, "*** BEGIN PASS %d ***\n", i+1); |
| 7653 | } |
| 7654 | j = sqlite3_bind_parameter_index(pSql, "$pass"); |
| 7655 | sqlite3_bind_int(pSql, j, i); |
| 7656 | if( pAr->bDryRun && i==0 ){ |
| 7657 | cli_printf(pAr->out, "%s\n", sqlite3_sql(pSql)); |
| 7658 | } |
| 7659 | while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ |
| 7660 | if( i==0 && pAr->bVerbose ){ |
| 7661 | cli_printf(pAr->out, "%s\n", sqlite3_column_text(pSql, 0)); |
| 7662 | } |
| 7663 | } |
| 7664 | if( pAr->bDryRun==1 ) break; |
| 7665 | shellReset(&rc, pSql); |
| 7666 | if( pAr->bDryRun>=2 ){ |
| 7667 | cli_printf(pAr->out, "*** END PASS %d ***\n", i+1); |
| 7668 | } |
| 7669 | } |
| 7670 | shellFinalize(&rc, pSql); |
| 7671 | } |
| 7672 | |
| 7673 | sqlite3_free(zDir); |
| 7674 | sqlite3_free(zWhere); |
| 7675 | return rc; |
| 7676 | } |
| 7677 | |
| 7678 | /* |
| 7679 | ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out. |
| 7680 | */ |
| 7681 | static int arExecSql(ArCommand *pAr, const char *zSql){ |
| 7682 | int rc; |
| 7683 | if( pAr->bDryRun ){ |
| 7684 | cli_printf(pAr->out, "%s\n", zSql); |
| 7685 | rc = SQLITE_OK; |
| 7686 | }else{ |
| 7687 | char *zErr = 0; |
| 7688 | rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); |
| 7689 | if( zErr ){ |
| 7690 | cli_printf(stdout, "ERROR: %s\n", zErr); |
| 7691 | sqlite3_free(zErr); |
| 7692 | } |
| 7693 | } |
| 7694 | return rc; |
| 7695 | } |
| 7696 | |
| 7697 | |
| 7698 | /* |
| 7699 | ** Implementation of .ar "create", "insert", and "update" commands. |
| 7700 | ** |
| 7701 | ** create -> Create a new SQL archive |
| 7702 | ** insert -> Insert or reinsert all files listed |
| 7703 | ** update -> Insert files that have changed or that were not |
| 7704 | ** previously in the archive |
| 7705 | ** |
| 7706 | ** Create the "sqlar" table in the database if it does not already exist. |
| 7707 | ** Then add each file in the azFile[] array to the archive. Directories |
| 7708 | ** are added recursively. If argument bVerbose is non-zero, a message is |
| 7709 | ** printed on stdout for each file archived. |
| 7710 | ** |
| 7711 | ** The create command is the same as update, except that it drops |
| 7712 | ** any existing "sqlar" table before beginning. The "insert" command |
| 7713 | ** always overwrites every file named on the command-line, where as |
| 7714 | ** "update" only overwrites if the size or mtime or mode has changed. |
| 7715 | */ |
| 7716 | static int arCreateOrUpdateCommand( |
| 7717 | ArCommand *pAr, /* Command arguments and options */ |
| 7718 | int bUpdate, /* true for a --create. */ |
| 7719 | int bOnlyIfChanged /* Only update if file has changed */ |
| 7720 | ){ |
| 7721 | const char *zCreate = |
| 7722 | "CREATE TABLE IF NOT EXISTS sqlar(\n" |
| 7723 | " name TEXT PRIMARY KEY, -- name of the file\n" |
| 7724 | " mode INT, -- access permissions\n" |
| 7725 | " mtime INT, -- last modification time\n" |
| 7726 | " sz INT, -- original file size\n" |
| 7727 | " data BLOB -- compressed content\n" |
| 7728 | ")"; |
| 7729 | const char *zDrop = "DROP TABLE IF EXISTS sqlar"; |
| 7730 | const char *zInsertFmt[2] = { |
| 7731 | "REPLACE INTO %s(name,mode,mtime,sz,data)\n" |
| 7732 | " SELECT\n" |
| 7733 | " %s,\n" |
| 7734 | " mode,\n" |
| 7735 | " mtime,\n" |
| 7736 | " CASE substr(lsmode(mode),1,1)\n" |
| 7737 | " WHEN '-' THEN length(data)\n" |
| 7738 | " WHEN 'd' THEN 0\n" |
| 7739 | " ELSE -1 END,\n" |
| 7740 | " sqlar_compress(data)\n" |
| 7741 | " FROM fsdir(%Q,%Q) AS disk\n" |
| 7742 | " WHERE lsmode(mode) NOT LIKE '?%%'%s;" |
| 7743 | , |
| 7744 | "REPLACE INTO %s(name,mode,mtime,data)\n" |
| 7745 | " SELECT\n" |
| 7746 | " %s,\n" |
| 7747 | " mode,\n" |
| 7748 | " mtime,\n" |
| 7749 | " data\n" |
| 7750 | " FROM fsdir(%Q,%Q) AS disk\n" |
| 7751 | " WHERE lsmode(mode) NOT LIKE '?%%'%s;" |
| 7752 | }; |
| 7753 | int i; /* For iterating through azFile[] */ |
| 7754 | int rc; /* Return code */ |
| 7755 | const char *zTab = 0; /* SQL table into which to insert */ |
| 7756 | char *zSql; |
| 7757 | char zTemp[50]; |
| 7758 | char *zExists = 0; |
| 7759 | |
| 7760 | arExecSql(pAr, "PRAGMA page_size=512"); |
| 7761 | rc = arExecSql(pAr, "SAVEPOINT ar;"); |
| 7762 | if( rc!=SQLITE_OK ) return rc; |
| 7763 | zTemp[0] = 0; |
| 7764 | if( pAr->bZip ){ |
| 7765 | /* Initialize the zipfile virtual table, if necessary */ |
| 7766 | if( pAr->zFile ){ |
| 7767 | sqlite3_uint64 r; |
| 7768 | sqlite3_randomness(sizeof(r),&r); |
| 7769 | sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r); |
| 7770 | zTab = zTemp; |
| 7771 | zSql = sqlite3_mprintf( |
| 7772 | "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)", |
| 7773 | zTab, pAr->zFile |
| 7774 | ); |
| 7775 | rc = arExecSql(pAr, zSql); |
| 7776 | sqlite3_free(zSql); |
| 7777 | }else{ |
| 7778 | zTab = "zip"; |
| 7779 | } |
| 7780 | }else{ |
| 7781 | /* Initialize the table for an SQLAR */ |
| 7782 | zTab = "sqlar"; |
| 7783 | if( bUpdate==0 ){ |
| 7784 | rc = arExecSql(pAr, zDrop); |
| 7785 | if( rc!=SQLITE_OK ) goto end_ar_transaction; |
| 7786 | } |
| 7787 | rc = arExecSql(pAr, zCreate); |
| 7788 | } |
| 7789 | if( bOnlyIfChanged ){ |
| 7790 | zExists = sqlite3_mprintf( |
| 7791 | " AND NOT EXISTS(" |
| 7792 | "SELECT 1 FROM %s AS mem" |
| 7793 | " WHERE mem.name=disk.name" |
| 7794 | " AND mem.mtime=disk.mtime" |
| 7795 | " AND mem.mode=disk.mode)", zTab); |
| 7796 | }else{ |
| 7797 | zExists = sqlite3_mprintf(""); |
| 7798 | } |
| 7799 | if( zExists==0 ) rc = SQLITE_NOMEM; |
| 7800 | for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ |
| 7801 | char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab, |
| 7802 | pAr->bVerbose ? "shell_putsnl(name)" : "name", |
| 7803 | pAr->azArg[i], pAr->zDir, zExists); |
| 7804 | rc = arExecSql(pAr, zSql2); |
| 7805 | sqlite3_free(zSql2); |
| 7806 | } |
| 7807 | end_ar_transaction: |
| 7808 | if( rc!=SQLITE_OK ){ |
| 7809 | sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); |
| 7810 | }else{ |
| 7811 | rc = arExecSql(pAr, "RELEASE ar;"); |
| 7812 | if( pAr->bZip && pAr->zFile ){ |
| 7813 | zSql = sqlite3_mprintf("DROP TABLE %s", zTemp); |
| 7814 | arExecSql(pAr, zSql); |
| 7815 | sqlite3_free(zSql); |
| 7816 | } |
| 7817 | } |
| 7818 | sqlite3_free(zExists); |
| 7819 | return rc; |
| 7820 | } |
| 7821 | |
| 7822 | /* |
| 7823 | ** Implementation of ".ar" dot command. |
| 7824 | */ |
| 7825 | static int arDotCommand( |
| 7826 | ShellState *pState, /* Current shell tool state */ |
| 7827 | int fromCmdLine, /* True if -A command-line option, not .ar cmd */ |
| 7828 | char **azArg, /* Array of arguments passed to dot command */ |
| 7829 | int nArg /* Number of entries in azArg[] */ |
| 7830 | ){ |
| 7831 | ArCommand cmd; |
| 7832 | int rc; |
| 7833 | memset(&cmd, 0, sizeof(cmd)); |
| 7834 | cmd.fromCmdLine = fromCmdLine; |
| 7835 | rc = arParseCommand(azArg, nArg, &cmd); |
| 7836 | if( rc==SQLITE_OK ){ |
| 7837 | int eDbType = SHELL_OPEN_UNSPEC; |
| 7838 | cmd.p = pState; |
| 7839 | cmd.out = pState->out; |
| 7840 | cmd.db = pState->db; |
| 7841 | if( cmd.zFile ){ |
| 7842 | eDbType = deduceDatabaseType(cmd.zFile, 1, 0); |
| 7843 | }else{ |
| 7844 | eDbType = pState->openMode; |
| 7845 | } |
| 7846 | if( eDbType==SHELL_OPEN_ZIPFILE ){ |
| 7847 | if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){ |
| 7848 | if( cmd.zFile==0 ){ |
| 7849 | cmd.zSrcTable = sqlite3_mprintf("zip"); |
| 7850 | }else{ |
| 7851 | cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile); |
| 7852 | } |
| 7853 | } |
| 7854 | cmd.bZip = 1; |
| 7855 | }else if( cmd.zFile ){ |
| 7856 | int flags; |
| 7857 | if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS; |
| 7858 | if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT |
| 7859 | || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){ |
| 7860 | flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; |
| 7861 | }else{ |
| 7862 | flags = SQLITE_OPEN_READONLY; |
| 7863 | } |
| 7864 | cmd.db = 0; |
| 7865 | if( cmd.bDryRun ){ |
| 7866 | cli_printf(cmd.out, "-- open database '%s'%s\n", cmd.zFile, |
| 7867 | eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : ""); |
| 7868 | } |
| 7869 | rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, |
| 7870 | eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0); |
| 7871 | if( rc!=SQLITE_OK ){ |
| 7872 | cli_printf(stderr, "cannot open file: %s (%s)\n", |
| 7873 | cmd.zFile, sqlite3_errmsg(cmd.db)); |
| 7874 | goto end_ar_command; |
| 7875 | } |
| 7876 | sqlite3_fileio_init(cmd.db, 0, 0); |
| 7877 | sqlite3_sqlar_init(cmd.db, 0, 0); |
| 7878 | sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p, |
| 7879 | shellPutsFunc, 0, 0); |
| 7880 | |
| 7881 | } |
| 7882 | if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){ |
| 7883 | if( cmd.eCmd!=AR_CMD_CREATE |
| 7884 | && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0) |
| 7885 | ){ |
| 7886 | cli_printf(stderr, "database does not contain an 'sqlar' table\n"); |
| 7887 | rc = SQLITE_ERROR; |
| 7888 | goto end_ar_command; |
| 7889 | } |
| 7890 | cmd.zSrcTable = sqlite3_mprintf("sqlar"); |
| 7891 | } |
| 7892 | |
| 7893 | switch( cmd.eCmd ){ |
| 7894 | case AR_CMD_CREATE: |
| 7895 | rc = arCreateOrUpdateCommand(&cmd, 0, 0); |
| 7896 | break; |
| 7897 | |
| 7898 | case AR_CMD_EXTRACT: |
| 7899 | rc = arExtractCommand(&cmd); |
| 7900 | break; |
| 7901 | |
| 7902 | case AR_CMD_LIST: |
| 7903 | rc = arListCommand(&cmd); |
| 7904 | break; |
| 7905 | |
| 7906 | case AR_CMD_HELP: |
| 7907 | arUsage(pState->out); |
| 7908 | break; |
| 7909 | |
| 7910 | case AR_CMD_INSERT: |
| 7911 | rc = arCreateOrUpdateCommand(&cmd, 1, 0); |
| 7912 | break; |
| 7913 | |
| 7914 | case AR_CMD_REMOVE: |
| 7915 | rc = arRemoveCommand(&cmd); |
| 7916 | break; |
| 7917 | |
| 7918 | default: |
| 7919 | assert( cmd.eCmd==AR_CMD_UPDATE ); |
| 7920 | rc = arCreateOrUpdateCommand(&cmd, 1, 1); |
| 7921 | break; |
| 7922 | } |
| 7923 | } |
| 7924 | end_ar_command: |
| 7925 | if( cmd.db!=pState->db ){ |
| 7926 | close_db(cmd.db); |
| 7927 | } |
| 7928 | sqlite3_free(cmd.zSrcTable); |
| 7929 | |
| 7930 | return rc; |
| 7931 | } |
| 7932 | /* End of the ".archive" or ".ar" command logic |
| 7933 | *******************************************************************************/ |
| 7934 | #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */ |
| 7935 | |
| 7936 | #if SQLITE_SHELL_HAVE_RECOVER |
| 7937 | |
| 7938 | /* |
| 7939 | ** This function is used as a callback by the recover extension. Simply |
| 7940 | ** print the supplied SQL statement to stdout. |
| 7941 | */ |
| 7942 | static int recoverSqlCb(void *pCtx, const char *zSql){ |
| 7943 | ShellState *pState = (ShellState*)pCtx; |
| 7944 | sqlite3_str *pOut = sqlite3_str_new(pState->db); |
| 7945 | char *zOut; |
| 7946 | int rc = SQLITE_OK; |
| 7947 | sqlite3_str_appendall(pOut, zSql); |
| 7948 | appendCompletion(pOut, zSql, 0); |
| 7949 | zOut = sqlite3_str_value(pOut); |
| 7950 | if( zOut ){ |
| 7951 | cli_printf(pState->out, "%s;\n", zOut); |
| 7952 | }else{ |
| 7953 | rc = SQLITE_NOMEM; |
| 7954 | } |
| 7955 | sqlite3_str_free(pOut); |
| 7956 | return rc; |
| 7957 | } |
| 7958 | |
| 7959 | /* |
| 7960 | ** This function is called to recover data from the database. A script |
| 7961 | ** to construct a new database containing all recovered data is output |
| 7962 | ** on stream pState->out. |
| 7963 | */ |
| 7964 | static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){ |
| 7965 | int rc = SQLITE_OK; |
| 7966 | const char *zRecoveryDb = ""; /* Name of "recovery" database. Debug only */ |
| 7967 | const char *zLAF = "lost_and_found"; |
| 7968 | int bFreelist = 1; /* 0 if --ignore-freelist is specified */ |
| 7969 | int bRowids = 1; /* 0 if --no-rowids */ |
| 7970 | int bUnsafe = 0; /* 1 if --unsafe */ |
| 7971 | sqlite3_recover *p = 0; |
| 7972 | int i = 0; |
| 7973 | |
| 7974 | for(i=1; i<nArg; i++){ |
| 7975 | char *z = azArg[i]; |
| 7976 | int n; |
| 7977 | if( z[0]=='-' && z[1]=='-' ) z++; |
| 7978 | n = strlen30(z); |
| 7979 | if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){ |
| 7980 | bFreelist = 0; |
| 7981 | }else |
| 7982 | if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){ |
| 7983 | /* This option determines the name of the ATTACH-ed database used |
| 7984 | ** internally by the recovery extension. The default is "" which |
| 7985 | ** means to use a temporary database that is automatically deleted |
| 7986 | ** when closed. This option is undocumented and might disappear at |
| 7987 | ** any moment. */ |
| 7988 | i++; |
| 7989 | zRecoveryDb = azArg[i]; |
| 7990 | }else |
| 7991 | if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){ |
| 7992 | i++; |
| 7993 | zLAF = azArg[i]; |
| 7994 | }else |
| 7995 | if( n<=10 && memcmp("-no-rowids", z, n)==0 ){ |
| 7996 | bRowids = 0; |
| 7997 | }else |
| 7998 | if( n<=7 && memcmp("-unsafe", z, n)==0 ){ |
| 7999 | bUnsafe = 1; |
| 8000 | } |
| 8001 | else{ |
| 8002 | cli_printf(stderr,"unexpected option: %s\n", azArg[i]); |
| 8003 | showHelp(pState->out, azArg[0]); |
| 8004 | return 1; |
| 8005 | } |
| 8006 | } |
| 8007 | |
| 8008 | p = sqlite3_recover_init_sql( |
| 8009 | pState->db, "main", recoverSqlCb, (void*)pState |
| 8010 | ); |
| 8011 | |
| 8012 | if( !pState->bSafeMode ){ |
| 8013 | sqlite3_recover_config(p, 789, (void*)zRecoveryDb); /* Debug use only */ |
| 8014 | } |
| 8015 | sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF); |
| 8016 | sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids); |
| 8017 | sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist); |
| 8018 | |
| 8019 | cli_printf(pState->out, ".dbconfig defensive off\n"); |
| 8020 | if( !bUnsafe ) cli_printf(pState->out, ".safe\n"); |
| 8021 | sqlite3_recover_run(p); |
| 8022 | if( sqlite3_recover_errcode(p)!=SQLITE_OK ){ |
| 8023 | const char *zErr = sqlite3_recover_errmsg(p); |
| 8024 | int errCode = sqlite3_recover_errcode(p); |
| 8025 | cli_printf(stderr,"sql error: %s (%d)\n", zErr, errCode); |
| 8026 | } |
| 8027 | rc = sqlite3_recover_finish(p); |
| 8028 | return rc; |
| 8029 | } |
| 8030 | #endif /* SQLITE_SHELL_HAVE_RECOVER */ |
| 8031 | |
| 8032 | /* |
| 8033 | ** Implementation of ".intck STEPS_PER_UNLOCK" command. |
| 8034 | */ |
| 8035 | static int intckDatabaseCmd(ShellState *pState, i64 nStepPerUnlock){ |
| 8036 | sqlite3_intck *p = 0; |
| 8037 | int rc = SQLITE_OK; |
| 8038 | |
| 8039 | rc = sqlite3_intck_open(pState->db, "main", &p); |
| 8040 | if( rc==SQLITE_OK ){ |
| 8041 | i64 nStep = 0; |
| 8042 | i64 nError = 0; |
| 8043 | const char *zErr = 0; |
| 8044 | while( SQLITE_OK==sqlite3_intck_step(p) ){ |
| 8045 | const char *zMsg = sqlite3_intck_message(p); |
| 8046 | if( zMsg ){ |
| 8047 | cli_printf(pState->out, "%s\n", zMsg); |
| 8048 | nError++; |
| 8049 | } |
| 8050 | nStep++; |
| 8051 | if( nStepPerUnlock && (nStep % nStepPerUnlock)==0 ){ |
| 8052 | sqlite3_intck_unlock(p); |
| 8053 | } |
| 8054 | } |
| 8055 | rc = sqlite3_intck_error(p, &zErr); |
| 8056 | if( zErr ){ |
| 8057 | cli_printf(stderr,"%s\n", zErr); |
| 8058 | } |
| 8059 | sqlite3_intck_close(p); |
| 8060 | |
| 8061 | cli_printf(pState->out, "%lld steps, %lld errors\n", nStep, nError); |
| 8062 | } |
| 8063 | |
| 8064 | return rc; |
| 8065 | } |
| 8066 | |
| 8067 | /* |
| 8068 | * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it. |
| 8069 | * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE, |
| 8070 | * close db and set it to 0, and return the columns spec, to later |
| 8071 | * be sqlite3_free()'ed by the caller. |
| 8072 | * The return is 0 when either: |
| 8073 | * (a) The db was not initialized and zCol==0 (There are no columns.) |
| 8074 | * (b) zCol!=0 (Column was added, db initialized as needed.) |
| 8075 | * The 3rd argument, pRenamed, references an out parameter. If the |
| 8076 | * pointer is non-zero, its referent will be set to a summary of renames |
| 8077 | * done if renaming was necessary, or set to 0 if none was done. The out |
| 8078 | * string (if any) must be sqlite3_free()'ed by the caller. |
| 8079 | */ |
| 8080 | #ifdef SHELL_DEBUG |
| 8081 | #define rc_err_oom_die(rc) \ |
| 8082 | if( rc==SQLITE_NOMEM ) shell_check_oom(0); \ |
| 8083 | else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \ |
| 8084 | cli_printf(stderr,"E:%d\n",rc), assert(0) |
| 8085 | #else |
| 8086 | static void rc_err_oom_die(int rc){ |
| 8087 | if( rc==SQLITE_NOMEM ) shell_check_oom(0); |
| 8088 | assert(rc==SQLITE_OK||rc==SQLITE_DONE); |
| 8089 | } |
| 8090 | #endif |
| 8091 | |
| 8092 | #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */ |
| 8093 | static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB); |
| 8094 | #else /* Otherwise, memory is faster/better for the transient DB. */ |
| 8095 | static const char *zCOL_DB = ":memory:"; |
| 8096 | #endif |
| 8097 | |
| 8098 | /* Define character (as C string) to separate generated column ordinal |
| 8099 | * from protected part of incoming column names. This defaults to "_" |
| 8100 | * so that incoming column identifiers that did not need not be quoted |
| 8101 | * remain usable without being quoted. It must be one character. |
| 8102 | */ |
| 8103 | #ifndef SHELL_AUTOCOLUMN_SEP |
| 8104 | # define AUTOCOLUMN_SEP "_" |
| 8105 | #else |
| 8106 | # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP) |
| 8107 | #endif |
| 8108 | |
| 8109 | static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){ |
| 8110 | /* Queries and D{D,M}L used here */ |
| 8111 | static const char * const zTabMake = "\ |
| 8112 | CREATE TABLE ColNames(\ |
| 8113 | cpos INTEGER PRIMARY KEY,\ |
| 8114 | name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\ |
| 8115 | CREATE VIEW RepeatedNames AS \ |
| 8116 | SELECT DISTINCT t.name FROM ColNames t \ |
| 8117 | WHERE t.name COLLATE NOCASE IN (\ |
| 8118 | SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\ |
| 8119 | );\ |
| 8120 | "; |
| 8121 | static const char * const zTabFill = "\ |
| 8122 | INSERT INTO ColNames(name,nlen,chop,reps,suff)\ |
| 8123 | VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\ |
| 8124 | "; |
| 8125 | static const char * const zHasDupes = "\ |
| 8126 | SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\ |
| 8127 | <count(name) FROM ColNames\ |
| 8128 | "; |
| 8129 | #ifdef SHELL_COLUMN_RENAME_CLEAN |
| 8130 | static const char * const zDedoctor = "\ |
| 8131 | UPDATE ColNames SET chop=iif(\ |
| 8132 | (substring(name,nlen,1) BETWEEN '0' AND '9')\ |
| 8133 | AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\ |
| 8134 | nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\ |
| 8135 | 0\ |
| 8136 | )\ |
| 8137 | "; |
| 8138 | #endif |
| 8139 | static const char * const zSetReps = "\ |
| 8140 | UPDATE ColNames AS t SET reps=\ |
| 8141 | (SELECT count(*) FROM ColNames d \ |
| 8142 | WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\ |
| 8143 | COLLATE NOCASE\ |
| 8144 | )\ |
| 8145 | "; |
| 8146 | #ifdef SQLITE_ENABLE_MATH_FUNCTIONS |
| 8147 | static const char * const zColDigits = "\ |
| 8148 | SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \ |
| 8149 | "; |
| 8150 | #else |
| 8151 | /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */ |
| 8152 | static const char * const zColDigits = "\ |
| 8153 | SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \ |
| 8154 | WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \ |
| 8155 | ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \ |
| 8156 | "; |
| 8157 | #endif |
| 8158 | static const char * const zRenameRank = |
| 8159 | #ifdef SHELL_COLUMN_RENAME_CLEAN |
| 8160 | "UPDATE ColNames AS t SET suff=" |
| 8161 | "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')" |
| 8162 | #else /* ...RENAME_MINIMAL_ONE_PASS */ |
| 8163 | "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */ |
| 8164 | " SELECT 0 AS nlz" |
| 8165 | " UNION" |
| 8166 | " SELECT nlz+1 AS nlz FROM Lzn" |
| 8167 | " WHERE EXISTS(" |
| 8168 | " SELECT 1" |
| 8169 | " FROM ColNames t, ColNames o" |
| 8170 | " WHERE" |
| 8171 | " iif(t.name IN (SELECT * FROM RepeatedNames)," |
| 8172 | " printf('%s"AUTOCOLUMN_SEP"%s'," |
| 8173 | " t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2))," |
| 8174 | " t.name" |
| 8175 | " )" |
| 8176 | " =" |
| 8177 | " iif(o.name IN (SELECT * FROM RepeatedNames)," |
| 8178 | " printf('%s"AUTOCOLUMN_SEP"%s'," |
| 8179 | " o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2))," |
| 8180 | " o.name" |
| 8181 | " )" |
| 8182 | " COLLATE NOCASE" |
| 8183 | " AND o.cpos<>t.cpos" |
| 8184 | " GROUP BY t.cpos" |
| 8185 | " )" |
| 8186 | ") UPDATE Colnames AS t SET" |
| 8187 | " chop = 0," /* No chopping, never touch incoming names. */ |
| 8188 | " suff = iif(name IN (SELECT * FROM RepeatedNames)," |
| 8189 | " printf('"AUTOCOLUMN_SEP"%s', substring(" |
| 8190 | " printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2))," |
| 8191 | " ''" |
| 8192 | " )" |
| 8193 | #endif |
| 8194 | ; |
| 8195 | static const char * const zCollectVar = "\ |
| 8196 | SELECT\ |
| 8197 | '('||x'0a'\ |
| 8198 | || group_concat(\ |
| 8199 | cname,\ |
| 8200 | ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\ |
| 8201 | ||')' AS ColsSpec \ |
| 8202 | FROM (\ |
| 8203 | SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \ |
| 8204 | FROM ColNames ORDER BY cpos\ |
| 8205 | )"; |
| 8206 | static const char * const zRenamesDone = |
| 8207 | "SELECT group_concat(" |
| 8208 | " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff))," |
| 8209 | " ','||x'0a')" |
| 8210 | "FROM ColNames WHERE suff<>'' OR chop!=0" |
| 8211 | ; |
| 8212 | int rc; |
| 8213 | sqlite3_stmt *pStmt = 0; |
| 8214 | assert(pDb!=0); |
| 8215 | if( zColNew ){ |
| 8216 | /* Add initial or additional column. Init db if necessary. */ |
| 8217 | if( *pDb==0 ){ |
| 8218 | if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0; |
| 8219 | #ifdef SHELL_COLFIX_DB |
| 8220 | if(*zCOL_DB!=':') |
| 8221 | sqlite3_exec(*pDb,"drop table if exists ColNames;" |
| 8222 | "drop view if exists RepeatedNames;",0,0,0); |
| 8223 | #endif |
| 8224 | #undef SHELL_COLFIX_DB |
| 8225 | rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0); |
| 8226 | rc_err_oom_die(rc); |
| 8227 | } |
| 8228 | assert(*pDb!=0); |
| 8229 | rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0); |
| 8230 | rc_err_oom_die(rc); |
| 8231 | rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0); |
| 8232 | rc_err_oom_die(rc); |
| 8233 | rc = sqlite3_step(pStmt); |
| 8234 | rc_err_oom_die(rc); |
| 8235 | sqlite3_finalize(pStmt); |
| 8236 | return 0; |
| 8237 | }else if( *pDb==0 ){ |
| 8238 | return 0; |
| 8239 | }else{ |
| 8240 | /* Formulate the columns spec, close the DB, zero *pDb. */ |
| 8241 | char *zColsSpec = 0; |
| 8242 | int hasDupes = db_int(*pDb, "%s", zHasDupes); |
| 8243 | int nDigits = (hasDupes)? db_int(*pDb, "%s", zColDigits) : 0; |
| 8244 | if( hasDupes ){ |
| 8245 | #ifdef SHELL_COLUMN_RENAME_CLEAN |
| 8246 | rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0); |
| 8247 | rc_err_oom_die(rc); |
| 8248 | #endif |
| 8249 | rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0); |
| 8250 | rc_err_oom_die(rc); |
| 8251 | rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0); |
| 8252 | rc_err_oom_die(rc); |
| 8253 | sqlite3_bind_int(pStmt, 1, nDigits); |
| 8254 | rc = sqlite3_step(pStmt); |
| 8255 | sqlite3_finalize(pStmt); |
| 8256 | if( rc!=SQLITE_DONE ) rc_err_oom_die(SQLITE_NOMEM); |
| 8257 | } |
| 8258 | assert(db_int(*pDb, "%s", zHasDupes)==0); /* Consider: remove this */ |
| 8259 | rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0); |
| 8260 | rc_err_oom_die(rc); |
| 8261 | rc = sqlite3_step(pStmt); |
| 8262 | if( rc==SQLITE_ROW ){ |
| 8263 | zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); |
| 8264 | }else{ |
| 8265 | zColsSpec = 0; |
| 8266 | } |
| 8267 | if( pzRenamed!=0 ){ |
| 8268 | if( !hasDupes ) *pzRenamed = 0; |
| 8269 | else{ |
| 8270 | sqlite3_finalize(pStmt); |
| 8271 | if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0) |
| 8272 | && SQLITE_ROW==sqlite3_step(pStmt) ){ |
| 8273 | *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); |
| 8274 | }else |
| 8275 | *pzRenamed = 0; |
| 8276 | } |
| 8277 | } |
| 8278 | sqlite3_finalize(pStmt); |
| 8279 | sqlite3_close(*pDb); |
| 8280 | *pDb = 0; |
| 8281 | return zColsSpec; |
| 8282 | } |
| 8283 | } |
| 8284 | |
| 8285 | /* |
| 8286 | ** Check if the sqlite_schema table contains one or more virtual tables. If |
| 8287 | ** parameter zLike is not NULL, then it is an SQL expression that the |
| 8288 | ** sqlite_schema row must also match. If one or more such rows are found, |
| 8289 | ** print the following warning to the output: |
| 8290 | ** |
| 8291 | ** WARNING: Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled |
| 8292 | */ |
| 8293 | static int outputDumpWarning(ShellState *p, const char *zLike){ |
| 8294 | int rc = SQLITE_OK; |
| 8295 | sqlite3_stmt *pStmt = 0; |
| 8296 | shellPreparePrintf(p->db, &rc, &pStmt, |
| 8297 | "SELECT 1 FROM sqlite_schema o WHERE " |
| 8298 | "sql LIKE 'CREATE VIRTUAL TABLE%%' AND (%s)", zLike ? zLike : "true" |
| 8299 | ); |
| 8300 | if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 8301 | cli_puts("/* WARNING: " |
| 8302 | "Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled */\n", |
| 8303 | p->out |
| 8304 | ); |
| 8305 | } |
| 8306 | shellFinalize(&rc, pStmt); |
| 8307 | return rc; |
| 8308 | } |
| 8309 | |
| 8310 | /* |
| 8311 | ** Fault-Simulator state and logic. |
| 8312 | */ |
| 8313 | static struct { |
| 8314 | int iId; /* ID that triggers a simulated fault. -1 means "any" */ |
| 8315 | int iErr; /* The error code to return on a fault */ |
| 8316 | int iCnt; /* Trigger the fault only if iCnt is already zero */ |
| 8317 | int iInterval; /* Reset iCnt to this value after each fault */ |
| 8318 | int eVerbose; /* When to print output */ |
| 8319 | int nHit; /* Number of hits seen so far */ |
| 8320 | int nRepeat; /* Turn off after this many hits. 0 for never */ |
| 8321 | int nSkip; /* Skip this many before first fault */ |
| 8322 | } faultsim_state = {-1, 0, 0, 0, 0, 0, 0, 0}; |
| 8323 | |
| 8324 | /* |
| 8325 | ** This is the fault-sim callback |
| 8326 | */ |
| 8327 | static int faultsim_callback(int iArg){ |
| 8328 | if( faultsim_state.iId>0 && faultsim_state.iId!=iArg ){ |
| 8329 | return SQLITE_OK; |
| 8330 | } |
| 8331 | if( faultsim_state.iCnt ){ |
| 8332 | if( faultsim_state.iCnt>0 ) faultsim_state.iCnt--; |
| 8333 | if( faultsim_state.eVerbose>=2 ){ |
| 8334 | cli_printf(stdout, |
| 8335 | "FAULT-SIM id=%d no-fault (cnt=%d)\n", iArg, faultsim_state.iCnt); |
| 8336 | } |
| 8337 | return SQLITE_OK; |
| 8338 | } |
| 8339 | if( faultsim_state.eVerbose>=1 ){ |
| 8340 | cli_printf(stdout, |
| 8341 | "FAULT-SIM id=%d returns %d\n", iArg, faultsim_state.iErr); |
| 8342 | } |
| 8343 | faultsim_state.iCnt = faultsim_state.iInterval; |
| 8344 | faultsim_state.nHit++; |
| 8345 | if( faultsim_state.nRepeat>0 && faultsim_state.nRepeat<=faultsim_state.nHit ){ |
| 8346 | faultsim_state.iCnt = -1; |
| 8347 | } |
| 8348 | return faultsim_state.iErr; |
| 8349 | } |
| 8350 | |
| 8351 | /* |
| 8352 | ** pickStr(zArg, &zErr, zS1, zS2, ..., ""); |
| 8353 | ** |
| 8354 | ** Try to match zArg against zS1, zS2, and so forth until the first |
| 8355 | ** emptry string. Return the index of the match or -1 if none is found. |
| 8356 | ** If no match is found, and &zErr is not NULL, then write into |
| 8357 | ** zErr a message describing the valid choices. |
| 8358 | */ |
| 8359 | static int pickStr(const char *zArg, char **pzErr, ...){ |
| 8360 | int i, n; |
| 8361 | const char *z; |
| 8362 | sqlite3_str *pMsg; |
| 8363 | va_list ap; |
| 8364 | va_start(ap, pzErr); |
| 8365 | i = 0; |
| 8366 | while( (z = va_arg(ap,const char*))!=0 && z[0]!=0 ){ |
| 8367 | if( cli_strcmp(zArg, z)==0 ) return i; |
| 8368 | i++; |
| 8369 | } |
| 8370 | va_end(ap); |
| 8371 | if( pzErr==0 ) return -1; |
| 8372 | n = i; |
| 8373 | pMsg = sqlite3_str_new(0); |
| 8374 | va_start(ap, pzErr); |
| 8375 | sqlite3_str_appendall(pMsg, "should be"); |
| 8376 | i = 0; |
| 8377 | while( (z = va_arg(ap, const char*))!=0 && z[0]!=0 ){ |
| 8378 | if( i==n-1 ){ |
| 8379 | sqlite3_str_append(pMsg,", or",4); |
| 8380 | }else if( i>0 ){ |
| 8381 | sqlite3_str_append(pMsg, ",", 1); |
| 8382 | } |
| 8383 | sqlite3_str_appendf(pMsg, " %s", z); |
| 8384 | i++; |
| 8385 | } |
| 8386 | va_end(ap); |
| 8387 | *pzErr = sqlite3_str_finish(pMsg); |
| 8388 | return -1; |
| 8389 | } |
| 8390 | |
| 8391 | /* |
| 8392 | ** DOT-COMMAND: .import |
| 8393 | ** |
| 8394 | ** USAGE: .import [OPTIONS] FILE TABLE |
| 8395 | ** |
| 8396 | ** Import CSV or similar text from FILE into TABLE. If TABLE does |
| 8397 | ** not exist, it is created using the first row of FILE as the column |
| 8398 | ** names. If FILE begins with "|" then it is a command that is run |
| 8399 | ** and the output from the command is used as the input data. If |
| 8400 | ** FILE begins with "<<" followed by a label, then content is read from |
| 8401 | ** the script until the first line that matches the label. |
| 8402 | ** |
| 8403 | ** The content of FILE is interpreted using RFC-4180 ("CSV") quoting |
| 8404 | ** rules unless the current mode is "ascii" or "tabs" or unless one |
| 8405 | ** the --ascii option is used. |
| 8406 | ** |
| 8407 | ** The column and row separators must be single ASCII characters. If |
| 8408 | ** multiple characters or a Unicode character are specified for the |
| 8409 | ** separators, then only the first byte of the separator is used. Except, |
| 8410 | ** if the row separator is \n and the mode is not --ascii, then \r\n is |
| 8411 | ** understood as a row separator too. |
| 8412 | ** |
| 8413 | ** Options: |
| 8414 | ** --ascii Do not use RFC-4180 quoting. Use \037 and \036 |
| 8415 | ** as column and row separators on input, unless other |
| 8416 | ** delimiters are specified using --colsep and/or --rowsep |
| 8417 | ** --colsep CHAR Use CHAR as the column separator. |
| 8418 | ** --csv Input is standard RFC-4180 CSV. |
| 8419 | ** --esc CHAR Use CHAR as an escape character in unquoted CSV inputs. |
| 8420 | ** --qesc CHAR Use CHAR as an escape character in quoted CSV inputs. |
| 8421 | ** --rowsep CHAR Use CHAR as the row separator. |
| 8422 | ** --schema S When creating TABLE, put it in schema S |
| 8423 | ** --skip N Ignore the first N rows of input |
| 8424 | ** -v Verbose mode |
| 8425 | */ |
| 8426 | static int dotCmdImport(ShellState *p){ |
| 8427 | int nArg = p->dot.nArg; /* Number of arguments */ |
| 8428 | char **azArg = p->dot.azArg;/* Argument list */ |
| 8429 | char *zTable = 0; /* Insert data into this table */ |
| 8430 | char *zSchema = 0; /* Schema of zTable */ |
| 8431 | char *zFile = 0; /* Name of file to extra content from */ |
| 8432 | sqlite3_stmt *pStmt = NULL; /* A statement */ |
| 8433 | int nCol; /* Number of columns in the table */ |
| 8434 | i64 nByte; /* Number of bytes in an SQL string */ |
| 8435 | int i, j; /* Loop counters */ |
| 8436 | int needCommit; /* True to COMMIT or ROLLBACK at end */ |
| 8437 | char *zSql = 0; /* An SQL statement */ |
| 8438 | ImportCtx sCtx; /* Reader context */ |
| 8439 | char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */ |
| 8440 | int eVerbose = 0; /* Larger for more console output */ |
| 8441 | i64 nSkip = 0; /* Initial lines to skip */ |
| 8442 | i64 iLineOffset = 0; /* Offset to the first line of input */ |
| 8443 | char *zCreate = 0; /* CREATE TABLE statement text */ |
| 8444 | int rc; /* Result code */ |
| 8445 | |
| 8446 | failIfSafeMode(p, "cannot run .import in safe mode"); |
| 8447 | memset(&sCtx, 0, sizeof(sCtx)); |
| 8448 | if( p->mode.eMode==MODE_Ascii ){ |
| 8449 | xRead = ascii_read_one_field; |
| 8450 | }else{ |
| 8451 | xRead = csv_read_one_field; |
| 8452 | } |
| 8453 | for(i=1; i<nArg; i++){ |
| 8454 | char *z = azArg[i]; |
| 8455 | if( z[0]=='-' && z[1]=='-' ) z++; |
| 8456 | if( z[0]!='-' ){ |
| 8457 | if( zFile==0 ){ |
| 8458 | zFile = z; |
| 8459 | }else if( zTable==0 ){ |
| 8460 | zTable = z; |
| 8461 | }else{ |
| 8462 | dotCmdError(p, i, "unknown argument", 0); |
| 8463 | return 1; |
| 8464 | } |
| 8465 | }else if( cli_strcmp(z,"-v")==0 ){ |
| 8466 | eVerbose++; |
| 8467 | }else if( cli_strcmp(z,"-schema")==0 ){ |
| 8468 | if( i==nArg-1 ){ |
| 8469 | dotCmdError(p, i, "missing argument", 0); |
| 8470 | return 1; |
| 8471 | } |
| 8472 | zSchema = azArg[++i]; |
| 8473 | }else if( cli_strcmp(z,"-skip")==0 ){ |
| 8474 | if( i==nArg-1 ){ |
| 8475 | dotCmdError(p, i, "missing argument", 0); |
| 8476 | return 1; |
| 8477 | } |
| 8478 | nSkip = integerValue(azArg[++i]); |
| 8479 | }else if( cli_strcmp(z,"-ascii")==0 ){ |
| 8480 | if( sCtx.cColSep==0 ) sCtx.cColSep = '\037'; |
| 8481 | if( sCtx.cRowSep==0 ) sCtx.cRowSep = '\036'; |
| 8482 | xRead = ascii_read_one_field; |
| 8483 | }else if( cli_strcmp(z,"-csv")==0 ){ |
| 8484 | if( sCtx.cColSep==0 ) sCtx.cColSep = ','; |
| 8485 | if( sCtx.cRowSep==0 ) sCtx.cRowSep = '\n'; |
| 8486 | xRead = csv_read_one_field; |
| 8487 | }else if( cli_strcmp(z,"-esc")==0 ){ |
| 8488 | if( i==nArg-1 ){ |
| 8489 | dotCmdError(p, i, "missing argument", 0); |
| 8490 | return 1; |
| 8491 | } |
| 8492 | sCtx.cUQEscape = azArg[++i][0]; |
| 8493 | }else if( cli_strcmp(z,"-qesc")==0 ){ |
| 8494 | if( i==nArg-1 ){ |
| 8495 | dotCmdError(p, i, "missing argument", 0); |
| 8496 | return 1; |
| 8497 | } |
| 8498 | sCtx.cQEscape = azArg[++i][0]; |
| 8499 | }else if( cli_strcmp(z,"-colsep")==0 ){ |
| 8500 | if( i==nArg-1 ){ |
| 8501 | dotCmdError(p, i, "missing argument", 0); |
| 8502 | return 1; |
| 8503 | } |
| 8504 | i++; |
| 8505 | sCtx.cColSep = azArg[i][0]; |
| 8506 | }else if( cli_strcmp(z,"-rowsep")==0 ){ |
| 8507 | if( i==nArg-1 ){ |
| 8508 | dotCmdError(p, i, "missing argument", 0); |
| 8509 | return 1; |
| 8510 | } |
| 8511 | i++; |
| 8512 | sCtx.cRowSep = azArg[i][0]; |
| 8513 | }else{ |
| 8514 | dotCmdError(p, i, "unknown option", 0); |
| 8515 | return 1; |
| 8516 | } |
| 8517 | } |
| 8518 | if( zTable==0 ){ |
| 8519 | dotCmdError(p, nArg, 0, "Missing %s argument\n", |
| 8520 | zFile==0 ? "FILE" : "TABLE"); |
| 8521 | return 1; |
| 8522 | } |
| 8523 | seenInterrupt = 0; |
| 8524 | open_db(p, 0); |
| 8525 | if( sCtx.cColSep==0 ){ |
| 8526 | if( p->mode.spec.zColumnSep && p->mode.spec.zColumnSep[0]!=0 ){ |
| 8527 | sCtx.cColSep = p->mode.spec.zColumnSep[0]; |
| 8528 | }else{ |
| 8529 | sCtx.cColSep = ','; |
| 8530 | } |
| 8531 | } |
| 8532 | if( (sCtx.cColSep & 0x80)!=0 ){ |
| 8533 | eputz("Error: .import column separator must be ASCII\n"); |
| 8534 | return 1; |
| 8535 | } |
| 8536 | if( sCtx.cRowSep==0 ){ |
| 8537 | if( p->mode.spec.zRowSep && p->mode.spec.zRowSep[0]!=0 ){ |
| 8538 | sCtx.cRowSep = p->mode.spec.zRowSep[0]; |
| 8539 | }else{ |
| 8540 | sCtx.cRowSep = '\n'; |
| 8541 | } |
| 8542 | } |
| 8543 | if( sCtx.cRowSep=='\r' && xRead!=ascii_read_one_field ){ |
| 8544 | sCtx.cRowSep = '\n'; |
| 8545 | } |
| 8546 | if( (sCtx.cRowSep & 0x80)!=0 ){ |
| 8547 | eputz("Error: .import row separator must be ASCII\n"); |
| 8548 | return 1; |
| 8549 | } |
| 8550 | sCtx.zFile = zFile; |
| 8551 | sCtx.nLine = 1; |
| 8552 | if( sCtx.zFile[0]=='|' ){ |
| 8553 | #ifdef SQLITE_OMIT_POPEN |
| 8554 | eputz("Error: pipes are not supported in this OS\n"); |
| 8555 | return 1; |
| 8556 | #else |
| 8557 | sCtx.in = sqlite3_popen(sCtx.zFile+1, "r"); |
| 8558 | sCtx.zFile = "<pipe>"; |
| 8559 | sCtx.xCloser = pclose; |
| 8560 | #endif |
| 8561 | }else if( sCtx.zFile[0]=='<' && sCtx.zFile[1]=='<' && sCtx.zFile[2]!=0 ){ |
| 8562 | /* Input text comes from subsequent lines of script until the zFile |
| 8563 | ** delimiter */ |
| 8564 | int nEndMark = strlen30(zFile)-2; |
| 8565 | char *zEndMark = &zFile[2]; |
| 8566 | sqlite3_str *pContent = sqlite3_str_new(p->db); |
| 8567 | int ckEnd = 1; |
| 8568 | i64 iStart = p->lineno; |
| 8569 | char zLine[2000]; |
| 8570 | sCtx.zFile = p->zInFile; |
| 8571 | sCtx.nLine = p->lineno+1; |
| 8572 | iLineOffset = p->lineno; |
| 8573 | while( shell_fgets(p, zLine,sizeof(zLine),p->in) ){ |
| 8574 | if( ckEnd && cli_strncmp(zLine,zEndMark,nEndMark)==0 ){ |
| 8575 | ckEnd = 2; |
| 8576 | if( strchr(zLine,'\n') ) p->lineno++; |
| 8577 | break; |
| 8578 | } |
| 8579 | if( strchr(zLine,'\n') ){ |
| 8580 | p->lineno++; |
| 8581 | ckEnd = 1; |
| 8582 | }else{ |
| 8583 | ckEnd = 0; |
| 8584 | } |
| 8585 | sqlite3_str_appendall(pContent, zLine); |
| 8586 | } |
| 8587 | sCtx.zIn = sqlite3_str_finish(pContent); |
| 8588 | if( sCtx.zIn==0 ){ |
| 8589 | sCtx.zIn = sqlite3_mprintf(""); |
| 8590 | } |
| 8591 | if( ckEnd<2 ){ |
| 8592 | i64 savedLn = p->lineno; |
| 8593 | p->lineno = iStart; |
| 8594 | dotCmdError(p, 0, 0,"Content terminator \"%s\" not found.",zEndMark); |
| 8595 | p->lineno = savedLn; |
| 8596 | import_cleanup(&sCtx); |
| 8597 | return 1; |
| 8598 | } |
| 8599 | }else{ |
| 8600 | sCtx.in = sqlite3_fopen(sCtx.zFile, "rb"); |
| 8601 | sCtx.xCloser = fclose; |
| 8602 | } |
| 8603 | if( sCtx.in==0 && sCtx.zIn==0 ){ |
| 8604 | dotCmdError(p, 0, 0, "cannot open \"%s\"", zFile); |
| 8605 | import_cleanup(&sCtx); |
| 8606 | return 1; |
| 8607 | } |
| 8608 | if( eVerbose>=1 ){ |
| 8609 | char zSep[2]; |
| 8610 | zSep[1] = 0; |
| 8611 | zSep[0] = sCtx.cColSep; |
| 8612 | cli_puts("Column separator ", p->out); |
| 8613 | output_c_string(p->out, zSep); |
| 8614 | cli_puts(", row separator ", p->out); |
| 8615 | zSep[0] = sCtx.cRowSep; |
| 8616 | output_c_string(p->out, zSep); |
| 8617 | cli_puts("\n", p->out); |
| 8618 | } |
| 8619 | sCtx.z = sqlite3_malloc64(120); |
| 8620 | if( sCtx.z==0 ){ |
| 8621 | import_cleanup(&sCtx); |
| 8622 | shell_out_of_memory(); |
| 8623 | } |
| 8624 | /* Below, resources must be freed before exit. */ |
| 8625 | while( nSkip>0 ){ |
| 8626 | nSkip--; |
| 8627 | while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){} |
| 8628 | } |
| 8629 | import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */ |
| 8630 | if( sqlite3_table_column_metadata(p->db, zSchema, zTable,0,0,0,0,0,0) |
| 8631 | && 0==db_int(p->db, "SELECT count(*) FROM \"%w\".sqlite_schema" |
| 8632 | " WHERE name=%Q COLLATE nocase AND type='view'", |
| 8633 | zSchema ? zSchema : "main", zTable) |
| 8634 | ){ |
| 8635 | /* Table does not exist. Create it. */ |
| 8636 | sqlite3 *dbCols = 0; |
| 8637 | char *zRenames = 0; |
| 8638 | char *zColDefs; |
| 8639 | zCreate = sqlite3_mprintf("CREATE TABLE \"%w\".\"%w\"", |
| 8640 | zSchema ? zSchema : "main", zTable); |
| 8641 | while( xRead(&sCtx) ){ |
| 8642 | zAutoColumn(sCtx.z, &dbCols, 0); |
| 8643 | if( sCtx.cTerm!=sCtx.cColSep ) break; |
| 8644 | } |
| 8645 | zColDefs = zAutoColumn(0, &dbCols, &zRenames); |
| 8646 | if( zRenames!=0 ){ |
| 8647 | cli_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr, |
| 8648 | "Columns renamed during .import %s due to duplicates:\n" |
| 8649 | "%s\n", sCtx.zFile, zRenames); |
| 8650 | sqlite3_free(zRenames); |
| 8651 | } |
| 8652 | assert(dbCols==0); |
| 8653 | if( zColDefs==0 ){ |
| 8654 | cli_printf(stderr,"%s: empty file\n", sCtx.zFile); |
| 8655 | import_cleanup(&sCtx); |
| 8656 | sqlite3_free(zCreate); |
| 8657 | return 1; |
| 8658 | } |
| 8659 | zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs); |
| 8660 | if( zCreate==0 ){ |
| 8661 | import_cleanup(&sCtx); |
| 8662 | shell_out_of_memory(); |
| 8663 | } |
| 8664 | if( eVerbose>=1 ){ |
| 8665 | cli_printf(p->out, "%s\n", zCreate); |
| 8666 | } |
| 8667 | rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); |
| 8668 | if( rc ){ |
| 8669 | cli_printf(stderr, |
| 8670 | "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db)); |
| 8671 | } |
| 8672 | sqlite3_free(zCreate); |
| 8673 | zCreate = 0; |
| 8674 | if( rc ){ |
| 8675 | import_cleanup(&sCtx); |
| 8676 | return 1; |
| 8677 | } |
| 8678 | } |
| 8679 | zSql = sqlite3_mprintf("SELECT count(*) FROM pragma_table_info(%Q,%Q);", |
| 8680 | zTable, zSchema); |
| 8681 | if( zSql==0 ){ |
| 8682 | import_cleanup(&sCtx); |
| 8683 | shell_out_of_memory(); |
| 8684 | } |
| 8685 | rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); |
| 8686 | sqlite3_free(zSql); |
| 8687 | zSql = 0; |
| 8688 | if( rc ){ |
| 8689 | if (pStmt) sqlite3_finalize(pStmt); |
| 8690 | shellDatabaseError(p->db); |
| 8691 | import_cleanup(&sCtx); |
| 8692 | return 1; |
| 8693 | } |
| 8694 | if( sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 8695 | nCol = sqlite3_column_int(pStmt, 0); |
| 8696 | }else{ |
| 8697 | nCol = 0; |
| 8698 | } |
| 8699 | sqlite3_finalize(pStmt); |
| 8700 | pStmt = 0; |
| 8701 | if( nCol==0 ) return 0; /* no columns, no error */ |
| 8702 | |
| 8703 | nByte = 64 /* space for "INSERT INTO", "VALUES(", ")\0" */ |
| 8704 | + (zSchema ? strlen(zSchema)*2 + 2: 0) /* Quoted schema name */ |
| 8705 | + strlen(zTable)*2 + 2 /* Quoted table name */ |
| 8706 | + nCol*2; /* Space for ",?" for each column */ |
| 8707 | zSql = sqlite3_malloc64( nByte ); |
| 8708 | if( zSql==0 ){ |
| 8709 | import_cleanup(&sCtx); |
| 8710 | shell_out_of_memory(); |
| 8711 | } |
| 8712 | if( zSchema ){ |
| 8713 | sqlite3_snprintf(nByte, zSql, "INSERT INTO \"%w\".\"%w\" VALUES(?", |
| 8714 | zSchema, zTable); |
| 8715 | }else{ |
| 8716 | sqlite3_snprintf(nByte, zSql, "INSERT INTO \"%w\" VALUES(?", zTable); |
| 8717 | } |
| 8718 | j = strlen30(zSql); |
| 8719 | for(i=1; i<nCol; i++){ |
| 8720 | zSql[j++] = ','; |
| 8721 | zSql[j++] = '?'; |
| 8722 | } |
| 8723 | zSql[j++] = ')'; |
| 8724 | zSql[j] = 0; |
| 8725 | assert( j<nByte ); |
| 8726 | if( eVerbose>=2 ){ |
| 8727 | cli_printf(p->out, "Insert using: %s\n", zSql); |
| 8728 | } |
| 8729 | rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); |
| 8730 | sqlite3_free(zSql); |
| 8731 | zSql = 0; |
| 8732 | if( rc ){ |
| 8733 | shellDatabaseError(p->db); |
| 8734 | if (pStmt) sqlite3_finalize(pStmt); |
| 8735 | import_cleanup(&sCtx); |
| 8736 | return 1; |
| 8737 | } |
| 8738 | needCommit = sqlite3_get_autocommit(p->db); |
| 8739 | if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); |
| 8740 | do{ |
| 8741 | int startLine = sCtx.nLine; |
| 8742 | for(i=0; i<nCol; i++){ |
| 8743 | char *z = xRead(&sCtx); |
| 8744 | /* |
| 8745 | ** Did we reach end-of-file before finding any columns? |
| 8746 | ** If so, stop instead of NULL filling the remaining columns. |
| 8747 | */ |
| 8748 | if( z==0 && i==0 ) break; |
| 8749 | /* |
| 8750 | ** Did we reach end-of-file OR end-of-line before finding any |
| 8751 | ** columns in ASCII mode? If so, stop instead of NULL filling |
| 8752 | ** the remaining columns. |
| 8753 | */ |
| 8754 | if( p->mode.eMode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; |
| 8755 | /* |
| 8756 | ** For CSV mode, per RFC 4180, accept EOF in lieu of final |
| 8757 | ** record terminator but only for last field of multi-field row. |
| 8758 | ** (If there are too few fields, it's not valid CSV anyway.) |
| 8759 | */ |
| 8760 | if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){ |
| 8761 | z = ""; |
| 8762 | } |
| 8763 | sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); |
| 8764 | if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){ |
| 8765 | if( i==0 && (strcmp(z,"\n")==0 || strcmp(z,"\r\n")==0) ){ |
| 8766 | /* Ignore trailing \n or \r\n when some other row separator */ |
| 8767 | break; |
| 8768 | } |
| 8769 | cli_printf(stderr,"%s:%d: expected %d columns but found %d" |
| 8770 | " - filling the rest with NULL\n", |
| 8771 | sCtx.zFile, startLine, nCol, i+1); |
| 8772 | i += 2; |
| 8773 | while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; } |
| 8774 | } |
| 8775 | } |
| 8776 | if( sCtx.cTerm==sCtx.cColSep ){ |
| 8777 | do{ |
| 8778 | xRead(&sCtx); |
| 8779 | i++; |
| 8780 | }while( sCtx.cTerm==sCtx.cColSep ); |
| 8781 | cli_printf(stderr, |
| 8782 | "%s:%d: expected %d columns but found %d - extras ignored\n", |
| 8783 | sCtx.zFile, startLine, nCol, i); |
| 8784 | } |
| 8785 | if( i>=nCol ){ |
| 8786 | sqlite3_step(pStmt); |
| 8787 | rc = sqlite3_reset(pStmt); |
| 8788 | if( rc!=SQLITE_OK ){ |
| 8789 | cli_printf(stderr,"%s:%d: INSERT failed: %s\n", |
| 8790 | sCtx.zFile, startLine, sqlite3_errmsg(p->db)); |
| 8791 | sCtx.nErr++; |
| 8792 | if( bail_on_error ) break; |
| 8793 | }else{ |
| 8794 | sCtx.nRow++; |
| 8795 | } |
| 8796 | } |
| 8797 | }while( sCtx.cTerm!=EOF ); |
| 8798 | |
| 8799 | import_cleanup(&sCtx); |
| 8800 | sqlite3_finalize(pStmt); |
| 8801 | if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); |
| 8802 | if( eVerbose>0 ){ |
| 8803 | cli_printf(p->out, |
| 8804 | "Added %d rows with %d errors using %lld lines of input\n", |
| 8805 | sCtx.nRow, sCtx.nErr, sCtx.nLine-1-iLineOffset); |
| 8806 | } |
| 8807 | return sCtx.nErr ? 1 : 0; |
| 8808 | } |
| 8809 | |
| 8810 | |
| 8811 | /* |
| 8812 | ** This function computes what to show the user about the configured |
| 8813 | ** titles (or column-names). Output is an integer between 0 and 3: |
| 8814 | ** |
| 8815 | ** 0: The titles do not matter. Never show anything. |
| 8816 | ** 1: Show "--title off" |
| 8817 | ** 2: Show "--title on" |
| 8818 | ** 3: Show "--title always" |
| 8819 | ** 4: Show "--title VALUE" where VALUE is an encoding method |
| 8820 | ** to use, one of: plain sql csv html tcl json |
| 8821 | ** 5: Show "--title VALUE" as in 3, followed by "--title always" |
| 8822 | ** |
| 8823 | ** Inputs are: |
| 8824 | ** |
| 8825 | ** spec.bTitles (bT) Whether or not to show the titles |
| 8826 | ** spec.eTitle (eT) The actual encoding to be used for titles |
| 8827 | ** ModeInfo.bHdr (bH) Default value for spec.bTitles |
| 8828 | ** ModeInfo.eHdr (eH) Default value for spec.eTitle |
| 8829 | ** bAll Whether the -v option is used |
| 8830 | */ |
| 8831 | static int modeTitleDsply(ShellState *p, int bAll){ |
| 8832 | int eMode = p->mode.eMode; |
| 8833 | const ModeInfo *pI = &aModeInfo[eMode]; |
| 8834 | int bT = p->mode.spec.bTitles; |
| 8835 | int eT = p->mode.spec.eTitle; |
| 8836 | int bH = pI->bHdr; |
| 8837 | int eH = pI->eHdr; |
| 8838 | |
| 8839 | /* Variable "v" is the truth table that will determine the answer |
| 8840 | ** |
| 8841 | ** Actual encoding is different from default |
| 8842 | ** vvvvvvvv */ |
| 8843 | sqlite3_uint64 v = UINT64_C(0x0133013311220102); |
| 8844 | /* ^^^^ ^^^^ |
| 8845 | ** Upper 2-byte groups for when ON/OFF disagrees with |
| 8846 | ** the default. */ |
| 8847 | |
| 8848 | if( bH==0 ) return 0; /* Header not appliable. Ex: off, count */ |
| 8849 | |
| 8850 | if( eT==0 ) eT = eH; /* Fill in missing spec.eTitle */ |
| 8851 | if( bT==0 ) bT = bH; /* Fill in missing spec.bTitles */ |
| 8852 | |
| 8853 | if( eT!=eH ) v >>= 32; /* Encoding disagree in upper 4-bytes */ |
| 8854 | if( bT!=bH ) v >>= 16; /* ON/OFF disagree in upper 2-byte pairs */ |
| 8855 | if( bT<2 ) v >>= 8; /* ON in even bytes, OFF in odd bytes (1st byte 0) */ |
| 8856 | if( !bAll ) v >>= 4; /* bAll values are in the lower half-byte */ |
| 8857 | |
| 8858 | v &= 3; |
| 8859 | /* At this point v means: |
| 8860 | ** 0: The titles do not matter. Never show anything. |
| 8861 | ** 1: Show "--title off" |
| 8862 | ** 2: Show "--title on" |
| 8863 | ** 3: Show "--title VALUE" where VALUE is an encoding method |
| 8864 | ** to use, one of: plain sql csv html tcl json |
| 8865 | ** If bTitles is QRF_Always, convert 2->3, 3->5. If bTitles is not |
| 8866 | ** QRF_Always, convert 3->4. |
| 8867 | */ |
| 8868 | if( p->mode.spec.bTitles==QRF_Always ){ |
| 8869 | if( v==3 ) v = 5; |
| 8870 | if( v==2 ) v = 3; |
| 8871 | }else{ |
| 8872 | if( v==3 ) v = 4; |
| 8873 | } |
| 8874 | return v; |
| 8875 | } |
| 8876 | |
| 8877 | /* |
| 8878 | ** DOT-COMMAND: .mode |
| 8879 | ** |
| 8880 | ** USAGE: .mode [MODE] [OPTIONS] |
| 8881 | ** |
| 8882 | ** Change the output mode to MODE and/or apply OPTIONS to the output mode. |
| 8883 | ** Arguments are processed from left to right. If no arguments, show the |
| 8884 | ** current output mode and relevant options. Use the --list option to get |
| 8885 | ** a list of available MODE values. Use -v to show all the current output |
| 8886 | ** mode settings. |
| 8887 | ** |
| 8888 | ** Options: |
| 8889 | ** --align STRING Set the alignment of text in columnar modes |
| 8890 | ** String consists of characters 'L', 'C', 'R' |
| 8891 | ** meaning "left", "centered", and "right", with |
| 8892 | ** one letter per column starting from the left. |
| 8893 | ** Unspecified alignment defaults to 'L'. |
| 8894 | ** --blob-quote ARG ARG can be "auto", "text", "sql", "hex", "tcl", |
| 8895 | ** "json", or "size". Default is "auto". |
| 8896 | ** --border on|off Show outer border on "box" and "table" modes. |
| 8897 | ** --charlimit N Set the maximum number of output characters to |
| 8898 | ** show for any single SQL value to N. Longer values |
| 8899 | ** truncated. Zero means "no limit". |
| 8900 | ** --colsep STRING Use STRING as the column separator |
| 8901 | ** --escape ESC Enable/disable escaping of control characters |
| 8902 | ** found in the output. ESC can be "auto", "off", |
| 8903 | ** "ascii", or "symbol". Default is "auto" |
| 8904 | ** --fpfmt STRING String is a printf-style format string used to |
| 8905 | ** render floating-point values. |
| 8906 | ** --ifmt STRING String is a printf-style format string used to |
| 8907 | ** render integer values. |
| 8908 | ** --linelimit N Set the maximum number of output lines to show for |
| 8909 | ** any single SQL value to N. Longer values are |
| 8910 | ** truncated. Zero means "no limit". Only works |
| 8911 | ** in "line" mode and in columnar modes. |
| 8912 | ** --limits L,C,T Shorthand for "--linelimit L --charlimit C |
| 8913 | ** --titlelimit T". The ",T" can be omitted in which |
| 8914 | ** case the --titlelimit is unchanged. The argument |
| 8915 | ** can also be "off" to mean "0,0,0" or "on" to |
| 8916 | ** mean "5,300,20". |
| 8917 | ** --list List available modes |
| 8918 | ** --multiinsert N In "insert" mode, put multiple rows on a single |
| 8919 | ** INSERT statement until the size exceeds N bytes. |
| 8920 | ** --null STRING Render SQL NULL values as the given string |
| 8921 | ** --once Setting changes to the right are reverted after |
| 8922 | ** the next SQL command. |
| 8923 | ** --quote ARG Enable/disable quoting of text. ARG can be |
| 8924 | ** "off", "on", "sql", "relaxed", "csv", "html", |
| 8925 | ** "tcl", or "json". "off" means show the text as-is. |
| 8926 | ** "on" is an alias for "sql". |
| 8927 | ** --reset Changes all mode settings back to their default. |
| 8928 | ** --rowcount BOOLEAN Show "(N rows)" at the end of query results. |
| 8929 | ** --rowsep STRING Use STRING as the row separator |
| 8930 | ** --sw|--screenwidth N Declare the screen width of the output device |
| 8931 | ** to be N characters. An attempt may be made to |
| 8932 | ** wrap output text to fit within this limit. Zero |
| 8933 | ** means "no limit". Or N can be "auto" to set the |
| 8934 | ** width automatically. |
| 8935 | ** --tablename NAME Set the name of the table for "insert" mode. |
| 8936 | ** --tag NAME Save current settings as a new mode called NAME. |
| 8937 | ** --textjsonb BOOLEAN If enabled, JSONB text is displayed as text JSON. |
| 8938 | ** --title ARG Whether or not to show column headers, and if so |
| 8939 | ** how to encode them. ARG can be "off", "on", |
| 8940 | ** "always", "sql", "csv", "html", "tcl", or "json". |
| 8941 | ** --titlelimit N Limit the length of column titles to N characters. |
| 8942 | ** -v|--verbose Verbose output |
| 8943 | ** --widths LIST Set the columns widths for columnar modes. The |
| 8944 | ** argument is a list of integers, one for each |
| 8945 | ** column. A "0" width means use a dynamic width |
| 8946 | ** based on the actual width of data. If there are |
| 8947 | ** fewer entries in LIST than columns, "0" is used |
| 8948 | ** for the unspecified widths. |
| 8949 | ** --wordwrap BOOLEAN Enable/disable word wrapping |
| 8950 | ** --wrap N Wrap columns wider than N characters |
| 8951 | ** --ww Shorthand for "--wordwrap on" |
| 8952 | */ |
| 8953 | static int dotCmdMode(ShellState *p){ |
| 8954 | int nArg = p->dot.nArg; /* Number of arguments */ |
| 8955 | char **azArg = p->dot.azArg;/* Argument list */ |
| 8956 | int eMode = -1; /* New mode value, or -1 for none */ |
| 8957 | int iMode = -1; /* Index of the argument that is the mode name */ |
| 8958 | int i; /* Loop counter */ |
| 8959 | int k; /* Misc index variable */ |
| 8960 | int chng = 0; /* True if anything has changed */ |
| 8961 | int bAll = 0; /* Show all details of the mode */ |
| 8962 | |
| 8963 | for(i=1; i<nArg; i++){ |
| 8964 | const char *z = azArg[i]; |
| 8965 | if( z[0]=='-' && z[1]=='-' ) z++; |
| 8966 | if( z[0]!='-' |
| 8967 | && iMode<0 |
| 8968 | && (eMode = modeFind(p, azArg[i]))>=0 |
| 8969 | && eMode!=MODE_Www |
| 8970 | ){ |
| 8971 | iMode = i; |
| 8972 | modeChange(p, eMode); |
| 8973 | /* (Legacy) If the mode is MODE_Insert and the next argument |
| 8974 | ** is not an option, then the next argument must be the table |
| 8975 | ** name. |
| 8976 | */ |
| 8977 | if( i+1<nArg && azArg[i+1][0]!='-' ){ |
| 8978 | i++; |
| 8979 | modeSetStr(&p->mode.spec.zTableName, azArg[i]); |
| 8980 | } |
| 8981 | chng = 1; |
| 8982 | }else if( optionMatch(z,"align") ){ |
| 8983 | char *zAlign; |
| 8984 | int nAlign; |
| 8985 | int nErr = 0; |
| 8986 | if( i+1>=nArg ){ |
| 8987 | dotCmdError(p, i, "missing argument", 0); |
| 8988 | return 1; |
| 8989 | } |
| 8990 | i++; |
| 8991 | zAlign = azArg[i]; |
| 8992 | nAlign = 0x3fff & strlen(zAlign); |
| 8993 | free(p->mode.spec.aAlign); |
| 8994 | p->mode.spec.aAlign = malloc(nAlign); |
| 8995 | shell_check_oom(p->mode.spec.aAlign); |
| 8996 | for(k=0; k<nAlign; k++){ |
| 8997 | unsigned char c = 0; |
| 8998 | switch( zAlign[k] ){ |
| 8999 | case 'l': case 'L': c = QRF_ALIGN_Left; break; |
| 9000 | case 'c': case 'C': c = QRF_ALIGN_Center; break; |
| 9001 | case 'r': case 'R': c = QRF_ALIGN_Right; break; |
| 9002 | default: nErr++; break; |
| 9003 | } |
| 9004 | p->mode.spec.aAlign[k] = c; |
| 9005 | } |
| 9006 | p->mode.spec.nAlign = nAlign; |
| 9007 | chng = 1; |
| 9008 | if( nErr ){ |
| 9009 | dotCmdError(p, i, "bad alignment string", |
| 9010 | "Should contain only characters L, C, and R."); |
| 9011 | return 1; |
| 9012 | } |
| 9013 | }else if( pickStr(z,0,"-blob","-blob-quote","")>=0 ){ |
| 9014 | if( (++i)>=nArg ){ |
| 9015 | dotCmdError(p, i-1, "missing argument", 0); |
| 9016 | return 1; |
| 9017 | } |
| 9018 | k = pickStr(azArg[i], 0, |
| 9019 | "auto", "text", "sql", "hex", "tcl", "json", "size", ""); |
| 9020 | /* 0 1 2 3 4 5 6 |
| 9021 | ** Must match QRF_BLOB_xxxx values. See also tag-20251124a */ |
| 9022 | if( k>=0 ){ |
| 9023 | p->mode.spec.eBlob = k & 0xff; |
| 9024 | } |
| 9025 | chng = 1; |
| 9026 | }else if( optionMatch(z,"border") ){ |
| 9027 | if( (++i)>=nArg ){ |
| 9028 | dotCmdError(p, i-1, "missing argument", 0); |
| 9029 | return 1; |
| 9030 | } |
| 9031 | k = pickStr(azArg[i], 0, "auto", "off", "on", ""); |
| 9032 | if( k>=0 ){ |
| 9033 | p->mode.spec.bBorder = k & 0x3; |
| 9034 | } |
| 9035 | chng = 1; |
| 9036 | }else if( 0<=(k=pickStr(z,0, |
| 9037 | "-charlimit","-linelimit","-titlelimit","-multiinsert","")) ){ |
| 9038 | i64 w; /* 0 1 2 3 */ |
| 9039 | if( i+1>=nArg ){ |
| 9040 | dotCmdError(p, i, "missing argument", 0); |
| 9041 | return 1; |
| 9042 | } |
| 9043 | w = integerValue(azArg[++i]); |
| 9044 | switch( k ){ |
| 9045 | case 0: p->mode.spec.nCharLimit = modeClamp32(w); break; |
| 9046 | case 1: p->mode.spec.nLineLimit = modeClamp16(w); break; |
| 9047 | case 2: p->mode.spec.nTitleLimit = modeClamp16(w); break; |
| 9048 | default: p->mode.spec.nMultiInsert = modeClamp32(w); break; |
| 9049 | } |
| 9050 | chng = 1; |
| 9051 | }else if( 0<=(k=pickStr(z,0,"-tablename","-rowsep","-colsep","-null","")) ){ |
| 9052 | /* 0 1 2 3 */ |
| 9053 | if( i+1>=nArg ){ |
| 9054 | dotCmdError(p, i, "missing argument", 0); |
| 9055 | return 1; |
| 9056 | } |
| 9057 | i++; |
| 9058 | switch( k ){ |
| 9059 | case 0: modeSetStr(&p->mode.spec.zTableName, azArg[i]); break; |
| 9060 | case 1: modeSetStr(&p->mode.spec.zRowSep, azArg[i]); break; |
| 9061 | case 2: modeSetStr(&p->mode.spec.zColumnSep, azArg[i]); break; |
| 9062 | case 3: modeSetStr(&p->mode.spec.zNull, azArg[i]); break; |
| 9063 | } |
| 9064 | chng = 1; |
| 9065 | }else if( optionMatch(z,"escape") ){ |
| 9066 | /* See similar code at tag-20250224-1 */ |
| 9067 | char *zErr = 0; |
| 9068 | if( (++i)>=nArg ){ |
| 9069 | dotCmdError(p, i-1, "missing argument", 0); |
| 9070 | return 1; |
| 9071 | } /* 0 1 2 3 */ |
| 9072 | k = pickStr(azArg[i],&zErr,"auto", "off","ascii","symbol",""); |
| 9073 | if( k<0 ){ |
| 9074 | dotCmdError(p, i, "unknown escape type", "%s", zErr); |
| 9075 | sqlite3_free(zErr); |
| 9076 | return 1; |
| 9077 | } |
| 9078 | p->mode.spec.eEsc = k; |
| 9079 | chng = 1; |
| 9080 | }else if( optionMatch(z,"limits") ){ |
| 9081 | if( (++i)>=nArg ){ |
| 9082 | dotCmdError(p, i-1, "missing argument", 0); |
| 9083 | return 1; |
| 9084 | } |
| 9085 | if( modeSetLimit(p, azArg[i]) ){ |
| 9086 | dotCmdError(p, i, "bad argument", "Should be \"on\" or \"off\" or " |
| 9087 | "\"L,C,T\" where L, C, and T are unsigned integers"); |
| 9088 | return 1; |
| 9089 | } |
| 9090 | chng = 1; |
| 9091 | }else if( optionMatch(z,"list") ){ |
| 9092 | int ii; |
| 9093 | cli_puts("available modes:", p->out); |
| 9094 | for(ii=0; ii<ArraySize(aModeInfo); ii++){ |
| 9095 | if( ii==MODE_Www ) continue; |
| 9096 | cli_printf(p->out, " %s", aModeInfo[ii].zName); |
| 9097 | } |
| 9098 | for(ii=0; ii<p->nSavedModes; ii++){ |
| 9099 | cli_printf(p->out, " %s", p->aSavedModes[ii].zTag); |
| 9100 | } |
| 9101 | cli_puts(" batch tty\n", p->out); |
| 9102 | chng = 1; /* Not really a change, but we still want to suppress the |
| 9103 | ** "current mode" output */ |
| 9104 | }else if( optionMatch(z,"once") ){ |
| 9105 | modePush(p); |
| 9106 | p->nPopMode = 1; |
| 9107 | }else if( optionMatch(z,"noquote") ){ |
| 9108 | /* (undocumented legacy) --noquote always turns quoting off */ |
| 9109 | p->mode.spec.eText = QRF_TEXT_Plain; |
| 9110 | p->mode.spec.eBlob = QRF_BLOB_Auto; |
| 9111 | chng = 1; |
| 9112 | }else if( optionMatch(z,"quote") ){ |
| 9113 | if( i+1<nArg |
| 9114 | && azArg[i+1][0]!='-' |
| 9115 | && (iMode>0 || strcmp(azArg[i+1],"off")==0 || modeFind(p, azArg[i+1])<0) |
| 9116 | ){ |
| 9117 | /* --quote is followed by an argument other that is not an option |
| 9118 | ** or a mode name. See it must be a boolean or a keyword to describe |
| 9119 | ** how to set quoting. */ |
| 9120 | i++; |
| 9121 | if( (k = pickStr(azArg[i],0,"no","yes","0","1",""))>=0 ){ |
| 9122 | k &= 1; /* 0 for "off". 1 for "on". */ |
| 9123 | }else{ |
| 9124 | char *zErr = 0; |
| 9125 | k = pickStr(azArg[i],&zErr, |
| 9126 | "off","on","sql","csv","html","tcl","json","relaxed",""); |
| 9127 | /* 0 1 2 3 4 5 6 7 */ |
| 9128 | if( k<0 ){ |
| 9129 | dotCmdError(p, i, "unknown", "%z", zErr); |
| 9130 | return 1; |
| 9131 | } |
| 9132 | } |
| 9133 | }else{ |
| 9134 | /* (Legacy) no following boolean argument. Turn quoting on */ |
| 9135 | k = 1; |
| 9136 | } |
| 9137 | switch( k ){ |
| 9138 | case 1: /* on */ |
| 9139 | modeSetStr(&p->mode.spec.zNull, "NULL"); |
| 9140 | /* Fall through */ |
| 9141 | case 2: /* sql */ |
| 9142 | p->mode.spec.eText = QRF_TEXT_Sql; |
| 9143 | break; |
| 9144 | case 3: /* csv */ |
| 9145 | p->mode.spec.eText = QRF_TEXT_Csv; |
| 9146 | break; |
| 9147 | case 4: /* html */ |
| 9148 | p->mode.spec.eText = QRF_TEXT_Html; |
| 9149 | break; |
| 9150 | case 5: /* tcl */ |
| 9151 | p->mode.spec.eText = QRF_TEXT_Tcl; |
| 9152 | break; |
| 9153 | case 6: /* json */ |
| 9154 | p->mode.spec.eText = QRF_TEXT_Json; |
| 9155 | break; |
| 9156 | case 7: /* relaxed */ |
| 9157 | p->mode.spec.eText = QRF_TEXT_Relaxed; |
| 9158 | break; |
| 9159 | default: /* off */ |
| 9160 | p->mode.spec.eText = QRF_TEXT_Plain; |
| 9161 | break; |
| 9162 | } |
| 9163 | chng = 1; |
| 9164 | }else if( optionMatch(z,"ifmt") ){ |
| 9165 | if( i+1>=nArg ){ |
| 9166 | dotCmdError(p, i, "missing argument", 0); |
| 9167 | return 1; |
| 9168 | } |
| 9169 | i++; |
| 9170 | if( azArg[i][0]==0 || cli_strcmp(azArg[i],"auto")==0 ){ |
| 9171 | p->mode.spec.zIFmt = 0; |
| 9172 | }else if( sqlite3_qrf_ckformat(azArg[i])!=1 ){ |
| 9173 | dotCmdError(p, i, "not a valid integer format", 0); |
| 9174 | return 1; |
| 9175 | }else{ |
| 9176 | assert( strlen(azArg[i])<sizeof(p->mode.zIFmt)-1 ); |
| 9177 | memcpy(p->mode.zIFmt, azArg[i], strlen(azArg[i])+1); |
| 9178 | p->mode.spec.zIFmt = p->mode.zIFmt; |
| 9179 | } |
| 9180 | chng = 1; |
| 9181 | }else if( optionMatch(z,"fpfmt") ){ |
| 9182 | if( i+1>=nArg ){ |
| 9183 | dotCmdError(p, i, "missing argument", 0); |
| 9184 | return 1; |
| 9185 | } |
| 9186 | i++; |
| 9187 | if( azArg[i][0]==0 || cli_strcmp(azArg[i],"auto")==0 ){ |
| 9188 | p->mode.spec.zFpFmt = 0; |
| 9189 | }else if( sqlite3_qrf_ckformat(azArg[i])!=2 ){ |
| 9190 | dotCmdError(p, i, "not a valid floating-point format", 0); |
| 9191 | return 1; |
| 9192 | }else{ |
| 9193 | assert( strlen(azArg[i])<sizeof(p->mode.zFpFmt)-1 ); |
| 9194 | memcpy(p->mode.zFpFmt, azArg[i], strlen(azArg[i])+1); |
| 9195 | p->mode.spec.zFpFmt = p->mode.zFpFmt; |
| 9196 | } |
| 9197 | chng = 1; |
| 9198 | }else if( optionMatch(z,"reset") ){ |
| 9199 | int saved_eMode = p->mode.eMode; /* Don't change the mode */ |
| 9200 | u8 saved_echo = p->mode.mFlags & MFLG_ECHO; /* Don't reset --echo */ |
| 9201 | modeFree(&p->mode); /* Reset everything else */ |
| 9202 | modeChange(p, saved_eMode); |
| 9203 | p->mode.mFlags = saved_echo; |
| 9204 | }else if( optionMatch(z,"rowcount") ){ |
| 9205 | if( i+1>=nArg ){ |
| 9206 | dotCmdError(p, i, "missing argument", 0); |
| 9207 | return 1; |
| 9208 | } |
| 9209 | p->mode.spec.bRowCount = booleanValue(azArg[++i]) ? QRF_Yes : QRF_No; |
| 9210 | chng = 1; |
| 9211 | }else if( optionMatch(z,"screenwidth") || optionMatch(z,"sw") ){ |
| 9212 | if( (++i)>=nArg ){ |
| 9213 | dotCmdError(p, i-1, "missing argument", 0); |
| 9214 | return 1; |
| 9215 | } |
| 9216 | k = pickStr(azArg[i],0,"off","auto",""); |
| 9217 | if( k==0 ){ |
| 9218 | p->mode.bAutoScreenWidth = 0; |
| 9219 | p->mode.spec.nScreenWidth = 0; |
| 9220 | }else if( k==1 ){ |
| 9221 | p->mode.bAutoScreenWidth = 1; |
| 9222 | }else{ |
| 9223 | i64 w = integerValue(azArg[i]); |
| 9224 | p->mode.bAutoScreenWidth = 0; |
| 9225 | if( w<0 ) w = 0; |
| 9226 | if( w>QRF_MAX_WIDTH ) w = QRF_MAX_WIDTH; |
| 9227 | p->mode.spec.nScreenWidth = w; |
| 9228 | } |
| 9229 | chng = 1; |
| 9230 | }else if( optionMatch(z,"tag") ){ |
| 9231 | size_t nByte; |
| 9232 | int n; |
| 9233 | const char *zTag; |
| 9234 | if( i+1>=nArg ){ |
| 9235 | dotCmdError(p, i, "missing argument", 0); |
| 9236 | return 1; |
| 9237 | } |
| 9238 | zTag = azArg[++i]; |
| 9239 | if( modeFind(p, zTag)>=0 ){ |
| 9240 | dotCmdError(p, i, "mode already exists", 0); |
| 9241 | return 1; |
| 9242 | } |
| 9243 | if( p->nSavedModes > MODE_N_USER ){ |
| 9244 | dotCmdError(p, i-1, "cannot add more modes", 0); |
| 9245 | return 1; |
| 9246 | } |
| 9247 | n = p->nSavedModes++; |
| 9248 | nByte = sizeof(p->aSavedModes[0]); |
| 9249 | nByte *= n+1; |
| 9250 | p->aSavedModes = realloc( p->aSavedModes, nByte ); |
| 9251 | shell_check_oom(p->aSavedModes); |
| 9252 | p->aSavedModes[n].zTag = strdup(zTag); |
| 9253 | shell_check_oom(p->aSavedModes[n].zTag); |
| 9254 | modeDup(&p->aSavedModes[n].mode, &p->mode); |
| 9255 | chng = 1; |
| 9256 | }else if( optionMatch(z,"textjsonb") ){ |
| 9257 | if( i+1>=nArg ){ |
| 9258 | dotCmdError(p, i, "missing argument", 0); |
| 9259 | return 1; |
| 9260 | } |
| 9261 | p->mode.spec.bTextJsonb = booleanValue(azArg[++i]) ? QRF_Yes : QRF_No; |
| 9262 | chng = 1; |
| 9263 | }else if( optionMatch(z,"titles") || optionMatch(z,"title") ){ |
| 9264 | /* The --titles option controls two fields of the |
| 9265 | ** sqlite3_qrf_spec object: eTitle and bTitles. |
| 9266 | ** |
| 9267 | ** --titles eTitle bTitles |
| 9268 | ** -------- --------------- --------------------- |
| 9269 | ** "off" (unchanged) QRF_Off |
| 9270 | ** "on" (unchanged) QRF_On |
| 9271 | ** "always" (unchanged) QRF_Always |
| 9272 | ** "auto", (default) (default) |
| 9273 | ** "plain" QRF_TEXT_Plain QRF_Always or QRF_On |
| 9274 | ** "sql" QRF_TEXT_Sql QRF_Always or QRF_On |
| 9275 | ** "csv" QRF_TEXT_Csv QRF_Always or QRF_On |
| 9276 | ** "html" QRF_TEXT_Html QRF_Always or QRF_On |
| 9277 | ** "tcl" QRF_TEXT_Tcl QRF_Always or QRF_On |
| 9278 | ** "json" QRF_TEXT_Json QRF_Always or QRF_On |
| 9279 | ** |
| 9280 | ** This mapping is different from the -title option to the "format" |
| 9281 | ** method of the TCL interface. In this mapping: |
| 9282 | ** |
| 9283 | ** * "off", "on", and "always" affect only bTitles and leave |
| 9284 | ** eTitle unchanged |
| 9285 | ** |
| 9286 | ** * "auto" sets both bTitles and eTitle to the default value |
| 9287 | ** in aModeInfo[] according to the current --style. |
| 9288 | ** |
| 9289 | ** * "plain" through "json" set eTitle but leave bTitles |
| 9290 | ** unchanged if it is not QRF_Off. If bTitles is QRF_Off, |
| 9291 | ** then it is changed QRF_Always. |
| 9292 | */ |
| 9293 | char *zErr = 0; |
| 9294 | if( i+1>=nArg ){ |
| 9295 | dotCmdError(p, i, "missing argument", 0); |
| 9296 | return 1; |
| 9297 | } |
| 9298 | k = pickStr(azArg[++i],&zErr, |
| 9299 | "off","on","always","auto","plain","sql","csv","html","tcl","json",""); |
| 9300 | /* 0 1 2 3 4 5 6 7 8 9 */ |
| 9301 | if( k<0 ){ |
| 9302 | dotCmdError(p, i, "bad --titles value","%z", zErr); |
| 9303 | return 1; |
| 9304 | } |
| 9305 | p->mode.mFlags &= ~MFLG_HDR; |
| 9306 | if( k<=2 ){ |
| 9307 | p->mode.spec.bTitles = QRF_No+k; |
| 9308 | }else if( k==3 ){ |
| 9309 | p->mode.spec.eTitle = aModeInfo[p->mode.eMode].eHdr; |
| 9310 | p->mode.spec.bTitles = aModeInfo[p->mode.eMode].bHdr; |
| 9311 | }else{ |
| 9312 | p->mode.spec.eTitle = (k-4)+QRF_TEXT_Plain; |
| 9313 | if( p->mode.spec.bTitles==QRF_No ){ |
| 9314 | p->mode.spec.bTitles = QRF_Always; |
| 9315 | } |
| 9316 | } |
| 9317 | chng = 1; |
| 9318 | }else if( optionMatch(z,"widths") || optionMatch(z,"width") ){ |
| 9319 | int nWidth = 0; |
| 9320 | short int *aWidth; |
| 9321 | const char *zW; |
| 9322 | if( i+1>=nArg ){ |
| 9323 | dotCmdError(p, i, "missing argument", 0); |
| 9324 | return 1; |
| 9325 | } |
| 9326 | zW = azArg[++i]; |
| 9327 | /* Every width value except a single-digit final value takes at |
| 9328 | ** least 2 bytes in the input string to specify, so strlen(zW)+1 |
| 9329 | ** entries is plenty of space to hold the result. */ |
| 9330 | aWidth = malloc( strlen(zW)+1 ); |
| 9331 | while( IsSpace(zW[0]) ) zW++; |
| 9332 | while( zW[0] ){ |
| 9333 | int w = 0; |
| 9334 | int nDigit = 0; |
| 9335 | k = zW[0]=='-' && IsDigit(zW[1]); |
| 9336 | while( IsDigit(zW[k]) ){ |
| 9337 | w = w*10 + zW[k] - '0'; |
| 9338 | if( w>QRF_MAX_WIDTH ){ |
| 9339 | dotCmdError(p,i+1,"width too big", |
| 9340 | "Maximum column width is %d", QRF_MAX_WIDTH); |
| 9341 | free(aWidth); |
| 9342 | return 1; |
| 9343 | } |
| 9344 | nDigit++; |
| 9345 | k++; |
| 9346 | } |
| 9347 | if( nDigit==0 ){ |
| 9348 | dotCmdError(p,i+1,"syntax error", |
| 9349 | "should be a comma-separated list if integers"); |
| 9350 | free(aWidth); |
| 9351 | return 1; |
| 9352 | } |
| 9353 | if( zW[0]=='-' ) w = -w; |
| 9354 | aWidth[nWidth++] = w; |
| 9355 | zW += k; |
| 9356 | if( zW[0]==',' ) zW++; |
| 9357 | while( IsSpace(zW[0]) ) zW++; |
| 9358 | } |
| 9359 | free(p->mode.spec.aWidth); |
| 9360 | p->mode.spec.aWidth = aWidth; |
| 9361 | p->mode.spec.nWidth = nWidth; |
| 9362 | chng = 1; |
| 9363 | }else if( optionMatch(z,"wrap") ){ |
| 9364 | int w; |
| 9365 | if( i+1>=nArg ){ |
| 9366 | dotCmdError(p, i, "missing argument", 0); |
| 9367 | return 1; |
| 9368 | } |
| 9369 | w = integerValue(azArg[++i]); |
| 9370 | if( w<(-QRF_MAX_WIDTH) ) w = -QRF_MAX_WIDTH; |
| 9371 | if( w>QRF_MAX_WIDTH ) w = QRF_MAX_WIDTH; |
| 9372 | p->mode.spec.nWrap = w; |
| 9373 | chng = 1; |
| 9374 | }else if( optionMatch(z,"ww") ){ |
| 9375 | p->mode.spec.bWordWrap = QRF_Yes; |
| 9376 | chng = 1; |
| 9377 | }else if( optionMatch(z,"wordwrap") ){ |
| 9378 | if( i+1>=nArg ){ |
| 9379 | dotCmdError(p, i, "missing argument", 0); |
| 9380 | return 1; |
| 9381 | } |
| 9382 | p->mode.spec.bWordWrap = (u8)booleanValue(azArg[++i]) ? QRF_Yes : QRF_No; |
| 9383 | chng = 1; |
| 9384 | }else if( optionMatch(z,"v") || optionMatch(z,"verbose") ){ |
| 9385 | bAll = 1; |
| 9386 | }else if( z[0]=='-' ){ |
| 9387 | dotCmdError(p, i, "bad option", "Use \".help .mode\" for more info"); |
| 9388 | return 1; |
| 9389 | }else{ |
| 9390 | dotCmdError(p, i, iMode>0?"bad argument":"unknown mode", |
| 9391 | "Use \".help .mode\" for more info"); |
| 9392 | return 1; |
| 9393 | } |
| 9394 | } |
| 9395 | if( !chng || bAll ){ |
| 9396 | const ModeInfo *pI = aModeInfo + p->mode.eMode; |
| 9397 | sqlite3_str *pDesc = sqlite3_str_new(p->db); |
| 9398 | char *zDesc; |
| 9399 | const char *zSetting; |
| 9400 | |
| 9401 | if( p->nPopMode ) sqlite3_str_appendall(pDesc, "--once "); |
| 9402 | sqlite3_str_appendall(pDesc,pI->zName); |
| 9403 | if( bAll || (p->mode.spec.nAlign && pI->eCx==2) ){ |
| 9404 | int ii; |
| 9405 | sqlite3_str_appendall(pDesc, " --align \""); |
| 9406 | for(ii=0; ii<p->mode.spec.nAlign; ii++){ |
| 9407 | unsigned char a = p->mode.spec.aAlign[ii]; |
| 9408 | sqlite3_str_appendchar(pDesc, 1, "LLCR"[a&3]); |
| 9409 | } |
| 9410 | sqlite3_str_append(pDesc, "\"", 1); |
| 9411 | } |
| 9412 | if( bAll |
| 9413 | || (p->mode.spec.bBorder==QRF_No) != ((pI->mFlg&1)!=0) |
| 9414 | ){ |
| 9415 | sqlite3_str_appendf(pDesc," --border %s", |
| 9416 | p->mode.spec.bBorder==QRF_No ? "off" : "on"); |
| 9417 | } |
| 9418 | if( bAll || p->mode.spec.eBlob!=QRF_BLOB_Auto ){ |
| 9419 | const char *azBQuote[] = |
| 9420 | { "auto", "text", "sql", "hex", "tcl", "json", "size" }; |
| 9421 | /* 0 1 2 3 4 5 6 |
| 9422 | ** Must match QRF_BLOB_xxxx values. See all instances of tag-20251124a */ |
| 9423 | u8 e = p->mode.spec.eBlob; |
| 9424 | sqlite3_str_appendf(pDesc, " --blob-quote %s", azBQuote[e]); |
| 9425 | } |
| 9426 | zSetting = aModeStr[pI->eCSep]; |
| 9427 | if( bAll || (zSetting && cli_strcmp(zSetting,p->mode.spec.zColumnSep)!=0) ){ |
| 9428 | sqlite3_str_appendf(pDesc, " --colsep "); |
| 9429 | append_c_string(pDesc, p->mode.spec.zColumnSep); |
| 9430 | } |
| 9431 | if( bAll || p->mode.spec.eEsc!=QRF_Auto ){ |
| 9432 | sqlite3_str_appendf(pDesc, " --escape %s",qrfEscNames[p->mode.spec.eEsc]); |
| 9433 | } |
| 9434 | if( bAll || p->mode.spec.zFpFmt!=0 ){ |
| 9435 | const char *z = p->mode.spec.zFpFmt; |
| 9436 | sqlite3_str_appendf(pDesc, " --fpfmt %s", z ? z : "auto"); |
| 9437 | } |
| 9438 | if( bAll || p->mode.spec.zIFmt!=0 ){ |
| 9439 | const char *z = p->mode.spec.zIFmt; |
| 9440 | sqlite3_str_appendf(pDesc, " --ifmt %s", z ? z : "auto"); |
| 9441 | } |
| 9442 | if( bAll |
| 9443 | || (p->mode.spec.nLineLimit>0 && pI->eCx>0) |
| 9444 | || p->mode.spec.nCharLimit>0 |
| 9445 | || (p->mode.spec.nTitleLimit>0 && pI->eCx>0) |
| 9446 | ){ |
| 9447 | if( p->mode.spec.nLineLimit==0 |
| 9448 | && p->mode.spec.nCharLimit==0 |
| 9449 | && p->mode.spec.nTitleLimit==0 |
| 9450 | ){ |
| 9451 | sqlite3_str_appendf(pDesc, " --limits off"); |
| 9452 | }else if( p->mode.spec.nLineLimit==DFLT_LINE_LIMIT |
| 9453 | && p->mode.spec.nCharLimit==DFLT_CHAR_LIMIT |
| 9454 | && p->mode.spec.nTitleLimit==DFLT_TITLE_LIMIT |
| 9455 | ){ |
| 9456 | sqlite3_str_appendf(pDesc, " --limits on"); |
| 9457 | }else{ |
| 9458 | sqlite3_str_appendf(pDesc, " --limits %d,%d,%d", |
| 9459 | p->mode.spec.nLineLimit, p->mode.spec.nCharLimit, |
| 9460 | p->mode.spec.nTitleLimit); |
| 9461 | } |
| 9462 | } |
| 9463 | if( bAll |
| 9464 | || (p->mode.spec.nMultiInsert && p->mode.spec.eStyle==QRF_STYLE_Insert) |
| 9465 | ){ |
| 9466 | sqlite3_str_appendf(pDesc, " --multiinsert %u", |
| 9467 | p->mode.spec.nMultiInsert); |
| 9468 | } |
| 9469 | zSetting = aModeStr[pI->eNull]; |
| 9470 | if( bAll || (zSetting && cli_strcmp(zSetting,p->mode.spec.zNull)!=0) ){ |
| 9471 | sqlite3_str_appendf(pDesc, " --null "); |
| 9472 | append_c_string(pDesc, p->mode.spec.zNull); |
| 9473 | } |
| 9474 | if( bAll |
| 9475 | || (pI->eText!=p->mode.spec.eText && (pI->eText>1 || p->mode.spec.eText>1)) |
| 9476 | ){ |
| 9477 | sqlite3_str_appendf(pDesc," --quote %s", |
| 9478 | qrfQuoteNames[p->mode.spec.eText]); |
| 9479 | } |
| 9480 | if( bAll |
| 9481 | || ((p->mode.spec.bRowCount==QRF_Yes) != ((pI->mFlg&4)!=0)) |
| 9482 | ){ |
| 9483 | sqlite3_str_appendf(pDesc," --rowcount %s", |
| 9484 | p->mode.spec.bRowCount==QRF_Yes ? "on" : "off"); |
| 9485 | } |
| 9486 | zSetting = aModeStr[pI->eRSep]; |
| 9487 | if( bAll || (zSetting && cli_strcmp(zSetting,p->mode.spec.zRowSep)!=0) ){ |
| 9488 | sqlite3_str_appendf(pDesc, " --rowsep "); |
| 9489 | append_c_string(pDesc, p->mode.spec.zRowSep); |
| 9490 | } |
| 9491 | if( bAll |
| 9492 | || (pI->eCx && (p->mode.spec.nScreenWidth>0 || p->mode.bAutoScreenWidth)) |
| 9493 | ){ |
| 9494 | if( p->mode.bAutoScreenWidth ){ |
| 9495 | sqlite3_str_appendall(pDesc, " --sw auto"); |
| 9496 | }else{ |
| 9497 | sqlite3_str_appendf(pDesc," --sw %d", |
| 9498 | p->mode.spec.nScreenWidth); |
| 9499 | } |
| 9500 | } |
| 9501 | if( bAll || p->mode.eMode==MODE_Insert ){ |
| 9502 | sqlite3_str_appendf(pDesc," --tablename "); |
| 9503 | append_c_string(pDesc, p->mode.spec.zTableName); |
| 9504 | } |
| 9505 | if( bAll || p->mode.spec.bTextJsonb ){ |
| 9506 | sqlite3_str_appendf(pDesc," --textjsonb %s", |
| 9507 | p->mode.spec.bTextJsonb==QRF_Yes ? "on" : "off"); |
| 9508 | } |
| 9509 | k = modeTitleDsply(p, bAll); |
| 9510 | if( k==1 ){ |
| 9511 | sqlite3_str_appendall(pDesc, " --titles off"); |
| 9512 | }else if( k==2 ){ |
| 9513 | sqlite3_str_appendall(pDesc, " --titles on"); |
| 9514 | }else if( k==3 ){ |
| 9515 | sqlite3_str_appendall(pDesc, " --titles always"); |
| 9516 | }else if( k>=4 ){ |
| 9517 | static const char *azTitle[] = |
| 9518 | { "plain", "sql", "csv", "html", "tcl", "json"}; |
| 9519 | sqlite3_str_appendf(pDesc, " --titles %s", |
| 9520 | azTitle[p->mode.spec.eTitle-1]); |
| 9521 | if( k==5 ){ |
| 9522 | sqlite3_str_appendf(pDesc, " --titles always"); |
| 9523 | } |
| 9524 | } |
| 9525 | if( p->mode.spec.nWidth>0 && (bAll || pI->eCx==2) ){ |
| 9526 | int ii; |
| 9527 | const char *zSep = " --widths "; |
| 9528 | for(ii=0; ii<p->mode.spec.nWidth; ii++){ |
| 9529 | sqlite3_str_appendf(pDesc, "%s%d", zSep, (int)p->mode.spec.aWidth[ii]); |
| 9530 | zSep = ","; |
| 9531 | } |
| 9532 | }else if( bAll ){ |
| 9533 | sqlite3_str_appendall(pDesc, " --widths \"\""); |
| 9534 | } |
| 9535 | if( bAll || (pI->eCx>0 && p->mode.spec.bWordWrap) ){ |
| 9536 | if( bAll ){ |
| 9537 | sqlite3_str_appendf(pDesc, " --wordwrap %s", |
| 9538 | p->mode.spec.bWordWrap==QRF_Yes ? "on" : "off"); |
| 9539 | } |
| 9540 | if( p->mode.spec.nWrap ){ |
| 9541 | sqlite3_str_appendf(pDesc, " --wrap %d", p->mode.spec.nWrap); |
| 9542 | } |
| 9543 | if( !bAll ) sqlite3_str_append(pDesc, " --ww", 5); |
| 9544 | } |
| 9545 | zDesc = sqlite3_str_finish(pDesc); |
| 9546 | cli_printf(p->out, ".mode %s\n", zDesc); |
| 9547 | fflush(p->out); |
| 9548 | sqlite3_free(zDesc); |
| 9549 | } |
| 9550 | return 0; |
| 9551 | } |
| 9552 | |
| 9553 | /* |
| 9554 | ** DOT-COMMAND: .output |
| 9555 | ** USAGE: .output [OPTIONS] [FILE] |
| 9556 | ** |
| 9557 | ** Begin redirecting output to FILE. Or if FILE is omitted, revert |
| 9558 | ** to sending output to the console. If FILE begins with "|" then |
| 9559 | ** the remainder of file is taken as a pipe and output is directed |
| 9560 | ** into that pipe. If FILE is "memory" then output is captured in an |
| 9561 | ** internal memory buffer. If FILE is "off" then output is redirected |
| 9562 | ** into /dev/null or the equivalent. |
| 9563 | ** |
| 9564 | ** Options: |
| 9565 | ** --bom Prepend a byte-order mark to the output |
| 9566 | ** -e Accumulate output in a temporary text file then |
| 9567 | ** launch a text editor when the redirection ends. |
| 9568 | ** --error-prefix X Use X as the left-margin prefix for error messages. |
| 9569 | ** Set to an empty string to restore the default. |
| 9570 | ** --keep Keep redirecting output to its current destination. |
| 9571 | ** Use this option in combination with --show or |
| 9572 | ** with --error-prefix when you do not want to stop |
| 9573 | ** a current redirection. |
| 9574 | ** --plain Use plain text rather than HTML tables with -w |
| 9575 | ** --show Show output text captured by .testcase or by |
| 9576 | ** redirecting to "memory". |
| 9577 | ** -w Show the output in a web browser. Output is |
| 9578 | ** written into a temporary HTML file until the |
| 9579 | ** redirect ends, then the web browser is launched. |
| 9580 | ** Query results are shown as HTML tables, unless |
| 9581 | ** the --plain is used too. |
| 9582 | ** -x Show the output in a spreadsheet. Output is |
| 9583 | ** written to a temp file as CSV then the spreadsheet |
| 9584 | ** is launched when |
| 9585 | ** |
| 9586 | ** DOT-COMMAND: .once |
| 9587 | ** USAGE: .once [OPTIONS] FILE ... |
| 9588 | ** |
| 9589 | ** Write the output for the next line of SQL or the next dot-command into |
| 9590 | ** FILE. If FILE begins with "|" then it is a program into which output |
| 9591 | ** is written. The FILE argument should be omitted if one of the -e, -w, |
| 9592 | ** or -x options is used. |
| 9593 | ** |
| 9594 | ** Options: |
| 9595 | ** -e Capture output into a temporary file then bring up |
| 9596 | ** a text editor on that temporary file. |
| 9597 | ** --plain Use plain text rather than HTML tables with -w |
| 9598 | ** -w Capture output into an HTML file then bring up that |
| 9599 | ** file in a web browser |
| 9600 | ** -x Show the output in a spreadsheet. Output is |
| 9601 | ** written to a temp file as CSV then the spreadsheet |
| 9602 | ** is launched when |
| 9603 | ** |
| 9604 | ** DOT-COMMAND: .excel |
| 9605 | ** Shorthand for ".once -x" |
| 9606 | ** |
| 9607 | ** DOT-COMMAND: .www [--plain] |
| 9608 | ** Shorthand for ".once -w" or ".once --plain -w" |
| 9609 | */ |
| 9610 | static int dotCmdOutput(ShellState *p){ |
| 9611 | int nArg = p->dot.nArg; /* Number of arguments */ |
| 9612 | char **azArg = p->dot.azArg; /* Text of the arguments */ |
| 9613 | char *zFile = 0; /* The FILE argument */ |
| 9614 | int i; /* Loop counter */ |
| 9615 | int eMode = 0; /* 0: .outout/.once, 'x'=.excel, 'w'=.www */ |
| 9616 | int bOnce = 0; /* 0: .output, 1: .once, 2: .excel/.www */ |
| 9617 | int bPlain = 0; /* --plain option */ |
| 9618 | int bKeep = 0; /* Keep redirecting */ |
| 9619 | static const char *zBomUtf8 = "\357\273\277"; |
| 9620 | const char *zBom = 0; |
| 9621 | char c = azArg[0][0]; |
| 9622 | int n = strlen30(azArg[0]); |
| 9623 | |
| 9624 | failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); |
| 9625 | if( c=='e' ){ |
| 9626 | eMode = 'x'; |
| 9627 | bOnce = 2; |
| 9628 | }else if( c=='w' ){ |
| 9629 | eMode = 'w'; |
| 9630 | bOnce = 2; |
| 9631 | }else if( n>=2 && cli_strncmp(azArg[0],"once",n)==0 ){ |
| 9632 | bOnce = 1; |
| 9633 | } |
| 9634 | for(i=1; i<nArg; i++){ |
| 9635 | char *z = azArg[i]; |
| 9636 | if( z[0]=='-' ){ |
| 9637 | if( z[1]=='-' ) z++; |
| 9638 | if( cli_strcmp(z,"-bom")==0 ){ |
| 9639 | zBom = zBomUtf8; |
| 9640 | }else if( cli_strcmp(z,"-plain")==0 ){ |
| 9641 | bPlain = 1; |
| 9642 | }else if( c=='o' && sqlite3_strglob("-[ewx]",z)==0 ){ |
| 9643 | if( bKeep || eMode ){ |
| 9644 | dotCmdError(p, i, "incompatible with prior options",0); |
| 9645 | goto dotCmdOutput_error; |
| 9646 | } |
| 9647 | eMode = z[1]; |
| 9648 | }else if( cli_strcmp(z,"-show")==0 ){ |
| 9649 | if( sqlite3_str_length(cli_output_capture)>0 ){ |
| 9650 | sqlite3_fprintf(stdout, "%s", sqlite3_str_value(cli_output_capture)); |
| 9651 | } |
| 9652 | }else if( cli_strcmp(z,"-keep")==0 ){ |
| 9653 | bKeep = 1; |
| 9654 | }else if( optionMatch(z,"error-prefix") ){ |
| 9655 | if( i+1>=nArg ){ |
| 9656 | dotCmdError(p, i, "missing argument", 0); |
| 9657 | return 1; |
| 9658 | } |
| 9659 | free(p->zErrPrefix); |
| 9660 | i++; |
| 9661 | p->zErrPrefix = azArg[i][0]==0 ? 0 : strdup(azArg[i]); |
| 9662 | }else{ |
| 9663 | dotCmdError(p, i, "unknown option", 0); |
| 9664 | sqlite3_free(zFile); |
| 9665 | return 1; |
| 9666 | } |
| 9667 | }else if( zFile==0 && eMode==0 ){ |
| 9668 | if( bKeep ){ |
| 9669 | dotCmdError(p, i, "incompatible with prior options",0); |
| 9670 | goto dotCmdOutput_error; |
| 9671 | } |
| 9672 | if( cli_strcmp(z, "memory")==0 && bOnce ){ |
| 9673 | dotCmdError(p, 0, "cannot redirect to \"memory\"", 0); |
| 9674 | goto dotCmdOutput_error; |
| 9675 | } |
| 9676 | if( cli_strcmp(z, "off")==0 ){ |
| 9677 | #ifdef _WIN32 |
| 9678 | zFile = sqlite3_mprintf("nul"); |
| 9679 | #else |
| 9680 | zFile = sqlite3_mprintf("/dev/null"); |
| 9681 | #endif |
| 9682 | }else{ |
| 9683 | zFile = sqlite3_mprintf("%s", z); |
| 9684 | } |
| 9685 | if( zFile && zFile[0]=='|' ){ |
| 9686 | while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]); |
| 9687 | break; |
| 9688 | } |
| 9689 | }else{ |
| 9690 | dotCmdError(p, i, "surplus argument", 0); |
| 9691 | sqlite3_free(zFile); |
| 9692 | return 1; |
| 9693 | } |
| 9694 | } |
| 9695 | if( zFile==0 && !bKeep ){ |
| 9696 | zFile = sqlite3_mprintf("stdout"); |
| 9697 | shell_check_oom(zFile); |
| 9698 | } |
| 9699 | if( bOnce ){ |
| 9700 | p->nPopOutput = 2; |
| 9701 | }else{ |
| 9702 | p->nPopOutput = 0; |
| 9703 | } |
| 9704 | if( !bKeep ) output_reset(p); |
| 9705 | #ifndef SQLITE_NOHAVE_SYSTEM |
| 9706 | if( eMode=='e' || eMode=='x' || eMode=='w' ){ |
| 9707 | p->doXdgOpen = 1; |
| 9708 | modePush(p); |
| 9709 | if( eMode=='x' ){ |
| 9710 | /* spreadsheet mode. Output as CSV. */ |
| 9711 | newTempFile(p, "csv"); |
| 9712 | p->mode.mFlags &= ~MFLG_ECHO; |
| 9713 | p->mode.eMode = MODE_Csv; |
| 9714 | modeSetStr(&p->mode.spec.zColumnSep, ","); |
| 9715 | modeSetStr(&p->mode.spec.zRowSep, "\r\n"); |
| 9716 | #ifdef _WIN32 |
| 9717 | zBom = zBomUtf8; /* Always include the BOM on Windows, as Excel does |
| 9718 | ** not work without it. */ |
| 9719 | #endif |
| 9720 | }else if( eMode=='w' ){ |
| 9721 | /* web-browser mode. */ |
| 9722 | newTempFile(p, "html"); |
| 9723 | if( !bPlain ) p->mode.eMode = MODE_Www; |
| 9724 | }else{ |
| 9725 | /* text editor mode */ |
| 9726 | newTempFile(p, "txt"); |
| 9727 | } |
| 9728 | sqlite3_free(zFile); |
| 9729 | zFile = sqlite3_mprintf("%s", p->zTempFile); |
| 9730 | } |
| 9731 | #endif /* SQLITE_NOHAVE_SYSTEM */ |
| 9732 | if( !bKeep ) shell_check_oom(zFile); |
| 9733 | if( bKeep ){ |
| 9734 | /* no-op */ |
| 9735 | }else if( cli_strcmp(zFile,"memory")==0 ){ |
| 9736 | if( cli_output_capture ){ |
| 9737 | sqlite3_str_free(cli_output_capture); |
| 9738 | } |
| 9739 | cli_output_capture = sqlite3_str_new(0); |
| 9740 | }else if( zFile[0]=='|' ){ |
| 9741 | #ifdef SQLITE_OMIT_POPEN |
| 9742 | eputz("Error: pipes are not supported in this OS\n"); |
| 9743 | output_redir(p, stdout); |
| 9744 | goto dotCmdOutput_error; |
| 9745 | #else |
| 9746 | FILE *pfPipe = sqlite3_popen(zFile + 1, "w"); |
| 9747 | if( pfPipe==0 ){ |
| 9748 | assert( stderr!=NULL ); |
| 9749 | cli_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1); |
| 9750 | goto dotCmdOutput_error; |
| 9751 | }else{ |
| 9752 | output_redir(p, pfPipe); |
| 9753 | if( zBom ) cli_puts(zBom, pfPipe); |
| 9754 | sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); |
| 9755 | } |
| 9756 | #endif |
| 9757 | }else{ |
| 9758 | FILE *pfFile = output_file_open(p, zFile); |
| 9759 | if( pfFile==0 ){ |
| 9760 | if( cli_strcmp(zFile,"off")!=0 ){ |
| 9761 | assert( stderr!=NULL ); |
| 9762 | cli_printf(stderr,"Error: cannot write to \"%s\"\n", zFile); |
| 9763 | } |
| 9764 | goto dotCmdOutput_error; |
| 9765 | } else { |
| 9766 | output_redir(p, pfFile); |
| 9767 | if( zBom ) cli_puts(zBom, pfFile); |
| 9768 | if( bPlain && eMode=='w' ){ |
| 9769 | cli_puts( |
| 9770 | "<!DOCTYPE html>\n<BODY>\n<PLAINTEXT>\n", |
| 9771 | pfFile |
| 9772 | ); |
| 9773 | } |
| 9774 | sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); |
| 9775 | } |
| 9776 | } |
| 9777 | sqlite3_free(zFile); |
| 9778 | return 0; |
| 9779 | |
| 9780 | dotCmdOutput_error: |
| 9781 | sqlite3_free(zFile); |
| 9782 | return 1; |
| 9783 | } |
| 9784 | |
| 9785 | /* |
| 9786 | ** Return true if the argument is <<MARK for some arbitrary mark |
| 9787 | */ |
| 9788 | static int isHereDoc(const char *z){ |
| 9789 | return z[0]=='<' && z[1]=='<' && z[2]!=0; |
| 9790 | } |
| 9791 | |
| 9792 | /* |
| 9793 | ** Capture lines of input text up until a line that matches zTerminator. |
| 9794 | ** Return a memory buffer (allocated using sqlite3_malloc64()) that |
| 9795 | ** contains the complete text, without the terminator. |
| 9796 | */ |
| 9797 | static char *captureHereDoc(ShellState *p, const char *zTerminator){ |
| 9798 | int nTerminator = strlen30(zTerminator); |
| 9799 | sqlite3_str *pHeredoc = sqlite3_str_new(p->db); |
| 9800 | char zLine[2000]; |
| 9801 | while( shell_fgets(p, zLine,sizeof(zLine),p->in) ){ |
| 9802 | if( strchr(zLine,'\n') ) p->lineno++; |
| 9803 | if( cli_strncmp(zTerminator,zLine,nTerminator)==0 ) break; |
| 9804 | sqlite3_str_appendall(pHeredoc, zLine); |
| 9805 | } |
| 9806 | return sqlite3_str_finish(pHeredoc); |
| 9807 | } |
| 9808 | |
| 9809 | /* |
| 9810 | ** Return a pointer to the first non-whitespace character in the input |
| 9811 | ** string, or a pointer to the string terminator if the input contains |
| 9812 | ** no non-whitespace characters. |
| 9813 | ** |
| 9814 | ** The number of bytes that follow, excluding trailing whitespace, is |
| 9815 | ** written into *pN if pN!=0. |
| 9816 | */ |
| 9817 | static char *trimSpace(char *zIn, int *pN){ |
| 9818 | while( IsSpace(zIn[0]) ){ zIn++; } |
| 9819 | if( pN ){ |
| 9820 | size_t n = strlen(zIn); |
| 9821 | while( n>0 && IsSpace(zIn[n-1]) ){ n--; } |
| 9822 | *pN = n; |
| 9823 | } |
| 9824 | return zIn; |
| 9825 | } |
| 9826 | |
| 9827 | /* |
| 9828 | ** DOT-COMMAND: .check |
| 9829 | ** USAGE: .check [OPTIONS] PATTERN |
| 9830 | ** |
| 9831 | ** Verify the output of all commands since the most recent .testcase |
| 9832 | ** command. Both stdout and stderr are captured and compared, so error |
| 9833 | ** messages are part of the text being compared, however output from |
| 9834 | ** the ".echo on" dot-command is not captured and is not part of the test |
| 9835 | ** result. |
| 9836 | ** |
| 9837 | ** After checking the result, all captured output is discarded and |
| 9838 | ** output starts going back to the console, unless --keep is used. |
| 9839 | ** |
| 9840 | ** If PATTERN is "<<ENDMARK" (for any ENDMARK) then the actual pattern is |
| 9841 | ** taken from subsequent lines of text up to the first line that begins |
| 9842 | ** with ENDMARK. |
| 9843 | ** |
| 9844 | ** The default comparison algorithm is to ignore all leading and trailing |
| 9845 | ** whitespace and compare the pattern against the result byte-for-byte except |
| 9846 | ** that whitespace characters are equal to other whitespace characters. |
| 9847 | ** Thus if the pattern contains a space character and the result contains |
| 9848 | ** a tab in the same spot, they would still compare equal. The number of |
| 9849 | ** whitespace characters must be the same in the pattern and the result. |
| 9850 | ** |
| 9851 | ** The --glob, --notglob, and --allglob comparisons are extended so that |
| 9852 | ** "#" in the pattern matches a sequence of one or more digits with an |
| 9853 | ** optional leading "+" or "-", and a space in the pattern matches a run |
| 9854 | ** of one or more whitespace characters. |
| 9855 | ** |
| 9856 | ** Options: |
| 9857 | ** --allglob PATTERN is a GLOB matching the entire test output except |
| 9858 | ** leading and trailing whitespace. |
| 9859 | ** --any PATTERN is any substring within the test output. |
| 9860 | ** --exact PATTERN matches the entire test output, byte for byte. |
| 9861 | ** --glob PATTERN is a GLOB matching any substring of the test |
| 9862 | ** output. Leading and trailing whitespace on the PATTERN |
| 9863 | ** is ignored. |
| 9864 | ** --keep Do not reset the test output. One or more .check commands |
| 9865 | ** will follow and do additional tests. |
| 9866 | ** --not Pass if the test output does *not* match PATTERN. |
| 9867 | ** --notglob Shorthand for "--not --glob". |
| 9868 | ** --nowhere Shorthand for "--not --any". |
| 9869 | ** --regexp PATTERN is a regular expression matching any substring |
| 9870 | ** of the test output. |
| 9871 | ** --show Write test output to the screen, for debugging. |
| 9872 | */ |
| 9873 | static int dotCmdCheck(ShellState *p){ |
| 9874 | int nArg = p->dot.nArg; /* Number of arguments */ |
| 9875 | char **azArg = p->dot.azArg; /* Text of the arguments */ |
| 9876 | int i; /* Loop counter */ |
| 9877 | int k; /* Result of pickStr() */ |
| 9878 | char *zTest; /* Textcase result */ |
| 9879 | int bKeep = 0; /* --keep option */ |
| 9880 | char *zCheck = 0; /* PATTERN argument */ |
| 9881 | char *zPattern = 0; /* Actual test pattern */ |
| 9882 | char *zToFree = 0; /* allocated text to free */ |
| 9883 | int eCheck = 0; /* 0: default. Else 1+index of option */ |
| 9884 | int isOk = 0; /* True if results are OK */ |
| 9885 | int bNot = 0; /* Invert the sense of the test */ |
| 9886 | int iPat = -1; /* Location of the pattern */ |
| 9887 | sqlite3_int64 iStart = p->lineno; /* Line number of .check statement */ |
| 9888 | |
| 9889 | if( p->mIf!=0 ){ |
| 9890 | /* Unlike most other dot-commands, the .check command runs even if |
| 9891 | ** inside the false branch of a .if. It needs to do this so that it |
| 9892 | ** can capture any "<<MARKER" heredoc text specified. */ |
| 9893 | if( nArg>0 && isHereDoc(azArg[nArg-1]) ){ |
| 9894 | sqlite3_free(captureHereDoc(p, azArg[nArg-1]+2)); |
| 9895 | } |
| 9896 | return 0; |
| 9897 | } |
| 9898 | if( p->zTestcase[0]==0 ){ |
| 9899 | dotCmdError(p, 0, "no .testcase is active", 0); |
| 9900 | return 1; |
| 9901 | } |
| 9902 | for(i=1; i<nArg; i++){ |
| 9903 | char *z = azArg[i]; |
| 9904 | if( z[0]=='-' && z[1]=='-' && z[2]!=0 ) z++; |
| 9905 | if( cli_strcmp(z,"-keep")==0 ){ |
| 9906 | bKeep = 1; |
| 9907 | }else if( cli_strcmp(z,"-show")==0 ){ |
| 9908 | if( sqlite3_str_length(cli_output_capture)>0 ){ |
| 9909 | sqlite3_fprintf(stdout, "%s", sqlite3_str_value(cli_output_capture)); |
| 9910 | } |
| 9911 | bKeep = 1; |
| 9912 | }else if( z[0]=='-' |
| 9913 | && (k = pickStr(&z[1],0, |
| 9914 | /* 0 1 2 3 4 5 6 7 */ |
| 9915 | "glob","exact","regexp","any","nowhere","allglob","notglob","not",""))>=0 |
| 9916 | ){ |
| 9917 | if( k==7 ){ |
| 9918 | bNot = !bNot; |
| 9919 | }else if( eCheck==0 || eCheck==k+1 ){ |
| 9920 | eCheck = k+1; |
| 9921 | }else{ |
| 9922 | output_reset(p); |
| 9923 | dotCmdError(p, i, "incompatible with prior options",0); |
| 9924 | return 1; |
| 9925 | } |
| 9926 | }else if( zCheck ){ |
| 9927 | output_reset(p); |
| 9928 | dotCmdError(p, i, "unknown option", 0); |
| 9929 | return 1; |
| 9930 | }else{ |
| 9931 | zCheck = azArg[i]; |
| 9932 | iPat = i; |
| 9933 | } |
| 9934 | } |
| 9935 | if( zCheck==0 ){ |
| 9936 | zCheck = ""; /* No pattern string defaults to mean no output */ |
| 9937 | } |
| 9938 | if( sqlite3_str_length(cli_output_capture) ){ |
| 9939 | zTest = sqlite3_str_value(cli_output_capture); |
| 9940 | shell_check_oom(zTest); |
| 9941 | }else{ |
| 9942 | zTest = ""; |
| 9943 | } |
| 9944 | p->nTestRun++; |
| 9945 | if( isHereDoc(zCheck) ){ |
| 9946 | zPattern = captureHereDoc(p, zCheck+2); |
| 9947 | if( zPattern==0 ){ |
| 9948 | zPattern = sqlite3_mprintf(""); |
| 9949 | } |
| 9950 | zToFree = zPattern; |
| 9951 | }else{ |
| 9952 | zPattern = zCheck; |
| 9953 | zToFree = 0; |
| 9954 | } |
| 9955 | shell_check_oom(zPattern); |
| 9956 | switch( eCheck ){ |
| 9957 | case 6: /* --allglob */ |
| 9958 | case 7: /* --notglob */ |
| 9959 | case 1: { /* --glob */ |
| 9960 | int nPat = 0; |
| 9961 | char *zGlob; |
| 9962 | zPattern = trimSpace(zPattern, &nPat); |
| 9963 | zTest = trimSpace(zTest, 0); |
| 9964 | if( eCheck==6 ){ |
| 9965 | zGlob = sqlite3_mprintf("%.*s", nPat, zPattern); |
| 9966 | }else{ |
| 9967 | zGlob = sqlite3_mprintf("*%.*s*", nPat, zPattern); |
| 9968 | } |
| 9969 | shell_check_oom(zGlob); |
| 9970 | isOk = testcase_glob(zGlob, zTest)!=0; |
| 9971 | if( eCheck==7 ) isOk = !isOk; |
| 9972 | sqlite3_free(zGlob); |
| 9973 | break; |
| 9974 | } |
| 9975 | case 2: { /* --exact */ |
| 9976 | isOk = cli_strcmp(zTest,zPattern)==0; |
| 9977 | break; |
| 9978 | } |
| 9979 | case 3: { /* --regexp */ |
| 9980 | ReCompiled *pRe = 0; |
| 9981 | const char *zErr = re_compile(&pRe, zPattern, 1000, 0); |
| 9982 | if( zErr ){ |
| 9983 | re_free(pRe); |
| 9984 | sqlite3_free(zToFree); |
| 9985 | output_reset(p); |
| 9986 | p->nTestErr++; |
| 9987 | dotCmdError(p, iPat, "bad regexp", "bad regular expression: %s", zErr); |
| 9988 | return 1; |
| 9989 | } |
| 9990 | shell_check_oom(pRe); |
| 9991 | isOk = re_match(pRe, (const unsigned char*)zTest, -1); |
| 9992 | re_free(pRe); |
| 9993 | break; |
| 9994 | } |
| 9995 | case 4: { /* --any */ |
| 9996 | isOk = strstr(zTest,zPattern)!=0; |
| 9997 | break; |
| 9998 | } |
| 9999 | case 5: { /* --nowhere */ |
| 10000 | isOk = strstr(zTest,zPattern)==0; |
| 10001 | break; |
| 10002 | } |
| 10003 | default: { /* default matching rule */ |
| 10004 | /* Ignore leading and trailing whitespace on both the pattern and the |
| 10005 | ** test output. Each interior whitespace character will compare equal |
| 10006 | ** to exactly one other whitespace character. */ |
| 10007 | int nPat = 0; |
| 10008 | int nTest = 0; |
| 10009 | zPattern = trimSpace(zPattern, &nPat); |
| 10010 | zTest = trimSpace(zTest, &nTest); |
| 10011 | if( nPat!=nTest ){ |
| 10012 | isOk = 0; |
| 10013 | }else if( memcmp(zPattern, zTest, nPat)==0 ){ |
| 10014 | isOk = 1; |
| 10015 | }else{ |
| 10016 | int ii; |
| 10017 | isOk = 1; |
| 10018 | for(ii=0; ii<nPat; ii++){ |
| 10019 | if( zPattern[ii]!=zTest[ii] |
| 10020 | && !(IsSpace(zPattern[ii]) && IsSpace(zTest[ii])) |
| 10021 | ){ |
| 10022 | isOk = 0; |
| 10023 | break; |
| 10024 | } |
| 10025 | } |
| 10026 | } |
| 10027 | break; |
| 10028 | } |
| 10029 | } |
| 10030 | if( bNot ) isOk = !isOk; |
| 10031 | if( !isOk ){ |
| 10032 | static const char zDL[] = "\342\225\255\342\224\200"; |
| 10033 | static const char zDR[] = "\342\224\200\342\225\256"; |
| 10034 | static const char zUL[] = "\342\225\260\342\224\200"; |
| 10035 | static const char zUR[] = "\342\224\200\342\225\257"; |
| 10036 | static const char zLine[] = "\342\224\200\342\224\200\342\224\200" |
| 10037 | "\342\224\200\342\224\200\342\224\200" |
| 10038 | "\342\224\200\342\224\200\342\224\200" |
| 10039 | "\342\224\200\342\224\200\342\224\200" |
| 10040 | "\342\224\200\342\224\200"; |
| 10041 | sqlite3_fprintf(stderr, |
| 10042 | "%s:%lld: .check failed for testcase %s\n", |
| 10043 | p->zInFile, iStart, p->zTestcase); |
| 10044 | p->nTestErr++; |
| 10045 | if( sqlite3_strglob("*\n", zPattern)==0 ){ |
| 10046 | sqlite3_fprintf(stderr, "%s%s Expected %s%s\n%s%s%s Expected %s%s\n", |
| 10047 | zDL, zLine+9, zLine+9, zDR, |
| 10048 | zPattern, |
| 10049 | zUL, zLine+9, zLine+9, zUR); |
| 10050 | }else{ |
| 10051 | sqlite3_fprintf(stderr, "Expected: [%s]\n", zPattern); |
| 10052 | } |
| 10053 | if( sqlite3_strglob("*\n", zTest)==0 ){ |
| 10054 | sqlite3_fprintf(stderr, "%s%s Got %s%s\n%s%s%s Got %s%s\n", |
| 10055 | zDL, zLine+3, zLine, zDR, |
| 10056 | zTest, |
| 10057 | zUL, zLine+3, zLine, zUR); |
| 10058 | }else{ |
| 10059 | sqlite3_fprintf(stderr, "Got: [%s]\n", zTest); |
| 10060 | } |
| 10061 | } |
| 10062 | sqlite3_free(zToFree); |
| 10063 | if( !bKeep ){ |
| 10064 | output_reset(p); |
| 10065 | p->zTestcase[0] = 0; |
| 10066 | } |
| 10067 | return 0; |
| 10068 | } |
| 10069 | |
| 10070 | /* |
| 10071 | ** DOT-COMMAND: .stats |
| 10072 | ** USAGE: .stats [OPTIONS] ... |
| 10073 | ** |
| 10074 | ** Show status information about the database and database connection. |
| 10075 | ** The stats setting is persistent, unless the --once option is used. |
| 10076 | ** Options are cumulative and are processed from left to right. |
| 10077 | ** If no options are given, that is the same as ".stats all --once". |
| 10078 | ** |
| 10079 | ** Options: |
| 10080 | ** all Show all available stats. |
| 10081 | ** io Show I/O stats (Linux only). |
| 10082 | ** mem Show basic memory usage. |
| 10083 | ** off Show nothing. Turn off stat display. |
| 10084 | ** on Shorthand for "stmt xmem". |
| 10085 | ** --once Show the stats once. Do not change the default stats display. |
| 10086 | ** reset Reset "max" values after next display of each that value. |
| 10087 | ** stmt Show information about the last SQL statement. |
| 10088 | ** vmstep Show the number of virtual machine steps taken. |
| 10089 | ** xmem Show detailed memory status information |
| 10090 | ** xstmt Show details about each SQL statement |
| 10091 | */ |
| 10092 | static int dotCmdStats(ShellState *p){ |
| 10093 | int nArg = p->dot.nArg; /* Number of arguments */ |
| 10094 | char **azArg = p->dot.azArg; /* Text of the arguments */ |
| 10095 | int ii; /* Loop counter */ |
| 10096 | int bOnce = 0; /* --once option seen */ |
| 10097 | u8 mNew = 0; /* New status setting */ |
| 10098 | u8 savedStats = p->mStats; /* Current stats setting */ |
| 10099 | |
| 10100 | if( nArg==1 ){ |
| 10101 | p->mStats = CLISTAT_ALL; |
| 10102 | display_stats(p->db, p); |
| 10103 | p->mStats = savedStats; |
| 10104 | return 0; |
| 10105 | } |
| 10106 | for(ii=1; ii<nArg; ii++){ |
| 10107 | const char *z = azArg[ii]; |
| 10108 | if( z[0]=='-' ){ |
| 10109 | z++; |
| 10110 | if( z[0]=='-' && z[1]!=0 ) z++; |
| 10111 | } |
| 10112 | if( cli_strcmp(z,"stmt")==0 ){ |
| 10113 | mNew |= CLISTAT_STMT|CLISTAT_VMSTEP; |
| 10114 | }else if( cli_strcmp(z,"xstmt")==0 ){ |
| 10115 | mNew |= CLISTAT_STMT|CLISTAT_XSTMT|CLISTAT_VMSTEP; |
| 10116 | }else if( cli_strcmp(z,"vmstep")==0 ){ |
| 10117 | mNew |= CLISTAT_VMSTEP; |
| 10118 | }else if( cli_strcmp(z,"mem")==0 ){ |
| 10119 | mNew |= CLISTAT_MEM; |
| 10120 | }else if( cli_strcmp(z,"xmem")==0 ){ |
| 10121 | mNew |= CLISTAT_XMEM|CLISTAT_MEM; |
| 10122 | }else if( cli_strcmp(z,"io")==0 ){ |
| 10123 | mNew |= CLISTAT_IO; |
| 10124 | }else if( cli_strcmp(z,"all")==0 ){ |
| 10125 | mNew |= CLISTAT_ALL; |
| 10126 | #ifndef __linux__ |
| 10127 | dotCmdError(p, ii, "available only on Linux", 0); |
| 10128 | return 1; |
| 10129 | #endif |
| 10130 | #ifdef SQLITE_ENABLE_ZIPVFS_VTAB |
| 10131 | }else if( cli_strcmp(z,"zipvfs")==0 ){ |
| 10132 | mNew |= CLISTAT_ZIPVFS; |
| 10133 | #endif |
| 10134 | }else if( cli_strcmp(z,"reset")==0 ){ |
| 10135 | mNew |= CLISTAT_RESET; |
| 10136 | }else if( cli_strcmp(z,"once")==0 ){ |
| 10137 | bOnce = 1; |
| 10138 | }else if( IsDigit(z[0]) ){ |
| 10139 | if( booleanValue(z) ){ |
| 10140 | mNew |= CLISTAT_ON; |
| 10141 | }else{ |
| 10142 | mNew = 0; |
| 10143 | } |
| 10144 | }else if( pickStr(z, 0, "on", "yes", "ON", "YES", "")>=0 ){ |
| 10145 | mNew |= CLISTAT_ON; |
| 10146 | }else if( pickStr(z, 0, "off", "no", "OFF", "NO", "")>=0 ){ |
| 10147 | mNew = 0; |
| 10148 | }else{ |
| 10149 | dotCmdError(p, ii, "unknown argument", 0); |
| 10150 | return 1; |
| 10151 | } |
| 10152 | } |
| 10153 | p->mStats = mNew; |
| 10154 | if( bOnce ){ |
| 10155 | display_stats(p->db, p); |
| 10156 | p->mStats = savedStats; |
| 10157 | } |
| 10158 | return 0; |
| 10159 | } |
| 10160 | |
| 10161 | /* |
| 10162 | ** DOT-COMMAND: .testcase |
| 10163 | ** USAGE: .testcase [OPTIONS] NAME |
| 10164 | ** |
| 10165 | ** Start a new test case identified by NAME. All output |
| 10166 | ** through the next ".check" command is captured for comparison. See the |
| 10167 | ** ".check" command for additional informatioon. |
| 10168 | ** |
| 10169 | ** Options: |
| 10170 | ** --error-prefix TEXT Change error message prefix text to TEXT |
| 10171 | */ |
| 10172 | static int dotCmdTestcase(ShellState *p){ |
| 10173 | int nArg = p->dot.nArg; /* Number of arguments */ |
| 10174 | char **azArg = p->dot.azArg; /* Text of the arguments */ |
| 10175 | int i; /* Loop counter */ |
| 10176 | const char *zName = 0; /* Testcase name */ |
| 10177 | |
| 10178 | for(i=1; i<nArg; i++){ |
| 10179 | char *z = azArg[i]; |
| 10180 | if( z[0]=='-' && z[1]=='-' && z[2]!=0 ) z++; |
| 10181 | if( optionMatch(z,"error-prefix") ){ |
| 10182 | if( i+1>=nArg ){ |
| 10183 | dotCmdError(p, i, "missing argument", 0); |
| 10184 | return 1; |
| 10185 | } |
| 10186 | free(p->zErrPrefix); |
| 10187 | i++; |
| 10188 | p->zErrPrefix = azArg[i][0]==0 ? 0 : strdup(azArg[i]); |
| 10189 | }else if( zName ){ |
| 10190 | dotCmdError(p, i, "unknown option", 0); |
| 10191 | return 1; |
| 10192 | }else{ |
| 10193 | zName = azArg[i]; |
| 10194 | } |
| 10195 | } |
| 10196 | output_reset(p); |
| 10197 | if( cli_output_capture ){ |
| 10198 | sqlite3_str_free(cli_output_capture); |
| 10199 | } |
| 10200 | cli_output_capture = sqlite3_str_new(0); |
| 10201 | if( zName ){ |
| 10202 | sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", zName); |
| 10203 | }else{ |
| 10204 | sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s:%lld", |
| 10205 | p->zInFile, p->lineno); |
| 10206 | } |
| 10207 | return 0; |
| 10208 | } |
| 10209 | |
| 10210 | /* |
| 10211 | ** Evaluate the text of zExpr as an SQL expression. Return true if the |
| 10212 | ** expression is true. Return false if the expression evaluates to |
| 10213 | ** false or NULL. Return false if there is any kind of error, either |
| 10214 | ** a run-time or a compile-time error. |
| 10215 | */ |
| 10216 | static int sqlExprIsTrue(ShellState *p, const char *zExpr){ |
| 10217 | char *zSql = sqlite3_mprintf("SELECT %s", zExpr); |
| 10218 | sqlite3_stmt *pStmt; |
| 10219 | int rc; |
| 10220 | |
| 10221 | rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); |
| 10222 | sqlite3_free(zSql); |
| 10223 | if( rc ){ |
| 10224 | rc = 0; |
| 10225 | }else{ |
| 10226 | bind_prepared_stmt(p, pStmt); |
| 10227 | rc = sqlite3_step(pStmt); |
| 10228 | if( rc==SQLITE_ROW ){ |
| 10229 | rc = sqlite3_column_double(pStmt,0)!=0.0; |
| 10230 | }else{ |
| 10231 | rc = 0; |
| 10232 | } |
| 10233 | } |
| 10234 | sqlite3_finalize(pStmt); |
| 10235 | return rc; |
| 10236 | } |
| 10237 | |
| 10238 | /* |
| 10239 | ** DOT-COMMAND: .if |
| 10240 | ** USAGE: .if SQL-EXPRESSION |
| 10241 | ** |
| 10242 | ** The argument can be any SQL expression, including a subquery in |
| 10243 | ** parentheses. If the expression evalutes to true (if it is non-zero |
| 10244 | ** when converted into an number) then subsequent statements are |
| 10245 | ** evaluated. If SQL-EXPRESSION evalutes to false or NULL or raises |
| 10246 | ** an error, then subsequent statements are skipped, up until the first |
| 10247 | ** matching .elseif, .else, or .endif. |
| 10248 | ** |
| 10249 | ** Maximum nested depth is limited. An error is raised if .if statements |
| 10250 | ** are nested to deep. |
| 10251 | ** |
| 10252 | ** Every .if must be followed by a matching .endif, or an error is raised. |
| 10253 | */ |
| 10254 | static int dotCmdIf(ShellState *p){ |
| 10255 | int jj; |
| 10256 | if( p->nIfLevel==MX_IF ){ |
| 10257 | dotCmdError(p, 0, 0, ".if nested too deep"); |
| 10258 | return 1; |
| 10259 | } |
| 10260 | jj = p->nIfLevel++; |
| 10261 | open_db(p, 0); |
| 10262 | if( sqlExprIsTrue(p, p->dot.zOrig+3) ){ |
| 10263 | p->mIfHasBeenTrue |= 1<<jj; |
| 10264 | }else{ |
| 10265 | p->mIf |= 1<<jj; |
| 10266 | } |
| 10267 | p->lnIf[jj] = p->lineno; |
| 10268 | return 0; |
| 10269 | } |
| 10270 | |
| 10271 | /* |
| 10272 | ** DOT-COMMAND: .elseif |
| 10273 | ** USAGE: .elseif SQL-EXPRESSION |
| 10274 | ** |
| 10275 | ** An "else-if". The prior .if is finished and a new condition is applied. |
| 10276 | */ |
| 10277 | static int dotCmdElseif(ShellState *p){ |
| 10278 | int jj = p->nIfLevel-1; |
| 10279 | if( jj<p->nIfAtStart ){ |
| 10280 | dotCmdError(p, 0, 0, ".elseif with no .if"); |
| 10281 | return 1; |
| 10282 | } |
| 10283 | if( (p->mElse & (1<<jj))!=0 ){ |
| 10284 | dotCmdError(p, 0, 0, ".elseif follows a .else on line %lld", p->lnElse[jj]); |
| 10285 | p->mIf |= 1<<jj; |
| 10286 | return 1; |
| 10287 | } |
| 10288 | if( p->mIfHasBeenTrue & (1<<jj) ){ |
| 10289 | p->mIf |= 1<<jj; |
| 10290 | }else if( sqlExprIsTrue(p, p->dot.zOrig+7) ){ |
| 10291 | p->mIf &= ~(1<<jj); |
| 10292 | p->mIfHasBeenTrue |= (1<<jj); |
| 10293 | }else{ |
| 10294 | p->mIf |= 1<<jj; |
| 10295 | } |
| 10296 | return 0; |
| 10297 | } |
| 10298 | |
| 10299 | /* |
| 10300 | ** DOT-COMMAND: .else |
| 10301 | ** USAGE: .else |
| 10302 | ** |
| 10303 | ** Invert the sense of the inner-most .if. Start processing if the prior |
| 10304 | ** .if was false. Stop processing if the prior .if was true. |
| 10305 | */ |
| 10306 | static int dotCmdElse(ShellState *p){ |
| 10307 | int ii; |
| 10308 | if( p->nIfLevel<=p->nIfAtStart ){ |
| 10309 | dotCmdError(p, 0, 0, ".else without a .if"); |
| 10310 | return 1; |
| 10311 | } |
| 10312 | ii = p->nIfLevel-1; |
| 10313 | if( (p->mElse & (1<<ii))!=0 ){ |
| 10314 | dotCmdError(p, 0, 0, "already saw a .else at line %lld", p->lnElse[ii]); |
| 10315 | return 1; |
| 10316 | } |
| 10317 | if( p->mIfHasBeenTrue & (1<<ii) ){ |
| 10318 | p->mIf |= (1<<ii); |
| 10319 | }else{ |
| 10320 | p->mIf &= ~(1<<ii); |
| 10321 | } |
| 10322 | p->mElse |= (1<<ii); |
| 10323 | p->lnElse[ii] = p->lineno; |
| 10324 | return 0; |
| 10325 | } |
| 10326 | |
| 10327 | /* |
| 10328 | ** DOT-COMMAND: .endif |
| 10329 | ** USAGE: .endif |
| 10330 | ** |
| 10331 | ** Terminate an .if statement. |
| 10332 | */ |
| 10333 | static int dotCmdEndif(ShellState *p){ |
| 10334 | if( p->nIfLevel<=p->nIfAtStart ){ |
| 10335 | dotCmdError(p, 0, 0, ".endif without a .if"); |
| 10336 | return 1; |
| 10337 | } |
| 10338 | p->nIfLevel--; |
| 10339 | p->mIf &= ~(1<<p->nIfLevel); |
| 10340 | p->mElse &= ~(1<<p->nIfLevel); |
| 10341 | p->mIfHasBeenTrue &= ~(1<<p->nIfLevel); |
| 10342 | return 0; |
| 10343 | } |
| 10344 | |
| 10345 | /* |
| 10346 | ** DOT-COMMAND: .eqp |
| 10347 | ** USAGE: .eqp EQPMODE [>OUTPUTFILE] |
| 10348 | ** |
| 10349 | ** The .eqp command enables or disables the automatic display of EXPLAIN |
| 10350 | ** output for each SQL statement evaluated. The required EQPMODE argument |
| 10351 | ** may be one of the following: |
| 10352 | ** |
| 10353 | ** full Show both EXPLAIN QUERY PLAN and EXPLAIN output. |
| 10354 | ** |
| 10355 | ** off Disable all explain output. |
| 10356 | ** |
| 10357 | ** on Show EXPLAIN QUERY PLAN output only. |
| 10358 | ** |
| 10359 | ** trace Like "full" but also enable VDBE tracing using |
| 10360 | ** PRAGMA vdbe_trace=ON. This option only works if the |
| 10361 | ** CLI is compiled with -DSQLITE_DEBUG. The trace output |
| 10362 | ** always appears on stdout and is not redirected to a file. |
| 10363 | ** |
| 10364 | ** trigger Like "full" but also show EXPLAIN output for trigger |
| 10365 | ** subprograms. |
| 10366 | ** |
| 10367 | ** The EQPMODE maybe be optionally followed by a filename. If a file is |
| 10368 | ** specified, with or without a single leading ">", then the file is |
| 10369 | ** deleted and all subsequent explain output is appended to that file. |
| 10370 | ** If the filename begins with ">>" then the content of the file is retained |
| 10371 | ** and all output is appended. If not redirection argument is provided, |
| 10372 | ** output redirection is cancelled. The ability to redirect is not available |
| 10373 | ** for --safe mode. |
| 10374 | */ |
| 10375 | static int dotCmdEqp(ShellState *p){ |
| 10376 | int nArg = p->dot.nArg; /* Number of arguments */ |
| 10377 | char **azArg = p->dot.azArg; /* Argument list */ |
| 10378 | if( nArg==2 || nArg==3 ){ |
| 10379 | int isTrace = 0; |
| 10380 | if( p->db ) sqlite3_db_config(p->db, SQLITE_DBCONFIG_VDBE_TRACE, 0, |
| 10381 | (int*)0); |
| 10382 | if( cli_strcmp(azArg[1],"full")==0 ){ |
| 10383 | p->mode.autoEQP = AUTOEQP_full; |
| 10384 | }else if( cli_strcmp(azArg[1],"trigger")==0 ){ |
| 10385 | p->mode.autoEQP = AUTOEQP_trigger; |
| 10386 | }else if( cli_strcmp(azArg[1],"trace")==0 ){ |
| 10387 | #ifdef SQLITE_DEBUG |
| 10388 | p->mode.autoEQP = AUTOEQP_full; |
| 10389 | if( p->db==0 ){ |
| 10390 | open_db(p, 0); |
| 10391 | sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1",0,0,0); |
| 10392 | } |
| 10393 | sqlite3_db_config(p->db, SQLITE_DBCONFIG_VDBE_TRACE, 1, (int*)0); |
| 10394 | isTrace = 1; |
| 10395 | #else |
| 10396 | eputz("\".eqp trace\" is only available in debug builds\n"); |
| 10397 | return 1; |
| 10398 | #endif |
| 10399 | }else{ |
| 10400 | p->mode.autoEQP = (u8)booleanValue(azArg[1]); |
| 10401 | } |
| 10402 | free(p->zEqpFile); |
| 10403 | if( nArg==3 ){ |
| 10404 | const char *zOut = azArg[2]; |
| 10405 | int bAppend = 0; |
| 10406 | failIfSafeMode(p, "cannot redirect .eqp output in safe mode"); |
| 10407 | if( zOut[0]=='>' ) zOut++; |
| 10408 | if( zOut[0]=='>' ){ bAppend = 1; zOut++; } |
| 10409 | p->zEqpFile = strdup(zOut); |
| 10410 | if( !bAppend ){ |
| 10411 | (void)shellDeleteFile(p->zEqpFile, 0); |
| 10412 | } |
| 10413 | if( isTrace ){ |
| 10414 | cli_printf(p->out, "WARNING: trace output will not be redirected\n"); |
| 10415 | } |
| 10416 | }else{ |
| 10417 | p->zEqpFile = 0; |
| 10418 | } |
| 10419 | }else{ |
| 10420 | eputz("Usage: .eqp off|on|trace|trigger|full [OUTPUTFILE]\n"); |
| 10421 | return 1; |
| 10422 | } |
| 10423 | return 0; |
| 10424 | } |
| 10425 | |
| 10426 | |
| 10427 | /* |
| 10428 | ** DOT-COMMAND: .safe |
| 10429 | ** USAGE: .safe |
| 10430 | ** |
| 10431 | ** This command puts the CLI into "safe mode". This command cannot be |
| 10432 | ** undone. The only way to restore full capabilities is to exit and |
| 10433 | ** restart the CLI. |
| 10434 | ** |
| 10435 | ** Safe mode restricts SQL statements and dot-commands so that no |
| 10436 | ** changes may be made to the filesystem other than writing to database |
| 10437 | ** files that are already open. |
| 10438 | ** |
| 10439 | ** * The .open command is blocked unless the database is ":memory:" |
| 10440 | ** or the --hexdb option is used. |
| 10441 | ** * The ATTACH command of SQL may not be used |
| 10442 | ** * SQL functions with side effects (ex: writefile()) are blocked. |
| 10443 | ** * The ".shell" and ".system" dot-commands are blocked. |
| 10444 | ** * Dot-command like ".archive", ".backup", ".load", ".log", ".save" |
| 10445 | ** are blocked. |
| 10446 | ** * Other commands with deleterious side effects are blocked. |
| 10447 | ** |
| 10448 | ** Unsafe actions might be simply blocked, or the CLI might issue an error |
| 10449 | ** and exit immediately. |
| 10450 | ** |
| 10451 | ** Safe mode does not prevent harm to database files that are already open. |
| 10452 | ** An attacker can still delete content and even use commands like |
| 10453 | ** "PRAGMA writable_schema=ON" to corrupt a database file that is already |
| 10454 | ** open. Safe mode only blocks access to other previously unopened files. |
| 10455 | ** |
| 10456 | ** CAUTION: If third-party extensions with system side effects have been |
| 10457 | ** loaded prior to the .safe command, the CLI has no knowledge of those |
| 10458 | ** extensions and does not know to block them. Unsafe actions might still |
| 10459 | ** be possible using those third-party extension. |
| 10460 | */ |
| 10461 | static int dotCmdSafe(ShellState *p){ |
| 10462 | int i; |
| 10463 | p->bSafeMode = 1; |
| 10464 | p->bSafeModePersist = 1; |
| 10465 | for(i=0; i<ArraySize(p->aAuxDb); i++){ |
| 10466 | sqlite3 *db = p->aAuxDb[i].db; |
| 10467 | if( db==0 ) continue; |
| 10468 | sqlite3_create_module(db, "fsdir", 0, 0); |
| 10469 | sqlite3_create_function(db, "writefile", -1, 0, 0, 0, 0, 0); |
| 10470 | sqlite3_create_module(db, "zipfile", 0, 0); |
| 10471 | sqlite3_create_function(db, "zipfile", -1, 0, 0, 0, 0, 0); |
| 10472 | } |
| 10473 | return 0; |
| 10474 | } |
| 10475 | |
| 10476 | /* |
| 10477 | ** Enlarge the space allocated in p->dot so that it can hold more |
| 10478 | ** than nArg parsed command-line arguments. |
| 10479 | */ |
| 10480 | static void parseDotRealloc(ShellState *p, int nArg){ |
| 10481 | p->dot.nAlloc = nArg+22; |
| 10482 | p->dot.azArg = realloc(p->dot.azArg,p->dot.nAlloc*sizeof(char*)); |
| 10483 | shell_check_oom(p->dot.azArg); |
| 10484 | p->dot.aiOfst = realloc(p->dot.aiOfst,p->dot.nAlloc*sizeof(int)); |
| 10485 | shell_check_oom(p->dot.aiOfst); |
| 10486 | p->dot.abQuot = realloc(p->dot.abQuot,p->dot.nAlloc); |
| 10487 | shell_check_oom(p->dot.abQuot); |
| 10488 | } |
| 10489 | |
| 10490 | /* |
| 10491 | ** Parse input line zLine up into individual arguments. Retain the |
| 10492 | ** parse in the p->dot substructure. |
| 10493 | */ |
| 10494 | static void parseDotCmdArgs(const char *zLine, ShellState *p){ |
| 10495 | char *z; |
| 10496 | int h = 1; |
| 10497 | int nArg = 0; |
| 10498 | size_t szLine; |
| 10499 | |
| 10500 | p->dot.zOrig = zLine; |
| 10501 | free(p->dot.zCopy); |
| 10502 | z = p->dot.zCopy = strdup(zLine); |
| 10503 | shell_check_oom(z); |
| 10504 | szLine = strlen(z); |
| 10505 | while( szLine>0 && IsSpace(z[szLine-1]) ) szLine--; |
| 10506 | if( szLine>0 && z[szLine-1]==';' ){ |
| 10507 | szLine--; |
| 10508 | while( szLine>0 && IsSpace(z[szLine-1]) ) szLine--; |
| 10509 | } |
| 10510 | z[szLine] = 0; |
| 10511 | parseDotRealloc(p, 2); |
| 10512 | while( z[h] ){ |
| 10513 | while( IsSpace(z[h]) ){ h++; } |
| 10514 | if( z[h]==0 ) break; |
| 10515 | if( nArg+2>p->dot.nAlloc ){ |
| 10516 | parseDotRealloc(p, nArg); |
| 10517 | } |
| 10518 | if( z[h]=='\'' || z[h]=='"' ){ |
| 10519 | int delim = z[h++]; |
| 10520 | p->dot.abQuot[nArg] = 1; |
| 10521 | p->dot.azArg[nArg] = &z[h]; |
| 10522 | p->dot.aiOfst[nArg] = h; |
| 10523 | while( z[h] && z[h]!=delim ){ |
| 10524 | if( z[h]=='\\' && delim=='"' && z[h+1]!=0 ) h++; |
| 10525 | h++; |
| 10526 | } |
| 10527 | if( z[h]==delim ){ |
| 10528 | z[h++] = 0; |
| 10529 | } |
| 10530 | if( delim=='"' ) resolve_backslashes(p->dot.azArg[nArg]); |
| 10531 | }else{ |
| 10532 | p->dot.abQuot[nArg] = 0; |
| 10533 | p->dot.azArg[nArg] = &z[h]; |
| 10534 | p->dot.aiOfst[nArg] = h; |
| 10535 | while( z[h] && !IsSpace(z[h]) ){ h++; } |
| 10536 | if( z[h] ) z[h++] = 0; |
| 10537 | } |
| 10538 | nArg++; |
| 10539 | } |
| 10540 | p->dot.nArg = nArg; |
| 10541 | p->dot.azArg[nArg] = 0; |
| 10542 | } |
| 10543 | |
| 10544 | /* |
| 10545 | ** If an input line begins with "." then invoke this routine to |
| 10546 | ** process that line. |
| 10547 | ** |
| 10548 | ** Return 1 on error, 2 to exit, and 0 otherwise. |
| 10549 | */ |
| 10550 | static int do_meta_command(const char *zLine, ShellState *p){ |
| 10551 | int nArg; |
| 10552 | int n, c; |
| 10553 | int rc = 0; |
| 10554 | char **azArg; |
| 10555 | |
| 10556 | #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION) |
| 10557 | if( p->expert.pExpert ){ |
| 10558 | expertFinish(p, 1, 0); |
| 10559 | } |
| 10560 | #endif |
| 10561 | |
| 10562 | /* Parse the input line into tokens stored in p->dot. |
| 10563 | */ |
| 10564 | parseDotCmdArgs(zLine, p); |
| 10565 | nArg = p->dot.nArg; |
| 10566 | azArg = p->dot.azArg; |
| 10567 | |
| 10568 | /* Process the input line. |
| 10569 | */ |
| 10570 | if( nArg==0 ) return 0; /* no tokens, no error */ |
| 10571 | n = strlen30(azArg[0]); |
| 10572 | c = azArg[0][0]; |
| 10573 | clearTempFile(p,0,0); |
| 10574 | |
| 10575 | #ifndef SQLITE_OMIT_AUTHORIZATION |
| 10576 | if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){ |
| 10577 | int ii; |
| 10578 | int eOnOff = -1; |
| 10579 | open_db(p, 0); |
| 10580 | for(ii=1; ii<nArg && rc==0; ii++){ |
| 10581 | const char *z = azArg[ii]; |
| 10582 | if( z[0]=='-' && z[1]=='-' ) z++; |
| 10583 | if( strcmp(z,"-deny")==0 ){ |
| 10584 | ii++; |
| 10585 | if( ii>=nArg ){ |
| 10586 | dotCmdError(p, ii-1, "missing argument", 0); |
| 10587 | rc = 1; |
| 10588 | goto meta_command_exit; |
| 10589 | }else{ |
| 10590 | free(p->zAuthDeny); |
| 10591 | p->zAuthDeny = 0; |
| 10592 | if( azArg[ii][0] ){ |
| 10593 | p->zAuthDeny = strdup(azArg[ii]); |
| 10594 | shell_check_oom(p->zAuthDeny); |
| 10595 | } |
| 10596 | } |
| 10597 | }else |
| 10598 | if( strcmp(z,"-ignore")==0 ){ |
| 10599 | ii++; |
| 10600 | if( ii>=nArg ){ |
| 10601 | dotCmdError(p, ii-1, "missing argument", 0); |
| 10602 | rc = 1; |
| 10603 | goto meta_command_exit; |
| 10604 | }else{ |
| 10605 | free(p->zAuthIgnore); |
| 10606 | p->zAuthIgnore = 0; |
| 10607 | if( azArg[ii][0] ){ |
| 10608 | p->zAuthIgnore = strdup(azArg[ii]); |
| 10609 | shell_check_oom(p->zAuthIgnore); |
| 10610 | } |
| 10611 | } |
| 10612 | }else |
| 10613 | if( eOnOff<0 ){ |
| 10614 | eOnOff = booleanValue(z); |
| 10615 | }else |
| 10616 | { |
| 10617 | dotCmdError(p, ii, "unknown argument", 0); |
| 10618 | rc = 1; |
| 10619 | goto meta_command_exit; |
| 10620 | } |
| 10621 | } |
| 10622 | if( eOnOff<0 ){ |
| 10623 | cli_printf(stderr, "Usage: .auth ON|OFF [--deny GLOB] [--ignore]\n"); |
| 10624 | rc = 1; |
| 10625 | goto meta_command_exit; |
| 10626 | } |
| 10627 | if( eOnOff ){ |
| 10628 | sqlite3_set_authorizer(p->db, shellAuth, p); |
| 10629 | }else if( p->bSafeModePersist ){ |
| 10630 | sqlite3_set_authorizer(p->db, safeModeAuth, p); |
| 10631 | }else{ |
| 10632 | sqlite3_set_authorizer(p->db, 0, 0); |
| 10633 | } |
| 10634 | }else |
| 10635 | #endif |
| 10636 | |
| 10637 | #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \ |
| 10638 | && !defined(SQLITE_SHELL_FIDDLE) |
| 10639 | if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){ |
| 10640 | open_db(p, 0); |
| 10641 | failIfSafeMode(p, "cannot run .archive in safe mode"); |
| 10642 | rc = arDotCommand(p, 0, azArg, nArg); |
| 10643 | }else |
| 10644 | #endif |
| 10645 | |
| 10646 | #ifndef SQLITE_SHELL_FIDDLE |
| 10647 | if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0) |
| 10648 | || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0) |
| 10649 | ){ |
| 10650 | const char *zDestFile = 0; |
| 10651 | const char *zDb = 0; |
| 10652 | sqlite3 *pDest; |
| 10653 | sqlite3_backup *pBackup; |
| 10654 | int j; |
| 10655 | int bAsync = 0; |
| 10656 | const char *zVfs = 0; |
| 10657 | failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); |
| 10658 | for(j=1; j<nArg; j++){ |
| 10659 | const char *z = azArg[j]; |
| 10660 | if( z[0]=='-' ){ |
| 10661 | if( z[1]=='-' ) z++; |
| 10662 | if( cli_strcmp(z, "-append")==0 ){ |
| 10663 | zVfs = "apndvfs"; |
| 10664 | }else |
| 10665 | if( cli_strcmp(z, "-async")==0 ){ |
| 10666 | bAsync = 1; |
| 10667 | }else |
| 10668 | { |
| 10669 | dotCmdError(p, j, "unknown option", "should be -append or -async"); |
| 10670 | return 1; |
| 10671 | } |
| 10672 | }else if( zDestFile==0 ){ |
| 10673 | zDestFile = azArg[j]; |
| 10674 | }else if( zDb==0 ){ |
| 10675 | zDb = zDestFile; |
| 10676 | zDestFile = azArg[j]; |
| 10677 | }else{ |
| 10678 | cli_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n"); |
| 10679 | return 1; |
| 10680 | } |
| 10681 | } |
| 10682 | if( zDestFile==0 ){ |
| 10683 | cli_printf(stderr, "missing FILENAME argument on .backup\n"); |
| 10684 | return 1; |
| 10685 | } |
| 10686 | if( zDb==0 ) zDb = "main"; |
| 10687 | rc = sqlite3_open_v2(zDestFile, &pDest, |
| 10688 | SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs); |
| 10689 | if( rc!=SQLITE_OK ){ |
| 10690 | cli_printf(stderr,"Error: cannot open \"%s\"\n", zDestFile); |
| 10691 | close_db(pDest); |
| 10692 | return 1; |
| 10693 | } |
| 10694 | if( bAsync ){ |
| 10695 | sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;", |
| 10696 | 0, 0, 0); |
| 10697 | } |
| 10698 | open_db(p, 0); |
| 10699 | pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb); |
| 10700 | if( pBackup==0 ){ |
| 10701 | shellDatabaseError(pDest); |
| 10702 | close_db(pDest); |
| 10703 | return 1; |
| 10704 | } |
| 10705 | while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} |
| 10706 | sqlite3_backup_finish(pBackup); |
| 10707 | if( rc==SQLITE_DONE ){ |
| 10708 | rc = 0; |
| 10709 | }else{ |
| 10710 | shellDatabaseError(pDest); |
| 10711 | rc = 1; |
| 10712 | } |
| 10713 | close_db(pDest); |
| 10714 | }else |
| 10715 | #endif /* !defined(SQLITE_SHELL_FIDDLE) */ |
| 10716 | |
| 10717 | if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){ |
| 10718 | if( nArg==2 ){ |
| 10719 | bail_on_error = booleanValue(azArg[1]); |
| 10720 | }else{ |
| 10721 | eputz("Usage: .bail on|off\n"); |
| 10722 | rc = 1; |
| 10723 | } |
| 10724 | }else |
| 10725 | |
| 10726 | /* Undocumented. Legacy only. See "crlf" below */ |
| 10727 | if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){ |
| 10728 | eputz("The \".binary\" command is deprecated.\n"); |
| 10729 | rc = 1; |
| 10730 | }else |
| 10731 | |
| 10732 | /* The undocumented ".breakpoint" command causes a call to the no-op |
| 10733 | ** routine named test_breakpoint(). |
| 10734 | */ |
| 10735 | if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){ |
| 10736 | test_breakpoint(); |
| 10737 | }else |
| 10738 | |
| 10739 | #ifndef SQLITE_SHELL_FIDDLE |
| 10740 | if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){ |
| 10741 | failIfSafeMode(p, "cannot run .cd in safe mode"); |
| 10742 | if( nArg==2 ){ |
| 10743 | #if defined(_WIN32) || defined(WIN32) |
| 10744 | wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]); |
| 10745 | rc = !SetCurrentDirectoryW(z); |
| 10746 | sqlite3_free(z); |
| 10747 | #else |
| 10748 | rc = chdir(azArg[1]); |
| 10749 | #endif |
| 10750 | if( rc ){ |
| 10751 | cli_printf(stderr,"Cannot change to directory \"%s\"\n", azArg[1]); |
| 10752 | rc = 1; |
| 10753 | } |
| 10754 | }else{ |
| 10755 | eputz("Usage: .cd DIRECTORY\n"); |
| 10756 | rc = 1; |
| 10757 | } |
| 10758 | }else |
| 10759 | #endif /* !defined(SQLITE_SHELL_FIDDLE) */ |
| 10760 | |
| 10761 | if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){ |
| 10762 | if( nArg==2 ){ |
| 10763 | setOrClearFlag(p, SHFLG_CountChanges, azArg[1]); |
| 10764 | }else{ |
| 10765 | eputz("Usage: .changes on|off\n"); |
| 10766 | rc = 1; |
| 10767 | } |
| 10768 | }else |
| 10769 | |
| 10770 | /* Cancel output redirection, if it is currently set (by .testcase) |
| 10771 | ** Then read the content of the testcase-out.txt file and compare against |
| 10772 | ** azArg[1]. If there are differences, report an error and exit. |
| 10773 | */ |
| 10774 | if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){ |
| 10775 | rc = dotCmdCheck(p); |
| 10776 | }else |
| 10777 | |
| 10778 | #ifndef SQLITE_SHELL_FIDDLE |
| 10779 | if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){ |
| 10780 | rc = dotCmdClone(p); |
| 10781 | }else |
| 10782 | #endif /* !defined(SQLITE_SHELL_FIDDLE) */ |
| 10783 | |
| 10784 | if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){ |
| 10785 | if( nArg==1 ){ |
| 10786 | /* List available connections */ |
| 10787 | int i; |
| 10788 | for(i=0; i<ArraySize(p->aAuxDb); i++){ |
| 10789 | const char *zFile = p->aAuxDb[i].zDbFilename; |
| 10790 | if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){ |
| 10791 | zFile = "(not open)"; |
| 10792 | }else if( zFile==0 ){ |
| 10793 | zFile = "(memory)"; |
| 10794 | }else if( zFile[0]==0 ){ |
| 10795 | zFile = "(temporary-file)"; |
| 10796 | } |
| 10797 | if( p->pAuxDb == &p->aAuxDb[i] ){ |
| 10798 | cli_printf(stdout, "ACTIVE %d: %s\n", i, zFile); |
| 10799 | }else if( p->aAuxDb[i].db!=0 ){ |
| 10800 | cli_printf(stdout, " %d: %s\n", i, zFile); |
| 10801 | } |
| 10802 | } |
| 10803 | }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){ |
| 10804 | int i = azArg[1][0] - '0'; |
| 10805 | if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){ |
| 10806 | p->pAuxDb->db = p->db; |
| 10807 | p->pAuxDb = &p->aAuxDb[i]; |
| 10808 | globalDb = p->db = p->pAuxDb->db; |
| 10809 | p->pAuxDb->db = 0; |
| 10810 | } |
| 10811 | }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0 |
| 10812 | && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){ |
| 10813 | int i = azArg[2][0] - '0'; |
| 10814 | if( i<0 || i>=ArraySize(p->aAuxDb) ){ |
| 10815 | /* No-op */ |
| 10816 | }else if( p->pAuxDb == &p->aAuxDb[i] ){ |
| 10817 | eputz("cannot close the active database connection\n"); |
| 10818 | rc = 1; |
| 10819 | }else if( p->aAuxDb[i].db ){ |
| 10820 | session_close_all(p, i); |
| 10821 | close_db(p->aAuxDb[i].db); |
| 10822 | p->aAuxDb[i].db = 0; |
| 10823 | } |
| 10824 | }else{ |
| 10825 | eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n"); |
| 10826 | rc = 1; |
| 10827 | } |
| 10828 | }else |
| 10829 | |
| 10830 | if( c=='c' && n==4 |
| 10831 | && (cli_strncmp(azArg[0], "crlf", n)==0 |
| 10832 | || cli_strncmp(azArg[0], "crnl",n)==0) |
| 10833 | ){ |
| 10834 | if( nArg==2 ){ |
| 10835 | #ifdef _WIN32 |
| 10836 | if( booleanValue(azArg[1]) ){ |
| 10837 | p->mode.mFlags |= MFLG_CRLF; |
| 10838 | }else{ |
| 10839 | p->mode.mFlags &= ~MFLG_CRLF; |
| 10840 | } |
| 10841 | #else |
| 10842 | p->mode.mFlags &= ~MFLG_CRLF; |
| 10843 | #endif |
| 10844 | } |
| 10845 | cli_printf(stderr, "crlf is %s\n", |
| 10846 | (p->mode.mFlags & MFLG_CRLF)!=0 ? "ON" : "OFF"); |
| 10847 | }else |
| 10848 | |
| 10849 | if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){ |
| 10850 | char **azName = 0; |
| 10851 | int nName = 0; |
| 10852 | sqlite3_stmt *pStmt; |
| 10853 | int i; |
| 10854 | open_db(p, 0); |
| 10855 | rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); |
| 10856 | if( rc ){ |
| 10857 | shellDatabaseError(p->db); |
| 10858 | rc = 1; |
| 10859 | }else{ |
| 10860 | while( sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 10861 | const char *zSchema = (const char *)sqlite3_column_text(pStmt,1); |
| 10862 | const char *zFile = (const char*)sqlite3_column_text(pStmt,2); |
| 10863 | if( zSchema==0 || zFile==0 ) continue; |
| 10864 | azName = sqlite3_realloc64(azName, (nName+1)*2*sizeof(char*)); |
| 10865 | shell_check_oom(azName); |
| 10866 | azName[nName*2] = strdup(zSchema); |
| 10867 | azName[nName*2+1] = strdup(zFile); |
| 10868 | nName++; |
| 10869 | } |
| 10870 | } |
| 10871 | sqlite3_finalize(pStmt); |
| 10872 | for(i=0; i<nName; i++){ |
| 10873 | int eTxn = sqlite3_txn_state(p->db, azName[i*2]); |
| 10874 | int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]); |
| 10875 | const char *z = azName[i*2+1]; |
| 10876 | cli_printf(p->out, "%s: %s %s%s\n", |
| 10877 | azName[i*2], z && z[0] ? z : "\"\"", bRdonly ? "r/o" : "r/w", |
| 10878 | eTxn==SQLITE_TXN_NONE ? "" : |
| 10879 | eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn"); |
| 10880 | free(azName[i*2]); |
| 10881 | free(azName[i*2+1]); |
| 10882 | } |
| 10883 | sqlite3_free(azName); |
| 10884 | }else |
| 10885 | |
| 10886 | if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){ |
| 10887 | static const struct DbConfigChoices { |
| 10888 | const char *zName; |
| 10889 | int op; |
| 10890 | } aDbConfig[] = { |
| 10891 | { "attach_create", SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE }, |
| 10892 | { "attach_write", SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE }, |
| 10893 | { "comments", SQLITE_DBCONFIG_ENABLE_COMMENTS }, |
| 10894 | { "defensive", SQLITE_DBCONFIG_DEFENSIVE }, |
| 10895 | { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL }, |
| 10896 | { "dqs_dml", SQLITE_DBCONFIG_DQS_DML }, |
| 10897 | { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY }, |
| 10898 | { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG }, |
| 10899 | { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER }, |
| 10900 | { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW }, |
| 10901 | { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER }, |
| 10902 | { "fp_digits", SQLITE_DBCONFIG_FP_DIGITS }, |
| 10903 | { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE }, |
| 10904 | { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT }, |
| 10905 | { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION }, |
| 10906 | { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE }, |
| 10907 | { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE }, |
| 10908 | { "reverse_scanorder", SQLITE_DBCONFIG_REVERSE_SCANORDER }, |
| 10909 | { "stmt_scanstatus", SQLITE_DBCONFIG_STMT_SCANSTATUS }, |
| 10910 | { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP }, |
| 10911 | { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA }, |
| 10912 | #ifdef SQLITE_DEBUG |
| 10913 | { "vdbe_trace", SQLITE_DBCONFIG_VDBE_TRACE }, |
| 10914 | #endif |
| 10915 | { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA }, |
| 10916 | }; |
| 10917 | int ii, v; |
| 10918 | open_db(p, 0); |
| 10919 | for(ii=0; ii<ArraySize(aDbConfig); ii++){ |
| 10920 | if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue; |
| 10921 | if( nArg>=3 ){ |
| 10922 | if( aDbConfig[ii].op==SQLITE_DBCONFIG_FP_DIGITS ){ |
| 10923 | sqlite3_db_config(p->db, aDbConfig[ii].op, atoi(azArg[2]), (int*)0); |
| 10924 | }else{ |
| 10925 | sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), |
| 10926 | (int*)0); |
| 10927 | } |
| 10928 | } |
| 10929 | sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v); |
| 10930 | if( aDbConfig[ii].op==SQLITE_DBCONFIG_FP_DIGITS ){ |
| 10931 | cli_printf(p->out, "%19s %d\n", aDbConfig[ii].zName, v); |
| 10932 | }else{ |
| 10933 | cli_printf(p->out, "%19s %s\n", |
| 10934 | aDbConfig[ii].zName, v ? "on" : "off"); |
| 10935 | } |
| 10936 | if( nArg>1 ) break; |
| 10937 | } |
| 10938 | if( nArg>1 && ii==ArraySize(aDbConfig) ){ |
| 10939 | dotCmdError(p, 1, "unknown dbconfig", |
| 10940 | "Enter \".dbconfig\" with no arguments for a list"); |
| 10941 | } |
| 10942 | }else |
| 10943 | |
| 10944 | #if SQLITE_SHELL_HAVE_RECOVER |
| 10945 | if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){ |
| 10946 | rc = shell_dbinfo_command(p, nArg, azArg); |
| 10947 | }else |
| 10948 | #endif /* SQLITE_SHELL_HAVE_RECOVER */ |
| 10949 | |
| 10950 | if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbtotxt", n)==0 ){ |
| 10951 | open_db(p, 0); |
| 10952 | sqlite3_exec(p->db, "PRAGMA page_count", 0, 0, 0); |
| 10953 | rc = shell_dbtotxt_command(p, nArg, azArg); |
| 10954 | }else |
| 10955 | |
| 10956 | if( c=='d' && n==8 && cli_strncmp(azArg[0], "diskused", n)==0 ){ |
| 10957 | const char *zSchema = 0; |
| 10958 | int ii; |
| 10959 | char *zSql; |
| 10960 | open_db(p, 0); |
| 10961 | for(ii=1; ii<nArg; ii++){ |
| 10962 | const char *z = azArg[ii]; |
| 10963 | if( z[0]=='-' ){ |
| 10964 | dotCmdError(p, ii, "unknown option", 0); |
| 10965 | rc = 1; |
| 10966 | goto meta_command_exit; |
| 10967 | } |
| 10968 | if( zSchema ){ |
| 10969 | dotCmdError(p, ii, "unknown argument", 0); |
| 10970 | rc = 1; |
| 10971 | goto meta_command_exit; |
| 10972 | } |
| 10973 | zSchema = z; |
| 10974 | } |
| 10975 | zSql = sqlite3_mprintf("SELECT diskused(%Q)", zSchema); |
| 10976 | shell_check_oom(zSql); |
| 10977 | modePush(p); |
| 10978 | modeChange(p, MODE_BATCH); |
| 10979 | shell_exec(p, zSql, 0); |
| 10980 | modePop(p); |
| 10981 | sqlite3_free(zSql); |
| 10982 | }else |
| 10983 | |
| 10984 | if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){ |
| 10985 | char *zLike = 0; |
| 10986 | char *zSql; |
| 10987 | int i; |
| 10988 | int savedShellFlags = p->shellFlgs; |
| 10989 | Mode saved_mode; |
| 10990 | ShellClearFlag(p, |
| 10991 | SHFLG_PreserveRowid|SHFLG_DumpDataOnly|SHFLG_DumpNoSys); |
| 10992 | for(i=1; i<nArg; i++){ |
| 10993 | if( azArg[i][0]=='-' ){ |
| 10994 | const char *z = azArg[i]+1; |
| 10995 | if( z[0]=='-' ) z++; |
| 10996 | if( cli_strcmp(z,"preserve-rowids")==0 ){ |
| 10997 | #ifdef SQLITE_OMIT_VIRTUALTABLE |
| 10998 | dotCmdError(p, i, "unable", |
| 10999 | "The --preserve-rowids option is not compatible" |
| 11000 | " with SQLITE_OMIT_VIRTUALTABLE"); |
| 11001 | rc = 1; |
| 11002 | sqlite3_free(zLike); |
| 11003 | goto meta_command_exit; |
| 11004 | #else |
| 11005 | ShellSetFlag(p, SHFLG_PreserveRowid); |
| 11006 | #endif |
| 11007 | }else |
| 11008 | if( cli_strcmp(z,"newlines")==0 ){ |
| 11009 | /*ShellSetFlag(p, SHFLG_Newlines);*/ |
| 11010 | }else |
| 11011 | if( cli_strcmp(z,"data-only")==0 ){ |
| 11012 | ShellSetFlag(p, SHFLG_DumpDataOnly); |
| 11013 | }else |
| 11014 | if( cli_strcmp(z,"nosys")==0 ){ |
| 11015 | ShellSetFlag(p, SHFLG_DumpNoSys); |
| 11016 | }else |
| 11017 | { |
| 11018 | dotCmdError(p, i, "unknown option", 0); |
| 11019 | rc = 1; |
| 11020 | sqlite3_free(zLike); |
| 11021 | goto meta_command_exit; |
| 11022 | } |
| 11023 | }else{ |
| 11024 | /* azArg[i] contains a LIKE pattern. This ".dump" request should |
| 11025 | ** only dump data for tables for which either the table name matches |
| 11026 | ** the LIKE pattern, or the table appears to be a shadow table of |
| 11027 | ** a virtual table for which the name matches the LIKE pattern. |
| 11028 | */ |
| 11029 | char *zExpr = sqlite3_mprintf( |
| 11030 | "name LIKE %Q ESCAPE '\\' OR EXISTS (" |
| 11031 | " SELECT 1 FROM sqlite_schema WHERE " |
| 11032 | " name LIKE %Q ESCAPE '\\' AND" |
| 11033 | " sql LIKE 'CREATE VIRTUAL TABLE%%' AND" |
| 11034 | " substr(o.name, 1, length(name)+1) == (name||'_')" |
| 11035 | ")", azArg[i], azArg[i] |
| 11036 | ); |
| 11037 | |
| 11038 | if( zLike ){ |
| 11039 | zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr); |
| 11040 | }else{ |
| 11041 | zLike = zExpr; |
| 11042 | } |
| 11043 | } |
| 11044 | } |
| 11045 | |
| 11046 | open_db(p, 0); |
| 11047 | |
| 11048 | modeDup(&saved_mode, &p->mode); |
| 11049 | outputDumpWarning(p, zLike); |
| 11050 | if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ |
| 11051 | /* When playing back a "dump", the content might appear in an order |
| 11052 | ** which causes immediate foreign key constraints to be violated. |
| 11053 | ** So disable foreign-key constraint enforcement to prevent problems. */ |
| 11054 | cli_puts("PRAGMA foreign_keys=OFF;\n", p->out); |
| 11055 | cli_puts("BEGIN TRANSACTION;\n", p->out); |
| 11056 | } |
| 11057 | p->writableSchema = 0; |
| 11058 | p->mode.spec.bTitles = QRF_No; |
| 11059 | /* Set writable_schema=ON since doing so forces SQLite to initialize |
| 11060 | ** as much of the schema as it can even if the sqlite_schema table is |
| 11061 | ** corrupt. */ |
| 11062 | sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); |
| 11063 | p->nErr = 0; |
| 11064 | if( zLike==0 ) zLike = sqlite3_mprintf("true"); |
| 11065 | zSql = sqlite3_mprintf( |
| 11066 | "SELECT name, type, shell_complete_sql(sql) FROM sqlite_schema AS o " |
| 11067 | "WHERE (%s) AND type=='table'" |
| 11068 | " AND sql NOT NULL" |
| 11069 | " ORDER BY tbl_name='sqlite_sequence', rowid", |
| 11070 | zLike |
| 11071 | ); |
| 11072 | run_schema_dump_query(p,zSql); |
| 11073 | sqlite3_free(zSql); |
| 11074 | if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ |
| 11075 | zSql = sqlite3_mprintf( |
| 11076 | "SELECT shell_complete_sql(sql) FROM sqlite_schema AS o " |
| 11077 | "WHERE (%s) AND sql NOT NULL" |
| 11078 | " AND type IN ('index','trigger','view') " |
| 11079 | "ORDER BY type COLLATE NOCASE DESC", |
| 11080 | zLike |
| 11081 | ); |
| 11082 | run_table_dump_query(p, zSql); |
| 11083 | sqlite3_free(zSql); |
| 11084 | } |
| 11085 | sqlite3_free(zLike); |
| 11086 | if( p->writableSchema ){ |
| 11087 | cli_puts("PRAGMA writable_schema=OFF;\n", p->out); |
| 11088 | p->writableSchema = 0; |
| 11089 | } |
| 11090 | sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); |
| 11091 | sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); |
| 11092 | if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ |
| 11093 | cli_puts(p->nErr?";\nROLLBACK; -- due to errors\n":"COMMIT;\n", p->out); |
| 11094 | } |
| 11095 | p->shellFlgs = savedShellFlags; |
| 11096 | modeFree(&p->mode); |
| 11097 | p->mode = saved_mode; |
| 11098 | if( p->mode.spec.zFpFmt ) p->mode.spec.zFpFmt = p->mode.zFpFmt; |
| 11099 | if( p->mode.spec.zIFmt ) p->mode.spec.zIFmt = p->mode.zIFmt; |
| 11100 | rc = p->nErr>0; |
| 11101 | }else |
| 11102 | |
| 11103 | if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){ |
| 11104 | if( nArg==2 ){ |
| 11105 | if( booleanValue(azArg[1]) ){ |
| 11106 | p->mode.mFlags |= MFLG_ECHO; |
| 11107 | }else{ |
| 11108 | p->mode.mFlags &= ~MFLG_ECHO; |
| 11109 | } |
| 11110 | }else{ |
| 11111 | eputz("Usage: .echo on|off\n"); |
| 11112 | rc = 1; |
| 11113 | } |
| 11114 | }else |
| 11115 | |
| 11116 | if( c=='e' && n==6 && cli_strcmp(azArg[0],"elseif")==0 ){ |
| 11117 | rc = dotCmdElseif(p); |
| 11118 | }else |
| 11119 | |
| 11120 | if( c=='e' && n==4 && cli_strcmp(azArg[0],"else")==0 ){ |
| 11121 | rc = dotCmdElse(p); |
| 11122 | }else |
| 11123 | |
| 11124 | if( c=='e' && n==5 && cli_strcmp(azArg[0],"endif")==0 ){ |
| 11125 | rc = dotCmdEndif(p); |
| 11126 | }else |
| 11127 | |
| 11128 | if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){ |
| 11129 | rc = dotCmdEqp(p); |
| 11130 | }else |
| 11131 | |
| 11132 | #ifndef SQLITE_SHELL_FIDDLE |
| 11133 | if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){ |
| 11134 | if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) cli_exit(rc); |
| 11135 | rc = 2; |
| 11136 | }else |
| 11137 | #endif |
| 11138 | |
| 11139 | /* The ".explain" command is automatic now. It is largely pointless. It |
| 11140 | ** retained purely for backwards compatibility */ |
| 11141 | if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){ |
| 11142 | if( nArg>=2 ){ |
| 11143 | if( cli_strcmp(azArg[1],"auto")==0 ){ |
| 11144 | p->mode.autoExplain = 1; |
| 11145 | }else{ |
| 11146 | p->mode.autoExplain = booleanValue(azArg[1]); |
| 11147 | } |
| 11148 | } |
| 11149 | }else |
| 11150 | |
| 11151 | #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION) |
| 11152 | if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){ |
| 11153 | if( p->bSafeMode ){ |
| 11154 | cli_printf(stderr, |
| 11155 | "Cannot run experimental commands such as \"%s\" in safe mode\n", |
| 11156 | azArg[0]); |
| 11157 | rc = 1; |
| 11158 | }else{ |
| 11159 | open_db(p, 0); |
| 11160 | expertDotCommand(p, azArg, nArg); |
| 11161 | } |
| 11162 | }else |
| 11163 | #endif |
| 11164 | |
| 11165 | if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){ |
| 11166 | static const struct { |
| 11167 | const char *zCtrlName; /* Name of a test-control option */ |
| 11168 | int ctrlCode; /* Integer code for that option */ |
| 11169 | const char *zUsage; /* Usage notes */ |
| 11170 | } aCtrl[] = { |
| 11171 | { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" }, |
| 11172 | { "data_version", SQLITE_FCNTL_DATA_VERSION, "" }, |
| 11173 | { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" }, |
| 11174 | { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" }, |
| 11175 | { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" }, |
| 11176 | /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/ |
| 11177 | { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" }, |
| 11178 | { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" }, |
| 11179 | { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" }, |
| 11180 | { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" }, |
| 11181 | /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/ |
| 11182 | }; |
| 11183 | int filectrl = -1; |
| 11184 | int iCtrl = -1; |
| 11185 | sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */ |
| 11186 | int isOk = 0; /* 0: usage 1: %lld 2: no-result */ |
| 11187 | int n2, i; |
| 11188 | const char *zCmd = 0; |
| 11189 | const char *zSchema = 0; |
| 11190 | |
| 11191 | open_db(p, 0); |
| 11192 | zCmd = nArg>=2 ? azArg[1] : "help"; |
| 11193 | |
| 11194 | if( zCmd[0]=='-' |
| 11195 | && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0) |
| 11196 | && nArg>=4 |
| 11197 | ){ |
| 11198 | zSchema = azArg[2]; |
| 11199 | for(i=3; i<nArg; i++) azArg[i-2] = azArg[i]; |
| 11200 | nArg -= 2; |
| 11201 | zCmd = azArg[1]; |
| 11202 | } |
| 11203 | |
| 11204 | /* The argument can optionally begin with "-" or "--" */ |
| 11205 | if( zCmd[0]=='-' && zCmd[1] ){ |
| 11206 | zCmd++; |
| 11207 | if( zCmd[0]=='-' && zCmd[1] ) zCmd++; |
| 11208 | } |
| 11209 | |
| 11210 | /* --help lists all file-controls */ |
| 11211 | if( cli_strcmp(zCmd,"help")==0 ){ |
| 11212 | cli_puts("Available file-controls:\n", p->out); |
| 11213 | for(i=0; i<ArraySize(aCtrl); i++){ |
| 11214 | cli_printf(p->out, |
| 11215 | " .filectrl %s %s\n", aCtrl[i].zCtrlName, aCtrl[i].zUsage); |
| 11216 | } |
| 11217 | rc = 1; |
| 11218 | goto meta_command_exit; |
| 11219 | } |
| 11220 | |
| 11221 | /* convert filectrl text option to value. allow any unique prefix |
| 11222 | ** of the option name, or a numerical value. */ |
| 11223 | n2 = strlen30(zCmd); |
| 11224 | for(i=0; i<ArraySize(aCtrl); i++){ |
| 11225 | if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ |
| 11226 | if( filectrl<0 ){ |
| 11227 | filectrl = aCtrl[i].ctrlCode; |
| 11228 | iCtrl = i; |
| 11229 | }else{ |
| 11230 | cli_printf(stderr,"Error: ambiguous file-control: \"%s\"\n" |
| 11231 | "Use \".filectrl --help\" for help\n", zCmd); |
| 11232 | rc = 1; |
| 11233 | goto meta_command_exit; |
| 11234 | } |
| 11235 | } |
| 11236 | } |
| 11237 | if( filectrl<0 ){ |
| 11238 | cli_printf(stderr,"Error: unknown file-control: %s\n" |
| 11239 | "Use \".filectrl --help\" for help\n", zCmd); |
| 11240 | }else{ |
| 11241 | switch(filectrl){ |
| 11242 | case SQLITE_FCNTL_SIZE_LIMIT: { |
| 11243 | if( nArg!=2 && nArg!=3 ) break; |
| 11244 | iRes = nArg==3 ? integerValue(azArg[2]) : -1; |
| 11245 | sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes); |
| 11246 | isOk = 1; |
| 11247 | break; |
| 11248 | } |
| 11249 | case SQLITE_FCNTL_LOCK_TIMEOUT: |
| 11250 | case SQLITE_FCNTL_CHUNK_SIZE: { |
| 11251 | int x; |
| 11252 | if( nArg!=3 ) break; |
| 11253 | x = (int)integerValue(azArg[2]); |
| 11254 | sqlite3_file_control(p->db, zSchema, filectrl, &x); |
| 11255 | isOk = 2; |
| 11256 | break; |
| 11257 | } |
| 11258 | case SQLITE_FCNTL_PERSIST_WAL: |
| 11259 | case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { |
| 11260 | int x; |
| 11261 | if( nArg!=2 && nArg!=3 ) break; |
| 11262 | x = nArg==3 ? booleanValue(azArg[2]) : -1; |
| 11263 | sqlite3_file_control(p->db, zSchema, filectrl, &x); |
| 11264 | iRes = x; |
| 11265 | isOk = 1; |
| 11266 | break; |
| 11267 | } |
| 11268 | case SQLITE_FCNTL_DATA_VERSION: |
| 11269 | case SQLITE_FCNTL_HAS_MOVED: { |
| 11270 | int x; |
| 11271 | if( nArg!=2 ) break; |
| 11272 | sqlite3_file_control(p->db, zSchema, filectrl, &x); |
| 11273 | iRes = x; |
| 11274 | isOk = 1; |
| 11275 | break; |
| 11276 | } |
| 11277 | case SQLITE_FCNTL_TEMPFILENAME: { |
| 11278 | char *z = 0; |
| 11279 | if( nArg!=2 ) break; |
| 11280 | sqlite3_file_control(p->db, zSchema, filectrl, &z); |
| 11281 | if( z ){ |
| 11282 | cli_printf(p->out, "%s\n", z); |
| 11283 | sqlite3_free(z); |
| 11284 | } |
| 11285 | isOk = 2; |
| 11286 | break; |
| 11287 | } |
| 11288 | case SQLITE_FCNTL_RESERVE_BYTES: { |
| 11289 | int x; |
| 11290 | if( nArg>=3 ){ |
| 11291 | x = atoi(azArg[2]); |
| 11292 | sqlite3_file_control(p->db, zSchema, filectrl, &x); |
| 11293 | } |
| 11294 | x = -1; |
| 11295 | sqlite3_file_control(p->db, zSchema, filectrl, &x); |
| 11296 | cli_printf(p->out, "%d\n", x); |
| 11297 | isOk = 2; |
| 11298 | break; |
| 11299 | } |
| 11300 | } |
| 11301 | } |
| 11302 | if( isOk==0 && iCtrl>=0 ){ |
| 11303 | cli_printf(p->out, "Usage: .filectrl %s %s\n", |
| 11304 | zCmd, aCtrl[iCtrl].zUsage); |
| 11305 | rc = 1; |
| 11306 | }else if( isOk==1 ){ |
| 11307 | char zBuf[100]; |
| 11308 | sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes); |
| 11309 | cli_printf(p->out, "%s\n", zBuf); |
| 11310 | } |
| 11311 | }else |
| 11312 | |
| 11313 | if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){ |
| 11314 | ShellState data; |
| 11315 | int doStats = 0; |
| 11316 | int hasStat[5]; |
| 11317 | int bIndent = 0; |
| 11318 | char *zSql; |
| 11319 | if( nArg==2 && optionMatch(azArg[1], "indent") ){ |
| 11320 | nArg = 1; |
| 11321 | bIndent = 1; |
| 11322 | } |
| 11323 | if( nArg!=1 ){ |
| 11324 | eputz("Usage: .fullschema ?--indent?\n"); |
| 11325 | rc = 1; |
| 11326 | goto meta_command_exit; |
| 11327 | } |
| 11328 | open_db(p, 0); |
| 11329 | zSql = sqlite3_mprintf( |
| 11330 | "SELECT shell_format_schema(shell_complete_sql(sql),%d) FROM" |
| 11331 | " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" |
| 11332 | " FROM sqlite_schema UNION ALL" |
| 11333 | " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) " |
| 11334 | "WHERE type!='meta' AND sql NOTNULL" |
| 11335 | " AND name NOT LIKE 'sqlite__%%' ESCAPE '_' " |
| 11336 | "ORDER BY x", bIndent); |
| 11337 | memcpy(&data, p, sizeof(data)); |
| 11338 | data.mode.spec.bTitles = QRF_No; |
| 11339 | data.mode.eMode = MODE_List; |
| 11340 | data.mode.spec.eText = QRF_TEXT_Plain; |
| 11341 | data.mode.spec.nCharLimit = 0; |
| 11342 | data.mode.spec.zRowSep = ";\n"; |
| 11343 | rc = shell_exec(&data,zSql,0); |
| 11344 | sqlite3_free(zSql); |
| 11345 | if( rc==SQLITE_OK ){ |
| 11346 | sqlite3_stmt *pStmt; |
| 11347 | memset(hasStat, 0, sizeof(hasStat)); |
| 11348 | rc = sqlite3_prepare_v2(p->db, |
| 11349 | "SELECT substr(name,12,1) FROM sqlite_schema" |
| 11350 | " WHERE name GLOB 'sqlite_stat[134]'", |
| 11351 | -1, &pStmt, 0); |
| 11352 | if( rc==SQLITE_OK ){ |
| 11353 | while( sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 11354 | int k = sqlite3_column_int(pStmt,0); |
| 11355 | assert( k==1 || k==3 || k==4 ); |
| 11356 | hasStat[k] = 1; |
| 11357 | doStats = 1; |
| 11358 | } |
| 11359 | } |
| 11360 | sqlite3_finalize(pStmt); |
| 11361 | } |
| 11362 | if( doStats==0 ){ |
| 11363 | cli_puts("/* No STAT tables available */\n", p->out); |
| 11364 | }else{ |
| 11365 | cli_puts("ANALYZE sqlite_schema;\n", p->out); |
| 11366 | data.mode.eMode = MODE_Insert; |
| 11367 | if( hasStat[1] ){ |
| 11368 | data.mode.spec.zTableName = "sqlite_stat1"; |
| 11369 | shell_exec(&data, "SELECT * FROM sqlite_stat1", 0); |
| 11370 | } |
| 11371 | if( hasStat[4] ){ |
| 11372 | data.mode.spec.zTableName = "sqlite_stat4"; |
| 11373 | shell_exec(&data, "SELECT * FROM sqlite_stat4", 0); |
| 11374 | } |
| 11375 | cli_puts("ANALYZE sqlite_schema;\n", p->out); |
| 11376 | } |
| 11377 | }else |
| 11378 | |
| 11379 | if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){ |
| 11380 | if( nArg==2 ){ |
| 11381 | if( cli_strcmp(azArg[1],"always")==0 ){ |
| 11382 | p->mode.spec.bTitles = QRF_Always; |
| 11383 | }else{ |
| 11384 | p->mode.spec.bTitles = booleanValue(azArg[1]) ? QRF_Yes : QRF_No; |
| 11385 | } |
| 11386 | p->mode.mFlags |= MFLG_HDR; |
| 11387 | p->mode.spec.eTitle = aModeInfo[p->mode.eMode].eHdr; |
| 11388 | }else{ |
| 11389 | eputz("Usage: .headers off|on|always\n"); |
| 11390 | rc = 1; |
| 11391 | } |
| 11392 | }else |
| 11393 | |
| 11394 | if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){ |
| 11395 | if( nArg>=2 ){ |
| 11396 | n = showHelp(p->out, azArg[1]); |
| 11397 | if( n==0 ){ |
| 11398 | cli_printf(p->out, "Nothing matches '%s'\n", azArg[1]); |
| 11399 | } |
| 11400 | }else{ |
| 11401 | showHelp(p->out, 0); |
| 11402 | } |
| 11403 | }else |
| 11404 | |
| 11405 | if( c=='i' && n==2 && cli_strcmp(azArg[0],"if")==0 ){ |
| 11406 | rc = dotCmdIf(p); |
| 11407 | }else |
| 11408 | |
| 11409 | #ifndef SQLITE_SHELL_FIDDLE |
| 11410 | if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){ |
| 11411 | rc = dotCmdImport(p); |
| 11412 | }else |
| 11413 | #endif /* !defined(SQLITE_SHELL_FIDDLE) */ |
| 11414 | |
| 11415 | #ifndef SQLITE_UNTESTABLE |
| 11416 | if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){ |
| 11417 | char *zSql; |
| 11418 | char *zCollist = 0; |
| 11419 | sqlite3_stmt *pStmt; |
| 11420 | int tnum = 0; |
| 11421 | int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */ |
| 11422 | int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */ |
| 11423 | int i; |
| 11424 | if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){ |
| 11425 | eputz("Usage: .imposter INDEX IMPOSTER\n" |
| 11426 | " .imposter off\n"); |
| 11427 | /* Also allowed, but not documented: |
| 11428 | ** |
| 11429 | ** .imposter TABLE IMPOSTER |
| 11430 | ** |
| 11431 | ** where TABLE is a WITHOUT ROWID table. In that case, the |
| 11432 | ** imposter is another WITHOUT ROWID table with the columns in |
| 11433 | ** storage order. */ |
| 11434 | rc = 1; |
| 11435 | goto meta_command_exit; |
| 11436 | } |
| 11437 | open_db(p, 0); |
| 11438 | if( nArg==2 ){ |
| 11439 | sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1); |
| 11440 | goto meta_command_exit; |
| 11441 | } |
| 11442 | zSql = sqlite3_mprintf( |
| 11443 | "SELECT rootpage, 0 FROM sqlite_schema" |
| 11444 | " WHERE type='index' AND lower(name)=lower('%q')" |
| 11445 | "UNION ALL " |
| 11446 | "SELECT rootpage, 1 FROM sqlite_schema" |
| 11447 | " WHERE type='table' AND lower(name)=lower('%q')" |
| 11448 | " AND sql LIKE '%%without%%rowid%%'", |
| 11449 | azArg[1], azArg[1] |
| 11450 | ); |
| 11451 | sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); |
| 11452 | sqlite3_free(zSql); |
| 11453 | if( sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 11454 | tnum = sqlite3_column_int(pStmt, 0); |
| 11455 | isWO = sqlite3_column_int(pStmt, 1); |
| 11456 | } |
| 11457 | sqlite3_finalize(pStmt); |
| 11458 | zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]); |
| 11459 | rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); |
| 11460 | sqlite3_free(zSql); |
| 11461 | i = 0; |
| 11462 | while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 11463 | char zLabel[20]; |
| 11464 | const char *zCol = (const char*)sqlite3_column_text(pStmt,2); |
| 11465 | i++; |
| 11466 | if( zCol==0 ){ |
| 11467 | if( sqlite3_column_int(pStmt,1)==-1 ){ |
| 11468 | zCol = "_ROWID_"; |
| 11469 | }else{ |
| 11470 | sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i); |
| 11471 | zCol = zLabel; |
| 11472 | } |
| 11473 | } |
| 11474 | if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){ |
| 11475 | lenPK = (int)strlen(zCollist); |
| 11476 | } |
| 11477 | if( zCollist==0 ){ |
| 11478 | zCollist = sqlite3_mprintf("\"%w\"", zCol); |
| 11479 | }else{ |
| 11480 | zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol); |
| 11481 | } |
| 11482 | } |
| 11483 | sqlite3_finalize(pStmt); |
| 11484 | if( i==0 || tnum==0 ){ |
| 11485 | cli_printf(stderr,"no such index: \"%s\"\n", azArg[1]); |
| 11486 | rc = 1; |
| 11487 | sqlite3_free(zCollist); |
| 11488 | goto meta_command_exit; |
| 11489 | } |
| 11490 | if( lenPK==0 ) lenPK = 100000; |
| 11491 | zSql = sqlite3_mprintf( |
| 11492 | "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID", |
| 11493 | azArg[2], zCollist, lenPK, zCollist); |
| 11494 | sqlite3_free(zCollist); |
| 11495 | rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 2, tnum); |
| 11496 | if( rc==SQLITE_OK ){ |
| 11497 | rc = sqlite3_exec(p->db, zSql, 0, 0, 0); |
| 11498 | sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0); |
| 11499 | if( rc ){ |
| 11500 | cli_printf(stderr, |
| 11501 | "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db)); |
| 11502 | }else{ |
| 11503 | cli_printf(stdout, "%s;\n", zSql); |
| 11504 | } |
| 11505 | }else{ |
| 11506 | cli_printf(stderr,"SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc); |
| 11507 | rc = 1; |
| 11508 | } |
| 11509 | sqlite3_free(zSql); |
| 11510 | }else |
| 11511 | #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */ |
| 11512 | |
| 11513 | if( c=='i' && (cli_strncmp(azArg[0], "indices", n)==0 |
| 11514 | || cli_strncmp(azArg[0], "indexes", n)==0) |
| 11515 | ){ |
| 11516 | sqlite3_str *pSql; |
| 11517 | int i; |
| 11518 | int allFlag = 0; |
| 11519 | int sysFlag = 0; |
| 11520 | int exprFlag = 0; |
| 11521 | int debugFlag = 0; /* Undocument --debug flag */ |
| 11522 | const char *zPattern = 0; |
| 11523 | const char *zSep = "WHERE"; |
| 11524 | |
| 11525 | for(i=1; i<nArg; i++){ |
| 11526 | if( azArg[i][0]=='-' ){ |
| 11527 | const char *z = azArg[i]+1; |
| 11528 | if( z[0]=='-' ) z++; |
| 11529 | if( cli_strcmp(z,"all")==0 || cli_strcmp(z,"a")==0 ){ |
| 11530 | allFlag = 1; |
| 11531 | }else |
| 11532 | if( cli_strcmp(z,"sys")==0 ){ |
| 11533 | sysFlag = 1; |
| 11534 | allFlag = 0; |
| 11535 | }else |
| 11536 | if( cli_strcmp(z,"expr")==0 ){ |
| 11537 | exprFlag = 1; |
| 11538 | allFlag = 0; |
| 11539 | }else |
| 11540 | if( cli_strcmp(z,"debug")==0 ){ |
| 11541 | debugFlag = 1; |
| 11542 | }else |
| 11543 | { |
| 11544 | dotCmdError(p, i, "unknown option", 0); |
| 11545 | rc = 1; |
| 11546 | goto meta_command_exit; |
| 11547 | } |
| 11548 | }else if( zPattern==0 ){ |
| 11549 | zPattern = azArg[i]; |
| 11550 | }else{ |
| 11551 | dotCmdError(p, i, "unknown argument", 0); |
| 11552 | rc = 1; |
| 11553 | goto meta_command_exit; |
| 11554 | } |
| 11555 | } |
| 11556 | |
| 11557 | open_db(p, 0); |
| 11558 | pSql = sqlite3_str_new(p->db); |
| 11559 | sqlite3_str_appendf(pSql, |
| 11560 | "SELECT if(t.schema='main',i.name,t.schema||'.'||i.name)\n" |
| 11561 | "FROM pragma_table_list t, pragma_index_list(t.name,t.schema) i\n" |
| 11562 | ); |
| 11563 | if( exprFlag ){ |
| 11564 | allFlag = 0; |
| 11565 | sqlite3_str_appendf(pSql, |
| 11566 | "%s (EXISTS(SELECT 1 FROM pragma_index_xinfo(i.name) WHERE cid=-2)\n" |
| 11567 | " OR\n" |
| 11568 | " EXISTS(SELECT cid FROM pragma_table_xinfo(t.name) WHERE hidden=2" |
| 11569 | " INTERSECT " |
| 11570 | " SELECT cid FROM pragma_index_info(i.name)))\n", zSep); |
| 11571 | zSep = "AND"; |
| 11572 | } |
| 11573 | if( sysFlag ){ |
| 11574 | sqlite3_str_appendf(pSql, |
| 11575 | "%s i.name LIKE 'sqlite__autoindex__%%' ESCAPE '_'\n", zSep); |
| 11576 | zSep = "AND"; |
| 11577 | }else if( !allFlag ){ |
| 11578 | sqlite3_str_appendf(pSql, |
| 11579 | "%s i.name NOT LIKE 'sqlite__%%' ESCAPE '_'\n", zSep); |
| 11580 | zSep = "AND"; |
| 11581 | } |
| 11582 | if( zPattern ){ |
| 11583 | sqlite3_str_appendf(pSql, "%s i.name LIKE '%%%q%%'\n", zSep, zPattern); |
| 11584 | } |
| 11585 | sqlite3_str_appendf(pSql, "ORDER BY 1"); |
| 11586 | |
| 11587 | /* Run the SQL statement in "split" mode. */ |
| 11588 | if( debugFlag ){ |
| 11589 | cli_printf(stdout,"%s;\n", sqlite3_str_value(pSql)); |
| 11590 | }else{ |
| 11591 | modePush(p); |
| 11592 | modeChange(p, MODE_Split); |
| 11593 | shell_exec(p, sqlite3_str_value(pSql), 0); |
| 11594 | modePop(p); |
| 11595 | } |
| 11596 | sqlite3_str_free(pSql); |
| 11597 | }else |
| 11598 | |
| 11599 | if( c=='i' && cli_strncmp(azArg[0], "intck", n)==0 ){ |
| 11600 | i64 iArg = 0; |
| 11601 | open_db(p, 0); |
| 11602 | if( nArg==2 ){ |
| 11603 | iArg = integerValue(azArg[1]); |
| 11604 | if( iArg==0 ){ |
| 11605 | if( cli_strcmp(azArg[1],"register")==0 ){ |
| 11606 | sqlite3_intck_register(p->db, 1); |
| 11607 | rc = 0; |
| 11608 | goto meta_command_exit; |
| 11609 | } |
| 11610 | iArg = -1; |
| 11611 | } |
| 11612 | } |
| 11613 | if( (nArg!=1 && nArg!=2) || iArg<0 ){ |
| 11614 | cli_printf(stderr,"%s","Usage: .intck STEPS_PER_UNLOCK\n"); |
| 11615 | rc = 1; |
| 11616 | goto meta_command_exit; |
| 11617 | } |
| 11618 | open_db(p, 0); |
| 11619 | rc = intckDatabaseCmd(p, iArg); |
| 11620 | }else |
| 11621 | |
| 11622 | #ifdef SQLITE_ENABLE_IOTRACE |
| 11623 | if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){ |
| 11624 | SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...); |
| 11625 | if( iotrace && iotrace!=stdout ) fclose(iotrace); |
| 11626 | iotrace = 0; |
| 11627 | if( nArg<2 ){ |
| 11628 | sqlite3IoTrace = 0; |
| 11629 | }else if( cli_strcmp(azArg[1], "-")==0 ){ |
| 11630 | sqlite3IoTrace = iotracePrintf; |
| 11631 | iotrace = stdout; |
| 11632 | }else{ |
| 11633 | iotrace = sqlite3_fopen(azArg[1], "w"); |
| 11634 | if( iotrace==0 ){ |
| 11635 | cli_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); |
| 11636 | sqlite3IoTrace = 0; |
| 11637 | rc = 1; |
| 11638 | }else{ |
| 11639 | sqlite3IoTrace = iotracePrintf; |
| 11640 | } |
| 11641 | } |
| 11642 | }else |
| 11643 | #endif |
| 11644 | |
| 11645 | if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){ |
| 11646 | static const struct { |
| 11647 | const char *zLimitName; /* Name of a limit */ |
| 11648 | int limitCode; /* Integer code for that limit */ |
| 11649 | } aLimit[] = { |
| 11650 | { "length", SQLITE_LIMIT_LENGTH }, |
| 11651 | { "sql_length", SQLITE_LIMIT_SQL_LENGTH }, |
| 11652 | { "column", SQLITE_LIMIT_COLUMN }, |
| 11653 | { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH }, |
| 11654 | { "parser_depth", SQLITE_LIMIT_PARSER_DEPTH }, |
| 11655 | { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT }, |
| 11656 | { "vdbe_op", SQLITE_LIMIT_VDBE_OP }, |
| 11657 | { "function_arg", SQLITE_LIMIT_FUNCTION_ARG }, |
| 11658 | { "attached", SQLITE_LIMIT_ATTACHED }, |
| 11659 | { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH }, |
| 11660 | { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER }, |
| 11661 | { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH }, |
| 11662 | { "worker_threads", SQLITE_LIMIT_WORKER_THREADS }, |
| 11663 | { "schema", SQLITE_LIMIT_SCHEMA }, |
| 11664 | { "trigger_steps", SQLITE_LIMIT_TRIGGER_STEPS }, |
| 11665 | { "ctes", SQLITE_LIMIT_CTES }, |
| 11666 | }; |
| 11667 | int i, n2; |
| 11668 | open_db(p, 0); |
| 11669 | if( nArg==1 ){ |
| 11670 | for(i=0; i<ArraySize(aLimit); i++){ |
| 11671 | cli_printf(stdout, "%20s %d\n", aLimit[i].zLimitName, |
| 11672 | sqlite3_limit(p->db, aLimit[i].limitCode, -1)); |
| 11673 | } |
| 11674 | }else if( nArg>3 ){ |
| 11675 | eputz("Usage: .limit NAME ?NEW-VALUE?\n"); |
| 11676 | rc = 1; |
| 11677 | goto meta_command_exit; |
| 11678 | }else{ |
| 11679 | int iLimit = -1; |
| 11680 | n2 = strlen30(azArg[1]); |
| 11681 | for(i=0; i<ArraySize(aLimit); i++){ |
| 11682 | if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){ |
| 11683 | if( iLimit<0 ){ |
| 11684 | iLimit = i; |
| 11685 | }else{ |
| 11686 | cli_printf(stderr,"ambiguous limit: \"%s\"\n", azArg[1]); |
| 11687 | rc = 1; |
| 11688 | goto meta_command_exit; |
| 11689 | } |
| 11690 | } |
| 11691 | } |
| 11692 | if( iLimit<0 ){ |
| 11693 | cli_printf(stderr,"unknown limit: \"%s\"\n" |
| 11694 | "enter \".limits\" with no arguments for a list.\n", |
| 11695 | azArg[1]); |
| 11696 | rc = 1; |
| 11697 | goto meta_command_exit; |
| 11698 | } |
| 11699 | if( nArg==3 ){ |
| 11700 | int v = (int)integerValue(azArg[2]); |
| 11701 | sqlite3_limit(p->db, aLimit[iLimit].limitCode, v); |
| 11702 | }else{ |
| 11703 | cli_printf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName, |
| 11704 | sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); |
| 11705 | } |
| 11706 | } |
| 11707 | }else |
| 11708 | |
| 11709 | if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){ |
| 11710 | open_db(p, 0); |
| 11711 | lintDotCommand(p, azArg, nArg); |
| 11712 | }else |
| 11713 | |
| 11714 | #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE) |
| 11715 | if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){ |
| 11716 | const char *zFile, *zProc; |
| 11717 | char *zErrMsg = 0; |
| 11718 | failIfSafeMode(p, "cannot run .load in safe mode"); |
| 11719 | if( nArg<2 || azArg[1][0]==0 ){ |
| 11720 | /* Must have a non-empty FILE. (Will not load self.) */ |
| 11721 | eputz("Usage: .load FILE ?ENTRYPOINT?\n"); |
| 11722 | rc = 1; |
| 11723 | goto meta_command_exit; |
| 11724 | } |
| 11725 | zFile = azArg[1]; |
| 11726 | zProc = nArg>=3 ? azArg[2] : 0; |
| 11727 | open_db(p, 0); |
| 11728 | rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); |
| 11729 | if( rc!=SQLITE_OK ){ |
| 11730 | shellEmitError(zErrMsg); |
| 11731 | sqlite3_free(zErrMsg); |
| 11732 | rc = 1; |
| 11733 | } |
| 11734 | }else |
| 11735 | #endif |
| 11736 | |
| 11737 | if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){ |
| 11738 | if( nArg!=2 ){ |
| 11739 | eputz("Usage: .log FILENAME\n"); |
| 11740 | rc = 1; |
| 11741 | }else{ |
| 11742 | const char *zFile = azArg[1]; |
| 11743 | if( p->bSafeMode |
| 11744 | && cli_strcmp(zFile,"on")!=0 |
| 11745 | && cli_strcmp(zFile,"off")!=0 |
| 11746 | ){ |
| 11747 | sputz(stdout, "cannot set .log to anything other" |
| 11748 | " than \"on\" or \"off\"\n"); |
| 11749 | zFile = "off"; |
| 11750 | } |
| 11751 | output_file_close(p->pLog); |
| 11752 | if( cli_strcmp(zFile,"on")==0 ) zFile = "stdout"; |
| 11753 | p->pLog = output_file_open(p, zFile); |
| 11754 | } |
| 11755 | }else |
| 11756 | |
| 11757 | if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){ |
| 11758 | rc = dotCmdMode(p); |
| 11759 | }else |
| 11760 | |
| 11761 | #ifndef SQLITE_SHELL_FIDDLE |
| 11762 | if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){ |
| 11763 | if( nArg!=2 ){ |
| 11764 | eputz("Usage: .nonce NONCE\n"); |
| 11765 | rc = 1; |
| 11766 | }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){ |
| 11767 | cli_printf(stderr,"line %lld: incorrect nonce: \"%s\"\n", |
| 11768 | p->lineno, azArg[1]); |
| 11769 | cli_exit(1); |
| 11770 | }else{ |
| 11771 | p->bSafeMode = 0; |
| 11772 | return 0; /* Return immediately to bypass the safe mode reset |
| 11773 | ** at the end of this procedure */ |
| 11774 | } |
| 11775 | }else |
| 11776 | #endif /* !defined(SQLITE_SHELL_FIDDLE) */ |
| 11777 | |
| 11778 | if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){ |
| 11779 | if( nArg==2 ){ |
| 11780 | modeSetStr(&p->mode.spec.zNull, azArg[1]); |
| 11781 | }else{ |
| 11782 | eputz("Usage: .nullvalue STRING\n"); |
| 11783 | rc = 1; |
| 11784 | } |
| 11785 | }else |
| 11786 | |
| 11787 | if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){ |
| 11788 | const char *zFN = 0; /* Pointer to constant filename */ |
| 11789 | char *zNewFilename = 0; /* Name of the database file to open */ |
| 11790 | int iName = 1; /* Index in azArg[] of the filename */ |
| 11791 | int newFlag = 0; /* True to delete file before opening */ |
| 11792 | int openMode = SHELL_OPEN_UNSPEC; |
| 11793 | int openFlags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; |
| 11794 | |
| 11795 | if( p->bSafeMode ) openFlags = SQLITE_OPEN_READONLY; |
| 11796 | |
| 11797 | /* Check for command-line arguments */ |
| 11798 | for(iName=1; iName<nArg; iName++){ |
| 11799 | const char *z = azArg[iName]; |
| 11800 | #ifndef SQLITE_SHELL_FIDDLE |
| 11801 | if( optionMatch(z,"new") ){ |
| 11802 | newFlag = 1; |
| 11803 | #ifdef SQLITE_HAVE_ZLIB |
| 11804 | }else if( optionMatch(z, "zip") && !p->bSafeMode ){ |
| 11805 | openMode = SHELL_OPEN_ZIPFILE; |
| 11806 | #endif |
| 11807 | }else if( optionMatch(z, "append") && !p->bSafeMode ){ |
| 11808 | openMode = SHELL_OPEN_APPENDVFS; |
| 11809 | }else if( optionMatch(z, "readonly") ){ |
| 11810 | openFlags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); |
| 11811 | openFlags |= SQLITE_OPEN_READONLY; |
| 11812 | }else if( optionMatch(z, "exclusive") ){ |
| 11813 | openFlags |= SQLITE_OPEN_EXCLUSIVE; |
| 11814 | }else if( optionMatch(z, "ifexists") ){ |
| 11815 | openFlags &= ~(SQLITE_OPEN_CREATE); |
| 11816 | }else if( optionMatch(z, "nofollow") ){ |
| 11817 | openFlags |= SQLITE_OPEN_NOFOLLOW; |
| 11818 | #ifndef SQLITE_OMIT_DESERIALIZE |
| 11819 | }else if( optionMatch(z, "deserialize") ){ |
| 11820 | openMode = SHELL_OPEN_DESERIALIZE; |
| 11821 | }else if( optionMatch(z, "hexdb") ){ |
| 11822 | openMode = SHELL_OPEN_HEXDB; |
| 11823 | }else if( optionMatch(z, "normal") ){ |
| 11824 | openMode = SHELL_OPEN_NORMAL; |
| 11825 | }else if( optionMatch(z, "maxsize") && iName+1<nArg ){ |
| 11826 | p->szMax = integerValue(azArg[++iName]); |
| 11827 | #endif /* SQLITE_OMIT_DESERIALIZE */ |
| 11828 | }else |
| 11829 | #endif /* !SQLITE_SHELL_FIDDLE */ |
| 11830 | if( z[0]=='-' ){ |
| 11831 | cli_printf(stderr,"unknown option: %s\n", z); |
| 11832 | rc = 1; |
| 11833 | goto meta_command_exit; |
| 11834 | }else if( zFN ){ |
| 11835 | cli_printf(stderr,"extra argument: \"%s\"\n", z); |
| 11836 | rc = 1; |
| 11837 | goto meta_command_exit; |
| 11838 | }else{ |
| 11839 | zFN = z; |
| 11840 | } |
| 11841 | } |
| 11842 | |
| 11843 | /* Close the existing database */ |
| 11844 | session_close_all(p, -1); |
| 11845 | close_db(p->db); |
| 11846 | p->db = 0; |
| 11847 | p->pAuxDb->zDbFilename = 0; |
| 11848 | sqlite3_free(p->pAuxDb->zFreeOnClose); |
| 11849 | p->pAuxDb->zFreeOnClose = 0; |
| 11850 | p->openMode = openMode; |
| 11851 | p->openFlags = openFlags; |
| 11852 | p->szMax = 0; |
| 11853 | |
| 11854 | /* If a filename is specified, try to open it first */ |
| 11855 | if( zFN || p->openMode==SHELL_OPEN_HEXDB ){ |
| 11856 | if( newFlag && zFN && !p->bSafeMode ){ |
| 11857 | if( cli_strncmp(zFN,"file:",5)==0 ){ |
| 11858 | char *zDel = shellFilenameFromUri(zFN); |
| 11859 | shell_check_oom(zDel); |
| 11860 | shellDeleteFile(zDel, 0); |
| 11861 | sqlite3_free(zDel); |
| 11862 | }else{ |
| 11863 | shellDeleteFile(zFN, 0); |
| 11864 | } |
| 11865 | } |
| 11866 | #ifndef SQLITE_SHELL_FIDDLE |
| 11867 | if( p->bSafeMode |
| 11868 | && p->openMode!=SHELL_OPEN_HEXDB |
| 11869 | && zFN |
| 11870 | && cli_strcmp(zFN,":memory:")!=0 |
| 11871 | ){ |
| 11872 | failIfSafeMode(p, "cannot open disk-based database files in safe mode"); |
| 11873 | } |
| 11874 | #else |
| 11875 | /* WASM mode has its own sandboxed pseudo-filesystem. */ |
| 11876 | #endif |
| 11877 | if( zFN ){ |
| 11878 | zNewFilename = sqlite3_mprintf("%s", zFN); |
| 11879 | shell_check_oom(zNewFilename); |
| 11880 | }else{ |
| 11881 | zNewFilename = 0; |
| 11882 | } |
| 11883 | p->pAuxDb->zDbFilename = zNewFilename; |
| 11884 | open_db(p, OPEN_DB_KEEPALIVE); |
| 11885 | if( p->db==0 ){ |
| 11886 | cli_printf(stderr,"Error: cannot open '%s'\n", zNewFilename); |
| 11887 | sqlite3_free(zNewFilename); |
| 11888 | }else{ |
| 11889 | p->pAuxDb->zFreeOnClose = zNewFilename; |
| 11890 | } |
| 11891 | } |
| 11892 | if( p->db==0 ){ |
| 11893 | /* As a fall-back open a TEMP database */ |
| 11894 | p->pAuxDb->zDbFilename = 0; |
| 11895 | open_db(p, 0); |
| 11896 | } |
| 11897 | }else |
| 11898 | |
| 11899 | #ifndef SQLITE_SHELL_FIDDLE |
| 11900 | if( (c=='o' |
| 11901 | && (cli_strncmp(azArg[0], "output", n)==0 |
| 11902 | || cli_strncmp(azArg[0], "once", n)==0)) |
| 11903 | || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0) |
| 11904 | || (c=='w' && n==3 && cli_strcmp(azArg[0],"www")==0) |
| 11905 | ){ |
| 11906 | rc = dotCmdOutput(p); |
| 11907 | }else |
| 11908 | #endif /* !defined(SQLITE_SHELL_FIDDLE) */ |
| 11909 | |
| 11910 | if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){ |
| 11911 | open_db(p,0); |
| 11912 | if( nArg<=1 ) goto parameter_syntax_error; |
| 11913 | |
| 11914 | /* .parameter clear |
| 11915 | ** Clear all bind parameters by dropping the TEMP table that holds them. |
| 11916 | */ |
| 11917 | if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){ |
| 11918 | sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;", |
| 11919 | 0, 0, 0); |
| 11920 | }else |
| 11921 | |
| 11922 | /* .parameter list |
| 11923 | ** List all bind parameters. |
| 11924 | */ |
| 11925 | if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){ |
| 11926 | sqlite3_stmt *pStmt = 0; |
| 11927 | int rx; |
| 11928 | int len = 0; |
| 11929 | rx = sqlite3_prepare_v2(p->db, |
| 11930 | "SELECT max(length(key)) " |
| 11931 | "FROM temp.sqlite_parameters;", -1, &pStmt, 0); |
| 11932 | if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 11933 | len = sqlite3_column_int(pStmt, 0); |
| 11934 | if( len>40 ) len = 40; |
| 11935 | } |
| 11936 | sqlite3_finalize(pStmt); |
| 11937 | pStmt = 0; |
| 11938 | if( len ){ |
| 11939 | rx = sqlite3_prepare_v2(p->db, |
| 11940 | "SELECT key, quote(value) " |
| 11941 | "FROM temp.sqlite_parameters;", -1, &pStmt, 0); |
| 11942 | while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 11943 | cli_printf(p->out, |
| 11944 | "%-*s %s\n", len, sqlite3_column_text(pStmt,0), |
| 11945 | sqlite3_column_text(pStmt,1)); |
| 11946 | } |
| 11947 | sqlite3_finalize(pStmt); |
| 11948 | } |
| 11949 | }else |
| 11950 | |
| 11951 | /* .parameter init |
| 11952 | ** Make sure the TEMP table used to hold bind parameters exists. |
| 11953 | ** Create it if necessary. |
| 11954 | */ |
| 11955 | if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){ |
| 11956 | bind_table_init(p); |
| 11957 | }else |
| 11958 | |
| 11959 | /* .parameter set NAME VALUE |
| 11960 | ** Set or reset a bind parameter. NAME should be the full parameter |
| 11961 | ** name exactly as it appears in the query. (ex: $abc, @def). The |
| 11962 | ** VALUE can be in either SQL literal notation, or if not it will be |
| 11963 | ** understood to be a text string. |
| 11964 | */ |
| 11965 | if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){ |
| 11966 | int rx; |
| 11967 | char *zSql; |
| 11968 | sqlite3_stmt *pStmt; |
| 11969 | const char *zKey = azArg[2]; |
| 11970 | const char *zValue = azArg[3]; |
| 11971 | bind_table_init(p); |
| 11972 | zSql = sqlite3_mprintf( |
| 11973 | "REPLACE INTO temp.sqlite_parameters(key,value)" |
| 11974 | "VALUES(%Q,%s);", zKey, zValue); |
| 11975 | shell_check_oom(zSql); |
| 11976 | pStmt = 0; |
| 11977 | rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); |
| 11978 | sqlite3_free(zSql); |
| 11979 | if( rx!=SQLITE_OK ){ |
| 11980 | sqlite3_finalize(pStmt); |
| 11981 | pStmt = 0; |
| 11982 | zSql = sqlite3_mprintf( |
| 11983 | "REPLACE INTO temp.sqlite_parameters(key,value)" |
| 11984 | "VALUES(%Q,%Q);", zKey, zValue); |
| 11985 | shell_check_oom(zSql); |
| 11986 | rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); |
| 11987 | sqlite3_free(zSql); |
| 11988 | if( rx!=SQLITE_OK ){ |
| 11989 | cli_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db)); |
| 11990 | sqlite3_finalize(pStmt); |
| 11991 | pStmt = 0; |
| 11992 | rc = 1; |
| 11993 | } |
| 11994 | } |
| 11995 | bind_prepared_stmt(p, pStmt); |
| 11996 | sqlite3_step(pStmt); |
| 11997 | sqlite3_finalize(pStmt); |
| 11998 | }else |
| 11999 | |
| 12000 | /* .parameter unset NAME |
| 12001 | ** Remove the NAME binding from the parameter binding table, if it |
| 12002 | ** exists. |
| 12003 | */ |
| 12004 | if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){ |
| 12005 | char *zSql = sqlite3_mprintf( |
| 12006 | "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]); |
| 12007 | shell_check_oom(zSql); |
| 12008 | sqlite3_exec(p->db, zSql, 0, 0, 0); |
| 12009 | sqlite3_free(zSql); |
| 12010 | }else |
| 12011 | /* If no command name matches, show a syntax error */ |
| 12012 | parameter_syntax_error: |
| 12013 | showHelp(p->out, "parameter"); |
| 12014 | }else |
| 12015 | |
| 12016 | if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){ |
| 12017 | int i; |
| 12018 | for(i=1; i<nArg; i++){ |
| 12019 | if( i>1 ) cli_puts(" ", p->out); |
| 12020 | cli_puts(azArg[i], p->out); |
| 12021 | } |
| 12022 | cli_puts("\n", p->out); |
| 12023 | }else |
| 12024 | |
| 12025 | #ifndef SQLITE_OMIT_PROGRESS_CALLBACK |
| 12026 | if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){ |
| 12027 | int i; |
| 12028 | int nn = 0; |
| 12029 | p->flgProgress = 0; |
| 12030 | p->mxProgress = 0; |
| 12031 | p->nProgress = 0; |
| 12032 | for(i=1; i<nArg; i++){ |
| 12033 | const char *z = azArg[i]; |
| 12034 | if( z[0]=='-' ){ |
| 12035 | z++; |
| 12036 | if( z[0]=='-' ) z++; |
| 12037 | if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){ |
| 12038 | p->flgProgress |= SHELL_PROGRESS_QUIET; |
| 12039 | continue; |
| 12040 | } |
| 12041 | if( cli_strcmp(z,"reset")==0 ){ |
| 12042 | p->flgProgress |= SHELL_PROGRESS_RESET; |
| 12043 | continue; |
| 12044 | } |
| 12045 | if( cli_strcmp(z,"once")==0 ){ |
| 12046 | p->flgProgress |= SHELL_PROGRESS_ONCE; |
| 12047 | continue; |
| 12048 | } |
| 12049 | if( cli_strcmp(z,"timeout")==0 ){ |
| 12050 | if( i==nArg-1 ){ |
| 12051 | dotCmdError(p, i, "missing argument", 0); |
| 12052 | return 1; |
| 12053 | } |
| 12054 | i++; |
| 12055 | p->tmProgress = atof(azArg[i]); |
| 12056 | if( p->tmProgress>0.0 ){ |
| 12057 | p->flgProgress = SHELL_PROGRESS_QUIET|SHELL_PROGRESS_TMOUT; |
| 12058 | if( nn==0 ) nn = 100; |
| 12059 | } |
| 12060 | continue; |
| 12061 | } |
| 12062 | if( cli_strcmp(z,"limit")==0 ){ |
| 12063 | if( i+1>=nArg ){ |
| 12064 | eputz("Error: missing argument on --limit\n"); |
| 12065 | rc = 1; |
| 12066 | goto meta_command_exit; |
| 12067 | }else{ |
| 12068 | p->mxProgress = (int)integerValue(azArg[++i]); |
| 12069 | } |
| 12070 | continue; |
| 12071 | } |
| 12072 | cli_printf(stderr,"Error: unknown option: \"%s\"\n", azArg[i]); |
| 12073 | rc = 1; |
| 12074 | goto meta_command_exit; |
| 12075 | }else{ |
| 12076 | nn = (int)integerValue(z); |
| 12077 | } |
| 12078 | } |
| 12079 | open_db(p, 0); |
| 12080 | sqlite3_progress_handler(p->db, nn, progress_handler, p); |
| 12081 | }else |
| 12082 | #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ |
| 12083 | |
| 12084 | if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){ |
| 12085 | int i; |
| 12086 | int cnt = 0; |
| 12087 | int noOpt = 0; |
| 12088 | for(i=1; i<nArg; i++){ |
| 12089 | const char *z = azArg[i]; |
| 12090 | if( z[0]=='-' && !noOpt ){ |
| 12091 | if( z[1]=='-' ) z++; |
| 12092 | if( strcmp(z,"-hard-reset")==0 ){ |
| 12093 | #ifdef _WIN32 |
| 12094 | _putenv("SQLITE_PS1="); |
| 12095 | _putenv("SQLITE_PS2="); |
| 12096 | #else |
| 12097 | unsetenv("SQLITE_PS1"); |
| 12098 | unsetenv("SQLITE_PS2"); |
| 12099 | #endif |
| 12100 | z += 5; |
| 12101 | } |
| 12102 | if( strcmp(z,"-reset")==0 ){ |
| 12103 | free(p->azPrompt[0]); |
| 12104 | free(p->azPrompt[1]); |
| 12105 | memset(p->azPrompt, 0, sizeof(p->azPrompt)); |
| 12106 | }else |
| 12107 | if( strcmp(z,"-show")==0 ){ |
| 12108 | cli_printf(stdout,"Main prompt: '%s'\n", prompt_string(p, 0)); |
| 12109 | cli_printf(stdout,"Continuation: '%s'\n", prompt_string(p, 1)); |
| 12110 | }else |
| 12111 | #ifndef SQLITE_NO_COLOR |
| 12112 | if( strcmp(z,"-color")==0 ){ |
| 12113 | #ifdef _WIN32 |
| 12114 | _putenv("NO_COLOR="); |
| 12115 | #else |
| 12116 | unsetenv("NO_COLOR"); |
| 12117 | #endif |
| 12118 | }else |
| 12119 | if( strcmp(z,"-no-color")==0 ){ |
| 12120 | #ifdef _WIN32 |
| 12121 | _putenv("NO_COLOR=1"); |
| 12122 | #else |
| 12123 | setenv("NO_COLOR","1",1); |
| 12124 | #endif |
| 12125 | }else |
| 12126 | #endif |
| 12127 | if( strcmp(z,"-")==0 ){ |
| 12128 | noOpt = 1; |
| 12129 | }else |
| 12130 | { |
| 12131 | dotCmdError(p, i, "unknown option", 0); |
| 12132 | rc = 1; |
| 12133 | goto meta_command_exit; |
| 12134 | } |
| 12135 | }else if( cnt>1 ){ |
| 12136 | dotCmdError(p, i, "extra argument", 0); |
| 12137 | rc = 1; |
| 12138 | goto meta_command_exit; |
| 12139 | }else if( !p->dot.abQuot[i] && sqlite3_strglob("*[^a-z]*",z)!=0 ){ |
| 12140 | dotCmdError(p, i, "use quotes around the prompt string", 0); |
| 12141 | rc = 1; |
| 12142 | }else{ |
| 12143 | free(p->azPrompt[cnt]); |
| 12144 | p->azPrompt[cnt] = strdup(z); |
| 12145 | cnt++; |
| 12146 | } |
| 12147 | } |
| 12148 | }else |
| 12149 | |
| 12150 | #ifndef SQLITE_SHELL_FIDDLE |
| 12151 | if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){ |
| 12152 | rc = 2; |
| 12153 | }else |
| 12154 | #endif |
| 12155 | |
| 12156 | #ifndef SQLITE_SHELL_FIDDLE |
| 12157 | if( c=='r' && n==4 && cli_strcmp(azArg[0], "read")==0 ){ |
| 12158 | FILE *inSaved = p->in; |
| 12159 | i64 savedLineno = p->lineno; |
| 12160 | if( p->mIf ){ |
| 12161 | if( nArg==2 && isHereDoc(azArg[1]) ){ |
| 12162 | sqlite3_free(captureHereDoc(p, azArg[1]+2)); |
| 12163 | } |
| 12164 | return 0; |
| 12165 | } |
| 12166 | if( nArg!=2 ){ |
| 12167 | eputz("Usage: .read FILE\n"); |
| 12168 | rc = 1; |
| 12169 | goto meta_command_exit; |
| 12170 | } |
| 12171 | if( !isHereDoc(azArg[1]) ){ |
| 12172 | failIfSafeMode(p, "cannot run .read in safe mode"); |
| 12173 | } |
| 12174 | if( azArg[1][0]=='|' ){ |
| 12175 | #ifdef SQLITE_OMIT_POPEN |
| 12176 | eputz("Error: pipes are not supported in this OS\n"); |
| 12177 | rc = 1; |
| 12178 | #else |
| 12179 | p->in = sqlite3_popen(azArg[1]+1, "r"); |
| 12180 | if( p->in==0 ){ |
| 12181 | cli_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); |
| 12182 | rc = 1; |
| 12183 | }else{ |
| 12184 | rc = process_input(p, "<pipe>"); |
| 12185 | pclose(p->in); |
| 12186 | } |
| 12187 | #endif |
| 12188 | }else if( isHereDoc(azArg[1]) ){ |
| 12189 | char *saved_zInput; |
| 12190 | i64 saved_nInputUsed; |
| 12191 | char *zScript = captureHereDoc(p, azArg[1]+2); |
| 12192 | savedLineno = p->lineno; |
| 12193 | saved_zInput = p->zInput; |
| 12194 | saved_nInputUsed = p->nInputUsed; |
| 12195 | p->zInput = zScript; |
| 12196 | p->nInputUsed = 0; |
| 12197 | p->in = (FILE*)&p->zInput; |
| 12198 | rc = process_input(p, "<heredoc>"); |
| 12199 | sqlite3_free(p->zInput); |
| 12200 | p->zInput = saved_zInput; |
| 12201 | p->nInputUsed = saved_nInputUsed; |
| 12202 | }else if( (p->in = openChrSource(azArg[1]))==0 ){ |
| 12203 | cli_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); |
| 12204 | rc = 1; |
| 12205 | }else{ |
| 12206 | char *zFilename = strdup(azArg[1]); |
| 12207 | rc = process_input(p, zFilename); |
| 12208 | free(zFilename); |
| 12209 | fclose(p->in); |
| 12210 | } |
| 12211 | p->in = inSaved; |
| 12212 | p->lineno = savedLineno; |
| 12213 | }else |
| 12214 | #endif /* !defined(SQLITE_SHELL_FIDDLE) */ |
| 12215 | |
| 12216 | #if SQLITE_SHELL_HAVE_RECOVER |
| 12217 | if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){ |
| 12218 | open_db(p, 0); |
| 12219 | rc = recoverDatabaseCmd(p, nArg, azArg); |
| 12220 | }else |
| 12221 | #endif /* SQLITE_SHELL_HAVE_RECOVER */ |
| 12222 | |
| 12223 | #ifndef SQLITE_SHELL_FIDDLE |
| 12224 | if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){ |
| 12225 | const char *zSrcFile; |
| 12226 | const char *zDb; |
| 12227 | sqlite3 *pSrc; |
| 12228 | sqlite3_backup *pBackup; |
| 12229 | int nTimeout = 0; |
| 12230 | |
| 12231 | failIfSafeMode(p, "cannot run .restore in safe mode"); |
| 12232 | if( nArg==2 ){ |
| 12233 | zSrcFile = azArg[1]; |
| 12234 | zDb = "main"; |
| 12235 | }else if( nArg==3 ){ |
| 12236 | zSrcFile = azArg[2]; |
| 12237 | zDb = azArg[1]; |
| 12238 | }else{ |
| 12239 | eputz("Usage: .restore ?DB? FILE\n"); |
| 12240 | rc = 1; |
| 12241 | goto meta_command_exit; |
| 12242 | } |
| 12243 | rc = sqlite3_open(zSrcFile, &pSrc); |
| 12244 | if( rc!=SQLITE_OK ){ |
| 12245 | cli_printf(stderr,"Error: cannot open \"%s\"\n", zSrcFile); |
| 12246 | close_db(pSrc); |
| 12247 | return 1; |
| 12248 | } |
| 12249 | open_db(p, 0); |
| 12250 | pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); |
| 12251 | if( pBackup==0 ){ |
| 12252 | shellDatabaseError(p->db); |
| 12253 | close_db(pSrc); |
| 12254 | return 1; |
| 12255 | } |
| 12256 | while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK |
| 12257 | || rc==SQLITE_BUSY ){ |
| 12258 | if( rc==SQLITE_BUSY ){ |
| 12259 | if( nTimeout++ >= 3 ) break; |
| 12260 | sqlite3_sleep(100); |
| 12261 | } |
| 12262 | } |
| 12263 | sqlite3_backup_finish(pBackup); |
| 12264 | if( rc==SQLITE_DONE ){ |
| 12265 | rc = 0; |
| 12266 | }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ |
| 12267 | eputz("Error: source database is busy\n"); |
| 12268 | rc = 1; |
| 12269 | }else{ |
| 12270 | shellDatabaseError(p->db); |
| 12271 | rc = 1; |
| 12272 | } |
| 12273 | close_db(pSrc); |
| 12274 | }else |
| 12275 | #endif /* !defined(SQLITE_SHELL_FIDDLE) */ |
| 12276 | |
| 12277 | if( c=='s' && cli_strcmp(azArg[0], "safe")==0 ){ |
| 12278 | rc = dotCmdSafe(p); |
| 12279 | }else |
| 12280 | |
| 12281 | if( c=='s' && |
| 12282 | (cli_strncmp(azArg[0], "scanstats", n)==0 || |
| 12283 | cli_strncmp(azArg[0], "scanstatus", n)==0) |
| 12284 | ){ |
| 12285 | if( nArg==2 ){ |
| 12286 | if( cli_strcmp(azArg[1], "vm")==0 ){ |
| 12287 | p->mode.scanstatsOn = 3; |
| 12288 | }else |
| 12289 | if( cli_strcmp(azArg[1], "est")==0 ){ |
| 12290 | p->mode.scanstatsOn = 2; |
| 12291 | }else{ |
| 12292 | p->mode.scanstatsOn = (u8)booleanValue(azArg[1]); |
| 12293 | } |
| 12294 | open_db(p, 0); |
| 12295 | sqlite3_db_config( |
| 12296 | p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->mode.scanstatsOn, (int*)0 |
| 12297 | ); |
| 12298 | #if !defined(SQLITE_ENABLE_STMT_SCANSTATUS) |
| 12299 | eputz("Warning: .scanstats not available in this build.\n"); |
| 12300 | #elif !defined(SQLITE_ENABLE_BYTECODE_VTAB) |
| 12301 | if( p->mode.scanstatsOn==3 ){ |
| 12302 | eputz("Warning: \".scanstats vm\" not available in this build.\n"); |
| 12303 | } |
| 12304 | #endif |
| 12305 | }else{ |
| 12306 | eputz("Usage: .scanstats on|off|est\n"); |
| 12307 | rc = 1; |
| 12308 | } |
| 12309 | }else |
| 12310 | |
| 12311 | if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){ |
| 12312 | ShellState data; |
| 12313 | char *zErrMsg = 0; |
| 12314 | const char *zDiv = "("; |
| 12315 | const char *zName = 0; |
| 12316 | int iSchema = 0; |
| 12317 | int bDebug = 0; |
| 12318 | int bNoSystemTabs = 0; |
| 12319 | int bIndent = 0; |
| 12320 | int ii; |
| 12321 | sqlite3_str *pSql; |
| 12322 | sqlite3_stmt *pStmt = 0; |
| 12323 | |
| 12324 | open_db(p, 0); |
| 12325 | memcpy(&data, p, sizeof(data)); |
| 12326 | data.mode.spec.bTitles = QRF_No; |
| 12327 | data.mode.eMode = MODE_List; |
| 12328 | data.mode.spec.eText = QRF_TEXT_Plain; |
| 12329 | data.mode.spec.nCharLimit = 0; |
| 12330 | data.mode.spec.zRowSep = "\n"; |
| 12331 | for(ii=1; ii<nArg; ii++){ |
| 12332 | if( optionMatch(azArg[ii],"indent") ){ |
| 12333 | bIndent = 1; |
| 12334 | }else if( optionMatch(azArg[ii],"debug") ){ |
| 12335 | bDebug = 1; |
| 12336 | }else if( optionMatch(azArg[ii],"nosys") ){ |
| 12337 | bNoSystemTabs = 1; |
| 12338 | }else if( azArg[ii][0]=='-' ){ |
| 12339 | cli_printf(stderr,"Unknown option: \"%s\"\n", azArg[ii]); |
| 12340 | rc = 1; |
| 12341 | goto meta_command_exit; |
| 12342 | }else if( zName==0 ){ |
| 12343 | zName = azArg[ii]; |
| 12344 | }else{ |
| 12345 | eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n"); |
| 12346 | rc = 1; |
| 12347 | goto meta_command_exit; |
| 12348 | } |
| 12349 | } |
| 12350 | if( zName!=0 ){ |
| 12351 | int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0 |
| 12352 | || sqlite3_strlike(zName, "sqlite_schema", '\\')==0 |
| 12353 | || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 |
| 12354 | || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0; |
| 12355 | if( isSchema ){ |
| 12356 | cli_printf(p->out, |
| 12357 | "CREATE TABLE %ssqlite_schema (\n" |
| 12358 | " type text,\n" |
| 12359 | " name text,\n" |
| 12360 | " tbl_name text,\n" |
| 12361 | " rootpage integer,\n" |
| 12362 | " sql text\n" |
| 12363 | ");\n", |
| 12364 | sqlite3_strlike("sqlite_t%",zName,0)==0 ? "temp." : "" |
| 12365 | ); |
| 12366 | } |
| 12367 | } |
| 12368 | rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); |
| 12369 | if( rc ){ |
| 12370 | shellDatabaseError(p->db); |
| 12371 | sqlite3_finalize(pStmt); |
| 12372 | |
| 12373 | rc = 1; |
| 12374 | goto meta_command_exit; |
| 12375 | } |
| 12376 | pSql = sqlite3_str_new(p->db); |
| 12377 | sqlite3_str_appendf(pSql, "SELECT shell_complete_sql(sql,1) FROM", 0); |
| 12378 | iSchema = 0; |
| 12379 | while( sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 12380 | const char *zDb = (const char*)sqlite3_column_text(pStmt, 1); |
| 12381 | char zScNum[30]; |
| 12382 | sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema); |
| 12383 | sqlite3_str_appendall(pSql, zDiv); |
| 12384 | zDiv = " UNION ALL "; |
| 12385 | if( sqlite3_stricmp(zDb, "main")==0 ){ |
| 12386 | sqlite3_str_appendf(pSql, |
| 12387 | "SELECT shell_format_schema(shell_add_schema(sql,NULL,name),%d)", |
| 12388 | bIndent); |
| 12389 | }else{ |
| 12390 | sqlite3_str_appendf(pSql, |
| 12391 | "SELECT shell_format_schema(shell_add_schema(sql,%Q,name),%d)", |
| 12392 | zDb, bIndent); |
| 12393 | } |
| 12394 | sqlite3_str_appendf(pSql, |
| 12395 | " AS sql, type, tbl_name, name, rowid, %d AS snum, %Q as sname", |
| 12396 | ++iSchema, zDb); |
| 12397 | sqlite3_str_appendf(pSql," FROM \"%w\".sqlite_schema", zDb); |
| 12398 | } |
| 12399 | sqlite3_finalize(pStmt); |
| 12400 | #if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS) \ |
| 12401 | && !defined(SQLITE_OMIT_VIRTUALTABLE) |
| 12402 | if( zName ){ |
| 12403 | sqlite3_str_appendall(pSql, |
| 12404 | " UNION ALL SELECT shell_module_schema(name)," |
| 12405 | " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list"); |
| 12406 | } |
| 12407 | #endif |
| 12408 | sqlite3_str_appendf(pSql, ") WHERE ", 0); |
| 12409 | if( zName ){ |
| 12410 | int bGlob; |
| 12411 | bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 || |
| 12412 | strchr(zName, '[') != 0; |
| 12413 | if( strchr(zName, '.') ){ |
| 12414 | sqlite3_str_appendall(pSql, "lower(format('%%s.%%s',sname,tbl_name))"); |
| 12415 | }else{ |
| 12416 | sqlite3_str_appendall(pSql, "lower(tbl_name)"); |
| 12417 | } |
| 12418 | if( bGlob ){ |
| 12419 | sqlite3_str_appendf(pSql, " GLOB %Q AND ", zName); |
| 12420 | }else{ |
| 12421 | sqlite3_str_appendf(pSql, " LIKE %Q ESCAPE '\\' AND ", zName); |
| 12422 | } |
| 12423 | } |
| 12424 | if( bNoSystemTabs ){ |
| 12425 | sqlite3_str_appendf(pSql, " name NOT LIKE 'sqlite__%%' ESCAPE '_' AND "); |
| 12426 | } |
| 12427 | sqlite3_str_appendf(pSql, "sql IS NOT NULL ORDER BY snum, rowid"); |
| 12428 | if( bDebug ){ |
| 12429 | cli_printf(p->out, "SQL: %s;\n", sqlite3_str_value(pSql)); |
| 12430 | }else{ |
| 12431 | rc = shell_exec(&data, sqlite3_str_value(pSql), &zErrMsg); |
| 12432 | } |
| 12433 | sqlite3_str_free(pSql); |
| 12434 | |
| 12435 | if( zErrMsg ){ |
| 12436 | shellEmitError(zErrMsg); |
| 12437 | sqlite3_free(zErrMsg); |
| 12438 | rc = 1; |
| 12439 | }else if( rc != SQLITE_OK ){ |
| 12440 | eputz("Error: querying schema information\n"); |
| 12441 | rc = 1; |
| 12442 | }else{ |
| 12443 | rc = 0; |
| 12444 | } |
| 12445 | }else |
| 12446 | |
| 12447 | if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0) |
| 12448 | || (c=='t' && n==9 && cli_strncmp(azArg[0], "treetrace", n)==0) |
| 12449 | ){ |
| 12450 | unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff; |
| 12451 | sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x); |
| 12452 | }else |
| 12453 | |
| 12454 | #if defined(SQLITE_ENABLE_SESSION) |
| 12455 | if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){ |
| 12456 | struct AuxDb *pAuxDb = p->pAuxDb; |
| 12457 | OpenSession *pSession = &pAuxDb->aSession[0]; |
| 12458 | char **azCmd = &azArg[1]; |
| 12459 | int iSes = 0; |
| 12460 | int nCmd = nArg - 1; |
| 12461 | int i; |
| 12462 | if( nArg<=1 ) goto session_syntax_error; |
| 12463 | open_db(p, 0); |
| 12464 | if( nArg>=3 ){ |
| 12465 | for(iSes=0; iSes<pAuxDb->nSession; iSes++){ |
| 12466 | if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break; |
| 12467 | } |
| 12468 | if( iSes<pAuxDb->nSession ){ |
| 12469 | pSession = &pAuxDb->aSession[iSes]; |
| 12470 | azCmd++; |
| 12471 | nCmd--; |
| 12472 | }else{ |
| 12473 | pSession = &pAuxDb->aSession[0]; |
| 12474 | iSes = 0; |
| 12475 | } |
| 12476 | } |
| 12477 | |
| 12478 | /* .session attach TABLE |
| 12479 | ** Invoke the sqlite3session_attach() interface to attach a particular |
| 12480 | ** table so that it is never filtered. |
| 12481 | */ |
| 12482 | if( cli_strcmp(azCmd[0],"attach")==0 ){ |
| 12483 | if( nCmd!=2 ) goto session_syntax_error; |
| 12484 | if( pSession->p==0 ){ |
| 12485 | session_not_open: |
| 12486 | eputz("ERROR: No sessions are open\n"); |
| 12487 | }else{ |
| 12488 | rc = sqlite3session_attach(pSession->p, azCmd[1]); |
| 12489 | if( rc ){ |
| 12490 | cli_printf(stderr, |
| 12491 | "ERROR: sqlite3session_attach() returns %d\n",rc); |
| 12492 | rc = 0; |
| 12493 | } |
| 12494 | } |
| 12495 | }else |
| 12496 | |
| 12497 | /* .session changeset FILE |
| 12498 | ** .session patchset FILE |
| 12499 | ** Write a changeset or patchset into a file. The file is overwritten. |
| 12500 | */ |
| 12501 | if( cli_strcmp(azCmd[0],"changeset")==0 |
| 12502 | || cli_strcmp(azCmd[0],"patchset")==0 |
| 12503 | ){ |
| 12504 | FILE *out = 0; |
| 12505 | failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]); |
| 12506 | if( nCmd!=2 ) goto session_syntax_error; |
| 12507 | if( pSession->p==0 ) goto session_not_open; |
| 12508 | out = sqlite3_fopen(azCmd[1], "wb"); |
| 12509 | if( out==0 ){ |
| 12510 | cli_printf(stderr,"ERROR: cannot open \"%s\" for writing\n", |
| 12511 | azCmd[1]); |
| 12512 | }else{ |
| 12513 | int szChng; |
| 12514 | void *pChng; |
| 12515 | if( azCmd[0][0]=='c' ){ |
| 12516 | rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); |
| 12517 | }else{ |
| 12518 | rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); |
| 12519 | } |
| 12520 | if( rc ){ |
| 12521 | cli_printf(stdout, "Error: error code %d\n", rc); |
| 12522 | rc = 0; |
| 12523 | } |
| 12524 | if( pChng |
| 12525 | && fwrite(pChng, szChng, 1, out)!=1 ){ |
| 12526 | cli_printf(stderr, |
| 12527 | "ERROR: Failed to write entire %d-byte output\n", szChng); |
| 12528 | } |
| 12529 | sqlite3_free(pChng); |
| 12530 | fclose(out); |
| 12531 | } |
| 12532 | }else |
| 12533 | |
| 12534 | /* .session close |
| 12535 | ** Close the identified session |
| 12536 | */ |
| 12537 | if( cli_strcmp(azCmd[0], "close")==0 ){ |
| 12538 | if( nCmd!=1 ) goto session_syntax_error; |
| 12539 | if( pAuxDb->nSession ){ |
| 12540 | session_close(pSession); |
| 12541 | pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession]; |
| 12542 | } |
| 12543 | }else |
| 12544 | |
| 12545 | /* .session enable ?BOOLEAN? |
| 12546 | ** Query or set the enable flag |
| 12547 | */ |
| 12548 | if( cli_strcmp(azCmd[0], "enable")==0 ){ |
| 12549 | int ii; |
| 12550 | if( nCmd>2 ) goto session_syntax_error; |
| 12551 | ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); |
| 12552 | if( pAuxDb->nSession ){ |
| 12553 | ii = sqlite3session_enable(pSession->p, ii); |
| 12554 | cli_printf(p->out, |
| 12555 | "session %s enable flag = %d\n", pSession->zName, ii); |
| 12556 | } |
| 12557 | }else |
| 12558 | |
| 12559 | /* .session filter GLOB .... |
| 12560 | ** Set a list of GLOB patterns of table names to be excluded. |
| 12561 | */ |
| 12562 | if( cli_strcmp(azCmd[0], "filter")==0 ){ |
| 12563 | int ii; |
| 12564 | i64 nByte; |
| 12565 | if( nCmd<2 ) goto session_syntax_error; |
| 12566 | if( pAuxDb->nSession ){ |
| 12567 | for(ii=0; ii<pSession->nFilter; ii++){ |
| 12568 | sqlite3_free(pSession->azFilter[ii]); |
| 12569 | } |
| 12570 | sqlite3_free(pSession->azFilter); |
| 12571 | nByte = sizeof(pSession->azFilter[0])*(nCmd-1); |
| 12572 | pSession->azFilter = sqlite3_malloc64( nByte ); |
| 12573 | shell_check_oom( pSession->azFilter ); |
| 12574 | for(ii=1; ii<nCmd; ii++){ |
| 12575 | char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); |
| 12576 | shell_check_oom(x); |
| 12577 | } |
| 12578 | pSession->nFilter = ii-1; |
| 12579 | } |
| 12580 | }else |
| 12581 | |
| 12582 | /* .session indirect ?BOOLEAN? |
| 12583 | ** Query or set the indirect flag |
| 12584 | */ |
| 12585 | if( cli_strcmp(azCmd[0], "indirect")==0 ){ |
| 12586 | int ii; |
| 12587 | if( nCmd>2 ) goto session_syntax_error; |
| 12588 | ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); |
| 12589 | if( pAuxDb->nSession ){ |
| 12590 | ii = sqlite3session_indirect(pSession->p, ii); |
| 12591 | cli_printf(p->out, |
| 12592 | "session %s indirect flag = %d\n", pSession->zName, ii); |
| 12593 | } |
| 12594 | }else |
| 12595 | |
| 12596 | /* .session isempty |
| 12597 | ** Determine if the session is empty |
| 12598 | */ |
| 12599 | if( cli_strcmp(azCmd[0], "isempty")==0 ){ |
| 12600 | int ii; |
| 12601 | if( nCmd!=1 ) goto session_syntax_error; |
| 12602 | if( pAuxDb->nSession ){ |
| 12603 | ii = sqlite3session_isempty(pSession->p); |
| 12604 | cli_printf(p->out, |
| 12605 | "session %s isempty flag = %d\n", pSession->zName, ii); |
| 12606 | } |
| 12607 | }else |
| 12608 | |
| 12609 | /* .session list |
| 12610 | ** List all currently open sessions |
| 12611 | */ |
| 12612 | if( cli_strcmp(azCmd[0],"list")==0 ){ |
| 12613 | for(i=0; i<pAuxDb->nSession; i++){ |
| 12614 | cli_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName); |
| 12615 | } |
| 12616 | }else |
| 12617 | |
| 12618 | /* .session open DB NAME |
| 12619 | ** Open a new session called NAME on the attached database DB. |
| 12620 | ** DB is normally "main". |
| 12621 | */ |
| 12622 | if( cli_strcmp(azCmd[0],"open")==0 ){ |
| 12623 | char *zName; |
| 12624 | if( nCmd!=3 ) goto session_syntax_error; |
| 12625 | zName = azCmd[2]; |
| 12626 | if( zName[0]==0 ) goto session_syntax_error; |
| 12627 | for(i=0; i<pAuxDb->nSession; i++){ |
| 12628 | if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){ |
| 12629 | cli_printf(stderr,"Session \"%s\" already exists\n", zName); |
| 12630 | goto meta_command_exit; |
| 12631 | } |
| 12632 | } |
| 12633 | if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){ |
| 12634 | cli_printf(stderr, |
| 12635 | "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession)); |
| 12636 | goto meta_command_exit; |
| 12637 | } |
| 12638 | pSession = &pAuxDb->aSession[pAuxDb->nSession]; |
| 12639 | rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); |
| 12640 | if( rc ){ |
| 12641 | cli_printf(stderr,"Cannot open session: error code=%d\n", rc); |
| 12642 | rc = 0; |
| 12643 | goto meta_command_exit; |
| 12644 | } |
| 12645 | pSession->nFilter = 0; |
| 12646 | sqlite3session_table_filter(pSession->p, session_filter, pSession); |
| 12647 | pAuxDb->nSession++; |
| 12648 | pSession->zName = sqlite3_mprintf("%s", zName); |
| 12649 | shell_check_oom(pSession->zName); |
| 12650 | }else |
| 12651 | /* If no command name matches, show a syntax error */ |
| 12652 | session_syntax_error: |
| 12653 | showHelp(p->out, "session"); |
| 12654 | }else |
| 12655 | #endif |
| 12656 | |
| 12657 | #ifdef SQLITE_DEBUG |
| 12658 | /* Undocumented commands for internal testing. Subject to change |
| 12659 | ** without notice. */ |
| 12660 | if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){ |
| 12661 | if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){ |
| 12662 | int i, v; |
| 12663 | for(i=1; i<nArg; i++){ |
| 12664 | v = booleanValue(azArg[i]); |
| 12665 | cli_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v); |
| 12666 | } |
| 12667 | } |
| 12668 | if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){ |
| 12669 | int i; sqlite3_int64 v; |
| 12670 | for(i=1; i<nArg; i++){ |
| 12671 | char zBuf[200]; |
| 12672 | v = integerValue(azArg[i]); |
| 12673 | sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v); |
| 12674 | cli_puts(zBuf, p->out); |
| 12675 | } |
| 12676 | } |
| 12677 | }else |
| 12678 | #endif |
| 12679 | |
| 12680 | if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){ |
| 12681 | int bIsInit = 0; /* True to initialize the SELFTEST table */ |
| 12682 | int bVerbose = 0; /* Verbose output */ |
| 12683 | int bSelftestExists; /* True if SELFTEST already exists */ |
| 12684 | int i, k; /* Loop counters */ |
| 12685 | int nTest = 0; /* Number of tests runs */ |
| 12686 | int nErr = 0; /* Number of errors seen */ |
| 12687 | ShellText str; /* Answer for a query */ |
| 12688 | sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */ |
| 12689 | |
| 12690 | open_db(p,0); |
| 12691 | for(i=1; i<nArg; i++){ |
| 12692 | const char *z = azArg[i]; |
| 12693 | if( z[0]=='-' && z[1]=='-' ) z++; |
| 12694 | if( cli_strcmp(z,"-init")==0 ){ |
| 12695 | bIsInit = 1; |
| 12696 | }else |
| 12697 | if( cli_strcmp(z,"-v")==0 ){ |
| 12698 | bVerbose++; |
| 12699 | }else |
| 12700 | { |
| 12701 | cli_printf(stderr, |
| 12702 | "Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]); |
| 12703 | cli_puts("Should be one of: --init -v\n", stderr); |
| 12704 | rc = 1; |
| 12705 | goto meta_command_exit; |
| 12706 | } |
| 12707 | } |
| 12708 | if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0) |
| 12709 | != SQLITE_OK ){ |
| 12710 | bSelftestExists = 0; |
| 12711 | }else{ |
| 12712 | bSelftestExists = 1; |
| 12713 | } |
| 12714 | if( bIsInit ){ |
| 12715 | createSelftestTable(p); |
| 12716 | bSelftestExists = 1; |
| 12717 | } |
| 12718 | initText(&str); |
| 12719 | appendText(&str, "x", 0); |
| 12720 | for(k=bSelftestExists; k>=0; k--){ |
| 12721 | if( k==1 ){ |
| 12722 | rc = sqlite3_prepare_v2(p->db, |
| 12723 | "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno", |
| 12724 | -1, &pStmt, 0); |
| 12725 | }else{ |
| 12726 | rc = sqlite3_prepare_v2(p->db, |
| 12727 | "VALUES(0,'memo','Missing SELFTEST table - default checks only','')," |
| 12728 | " (1,'run','PRAGMA integrity_check','ok')", |
| 12729 | -1, &pStmt, 0); |
| 12730 | } |
| 12731 | if( rc ){ |
| 12732 | eputz("Error querying the selftest table\n"); |
| 12733 | rc = 1; |
| 12734 | sqlite3_finalize(pStmt); |
| 12735 | goto meta_command_exit; |
| 12736 | } |
| 12737 | for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){ |
| 12738 | int tno = sqlite3_column_int(pStmt, 0); |
| 12739 | const char *zOp = (const char*)sqlite3_column_text(pStmt, 1); |
| 12740 | const char *zSql = (const char*)sqlite3_column_text(pStmt, 2); |
| 12741 | const char *zAns = (const char*)sqlite3_column_text(pStmt, 3); |
| 12742 | |
| 12743 | if( zOp==0 ) continue; |
| 12744 | if( zSql==0 ) continue; |
| 12745 | if( zAns==0 ) continue; |
| 12746 | k = 0; |
| 12747 | if( bVerbose>0 ){ |
| 12748 | cli_printf(stdout, "%d: %s %s\n", tno, zOp, zSql); |
| 12749 | } |
| 12750 | if( cli_strcmp(zOp,"memo")==0 ){ |
| 12751 | cli_printf(p->out, "%s\n", zSql); |
| 12752 | }else |
| 12753 | if( cli_strcmp(zOp,"run")==0 ){ |
| 12754 | char *zErrMsg = 0; |
| 12755 | str.n = 0; |
| 12756 | str.zTxt[0] = 0; |
| 12757 | rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg); |
| 12758 | nTest++; |
| 12759 | if( bVerbose ){ |
| 12760 | cli_printf(p->out, "Result: %s\n", str.zTxt); |
| 12761 | } |
| 12762 | if( rc || zErrMsg ){ |
| 12763 | nErr++; |
| 12764 | rc = 1; |
| 12765 | cli_printf(p->out, "%d: error-code-%d: %s\n", tno, rc,zErrMsg); |
| 12766 | sqlite3_free(zErrMsg); |
| 12767 | }else if( cli_strcmp(zAns,str.zTxt)!=0 ){ |
| 12768 | nErr++; |
| 12769 | rc = 1; |
| 12770 | cli_printf(p->out, "%d: Expected: [%s]\n", tno, zAns); |
| 12771 | cli_printf(p->out, "%d: Got: [%s]\n", tno, str.zTxt); |
| 12772 | } |
| 12773 | } |
| 12774 | else{ |
| 12775 | cli_printf(stderr, |
| 12776 | "Unknown operation \"%s\" on selftest line %d\n", zOp, tno); |
| 12777 | rc = 1; |
| 12778 | break; |
| 12779 | } |
| 12780 | } /* End loop over rows of content from SELFTEST */ |
| 12781 | sqlite3_finalize(pStmt); |
| 12782 | } /* End loop over k */ |
| 12783 | freeText(&str); |
| 12784 | cli_printf(p->out, "%d errors out of %d tests\n", nErr, nTest); |
| 12785 | }else |
| 12786 | |
| 12787 | if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){ |
| 12788 | if( nArg<2 || nArg>3 ){ |
| 12789 | eputz("Usage: .separator COL ?ROW?\n"); |
| 12790 | rc = 1; |
| 12791 | } |
| 12792 | if( nArg>=2 ){ |
| 12793 | modeSetStr(&p->mode.spec.zColumnSep, azArg[1]); |
| 12794 | } |
| 12795 | if( nArg>=3 ){ |
| 12796 | modeSetStr(&p->mode.spec.zRowSep,azArg[2]); |
| 12797 | } |
| 12798 | }else |
| 12799 | |
| 12800 | if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){ |
| 12801 | const char *zLike = 0; /* Which table to checksum. 0 means everything */ |
| 12802 | int i; /* Loop counter */ |
| 12803 | int bSchema = 0; /* Also hash the schema */ |
| 12804 | int bSeparate = 0; /* Hash each table separately */ |
| 12805 | int iSize = 224; /* Hash algorithm to use */ |
| 12806 | int bDebug = 0; /* Only show the query that would have run */ |
| 12807 | sqlite3_stmt *pStmt; /* For querying tables names */ |
| 12808 | char *zSql; /* SQL to be run */ |
| 12809 | char *zSep; /* Separator */ |
| 12810 | ShellText sSql; /* Complete SQL for the query to run the hash */ |
| 12811 | ShellText sQuery; /* Set of queries used to read all content */ |
| 12812 | open_db(p, 0); |
| 12813 | for(i=1; i<nArg; i++){ |
| 12814 | const char *z = azArg[i]; |
| 12815 | if( z[0]=='-' ){ |
| 12816 | z++; |
| 12817 | if( z[0]=='-' ) z++; |
| 12818 | if( cli_strcmp(z,"schema")==0 ){ |
| 12819 | bSchema = 1; |
| 12820 | }else |
| 12821 | if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0 |
| 12822 | || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0 |
| 12823 | ){ |
| 12824 | iSize = atoi(&z[5]); |
| 12825 | }else |
| 12826 | if( cli_strcmp(z,"debug")==0 ){ |
| 12827 | bDebug = 1; |
| 12828 | }else |
| 12829 | { |
| 12830 | cli_printf(stderr, |
| 12831 | "Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]); |
| 12832 | showHelp(p->out, azArg[0]); |
| 12833 | rc = 1; |
| 12834 | goto meta_command_exit; |
| 12835 | } |
| 12836 | }else if( zLike ){ |
| 12837 | eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n"); |
| 12838 | rc = 1; |
| 12839 | goto meta_command_exit; |
| 12840 | }else{ |
| 12841 | zLike = z; |
| 12842 | bSeparate = 1; |
| 12843 | if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1; |
| 12844 | } |
| 12845 | } |
| 12846 | if( bSchema ){ |
| 12847 | zSql = "SELECT lower(name) as tname FROM sqlite_schema" |
| 12848 | " WHERE type='table' AND coalesce(rootpage,0)>1" |
| 12849 | " UNION ALL SELECT 'sqlite_schema'" |
| 12850 | " ORDER BY 1 collate nocase"; |
| 12851 | }else{ |
| 12852 | zSql = "SELECT lower(name) as tname FROM sqlite_schema" |
| 12853 | " WHERE type='table' AND coalesce(rootpage,0)>1" |
| 12854 | " AND name NOT LIKE 'sqlite__%' ESCAPE '_'" |
| 12855 | " ORDER BY 1 collate nocase"; |
| 12856 | } |
| 12857 | sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); |
| 12858 | initText(&sQuery); |
| 12859 | initText(&sSql); |
| 12860 | appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0); |
| 12861 | zSep = "VALUES("; |
| 12862 | while( SQLITE_ROW==sqlite3_step(pStmt) ){ |
| 12863 | const char *zTab = (const char*)sqlite3_column_text(pStmt,0); |
| 12864 | if( zTab==0 ) continue; |
| 12865 | if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue; |
| 12866 | if( cli_strncmp(zTab, "sqlite_",7)!=0 ){ |
| 12867 | appendText(&sQuery,"SELECT * FROM ", 0); |
| 12868 | appendText(&sQuery,zTab,'"'); |
| 12869 | appendText(&sQuery," NOT INDEXED;", 0); |
| 12870 | }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){ |
| 12871 | appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema" |
| 12872 | " ORDER BY name;", 0); |
| 12873 | }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){ |
| 12874 | appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence" |
| 12875 | " ORDER BY name;", 0); |
| 12876 | }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){ |
| 12877 | appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1" |
| 12878 | " ORDER BY tbl,idx;", 0); |
| 12879 | }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){ |
| 12880 | appendText(&sQuery, "SELECT * FROM ", 0); |
| 12881 | appendText(&sQuery, zTab, 0); |
| 12882 | appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0); |
| 12883 | } |
| 12884 | appendText(&sSql, zSep, 0); |
| 12885 | appendText(&sSql, sQuery.zTxt, '\''); |
| 12886 | sQuery.n = 0; |
| 12887 | appendText(&sSql, ",", 0); |
| 12888 | appendText(&sSql, zTab, '\''); |
| 12889 | zSep = "),("; |
| 12890 | } |
| 12891 | sqlite3_finalize(pStmt); |
| 12892 | if( bSeparate ){ |
| 12893 | zSql = sqlite3_mprintf( |
| 12894 | "%s))" |
| 12895 | " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label" |
| 12896 | " FROM [sha3sum$query]", |
| 12897 | sSql.zTxt, iSize); |
| 12898 | }else{ |
| 12899 | zSql = sqlite3_mprintf( |
| 12900 | "%s))" |
| 12901 | " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash" |
| 12902 | " FROM [sha3sum$query]", |
| 12903 | sSql.zTxt, iSize); |
| 12904 | } |
| 12905 | shell_check_oom(zSql); |
| 12906 | freeText(&sQuery); |
| 12907 | freeText(&sSql); |
| 12908 | if( bDebug ){ |
| 12909 | cli_printf(p->out, "%s\n", zSql); |
| 12910 | }else{ |
| 12911 | shell_exec(p, zSql, 0); |
| 12912 | } |
| 12913 | #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE) |
| 12914 | { |
| 12915 | int lrc; |
| 12916 | char *zRevText = /* Query for reversible to-blob-to-text check */ |
| 12917 | "SELECT lower(name) as tname FROM sqlite_schema\n" |
| 12918 | "WHERE type='table' AND coalesce(rootpage,0)>1\n" |
| 12919 | "AND name NOT LIKE 'sqlite__%%' ESCAPE '_'%s\n" |
| 12920 | "ORDER BY 1 collate nocase"; |
| 12921 | zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : ""); |
| 12922 | zRevText = sqlite3_mprintf( |
| 12923 | /* lower-case query is first run, producing upper-case query. */ |
| 12924 | "with tabcols as materialized(\n" |
| 12925 | "select tname, cname\n" |
| 12926 | "from (" |
| 12927 | " select printf('\"%%w\"',ss.tname) as tname," |
| 12928 | " printf('\"%%w\"',ti.name) as cname\n" |
| 12929 | " from (%z) ss\n inner join pragma_table_info(tname) ti))\n" |
| 12930 | "select 'SELECT total(bad_text_count) AS bad_text_count\n" |
| 12931 | "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n" |
| 12932 | " from (select 'SELECT COUNT(*) AS bad_text_count\n" |
| 12933 | "FROM '||tname||' WHERE '\n" |
| 12934 | "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n" |
| 12935 | "|| ' AND typeof('||cname||')=''text'' ',\n" |
| 12936 | "' OR ') as query, tname from tabcols group by tname)" |
| 12937 | , zRevText); |
| 12938 | shell_check_oom(zRevText); |
| 12939 | if( bDebug ) cli_printf(p->out, "%s\n", zRevText); |
| 12940 | lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0); |
| 12941 | if( lrc!=SQLITE_OK ){ |
| 12942 | /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the |
| 12943 | ** user does cruel and unnatural things like ".limit expr_depth 0". */ |
| 12944 | rc = 1; |
| 12945 | }else{ |
| 12946 | if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC); |
| 12947 | lrc = SQLITE_ROW==sqlite3_step(pStmt); |
| 12948 | if( lrc ){ |
| 12949 | const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0); |
| 12950 | sqlite3_stmt *pCheckStmt; |
| 12951 | lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0); |
| 12952 | if( bDebug ) cli_printf(p->out, "%s\n", zGenQuery); |
| 12953 | if( lrc!=SQLITE_OK ){ |
| 12954 | rc = 1; |
| 12955 | }else{ |
| 12956 | if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){ |
| 12957 | double countIrreversible = sqlite3_column_double(pCheckStmt, 0); |
| 12958 | if( countIrreversible>0 ){ |
| 12959 | int sz = (int)(countIrreversible + 0.5); |
| 12960 | cli_printf(stderr, |
| 12961 | "Digest includes %d invalidly encoded text field%s.\n", |
| 12962 | sz, (sz>1)? "s": ""); |
| 12963 | } |
| 12964 | } |
| 12965 | sqlite3_finalize(pCheckStmt); |
| 12966 | } |
| 12967 | sqlite3_finalize(pStmt); |
| 12968 | } |
| 12969 | } |
| 12970 | if( rc ) eputz(".sha3sum failed.\n"); |
| 12971 | sqlite3_free(zRevText); |
| 12972 | } |
| 12973 | #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */ |
| 12974 | sqlite3_free(zSql); |
| 12975 | }else |
| 12976 | |
| 12977 | #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) |
| 12978 | if( c=='s' |
| 12979 | && (cli_strncmp(azArg[0], "shell", n)==0 |
| 12980 | || cli_strncmp(azArg[0],"system",n)==0) |
| 12981 | ){ |
| 12982 | char *zCmd; |
| 12983 | int i, x; |
| 12984 | failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); |
| 12985 | if( nArg<2 ){ |
| 12986 | eputz("Usage: .system COMMAND\n"); |
| 12987 | rc = 1; |
| 12988 | goto meta_command_exit; |
| 12989 | } |
| 12990 | zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]); |
| 12991 | for(i=2; i<nArg && zCmd!=0; i++){ |
| 12992 | zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"", |
| 12993 | zCmd, azArg[i]); |
| 12994 | } |
| 12995 | /*consoleRestore();*/ |
| 12996 | x = zCmd!=0 ? system(zCmd) : 1; |
| 12997 | /*consoleRenewSetup();*/ |
| 12998 | sqlite3_free(zCmd); |
| 12999 | if( x ) cli_printf(stderr,"System command returns %d\n", x); |
| 13000 | }else |
| 13001 | #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */ |
| 13002 | |
| 13003 | if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){ |
| 13004 | static const char *azBool[] = { "off", "on", "trigger", "full"}; |
| 13005 | int i; |
| 13006 | if( nArg!=1 ){ |
| 13007 | eputz("Usage: .show\n"); |
| 13008 | rc = 1; |
| 13009 | goto meta_command_exit; |
| 13010 | } |
| 13011 | cli_printf(p->out, "%12.12s: %s\n","echo", |
| 13012 | azBool[(p->mode.mFlags & MFLG_ECHO)!=0]); |
| 13013 | cli_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->mode.autoEQP&3]); |
| 13014 | cli_printf(p->out, "%12.12s: %s\n","explain", |
| 13015 | p->mode.autoExplain ? "auto" : "off"); |
| 13016 | cli_printf(p->out, "%12.12s: %s\n","headers", |
| 13017 | p->mode.spec.bTitles==QRF_Always ? "always" : |
| 13018 | azBool[p->mode.spec.bTitles==QRF_Yes]); |
| 13019 | if( p->mode.spec.eStyle==QRF_STYLE_Column |
| 13020 | || p->mode.spec.eStyle==QRF_STYLE_Box |
| 13021 | || p->mode.spec.eStyle==QRF_STYLE_Table |
| 13022 | || p->mode.spec.eStyle==QRF_STYLE_Markdown |
| 13023 | ){ |
| 13024 | cli_printf(p->out, |
| 13025 | "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode", |
| 13026 | aModeInfo[p->mode.eMode].zName, p->mode.spec.nWrap, |
| 13027 | p->mode.spec.bWordWrap==QRF_Yes ? "on" : "off", |
| 13028 | p->mode.spec.eText==QRF_TEXT_Sql ? "" : "no"); |
| 13029 | }else{ |
| 13030 | cli_printf(p->out, "%12.12s: %s\n","mode", |
| 13031 | aModeInfo[p->mode.eMode].zName); |
| 13032 | } |
| 13033 | cli_printf(p->out, "%12.12s: ", "nullvalue"); |
| 13034 | output_c_string(p->out, p->mode.spec.zNull); |
| 13035 | cli_puts("\n", p->out); |
| 13036 | cli_printf(p->out, "%12.12s: %s\n","output", |
| 13037 | strlen30(p->outfile) ? p->outfile : "stdout"); |
| 13038 | cli_printf(p->out, "%12.12s: ", "colseparator"); |
| 13039 | output_c_string(p->out, p->mode.spec.zColumnSep); |
| 13040 | cli_puts("\n", p->out); |
| 13041 | cli_printf(p->out, "%12.12s: ", "rowseparator"); |
| 13042 | output_c_string(p->out, p->mode.spec.zRowSep); |
| 13043 | cli_puts("\n", p->out); |
| 13044 | cli_printf(p->out, "%12.12s:", "stats"); |
| 13045 | if( p->mStats==0 ){ |
| 13046 | cli_printf(p->out, " off\n"); |
| 13047 | }else{ |
| 13048 | u8 mStats = p->mStats; |
| 13049 | if( (mStats & CLISTAT_ALL)==CLISTAT_ALL ){ |
| 13050 | cli_printf(p->out, " all"); |
| 13051 | mStats &= ~CLISTAT_ALL; |
| 13052 | } |
| 13053 | if( (mStats & CLISTAT_ON)==CLISTAT_ON ){ |
| 13054 | cli_printf(p->out, " on"); |
| 13055 | mStats &= ~CLISTAT_ON; |
| 13056 | } |
| 13057 | if( mStats & CLISTAT_XSTMT ){ |
| 13058 | cli_printf(p->out, " xstmt"); |
| 13059 | }else if( mStats & CLISTAT_STMT ){ |
| 13060 | cli_printf(p->out, " stmt"); |
| 13061 | }else if( mStats & CLISTAT_VMSTEP ){ |
| 13062 | cli_printf(p->out, " vmstep"); |
| 13063 | } |
| 13064 | if( mStats & CLISTAT_XMEM ){ |
| 13065 | cli_printf(p->out, " xmem"); |
| 13066 | }else if( mStats & CLISTAT_MEM ){ |
| 13067 | cli_printf(p->out, " mem"); |
| 13068 | } |
| 13069 | if( mStats & CLISTAT_IO ){ |
| 13070 | cli_printf(p->out, " io"); |
| 13071 | } |
| 13072 | if( mStats & CLISTAT_ZIPVFS ){ |
| 13073 | cli_printf(p->out, " zipvfs"); |
| 13074 | } |
| 13075 | if( mStats & CLISTAT_RESET ){ |
| 13076 | cli_printf(p->out, " reset"); |
| 13077 | } |
| 13078 | cli_printf(p->out,"\n"); |
| 13079 | } |
| 13080 | cli_printf(p->out, "%12.12s: ", "width"); |
| 13081 | for(i=0; i<p->mode.spec.nWidth; i++){ |
| 13082 | cli_printf(p->out, "%d ", (int)p->mode.spec.aWidth[i]); |
| 13083 | } |
| 13084 | cli_puts("\n", p->out); |
| 13085 | cli_printf(p->out, "%12.12s: %s\n", "filename", |
| 13086 | p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : ""); |
| 13087 | }else |
| 13088 | |
| 13089 | if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){ |
| 13090 | rc = dotCmdStats(p); |
| 13091 | }else |
| 13092 | |
| 13093 | if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0) ){ |
| 13094 | sqlite3_stmt *pStmt; |
| 13095 | sqlite3_str *pSql; |
| 13096 | const char *zPattern = nArg>1 ? azArg[1] : 0; |
| 13097 | |
| 13098 | open_db(p, 0); |
| 13099 | rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); |
| 13100 | if( rc ){ |
| 13101 | sqlite3_finalize(pStmt); |
| 13102 | return shellDatabaseError(p->db); |
| 13103 | } |
| 13104 | |
| 13105 | pSql = sqlite3_str_new(p->db); |
| 13106 | while( sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 13107 | const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); |
| 13108 | if( zDbName==0 ) continue; |
| 13109 | if( sqlite3_str_length(pSql) ){ |
| 13110 | sqlite3_str_appendall(pSql, " UNION ALL "); |
| 13111 | } |
| 13112 | if( sqlite3_stricmp(zDbName, "main")==0 ){ |
| 13113 | sqlite3_str_appendall(pSql, "SELECT name FROM "); |
| 13114 | }else{ |
| 13115 | sqlite3_str_appendf(pSql, "SELECT %Q||'.'||name FROM ", zDbName); |
| 13116 | } |
| 13117 | sqlite3_str_appendf(pSql, "\"%w\".sqlite_schema", zDbName); |
| 13118 | sqlite3_str_appendf(pSql, |
| 13119 | " WHERE type IN ('table','view')" |
| 13120 | " AND name NOT LIKE 'sqlite__%%' ESCAPE '_'" |
| 13121 | ); |
| 13122 | if( zPattern ){ |
| 13123 | sqlite3_str_appendf(pSql," AND name LIKE %Q", zPattern); |
| 13124 | } |
| 13125 | } |
| 13126 | rc = sqlite3_finalize(pStmt); |
| 13127 | if( rc==SQLITE_OK ){ |
| 13128 | sqlite3_str_appendall(pSql, " ORDER BY 1"); |
| 13129 | } |
| 13130 | |
| 13131 | /* Run the SQL statement in "split" mode. */ |
| 13132 | modePush(p); |
| 13133 | modeChange(p, MODE_Split); |
| 13134 | shell_exec(p, sqlite3_str_value(pSql), 0); |
| 13135 | sqlite3_str_free(pSql); |
| 13136 | modePop(p); |
| 13137 | if( rc ) return shellDatabaseError(p->db); |
| 13138 | }else |
| 13139 | |
| 13140 | /* Set the p->zTestcase name and begin redirecting output into |
| 13141 | ** the cli_output_capture sqlite3_str */ |
| 13142 | if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){ |
| 13143 | rc = dotCmdTestcase(p); |
| 13144 | }else |
| 13145 | |
| 13146 | #ifndef SQLITE_UNTESTABLE |
| 13147 | if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){ |
| 13148 | static const struct { |
| 13149 | const char *zCtrlName; /* Name of a test-control option */ |
| 13150 | int ctrlCode; /* Integer code for that option */ |
| 13151 | int unSafe; /* Not valid unless --unsafe-testing */ |
| 13152 | const char *zUsage; /* Usage notes */ |
| 13153 | } aCtrl[] = { |
| 13154 | {"always", SQLITE_TESTCTRL_ALWAYS, 1, "BOOLEAN" }, |
| 13155 | {"assert", SQLITE_TESTCTRL_ASSERT, 1, "BOOLEAN" }, |
| 13156 | /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, "" },*/ |
| 13157 | {"bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, 1, "SIZE INT-ARRAY"}, |
| 13158 | {"byteorder", SQLITE_TESTCTRL_BYTEORDER, 0, "" }, |
| 13159 | {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN" }, |
| 13160 | {"fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"args..." }, |
| 13161 | {"fk_no_action", SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN" }, |
| 13162 | {"imposter", SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"}, |
| 13163 | {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,"" }, |
| 13164 | {"json_selfcheck", SQLITE_TESTCTRL_JSON_SELFCHECK ,0,"BOOLEAN" }, |
| 13165 | {"localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN" }, |
| 13166 | {"never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN" }, |
| 13167 | {"optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK ..."}, |
| 13168 | #ifdef YYCOVERAGE |
| 13169 | {"parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE,0,"" }, |
| 13170 | #endif |
| 13171 | {"pending_byte", SQLITE_TESTCTRL_PENDING_BYTE,1, "OFFSET " }, |
| 13172 | {"prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE,0, "" }, |
| 13173 | {"prng_save", SQLITE_TESTCTRL_PRNG_SAVE, 0, "" }, |
| 13174 | {"prng_seed", SQLITE_TESTCTRL_PRNG_SEED, 0, "SEED ?db?" }, |
| 13175 | {"seek_count", SQLITE_TESTCTRL_SEEK_COUNT, 0, "" }, |
| 13176 | {"sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX" }, |
| 13177 | {"tune", SQLITE_TESTCTRL_TUNE, 1, "ID VALUE" }, |
| 13178 | }; |
| 13179 | int testctrl = -1; |
| 13180 | int iCtrl = -1; |
| 13181 | int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */ |
| 13182 | int isOk = 0; |
| 13183 | int i, n2; |
| 13184 | const char *zCmd = 0; |
| 13185 | |
| 13186 | open_db(p, 0); |
| 13187 | zCmd = nArg>=2 ? azArg[1] : "help"; |
| 13188 | |
| 13189 | /* The argument can optionally begin with "-" or "--" */ |
| 13190 | if( zCmd[0]=='-' && zCmd[1] ){ |
| 13191 | zCmd++; |
| 13192 | if( zCmd[0]=='-' && zCmd[1] ) zCmd++; |
| 13193 | } |
| 13194 | |
| 13195 | /* --help lists all test-controls */ |
| 13196 | if( cli_strcmp(zCmd,"help")==0 ){ |
| 13197 | cli_puts("Available test-controls:\n", p->out); |
| 13198 | for(i=0; i<ArraySize(aCtrl); i++){ |
| 13199 | if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue; |
| 13200 | cli_printf(p->out, " .testctrl %s %s\n", |
| 13201 | aCtrl[i].zCtrlName, aCtrl[i].zUsage); |
| 13202 | } |
| 13203 | rc = 1; |
| 13204 | goto meta_command_exit; |
| 13205 | } |
| 13206 | |
| 13207 | /* convert testctrl text option to value. allow any unique prefix |
| 13208 | ** of the option name, or a numerical value. */ |
| 13209 | n2 = strlen30(zCmd); |
| 13210 | for(i=0; i<ArraySize(aCtrl); i++){ |
| 13211 | if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue; |
| 13212 | if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ |
| 13213 | if( testctrl<0 ){ |
| 13214 | testctrl = aCtrl[i].ctrlCode; |
| 13215 | iCtrl = i; |
| 13216 | }else{ |
| 13217 | cli_printf(stderr,"Error: ambiguous test-control: \"%s\"\n" |
| 13218 | "Use \".testctrl --help\" for help\n", zCmd); |
| 13219 | rc = 1; |
| 13220 | goto meta_command_exit; |
| 13221 | } |
| 13222 | } |
| 13223 | } |
| 13224 | if( testctrl<0 ){ |
| 13225 | cli_printf(stderr,"Error: unknown test-control: %s\n" |
| 13226 | "Use \".testctrl --help\" for help\n", zCmd); |
| 13227 | }else{ |
| 13228 | switch(testctrl){ |
| 13229 | |
| 13230 | /* Special processing for .testctrl opt MASK ... |
| 13231 | ** Each MASK argument can be one of: |
| 13232 | ** |
| 13233 | ** +LABEL Enable the named optimization |
| 13234 | ** |
| 13235 | ** -LABEL Disable the named optimization |
| 13236 | ** |
| 13237 | ** INTEGER Mask of optimizations to disable |
| 13238 | */ |
| 13239 | case SQLITE_TESTCTRL_OPTIMIZATIONS: { |
| 13240 | u64 curOpt; /* Current opt-disabled mask */ |
| 13241 | u64 newOpt; /* New opt-disabled mask */ |
| 13242 | u64 m; /* A working mask value */ |
| 13243 | int ii, jj; /* Loop counters */ |
| 13244 | int nOff; /* Number of disabled optimizations */ |
| 13245 | const char *zName; /* Name of an optimization */ |
| 13246 | int bQuiet = 0; /* Suppress output echo */ |
| 13247 | |
| 13248 | sqlite3_test_control(SQLITE_TESTCTRL_GETOPT, p->db, &curOpt); |
| 13249 | newOpt = curOpt; |
| 13250 | for(ii=2; ii<nArg; ii++){ |
| 13251 | const char *z = azArg[ii]; |
| 13252 | int useLabel = 0; |
| 13253 | const char *zLabel = 0; |
| 13254 | if( (z[0]=='+'|| z[0]=='-') && !IsDigit(z[1]) ){ |
| 13255 | useLabel = z[0]; |
| 13256 | zLabel = &z[1]; |
| 13257 | }else if( !IsDigit(z[0]) && z[0]!=0 && !IsDigit(z[1]) ){ |
| 13258 | useLabel = '+'; |
| 13259 | zLabel = z; |
| 13260 | }else{ |
| 13261 | newOpt = (unsigned int)strtol(z,0,0); |
| 13262 | } |
| 13263 | if( useLabel ){ |
| 13264 | if( sqlite3_optimization_mask(zLabel,&m)==SQLITE_NOTFOUND ){ |
| 13265 | if( strcmp(zLabel,"q")==0 ){ |
| 13266 | /* Special -q option suppresses output */ |
| 13267 | bQuiet = 1; |
| 13268 | continue; |
| 13269 | } |
| 13270 | cli_printf(stderr, |
| 13271 | "Error: no such optimization: \"%s\"\n", zLabel); |
| 13272 | cli_puts("Should be one of: All", stderr); |
| 13273 | for(jj=0; jj<32; jj++){ |
| 13274 | zName = sqlite3_optimization_name(1ull<<jj); |
| 13275 | if( zName ) cli_printf(stderr," %s", zName); |
| 13276 | } |
| 13277 | cli_puts("\n", stderr); |
| 13278 | rc = 1; |
| 13279 | goto meta_command_exit; |
| 13280 | } |
| 13281 | if( useLabel=='+' ){ |
| 13282 | newOpt &= ~m; |
| 13283 | }else{ |
| 13284 | newOpt |= m; |
| 13285 | } |
| 13286 | } |
| 13287 | } |
| 13288 | if( curOpt!=newOpt ){ |
| 13289 | sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,p->db,newOpt); |
| 13290 | } |
| 13291 | if( !bQuiet ){ |
| 13292 | for(ii=nOff=0, m=1; ii<64; ii++, m <<= 1){ |
| 13293 | if( m & newOpt ) nOff++; |
| 13294 | } |
| 13295 | if( nOff<12 ){ |
| 13296 | cli_puts("+All", p->out); |
| 13297 | for(ii=0, m=1; ii<64; ii++, m <<= 1){ |
| 13298 | if( (newOpt & m)!=0 |
| 13299 | && (zName = sqlite3_optimization_name(m))!=0 |
| 13300 | ){ |
| 13301 | cli_printf(p->out, " -%s", zName); |
| 13302 | } |
| 13303 | } |
| 13304 | }else{ |
| 13305 | cli_puts("-All", p->out); |
| 13306 | for(ii=0, m=1; ii<64; ii++, m <<= 1){ |
| 13307 | if( (newOpt & m)==0 |
| 13308 | && (zName = sqlite3_optimization_name(m))!=0 |
| 13309 | ){ |
| 13310 | cli_printf(p->out, " +%s", zName); |
| 13311 | } |
| 13312 | } |
| 13313 | } |
| 13314 | cli_puts("\n", p->out); |
| 13315 | } |
| 13316 | rc2 = isOk = 3; |
| 13317 | break; |
| 13318 | } |
| 13319 | |
| 13320 | /* sqlite3_test_control(int, db, int) */ |
| 13321 | case SQLITE_TESTCTRL_FK_NO_ACTION: |
| 13322 | if( nArg==3 ){ |
| 13323 | unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0); |
| 13324 | rc2 = sqlite3_test_control(testctrl, p->db, opt); |
| 13325 | isOk = 3; |
| 13326 | } |
| 13327 | break; |
| 13328 | |
| 13329 | /* sqlite3_test_control(int) */ |
| 13330 | case SQLITE_TESTCTRL_PRNG_SAVE: |
| 13331 | case SQLITE_TESTCTRL_PRNG_RESTORE: |
| 13332 | case SQLITE_TESTCTRL_BYTEORDER: |
| 13333 | if( nArg==2 ){ |
| 13334 | rc2 = sqlite3_test_control(testctrl); |
| 13335 | isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3; |
| 13336 | } |
| 13337 | break; |
| 13338 | |
| 13339 | /* sqlite3_test_control(int, uint) */ |
| 13340 | case SQLITE_TESTCTRL_PENDING_BYTE: |
| 13341 | if( nArg==3 ){ |
| 13342 | unsigned int opt = (unsigned int)integerValue(azArg[2]); |
| 13343 | rc2 = sqlite3_test_control(testctrl, opt); |
| 13344 | isOk = 3; |
| 13345 | } |
| 13346 | break; |
| 13347 | |
| 13348 | /* sqlite3_test_control(int, int, sqlite3*) */ |
| 13349 | case SQLITE_TESTCTRL_PRNG_SEED: |
| 13350 | if( nArg==3 || nArg==4 ){ |
| 13351 | int ii = (int)integerValue(azArg[2]); |
| 13352 | sqlite3 *db; |
| 13353 | if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){ |
| 13354 | sqlite3_randomness(sizeof(ii),&ii); |
| 13355 | cli_printf(stdout, "-- random seed: %d\n", ii); |
| 13356 | } |
| 13357 | if( nArg==3 ){ |
| 13358 | db = 0; |
| 13359 | }else{ |
| 13360 | db = p->db; |
| 13361 | /* Make sure the schema has been loaded */ |
| 13362 | sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0); |
| 13363 | } |
| 13364 | rc2 = sqlite3_test_control(testctrl, ii, db); |
| 13365 | isOk = 3; |
| 13366 | } |
| 13367 | break; |
| 13368 | |
| 13369 | /* sqlite3_test_control(int, int) */ |
| 13370 | case SQLITE_TESTCTRL_ASSERT: |
| 13371 | case SQLITE_TESTCTRL_ALWAYS: |
| 13372 | if( nArg==3 ){ |
| 13373 | int opt = booleanValue(azArg[2]); |
| 13374 | rc2 = sqlite3_test_control(testctrl, opt); |
| 13375 | isOk = 1; |
| 13376 | } |
| 13377 | break; |
| 13378 | |
| 13379 | /* sqlite3_test_control(int, int) */ |
| 13380 | case SQLITE_TESTCTRL_LOCALTIME_FAULT: |
| 13381 | case SQLITE_TESTCTRL_NEVER_CORRUPT: |
| 13382 | if( nArg==3 ){ |
| 13383 | int opt = booleanValue(azArg[2]); |
| 13384 | rc2 = sqlite3_test_control(testctrl, opt); |
| 13385 | isOk = 3; |
| 13386 | } |
| 13387 | break; |
| 13388 | |
| 13389 | /* sqlite3_test_control(sqlite3*) */ |
| 13390 | case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: |
| 13391 | rc2 = sqlite3_test_control(testctrl, p->db); |
| 13392 | isOk = 3; |
| 13393 | break; |
| 13394 | |
| 13395 | case SQLITE_TESTCTRL_IMPOSTER: |
| 13396 | if( nArg==5 ){ |
| 13397 | rc2 = sqlite3_test_control(testctrl, p->db, |
| 13398 | azArg[2], |
| 13399 | integerValue(azArg[3]), |
| 13400 | integerValue(azArg[4])); |
| 13401 | isOk = 3; |
| 13402 | } |
| 13403 | break; |
| 13404 | |
| 13405 | case SQLITE_TESTCTRL_SEEK_COUNT: { |
| 13406 | u64 x = 0; |
| 13407 | rc2 = sqlite3_test_control(testctrl, p->db, &x); |
| 13408 | cli_printf(p->out, "%llu\n", x); |
| 13409 | isOk = 3; |
| 13410 | break; |
| 13411 | } |
| 13412 | |
| 13413 | #ifdef YYCOVERAGE |
| 13414 | case SQLITE_TESTCTRL_PARSER_COVERAGE: { |
| 13415 | if( nArg==2 ){ |
| 13416 | sqlite3_test_control(testctrl, p->out); |
| 13417 | isOk = 3; |
| 13418 | } |
| 13419 | break; |
| 13420 | } |
| 13421 | #endif |
| 13422 | #ifdef SQLITE_DEBUG |
| 13423 | case SQLITE_TESTCTRL_TUNE: { |
| 13424 | if( nArg==4 ){ |
| 13425 | int id = (int)integerValue(azArg[2]); |
| 13426 | int val = (int)integerValue(azArg[3]); |
| 13427 | sqlite3_test_control(testctrl, id, &val); |
| 13428 | isOk = 3; |
| 13429 | }else if( nArg==3 ){ |
| 13430 | int id = (int)integerValue(azArg[2]); |
| 13431 | sqlite3_test_control(testctrl, -id, &rc2); |
| 13432 | isOk = 1; |
| 13433 | }else if( nArg==2 ){ |
| 13434 | int id = 1; |
| 13435 | while(1){ |
| 13436 | int val = 0; |
| 13437 | rc2 = sqlite3_test_control(testctrl, -id, &val); |
| 13438 | if( rc2!=SQLITE_OK ) break; |
| 13439 | if( id>1 ) cli_puts(" ", p->out); |
| 13440 | cli_printf(p->out, "%d: %d", id, val); |
| 13441 | id++; |
| 13442 | } |
| 13443 | if( id>1 ) cli_puts("\n", p->out); |
| 13444 | isOk = 3; |
| 13445 | } |
| 13446 | break; |
| 13447 | } |
| 13448 | #endif |
| 13449 | case SQLITE_TESTCTRL_SORTER_MMAP: |
| 13450 | if( nArg==3 ){ |
| 13451 | int opt = (unsigned int)integerValue(azArg[2]); |
| 13452 | rc2 = sqlite3_test_control(testctrl, p->db, opt); |
| 13453 | isOk = 3; |
| 13454 | } |
| 13455 | break; |
| 13456 | case SQLITE_TESTCTRL_JSON_SELFCHECK: |
| 13457 | if( nArg==2 ){ |
| 13458 | rc2 = -1; |
| 13459 | isOk = 1; |
| 13460 | }else{ |
| 13461 | rc2 = booleanValue(azArg[2]); |
| 13462 | isOk = 3; |
| 13463 | } |
| 13464 | sqlite3_test_control(testctrl, &rc2); |
| 13465 | break; |
| 13466 | case SQLITE_TESTCTRL_BITVEC_TEST: { |
| 13467 | /* Examples: |
| 13468 | ** .testctrl bitvec_test 100 6,1 -- Show BITVEC constants |
| 13469 | ** .testctrl bitvec_test 1000 1,12,7,3 -- Simple test |
| 13470 | ** ---- -------- |
| 13471 | ** size of Bitvec -----^ ^--- aOp array. 0 added at end. |
| 13472 | ** |
| 13473 | ** See comments on sqlite3BitvecBuiltinTest() for more information |
| 13474 | ** about the aOp[] array. |
| 13475 | */ |
| 13476 | int iSize; |
| 13477 | const char *zTestArg; |
| 13478 | int nOp; |
| 13479 | int ii, jj, x; |
| 13480 | int *aOp; |
| 13481 | if( nArg!=4 ){ |
| 13482 | cli_printf(stderr, |
| 13483 | "ERROR - should be: \".testctrl bitvec_test SIZE INT-ARRAY\"\n" |
| 13484 | ); |
| 13485 | rc = 1; |
| 13486 | goto meta_command_exit; |
| 13487 | } |
| 13488 | isOk = 3; |
| 13489 | iSize = (int)integerValue(azArg[2]); |
| 13490 | zTestArg = azArg[3]; |
| 13491 | nOp = (int)strlen(zTestArg)+1; |
| 13492 | aOp = malloc( sizeof(int)*(nOp+1) ); |
| 13493 | shell_check_oom(aOp); |
| 13494 | memset(aOp, 0, sizeof(int)*(nOp+1) ); |
| 13495 | for(ii = jj = x = 0; zTestArg[ii]!=0; ii++){ |
| 13496 | if( IsDigit(zTestArg[ii]) ){ |
| 13497 | x = x*10 + zTestArg[ii] - '0'; |
| 13498 | }else{ |
| 13499 | aOp[jj++] = x; |
| 13500 | x = 0; |
| 13501 | } |
| 13502 | } |
| 13503 | aOp[jj] = x; |
| 13504 | x = sqlite3_test_control(testctrl, iSize, aOp); |
| 13505 | cli_printf(p->out, "result: %d\n", x); |
| 13506 | free(aOp); |
| 13507 | break; |
| 13508 | } |
| 13509 | case SQLITE_TESTCTRL_FAULT_INSTALL: { |
| 13510 | int kk; |
| 13511 | int bShowHelp = nArg<=2; |
| 13512 | isOk = 3; |
| 13513 | for(kk=2; kk<nArg; kk++){ |
| 13514 | const char *z = azArg[kk]; |
| 13515 | if( z[0]=='-' && z[1]=='-' ) z++; |
| 13516 | if( cli_strcmp(z,"off")==0 ){ |
| 13517 | sqlite3_test_control(testctrl, 0); |
| 13518 | }else if( cli_strcmp(z,"on")==0 ){ |
| 13519 | faultsim_state.iCnt = faultsim_state.nSkip; |
| 13520 | if( faultsim_state.iErr==0 ) faultsim_state.iErr = 1; |
| 13521 | faultsim_state.nHit = 0; |
| 13522 | sqlite3_test_control(testctrl, faultsim_callback); |
| 13523 | }else if( cli_strcmp(z,"reset")==0 ){ |
| 13524 | faultsim_state.iCnt = faultsim_state.nSkip; |
| 13525 | faultsim_state.nHit = 0; |
| 13526 | sqlite3_test_control(testctrl, faultsim_callback); |
| 13527 | }else if( cli_strcmp(z,"status")==0 ){ |
| 13528 | cli_printf(p->out, "faultsim.iId: %d\n", |
| 13529 | faultsim_state.iId); |
| 13530 | cli_printf(p->out, "faultsim.iErr: %d\n", |
| 13531 | faultsim_state.iErr); |
| 13532 | cli_printf(p->out, "faultsim.iCnt: %d\n", |
| 13533 | faultsim_state.iCnt); |
| 13534 | cli_printf(p->out, "faultsim.nHit: %d\n", |
| 13535 | faultsim_state.nHit); |
| 13536 | cli_printf(p->out, "faultsim.iInterval: %d\n", |
| 13537 | faultsim_state.iInterval); |
| 13538 | cli_printf(p->out, "faultsim.eVerbose: %d\n", |
| 13539 | faultsim_state.eVerbose); |
| 13540 | cli_printf(p->out, "faultsim.nRepeat: %d\n", |
| 13541 | faultsim_state.nRepeat); |
| 13542 | cli_printf(p->out, "faultsim.nSkip: %d\n", |
| 13543 | faultsim_state.nSkip); |
| 13544 | }else if( cli_strcmp(z,"-v")==0 ){ |
| 13545 | if( faultsim_state.eVerbose<2 ) faultsim_state.eVerbose++; |
| 13546 | }else if( cli_strcmp(z,"-q")==0 ){ |
| 13547 | if( faultsim_state.eVerbose>0 ) faultsim_state.eVerbose--; |
| 13548 | }else if( cli_strcmp(z,"-id")==0 && kk+1<nArg ){ |
| 13549 | faultsim_state.iId = atoi(azArg[++kk]); |
| 13550 | }else if( cli_strcmp(z,"-errcode")==0 && kk+1<nArg ){ |
| 13551 | faultsim_state.iErr = atoi(azArg[++kk]); |
| 13552 | }else if( cli_strcmp(z,"-interval")==0 && kk+1<nArg ){ |
| 13553 | faultsim_state.iInterval = atoi(azArg[++kk]); |
| 13554 | }else if( cli_strcmp(z,"-repeat")==0 && kk+1<nArg ){ |
| 13555 | faultsim_state.nRepeat = atoi(azArg[++kk]); |
| 13556 | }else if( cli_strcmp(z,"-skip")==0 && kk+1<nArg ){ |
| 13557 | faultsim_state.nSkip = atoi(azArg[++kk]); |
| 13558 | }else if( cli_strcmp(z,"-?")==0 || sqlite3_strglob("*help*",z)==0){ |
| 13559 | bShowHelp = 1; |
| 13560 | }else{ |
| 13561 | cli_printf(stderr, |
| 13562 | "Unrecognized fault_install argument: \"%s\"\n", |
| 13563 | azArg[kk]); |
| 13564 | rc = 1; |
| 13565 | bShowHelp = 1; |
| 13566 | break; |
| 13567 | } |
| 13568 | } |
| 13569 | if( bShowHelp ){ |
| 13570 | cli_puts( |
| 13571 | "Usage: .testctrl fault_install ARGS\n" |
| 13572 | "Possible arguments:\n" |
| 13573 | " off Disable faultsim\n" |
| 13574 | " on Activate faultsim\n" |
| 13575 | " reset Reset the trigger counter\n" |
| 13576 | " status Show current status\n" |
| 13577 | " -v Increase verbosity\n" |
| 13578 | " -q Decrease verbosity\n" |
| 13579 | " --errcode N When triggered, return N as error code\n" |
| 13580 | " --id ID Trigger only for the ID specified\n" |
| 13581 | " --interval N Trigger only after every N-th call\n" |
| 13582 | " --repeat N Turn off after N hits. 0 means never\n" |
| 13583 | " --skip N Skip the first N encounters\n" |
| 13584 | ,p->out |
| 13585 | ); |
| 13586 | } |
| 13587 | break; |
| 13588 | } |
| 13589 | } |
| 13590 | } |
| 13591 | if( isOk==0 && iCtrl>=0 ){ |
| 13592 | cli_printf(p->out, |
| 13593 | "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage); |
| 13594 | rc = 1; |
| 13595 | }else if( isOk==1 ){ |
| 13596 | cli_printf(p->out, "%d\n", rc2); |
| 13597 | }else if( isOk==2 ){ |
| 13598 | cli_printf(p->out, "0x%08x\n", rc2); |
| 13599 | } |
| 13600 | }else |
| 13601 | #endif /* !defined(SQLITE_UNTESTABLE) */ |
| 13602 | |
| 13603 | if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){ |
| 13604 | open_db(p, 0); |
| 13605 | sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); |
| 13606 | }else |
| 13607 | |
| 13608 | if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){ |
| 13609 | if( nArg==2 ){ |
| 13610 | if( cli_strcmp(azArg[1],"once")==0 ){ |
| 13611 | p->enableTimer = 1; |
| 13612 | }else{ |
| 13613 | p->enableTimer = 2*booleanValue(azArg[1]); |
| 13614 | } |
| 13615 | if( p->enableTimer && !HAS_TIMER ){ |
| 13616 | eputz("Error: timer not available on this system.\n"); |
| 13617 | p->enableTimer = 0; |
| 13618 | } |
| 13619 | }else{ |
| 13620 | eputz("Usage: .timer on|off|once\n"); |
| 13621 | rc = 1; |
| 13622 | } |
| 13623 | }else |
| 13624 | |
| 13625 | #ifndef SQLITE_OMIT_TRACE |
| 13626 | if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){ |
| 13627 | int mType = 0; |
| 13628 | int jj; |
| 13629 | open_db(p, 0); |
| 13630 | for(jj=1; jj<nArg; jj++){ |
| 13631 | const char *z = azArg[jj]; |
| 13632 | if( z[0]=='-' ){ |
| 13633 | if( optionMatch(z, "expanded") ){ |
| 13634 | p->eTraceType = SHELL_TRACE_EXPANDED; |
| 13635 | } |
| 13636 | #ifdef SQLITE_ENABLE_NORMALIZE |
| 13637 | else if( optionMatch(z, "normalized") ){ |
| 13638 | p->eTraceType = SHELL_TRACE_NORMALIZED; |
| 13639 | } |
| 13640 | #endif |
| 13641 | else if( optionMatch(z, "plain") ){ |
| 13642 | p->eTraceType = SHELL_TRACE_PLAIN; |
| 13643 | } |
| 13644 | else if( optionMatch(z, "profile") ){ |
| 13645 | mType |= SQLITE_TRACE_PROFILE; |
| 13646 | } |
| 13647 | else if( optionMatch(z, "row") ){ |
| 13648 | mType |= SQLITE_TRACE_ROW; |
| 13649 | } |
| 13650 | else if( optionMatch(z, "stmt") ){ |
| 13651 | mType |= SQLITE_TRACE_STMT; |
| 13652 | } |
| 13653 | else if( optionMatch(z, "close") ){ |
| 13654 | mType |= SQLITE_TRACE_CLOSE; |
| 13655 | } |
| 13656 | else { |
| 13657 | cli_printf(stderr,"Unknown option \"%s\" on \".trace\"\n", z); |
| 13658 | rc = 1; |
| 13659 | goto meta_command_exit; |
| 13660 | } |
| 13661 | }else{ |
| 13662 | output_file_close(p->traceOut); |
| 13663 | p->traceOut = output_file_open(p, z); |
| 13664 | } |
| 13665 | } |
| 13666 | if( p->traceOut==0 ){ |
| 13667 | sqlite3_trace_v2(p->db, 0, 0, 0); |
| 13668 | }else{ |
| 13669 | if( mType==0 ) mType = SQLITE_TRACE_STMT; |
| 13670 | sqlite3_trace_v2(p->db, mType, sql_trace_callback, p); |
| 13671 | } |
| 13672 | }else |
| 13673 | #endif /* !defined(SQLITE_OMIT_TRACE) */ |
| 13674 | |
| 13675 | #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE) |
| 13676 | if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){ |
| 13677 | int ii; |
| 13678 | int lenOpt; |
| 13679 | char *zOpt; |
| 13680 | if( nArg<2 ){ |
| 13681 | eputz("Usage: .unmodule [--allexcept] NAME ...\n"); |
| 13682 | rc = 1; |
| 13683 | goto meta_command_exit; |
| 13684 | } |
| 13685 | open_db(p, 0); |
| 13686 | zOpt = azArg[1]; |
| 13687 | if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++; |
| 13688 | lenOpt = (int)strlen(zOpt); |
| 13689 | if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){ |
| 13690 | assert( azArg[nArg]==0 ); |
| 13691 | sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0); |
| 13692 | }else{ |
| 13693 | for(ii=1; ii<nArg; ii++){ |
| 13694 | sqlite3_create_module(p->db, azArg[ii], 0, 0); |
| 13695 | } |
| 13696 | } |
| 13697 | }else |
| 13698 | #endif |
| 13699 | |
| 13700 | if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){ |
| 13701 | char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit"; |
| 13702 | cli_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/, |
| 13703 | sqlite3_libversion(), sqlite3_sourceid()); |
| 13704 | #if SQLITE_HAVE_ZLIB |
| 13705 | cli_printf(p->out, "zlib version %s\n", zlibVersion()); |
| 13706 | #endif |
| 13707 | #define CTIMEOPT_VAL_(opt) #opt |
| 13708 | #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) |
| 13709 | #if defined(__clang__) && defined(__clang_major__) |
| 13710 | cli_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "." |
| 13711 | CTIMEOPT_VAL(__clang_minor__) "." |
| 13712 | CTIMEOPT_VAL(__clang_patchlevel__) " (%s)\n", zPtrSz); |
| 13713 | #elif defined(_MSC_VER) |
| 13714 | cli_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz); |
| 13715 | #elif defined(__GNUC__) && defined(__VERSION__) |
| 13716 | cli_printf(p->out, "gcc-" __VERSION__ " (%s)\n", zPtrSz); |
| 13717 | #endif |
| 13718 | }else |
| 13719 | |
| 13720 | if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){ |
| 13721 | const char *zDbName = nArg==2 ? azArg[1] : "main"; |
| 13722 | sqlite3_vfs *pVfs = 0; |
| 13723 | if( p->db ){ |
| 13724 | sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); |
| 13725 | if( pVfs ){ |
| 13726 | cli_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName); |
| 13727 | cli_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); |
| 13728 | cli_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); |
| 13729 | cli_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); |
| 13730 | } |
| 13731 | } |
| 13732 | }else |
| 13733 | |
| 13734 | if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){ |
| 13735 | sqlite3_vfs *pVfs; |
| 13736 | sqlite3_vfs *pCurrent = 0; |
| 13737 | if( p->db ){ |
| 13738 | sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); |
| 13739 | } |
| 13740 | for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ |
| 13741 | cli_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName, |
| 13742 | pVfs==pCurrent ? " <--- CURRENT" : ""); |
| 13743 | cli_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); |
| 13744 | cli_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); |
| 13745 | cli_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); |
| 13746 | if( pVfs->pNext ){ |
| 13747 | cli_puts("-----------------------------------\n", p->out); |
| 13748 | } |
| 13749 | } |
| 13750 | }else |
| 13751 | |
| 13752 | if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){ |
| 13753 | const char *zDbName = nArg==2 ? azArg[1] : "main"; |
| 13754 | char *zVfsName = 0; |
| 13755 | if( p->db ){ |
| 13756 | sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); |
| 13757 | if( zVfsName ){ |
| 13758 | cli_printf(p->out, "%s\n", zVfsName); |
| 13759 | sqlite3_free(zVfsName); |
| 13760 | } |
| 13761 | } |
| 13762 | }else |
| 13763 | |
| 13764 | if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){ |
| 13765 | unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff; |
| 13766 | sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x); |
| 13767 | }else |
| 13768 | |
| 13769 | if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){ |
| 13770 | int j; |
| 13771 | p->mode.spec.nWidth = nArg-1; |
| 13772 | p->mode.spec.aWidth = realloc(p->mode.spec.aWidth, |
| 13773 | (p->mode.spec.nWidth+1)*sizeof(short int)); |
| 13774 | shell_check_oom(p->mode.spec.aWidth); |
| 13775 | for(j=1; j<nArg; j++){ |
| 13776 | i64 w = integerValue(azArg[j]); |
| 13777 | if( w < -QRF_MAX_WIDTH ) w = -QRF_MAX_WIDTH; |
| 13778 | if( w > QRF_MAX_WIDTH ) w = QRF_MAX_WIDTH; |
| 13779 | p->mode.spec.aWidth[j-1] = (short int)w; |
| 13780 | } |
| 13781 | }else |
| 13782 | |
| 13783 | { |
| 13784 | cli_printf(stderr,"Error: unknown command or invalid arguments: " |
| 13785 | " \"%s\". Enter \".help\" for help\n", azArg[0]); |
| 13786 | rc = 1; |
| 13787 | } |
| 13788 | |
| 13789 | meta_command_exit: |
| 13790 | if( p->nPopOutput ){ |
| 13791 | p->nPopOutput--; |
| 13792 | if( p->nPopOutput==0 ) output_reset(p); |
| 13793 | } |
| 13794 | p->bSafeMode = p->bSafeModePersist; |
| 13795 | p->dot.nArg = 0; |
| 13796 | return rc; |
| 13797 | } |
| 13798 | |
| 13799 | /* |
| 13800 | ** Test to see if a line consists entirely of whitespace. |
| 13801 | */ |
| 13802 | static int line_is_all_whitespace(const char *z){ |
| 13803 | for(; *z; z++){ |
| 13804 | if( IsSpace(z[0]) ) continue; |
| 13805 | if( *z=='/' && z[1]=='*' ){ |
| 13806 | z += 2; |
| 13807 | while( *z && (*z!='*' || z[1]!='/') ){ z++; } |
| 13808 | if( *z==0 ) return 0; |
| 13809 | z++; |
| 13810 | continue; |
| 13811 | } |
| 13812 | if( *z=='-' && z[1]=='-' ){ |
| 13813 | z += 2; |
| 13814 | while( *z && *z!='\n' ){ z++; } |
| 13815 | if( *z==0 ) return 1; |
| 13816 | continue; |
| 13817 | } |
| 13818 | return 0; |
| 13819 | } |
| 13820 | return 1; |
| 13821 | } |
| 13822 | |
| 13823 | /* |
| 13824 | ** The CLI needs a working sqlite3_complete() to work properly. So error |
| 13825 | ** out of the build if compiling with SQLITE_OMIT_COMPLETE. |
| 13826 | */ |
| 13827 | #ifdef SQLITE_OMIT_COMPLETE |
| 13828 | # error the CLI application is incompatible with SQLITE_OMIT_COMPLETE. |
| 13829 | #endif |
| 13830 | |
| 13831 | #ifdef SQLITE_SHELL_LEGACY_COMMAND_TERMINATOR |
| 13832 | /* |
| 13833 | ** Return TRUE if the line typed in is an SQL command terminator other |
| 13834 | ** than a semi-colon. The SQL Server style "go" command is understood |
| 13835 | ** as is the Oracle "/". |
| 13836 | */ |
| 13837 | static int line_is_command_terminator( |
| 13838 | const char *zLine, /* Current line of input */ |
| 13839 | char *zSql, /* Total accumulated input text */ |
| 13840 | int nSql /* Bytes of accumulated input text */ |
| 13841 | ){ |
| 13842 | while( IsSpace(zLine[0]) ){ zLine++; }; |
| 13843 | if( (zLine[0]=='/' && line_is_all_whitespace(&zLine[1])) /* Oracle */ |
| 13844 | || (sqlite3_strnicmp(zLine,"go",2)==0 |
| 13845 | && line_is_all_whitespace(&zLine[2])) /* SQL Server */ |
| 13846 | }{ |
| 13847 | int rc; |
| 13848 | if( zSql==0 ) return 1; |
| 13849 | zSql[nSql] = ';'; |
| 13850 | zSql[nSql+1] = 0; |
| 13851 | rc = sqlite3_complete(zSql); |
| 13852 | zSql[nSql] = 0; |
| 13853 | return rc; |
| 13854 | } |
| 13855 | return 0; |
| 13856 | } |
| 13857 | #endif |
| 13858 | |
| 13859 | /* |
| 13860 | ** This function is called after processing each line of SQL in the |
| 13861 | ** runOneSqlLine() function. Its purpose is to detect scenarios where |
| 13862 | ** defensive mode should be automatically turned off. Specifically, when |
| 13863 | ** |
| 13864 | ** 1. The first line of input is "PRAGMA foreign_keys=OFF;", |
| 13865 | ** 2. The second line of input is "BEGIN TRANSACTION;", |
| 13866 | ** 3. The database is empty, and |
| 13867 | ** 4. The shell is not running in --safe mode. |
| 13868 | ** |
| 13869 | ** The implementation uses the ShellState.eRestoreState to maintain state: |
| 13870 | ** |
| 13871 | ** 0: Have not seen any SQL. |
| 13872 | ** 1: Have seen "PRAGMA foreign_keys=OFF;". |
| 13873 | ** 2-6: Currently running .dump transaction. If the "2" bit is set, |
| 13874 | ** disable DEFENSIVE when done. If "4" is set, disable DQS_DDL. |
| 13875 | ** 7: Nothing left to do. This function becomes a no-op. |
| 13876 | */ |
| 13877 | static int doAutoDetectRestore(ShellState *p, const char *zSql){ |
| 13878 | int rc = SQLITE_OK; |
| 13879 | |
| 13880 | if( p->eRestoreState<7 ){ |
| 13881 | switch( p->eRestoreState ){ |
| 13882 | case 0: { |
| 13883 | const char *zExpect = "PRAGMA foreign_keys=OFF;"; |
| 13884 | assert( strlen(zExpect)==24 ); |
| 13885 | if( p->bSafeMode==0 |
| 13886 | && strlen(zSql)>=24 |
| 13887 | && memcmp(zSql, zExpect, 25)==0 |
| 13888 | ){ |
| 13889 | p->eRestoreState = 1; |
| 13890 | }else{ |
| 13891 | p->eRestoreState = 7; |
| 13892 | } |
| 13893 | break; |
| 13894 | }; |
| 13895 | |
| 13896 | case 1: { |
| 13897 | int bIsDump = 0; |
| 13898 | const char *zExpect = "BEGIN TRANSACTION;"; |
| 13899 | assert( strlen(zExpect)==18 ); |
| 13900 | if( memcmp(zSql, zExpect, 19)==0 ){ |
| 13901 | /* Now check if the database is empty. */ |
| 13902 | const char *zQuery = "SELECT 1 FROM sqlite_schema LIMIT 1"; |
| 13903 | sqlite3_stmt *pStmt = 0; |
| 13904 | |
| 13905 | bIsDump = 1; |
| 13906 | shellPrepare(p->db, &rc, zQuery, &pStmt); |
| 13907 | if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 13908 | bIsDump = 0; |
| 13909 | } |
| 13910 | shellFinalize(&rc, pStmt); |
| 13911 | } |
| 13912 | if( bIsDump && rc==SQLITE_OK ){ |
| 13913 | int bDefense = 0; |
| 13914 | int bDqsDdl = 0; |
| 13915 | sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense); |
| 13916 | sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl); |
| 13917 | sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, (int*)0); |
| 13918 | sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, (int*)0); |
| 13919 | p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0); |
| 13920 | }else{ |
| 13921 | p->eRestoreState = 7; |
| 13922 | } |
| 13923 | break; |
| 13924 | } |
| 13925 | |
| 13926 | default: { |
| 13927 | if( sqlite3_get_autocommit(p->db) ){ |
| 13928 | if( (p->eRestoreState & 2) ){ |
| 13929 | sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, (int*)0); |
| 13930 | } |
| 13931 | if( (p->eRestoreState & 4) ){ |
| 13932 | sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, (int*)0); |
| 13933 | } |
| 13934 | p->eRestoreState = 7; |
| 13935 | } |
| 13936 | break; |
| 13937 | } |
| 13938 | } |
| 13939 | } |
| 13940 | |
| 13941 | return rc; |
| 13942 | } |
| 13943 | |
| 13944 | /* |
| 13945 | ** When the (undocumented) command-line option --test-parse is used, |
| 13946 | ** this routine is run instead of runOneSqlLine() to process SQL. Don't |
| 13947 | ** actually run any SQL. Instead just provide a one-line summary of the |
| 13948 | ** SQL that would have run. |
| 13949 | */ |
| 13950 | static void runTestParse( |
| 13951 | ShellState *p, /* Execution context */ |
| 13952 | char *zSql /* SQL to be run */ |
| 13953 | ){ |
| 13954 | int nNL = 0; |
| 13955 | char *zNL; |
| 13956 | size_t i, j, n; |
| 13957 | int nPre = 0; |
| 13958 | int nSuf = 0; |
| 13959 | int mxPre = 20; |
| 13960 | char zPre[50], zSuf[50]; |
| 13961 | |
| 13962 | for(zNL=strchr(zSql,'\n'); zNL!=0; zNL=strchr(zNL+1,'\n')){ nNL++; } |
| 13963 | n = strlen(zSql); |
| 13964 | if( n<40 ) mxPre = 40; |
| 13965 | for(i=0; nPre<mxPre && i<n; i++){ |
| 13966 | char c = zSql[i]; |
| 13967 | if( c=='\n' ){ |
| 13968 | zPre[nPre++] = '\\'; |
| 13969 | zPre[nPre++] = 'n'; |
| 13970 | }else if( c>0 && c<' ' ){ |
| 13971 | zPre[nPre++] = '^'; |
| 13972 | zPre[nPre++] = c+0x40; |
| 13973 | }else{ |
| 13974 | zPre[nPre++] = c; |
| 13975 | } |
| 13976 | } |
| 13977 | zPre[nPre] = 0; |
| 13978 | if( n<=i+20 ){ |
| 13979 | j = i; |
| 13980 | }else{ |
| 13981 | j = n - 20; |
| 13982 | memcpy(zSuf," ... ", 5); |
| 13983 | nSuf = 5; |
| 13984 | } |
| 13985 | for(i=j; i<n; i++){ |
| 13986 | char c = zSql[i]; |
| 13987 | if( c=='\n' ){ |
| 13988 | zSuf[nSuf++] = '\\'; |
| 13989 | zSuf[nSuf++] = 'n'; |
| 13990 | }else if( c>0 && c<' ' ){ |
| 13991 | zSuf[nSuf++] = '^'; |
| 13992 | zSuf[nSuf++] = c+0x40; |
| 13993 | }else{ |
| 13994 | zSuf[nSuf++] = c; |
| 13995 | } |
| 13996 | } |
| 13997 | zSuf[nSuf] = 0; |
| 13998 | cli_printf(p->out, "%d line%s: %s%s\n", nNL+1, (nNL?"s":""), zPre, zSuf); |
| 13999 | } |
| 14000 | |
| 14001 | /* |
| 14002 | ** Run a single line of SQL. Return the number of errors. |
| 14003 | */ |
| 14004 | static int runOneSqlLine( |
| 14005 | ShellState *p, /* Execution context */ |
| 14006 | char *zSql, /* SQL to be run */ |
| 14007 | const char *zFilename, /* Source file of the sql */ |
| 14008 | int startline /* linenumber */ |
| 14009 | ){ |
| 14010 | int rc; |
| 14011 | char *zErrMsg = 0; |
| 14012 | |
| 14013 | open_db(p, 0); |
| 14014 | if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql); |
| 14015 | if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; |
| 14016 | if( p->bTestParse ){ |
| 14017 | runTestParse(p, zSql); |
| 14018 | rc = SQLITE_OK; |
| 14019 | }else{ |
| 14020 | BEGIN_TIMER(p); |
| 14021 | rc = shell_exec(p, zSql, &zErrMsg); |
| 14022 | END_TIMER(p); |
| 14023 | } |
| 14024 | if( rc || zErrMsg ){ |
| 14025 | sqlite3_str *pPrefix = sqlite3_str_new(p->db); |
| 14026 | const char *zErrorTail; |
| 14027 | const char *zErrorType; |
| 14028 | if( zErrMsg==0 ){ |
| 14029 | zErrorType = "Error"; |
| 14030 | zErrorTail = sqlite3_errmsg(p->db); |
| 14031 | }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){ |
| 14032 | zErrorType = "Parse error"; |
| 14033 | zErrorTail = &zErrMsg[12]; |
| 14034 | }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){ |
| 14035 | zErrorType = "Runtime error"; |
| 14036 | zErrorTail = &zErrMsg[10]; |
| 14037 | }else{ |
| 14038 | zErrorType = "Error"; |
| 14039 | zErrorTail = zErrMsg; |
| 14040 | } |
| 14041 | if( zFilename || !stdin_is_interactive ){ |
| 14042 | if( cli_strcmp(zFilename,"cmdline")==0 ){ |
| 14043 | sqlite3_str_appendf(pPrefix, |
| 14044 | "%s in %r command line argument:", zErrorType, startline); |
| 14045 | }else if( cli_strcmp(zFilename,"<stdin>")==0 ){ |
| 14046 | sqlite3_str_appendf(pPrefix, |
| 14047 | "%s near line %d:", zErrorType, startline); |
| 14048 | }else{ |
| 14049 | sqlite3_str_appendf(pPrefix, |
| 14050 | "%s near line %d of %s:", zErrorType, startline, zFilename); |
| 14051 | } |
| 14052 | }else{ |
| 14053 | sqlite3_str_appendf(pPrefix, "%s:", zErrorType); |
| 14054 | } |
| 14055 | cli_printf(stderr,"%s %s\n", sqlite3_str_value(pPrefix), zErrorTail); |
| 14056 | sqlite3_str_free(pPrefix); |
| 14057 | sqlite3_free(zErrMsg); |
| 14058 | zErrMsg = 0; |
| 14059 | return 1; |
| 14060 | }else if( ShellHasFlag(p, SHFLG_CountChanges) ){ |
| 14061 | cli_printf(p->out, |
| 14062 | "changes: %lld total_changes: %lld\n", |
| 14063 | sqlite3_changes64(p->db), sqlite3_total_changes64(p->db)); |
| 14064 | } |
| 14065 | |
| 14066 | if( doAutoDetectRestore(p, zSql) ) return 1; |
| 14067 | return 0; |
| 14068 | } |
| 14069 | |
| 14070 | static void echo_group_input(ShellState *p, const char *zDo){ |
| 14071 | if( p->mode.mFlags & MFLG_ECHO ){ |
| 14072 | sqlite3_str *savedCliCapture = cli_output_capture; |
| 14073 | cli_output_capture = 0; /* .echo should not be captured by .testcase */ |
| 14074 | cli_printf(p->out, "%s\n", zDo); |
| 14075 | fflush(p->out); |
| 14076 | cli_output_capture = savedCliCapture; |
| 14077 | } |
| 14078 | } |
| 14079 | |
| 14080 | #ifdef SQLITE_SHELL_FIDDLE |
| 14081 | /* |
| 14082 | ** Alternate one_input_line() impl for wasm mode. This is not in the primary |
| 14083 | ** impl because we need the global shellState and cannot access it from that |
| 14084 | ** function without moving lots of code around (creating a larger/messier diff). |
| 14085 | */ |
| 14086 | static char *one_input_line( |
| 14087 | ShellState *p, /* Shell state */ |
| 14088 | char *zPrior, /* Just the prior line of text */ |
| 14089 | const char *zAll, /* All accumulated statement text */ |
| 14090 | int bContinue /* True if this is an accumulation */ |
| 14091 | ){ |
| 14092 | /* Parse the next line from shellState.wasm.zInput. */ |
| 14093 | const char *zBegin = shellState.wasm.zPos; |
| 14094 | const char *z = zBegin; |
| 14095 | char *zLine = 0; |
| 14096 | i64 nZ = 0; |
| 14097 | FILE *in = p->in; |
| 14098 | |
| 14099 | UNUSED_PARAMETER(in); |
| 14100 | UNUSED_PARAMETER(bContinue); |
| 14101 | if(!z || !*z){ |
| 14102 | return 0; |
| 14103 | } |
| 14104 | while(*z && IsSpace(*z)) ++z; |
| 14105 | zBegin = z; |
| 14106 | for(; *z && '\n'!=*z; ++nZ, ++z){} |
| 14107 | if(nZ>0 && '\r'==zBegin[nZ-1]){ |
| 14108 | --nZ; |
| 14109 | } |
| 14110 | shellState.wasm.zPos = z; |
| 14111 | zLine = realloc(zPrior, nZ+1); |
| 14112 | shell_check_oom(zLine); |
| 14113 | memcpy(zLine, zBegin, nZ); |
| 14114 | zLine[nZ] = 0; |
| 14115 | return zLine; |
| 14116 | } |
| 14117 | #endif /* SQLITE_SHELL_FIDDLE */ |
| 14118 | |
| 14119 | /* |
| 14120 | ** Return true if the input would is complete SQL, or complete SQL |
| 14121 | ** followed by only whitespace. This is similar to sqlite3_complete() |
| 14122 | ** except that if the final semicolon is followed by whitespace, it |
| 14123 | ** still returns true. |
| 14124 | */ |
| 14125 | static int line_is_complete(char *zSql, int nSql){ |
| 14126 | sqlite3_int64 x; |
| 14127 | assert( nSql>=0 && zSql[nSql]==0 ); |
| 14128 | x = sqlite3_incomplete(zSql); |
| 14129 | if( x==0x00 || x==0x10 ) return 1; |
| 14130 | if( x==0x2d0001 ){ |
| 14131 | zSql[nSql] = '\n'; |
| 14132 | zSql[nSql+1] = 0; |
| 14133 | x = sqlite3_incomplete(zSql); |
| 14134 | zSql[nSql] = 0; |
| 14135 | if( x==0x00 || x==0x10 ) return 1; |
| 14136 | } |
| 14137 | return 0; |
| 14138 | } |
| 14139 | |
| 14140 | /* |
| 14141 | ** Return true if zLine is a dot-command that should always be run |
| 14142 | ** even if inside of the false leg of an ".if" |
| 14143 | */ |
| 14144 | static int alwaysRun(const char *zLine){ |
| 14145 | const char *az[] = { |
| 14146 | "3.if", |
| 14147 | "7.elseif", |
| 14148 | "5.else", |
| 14149 | "6.endif", |
| 14150 | "6.check", /* For its heredoc */ |
| 14151 | "5.read", /* For its heredoc */ |
| 14152 | "0" |
| 14153 | }; |
| 14154 | int jj, n; |
| 14155 | for(jj=0; (n = az[jj][0] - '0')>0; jj++){ |
| 14156 | if( strncmp(zLine,az[jj]+1,n)==0 && (IsSpace(zLine[n]) || zLine[n]==0) ){ |
| 14157 | return 1; |
| 14158 | } |
| 14159 | } |
| 14160 | return 0; |
| 14161 | } |
| 14162 | |
| 14163 | |
| 14164 | /* |
| 14165 | ** Read input from *in and process it. If *in==0 then input |
| 14166 | ** is interactive - the user is typing it it. Otherwise, input |
| 14167 | ** is coming from a file or device. A prompt is issued and history |
| 14168 | ** is saved only if input is interactive. An interrupt signal will |
| 14169 | ** cause this routine to exit immediately, unless input is interactive. |
| 14170 | ** |
| 14171 | ** Return the number of errors. |
| 14172 | */ |
| 14173 | static int process_input(ShellState *p, const char *zSrc){ |
| 14174 | char *zLine = 0; /* A single input line */ |
| 14175 | char *zSql = 0; /* Accumulated SQL text */ |
| 14176 | i64 nLine; /* Length of current line */ |
| 14177 | i64 nSql = 0; /* Bytes of zSql[] used */ |
| 14178 | i64 nAlloc = 0; /* Allocated zSql[] space */ |
| 14179 | int rc; /* Error code */ |
| 14180 | int errCnt = 0; /* Number of errors seen */ |
| 14181 | int hasSemi = 0; /* Input line contains a semicolon */ |
| 14182 | i64 startline = 0; /* Line number for start of current input */ |
| 14183 | const char *saved_zInFile; /* Prior value of p->zInFile */ |
| 14184 | i64 saved_lineno; /* Prior value of p->lineno */ |
| 14185 | int saved_nIfAtStart; /* Prior value of p->nIfAtStart */ |
| 14186 | |
| 14187 | if( p->inputNesting==MAX_INPUT_NESTING ){ |
| 14188 | /* This will be more informative in a later version. */ |
| 14189 | cli_printf(stderr,"%s: Input nesting limit (%d) reached at line %lld." |
| 14190 | " Check recursion.\n", zSrc, MAX_INPUT_NESTING, p->lineno); |
| 14191 | return 1; |
| 14192 | } |
| 14193 | ++p->inputNesting; |
| 14194 | saved_zInFile = p->zInFile; |
| 14195 | p->zInFile = zSrc; |
| 14196 | saved_lineno = p->lineno; |
| 14197 | p->lineno = 0; |
| 14198 | saved_nIfAtStart = p->nIfAtStart; |
| 14199 | p->nIfAtStart = p->nIfLevel; |
| 14200 | while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){ |
| 14201 | fflush(p->out); |
| 14202 | zLine = one_input_line(p, zLine, zSql, nSql>0); |
| 14203 | if( zLine==0 ){ |
| 14204 | /* End of input */ |
| 14205 | if( p->in==0 && stdin_is_interactive ) cli_puts("\n", p->out); |
| 14206 | break; |
| 14207 | } |
| 14208 | if( seenInterrupt ){ |
| 14209 | if( p->in!=0 ) break; |
| 14210 | seenInterrupt = 0; |
| 14211 | } |
| 14212 | p->lineno++; |
| 14213 | if( nSql==0 && line_is_all_whitespace(zLine) ){ |
| 14214 | /* Just swallow single-line whitespace */ |
| 14215 | echo_group_input(p, zLine); |
| 14216 | continue; |
| 14217 | } |
| 14218 | if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){ |
| 14219 | echo_group_input(p, zLine); |
| 14220 | if( zLine[0]=='.' ){ |
| 14221 | if( p->mIf==0 || alwaysRun(zLine) ){ |
| 14222 | rc = do_meta_command(zLine, p); |
| 14223 | if( rc==2 ){ /* exit requested */ |
| 14224 | p->nIfLevel = p->nIfAtStart; |
| 14225 | break; |
| 14226 | }else if( rc ){ |
| 14227 | errCnt++; |
| 14228 | } |
| 14229 | } |
| 14230 | } |
| 14231 | continue; |
| 14232 | } |
| 14233 | #ifdef SQLITE_SHELL_LEGACY_COMMAND_TERMINATOR |
| 14234 | if( line_is_command_terminator(zLine, zSql, nSql) ){ |
| 14235 | memcpy(zLine,";",2); |
| 14236 | } |
| 14237 | #endif |
| 14238 | if( strchr(zLine,';')!=0 ) hasSemi = 1; |
| 14239 | nLine = strlen(zLine); |
| 14240 | if( nSql+nLine+4>=nAlloc ){ |
| 14241 | /* Grow buffer by half-again increments when big. */ |
| 14242 | nAlloc = nSql+(nSql>>1)+nLine+100; |
| 14243 | zSql = realloc(zSql, nAlloc); |
| 14244 | shell_check_oom(zSql); |
| 14245 | } |
| 14246 | if( nSql==0 ){ |
| 14247 | i64 i; |
| 14248 | for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} |
| 14249 | assert( nAlloc>0 && zSql!=0 ); |
| 14250 | memcpy(zSql, zLine+i, nLine+1-i); |
| 14251 | startline = p->lineno; |
| 14252 | nSql = nLine-i; |
| 14253 | }else{ |
| 14254 | zSql[nSql++] = '\n'; |
| 14255 | memcpy(zSql+nSql, zLine, nLine+1); |
| 14256 | nSql += nLine; |
| 14257 | } |
| 14258 | if( nSql>0x7fff0000 ){ |
| 14259 | char zSize[100]; |
| 14260 | sqlite3_snprintf(sizeof(zSize),zSize,"%,lld",nSql); |
| 14261 | cli_printf(stderr, "%s:%lld: Input SQL is too big: %s bytes\n", |
| 14262 | zSrc, startline, zSize); |
| 14263 | nSql = 0; |
| 14264 | errCnt++; |
| 14265 | break; |
| 14266 | } |
| 14267 | if( nSql && hasSemi && line_is_complete(zSql, nSql) ){ |
| 14268 | echo_group_input(p, zSql); |
| 14269 | if( p->mIf==0 ){ |
| 14270 | errCnt += runOneSqlLine(p, zSql, p->zInFile, startline); |
| 14271 | } |
| 14272 | nSql = 0; |
| 14273 | if( p->nPopOutput ){ |
| 14274 | output_reset(p); |
| 14275 | p->nPopOutput = 0; |
| 14276 | }else{ |
| 14277 | clearTempFile(p,0,0); |
| 14278 | } |
| 14279 | if( p->nPopMode ){ |
| 14280 | modePop(p); |
| 14281 | p->nPopMode = 0; |
| 14282 | } |
| 14283 | p->bSafeMode = p->bSafeModePersist; |
| 14284 | }else if( nSql && line_is_all_whitespace(zSql) ){ |
| 14285 | echo_group_input(p, zSql); |
| 14286 | nSql = 0; |
| 14287 | } |
| 14288 | } |
| 14289 | if( nSql ){ |
| 14290 | /* This may be incomplete. Let the SQL parser deal with that. */ |
| 14291 | echo_group_input(p, zSql); |
| 14292 | if( p->mIf==0 ){ |
| 14293 | errCnt += runOneSqlLine(p, zSql, p->zInFile, startline); |
| 14294 | } |
| 14295 | } |
| 14296 | free(zSql); |
| 14297 | free(zLine); |
| 14298 | --p->inputNesting; |
| 14299 | while( p->nIfLevel > p->nIfAtStart ){ |
| 14300 | int ii = --p->nIfLevel; |
| 14301 | cli_printf(stderr,"%s:%lld: unterminated .if\n", zSrc, p->lnIf[ii]); |
| 14302 | p->mIf &= ~(1<<ii); |
| 14303 | p->mElse &= ~(1<<ii); |
| 14304 | p->mIfHasBeenTrue &= ~(1<<ii); |
| 14305 | errCnt++; |
| 14306 | } |
| 14307 | p->zInFile = saved_zInFile; |
| 14308 | p->lineno = saved_lineno; |
| 14309 | p->nIfAtStart = saved_nIfAtStart; |
| 14310 | return errCnt>0; |
| 14311 | } |
| 14312 | |
| 14313 | /* |
| 14314 | ** Return a pathname which is the user's home directory. A |
| 14315 | ** 0 return indicates an error of some kind. |
| 14316 | */ |
| 14317 | static char *find_home_dir(int clearFlag){ |
| 14318 | static char *home_dir = NULL; |
| 14319 | if( clearFlag ){ |
| 14320 | free(home_dir); |
| 14321 | home_dir = 0; |
| 14322 | return 0; |
| 14323 | } |
| 14324 | if( home_dir ) return home_dir; |
| 14325 | |
| 14326 | #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \ |
| 14327 | && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI) |
| 14328 | { |
| 14329 | struct passwd *pwent; |
| 14330 | uid_t uid = getuid(); |
| 14331 | if( (pwent=getpwuid(uid)) != NULL) { |
| 14332 | home_dir = pwent->pw_dir; |
| 14333 | } |
| 14334 | } |
| 14335 | #endif |
| 14336 | |
| 14337 | #if defined(_WIN32_WCE) |
| 14338 | /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() |
| 14339 | */ |
| 14340 | home_dir = "/"; |
| 14341 | #else |
| 14342 | |
| 14343 | #if defined(_WIN32) || defined(WIN32) |
| 14344 | if (!home_dir) { |
| 14345 | home_dir = getenv("USERPROFILE"); |
| 14346 | } |
| 14347 | #endif |
| 14348 | |
| 14349 | if (!home_dir) { |
| 14350 | home_dir = getenv("HOME"); |
| 14351 | } |
| 14352 | |
| 14353 | #if defined(_WIN32) || defined(WIN32) |
| 14354 | if (!home_dir) { |
| 14355 | char *zDrive, *zPath; |
| 14356 | int n; |
| 14357 | zDrive = getenv("HOMEDRIVE"); |
| 14358 | zPath = getenv("HOMEPATH"); |
| 14359 | if( zDrive && zPath ){ |
| 14360 | n = strlen30(zDrive) + strlen30(zPath) + 1; |
| 14361 | home_dir = malloc( n ); |
| 14362 | if( home_dir==0 ) return 0; |
| 14363 | sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); |
| 14364 | return home_dir; |
| 14365 | } |
| 14366 | home_dir = "c:\\"; |
| 14367 | } |
| 14368 | #endif |
| 14369 | |
| 14370 | #endif /* !_WIN32_WCE */ |
| 14371 | |
| 14372 | if( home_dir ){ |
| 14373 | i64 n = strlen(home_dir) + 1; |
| 14374 | char *z = malloc( n ); |
| 14375 | if( z ) memcpy(z, home_dir, n); |
| 14376 | home_dir = z; |
| 14377 | } |
| 14378 | |
| 14379 | return home_dir; |
| 14380 | } |
| 14381 | |
| 14382 | /* |
| 14383 | ** On non-Windows platforms, look for: |
| 14384 | ** |
| 14385 | ** - ${zEnvVar}/${zBaseName} |
| 14386 | ** - ${HOME}/${zSubdir}/${zBaseName} |
| 14387 | ** |
| 14388 | ** $zEnvVar is intended to be the name of an XDG_... environment |
| 14389 | ** variable, e.g. XDG_CONFIG_HOME or XDG_STATE_HOME. If zEnvVar is |
| 14390 | ** NULL or getenv(zEnvVar) is NULL then fall back to the second |
| 14391 | ** option. If the selected option is not found in the filesystem, |
| 14392 | ** return 0. |
| 14393 | ** |
| 14394 | ** zSubdir may be NULL or empty, in which case ${HOME}/${zBaseName} |
| 14395 | ** becomes the fallback. |
| 14396 | ** |
| 14397 | ** Both zSubdir and zBaseName may contain subdirectory parts. zSubdir |
| 14398 | ** will conventionally be ".config" or ".local/state", which, not |
| 14399 | ** coincidentally, is the typical subdir of the corresponding XDG_... |
| 14400 | ** var with the XDG var's $HOME prefix. |
| 14401 | ** |
| 14402 | ** The returned string is obtained from sqlite3_malloc() and should be |
| 14403 | ** sqlite3_free()'d by the caller. |
| 14404 | */ |
| 14405 | static char *find_xdg_file(const char *zEnvVar, const char *zSubdir, |
| 14406 | const char *zBaseName){ |
| 14407 | #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \ |
| 14408 | || defined(__RTP__) || defined(_WRS_KERNEL) |
| 14409 | return 0; |
| 14410 | #else |
| 14411 | char *zConfigFile = 0; |
| 14412 | const char *zXdgDir; |
| 14413 | |
| 14414 | zXdgDir = zEnvVar ? getenv(zEnvVar) : 0; |
| 14415 | if( zXdgDir ){ |
| 14416 | zConfigFile = sqlite3_mprintf("%s/%s", zXdgDir, zBaseName); |
| 14417 | }else{ |
| 14418 | const char * zHome = find_home_dir(0); |
| 14419 | if( zHome==0 ) return 0; |
| 14420 | zConfigFile = (zSubdir && *zSubdir) |
| 14421 | ? sqlite3_mprintf("%s/%s/%s", zHome, zSubdir, zBaseName) |
| 14422 | : sqlite3_mprintf("%s/%s", zHome, zBaseName); |
| 14423 | } |
| 14424 | shell_check_oom(zConfigFile); |
| 14425 | if( access(zConfigFile,0)!=0 ){ |
| 14426 | sqlite3_free(zConfigFile); |
| 14427 | zConfigFile = 0; |
| 14428 | } |
| 14429 | return zConfigFile; |
| 14430 | #endif |
| 14431 | } |
| 14432 | |
| 14433 | /* |
| 14434 | ** Read input from the file sqliterc_override. If that parameter is |
| 14435 | ** NULL, take it from find_xdg_file(), if found, or fall back to |
| 14436 | ** ~/.sqliterc. |
| 14437 | ** |
| 14438 | ** Failure to read the config is only considered a failure if |
| 14439 | ** sqliterc_override is not NULL, in which case this function may emit |
| 14440 | ** a warning or, if ::bail_on_error is true, fail fatally if the file |
| 14441 | ** named by sqliterc_override is not found. |
| 14442 | */ |
| 14443 | static void process_sqliterc( |
| 14444 | ShellState *p, /* Configuration data */ |
| 14445 | const char *sqliterc_override /* Name of config file. NULL to use default */ |
| 14446 | ){ |
| 14447 | char *home_dir = NULL; |
| 14448 | char *sqliterc = (char*)sqliterc_override; |
| 14449 | FILE *inSaved = p->in; |
| 14450 | i64 savedLineno = p->lineno; |
| 14451 | |
| 14452 | if( sqliterc == NULL ){ |
| 14453 | sqliterc = find_xdg_file("XDG_CONFIG_HOME", |
| 14454 | ".config", |
| 14455 | "sqlite3/sqliterc"); |
| 14456 | } |
| 14457 | if( sqliterc == NULL ){ |
| 14458 | home_dir = find_home_dir(0); |
| 14459 | if( home_dir==0 ){ |
| 14460 | eputz("-- warning: cannot find home directory;" |
| 14461 | " cannot read ~/.sqliterc\n"); |
| 14462 | return; |
| 14463 | } |
| 14464 | sqliterc = sqlite3_mprintf("%s/.sqliterc",home_dir); |
| 14465 | shell_check_oom(sqliterc); |
| 14466 | } |
| 14467 | p->in = sqliterc ? sqlite3_fopen(sqliterc,"rb") : 0; |
| 14468 | if( p->in ){ |
| 14469 | if( stdin_is_interactive ){ |
| 14470 | cli_printf(stderr,"-- Loading resources from %s\n", sqliterc); |
| 14471 | } |
| 14472 | if( process_input(p, sqliterc) && bail_on_error ) cli_exit(1); |
| 14473 | fclose(p->in); |
| 14474 | }else if( sqliterc_override!=0 ){ |
| 14475 | cli_printf(stderr,"cannot open: \"%s\"\n", sqliterc); |
| 14476 | if( bail_on_error ) cli_exit(1); |
| 14477 | } |
| 14478 | p->in = inSaved; |
| 14479 | p->lineno = savedLineno; |
| 14480 | if( sqliterc != sqliterc_override ){ |
| 14481 | sqlite3_free(sqliterc); |
| 14482 | } |
| 14483 | } |
| 14484 | |
| 14485 | /* |
| 14486 | ** Show available command line options |
| 14487 | */ |
| 14488 | static const char zOptions[] = |
| 14489 | " -- treat no subsequent arguments as options\n" |
| 14490 | #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) |
| 14491 | " -A ARGS... run \".archive ARGS\" and exit\n" |
| 14492 | #endif |
| 14493 | " -append append the database to the end of the file\n" |
| 14494 | " -ascii set '.mode ascii'\n" |
| 14495 | " -bail stop after hitting an error\n" |
| 14496 | " -batch force batch I/O\n" |
| 14497 | " -box set '.mode box'\n" |
| 14498 | " -cmd COMMAND run \"COMMAND\" before reading stdin\n" |
| 14499 | " -cmdline-edit BOOL enable or disable command-line editing\n" |
| 14500 | " -column set '.mode column'\n" |
| 14501 | " -csv set '.mode csv -limits off'\n" |
| 14502 | #if !defined(SQLITE_OMIT_DESERIALIZE) |
| 14503 | " -deserialize open the database using sqlite3_deserialize()\n" |
| 14504 | #endif |
| 14505 | " -echo print inputs before execution\n" |
| 14506 | " -escape T ctrl-char escape; T is one of: symbol, ascii, off\n" |
| 14507 | " -init FILENAME read/process named file\n" |
| 14508 | " -[no]header turn headers on or off\n" |
| 14509 | #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) |
| 14510 | " -heap SIZE Size of heap for memsys3 or memsys5\n" |
| 14511 | #endif |
| 14512 | " -help show this message\n" |
| 14513 | " -html set '.mode html'\n" |
| 14514 | " -ifexists only open if database already exists\n" |
| 14515 | " -interactive force interactive I/O\n" |
| 14516 | " -json set '.mode json'\n" |
| 14517 | " -line set '.mode line'\n" |
| 14518 | " -list set '.mode list'\n" |
| 14519 | " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n" |
| 14520 | " -markdown set '.mode markdown'\n" |
| 14521 | #if !defined(SQLITE_OMIT_DESERIALIZE) |
| 14522 | " -maxsize N maximum size for a --deserialize database\n" |
| 14523 | #endif |
| 14524 | " -memtrace trace all memory allocations and deallocations\n" |
| 14525 | " -mmap N default mmap size set to N\n" |
| 14526 | #ifdef SQLITE_ENABLE_MULTIPLEX |
| 14527 | " -multiplex enable the multiplexor VFS\n" |
| 14528 | #endif |
| 14529 | " -newline SEP set output row separator. Default: '\\n'\n" |
| 14530 | " -nofollow refuse to open symbolic links to database files\n" |
| 14531 | " -noinit Do not read the ~/.sqliterc file at startup\n" |
| 14532 | " -nonce STRING set the safe-mode escape nonce\n" |
| 14533 | " -no-rowid-in-view Disable rowid-in-view using sqlite3_config()\n" |
| 14534 | " -nullvalue TEXT set text string for NULL values. Default ''\n" |
| 14535 | " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n" |
| 14536 | " -pcachetrace trace all page cache operations\n" |
| 14537 | " -quote set '.mode quote'\n" |
| 14538 | " -readonly open the database read-only\n" |
| 14539 | " -runtests SCRIPT... Run multiple *.sql test script in subprocesses\n" |
| 14540 | " -safe enable safe-mode\n" |
| 14541 | " -screenwidth N use N as the default screenwidth \n" |
| 14542 | " -separator SEP set output column separator. Default: '|'\n" |
| 14543 | #ifdef SQLITE_ENABLE_SORTER_REFERENCES |
| 14544 | " -sorterref SIZE sorter references threshold size\n" |
| 14545 | #endif |
| 14546 | " -stats print memory stats before each finalize\n" |
| 14547 | " -table set '.mode table'\n" |
| 14548 | " -tabs set '.mode tabs'\n" |
| 14549 | " -unsafe-testing allow unsafe commands and modes for testing\n" |
| 14550 | " -version show SQLite version\n" |
| 14551 | " -vfs NAME use NAME as the default VFS\n" |
| 14552 | " -vfstrace enable tracing of all VFS calls\n" |
| 14553 | #ifdef SQLITE_HAVE_ZLIB |
| 14554 | " -zip open the file as a ZIP Archive\n" |
| 14555 | #endif |
| 14556 | ; |
| 14557 | static void usage(int showDetail){ |
| 14558 | cli_printf(stderr,"Usage: %s [OPTIONS] [FILENAME [SQL...]]\n" |
| 14559 | "FILENAME is the name of an SQLite database. A new database is created\n" |
| 14560 | "if the file does not previously exist. Defaults to :memory:.\n", Argv0); |
| 14561 | if( showDetail ){ |
| 14562 | cli_printf(stderr,"OPTIONS include:\n%s", zOptions); |
| 14563 | }else{ |
| 14564 | eputz("Use the -help option for additional information\n"); |
| 14565 | } |
| 14566 | exit(0); |
| 14567 | } |
| 14568 | |
| 14569 | /* |
| 14570 | ** Internal check: Verify that the SQLite is uninitialized. Print a |
| 14571 | ** error message if it is initialized. |
| 14572 | */ |
| 14573 | static void verify_uninitialized(void){ |
| 14574 | if( sqlite3_config(-1)==SQLITE_MISUSE ){ |
| 14575 | sputz(stdout, "WARNING: attempt to configure SQLite after" |
| 14576 | " initialization.\n"); |
| 14577 | } |
| 14578 | } |
| 14579 | |
| 14580 | /* |
| 14581 | ** Run a copy of this program as a subprocess |
| 14582 | */ |
| 14583 | static void runShellSubprocess( |
| 14584 | const char *zProg, |
| 14585 | const char *zScript, |
| 14586 | int *pNErr, |
| 14587 | int *pNTest |
| 14588 | ){ |
| 14589 | FILE *in; |
| 14590 | char *zCmd; |
| 14591 | const char *zTail; |
| 14592 | char zIn[1000]; |
| 14593 | zTail = strrchr(zScript, '/'); |
| 14594 | if( zTail ){ |
| 14595 | zTail++; |
| 14596 | }else{ |
| 14597 | zTail = zScript; |
| 14598 | } |
| 14599 | #ifdef _WIN32 |
| 14600 | { |
| 14601 | const char *zBackslash = strrchr(zTail, '\\'); |
| 14602 | if( zBackslash ) zTail = zBackslash+1; |
| 14603 | } |
| 14604 | #endif |
| 14605 | sqlite3_fprintf(stdout, "%-24s ", zTail); |
| 14606 | fflush(stdout); |
| 14607 | if( !isScriptFile(zScript,0) ){ |
| 14608 | sqlite3_fprintf(stdout, "not an SQL script\n"); |
| 14609 | (*pNErr)++; |
| 14610 | return; |
| 14611 | } |
| 14612 | #ifdef _WIN32 |
| 14613 | /* The command runs as "cmd.exe /c COMMAND". If COMMAND starts with a |
| 14614 | ** double-quote and contains more than two of them, then cmd.exe removes |
| 14615 | ** the first and the last double-quote before doing anything else. |
| 14616 | ** The extra pair of quotes around the whole command is there to be |
| 14617 | ** removed, so that the quotes on the individual arguments survive. */ |
| 14618 | zCmd = sqlite3_mprintf("\"\"%s\" \"%s\" 2>NUL\"", zProg, zScript); |
| 14619 | #else |
| 14620 | zCmd = sqlite3_mprintf("\"%s\" \"%s\" 2>/dev/null", zProg, zScript); |
| 14621 | #endif |
| 14622 | in = sqlite3_popen(zCmd, "r"); |
| 14623 | if( in==0 ){ |
| 14624 | sqlite3_fprintf(stdout, "cannot start subprocess\n"); |
| 14625 | sqlite3_free(zCmd); |
| 14626 | (*pNErr)++; |
| 14627 | return; |
| 14628 | } |
| 14629 | while( sqlite3_fgets(zIn, sizeof(zIn), in) ){ |
| 14630 | int n = 0; |
| 14631 | int m = 0; |
| 14632 | char *zRunWith; |
| 14633 | zRunWith = strstr(zIn, " run with "); |
| 14634 | if( zRunWith==0 ) continue; |
| 14635 | if( zIn[0]<'0' || zIn[0]>'9' ) continue; |
| 14636 | if( zRunWith[10]<'0' || zRunWith[10]>'9' ) continue; |
| 14637 | n = atoi(zIn); |
| 14638 | m = atoi(&zRunWith[10]); |
| 14639 | if( m==0 ){ |
| 14640 | sqlite3_fprintf(stdout, "tests %5d\n", n); |
| 14641 | }else{ |
| 14642 | sqlite3_fprintf(stdout, "tests %5d errors %5d\n", n, m); |
| 14643 | } |
| 14644 | (*pNErr) += m; |
| 14645 | (*pNTest) += n; |
| 14646 | pclose(in); |
| 14647 | sqlite3_free(zCmd); |
| 14648 | return; |
| 14649 | } |
| 14650 | pclose(in); |
| 14651 | sqlite3_free(zCmd); |
| 14652 | sqlite3_fprintf(stdout, "did not complete\n"); |
| 14653 | fflush(stdout); |
| 14654 | (*pNErr)++; |
| 14655 | } |
| 14656 | |
| 14657 | #ifdef _WIN32 |
| 14658 | /* |
| 14659 | ** Run a subprocess for each script file that matches the wildcard zPattern. |
| 14660 | ** CMD.EXE does not expand wildcards, so the application must do it. |
| 14661 | ** Only the final path component of zPattern may contain wildcards. |
| 14662 | ** Return the number of scripts run. |
| 14663 | */ |
| 14664 | static int runShellSubprocessGlob( |
| 14665 | const char *zProg, |
| 14666 | const char *zPattern, |
| 14667 | int *pNErr, |
| 14668 | int *pNTest |
| 14669 | ){ |
| 14670 | WIN32_FIND_DATAW sFind; |
| 14671 | HANDLE hFind; |
| 14672 | LPWSTR zW = sqlite3_win32_utf8_to_unicode(zPattern); |
| 14673 | int nDir; |
| 14674 | int nRun = 0; |
| 14675 | shell_check_oom(zW); |
| 14676 | for(nDir=(int)strlen(zPattern); nDir>0; nDir--){ |
| 14677 | char c = zPattern[nDir-1]; |
| 14678 | if( c=='/' || c=='\\' || c==':' ) break; |
| 14679 | } |
| 14680 | hFind = FindFirstFileW(zW, &sFind); |
| 14681 | sqlite3_free(zW); |
| 14682 | if( hFind==INVALID_HANDLE_VALUE ) return 0; |
| 14683 | do{ |
| 14684 | char *zName, *zPath; |
| 14685 | if( sFind.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) continue; |
| 14686 | zName = sqlite3_win32_unicode_to_utf8(sFind.cFileName); |
| 14687 | zPath = sqlite3_mprintf("%.*s%s", nDir, zPattern, zName); |
| 14688 | shell_check_oom(zPath); |
| 14689 | if( isScriptFile(zPath,0) ){ /* Also rejects 8.3-name false matches */ |
| 14690 | runShellSubprocess(zProg, zPath, pNErr, pNTest); |
| 14691 | nRun++; |
| 14692 | } |
| 14693 | sqlite3_free(zPath); |
| 14694 | sqlite3_free(zName); |
| 14695 | }while( FindNextFileW(hFind, &sFind) ); |
| 14696 | FindClose(hFind); |
| 14697 | return nRun; |
| 14698 | } |
| 14699 | #endif |
| 14700 | |
| 14701 | #if HAVE_EDITLINE |
| 14702 | /* |
| 14703 | ** https://sqlite.org/forum/forumpost/aad7a634916ff050: |
| 14704 | ** |
| 14705 | ** Calling setlocale(LC_...,"") is required to get libedit to accept |
| 14706 | ** non-ASCII input. |
| 14707 | */ |
| 14708 | #define DO_SET_LOCALE 1 |
| 14709 | #include <locale.h> |
| 14710 | #else |
| 14711 | #define DO_SET_LOCALE 0 |
| 14712 | #endif |
| 14713 | |
| 14714 | /* |
| 14715 | ** Initialize the state information in data |
| 14716 | */ |
| 14717 | static void main_init(ShellState *p) { |
| 14718 | memset(p, 0, sizeof(*p)); |
| 14719 | p->pAuxDb = &p->aAuxDb[0]; |
| 14720 | p->shellFlgs = SHFLG_Lookaside; |
| 14721 | sqlite3_config(SQLITE_CONFIG_LOG, shellLog, (void*)p); |
| 14722 | #if !defined(SQLITE_SHELL_FIDDLE) |
| 14723 | verify_uninitialized(); |
| 14724 | #endif |
| 14725 | sqlite3_config(SQLITE_CONFIG_URI, 1); |
| 14726 | sqlite3_config(SQLITE_CONFIG_MULTITHREAD); |
| 14727 | globalShellState = p; |
| 14728 | #if HAVE_EDITLINE || HAVE_READLINE |
| 14729 | /* Editline requires \001...\002 delimiters around ANSI x3.64 escapes in |
| 14730 | ** prompt strings. Readline does sometimes, depending on how it is |
| 14731 | ** compiled and installed. */ |
| 14732 | p->bDelimitNonprint = 1; |
| 14733 | #else |
| 14734 | /* No \001...\002 escapes required for linenoise or when not using a |
| 14735 | ** command-line editing library */ |
| 14736 | p->bDelimitNonprint = 0; |
| 14737 | #endif |
| 14738 | #if DO_SET_LOCALE |
| 14739 | setlocale(LC_CTYPE,""); |
| 14740 | #endif |
| 14741 | #undef DO_SET_LOCALE |
| 14742 | } |
| 14743 | |
| 14744 | /* |
| 14745 | ** Output text to the console in a font that attracts extra attention. |
| 14746 | */ |
| 14747 | static void printBold(const char *zText){ |
| 14748 | if( shellNoColor() ){ |
| 14749 | cli_printf(stdout, "%s", zText); |
| 14750 | }else{ |
| 14751 | cli_printf(stdout, "\033[1;36m\033[3m%s\033[0m", zText); |
| 14752 | } |
| 14753 | } |
| 14754 | |
| 14755 | /* |
| 14756 | ** Get the argument to an --option. Throw an error and die if no argument |
| 14757 | ** is available. |
| 14758 | */ |
| 14759 | static char *cmdline_option_value(int argc, char **argv, int i){ |
| 14760 | if( i==argc ){ |
| 14761 | cli_printf(stderr, |
| 14762 | "%s: Error: missing argument to %s\n", argv[0], argv[argc-1]); |
| 14763 | cli_exit(1); |
| 14764 | } |
| 14765 | return argv[i]; |
| 14766 | } |
| 14767 | |
| 14768 | /* |
| 14769 | ** The callback from atexit(). |
| 14770 | */ |
| 14771 | static void SQLITE_CDECL abnormalExit(void){ |
| 14772 | if( seenInterrupt ) eputz("Program interrupted.\n"); |
| 14773 | if( globalShellState ){ |
| 14774 | clearTempFile(globalShellState, 1, 1); |
| 14775 | } |
| 14776 | } |
| 14777 | |
| 14778 | /* Routine to output from vfstrace |
| 14779 | */ |
| 14780 | static int vfstraceOut(const char *z, void *pArg){ |
| 14781 | ShellState *p = (ShellState*)pArg; |
| 14782 | cli_puts(z, p->out); |
| 14783 | fflush(p->out); |
| 14784 | return 1; |
| 14785 | } |
| 14786 | |
| 14787 | #if defined(SQLITE_DEBUG) && !defined(SQLITE_SHELL_FIDDLE) |
| 14788 | /* Ensure that sqlite3_reset_auto_extension() clears auto-extension |
| 14789 | ** memory. https://sqlite.org/forum/forumpost/310cb231b07c80d1. |
| 14790 | ** Testing this: if we (inadvertently) remove the |
| 14791 | ** sqlite3_reset_auto_extension() call from main(), most shell tests |
| 14792 | ** will fail because of a leak message in their output. */ |
| 14793 | static int auto_ext_leak_tester( |
| 14794 | sqlite3 *db, |
| 14795 | char **pzErrMsg, |
| 14796 | const struct sqlite3_api_routines *pThunk |
| 14797 | ){ |
| 14798 | (void)db; (void)pzErrMsg; (void)pThunk; |
| 14799 | return SQLITE_OK; |
| 14800 | } |
| 14801 | #endif |
| 14802 | |
| 14803 | /* Alternative name to the entry point for Fiddle */ |
| 14804 | #ifdef SQLITE_SHELL_FIDDLE |
| 14805 | # define main fiddle_main |
| 14806 | #endif |
| 14807 | |
| 14808 | /* Use the wmain() entry point on Windows. Translate arguments to |
| 14809 | ** UTF8, then invoke the traditional main() entry point which is |
| 14810 | ** renamed using a #define to utf8_main() . |
| 14811 | */ |
| 14812 | #if defined(_WIN32) && !defined(__MINGW32__) && !defined(main) |
| 14813 | # define main utf8_main /* Rename entry point to utf_main() */ |
| 14814 | int SQLITE_CDECL utf8_main(int,char**); /* Forward declaration */ |
| 14815 | int SQLITE_CDECL wmain(int argc, wchar_t **wargv){ |
| 14816 | int rc, i; |
| 14817 | DWORD mode; |
| 14818 | HANDLE hOut; |
| 14819 | char **argv = malloc( sizeof(char*) * (argc+1) ); |
| 14820 | char **orig = argv; |
| 14821 | if( argv==0 ){ |
| 14822 | fprintf(stderr, "malloc failed\n"); |
| 14823 | exit(1); |
| 14824 | } |
| 14825 | for(i=0; i<argc; i++){ |
| 14826 | int nByte = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, 0, 0, 0, 0); |
| 14827 | if( nByte==0 ){ |
| 14828 | argv[i] = 0; |
| 14829 | }else{ |
| 14830 | argv[i] = malloc( nByte ); |
| 14831 | if( argv[i]==0 ){ |
| 14832 | fprintf(stderr, "malloc failed\n"); |
| 14833 | exit(1); |
| 14834 | } |
| 14835 | nByte = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, argv[i],nByte,0,0); |
| 14836 | if( nByte==0 ){ |
| 14837 | free(argv[i]); |
| 14838 | argv[i] = 0; |
| 14839 | } |
| 14840 | } |
| 14841 | } |
| 14842 | argv[argc] = 0; |
| 14843 | hOut = GetStdHandle(STD_OUTPUT_HANDLE); |
| 14844 | GetConsoleMode(hOut, &mode); |
| 14845 | SetConsoleMode(hOut, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING); |
| 14846 | _setmode(_fileno(stdout),_O_BINARY); /* Bug 2026-08-03T08:52:42Z */ |
| 14847 | rc = utf8_main(argc, argv); |
| 14848 | for(i=0; i<argc; i++) free(orig[i]); |
| 14849 | free(argv); |
| 14850 | return rc; |
| 14851 | } |
| 14852 | #endif /* WIN32 */ |
| 14853 | |
| 14854 | /* |
| 14855 | ** This is the main entry point for the process. Everything starts here. |
| 14856 | ** |
| 14857 | ** The "main" identifier may have been #defined to something else: |
| 14858 | ** |
| 14859 | ** utf8_main On Windows |
| 14860 | ** fiddle_main In Fiddle |
| 14861 | ** sqlite3_shell Other projects that use shell.c as a subroutine |
| 14862 | */ |
| 14863 | int SQLITE_CDECL main(int argc, char **argv){ |
| 14864 | #ifdef SQLITE_DEBUG |
| 14865 | sqlite3_int64 mem_main_enter = 0; |
| 14866 | #endif |
| 14867 | #ifdef SQLITE_SHELL_FIDDLE |
| 14868 | # define data shellState |
| 14869 | #else |
| 14870 | ShellState data; |
| 14871 | #endif |
| 14872 | const char *zInitFile = 0; |
| 14873 | int i; |
| 14874 | int rc = 0; |
| 14875 | int warnInmemoryDb = 0; |
| 14876 | int readStdin = 1; |
| 14877 | int noInit = 0; /* Do not read ~/.sqliterc if true */ |
| 14878 | int nCmd = 0; |
| 14879 | int nOptsEnd = argc; |
| 14880 | int bEnableVfstrace = 0; |
| 14881 | int bTestMode = 0; /* --runtests option */ |
| 14882 | char **azCmd = 0; |
| 14883 | int *aiCmd = 0; |
| 14884 | const char *zVfs = 0; /* Value of -vfs command-line option */ |
| 14885 | setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */ |
| 14886 | |
| 14887 | #ifdef SQLITE_SHELL_FIDDLE |
| 14888 | stdin_is_interactive = 0; |
| 14889 | stdout_is_console = 1; |
| 14890 | data.wasm.zDefaultDbName = "/fiddle.sqlite3"; |
| 14891 | #else |
| 14892 | stdin_is_interactive = isatty(0); |
| 14893 | stdout_is_console = isatty(1); |
| 14894 | if( !stdin_is_interactive || !stdout_is_console ){ |
| 14895 | shellCmdLineEdit = 0; |
| 14896 | } |
| 14897 | #endif |
| 14898 | atexit(abnormalExit); |
| 14899 | #ifdef SQLITE_DEBUG |
| 14900 | mem_main_enter = sqlite3_memory_used(); |
| 14901 | #endif |
| 14902 | #if !defined(_WIN32_WCE) |
| 14903 | if( getenv("SQLITE_DEBUG_BREAK") ){ |
| 14904 | if( isatty(0) && isatty(2) ){ |
| 14905 | char zLine[100]; |
| 14906 | cli_printf(stderr, |
| 14907 | "attach debugger to process %d and press ENTER to continue...", |
| 14908 | GETPID()); |
| 14909 | if( sqlite3_fgets(zLine, sizeof(zLine), stdin)!=0 |
| 14910 | && cli_strcmp(zLine,"stop")==0 |
| 14911 | ){ |
| 14912 | exit(1); |
| 14913 | } |
| 14914 | }else{ |
| 14915 | #if defined(_WIN32) || defined(WIN32) |
| 14916 | DebugBreak(); |
| 14917 | #elif defined(SIGTRAP) |
| 14918 | raise(SIGTRAP); |
| 14919 | #endif |
| 14920 | } |
| 14921 | } |
| 14922 | #endif |
| 14923 | /* Register a valid signal handler early, before much else is done. */ |
| 14924 | #ifdef SIGINT |
| 14925 | signal(SIGINT, interrupt_handler); |
| 14926 | #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) |
| 14927 | if( !SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE) ){ |
| 14928 | eputz("No ^C handler.\n"); |
| 14929 | } |
| 14930 | #endif |
| 14931 | #ifdef SIGTERM |
| 14932 | signal(SIGTERM, sigterm_handler); |
| 14933 | #endif |
| 14934 | #ifdef SIGHUP |
| 14935 | signal(SIGHUP, sigterm_handler); |
| 14936 | #endif |
| 14937 | |
| 14938 | |
| 14939 | #if USE_SYSTEM_SQLITE+0!=1 |
| 14940 | if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){ |
| 14941 | cli_printf(stderr, |
| 14942 | "SQLite header and source version mismatch\n%s\n%s\n", |
| 14943 | sqlite3_sourceid(), SQLITE_SOURCE_ID); |
| 14944 | exit(1); |
| 14945 | } |
| 14946 | #endif |
| 14947 | main_init(&data); |
| 14948 | |
| 14949 | assert( argc>=1 && argv && argv[0] ); |
| 14950 | Argv0 = argv[0]; |
| 14951 | |
| 14952 | #ifdef SQLITE_SHELL_DBNAME_PROC |
| 14953 | { |
| 14954 | /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name |
| 14955 | ** of a C-function that will provide the name of the database file. Use |
| 14956 | ** this compile-time option to embed this shell program in larger |
| 14957 | ** applications. */ |
| 14958 | extern void SQLITE_SHELL_DBNAME_PROC(const char**); |
| 14959 | SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename); |
| 14960 | warnInmemoryDb = 0; |
| 14961 | } |
| 14962 | #endif |
| 14963 | |
| 14964 | /* Do an initial pass through the command-line arguments to locate |
| 14965 | ** the name of the database file, the name of the initialization file, |
| 14966 | ** the size of the alternative malloc heap, options affecting commands |
| 14967 | ** or SQL run from the command line, and the first command to execute. |
| 14968 | */ |
| 14969 | #ifndef SQLITE_SHELL_FIDDLE |
| 14970 | verify_uninitialized(); |
| 14971 | #endif |
| 14972 | for(i=1; i<argc; i++){ |
| 14973 | char *z; |
| 14974 | z = argv[i]; |
| 14975 | if( z[0]!='-' || i>nOptsEnd ){ |
| 14976 | if( data.aAuxDb->zDbFilename==0 && !bTestMode && !isScriptFile(z,1) ){ |
| 14977 | data.aAuxDb->zDbFilename = z; |
| 14978 | }else{ |
| 14979 | /* Excess arguments are interpreted as SQL (or dot-commands) and |
| 14980 | ** mean that nothing is read from stdin */ |
| 14981 | readStdin = 0; |
| 14982 | stdin_is_interactive = 0; |
| 14983 | nCmd++; |
| 14984 | azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd); |
| 14985 | shell_check_oom(azCmd); |
| 14986 | aiCmd = realloc(aiCmd, sizeof(aiCmd[0])*nCmd); |
| 14987 | shell_check_oom(aiCmd); |
| 14988 | azCmd[nCmd-1] = z; |
| 14989 | aiCmd[nCmd-1] = i; |
| 14990 | } |
| 14991 | continue; |
| 14992 | } |
| 14993 | if( z[1]=='-' ) z++; |
| 14994 | if( cli_strcmp(z, "-")==0 ){ |
| 14995 | nOptsEnd = i; |
| 14996 | continue; |
| 14997 | }else if( cli_strcmp(z,"-separator")==0 |
| 14998 | || cli_strcmp(z,"-nullvalue")==0 |
| 14999 | || cli_strcmp(z,"-newline")==0 |
| 15000 | || cli_strcmp(z,"-cmd")==0 |
| 15001 | ){ |
| 15002 | (void)cmdline_option_value(argc, argv, ++i); |
| 15003 | }else if( cli_strcmp(z,"-init")==0 ){ |
| 15004 | zInitFile = cmdline_option_value(argc, argv, ++i); |
| 15005 | }else if( cli_strcmp(z,"-interactive")==0 ){ |
| 15006 | }else if( cli_strcmp(z,"-batch")==0 ){ |
| 15007 | /* Need to check for batch mode here to so we can avoid printing |
| 15008 | ** informational messages (like from process_sqliterc) before |
| 15009 | ** we do the actual processing of arguments later in a second pass. |
| 15010 | */ |
| 15011 | stdin_is_interactive = 0; |
| 15012 | stdout_is_console = 0; |
| 15013 | modeChange(&data, MODE_BATCH); |
| 15014 | }else if( cli_strcmp(z,"-screenwidth")==0 ){ |
| 15015 | int n = atoi(cmdline_option_value(argc, argv, ++i)); |
| 15016 | if( n<2 ){ |
| 15017 | sqlite3_fprintf(stderr,"minimum --screenwidth is 2\n"); |
| 15018 | exit(1); |
| 15019 | } |
| 15020 | stdout_tty_width = n; |
| 15021 | }else if( cli_strcmp(z,"-utf8")==0 ){ |
| 15022 | }else if( cli_strcmp(z,"-no-utf8")==0 ){ |
| 15023 | }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){ |
| 15024 | int val = 0; |
| 15025 | sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW, &val); |
| 15026 | assert( val==0 ); |
| 15027 | }else if( cli_strcmp(z,"-heap")==0 ){ |
| 15028 | #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) |
| 15029 | const char *zSize; |
| 15030 | sqlite3_int64 szHeap; |
| 15031 | |
| 15032 | zSize = cmdline_option_value(argc, argv, ++i); |
| 15033 | szHeap = integerValue(zSize); |
| 15034 | if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000; |
| 15035 | verify_uninitialized(); |
| 15036 | sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); |
| 15037 | #else |
| 15038 | (void)cmdline_option_value(argc, argv, ++i); |
| 15039 | #endif |
| 15040 | }else if( cli_strcmp(z,"-pagecache")==0 ){ |
| 15041 | sqlite3_int64 n, sz; |
| 15042 | sz = integerValue(cmdline_option_value(argc,argv,++i)); |
| 15043 | if( sz>65536 ) sz = 65536; |
| 15044 | if( sz<0 ) sz = 0; |
| 15045 | n = integerValue(cmdline_option_value(argc,argv,++i)); |
| 15046 | if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){ |
| 15047 | n = 0xffffffffffffLL/sz; |
| 15048 | } |
| 15049 | if( sz>0 && (sz & (sz-1))==0 ){ |
| 15050 | /* If SIZE is a power of two, round it up by the PCACHE_HDRSZ */ |
| 15051 | int szHdr = 0; |
| 15052 | sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &szHdr); |
| 15053 | sz += szHdr; |
| 15054 | cli_printf(stdout, "Page cache size increased to %d to accommodate" |
| 15055 | " the %d-byte headers\n", (int)sz, szHdr); |
| 15056 | } |
| 15057 | verify_uninitialized(); |
| 15058 | sqlite3_config(SQLITE_CONFIG_PAGECACHE, |
| 15059 | (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n); |
| 15060 | data.shellFlgs |= SHFLG_Pagecache; |
| 15061 | }else if( cli_strcmp(z,"-lookaside")==0 ){ |
| 15062 | int n, sz; |
| 15063 | sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); |
| 15064 | if( sz<0 ) sz = 0; |
| 15065 | n = (int)integerValue(cmdline_option_value(argc,argv,++i)); |
| 15066 | if( n<0 ) n = 0; |
| 15067 | verify_uninitialized(); |
| 15068 | sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n); |
| 15069 | if( (i64)sz*(i64)n==0 ) data.shellFlgs &= ~SHFLG_Lookaside; |
| 15070 | }else if( cli_strcmp(z,"-threadsafe")==0 ){ |
| 15071 | int n; |
| 15072 | n = (int)integerValue(cmdline_option_value(argc,argv,++i)); |
| 15073 | verify_uninitialized(); |
| 15074 | switch( n ){ |
| 15075 | case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); break; |
| 15076 | case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD); break; |
| 15077 | default: sqlite3_config(SQLITE_CONFIG_SERIALIZED); break; |
| 15078 | } |
| 15079 | }else if( cli_strcmp(z,"-vfstrace")==0 ){ |
| 15080 | bEnableVfstrace = 1; |
| 15081 | #ifdef SQLITE_ENABLE_MULTIPLEX |
| 15082 | }else if( cli_strcmp(z,"-multiplex")==0 ){ |
| 15083 | extern int sqlite3_multiplex_initialize(const char*,int); |
| 15084 | sqlite3_multiplex_initialize(0, 1); |
| 15085 | #endif |
| 15086 | }else if( cli_strcmp(z,"-mmap")==0 ){ |
| 15087 | sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); |
| 15088 | verify_uninitialized(); |
| 15089 | sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); |
| 15090 | #if defined(SQLITE_ENABLE_SORTER_REFERENCES) |
| 15091 | }else if( cli_strcmp(z,"-sorterref")==0 ){ |
| 15092 | sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); |
| 15093 | verify_uninitialized(); |
| 15094 | sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz); |
| 15095 | #endif |
| 15096 | }else if( cli_strcmp(z,"-vfs")==0 ){ |
| 15097 | zVfs = cmdline_option_value(argc, argv, ++i); |
| 15098 | #ifdef SQLITE_HAVE_ZLIB |
| 15099 | }else if( cli_strcmp(z,"-zip")==0 ){ |
| 15100 | data.openMode = SHELL_OPEN_ZIPFILE; |
| 15101 | #endif |
| 15102 | }else if( cli_strcmp(z,"-append")==0 ){ |
| 15103 | data.openMode = SHELL_OPEN_APPENDVFS; |
| 15104 | #ifndef SQLITE_OMIT_DESERIALIZE |
| 15105 | }else if( cli_strcmp(z,"-deserialize")==0 ){ |
| 15106 | data.openMode = SHELL_OPEN_DESERIALIZE; |
| 15107 | }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){ |
| 15108 | data.szMax = integerValue(argv[++i]); |
| 15109 | #endif |
| 15110 | }else if( cli_strcmp(z,"-readonly")==0 ){ |
| 15111 | data.openFlags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); |
| 15112 | data.openFlags |= SQLITE_OPEN_READONLY; |
| 15113 | }else if( cli_strcmp(z,"-nofollow")==0 ){ |
| 15114 | data.openFlags |= SQLITE_OPEN_NOFOLLOW; |
| 15115 | }else if( cli_strcmp(z,"-noinit")==0 ){ |
| 15116 | noInit = 1; |
| 15117 | }else if( cli_strcmp(z,"-exclusive")==0 ){ /* UNDOCUMENTED */ |
| 15118 | data.openFlags |= SQLITE_OPEN_EXCLUSIVE; |
| 15119 | }else if( cli_strcmp(z,"-ifexists")==0 ){ |
| 15120 | data.openFlags &= ~(SQLITE_OPEN_CREATE); |
| 15121 | if( data.openFlags==0 ) data.openFlags = SQLITE_OPEN_READWRITE; |
| 15122 | #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) |
| 15123 | }else if( cli_strncmp(z, "-A",2)==0 ){ |
| 15124 | /* All remaining command-line arguments are passed to the ".archive" |
| 15125 | ** command, so ignore them */ |
| 15126 | break; |
| 15127 | #endif |
| 15128 | }else if( cli_strcmp(z, "-memtrace")==0 ){ |
| 15129 | sqlite3MemTraceActivate(stderr); |
| 15130 | }else if( cli_strcmp(z, "-pcachetrace")==0 ){ |
| 15131 | sqlite3PcacheTraceActivate(stderr); |
| 15132 | }else if( cli_strcmp(z,"-bail")==0 ){ |
| 15133 | bail_on_error = 1; |
| 15134 | }else if( cli_strcmp(z,"-nonce")==0 ){ |
| 15135 | free(data.zNonce); |
| 15136 | data.zNonce = strdup(cmdline_option_value(argc, argv, ++i)); |
| 15137 | }else if( cli_strcmp(z,"-unsafe-testing")==0 |
| 15138 | || cli_strcmp(z,"-unsafe")==0 ){ |
| 15139 | ShellSetFlag(&data,SHFLG_TestingMode); |
| 15140 | }else if( cli_strcmp(z,"-safe")==0 ){ |
| 15141 | noInit = 1; /* --safe implies --noinit */ |
| 15142 | }else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){ |
| 15143 | /* skip over the argument */ |
| 15144 | i++; |
| 15145 | }else if( cli_strcmp(z,"-cmdline-edit")==0 ){ |
| 15146 | shellCmdLineEdit = booleanValue(cmdline_option_value(argc,argv,++i)); |
| 15147 | }else if( cli_strcmp(z,"-runtests")==0 ){ |
| 15148 | bTestMode = 1; |
| 15149 | }else if( cli_strcmp(z,"-test-argv")==0 ){ |
| 15150 | /* Undocumented test option. Print the values in argv[] and exit. |
| 15151 | ** Use this to verify that any translation of the argv[], for example |
| 15152 | ** on Windows that receives wargv[] from the OS and must convert |
| 15153 | ** to UTF8 prior to calling this routine. */ |
| 15154 | int kk; |
| 15155 | for(kk=0; kk<argc; kk++){ |
| 15156 | sqlite3_fprintf(stdout,"argv[%d] = \"%s\"\n", kk, argv[kk]); |
| 15157 | } |
| 15158 | return 0; |
| 15159 | }else if( cli_strcmp(z,"-test-parse")==0 ){ |
| 15160 | /* Undocumented test option. Read input normally and process all |
| 15161 | ** dot-commands. But do not process any SQL. Instead, whenever input |
| 15162 | ** text would have been processed as SQL, print a one-line summary of |
| 15163 | ** the input. This is used by test scripts to verify that the end-of-SQL |
| 15164 | ** parsing logic is working correctly. */ |
| 15165 | data.bTestParse = 1; |
| 15166 | } |
| 15167 | } |
| 15168 | #ifndef SQLITE_SHELL_FIDDLE |
| 15169 | if( !bEnableVfstrace ) verify_uninitialized(); |
| 15170 | #endif |
| 15171 | |
| 15172 | #ifndef SQLITE_SHELL_FIDDLE |
| 15173 | if( bTestMode ){ |
| 15174 | int nErr = 0; |
| 15175 | int nTest = 0; |
| 15176 | int nScript = 0; |
| 15177 | #ifdef _WIN32 |
| 15178 | /* Child processes inherit this. Without it, a crash in a test script |
| 15179 | ** might raise a dialog box that stalls the run until it is dismissed. */ |
| 15180 | SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX); |
| 15181 | #endif |
| 15182 | for(i=0; i<nCmd; i++){ |
| 15183 | #ifdef _WIN32 |
| 15184 | if( strpbrk(azCmd[i], "*?") ){ |
| 15185 | int n = runShellSubprocessGlob(argv[0], azCmd[i], &nErr, &nTest); |
| 15186 | if( n>0 ){ |
| 15187 | nScript += n; |
| 15188 | continue; |
| 15189 | } |
| 15190 | } |
| 15191 | #endif |
| 15192 | runShellSubprocess(argv[0], azCmd[i], &nErr, &nTest); |
| 15193 | nScript++; |
| 15194 | } |
| 15195 | sqlite3_fprintf(stdout, "%-24s tests %5d errors %5d scripts %5d\n", |
| 15196 | "TOTAL", nTest, nErr, nScript); |
| 15197 | rc = nErr>0; |
| 15198 | goto shell_main_exit; |
| 15199 | } |
| 15200 | #endif |
| 15201 | |
| 15202 | #ifdef SQLITE_SHELL_INIT_PROC |
| 15203 | { |
| 15204 | /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name |
| 15205 | ** of a C-function that will perform initialization actions on SQLite that |
| 15206 | ** occur just before or after sqlite3_initialize(). Use this compile-time |
| 15207 | ** option to embed this shell program in larger applications. */ |
| 15208 | extern void SQLITE_SHELL_INIT_PROC(void); |
| 15209 | SQLITE_SHELL_INIT_PROC(); |
| 15210 | } |
| 15211 | #else |
| 15212 | /* All the sqlite3_config() calls have now been made. So it is safe |
| 15213 | ** to call sqlite3_initialize() and process any command line -vfs option. */ |
| 15214 | sqlite3_initialize(); |
| 15215 | #endif |
| 15216 | |
| 15217 | if( zVfs ){ |
| 15218 | sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs); |
| 15219 | if( pVfs ){ |
| 15220 | sqlite3_vfs_register(pVfs, 1); |
| 15221 | } |
| 15222 | #if !defined(SQLITE_OMIT_LOAD_EXTENSION) |
| 15223 | else if( access(zVfs,0)==0 ){ |
| 15224 | /* If the VFS name is not the name of an existing VFS, but it is |
| 15225 | ** the name of a file, then try to load that file as an extension. |
| 15226 | ** Presumably the extension implements the desired VFS. */ |
| 15227 | sqlite3 *db = 0; |
| 15228 | char *zErr = 0; |
| 15229 | sqlite3_open(":memory:", &db); |
| 15230 | sqlite3_enable_load_extension(db, 1); |
| 15231 | rc = sqlite3_load_extension(db, zVfs, 0, &zErr); |
| 15232 | sqlite3_close(db); |
| 15233 | if( (rc&0xff)!=SQLITE_OK ){ |
| 15234 | cli_printf(stderr, "could not load extension VFS \"%s\": %s\n", |
| 15235 | zVfs, zErr); |
| 15236 | exit(1); |
| 15237 | } |
| 15238 | } |
| 15239 | #endif |
| 15240 | else{ |
| 15241 | cli_printf(stderr,"no such VFS: \"%s\"\n", zVfs); |
| 15242 | exit(1); |
| 15243 | } |
| 15244 | } |
| 15245 | |
| 15246 | if( data.pAuxDb->zDbFilename==0 ){ |
| 15247 | #ifndef SQLITE_OMIT_MEMORYDB |
| 15248 | data.pAuxDb->zDbFilename = ":memory:"; |
| 15249 | warnInmemoryDb = argc==1; |
| 15250 | #else |
| 15251 | cli_printf(stderr, |
| 15252 | "%s: Error: no database filename specified\n", Argv0); |
| 15253 | rc = 1; |
| 15254 | goto shell_main_exit; |
| 15255 | #endif |
| 15256 | } |
| 15257 | data.out = stdout; |
| 15258 | if( bEnableVfstrace ){ |
| 15259 | vfstrace_register("trace",0,vfstraceOut, &data, 1); |
| 15260 | } |
| 15261 | #ifndef SQLITE_SHELL_FIDDLE |
| 15262 | sqlite3_appendvfs_init(0,0,0); |
| 15263 | #ifdef SQLITE_DEBUG |
| 15264 | sqlite3_auto_extension( (void(*)(void))auto_ext_leak_tester ); |
| 15265 | #endif |
| 15266 | #endif |
| 15267 | modeDefault(&data); |
| 15268 | |
| 15269 | /* Go ahead and open the database file if it already exists. If the |
| 15270 | ** file does not exist, delay opening it. This prevents empty database |
| 15271 | ** files from being created if a user mistypes the database name argument |
| 15272 | ** to the sqlite command-line tool. |
| 15273 | */ |
| 15274 | if( access(data.pAuxDb->zDbFilename, 0)==0 ){ |
| 15275 | open_db(&data, 0); |
| 15276 | } |
| 15277 | |
| 15278 | /* Process the initialization file if there is one. If no -init option |
| 15279 | ** is given on the command line, look for a file named ~/.sqliterc and |
| 15280 | ** try to process it. |
| 15281 | */ |
| 15282 | if( !noInit ) process_sqliterc(&data,zInitFile); |
| 15283 | |
| 15284 | /* Make a second pass through the command-line arguments and set |
| 15285 | ** options. This second pass is delayed until after the initialization |
| 15286 | ** file is processed so that the command-line arguments will override |
| 15287 | ** settings in the initialization file. |
| 15288 | */ |
| 15289 | for(i=1; i<argc; i++){ |
| 15290 | char *z = argv[i]; |
| 15291 | if( z[0]!='-' || i>=nOptsEnd ) continue; |
| 15292 | if( z[1]=='-' ){ z++; } |
| 15293 | if( cli_strcmp(z,"-init")==0 ){ |
| 15294 | i++; |
| 15295 | }else if( cli_strcmp(z,"-html")==0 ){ |
| 15296 | modeChange(&data, MODE_Html); |
| 15297 | }else if( cli_strcmp(z,"-list")==0 ){ |
| 15298 | modeChange(&data, MODE_List); |
| 15299 | }else if( cli_strcmp(z,"-quote")==0 ){ |
| 15300 | modeChange(&data, MODE_Quote); |
| 15301 | }else if( cli_strcmp(z,"-line")==0 ){ |
| 15302 | modeChange(&data, MODE_Line); |
| 15303 | }else if( cli_strcmp(z,"-column")==0 ){ |
| 15304 | modeChange(&data, MODE_Column); |
| 15305 | }else if( cli_strcmp(z,"-json")==0 ){ |
| 15306 | modeChange(&data, MODE_Json); |
| 15307 | }else if( cli_strcmp(z,"-markdown")==0 ){ |
| 15308 | modeChange(&data, MODE_Markdown); |
| 15309 | }else if( cli_strcmp(z,"-table")==0 ){ |
| 15310 | modeChange(&data, MODE_Table); |
| 15311 | }else if( cli_strcmp(z,"-psql")==0 ){ |
| 15312 | modeChange(&data, MODE_Psql); |
| 15313 | }else if( cli_strcmp(z,"-box")==0 ){ |
| 15314 | modeChange(&data, MODE_Box); |
| 15315 | }else if( cli_strcmp(z,"-csv")==0 ){ |
| 15316 | modeChange(&data, MODE_Csv); |
| 15317 | modeSetLimit(&data, "off"); |
| 15318 | }else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){ |
| 15319 | /* See similar code at tag-20250224-1 */ |
| 15320 | const char *zEsc = argv[++i]; |
| 15321 | int k; |
| 15322 | for(k=0; k<ArraySize(qrfEscNames); k++){ |
| 15323 | if( sqlite3_stricmp(zEsc,qrfEscNames[k])==0 ){ |
| 15324 | data.mode.spec.eEsc = k; |
| 15325 | break; |
| 15326 | } |
| 15327 | } |
| 15328 | if( k>=ArraySize(qrfEscNames) ){ |
| 15329 | cli_printf(stderr, "unknown control character escape mode \"%s\"" |
| 15330 | " - choices:", zEsc); |
| 15331 | for(k=0; k<ArraySize(qrfEscNames); k++){ |
| 15332 | cli_printf(stderr, " %s", qrfEscNames[k]); |
| 15333 | } |
| 15334 | cli_printf(stderr, "\n"); |
| 15335 | exit(1); |
| 15336 | } |
| 15337 | #ifdef SQLITE_HAVE_ZLIB |
| 15338 | }else if( cli_strcmp(z,"-zip")==0 ){ |
| 15339 | data.openMode = SHELL_OPEN_ZIPFILE; |
| 15340 | #endif |
| 15341 | }else if( cli_strcmp(z,"-append")==0 ){ |
| 15342 | data.openMode = SHELL_OPEN_APPENDVFS; |
| 15343 | #ifndef SQLITE_OMIT_DESERIALIZE |
| 15344 | }else if( cli_strcmp(z,"-deserialize")==0 ){ |
| 15345 | data.openMode = SHELL_OPEN_DESERIALIZE; |
| 15346 | }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){ |
| 15347 | data.szMax = integerValue(argv[++i]); |
| 15348 | #endif |
| 15349 | }else if( cli_strcmp(z,"-readonly")==0 ){ |
| 15350 | data.openFlags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); |
| 15351 | data.openFlags |= SQLITE_OPEN_READONLY; |
| 15352 | }else if( cli_strcmp(z,"-nofollow")==0 ){ |
| 15353 | data.openFlags |= SQLITE_OPEN_NOFOLLOW; |
| 15354 | }else if( cli_strcmp(z,"-noinit")==0 ){ |
| 15355 | /* No-op */ |
| 15356 | }else if( cli_strcmp(z,"-exclusive")==0 ){ /* UNDOCUMENTED */ |
| 15357 | data.openFlags |= SQLITE_OPEN_EXCLUSIVE; |
| 15358 | }else if( cli_strcmp(z,"-ifexists")==0 ){ |
| 15359 | data.openFlags &= ~(SQLITE_OPEN_CREATE); |
| 15360 | if( data.openFlags==0 ) data.openFlags = SQLITE_OPEN_READWRITE; |
| 15361 | }else if( cli_strcmp(z,"-ascii")==0 ){ |
| 15362 | modeChange(&data, MODE_Ascii); |
| 15363 | }else if( cli_strcmp(z,"-tabs")==0 ){ |
| 15364 | modeChange(&data, MODE_Tabs); |
| 15365 | }else if( cli_strcmp(z,"-separator")==0 ){ |
| 15366 | modeSetStr(&data.mode.spec.zColumnSep, |
| 15367 | cmdline_option_value(argc,argv,++i)); |
| 15368 | }else if( cli_strcmp(z,"-newline")==0 ){ |
| 15369 | modeSetStr(&data.mode.spec.zRowSep, |
| 15370 | cmdline_option_value(argc,argv,++i)); |
| 15371 | }else if( cli_strcmp(z,"-nullvalue")==0 ){ |
| 15372 | modeSetStr(&data.mode.spec.zNull, |
| 15373 | cmdline_option_value(argc,argv,++i)); |
| 15374 | }else if( cli_strcmp(z,"-header")==0 ){ |
| 15375 | data.mode.spec.bTitles = QRF_Always; |
| 15376 | data.mode.mFlags |= MFLG_HDR; |
| 15377 | }else if( cli_strcmp(z,"-noheader")==0 ){ |
| 15378 | data.mode.spec.bTitles = QRF_No; |
| 15379 | data.mode.mFlags |= MFLG_HDR; |
| 15380 | }else if( cli_strcmp(z,"-echo")==0 ){ |
| 15381 | data.mode.mFlags |= MFLG_ECHO; |
| 15382 | }else if( cli_strcmp(z,"-eqp")==0 ){ |
| 15383 | data.mode.autoEQP = AUTOEQP_on; |
| 15384 | }else if( cli_strcmp(z,"-eqpfull")==0 ){ |
| 15385 | data.mode.autoEQP = AUTOEQP_full; |
| 15386 | }else if( cli_strcmp(z,"-stats")==0 ){ |
| 15387 | data.mStats = CLISTAT_ON; |
| 15388 | }else if( cli_strcmp(z,"-scanstats")==0 ){ |
| 15389 | data.mode.scanstatsOn = 1; |
| 15390 | }else if( cli_strcmp(z,"-backslash")==0 ){ |
| 15391 | /* Undocumented command-line option: -backslash |
| 15392 | ** Causes C-style backslash escapes to be evaluated in SQL statements |
| 15393 | ** prior to sending the SQL into SQLite. Useful for injecting |
| 15394 | ** crazy bytes in the middle of SQL statements for testing and debugging. |
| 15395 | */ |
| 15396 | ShellSetFlag(&data, SHFLG_Backslash); |
| 15397 | }else if( cli_strcmp(z,"-bail")==0 ){ |
| 15398 | /* No-op. The bail_on_error flag should already be set. */ |
| 15399 | }else if( cli_strcmp(z,"-version")==0 ){ |
| 15400 | cli_printf(stdout, "%s %s (%d-bit)\n", |
| 15401 | sqlite3_libversion(), sqlite3_sourceid(), 8*(int)sizeof(char*)); |
| 15402 | rc = 0; |
| 15403 | goto shell_main_exit; |
| 15404 | }else if( cli_strcmp(z,"-interactive")==0 ){ |
| 15405 | /* Need to check for interactive override here to so that it can |
| 15406 | ** affect console setup (for Windows only) and testing thereof. |
| 15407 | */ |
| 15408 | stdin_is_interactive = 1; |
| 15409 | }else if( cli_strcmp(z,"-batch")==0 ){ |
| 15410 | /* already handled */ |
| 15411 | }else if( cli_strcmp(z,"-screenwidth")==0 ){ |
| 15412 | i++; |
| 15413 | }else if( cli_strcmp(z,"-utf8")==0 ){ |
| 15414 | /* already handled */ |
| 15415 | }else if( cli_strcmp(z,"-no-utf8")==0 ){ |
| 15416 | /* already handled */ |
| 15417 | }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){ |
| 15418 | /* already handled */ |
| 15419 | }else if( cli_strcmp(z,"-heap")==0 ){ |
| 15420 | i++; |
| 15421 | }else if( cli_strcmp(z,"-pagecache")==0 ){ |
| 15422 | i+=2; |
| 15423 | }else if( cli_strcmp(z,"-lookaside")==0 ){ |
| 15424 | i+=2; |
| 15425 | }else if( cli_strcmp(z,"-threadsafe")==0 ){ |
| 15426 | i+=2; |
| 15427 | }else if( cli_strcmp(z,"-nonce")==0 ){ |
| 15428 | i += 2; |
| 15429 | }else if( cli_strcmp(z,"-mmap")==0 ){ |
| 15430 | i++; |
| 15431 | }else if( cli_strcmp(z,"-memtrace")==0 ){ |
| 15432 | i++; |
| 15433 | }else if( cli_strcmp(z,"-pcachetrace")==0 ){ |
| 15434 | i++; |
| 15435 | #ifdef SQLITE_ENABLE_SORTER_REFERENCES |
| 15436 | }else if( cli_strcmp(z,"-sorterref")==0 ){ |
| 15437 | i++; |
| 15438 | #endif |
| 15439 | }else if( cli_strcmp(z,"-vfs")==0 ){ |
| 15440 | i++; |
| 15441 | }else if( cli_strcmp(z,"-vfstrace")==0 ){ |
| 15442 | i++; |
| 15443 | #ifdef SQLITE_ENABLE_MULTIPLEX |
| 15444 | }else if( cli_strcmp(z,"-multiplex")==0 ){ |
| 15445 | i++; |
| 15446 | #endif |
| 15447 | }else if( cli_strcmp(z,"-cmdline-edit")==0 ){ |
| 15448 | i+=2; |
| 15449 | }else if( cli_strcmp(z,"-help")==0 ){ |
| 15450 | usage(1); |
| 15451 | }else if( cli_strcmp(z,"-cmd")==0 ){ |
| 15452 | /* Run commands that follow -cmd first and separately from commands |
| 15453 | ** that simply appear on the command-line. This seems goofy. It would |
| 15454 | ** be better if all commands ran in the order that they appear. But |
| 15455 | ** we retain the goofy behavior for historical compatibility. */ |
| 15456 | if( i==argc-1 ) break; |
| 15457 | z = cmdline_option_value(argc,argv,++i); |
| 15458 | if( z[0]=='.' ){ |
| 15459 | rc = do_meta_command(z, &data); |
| 15460 | if( rc && (bail_on_error || rc==2) ){ |
| 15461 | if( rc==2 ) rc = 0; |
| 15462 | goto shell_main_exit; |
| 15463 | } |
| 15464 | }else{ |
| 15465 | rc = runOneSqlLine(&data, z, "cmdline", i); |
| 15466 | if( bail_on_error ) goto shell_main_exit; |
| 15467 | } |
| 15468 | #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) |
| 15469 | }else if( cli_strncmp(z, "-A", 2)==0 ){ |
| 15470 | if( nCmd>0 ){ |
| 15471 | cli_printf(stderr,"Error: cannot mix regular SQL or dot-commands" |
| 15472 | " with \"%s\"\n", z); |
| 15473 | rc = 1; |
| 15474 | goto shell_main_exit; |
| 15475 | } |
| 15476 | open_db(&data, OPEN_DB_ZIPFILE); |
| 15477 | if( z[2] ){ |
| 15478 | char *zSaved = argv[i]; |
| 15479 | argv[i] = &z[2]; |
| 15480 | arDotCommand(&data, 1, argv+(i-1), argc-(i-1)); |
| 15481 | argv[i] = zSaved; |
| 15482 | }else{ |
| 15483 | arDotCommand(&data, 1, argv+i, argc-i); |
| 15484 | } |
| 15485 | readStdin = 0; |
| 15486 | stdin_is_interactive = 0; |
| 15487 | break; |
| 15488 | #endif |
| 15489 | }else if( cli_strcmp(z,"-safe")==0 ){ |
| 15490 | data.bSafeMode = data.bSafeModePersist = 1; |
| 15491 | }else if( cli_strcmp(z,"-unsafe-testing")==0 |
| 15492 | || cli_strcmp(z,"-unsafe")==0 ){ |
| 15493 | /* Acted upon in first pass. */ |
| 15494 | }else if( cli_strcmp(z,"-runtests")==0 ){ |
| 15495 | /* Acted upon in first pass. */ |
| 15496 | }else if( cli_strcmp(z,"-test-parse")==0 ){ |
| 15497 | /* Acted upon in first pass. */ |
| 15498 | }else{ |
| 15499 | cli_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z); |
| 15500 | eputz("Use -help for a list of options.\n"); |
| 15501 | rc = 1; |
| 15502 | goto shell_main_exit; |
| 15503 | } |
| 15504 | } |
| 15505 | |
| 15506 | if( !readStdin ){ |
| 15507 | /* Run all arguments that do not begin with '-' as if they were separate |
| 15508 | ** command-line inputs, except for the argToSkip argument which contains |
| 15509 | ** the database filename. |
| 15510 | */ |
| 15511 | for(i=0; i<nCmd; i++){ |
| 15512 | echo_group_input(&data, azCmd[i]); |
| 15513 | if( isScriptFile(azCmd[i],0) ){ |
| 15514 | FILE *inSaved = data.in; |
| 15515 | i64 savedLineno = data.lineno; |
| 15516 | int res = 1; |
| 15517 | if( (data.in = openChrSource(azCmd[i]))!=0 ){ |
| 15518 | res = process_input(&data, azCmd[i]); |
| 15519 | fclose(data.in); |
| 15520 | } |
| 15521 | data.in = inSaved; |
| 15522 | data.lineno = savedLineno; |
| 15523 | if( res && bail_on_error ) i = nCmd; |
| 15524 | }else if( azCmd[i][0]=='.' ){ |
| 15525 | char *zErrCtx = malloc( 64 ); |
| 15526 | shell_check_oom(zErrCtx); |
| 15527 | sqlite3_snprintf(64,zErrCtx,"argv[%i]:",aiCmd[i]); |
| 15528 | data.zInFile = "<cmdline>"; |
| 15529 | data.zErrPrefix = zErrCtx; |
| 15530 | rc = do_meta_command(azCmd[i], &data); |
| 15531 | free(data.zErrPrefix); |
| 15532 | data.zErrPrefix = 0; |
| 15533 | if( rc ){ |
| 15534 | if( rc==2 ) rc = 0; |
| 15535 | goto shell_main_exit; |
| 15536 | } |
| 15537 | }else{ |
| 15538 | rc = runOneSqlLine(&data, azCmd[i], "cmdline", aiCmd[i]); |
| 15539 | if( data.nPopMode ){ |
| 15540 | modePop(&data); |
| 15541 | data.nPopMode = 0; |
| 15542 | } |
| 15543 | if( rc ){ |
| 15544 | goto shell_main_exit; |
| 15545 | } |
| 15546 | } |
| 15547 | if( data.nPopOutput && azCmd[i][0]!='.' ){ |
| 15548 | output_reset(&data); |
| 15549 | data.nPopOutput = 0; |
| 15550 | }else{ |
| 15551 | clearTempFile(&data,0,0); |
| 15552 | } |
| 15553 | } |
| 15554 | }else{ |
| 15555 | /* Run commands received from standard input |
| 15556 | */ |
| 15557 | if( stdin_is_interactive ){ |
| 15558 | char *zHome; |
| 15559 | char *zHistory; |
| 15560 | cli_printf(stdout, |
| 15561 | "SQLite version %s %.19s\n" /*extra-version-info*/ |
| 15562 | "Enter \".help\" for usage hints.\n", |
| 15563 | sqlite3_libversion(), sqlite3_sourceid()); |
| 15564 | if( warnInmemoryDb ){ |
| 15565 | sputz(stdout, "Connected to a "); |
| 15566 | printBold("transient in-memory database"); |
| 15567 | sputz(stdout, ".\nUse \".open FILENAME\" to reopen on a" |
| 15568 | " persistent database.\n"); |
| 15569 | } |
| 15570 | zHistory = getenv("SQLITE_HISTORY"); |
| 15571 | if( zHistory ){ |
| 15572 | zHistory = sqlite3_mprintf("%s", zHistory); |
| 15573 | shell_check_oom(zHistory); |
| 15574 | }else{ |
| 15575 | zHistory = find_xdg_file("XDG_STATE_HOME", |
| 15576 | ".local/state", |
| 15577 | "sqlite_history"); |
| 15578 | if( 0==zHistory && (zHome = find_home_dir(0))!=0 ){ |
| 15579 | zHistory = sqlite3_mprintf("%s/.sqlite_history", zHome); |
| 15580 | shell_check_oom(zHistory); |
| 15581 | } |
| 15582 | } |
| 15583 | if( zHistory ){ shell_read_history(zHistory); } |
| 15584 | #if (HAVE_READLINE || HAVE_EDITLINE) && !defined(SQLITE_OMIT_READLINE_COMPLETION) |
| 15585 | rl_attempted_completion_function = readline_completion; |
| 15586 | #elif HAVE_LINENOISE==1 |
| 15587 | linenoiseSetCompletionCallback(linenoise_completion); |
| 15588 | #elif HAVE_LINENOISE==2 |
| 15589 | linenoiseSetCompletionCallback(linenoise_completion, NULL); |
| 15590 | #endif |
| 15591 | data.in = 0; |
| 15592 | open_db(&data, 0); |
| 15593 | rc = process_input(&data, "<stdin>"); |
| 15594 | if( zHistory ){ |
| 15595 | shell_stifle_history(2000); |
| 15596 | shell_write_history(zHistory); |
| 15597 | sqlite3_free(zHistory); |
| 15598 | } |
| 15599 | }else{ |
| 15600 | data.in = stdin; |
| 15601 | rc = process_input(&data, "<stdin>"); |
| 15602 | } |
| 15603 | } |
| 15604 | #ifndef SQLITE_SHELL_FIDDLE |
| 15605 | /* In WASM mode we have to leave the db state in place so that |
| 15606 | ** client code can "push" SQL into it after this call returns. */ |
| 15607 | #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION) |
| 15608 | if( data.expert.pExpert ){ |
| 15609 | expertFinish(&data, 1, 0); |
| 15610 | } |
| 15611 | #endif |
| 15612 | shell_main_exit: |
| 15613 | free(azCmd); |
| 15614 | free(aiCmd); |
| 15615 | set_table_name(&data, 0); |
| 15616 | if( data.db ){ |
| 15617 | session_close_all(&data, -1); |
| 15618 | close_db(data.db); |
| 15619 | } |
| 15620 | for(i=0; i<ArraySize(data.aAuxDb); i++){ |
| 15621 | sqlite3_free(data.aAuxDb[i].zFreeOnClose); |
| 15622 | if( data.aAuxDb[i].db ){ |
| 15623 | session_close_all(&data, i); |
| 15624 | close_db(data.aAuxDb[i].db); |
| 15625 | } |
| 15626 | } |
| 15627 | find_home_dir(1); |
| 15628 | output_reset(&data); |
| 15629 | data.doXdgOpen = 0; |
| 15630 | clearTempFile(&data,10000,1); |
| 15631 | globalShellState = 0; |
| 15632 | while( data.nModeStack ) modePop(&data); |
| 15633 | free(data.aModeStack); |
| 15634 | modeFree(&data.mode); |
| 15635 | if( data.nSavedModes ){ |
| 15636 | int ii; |
| 15637 | for(ii=0; ii<data.nSavedModes; ii++){ |
| 15638 | modeFree(&data.aSavedModes[ii].mode); |
| 15639 | free(data.aSavedModes[ii].zTag); |
| 15640 | } |
| 15641 | free(data.aSavedModes); |
| 15642 | } |
| 15643 | free(data.zEqpFile); |
| 15644 | free(data.zErrPrefix); |
| 15645 | free(data.zNonce); |
| 15646 | free(data.dot.zCopy); |
| 15647 | free(data.dot.azArg); |
| 15648 | free(data.dot.aiOfst); |
| 15649 | free(data.dot.abQuot); |
| 15650 | free(data.azPrompt[0]); |
| 15651 | free(data.azPrompt[1]); |
| 15652 | free(data.zAuthDeny); |
| 15653 | free(data.zAuthIgnore); |
| 15654 | if( data.nTestRun ){ |
| 15655 | sqlite3_fprintf(stdout, "%d test%s run with %d error%s\n", |
| 15656 | data.nTestRun, data.nTestRun==1 ? "" : "s", |
| 15657 | data.nTestErr, data.nTestErr==1 ? "" : "s"); |
| 15658 | fflush(stdout); |
| 15659 | rc = data.nTestErr>0; |
| 15660 | } |
| 15661 | /* Clear the global data structure so that valgrind will detect memory |
| 15662 | ** leaks */ |
| 15663 | memset(&data, 0, sizeof(data)); |
| 15664 | if( bEnableVfstrace ){ |
| 15665 | vfstrace_unregister("trace"); |
| 15666 | } |
| 15667 | sqlite3_reset_auto_extension(); |
| 15668 | #ifdef SQLITE_DEBUG |
| 15669 | if( sqlite3_memory_used()>mem_main_enter ){ |
| 15670 | cli_printf(stderr,"Memory leaked: %u bytes\n", |
| 15671 | (unsigned int)(sqlite3_memory_used()-mem_main_enter)); |
| 15672 | } |
| 15673 | #endif |
| 15674 | #else /* SQLITE_SHELL_FIDDLE... */ |
| 15675 | shell_main_exit: |
| 15676 | #endif |
| 15677 | return rc; |
| 15678 | } |
| 15679 | |
| 15680 | |
| 15681 | #ifdef SQLITE_SHELL_FIDDLE |
| 15682 | /* Only for emcc experimentation purposes. */ |
| 15683 | int fiddle_experiment(int a,int b){ |
| 15684 | return a + b; |
| 15685 | } |
| 15686 | |
| 15687 | /* |
| 15688 | ** Returns a pointer to the current DB handle. |
| 15689 | */ |
| 15690 | sqlite3 * fiddle_db_handle(){ |
| 15691 | return globalDb; |
| 15692 | } |
| 15693 | |
| 15694 | /* |
| 15695 | ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then |
| 15696 | ** "main" is assumed. Returns 0 if no db with the given name is |
| 15697 | ** open. |
| 15698 | */ |
| 15699 | sqlite3_vfs * fiddle_db_vfs(const char *zDbName){ |
| 15700 | sqlite3_vfs * pVfs = 0; |
| 15701 | if(globalDb){ |
| 15702 | sqlite3_file_control(globalDb, zDbName ? zDbName : "main", |
| 15703 | SQLITE_FCNTL_VFS_POINTER, &pVfs); |
| 15704 | } |
| 15705 | return pVfs; |
| 15706 | } |
| 15707 | |
| 15708 | /* Only for emcc experimentation purposes. */ |
| 15709 | sqlite3 * fiddle_db_arg(sqlite3 *arg){ |
| 15710 | cli_printf(stdout, "fiddle_db_arg(%p)\n", (const void*)arg); |
| 15711 | return arg; |
| 15712 | } |
| 15713 | |
| 15714 | /* |
| 15715 | ** Intended to be called via a SharedWorker() while a separate |
| 15716 | ** SharedWorker() (which manages the wasm module) is performing work |
| 15717 | ** which should be interrupted. Unfortunately, SharedWorker is not |
| 15718 | ** portable enough to make real use of. |
| 15719 | */ |
| 15720 | void fiddle_interrupt(void){ |
| 15721 | if( globalDb ) sqlite3_interrupt(globalDb); |
| 15722 | } |
| 15723 | |
| 15724 | /* |
| 15725 | ** Returns the filename of the given db name, assuming "main" if |
| 15726 | ** zDbName is NULL. Returns NULL if globalDb is not opened. |
| 15727 | */ |
| 15728 | const char * fiddle_db_filename(const char * zDbName){ |
| 15729 | return globalDb |
| 15730 | ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main") |
| 15731 | : NULL; |
| 15732 | } |
| 15733 | |
| 15734 | /* |
| 15735 | ** Completely wipes out the contents of the currently-opened database |
| 15736 | ** but leaves its storage intact for reuse. If any transactions are |
| 15737 | ** active, they are forcibly rolled back. |
| 15738 | */ |
| 15739 | void fiddle_reset_db(void){ |
| 15740 | if( globalDb ){ |
| 15741 | int rc; |
| 15742 | while( sqlite3_txn_state(globalDb,0)>0 ){ |
| 15743 | /* |
| 15744 | ** Resolve problem reported in |
| 15745 | ** https://sqlite.org/forum/forumpost/0b41a25d65 |
| 15746 | */ |
| 15747 | cli_puts("Rolling back in-progress transaction.\n", stdout); |
| 15748 | sqlite3_exec(globalDb,"ROLLBACK", 0, 0, 0); |
| 15749 | } |
| 15750 | rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, |
| 15751 | (int*)0); |
| 15752 | if( 0==rc ) sqlite3_exec(globalDb, "VACUUM", 0, 0, 0); |
| 15753 | sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, |
| 15754 | (int*)0); |
| 15755 | } |
| 15756 | } |
| 15757 | |
| 15758 | /* |
| 15759 | ** Uses the current database's VFS xRead to stream the db file's |
| 15760 | ** contents out to the given callback. The callback gets a single |
| 15761 | ** chunk of size n (its 2nd argument) on each call and must return 0 |
| 15762 | ** on success, non-0 on error. This function returns 0 on success, |
| 15763 | ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0 |
| 15764 | ** code from the callback. Note that this is not thread-friendly: it |
| 15765 | ** expects that it will be the only thread reading the db file and |
| 15766 | ** takes no measures to ensure that is the case. |
| 15767 | */ |
| 15768 | int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){ |
| 15769 | sqlite3_int64 nSize = 0; |
| 15770 | sqlite3_int64 nPos = 0; |
| 15771 | sqlite3_file * pFile = 0; |
| 15772 | unsigned char buf[1024 * 8]; |
| 15773 | int nBuf = (int)sizeof(buf); |
| 15774 | int rc = shellState.db |
| 15775 | ? sqlite3_file_control(shellState.db, "main", |
| 15776 | SQLITE_FCNTL_FILE_POINTER, &pFile) |
| 15777 | : SQLITE_NOTFOUND; |
| 15778 | if( rc ) return rc; |
| 15779 | rc = pFile->pMethods->xFileSize(pFile, &nSize); |
| 15780 | if( rc ) return rc; |
| 15781 | if(nSize % nBuf){ |
| 15782 | /* DB size is not an even multiple of the buffer size. Reduce |
| 15783 | ** buffer size so that we do not unduly inflate the db size when |
| 15784 | ** exporting. */ |
| 15785 | if(0 == nSize % 4096) nBuf = 4096; |
| 15786 | else if(0 == nSize % 2048) nBuf = 2048; |
| 15787 | else if(0 == nSize % 1024) nBuf = 1024; |
| 15788 | else nBuf = 512; |
| 15789 | } |
| 15790 | for( ; 0==rc && nPos<nSize; nPos += nBuf ){ |
| 15791 | rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos); |
| 15792 | if(SQLITE_IOERR_SHORT_READ == rc){ |
| 15793 | rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/; |
| 15794 | } |
| 15795 | if( 0==rc ) rc = xCallback(buf, nBuf); |
| 15796 | } |
| 15797 | return rc; |
| 15798 | } |
| 15799 | |
| 15800 | /* |
| 15801 | ** Trivial exportable function for emscripten. It processes zSql as if |
| 15802 | ** it were input to the sqlite3 shell and redirects all output to the |
| 15803 | ** wasm binding. fiddle_main() must have been called before this |
| 15804 | ** is called, or results are undefined. |
| 15805 | */ |
| 15806 | void fiddle_exec(const char * zSql){ |
| 15807 | if(zSql && *zSql){ |
| 15808 | if('.'==*zSql) puts(zSql); |
| 15809 | shellState.wasm.zInput = zSql; |
| 15810 | shellState.wasm.zPos = zSql; |
| 15811 | process_input(&shellState, "<stdin>"); |
| 15812 | shellState.wasm.zInput = shellState.wasm.zPos = 0; |
| 15813 | } |
| 15814 | } |
| 15815 | |
| 15816 | char *fiddle_get_prompt(void){ |
| 15817 | return expand_prompt(&shellState, 0, prompt_string(&shellState,0)); |
| 15818 | } |
| 15819 | #endif /* SQLITE_SHELL_FIDDLE */ |