Fossil SCM

fossil-scm / extsrc / shell.c
Source Blame History 7915 lines
71439dc… drh 1 ** ext/misc/diskused.c
564007c… drh 2 ** ext/misc/optname.c
ee87371… drh 3 ** ext/misc/strdup.c
c92989d… drh 4 ** ext/misc/tryeval.c
a10f931… drh 5
a10f931… drh 6 /*
a10f931… drh 7 ** Limit input nesting via .read or any other input redirect.
a10f931… drh 8 ** It's not too expensive, so a generous allowance can be made.
a10f931… drh 9 */
a10f931… drh 10 #define MAX_INPUT_NESTING 25
a10f931… drh 11
a10f931… drh 12 /*
a10f931… drh 13 ** Used to prevent warnings about unused parameters
a10f931… drh 14 */
a10f931… drh 15 #define UNUSED_PARAMETER(x) (void)(x)
a10f931… drh 16
a10f931… drh 17 /*
a10f931… drh 18 ** Number of elements in an array
a10f931… drh 19 */
a10f931… drh 20 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
cb89386… drh 21 #include <stdint.h>
055e4d0… drh 22 #include <time.h>
055e4d0… drh 23 #elif HAVE_EDITLINE
055e4d0… drh 24 /* If both HAVE_READLINE and HAVE_EDITLINE are true, assume that this
055e4d0… drh 25 ** libedit installation does not have its own headers, instead using
055e4d0… drh 26 ** those from libreadline. */
896a463… drh 27 # define SHELL_CMDLINE_EDIT_AVAILABLE 1 /* command-line editing available */
896a463… drh 28 # define SHELL_CMDLINE_EDIT_AVAILABLE 1 /* command-line editing available */
896a463… drh 29 # define SHELL_CMDLINE_EDIT_AVAILABLE 0 /* command-line editing not available */
896a463… drh 30 #endif
896a463… drh 31 /*
896a463… drh 32 ** Global variable shellCmdLineEdit determines whether or not command-line
896a463… drh 33 ** editing is enabled. It defaults to 1 if the CLI is linked against a
896a463… drh 34 ** command-line editing library (linenoise, readline, or editline) and
896a463… drh 35 ** to 0 if no command-line editing library is available. The
896a463… drh 36 ** "--cmdline-edit off" command-line option will change this value to 0.
896a463… drh 37 */
896a463… drh 38 static int shellCmdLineEdit = SHELL_CMDLINE_EDIT_AVAILABLE;
0201a1e… drh 39 b1 = sqlite3_malloc64( (sz1+1)*sizeof(b1[0]) );
0201a1e… drh 40 b2 = sqlite3_malloc64( (sz2+1)*sizeof(b1[0]) );
0201a1e… drh 41 b1 = sqlite3_malloc64( (sz1+1)*sizeof(b1[0]) );
0201a1e… drh 42 b2 = sqlite3_malloc64( (sz2+1)*sizeof(b1[0]) );
0201a1e… drh 43 wchar_t *b1 = sqlite3_malloc64( sz*sizeof(wchar_t) );
0201a1e… drh 44 wchar_t *b1 = sqlite3_malloc64( (sz+1)*sizeof(wchar_t) );
677842d… drh 45 if( z==0 ) return -1;
677842d… drh 46 if( z==0 ) return -1;
3361df8… drh 47 ** Header file for the Query Result-Format or "qrf" utility library for
3361df8… drh 48 ** SQLite. See the README.md documentation for additional information.
cb89386… drh 49 unsigned int nMultiInsert; /* Add rows to one INSERT until size exceeds */
ee87371… drh 50 /* The following are available in iVersion 2 and later */
ee87371… drh 51 unsigned char bRowCount; /* Show the number of rows at end of each query */
471d617… drh 52 char *zIFmt; /* Format string for integers */
471d617… drh 53 char *zFpFmt; /* Format string for floating point */
055e4d0… drh 54 ** Range of values for sqlite3_qrf_spec.aWidth[] entries.
896a463… drh 55 #define QRF_STYLE_Html 7 /* Generate HTML-style <tr><td> output */
ee87371… drh 56 ** Additional value allowed for bTitles
ee87371… drh 57 */
ee87371… drh 58 #define QRF_Always 3 /* Always show titles, even if no rows */
ee87371… drh 59
ee87371… drh 60 /*
471d617… drh 61 /*
471d617… drh 62 ** The argument is a proposed format string for the zIFmt or zFpFmt
471d617… drh 63 ** parameters. Return value indicates:
471d617… drh 64 **
471d617… drh 65 ** 0 The input is not a valid format string. If this string
471d617… drh 66 ** appears in either zIFmt or zFpFmt, it will be ignored.
471d617… drh 67 **
471d617… drh 68 ** 1 The input is a valid format string for integers.
471d617… drh 69 **
471d617… drh 70 ** 2 The input is a valid format string for floating point.
471d617… drh 71 */
471d617… drh 72 int sqlite3_qrf_ckformat(const char*);
3361df8… drh 73 ** Implementation of the Query Result-Format or "qrf" utility library for
3361df8… drh 74 ** SQLite. See the README.md documentation for additional information.
3361df8… drh 75 #ifndef SQLITE_AMALGAMATION
3361df8… drh 76 #endif
17f9878… drh 77 unsigned int nIns; /* Bytes used for current INSERT stmt */
471d617… drh 78 char zFmt[24]; /* Space to hold the true integer rendering fmt */
471d617… drh 79
471d617… drh 80 /*
471d617… drh 81 ** The argument is a proposed format string for the zIFmt or zFpFmt
471d617… drh 82 ** parameters. Return value indicates:
471d617… drh 83 **
471d617… drh 84 ** 0 The input is not a valid format string. If this string
471d617… drh 85 ** appears in either zIFmt or zFpFmt, it will be ignored.
471d617… drh 86 **
471d617… drh 87 ** 1 The input is a valid format string for integers.
471d617… drh 88 **
471d617… drh 89 ** 2 The input is a valid format string for floating point.
471d617… drh 90 */
471d617… drh 91 int sqlite3_qrf_ckformat(const char *z){
471d617… drh 92 size_t n;
471d617… drh 93 if( z==0 ) return 0;
471d617… drh 94 if( z[0]!='%' ) return 0;
471d617… drh 95 z++;
471d617… drh 96 n = strspn(z,"+-,#0");
471d617… drh 97 if( n>5 ) return 0;
471d617… drh 98 z += n;
471d617… drh 99 if( z[0]>='1' && z[0]<='9' ){
471d617… drh 100 n = strspn(z,"0123456789");
471d617… drh 101 if( n>3 ) return 0;
471d617… drh 102 z += n;
471d617… drh 103 }
471d617… drh 104 if( z[0]=='.' ){
471d617… drh 105 z++;
471d617… drh 106 n = strspn(z,"0123456789");
471d617… drh 107 if( n>3 ) return 0;
471d617… drh 108 z += n;
471d617… drh 109 }
471d617… drh 110 n = strspn(z,"eEgGf");
471d617… drh 111 if( n==1 && z[1]==0 ) return 2;
471d617… drh 112 n = strspn(z,"dxXo");
471d617… drh 113 if( n==1 && z[1]==0 ) return 1;
471d617… drh 114 return 0;
471d617… drh 115 }
471d617… drh 116
055e4d0… drh 117 if( N>=9223372036854775800LL ){
055e4d0… drh 118 sqlite3_str_appendf(pOut, "%.2fE", 1e-18*(double)N);
055e4d0… drh 119 return;
055e4d0… drh 120 }
677842d… drh 121 n = (z ? (int)strlen(z) : 0) + qrfStatsHeight(pS,i)*3;
055e4d0… drh 122 sqlite3_str_appendf(pStats, " %3.0f%%",
055e4d0… drh 123 ((100.0*(double)nCycle)+nTotal/2.0) / (double)nTotal
c5bdd31… drh 124 sqlite3_str_free(pLine);
c5bdd31… drh 125 sqlite3_str_free(pStats);
c92989d… drh 126 }else{
c92989d… drh 127 /* Any other control character is shown by qrfAppendWithTabs()
c92989d… drh 128 ** as a one-column-wide Control Picture symbol, and is counted as
c92989d… drh 129 ** one column by qrfWrapLine(). Count it as one column here too,
c92989d… drh 130 ** so that columns are wide enough to hold it. */
c92989d… drh 131 n++;
9b67f46… drh 132 ** Escape the text starting at byte iStart of pStr, if needed, using the
9b67f46… drh 133 ** escape encoding of eEsc, which is either QRF_ESC_Ascii or QRF_ESC_Symbol.
9b67f46… drh 134 ** The pStr string is modified appropriately.
9b67f46… drh 135 ** If no escaping is needed (the common case) then pStr is unchanged.
9b67f46… drh 136 ** If escaping is required, then pStr is expanded and modified to hold
9b67f46… drh 137 ** an escaped representation of the text.
9b67f46… drh 138 unsigned int nIn; /* Bytes of text to be escaped */
9b67f46… drh 139 nIn = sqlite3_str_length(pStr);
9b67f46… drh 140 nIn -= iStart;
9b67f46… drh 141 for(i=0; i<nIn; i++){
9b67f46… drh 142 if( (c = zIn[i])<=0x1f
9b67f46… drh 143 memmove(zIn,zOut,nIn);
9b67f46… drh 144 for(i=j=0; i<nIn; i++){
9b67f46… drh 145 if( (c = zIn[i])>0x1f
9b67f46… drh 146 nIn -= i+1;
e66a8c7… drh 147 if( z[i]=='0' && (z[i+1]=='x' || z[i+1]=='X') ){
e66a8c7… drh 148 /* Hexadecimal integer literal: 0x1f */
e66a8c7… drh 149 i += 2;
e66a8c7… drh 150 n = strspn(&z[i], "0123456789abcdefABCDEF");
e66a8c7… drh 151 return n==0 || z[i+n]!=0;
e66a8c7… drh 152 }
e66a8c7… drh 153 if( z[i]=='.' && qrfDigit(z[i+1]) ){
e66a8c7… drh 154 /* Real literal with no digits before the ".", such as ".5" */
e66a8c7… drh 155 i++;
e66a8c7… drh 156 }else if( !qrfDigit(z[i]) ){
e66a8c7… drh 157 return 1;
e66a8c7… drh 158 }else{
e66a8c7… drh 159 while( qrfDigit(z[i]) ){ i++; }
e66a8c7… drh 160 if( z[i]=='.' ) i++;
e66a8c7… drh 161 }
3b2d0c9… drh 162 case '>': sqlite3_str_append(pOut, "&gt;", 4); break;
c92989d… drh 163 int nEllipsis = 0; /* Display width of the text before zEllipsis */
c92989d… drh 164 if( n>=(N-3) && zEllipsis==0 ){ zEllipsis = z; nEllipsis = n; }
c92989d… drh 165 int w = sqlite3_qrf_wcwidth(u); /* Display width, not byte count */
c92989d… drh 166 if( n+w>(N-3) && zEllipsis==0 ){ zEllipsis = z; nEllipsis = n; }
c92989d… drh 167 if( n+w>N ){ z[0] = 0; break; }
c92989d… drh 168 n += w;
c92989d… drh 169 if( zEllipsis && N>=3 ){
c92989d… drh 170 memcpy(zEllipsis,"...",4);
c92989d… drh 171 n = nEllipsis + 3; /* Width of the text kept plus the "..." */
c92989d… drh 172 }
471d617… drh 173 sqlite3_str_appendf(pOut, p->spec.zIFmt,
471d617… drh 174 sqlite3_column_int64(p->pStmt,iCol));
471d617… drh 175 if( p->spec.zFpFmt ){
471d617… drh 176 double r = sqlite3_column_double(p->pStmt,iCol);
471d617… drh 177 sqlite3_str_appendf(pOut,p->spec.zFpFmt,r);
471d617… drh 178 }else{
471d617… drh 179 const char *zTxt = (const char*)sqlite3_column_text(p->pStmt,iCol);
471d617… drh 180 sqlite3_str_appendall(pOut, zTxt);
471d617… drh 181 }
9b67f46… drh 182 const void *pBlob = sqlite3_column_blob(p->pStmt,iCol);
9b67f46… drh 183 int nBlob = sqlite3_column_bytes(p->pStmt,iCol);
9b67f46… drh 184 int rc;
9b67f46… drh 185 qrfWrite(p);
9b67f46… drh 186 if( nBlob==0 ){
9b67f46… drh 187 /* no-op */
9b67f46… drh 188 }else if( p->spec.eEsc==QRF_ESC_Off ){
9b67f46… drh 189 rc = p->spec.xWrite(p->spec.pWriteArg,pBlob,nBlob);
9b67f46… drh 190 if( rc ){
9b67f46… drh 191 qrfError(p, rc, "Failed to write %d bytes of BLOB output", nBlob);
9b67f46… drh 192 }
9b67f46… drh 193 }else{
9b67f46… drh 194 sqlite3_str_append(pOut, pBlob, nBlob);
9b67f46… drh 195 qrfEscape(p->spec.eEsc, pOut, 0);
9b67f46… drh 196 qrfWrite(p);
9b67f46… drh 197 }
c92989d… drh 198 if( p->spec.eText==QRF_TEXT_Html ){
c92989d… drh 199 /* The NULL text is user-supplied (--null) and must be escaped */
c92989d… drh 200 qrfEncodeText(p, pOut, p->spec.zNull);
c92989d… drh 201 }else{
c92989d… drh 202 sqlite3_str_appendall(pOut, p->spec.zNull);
c92989d… drh 203 }
c92989d… drh 204 ** VT100 escape sequences and other control characters count as zero.
c92989d… drh 205 ** And so forth.
c92989d… drh 206 }else if( c<0x20 ){
c92989d… drh 207 /* Other control characters are zero-width, as in
c92989d… drh 208 ** sqlite3_qrf_wcswidth() */
c92989d… drh 209 i++;
3b2d0c9… drh 210 if( k<i/2 && i/2>0 ){
ee87371… drh 211 #define DBL_12 "\342\225\230" /* U+2558 `= */
ee87371… drh 212 #define DBL_14 "\342\225\233" /* U+255b =' */
ee87371… drh 213 #define DBL_124 "\342\225\247" /* U+2567 ='= */
ee87371… drh 214
055e4d0… drh 215 i64 nn = 3*(i64)N;
055e4d0… drh 216 while( nn>nDash ){
055e4d0… drh 217 nn -= nDash;
055e4d0… drh 218 sqlite3_str_append(pOut, azDash[bDbl], (int)nn);
ee87371… drh 219 sqlite3_str *pOut, /* Output to this sqlite3_str */
ee87371… drh 220 qrfColData *p, /* Columnar data */
ee87371… drh 221 const char *zSep1, /* Left margin */
ee87371… drh 222 const char *zSep2, /* Column separator */
ee87371… drh 223 const char *zSep3, /* Right margin */
ee87371… drh 224 int bDbl /* True for double-lines */
ee87371… drh 225 }
ee87371… drh 226
ee87371… drh 227 /*
ee87371… drh 228 ** Draw a horizontal separator for a QRF_STYLE_Column table.
ee87371… drh 229 ** This style of separator is only used for separating the title
ee87371… drh 230 ** from the content.
ee87371… drh 231 */
ee87371… drh 232 static void qrfColumnSeparator(
ee87371… drh 233 sqlite3_str *pOut, /* Output to this sqlite3_str */
ee87371… drh 234 qrfColData *p, /* Columnar data */
ee87371… drh 235 const char *colSep, /* Column separator text */
ee87371… drh 236 int szColSep, /* Size of zColSep in bytes */
ee87371… drh 237 const char *rowSep, /* Row separator text */
ee87371… drh 238 int szRowSep /* Size of zRowSep in bytes */
ee87371… drh 239 ){
ee87371… drh 240 int j;
ee87371… drh 241 int nColumn = p->nCol;
ee87371… drh 242 for(j=0; j<nColumn; j++){
ee87371… drh 243 sqlite3_str_appendchar(pOut, p->a[j].w, '-');
ee87371… drh 244 if( j<nColumn-1 ){
ee87371… drh 245 sqlite3_str_append(pOut, colSep, szColSep);
ee87371… drh 246 }else{
ee87371… drh 247 qrfRTrim(pOut);
ee87371… drh 248 sqlite3_str_append(pOut, rowSep, szRowSep);
ee87371… drh 249 }
ee87371… drh 250 }
055e4d0… drh 251 i64 t; /* Total width of all columns */
055e4d0… drh 252 for(i=0, sumW=0; i<nCol; i++){
055e4d0… drh 253 if( sumW > 2147483647 - pData->a[i].w ) return;
055e4d0… drh 254 sumW += pData->a[i].w;
055e4d0… drh 255 }
055e4d0… drh 256 if( p->spec.nScreenWidth >= (i64)sumW + sepW ) return;
c5bdd31… drh 257 ** Invoke sqlite3_str_finish(). But if it returns NULL, try to allocate
c5bdd31… drh 258 ** an empty string to replace the result.
c5bdd31… drh 259 **
c5bdd31… drh 260 ** The result might still be an empty string, but only after an OOM and
c5bdd31… drh 261 ** in that case qrfOom() has been called already and so it is safe to
c5bdd31… drh 262 ** return immediately.
c5bdd31… drh 263 */
c5bdd31… drh 264 static char *qrfStrFinish(Qrf *p, sqlite3_str *pStr){
c5bdd31… drh 265 char *z = sqlite3_str_finish(pStr);
c5bdd31… drh 266 if( z==0 ) z = sqlite3_mprintf("");
c5bdd31… drh 267 if( z==0 ) qrfOom(p);
c5bdd31… drh 268 return z;
c5bdd31… drh 269 }
c5bdd31… drh 270
c5bdd31… drh 271 /*
ee87371… drh 272 if( nColumn==0 ){
ee87371… drh 273 return; /* Not a query. No results every shown. */
ee87371… drh 274 }
ee87371… drh 275 if( rc==SQLITE_DONE && nColumn>0 ){
ee87371… drh 276 /* Empty query */
ee87371… drh 277 if( p->spec.bTitles==QRF_Always ){
ee87371… drh 278 /* fall through into the columnar logic below */
ee87371… drh 279 }else{
ee87371… drh 280 if( p->spec.bRowCount==QRF_Yes ){
ee87371… drh 281 sqlite3_str_appendf(p->pOut, "(0 rows)\n");
ee87371… drh 282 qrfWrite(p);
ee87371… drh 283 }
ee87371… drh 284 return; /* No output, other than the row count */
ee87371… drh 285 }
ee87371… drh 286 }else if( rc!=SQLITE_ROW ){
ee87371… drh 287 /* Load the column header names into data */
ee87371… drh 288 if( p->spec.bTitles>=QRF_Yes ){
c5bdd31… drh 289 z = data.az[data.n] = qrfStrFinish(p, pStr);
c5bdd31… drh 290 if( z==0 ) goto columnar_done;
ee87371… drh 291
ee87371… drh 292 /* Load query results into data */
ee87371… drh 293 while( rc==SQLITE_ROW && p->iErr==SQLITE_OK ){
c5bdd31… drh 294 z = data.az[data.n] = qrfStrFinish(p,pStr);
c5bdd31… drh 295 if( z==0 ) goto columnar_done;
ee87371… drh 296 rc = sqlite3_step(p->pStmt);
ee87371… drh 297 }
ee87371… drh 298 int isTitleDataSeparator = (i==0 && p->spec.bTitles>=QRF_Yes);
ee87371… drh 299 qrfColumnSeparator(p->pOut, &data, colSep, szColSep,
ee87371… drh 300 rowSep, szRowSep);
ee87371… drh 301 if( p->spec.bBorder!=QRF_No || p->nRow==0 ){
ee87371… drh 302 if( p->nRow>0 ){
ee87371… drh 303 qrfBoxSeparator(p->pOut, &data, BOX_R12, BOX_124, BOX_R14, 0);
ee87371… drh 304 }else{
ee87371… drh 305 qrfBoxSeparator(p->pOut, &data, DBL_12, DBL_124, DBL_14, 1);
ee87371… drh 306 }
ee87371… drh 307 case QRF_STYLE_Markdown:
ee87371… drh 308 if( p->nRow==0 ){
ee87371… drh 309 qrfRowSeparator(p->pOut, &data, '|');
ee87371… drh 310 }
ee87371… drh 311 break;
ee87371… drh 312 case QRF_STYLE_Column:
ee87371… drh 313 if( p->nRow==0 ){
ee87371… drh 314 qrfColumnSeparator(p->pOut, &data, colSep, szColSep,
ee87371… drh 315 rowSep, szRowSep);
ee87371… drh 316 }
ee87371… drh 317 break;
ee87371… drh 318 }
ee87371… drh 319 if( p->spec.bRowCount==QRF_Yes ){
ee87371… drh 320 sqlite3_int64 n = p->nRow;
ee87371… drh 321 sqlite3_str_appendf(p->pOut, "(%lld row%s)\n", n, n==1 ? "" : "s");
c5bdd31… drh 322 columnar_done:
ee87371… drh 323 ** Render a title row (a row containing column names) if the spec
ee87371… drh 324 ** calls for one and if it makes sense for the eStyle. Title rows
ee87371… drh 325 ** do not make sense for some eStyles, such as QRF_STYLE_Off,
ee87371… drh 326 ** QRF_STYLE_Count, QRF_STYLE_Json, and similar.
ee87371… drh 327 */
ee87371… drh 328 static void qrfSimpleTitle(Qrf *p){
ee87371… drh 329 assert( p->nRow==0 );
ee87371… drh 330 assert( p->spec.bTitles>=QRF_Yes );
ee87371… drh 331 switch( p->spec.eStyle ){
ee87371… drh 332 case QRF_STYLE_Html: {
ee87371… drh 333 int i;
896a463… drh 334 sqlite3_str_append(p->pOut, "<tr>", 4);
ee87371… drh 335 for(i=0; i<p->nCol; i++){
ee87371… drh 336 const char *zCName = sqlite3_column_name(p->pStmt, i);
896a463… drh 337 sqlite3_str_append(p->pOut, "\n<th>", 5);
ee87371… drh 338 qrfEncodeText(p, p->pOut, zCName);
ee87371… drh 339 }
896a463… drh 340 sqlite3_str_append(p->pOut, "\n</tr>\n", 7);
ee87371… drh 341 break;
ee87371… drh 342 }
ee87371… drh 343 case QRF_STYLE_Quote:
ee87371… drh 344 case QRF_STYLE_List: {
ee87371… drh 345 int i;
ee87371… drh 346 int saved_eText = p->spec.eText;
ee87371… drh 347 p->spec.eText = p->spec.eTitle;
ee87371… drh 348 for(i=0; i<p->nCol; i++){
ee87371… drh 349 const char *zCName = sqlite3_column_name(p->pStmt, i);
ee87371… drh 350 if( i>0 ) sqlite3_str_appendall(p->pOut, p->spec.zColumnSep);
ee87371… drh 351 qrfEncodeText(p, p->pOut, zCName);
ee87371… drh 352 }
ee87371… drh 353 sqlite3_str_appendall(p->pOut, p->spec.zRowSep);
ee87371… drh 354 qrfWrite(p);
ee87371… drh 355 p->spec.eText = saved_eText;
ee87371… drh 356 break;
ee87371… drh 357 }
ee87371… drh 358 }
ee87371… drh 359 }
ee87371… drh 360
ee87371… drh 361 /*
ee87371… drh 362 if( p->nRow==0 && p->spec.bTitles>=QRF_Yes ){
ee87371… drh 363 qrfSimpleTitle(p);
ee87371… drh 364 }
896a463… drh 365 sqlite3_str_append(p->pOut, "<tr>", 4);
ee87371… drh 366 for(i=0; i<p->nCol; i++){
896a463… drh 367 sqlite3_str_append(p->pOut, "\n<td>", 5);
896a463… drh 368 sqlite3_str_append(p->pOut, "\n</tr>\n", 7);
cb89386… drh 369 unsigned int mxIns = p->spec.nMultiInsert;
17f9878… drh 370 int szStart = sqlite3_str_length(p->pOut);
17f9878… drh 371 if( p->u.nIns==0 || p->u.nIns>=mxIns ){
17f9878… drh 372 if( p->u.nIns ){
17f9878… drh 373 sqlite3_str_append(p->pOut, ";\n", 2);
17f9878… drh 374 p->u.nIns = 0;
17f9878… drh 375 }
17f9878… drh 376 if( qrf_need_quote(p->spec.zTableName) ){
17f9878… drh 377 sqlite3_str_appendf(p->pOut,"INSERT INTO \"%w\"",p->spec.zTableName);
17f9878… drh 378 }else{
17f9878… drh 379 sqlite3_str_appendf(p->pOut,"INSERT INTO %s",p->spec.zTableName);
17f9878… drh 380 }
ee87371… drh 381 if( p->spec.bTitles>=QRF_Yes ){
17f9878… drh 382 for(i=0; i<p->nCol; i++){
17f9878… drh 383 const char *zCName = sqlite3_column_name(p->pStmt, i);
17f9878… drh 384 if( qrf_need_quote(zCName) ){
17f9878… drh 385 sqlite3_str_appendf(p->pOut, "%c\"%w\"",
17f9878… drh 386 i==0 ? '(' : ',', zCName);
17f9878… drh 387 }else{
17f9878… drh 388 sqlite3_str_appendf(p->pOut, "%c%s",
17f9878… drh 389 i==0 ? '(' : ',', zCName);
17f9878… drh 390 }
17f9878… drh 391 }
17f9878… drh 392 sqlite3_str_append(p->pOut, ")", 1);
17f9878… drh 393 }
17f9878… drh 394 sqlite3_str_append(p->pOut," VALUES(", 8);
17f9878… drh 395 }else{
17f9878… drh 396 sqlite3_str_append(p->pOut,",\n (", 5);
17f9878… drh 397 }
17f9878… drh 398 p->u.nIns += sqlite3_str_length(p->pOut) + 2 - szStart;
17f9878… drh 399 if( p->u.nIns>=mxIns ){
17f9878… drh 400 sqlite3_str_append(p->pOut, ");\n", 3);
17f9878… drh 401 p->u.nIns = 0;
17f9878… drh 402 }else{
17f9878… drh 403 sqlite3_str_append(p->pOut, ")", 1);
17f9878… drh 404 }
e66a8c7… drh 405 if( mxW<2 ){
e66a8c7… drh 406 /* The column names leave little or no room for the value. Use a
e66a8c7… drh 407 ** width of at least 2, enough for any one character, so that
e66a8c7… drh 408 ** qrfWrapLine() always makes progress. */
e66a8c7… drh 409 mxW = 2;
e66a8c7… drh 410 }
17f9878… drh 411 if( cnt ){
17f9878… drh 412 sqlite3_str_appendchar(p->pOut,p->u.sLine.mxColWth+nSep,' ');
17f9878… drh 413 }
c5bdd31… drh 414 sqlite3_str_free(pVal);
ee87371… drh 415 if( p->nRow==0 && p->spec.bTitles>=QRF_Yes ){
ee87371… drh 416 qrfSimpleTitle(p);
ee87371… drh 417 if( pSpec->iVersion>2 ){
471d617… drh 418 switch( pSpec->iVersion ){
471d617… drh 419 case 0: sz = offsetof(sqlite3_qrf_spec, bRowCount); break;
471d617… drh 420 case 1: sz = offsetof(sqlite3_qrf_spec, bRowCount); break;
471d617… drh 421 default: sz = sizeof(sqlite3_qrf_spec); break;
471d617… drh 422 }
055e4d0… drh 423 if( p->mxWidth<=0 ) p->mxWidth = 2147483647;
e6e6a32… drh 424 if( p->spec.zFpFmt && sqlite3_qrf_ckformat(p->spec.zFpFmt)!=2 ){
e6e6a32… drh 425 p->spec.zFpFmt = 0;
e6e6a32… drh 426 }
e66a8c7… drh 427 if( p->spec.zFpFmt==0 ) p->spec.zFpFmt = "%!0.17g";
c92989d… drh 428 if( pSpec->zNull==0 ) p->spec.zNull = "null";
e66a8c7… drh 429 if( p->spec.zFpFmt==0 ) p->spec.zFpFmt = "%!0.17g";
17f9878… drh 430 p->u.nIns = 0;
51267fb… drh 431 if( p->spec.eEsc==QRF_Auto ) p->spec.eEsc = QRF_ESC_Off;
3361df8… drh 432 int rc = sqlite3_stmt_explain(p->pStmt, 2);
3361df8… drh 433 if( rc ){ qrfError(p, SQLITE_ERROR, sqlite3_errstr(rc)); }
3361df8… drh 434 int rc = sqlite3_stmt_explain(p->pStmt, 1);
3361df8… drh 435 if( rc ){ qrfError(p, SQLITE_ERROR, sqlite3_errstr(rc)); }
e66a8c7… drh 436 if( p->spec.eText==QRF_TEXT_Csv ){
e66a8c7… drh 437 p->spec.eEsc = QRF_ESC_Off;
e66a8c7… drh 438 }else{
e66a8c7… drh 439 p->spec.eEsc = QRF_ESC_Ascii;
e66a8c7… drh 440 }
471d617… drh 441 if( p->spec.zIFmt==0 || sqlite3_qrf_ckformat(p->spec.zIFmt)!=1 ){
471d617… drh 442 p->spec.zIFmt = "%lld";
471d617… drh 443 }else{
471d617… drh 444 size_t n = strlen(p->spec.zIFmt);
471d617… drh 445 memcpy(p->zFmt, p->spec.zIFmt, n-1);
471d617… drh 446 p->zFmt[n-1] = 'l';
471d617… drh 447 p->zFmt[n] = 'l';
471d617… drh 448 p->zFmt[n+1] = p->spec.zIFmt[n-1];
471d617… drh 449 p->zFmt[n+2] = 0;
471d617… drh 450 p->spec.zIFmt = p->zFmt;
471d617… drh 451 }
17f9878… drh 452 }
17f9878… drh 453 break;
17f9878… drh 454 }
17f9878… drh 455 case QRF_STYLE_Insert: {
17f9878… drh 456 if( p->u.nIns ){
17f9878… drh 457 sqlite3_str_append(p->pOut, ";\n", 2);
17f9878… drh 458 qrfWrite(p);
ba8756a… drh 459 zCombined = sqlite3_realloc64(p->spec.pzOutput[0], sz+n+1);
e66a8c7… drh 460 if( n ) memcpy(zCombined+sz, sqlite3_str_value(p->pOut), n);
e66a8c7… drh 461 zCombined[sz+n] = 0;
c5bdd31… drh 462 sqlite3_str_free(p->pOut);
c5bdd31… drh 463 p->spec.pzOutput[0] = qrfStrFinish(p, p->pOut);
c5bdd31… drh 464 sqlite3_str_free(p->pOut);
3361df8… drh 465 if( sqlite3_stmt_busy(pStmt) ) return SQLITE_BUSY;
ee87371… drh 466 }
ee87371… drh 467 if( qrf.nCol>0 && qrf.nRow==0 && qrf.spec.bTitles==QRF_Always ){
ee87371… drh 468 qrfSimpleTitle(&qrf);
ee87371… drh 469 }
ee87371… drh 470 if( qrf.nCol>0 && qrf.spec.bRowCount==QRF_Yes ){
ee87371… drh 471 const char *zPlural = qrf.nRow==1 ? "" : "s";
ee87371… drh 472 switch( qrf.spec.eStyle ){
ee87371… drh 473 case QRF_STYLE_Line:
ee87371… drh 474 if( qrf.nRow>0 ) sqlite3_str_append(qrf.pOut, "\n", 1);
ee87371… drh 475 /* Fall through */
ee87371… drh 476 case QRF_STYLE_Csv:
ee87371… drh 477 case QRF_STYLE_List:
ee87371… drh 478 case QRF_STYLE_Quote:
ee87371… drh 479 sqlite3_str_appendf(qrf.pOut,"(%lld row%s)\n",qrf.nRow,zPlural);
ee87371… drh 480 break;
ee87371… drh 481 case QRF_STYLE_Html:
ee87371… drh 482 sqlite3_str_appendf(qrf.pOut,"<!-- %lld row%s -->\n",
ee87371… drh 483 qrf.nRow, zPlural);
ee87371… drh 484 break;
ee87371… drh 485 case QRF_STYLE_Insert:
ee87371… drh 486 sqlite3_str_appendf(qrf.pOut,"/* %lld row%s inserted */\n",
ee87371… drh 487 qrf.nRow, zPlural);
ee87371… drh 488 break;
ee87371… drh 489 }
a10f931… drh 490 }
1ec45d0… drh 491 int isRecursive = 0;
1ec45d0… drh 492 int *pIsRecursive;
1ec45d0… drh 493 pIsRecursive = (int*)sqlite3_get_clientdata(db,"sha3_query()");
1ec45d0… drh 494 if( pIsRecursive ){
1ec45d0… drh 495 *pIsRecursive = 1;
1ec45d0… drh 496 return;
1ec45d0… drh 497 }
1ec45d0… drh 498 sqlite3_set_clientdata(db, "sha3_query()", &isRecursive, 0);
1ec45d0… drh 499 sqlite3_set_clientdata(db, "sha3_query()", 0, 0);
1ec45d0… drh 500 if( isRecursive ){
1ec45d0… drh 501 sqlite3_result_error(context, "recursive use of sha3_query()", -1);
1ec45d0… drh 502 }else{
1ec45d0… drh 503 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1ec45d0… drh 504 }
055e4d0… drh 505 #if defined(__GNUC__) && __GNUC__>=11
055e4d0… drh 506 # pragma GCC diagnostic push
055e4d0… drh 507 # pragma GCC diagnostic ignored "-Wstringop-overread"
055e4d0… drh 508 #endif
ba00a43… drh 509 if( len-i>0 ) (void)memcpy(&p->buffer[j], &data[i], len - i);
055e4d0… drh 510 #if defined(__GNUC__) && __GNUC__>=11
055e4d0… drh 511 # pragma GCC diagnostic pop
055e4d0… drh 512 #endif
17f9878… drh 513 const unsigned char *pData;
17f9878… drh 514 pData = (const unsigned char*)sqlite3_value_blob(argv[0]);
17f9878… drh 515 pData = (const unsigned char*)sqlite3_value_text(argv[0]);
1ec45d0… drh 516 if( pData==0 ){
1ec45d0… drh 517 if( nByte ) return;
1ec45d0… drh 518 pData = (const unsigned char*)"";
1ec45d0… drh 519 }
17f9878… drh 520 hash_step(&cx, pData, nByte);
1ec45d0… drh 521 int isRecursive = 0;
1ec45d0… drh 522 int *pIsRecursive;
1ec45d0… drh 523 pIsRecursive = sqlite3_get_clientdata(db, "sha1_query()");
1ec45d0… drh 524 if( pIsRecursive ){
1ec45d0… drh 525 *pIsRecursive = 1;
1ec45d0… drh 526 return;
1ec45d0… drh 527 }
17f9878… drh 528 if( z==0 ) z = "";
1ec45d0… drh 529 sqlite3_set_clientdata(db, "sha1_query()", &isRecursive, 0);
1ec45d0… drh 530 sqlite3_set_clientdata(db, "sha1_query()", 0, 0);
1ec45d0… drh 531 if( isRecursive ){
1ec45d0… drh 532 sqlite3_result_error(context, "recursive use of sha1_query()", -1);
1ec45d0… drh 533 }else{
1ec45d0… drh 534 sqlite3_result_text(context, zOut, 40, SQLITE_TRANSIENT);
1ec45d0… drh 535 }
17f9878… drh 536 #ifndef SQLITE_DECIMAL_MAX_DIGIT
17f9878… drh 537 # define SQLITE_DECIMAL_MAX_DIGIT 10000000
17f9878… drh 538 #endif
17f9878… drh 539
8594585… drh 540 **
8594585… drh 541 ** Note that zIn[] is not necessarily zero-terminated. Always
8594585… drh 542 ** respect the boundary imposed by the n argument.
17f9878… drh 543 if( zIn==0 ) goto new_from_text_failed;
0201a1e… drh 544 p = sqlite3_malloc64( sizeof(*p) );
8594585… drh 545 for(i=0; i<n && IsSpace(zIn[i]); i++){}
8594585… drh 546 if( i<n && zIn[i]=='-' ){
8594585… drh 547 }else if( i<n && zIn[i]=='+' ){
17f9878… drh 548 signed char *a = sqlite3_realloc64(p->a, (sqlite3_int64)p->nDigit
17f9878… drh 549 if( a==0 ) goto new_from_text_failed;
17f9878… drh 550 p->a = a;
17f9878… drh 551 signed char *a = sqlite3_realloc64(p->a, (sqlite3_int64)p->nDigit
17f9878… drh 552 if( a==0 ) goto new_from_text_failed;
17f9878… drh 553 p->a = a;
17f9878… drh 554 if( p->nDigit>SQLITE_DECIMAL_MAX_DIGIT ) goto new_from_text_failed;
9b67f46… drh 555 z = sqlite3_malloc64( (sqlite3_int64)p->nDigit+8 );
c92989d… drh 556 if( p->sign ){
c92989d… drh 557 for(i=0; i<p->nDigit && p->a[i]==0; i++){}
c92989d… drh 558 if( i==p->nDigit ) p->sign = 0;
c92989d… drh 559 }
ba00a43… drh 560 /* Forward declaration */
ba00a43… drh 561 static void decimal_expand(Decimal *p, int nDigit, int nFrac);
ba00a43… drh 562
b8ab8b3… drh 563 /*
b8ab8b3… drh 564 ** Round a decimal value to N significant digits. N must be positive.
b8ab8b3… drh 565 */
b8ab8b3… drh 566 static void decimal_round(Decimal *p, int N){
b8ab8b3… drh 567 int i;
ba00a43… drh 568 int nZero; /* Number of leading zeros */
b8ab8b3… drh 569 if( N<1 ) return;
17f9878… drh 570 if( p==0 ) return;
17f9878… drh 571 if( p->nDigit<=N ) return;
b8ab8b3… drh 572 for(nZero=0; nZero<p->nDigit && p->a[nZero]==0; nZero++){}
b8ab8b3… drh 573 N += nZero;
b8ab8b3… drh 574 if( p->nDigit<=N ) return;
ba00a43… drh 575 if( p->a[N]>=5 ){
ba00a43… drh 576 /* If all leading digits are 9, increase the number of digits
ba00a43… drh 577 ** by adding a new 0 to the front */
ba00a43… drh 578 for(i=0; i<N && p->a[i]==9; i++){}
ba00a43… drh 579 if( i==N ){
8594585… drh 580 decimal_expand(p, p->nDigit+1, p->nFrac);
ba00a43… drh 581 if( p->oom ) return;
ba00a43… drh 582 }
ba00a43… drh 583
ba00a43… drh 584 /* Do the rounding */
b8ab8b3… drh 585 p->a[N-1]++;
b8ab8b3… drh 586 for(i=N-1; i>0 && p->a[i]>9; i--){
b8ab8b3… drh 587 p->a[i] = 0;
b8ab8b3… drh 588 p->a[i-1]++;
b8ab8b3… drh 589 }
ba00a43… drh 590 assert( p->a[0]<=9 );
b8ab8b3… drh 591 }
b8ab8b3… drh 592 memset(&p->a[N], 0, p->nDigit - N);
b8ab8b3… drh 593 }
b8ab8b3… drh 594
b8ab8b3… drh 595 static void decimal_result_sci(sqlite3_context *pCtx, Decimal *p, int N){
b8ab8b3… drh 596 if( N<1 ) N = 0;
b8ab8b3… drh 597 for(nDigit=p->nDigit; nDigit>N && p->a[nDigit-1]==0; nDigit--){}
e66a8c7… drh 598 int nASig, nBSig, rc, n, iA, iB;
e66a8c7… drh 599 for(iA=0; iA<pA->nDigit-pA->nFrac && pA->a[iA]==0; iA++){}
e66a8c7… drh 600 for(iB=0; iB<pB->nDigit-pB->nFrac && pB->a[iB]==0; iB++){}
e66a8c7… drh 601 nASig = pA->nDigit - pA->nFrac - iA;
e66a8c7… drh 602 nBSig = pB->nDigit - pB->nFrac - iB;
e66a8c7… drh 603 n = pA->nDigit - iA;
e66a8c7… drh 604 if( n>pB->nDigit - iB ) n = pB->nDigit - iB;
e66a8c7… drh 605 rc = memcmp(pA->a+iA, pB->a+iB, n);
e66a8c7… drh 606 rc = (pA->nDigit - iA) - (pB->nDigit - iB);
17f9878… drh 607 signed char *a;
8594585… drh 608 assert( nAddFrac>=0 );
17f9878… drh 609 if( nDigit+1>SQLITE_DECIMAL_MAX_DIGIT ){ p->oom = 1; return; }
17f9878… drh 610 a = sqlite3_realloc64(p->a, nDigit+1);
17f9878… drh 611 if( a==0 ){
17f9878… drh 612 p->a = a;
17f9878… drh 613 sqlite3_int64 sumDigit;
17f9878… drh 614 sumDigit = pA->nDigit;
17f9878… drh 615 sumDigit += pB->nDigit;
17f9878… drh 616 sumDigit += 2;
17f9878… drh 617 if( sumDigit>SQLITE_DECIMAL_MAX_DIGIT ){ pA->oom = 1; return; }
17f9878… drh 618 acc = sqlite3_malloc64( sumDigit );
564007c… drh 619 ** Extract a 32-bit signed integer from argument pVal and write the
564007c… drh 620 ** results into *pResult. Return 0 on success and 1 if the value is
564007c… drh 621 ** too larger to fit in 32-bits.
564007c… drh 622 */
564007c… drh 623 static int decimalSafeInt(
564007c… drh 624 sqlite3_context *context,
564007c… drh 625 sqlite3_value *pVal,
564007c… drh 626 int *pResult
564007c… drh 627 ){
e66a8c7… drh 628 sqlite3_int64 ii = sqlite3_value_int64(pVal);
e66a8c7… drh 629 if( ii<-2147483648LL || ii>2147483647LL ){
564007c… drh 630 char *zMsg = sqlite3_mprintf(
564007c… drh 631 "value %lld is too large: range limit -2147483648..+2147483647",
e66a8c7… drh 632 ii);
564007c… drh 633 sqlite3_result_error(context, zMsg, -1);
564007c… drh 634 sqlite3_free(zMsg);
564007c… drh 635 *pResult = 0;
564007c… drh 636 return 1;
564007c… drh 637 }else{
e66a8c7… drh 638 *pResult = (int)ii;
564007c… drh 639 return 0;
564007c… drh 640 }
564007c… drh 641 }
564007c… drh 642
564007c… drh 643 /*
b8ab8b3… drh 644 int N;
b8ab8b3… drh 645 if( argc==2 ){
564007c… drh 646 if( decimalSafeInt(context, argv[1], &N) ){
564007c… drh 647 decimal_free(p);
564007c… drh 648 p = 0;
564007c… drh 649 }else if( N>0 ){
564007c… drh 650 decimal_round(p, N);
564007c… drh 651 }
b8ab8b3… drh 652 }else{
b8ab8b3… drh 653 N = 0;
b8ab8b3… drh 654 }
b8ab8b3… drh 655 decimal_result_sci(context, p, N);
e66a8c7… drh 656 if( pA && pB ){
e66a8c7… drh 657 decimal_add(pA, pB);
e66a8c7… drh 658 decimal_result(context, pA);
e66a8c7… drh 659 }
e66a8c7… drh 660 if( pA && pB ){
0201a1e… drh 661 p->a = sqlite3_malloc64(2);
564007c… drh 662 int N;
c5bdd31… drh 663 Decimal *pA;
564007c… drh 664 if( decimalSafeInt(context, argv[0], &N) ) return;
c5bdd31… drh 665 pA = decimalPow2(N);
564007c… drh 666 if( pA ){
564007c… drh 667 decimal_result_sci(context, pA, 0);
564007c… drh 668 decimal_free(pA);
564007c… drh 669 }
b8ab8b3… drh 670 { "decimal", 2, 0, decimalFunc },
b8ab8b3… drh 671 { "decimal_exp", 2, 1, decimalFunc },
c92989d… drh 672 /* Decode base64 text into a byte buffer.
c92989d… drh 673 **
c92989d… drh 674 ** Whitespace is ignored wherever it appears, including inside a group
c92989d… drh 675 ** of four base64 digits. A pad character fills one position of its
c92989d… drh 676 ** group with zero bits. Any other non-base64 character inside a group
c92989d… drh 677 ** ends the decode. Each group yields only the whole bytes encoded by
c92989d… drh 678 ** the base64 digits actually present in it.
c92989d… drh 679 */
c92989d… drh 680 int nbo, nac = 0, ndg = 0;
c92989d… drh 681 if( ncIn>=4 ){
c92989d… drh 682 /* Fast path: a complete group of four base64 digits. */
c92989d… drh 683 u8 d0 = BX_DV_PROTO(pIn[0]), d1 = BX_DV_PROTO(pIn[1]);
c92989d… drh 684 u8 d2 = BX_DV_PROTO(pIn[2]), d3 = BX_DV_PROTO(pIn[3]);
c92989d… drh 685 if( IS_BX_DIGIT(d0|d1|d2|d3) ){
c92989d… drh 686 qv = (unsigned long)d0<<18 | (unsigned long)d1<<12 | d2<<6 | d3;
c92989d… drh 687 pOut[0] = (qv>>16) & 0xff;
c92989d… drh 688 pOut[1] = (qv>>8) & 0xff;
c92989d… drh 689 pOut[2] = (qv) & 0xff;
c92989d… drh 690 pOut += 3;
c92989d… drh 691 pIn += 4;
c92989d… drh 692 ncIn -= 4;
c92989d… drh 693 continue;
c92989d… drh 694 }
c92989d… drh 695 }
c92989d… drh 696 /* Gather up to four group positions: digits and pad characters. */
c92989d… drh 697 while( nac<4 && ncIn>0 ){
c92989d… drh 698 u8 bdp = BX_DV_PROTO(*pIn);
c92989d… drh 699 if( IS_BX_DIGIT(bdp) ){
c92989d… drh 700 ++nac;
c92989d… drh 701 ++ndg;
c92989d… drh 702 }else if( IS_BX_PAD(bdp) ){
c92989d… drh 703 qv <<= 6;
c92989d… drh 704 ++nac;
c92989d… drh 705 }else if( !IS_BX_WS(bdp) ){
c92989d… drh 706 /* Dark non-digits terminate the decode. */
c92989d… drh 707 ncIn = 0;
c92989d… drh 708 ++pIn;
c92989d… drh 709 --ncIn;
c92989d… drh 710 qv <<= 6*(4-nac);
c92989d… drh 711 nbo = nboi[ndg];
0201a1e… drh 712 cBuf = sqlite3_malloc64(nc);
0201a1e… drh 713 bBuf = sqlite3_malloc64(nb);
17f9878… drh 714 int sqlite3_base64_init
17f9878… drh 715 #ifndef OMIT_BASE85_CHECKER
17f9878… drh 716 #endif
0201a1e… drh 717 cBuf = sqlite3_malloc64(nc);
0201a1e… drh 718 bBuf = sqlite3_malloc64(nb);
17f9878… drh 719 int sqlite3_base85_init
17f9878… drh 720 #ifndef OMIT_BASE85_CHECKER
17f9878… drh 721 #endif
17f9878… drh 722 #ifndef OMIT_BASE85_CHECKER
17f9878… drh 723 #endif
564007c… drh 724 /************************* Begin ext/misc/optname.c ******************/
564007c… drh 725 /*
564007c… drh 726 ** 2026-10-10
564007c… drh 727 **
564007c… drh 728 ** The author disclaims copyright to this source code. In place of
564007c… drh 729 ** a legal notice, here is a blessing:
564007c… drh 730 **
564007c… drh 731 ** May you do good and not evil.
564007c… drh 732 ** May you find forgiveness for yourself and forgive others.
564007c… drh 733 ** May you share freely, never taking more than you give.
564007c… drh 734 **
564007c… drh 735 *************************************************************************
564007c… drh 736 **
564007c… drh 737 ** The sqlite3_test_control() interface with SQLITE_TESTCTRL_OPTIMIZATIONS
564007c… drh 738 ** and SQLITE_TESTCTRL_GETOPT are used to enable and/or disable various
564007c… drh 739 ** optimizations within SQLite. Optimizations are identified by a bitmask.
564007c… drh 740 ** This file contains external code that will map symbolic names into
564007c… drh 741 ** bitmask values, and bitmask values into symbolic names.
564007c… drh 742 **
564007c… drh 743 ** This code is not part of the SQLite core because we don't want to use
564007c… drh 744 ** code space to store all the symbolic names.
564007c… drh 745 */
564007c… drh 746 /* #include "sqlite3.h" */
564007c… drh 747
564007c… drh 748 /*
564007c… drh 749 ** Convert an optimization number (as recorded in sqliteInt.h) into
564007c… drh 750 ** a mask for that optimization.
564007c… drh 751 */
564007c… drh 752 #define OPT_MASK(N) ((1ull)<<((N)-1))
564007c… drh 753
564007c… drh 754
564007c… drh 755 /*
564007c… drh 756 ** This is the mapping between bits and names.
564007c… drh 757 **
564007c… drh 758 ** Some bit values have multiple names. The preferred name always
564007c… drh 759 ** comes first.
564007c… drh 760 */
564007c… drh 761 static const struct OptName {
564007c… drh 762 sqlite3_uint64 uMask;
564007c… drh 763 const char *zName;
564007c… drh 764 } aOpt[] = {
564007c… drh 765 { OPT_MASK(1), "QueryFlattener" },
564007c… drh 766 { OPT_MASK(1), "Flatten" }, /* Alias for prior */
564007c… drh 767 { OPT_MASK(2), "WindowFunc" },
564007c… drh 768 { OPT_MASK(3), "GroupByOrder" },
564007c… drh 769 { OPT_MASK(4), "JoinMiss" },
564007c… drh 770 { OPT_MASK(5), "DistinctOpt" },
564007c… drh 771 { OPT_MASK(6), "CoverIdxScan" },
564007c… drh 772 { OPT_MASK(7), "OrderByIdxJoin" },
564007c… drh 773 { OPT_MASK(8), "Transitive" },
564007c… drh 774 { OPT_MASK(9), "OmitNoopJoin" },
564007c… drh 775 { OPT_MASK(10), "CountOfView" },
564007c… drh 776 { OPT_MASK(11), "CursorHints" },
564007c… drh 777 { OPT_MASK(12), "Stat4" },
564007c… drh 778 { OPT_MASK(13), "PushDown" },
564007c… drh 779 { OPT_MASK(14), "SimplifyJoin" },
564007c… drh 780 { OPT_MASK(15), "SkipScan" },
564007c… drh 781 { OPT_MASK(16), "PropagateConst" },
564007c… drh 782 { OPT_MASK(17), "MinMaxOpt" },
564007c… drh 783 { OPT_MASK(18), "SeekScan" },
564007c… drh 784 { OPT_MASK(19), "OmitOrderBy" },
564007c… drh 785 { OPT_MASK(20), "BloomFilter" },
c92989d… drh 786 { OPT_MASK(21), "DevTest" },
564007c… drh 787 { OPT_MASK(22), "BalancedMerge" },
564007c… drh 788 { OPT_MASK(23), "ReleaseReg" },
564007c… drh 789 { OPT_MASK(24), "FlttnUnionAll" },
564007c… drh 790 { OPT_MASK(25), "IndexedExpr" },
564007c… drh 791 { OPT_MASK(26), "Coroutines" },
564007c… drh 792 { OPT_MASK(27), "NullUnusedCols" },
564007c… drh 793 { OPT_MASK(28), "OnePass" },
564007c… drh 794 { OPT_MASK(29), "OrderBySubq" },
564007c… drh 795 { OPT_MASK(29), "OrderBySubquery" }, /* Alias for prior */
564007c… drh 796 { OPT_MASK(30), "StarQuery" },
564007c… drh 797 { OPT_MASK(31), "ExistsToJoin" },
564007c… drh 798 { OPT_MASK(32), "UnionLimit" },
c92989d… drh 799 { OPT_MASK(33), "HavingToWhere" },
564007c… drh 800 /* Special names */
564007c… drh 801 { 0xffffffffffffffffULL, "All" },
564007c… drh 802 { 0x0000000000000000ULL, "None" },
564007c… drh 803 };
564007c… drh 804
564007c… drh 805 /*
564007c… drh 806 ** Given a symbolic name, try to compute the corresponding mask.
564007c… drh 807 **
564007c… drh 808 ** The return value is:
564007c… drh 809 **
564007c… drh 810 ** SQLITE_OK Successful match
564007c… drh 811 ** SQLITE_NOTFOUND No match
564007c… drh 812 ** SQLITE_MISUSE Bad arguments
564007c… drh 813 */
564007c… drh 814 int sqlite3_optimization_mask(const char *zName, sqlite3_uint64 *pMask){
564007c… drh 815 unsigned int i;
564007c… drh 816 if( zName==0 || pMask==0 ){ return SQLITE_MISUSE; }
564007c… drh 817 for(i=0; i<sizeof(aOpt)/sizeof(aOpt[0]); i++){
564007c… drh 818 if( sqlite3_stricmp(zName, aOpt[i].zName)==0 ){
564007c… drh 819 *pMask = aOpt[i].uMask;
564007c… drh 820 return SQLITE_OK;
564007c… drh 821 }
564007c… drh 822 }
564007c… drh 823 *pMask = 0;
564007c… drh 824 return SQLITE_NOTFOUND;
564007c… drh 825 }
564007c… drh 826
564007c… drh 827 /*
564007c… drh 828 ** Given a bitmap, return the canonical symbolic name. Return 0 for
564007c… drh 829 ** a bitmap input of 0 or a bitmap value that matches nothing.
564007c… drh 830 */
564007c… drh 831 const char *sqlite3_optimization_name(sqlite3_uint64 mask){
564007c… drh 832 unsigned int i;
564007c… drh 833 for(i=0; i<sizeof(aOpt)/sizeof(aOpt[0]); i++){
564007c… drh 834 if( aOpt[i].uMask==mask ){ return aOpt[i].zName; }
564007c… drh 835 }
564007c… drh 836 return 0;
564007c… drh 837 }
564007c… drh 838
564007c… drh 839 /************************* End ext/misc/optname.c ********************/
e66a8c7… drh 840 }else if( m==0 ){
b8ab8b3… drh 841 ** Functions to convert between 64-bit integers and floats.
b8ab8b3… drh 842 **
b8ab8b3… drh 843 ** The bit patterns are copied. The numeric values are different.
b8ab8b3… drh 844 */
b8ab8b3… drh 845 static void ieee754func_from_int(
b8ab8b3… drh 846 sqlite3_context *context,
b8ab8b3… drh 847 int argc,
b8ab8b3… drh 848 sqlite3_value **argv
b8ab8b3… drh 849 ){
b8ab8b3… drh 850 UNUSED_PARAMETER(argc);
b8ab8b3… drh 851 if( sqlite3_value_type(argv[0])==SQLITE_INTEGER ){
b8ab8b3… drh 852 double r;
b8ab8b3… drh 853 sqlite3_int64 v = sqlite3_value_int64(argv[0]);
b8ab8b3… drh 854 memcpy(&r, &v, sizeof(r));
b8ab8b3… drh 855 sqlite3_result_double(context, r);
b8ab8b3… drh 856 }
b8ab8b3… drh 857 }
b8ab8b3… drh 858 static void ieee754func_to_int(
b8ab8b3… drh 859 sqlite3_context *context,
b8ab8b3… drh 860 int argc,
b8ab8b3… drh 861 sqlite3_value **argv
b8ab8b3… drh 862 ){
b8ab8b3… drh 863 UNUSED_PARAMETER(argc);
b8ab8b3… drh 864 if( sqlite3_value_type(argv[0])==SQLITE_FLOAT ){
b8ab8b3… drh 865 double r = sqlite3_value_double(argv[0]);
b8ab8b3… drh 866 sqlite3_uint64 v;
b8ab8b3… drh 867 memcpy(&v, &r, sizeof(v));
b8ab8b3… drh 868 sqlite3_result_int64(context, v);
b8ab8b3… drh 869 }
b8ab8b3… drh 870 }
b8ab8b3… drh 871
b8ab8b3… drh 872 /*
b8ab8b3… drh 873 { "ieee754_to_int", 1, 0, ieee754func_to_int },
b8ab8b3… drh 874 { "ieee754_from_int", 1, 0, ieee754func_from_int },
e66a8c7… drh 875 if( p->sIn.i>=p->sIn.mx ){
e66a8c7… drh 876 p->zErr = "unknown \\ escape";
e66a8c7… drh 877 return 0;
e66a8c7… drh 878 }
0201a1e… drh 879 pRe = sqlite3_malloc64( sizeof(*pRe) );
c92989d… drh 880 re_append(pRe, RE_OP_ANYSTAR, 0);
c92989d… drh 881 }
c92989d… drh 882
c92989d… drh 883 /* If the regex begins with "^" and has no "|" at the top level, then
c92989d… drh 884 ** the whole regex is anchored at the start of the input and the
c92989d… drh 885 ** initial ".*" is not needed. Convert it into a no-op so that
c92989d… drh 886 ** re_match() can stop as soon as the start of the input fails to
c92989d… drh 887 ** match. A "|" at the top level would have caused a FORK to be
c92989d… drh 888 ** inserted at aOp[1], so aOp[1]==RE_OP_ATSTART is sufficient. Do
c92989d… drh 889 ** not remove the initial "^" itself, as there might be jumps back
c92989d… drh 890 ** to it, as in "^+". */
c92989d… drh 891 if( pRe->aOp[1]==RE_OP_ATSTART ){
c92989d… drh 892 pRe->aOp[0] = RE_OP_GOTO;
c92989d… drh 893 pRe->aArg[0] = 1;
17f9878… drh 894 (void)argc;
055e4d0… drh 895 if( sqlite3_str_errcode(pStr)==SQLITE_NOMEM ){
055e4d0… drh 896 sqlite3_str_finish(pStr);
055e4d0… drh 897 re_free(pRe);
055e4d0… drh 898 sqlite3_result_error_nomem(context);
055e4d0… drh 899 return;
055e4d0… drh 900 }
055e4d0… drh 901 sqlite3_result_text(context, z, n-1, sqlite3_free);
c92989d… drh 902 /************************* Begin ext/misc/series.c ******************/
c92989d… drh 903 /*
c92989d… drh 904 ** 2015-08-18, 2023-04-28
c92989d… drh 905 **
c92989d… drh 906 ** The author disclaims copyright to this source code. In place of
c92989d… drh 907 ** a legal notice, here is a blessing:
c92989d… drh 908 **
c92989d… drh 909 ** May you do good and not evil.
c92989d… drh 910 ** May you find forgiveness for yourself and forgive others.
c92989d… drh 911 ** May you share freely, never taking more than you give.
c92989d… drh 912 **
c92989d… drh 913 *************************************************************************
c92989d… drh 914 **
c92989d… drh 915 ** This file demonstrates how to create a table-valued-function using
c92989d… drh 916 ** a virtual table. This demo implements the generate_series() function
c92989d… drh 917 ** which gives the same results as the eponymous function in PostgreSQL,
c92989d… drh 918 ** within the limitation that its arguments are signed 64-bit integers.
c92989d… drh 919 **
c92989d… drh 920 ** Considering its equivalents to generate_series(start,stop,step): A
c92989d… drh 921 ** value V[n] sequence is produced for integer n ascending from 0 where
c92989d… drh 922 ** ( V[n] == start + n * step && sgn(V[n] - stop) * sgn(step) >= 0 )
c92989d… drh 923 ** for each produced value (independent of production time ordering.)
c92989d… drh 924 **
c92989d… drh 925 ** All parameters must be either integer or convertable to integer.
c92989d… drh 926 ** The start parameter is required.
c92989d… drh 927 ** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
c92989d… drh 928 ** The step parameter defaults to 1 and 0 is treated as 1.
c92989d… drh 929 **
c92989d… drh 930 ** Examples:
c92989d… drh 931 **
c92989d… drh 932 ** SELECT * FROM generate_series(0,100,5);
c92989d… drh 933 **
c92989d… drh 934 ** The query above returns integers from 0 through 100 counting by steps
c92989d… drh 935 ** of 5. In other words, 0, 5, 10, 15, ..., 90, 95, 100. There are a total
c92989d… drh 936 ** of 21 rows.
c92989d… drh 937 **
c92989d… drh 938 ** SELECT * FROM generate_series(0,100);
c92989d… drh 939 **
c92989d… drh 940 ** Integers from 0 through 100 with a step size of 1. 101 rows.
c92989d… drh 941 **
c92989d… drh 942 ** SELECT * FROM generate_series(20) LIMIT 10;
c92989d… drh 943 **
c92989d… drh 944 ** Integers 20 through 29. 10 rows.
c92989d… drh 945 **
c92989d… drh 946 ** SELECT * FROM generate_series(0,-100,-5);
c92989d… drh 947 **
c92989d… drh 948 ** Integers 0 -5 -10 ... -100. 21 rows.
c92989d… drh 949 **
c92989d… drh 950 ** SELECT * FROM generate_series(0,-1);
c92989d… drh 951 **
c92989d… drh 952 ** Empty sequence.
c92989d… drh 953 **
c92989d… drh 954 ** HOW IT WORKS
c92989d… drh 955 **
c92989d… drh 956 ** The generate_series "function" is really a virtual table with the
c92989d… drh 957 ** following schema:
c92989d… drh 958 **
c92989d… drh 959 ** CREATE TABLE generate_series(
c92989d… drh 960 ** value,
c92989d… drh 961 ** start HIDDEN,
c92989d… drh 962 ** stop HIDDEN,
c92989d… drh 963 ** step HIDDEN
c92989d… drh 964 ** );
c92989d… drh 965 **
c92989d… drh 966 ** The virtual table also has a rowid which is an alias for the value.
c92989d… drh 967 **
c92989d… drh 968 ** Function arguments in queries against this virtual table are translated
c92989d… drh 969 ** into equality constraints against successive hidden columns. In other
c92989d… drh 970 ** words, the following pairs of queries are equivalent to each other:
c92989d… drh 971 **
c92989d… drh 972 ** SELECT * FROM generate_series(0,100,5);
c92989d… drh 973 ** SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
c92989d… drh 974 **
c92989d… drh 975 ** SELECT * FROM generate_series(0,100);
c92989d… drh 976 ** SELECT * FROM generate_series WHERE start=0 AND stop=100;
c92989d… drh 977 **
c92989d… drh 978 ** SELECT * FROM generate_series(20) LIMIT 10;
c92989d… drh 979 ** SELECT * FROM generate_series WHERE start=20 LIMIT 10;
c92989d… drh 980 **
c92989d… drh 981 ** The generate_series virtual table implementation leaves the xCreate method
c92989d… drh 982 ** set to NULL. This means that it is not possible to do a CREATE VIRTUAL
c92989d… drh 983 ** TABLE command with "generate_series" as the USING argument. Instead, there
c92989d… drh 984 ** is a single generate_series virtual table that is always available without
c92989d… drh 985 ** having to be created first.
c92989d… drh 986 **
c92989d… drh 987 ** The xBestIndex method looks for equality constraints against the hidden
c92989d… drh 988 ** start, stop, and step columns, and if present, it uses those constraints
c92989d… drh 989 ** to bound the sequence of generated values. If the equality constraints
c92989d… drh 990 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
c92989d… drh 991 ** xBestIndex returns a small cost when both start and stop are available,
c92989d… drh 992 ** and a very large cost if either start or stop are unavailable. This
c92989d… drh 993 ** encourages the query planner to order joins such that the bounds of the
c92989d… drh 994 ** series are well-defined.
c92989d… drh 995 **
c92989d… drh 996 ** Update on 2024-08-22:
c92989d… drh 997 ** xBestIndex now also looks for equality and inequality constraints against
c92989d… drh 998 ** the value column and uses those constraints as additional bounds against
c92989d… drh 999 ** the sequence range. Thus, a query like this:
c92989d… drh 1000 **
c92989d… drh 1001 ** SELECT value FROM generate_series($SA,$EA)
c92989d… drh 1002 ** WHERE value BETWEEN $SB AND $EB;
c92989d… drh 1003 **
c92989d… drh 1004 ** Is logically the same as:
c92989d… drh 1005 **
c92989d… drh 1006 ** SELECT value FROM generate_series(max($SA,$SB),min($EA,$EB));
c92989d… drh 1007 **
c92989d… drh 1008 ** Constraints on the value column can server as substitutes for constraints
c92989d… drh 1009 ** on the hidden start and stop columns. So, the following two queries
c92989d… drh 1010 ** are equivalent:
c92989d… drh 1011 **
c92989d… drh 1012 ** SELECT value FROM generate_series($S,$E);
c92989d… drh 1013 ** SELECT value FROM generate_series WHERE value BETWEEN $S and $E;
c92989d… drh 1014 **
c92989d… drh 1015 */
c92989d… drh 1016 /* #include "sqlite3ext.h" */
c92989d… drh 1017 SQLITE_EXTENSION_INIT1
c92989d… drh 1018 #include <assert.h>
c92989d… drh 1019 #include <string.h>
c92989d… drh 1020 #include <limits.h>
c92989d… drh 1021 #include <math.h>
c92989d… drh 1022
c92989d… drh 1023 #ifndef SQLITE_OMIT_VIRTUALTABLE
c92989d… drh 1024
c92989d… drh 1025 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
c92989d… drh 1026 ** serve as the underlying representation of a cursor that scans
c92989d… drh 1027 ** over rows of the result.
c92989d… drh 1028 **
c92989d… drh 1029 ** iOBase, iOTerm, and iOStep are the original values of the
c92989d… drh 1030 ** start=, stop=, and step= constraints on the query. These are
c92989d… drh 1031 ** the values reported by the start, stop, and step columns of the
c92989d… drh 1032 ** virtual table.
c92989d… drh 1033 **
c92989d… drh 1034 ** iBase, iTerm, iStep, and bDescp are the actual values used to generate
c92989d… drh 1035 ** the sequence. These might be different from the iOxxxx values.
c92989d… drh 1036 ** For example in
c92989d… drh 1037 **
c92989d… drh 1038 ** SELECT value FROM generate_series(1,11,2)
c92989d… drh 1039 ** WHERE value BETWEEN 4 AND 8;
c92989d… drh 1040 **
c92989d… drh 1041 ** The iOBase is 1, but the iBase is 5. iOTerm is 11 but iTerm is 7.
c92989d… drh 1042 ** Another example:
c92989d… drh 1043 **
c92989d… drh 1044 ** SELECT value FROM generate_series(1,15,3) ORDER BY value DESC;
c92989d… drh 1045 **
c92989d… drh 1046 ** The cursor initialization for the above query is:
c92989d… drh 1047 **
c92989d… drh 1048 ** iOBase = 1 iBase = 13
c92989d… drh 1049 ** iOTerm = 15 iTerm = 1
c92989d… drh 1050 ** iOStep = 3 iStep = 3 bDesc = 1
c92989d… drh 1051 **
c92989d… drh 1052 ** The actual step size is unsigned so that can have a value of
c92989d… drh 1053 ** +9223372036854775808 which is needed for querys like this:
c92989d… drh 1054 **
c92989d… drh 1055 ** SELECT value
c92989d… drh 1056 ** FROM generate_series(9223372036854775807,
c92989d… drh 1057 ** -9223372036854775808,
c92989d… drh 1058 ** -9223372036854775808)
c92989d… drh 1059 ** ORDER BY value ASC;
c92989d… drh 1060 **
c92989d… drh 1061 ** The setup for the previous query will be:
c92989d… drh 1062 **
c92989d… drh 1063 ** iOBase = 9223372036854775807 iBase = -1
c92989d… drh 1064 ** iOTerm = -9223372036854775808 iTerm = 9223372036854775807
c92989d… drh 1065 ** iOStep = -9223372036854775808 iStep = 9223372036854775808 bDesc = 0
c92989d… drh 1066 */
c92989d… drh 1067 /* typedef unsigned char u8; */
c92989d… drh 1068 typedef struct series_cursor series_cursor;
c92989d… drh 1069 struct series_cursor {
c92989d… drh 1070 sqlite3_vtab_cursor base; /* Base class - must be first */
c92989d… drh 1071 sqlite3_int64 iOBase; /* Original starting value ("start") */
c92989d… drh 1072 sqlite3_int64 iOTerm; /* Original terminal value ("stop") */
c92989d… drh 1073 sqlite3_int64 iOStep; /* Original step value */
c92989d… drh 1074 sqlite3_int64 iBase; /* Starting value to actually use */
c92989d… drh 1075 sqlite3_int64 iTerm; /* Terminal value to actually use */
c92989d… drh 1076 sqlite3_uint64 iStep; /* The step size */
c92989d… drh 1077 sqlite3_int64 iValue; /* Current value */
c92989d… drh 1078 u8 bDesc; /* iStep is really negative */
c92989d… drh 1079 u8 bDone; /* True if stepped past last element */
c92989d… drh 1080 u8 bLimit; /* There exists a limit clause */
c92989d… drh 1081 };
c92989d… drh 1082
c92989d… drh 1083 /*
c92989d… drh 1084 ** Computed the difference between two 64-bit signed integers using a
c92989d… drh 1085 ** convoluted computation designed to work around the silly restriction
c92989d… drh 1086 ** against signed integer overflow in C.
c92989d… drh 1087 */
c92989d… drh 1088 static sqlite3_uint64 span64(sqlite3_int64 a, sqlite3_int64 b){
c92989d… drh 1089 assert( a>=b );
c92989d… drh 1090 return (*(sqlite3_uint64*)&a) - (*(sqlite3_uint64*)&b);
c92989d… drh 1091 }
c92989d… drh 1092
c92989d… drh 1093 /*
c92989d… drh 1094 ** Add or substract an unsigned 64-bit integer from a signed 64-bit integer
c92989d… drh 1095 ** and return the new signed 64-bit integer.
c92989d… drh 1096 */
c92989d… drh 1097 static sqlite3_int64 add64(sqlite3_int64 a, sqlite3_uint64 b){
c92989d… drh 1098 sqlite3_uint64 x = *(sqlite3_uint64*)&a;
c92989d… drh 1099 x += b;
c92989d… drh 1100 return *(sqlite3_int64*)&x;
c92989d… drh 1101 }
c92989d… drh 1102 static sqlite3_int64 sub64(sqlite3_int64 a, sqlite3_uint64 b){
c92989d… drh 1103 sqlite3_uint64 x = *(sqlite3_uint64*)&a;
c92989d… drh 1104 x -= b;
c92989d… drh 1105 return *(sqlite3_int64*)&x;
c92989d… drh 1106 }
c92989d… drh 1107
c92989d… drh 1108 /*
c92989d… drh 1109 ** The seriesConnect() method is invoked to create a new
c92989d… drh 1110 ** series_vtab that describes the generate_series virtual table.
c92989d… drh 1111 **
c92989d… drh 1112 ** Think of this routine as the constructor for series_vtab objects.
c92989d… drh 1113 **
c92989d… drh 1114 ** All this routine needs to do is:
c92989d… drh 1115 **
c92989d… drh 1116 ** (1) Allocate the series_vtab object and initialize all fields.
c92989d… drh 1117 **
c92989d… drh 1118 ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
c92989d… drh 1119 ** result set of queries against generate_series will look like.
c92989d… drh 1120 */
c92989d… drh 1121 static int seriesConnect(
c92989d… drh 1122 sqlite3 *db,
c92989d… drh 1123 void *pUnused,
c92989d… drh 1124 int argcUnused, const char *const*argvUnused,
c92989d… drh 1125 sqlite3_vtab **ppVtab,
c92989d… drh 1126 char **pzErrUnused
c92989d… drh 1127 ){
c92989d… drh 1128 sqlite3_vtab *pNew;
c92989d… drh 1129 int rc;
c92989d… drh 1130
c92989d… drh 1131 /* Column numbers */
c92989d… drh 1132 #define SERIES_COLUMN_ROWID (-1)
c92989d… drh 1133 #define SERIES_COLUMN_VALUE 0
c92989d… drh 1134 #define SERIES_COLUMN_START 1
c92989d… drh 1135 #define SERIES_COLUMN_STOP 2
c92989d… drh 1136 #define SERIES_COLUMN_STEP 3
c92989d… drh 1137
c92989d… drh 1138 (void)pUnused;
c92989d… drh 1139 (void)argcUnused;
c92989d… drh 1140 (void)argvUnused;
c92989d… drh 1141 (void)pzErrUnused;
c92989d… drh 1142 rc = sqlite3_declare_vtab(db,
c92989d… drh 1143 "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
c92989d… drh 1144 if( rc==SQLITE_OK ){
c92989d… drh 1145 pNew = *ppVtab = sqlite3_malloc64( sizeof(*pNew) );
c92989d… drh 1146 if( pNew==0 ) return SQLITE_NOMEM;
c92989d… drh 1147 memset(pNew, 0, sizeof(*pNew));
c92989d… drh 1148 sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
c92989d… drh 1149 }
c92989d… drh 1150 return rc;
c92989d… drh 1151 }
c92989d… drh 1152
c92989d… drh 1153 /*
c92989d… drh 1154 ** This method is the destructor for series_cursor objects.
c92989d… drh 1155 */
c92989d… drh 1156 static int seriesDisconnect(sqlite3_vtab *pVtab){
c92989d… drh 1157 sqlite3_free(pVtab);
c92989d… drh 1158 return SQLITE_OK;
c92989d… drh 1159 }
c92989d… drh 1160
c92989d… drh 1161 /*
c92989d… drh 1162 ** Constructor for a new series_cursor object.
c92989d… drh 1163 */
c92989d… drh 1164 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
c92989d… drh 1165 series_cursor *pCur;
c92989d… drh 1166 (void)pUnused;
c92989d… drh 1167 pCur = sqlite3_malloc64( sizeof(*pCur) );
c92989d… drh 1168 if( pCur==0 ) return SQLITE_NOMEM;
c92989d… drh 1169 memset(pCur, 0, sizeof(*pCur));
c92989d… drh 1170 *ppCursor = &pCur->base;
c92989d… drh 1171 return SQLITE_OK;
c92989d… drh 1172 }
c92989d… drh 1173
c92989d… drh 1174 /*
c92989d… drh 1175 ** Destructor for a series_cursor.
c92989d… drh 1176 */
c92989d… drh 1177 static int seriesClose(sqlite3_vtab_cursor *cur){
c92989d… drh 1178 sqlite3_free(cur);
c92989d… drh 1179 return SQLITE_OK;
c92989d… drh 1180 }
c92989d… drh 1181
c92989d… drh 1182
c92989d… drh 1183 /*
c92989d… drh 1184 ** Advance a series_cursor to its next row of output.
c92989d… drh 1185 */
c92989d… drh 1186 static int seriesNext(sqlite3_vtab_cursor *cur){
c92989d… drh 1187 series_cursor *pCur = (series_cursor*)cur;
c92989d… drh 1188 if( pCur->iValue==pCur->iTerm ){
c92989d… drh 1189 pCur->bDone = 1;
c92989d… drh 1190 }else if( pCur->bDesc ){
c92989d… drh 1191 pCur->iValue = sub64(pCur->iValue, pCur->iStep);
c92989d… drh 1192 assert( pCur->iValue>=pCur->iTerm || pCur->bLimit );
c92989d… drh 1193 }else{
c92989d… drh 1194 pCur->iValue = add64(pCur->iValue, pCur->iStep);
c92989d… drh 1195 assert( pCur->iValue<=pCur->iTerm || pCur->bLimit );
c92989d… drh 1196 }
c92989d… drh 1197 return SQLITE_OK;
c92989d… drh 1198 }
c92989d… drh 1199
c92989d… drh 1200 /*
c92989d… drh 1201 ** Return values of columns for the row at which the series_cursor
c92989d… drh 1202 ** is currently pointing.
c92989d… drh 1203 */
c92989d… drh 1204 static int seriesColumn(
c92989d… drh 1205 sqlite3_vtab_cursor *cur, /* The cursor */
c92989d… drh 1206 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
c92989d… drh 1207 int i /* Which column to return */
c92989d… drh 1208 ){
c92989d… drh 1209 series_cursor *pCur = (series_cursor*)cur;
c92989d… drh 1210 sqlite3_int64 x = 0;
c92989d… drh 1211 switch( i ){
c92989d… drh 1212 case SERIES_COLUMN_START: x = pCur->iOBase; break;
c92989d… drh 1213 case SERIES_COLUMN_STOP: x = pCur->iOTerm; break;
c92989d… drh 1214 case SERIES_COLUMN_STEP: x = pCur->iOStep; break;
c92989d… drh 1215 default: x = pCur->iValue; break;
c92989d… drh 1216 }
c92989d… drh 1217 sqlite3_result_int64(ctx, x);
c92989d… drh 1218 return SQLITE_OK;
c92989d… drh 1219 }
c92989d… drh 1220
c92989d… drh 1221 #ifndef LARGEST_UINT64
c92989d… drh 1222 #define LARGEST_INT64 ((sqlite3_int64)0x7fffffffffffffffLL)
c92989d… drh 1223 #define LARGEST_UINT64 ((sqlite3_uint64)0xffffffffffffffffULL)
c92989d… drh 1224 #define SMALLEST_INT64 ((sqlite3_int64)0x8000000000000000LL)
c92989d… drh 1225 #endif
c92989d… drh 1226
c92989d… drh 1227 /*
c92989d… drh 1228 ** The rowid is the same as the value.
c92989d… drh 1229 */
c92989d… drh 1230 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
c92989d… drh 1231 series_cursor *pCur = (series_cursor*)cur;
c92989d… drh 1232 *pRowid = pCur->iValue;
c92989d… drh 1233 return SQLITE_OK;
c92989d… drh 1234 }
c92989d… drh 1235
c92989d… drh 1236 /*
c92989d… drh 1237 ** Return TRUE if the cursor has been moved off of the last
c92989d… drh 1238 ** row of output.
c92989d… drh 1239 */
c92989d… drh 1240 static int seriesEof(sqlite3_vtab_cursor *cur){
c92989d… drh 1241 series_cursor *pCur = (series_cursor*)cur;
c92989d… drh 1242 return pCur->bDone;
c92989d… drh 1243 }
c92989d… drh 1244
c92989d… drh 1245 /* True to cause run-time checking of the start=, stop=, and/or step=
c92989d… drh 1246 ** parameters. The only reason to do this is for testing the
c92989d… drh 1247 ** constraint checking logic for virtual tables in the SQLite core.
c92989d… drh 1248 */
c92989d… drh 1249 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
c92989d… drh 1250 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
c92989d… drh 1251 #endif
c92989d… drh 1252
c92989d… drh 1253 /*
c92989d… drh 1254 ** Return the number of steps between pCur->iBase and pCur->iTerm if
c92989d… drh 1255 ** the step width is pCur->iStep.
c92989d… drh 1256 */
c92989d… drh 1257 static sqlite3_uint64 seriesSteps(series_cursor *pCur){
c92989d… drh 1258 if( pCur->bDesc ){
c92989d… drh 1259 assert( pCur->iBase >= pCur->iTerm );
c92989d… drh 1260 return span64(pCur->iBase, pCur->iTerm)/pCur->iStep;
c92989d… drh 1261 }else{
c92989d… drh 1262 assert( pCur->iBase <= pCur->iTerm );
c92989d… drh 1263 return span64(pCur->iTerm, pCur->iBase)/pCur->iStep;
c92989d… drh 1264 }
c92989d… drh 1265 }
c92989d… drh 1266
c92989d… drh 1267 #if defined(SQLITE_ENABLE_MATH_FUNCTIONS) || defined(_WIN32)
c92989d… drh 1268 /*
c92989d… drh 1269 ** Case 1 (the most common case):
c92989d… drh 1270 ** The standard math library is available so use ceil() and floor() from there.
c92989d… drh 1271 */
c92989d… drh 1272 static double seriesCeil(double r){ return ceil(r); }
c92989d… drh 1273 static double seriesFloor(double r){ return floor(r); }
c92989d… drh 1274 #elif defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
c92989d… drh 1275 /*
c92989d… drh 1276 ** Case 2 (2nd most common): Use GCC/Clang builtins
c92989d… drh 1277 */
c92989d… drh 1278 static double seriesCeil(double r){ return __builtin_ceil(r); }
c92989d… drh 1279 static double seriesFloor(double r){ return __builtin_floor(r); }
c92989d… drh 1280 #else
c92989d… drh 1281 /*
c92989d… drh 1282 ** Case 3 (rarely happens): Use home-grown ceil() and floor() routines.
c92989d… drh 1283 */
c92989d… drh 1284 static double seriesCeil(double r){
c92989d… drh 1285 sqlite3_int64 x;
c92989d… drh 1286 if( r!=r ) return r;
c92989d… drh 1287 if( r<=(-4503599627370496.0) ) return r;
c92989d… drh 1288 if( r>=(+4503599627370496.0) ) return r;
c92989d… drh 1289 x = (sqlite3_int64)r;
c92989d… drh 1290 if( r==(double)x ) return r;
c92989d… drh 1291 if( r>(double)x ) x++;
c92989d… drh 1292 return (double)x;
c92989d… drh 1293 }
c92989d… drh 1294 static double seriesFloor(double r){
c92989d… drh 1295 sqlite3_int64 x;
c92989d… drh 1296 if( r!=r ) return r;
c92989d… drh 1297 if( r<=(-4503599627370496.0) ) return r;
c92989d… drh 1298 if( r>=(+4503599627370496.0) ) return r;
c92989d… drh 1299 x = (sqlite3_int64)r;
c92989d… drh 1300 if( r==(double)x ) return r;
c92989d… drh 1301 if( r<(double)x ) x--;
c92989d… drh 1302 return (double)x;
c92989d… drh 1303 }
c92989d… drh 1304 #endif
c92989d… drh 1305
c92989d… drh 1306 /* Convert a floating point value to its closest integer. Do so in
c92989d… drh 1307 ** a way that avoids 'outside the range of representable values' warnings
c92989d… drh 1308 ** from UBSAN.
c92989d… drh 1309 */
c92989d… drh 1310 static sqlite3_int64 seriesRealToI64(double r){
c92989d… drh 1311 if( r<-9223372036854774784.0 ) return SMALLEST_INT64;
c92989d… drh 1312 if( r>+9223372036854774784.0 ) return LARGEST_INT64;
c92989d… drh 1313 return (sqlite3_int64)r;
c92989d… drh 1314 }
c92989d… drh 1315
c92989d… drh 1316 /* Return true if the type of the value is TEXT or BLOB.
c92989d… drh 1317 */
c92989d… drh 1318 static int seriesIsTextOrBlob(sqlite3_value *pVal){
c92989d… drh 1319 int eType = sqlite3_value_type(pVal);
c92989d… drh 1320 return eType==SQLITE_TEXT || eType==SQLITE_BLOB;
c92989d… drh 1321 }
c92989d… drh 1322
c92989d… drh 1323 /*
c92989d… drh 1324 ** This method is called to "rewind" the series_cursor object back
c92989d… drh 1325 ** to the first row of output. This method is always called at least
c92989d… drh 1326 ** once prior to any call to seriesColumn() or seriesRowid() or
c92989d… drh 1327 ** seriesEof().
c92989d… drh 1328 **
c92989d… drh 1329 ** The query plan selected by seriesBestIndex is passed in the idxNum
c92989d… drh 1330 ** parameter. (idxStr is not used in this implementation.) idxNum
c92989d… drh 1331 ** is a bitmask showing which constraints are available:
c92989d… drh 1332 **
c92989d… drh 1333 ** 0x0001: start=VALUE
c92989d… drh 1334 ** 0x0002: stop=VALUE
c92989d… drh 1335 ** 0x0004: step=VALUE
c92989d… drh 1336 ** 0x0008: descending order
c92989d… drh 1337 ** 0x0010: ascending order
c92989d… drh 1338 ** 0x0020: LIMIT VALUE
c92989d… drh 1339 ** 0x0040: OFFSET VALUE
c92989d… drh 1340 ** 0x0080: value=VALUE
c92989d… drh 1341 ** 0x0100: value>=VALUE
c92989d… drh 1342 ** 0x0200: value>VALUE
c92989d… drh 1343 ** 0x1000: value<=VALUE
c92989d… drh 1344 ** 0x2000: value<VALUE
c92989d… drh 1345 **
c92989d… drh 1346 ** This routine should initialize the cursor and position it so that it
c92989d… drh 1347 ** is pointing at the first row, or pointing off the end of the table
c92989d… drh 1348 ** (so that seriesEof() will return true) if the table is empty.
c92989d… drh 1349 */
c92989d… drh 1350 static int seriesFilter(
c92989d… drh 1351 sqlite3_vtab_cursor *pVtabCursor,
c92989d… drh 1352 int idxNum, const char *idxStrUnused,
c92989d… drh 1353 int argc, sqlite3_value **argv
c92989d… drh 1354 ){
c92989d… drh 1355 series_cursor *pCur = (series_cursor *)pVtabCursor;
c92989d… drh 1356 int iArg = 0; /* Arguments used so far */
c92989d… drh 1357 int i; /* Loop counter */
c92989d… drh 1358 sqlite3_int64 iMin = SMALLEST_INT64; /* Smallest allowed output value */
c92989d… drh 1359 sqlite3_int64 iMax = LARGEST_INT64; /* Largest allowed output value */
c92989d… drh 1360 sqlite3_int64 iLimit = 0; /* if >0, the value of the LIMIT */
c92989d… drh 1361 sqlite3_int64 iOffset = 0; /* if >0, the value of the OFFSET */
c92989d… drh 1362
c92989d… drh 1363 (void)idxStrUnused;
c92989d… drh 1364
c92989d… drh 1365 /* If any constraints have a NULL value, then return no rows.
c92989d… drh 1366 ** See ticket https://sqlite.org/src/info/fac496b61722daf2
c92989d… drh 1367 */
c92989d… drh 1368 for(i=0; i<argc; i++){
c92989d… drh 1369 if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
c92989d… drh 1370 goto series_no_rows;
c92989d… drh 1371 }
c92989d… drh 1372 }
c92989d… drh 1373
c92989d… drh 1374 /* Capture the three HIDDEN parameters to the virtual table and insert
c92989d… drh 1375 ** default values for any parameters that are omitted.
c92989d… drh 1376 */
c92989d… drh 1377 if( idxNum & 0x01 ){
c92989d… drh 1378 pCur->iOBase = sqlite3_value_int64(argv[iArg++]);
c92989d… drh 1379 }else{
c92989d… drh 1380 pCur->iOBase = 0;
c92989d… drh 1381 }
c92989d… drh 1382 if( idxNum & 0x02 ){
c92989d… drh 1383 pCur->iOTerm = sqlite3_value_int64(argv[iArg++]);
c92989d… drh 1384 }else{
c92989d… drh 1385 pCur->iOTerm = 0xffffffff;
c92989d… drh 1386 }
c92989d… drh 1387 if( idxNum & 0x04 ){
c92989d… drh 1388 pCur->iOStep = sqlite3_value_int64(argv[iArg++]);
c92989d… drh 1389 if( pCur->iOStep==0 ) pCur->iOStep = 1;
c92989d… drh 1390 }else{
c92989d… drh 1391 pCur->iOStep = 1;
c92989d… drh 1392 }
c92989d… drh 1393
c92989d… drh 1394 /* If there are constraints on the value column but there are
c92989d… drh 1395 ** no constraints on the start, stop, and step columns, then
c92989d… drh 1396 ** initialize the default range to be the entire range of 64-bit signed
c92989d… drh 1397 ** integers. This range will contracted by the value column constraints
c92989d… drh 1398 ** further below.
c92989d… drh 1399 */
c92989d… drh 1400 if( (idxNum & 0x05)==0 && (idxNum & 0x0380)!=0 ){
c92989d… drh 1401 pCur->iOBase = SMALLEST_INT64;
c92989d… drh 1402 }
c92989d… drh 1403 if( (idxNum & 0x06)==0 && (idxNum & 0x3080)!=0 ){
c92989d… drh 1404 pCur->iOTerm = LARGEST_INT64;
c92989d… drh 1405 }
c92989d… drh 1406 pCur->iBase = pCur->iOBase;
c92989d… drh 1407 pCur->iTerm = pCur->iOTerm;
c92989d… drh 1408 if( pCur->iOStep>0 ){
c92989d… drh 1409 pCur->iStep = pCur->iOStep;
c92989d… drh 1410 }else if( pCur->iOStep>SMALLEST_INT64 ){
c92989d… drh 1411 pCur->iStep = -pCur->iOStep;
c92989d… drh 1412 }else{
c92989d… drh 1413 pCur->iStep = LARGEST_INT64;
c92989d… drh 1414 pCur->iStep++;
c92989d… drh 1415 }
c92989d… drh 1416 pCur->bDesc = pCur->iOStep<0;
c92989d… drh 1417 if( pCur->bDesc==0 && pCur->iBase>pCur->iTerm ){
c92989d… drh 1418 goto series_no_rows;
c92989d… drh 1419 }
c92989d… drh 1420 if( pCur->bDesc!=0 && pCur->iBase<pCur->iTerm ){
c92989d… drh 1421 goto series_no_rows;
c92989d… drh 1422 }
c92989d… drh 1423
c92989d… drh 1424 /* Extract the LIMIT and OFFSET values, but do not apply them yet.
c92989d… drh 1425 ** The range must first be constrained by the limits on value.
c92989d… drh 1426 */
c92989d… drh 1427 if( idxNum & 0x20 ){
c92989d… drh 1428 iLimit = sqlite3_value_int64(argv[iArg++]);
c92989d… drh 1429 if( idxNum & 0x40 ){
c92989d… drh 1430 iOffset = sqlite3_value_int64(argv[iArg++]);
c92989d… drh 1431 }
c92989d… drh 1432 if( iLimit>0 ) pCur->bLimit = 1;
c92989d… drh 1433 }
c92989d… drh 1434
c92989d… drh 1435 /* Narrow the range of iMin and iMax (the minimum and maximum outputs)
c92989d… drh 1436 ** based on equality and inequality constraints on the "value" column.
c92989d… drh 1437 **
c92989d… drh 1438 ** The "value" column has no affinity, so a TEXT or BLOB operand X is
c92989d… drh 1439 ** not converted into a number. Every INTEGER is less than any TEXT
c92989d… drh 1440 ** or BLOB, so "value=X", "value>X" and "value>=X" are never true and
c92989d… drh 1441 ** "value<X" and "value<=X" are always true. The type must be checked
c92989d… drh 1442 ** before sqlite3_value_numeric_type(), which would convert a TEXT
c92989d… drh 1443 ** value such as '3' into a number.
c92989d… drh 1444 */
c92989d… drh 1445 if( idxNum & 0x3380 ){
c92989d… drh 1446 if( idxNum & 0x0080 ){ /* value=X */
c92989d… drh 1447 if( seriesIsTextOrBlob(argv[iArg]) ){
c92989d… drh 1448 goto series_no_rows;
c92989d… drh 1449 }else if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
c92989d… drh 1450 double r = sqlite3_value_double(argv[iArg++]);
c92989d… drh 1451 if( r==seriesCeil(r)
c92989d… drh 1452 && r>=(double)SMALLEST_INT64
c92989d… drh 1453 && r<=(double)LARGEST_INT64
c92989d… drh 1454 ){
c92989d… drh 1455 iMin = iMax = seriesRealToI64(r);
c92989d… drh 1456 }else{
c92989d… drh 1457 goto series_no_rows;
c92989d… drh 1458 }
c92989d… drh 1459 }else{
c92989d… drh 1460 iMin = iMax = sqlite3_value_int64(argv[iArg++]);
c92989d… drh 1461 }
c92989d… drh 1462 }else{
c92989d… drh 1463 if( idxNum & 0x0300 ){ /* value>X (0x200) or value>=X (0x100) */
c92989d… drh 1464 if( seriesIsTextOrBlob(argv[iArg]) ){
c92989d… drh 1465 goto series_no_rows;
c92989d… drh 1466 }else if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
c92989d… drh 1467 double r = sqlite3_value_double(argv[iArg++]);
c92989d… drh 1468 if( r<=(double)SMALLEST_INT64 ){
c92989d… drh 1469 iMin = SMALLEST_INT64;
c92989d… drh 1470 }else if( r>(double)LARGEST_INT64 ){
c92989d… drh 1471 goto series_no_rows;
c92989d… drh 1472 }else{
c92989d… drh 1473 iMin = seriesRealToI64(seriesCeil(r));
c92989d… drh 1474 if( (idxNum & 0x0200)!=0 && r==seriesCeil(r) ){
c92989d… drh 1475 if( iMin==LARGEST_INT64 ) goto series_no_rows;
c92989d… drh 1476 iMin++;
c92989d… drh 1477 }
c92989d… drh 1478 }
c92989d… drh 1479 }else{
c92989d… drh 1480 iMin = sqlite3_value_int64(argv[iArg++]);
c92989d… drh 1481 if( (idxNum & 0x0200)!=0 ){
c92989d… drh 1482 if( iMin==LARGEST_INT64 ){
c92989d… drh 1483 goto series_no_rows;
c92989d… drh 1484 }else{
c92989d… drh 1485 iMin++;
c92989d… drh 1486 }
c92989d… drh 1487 }
c92989d… drh 1488 }
c92989d… drh 1489 }
c92989d… drh 1490 if( idxNum & 0x3000 ){ /* value<X (0x2000) or value<=X (0x1000) */
c92989d… drh 1491 if( seriesIsTextOrBlob(argv[iArg]) ){
c92989d… drh 1492 iArg++; /* No upper bound */
c92989d… drh 1493 }else if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
c92989d… drh 1494 double r = sqlite3_value_double(argv[iArg++]);
c92989d… drh 1495 if( r>=(double)LARGEST_INT64 ){
c92989d… drh 1496 iMax = LARGEST_INT64;
c92989d… drh 1497 }else if( r<=(double)SMALLEST_INT64 ){
c92989d… drh 1498 goto series_no_rows;
c92989d… drh 1499 }else{
c92989d… drh 1500 iMax = seriesRealToI64(seriesFloor(r));
c92989d… drh 1501 if( (idxNum & 0x2000)!=0 && r==seriesFloor(r) ){
c92989d… drh 1502 if( iMax==SMALLEST_INT64 ) goto series_no_rows;
c92989d… drh 1503 iMax--;
c92989d… drh 1504 }
c92989d… drh 1505 }
c92989d… drh 1506 }else{
c92989d… drh 1507 iMax = sqlite3_value_int64(argv[iArg++]);
c92989d… drh 1508 if( idxNum & 0x2000 ){
c92989d… drh 1509 if( iMax==SMALLEST_INT64 ){
c92989d… drh 1510 goto series_no_rows;
c92989d… drh 1511 }else{
c92989d… drh 1512 iMax--;
c92989d… drh 1513 }
c92989d… drh 1514 }
c92989d… drh 1515 }
c92989d… drh 1516 }
c92989d… drh 1517 if( iMin>iMax ){
c92989d… drh 1518 goto series_no_rows;
c92989d… drh 1519 }
c92989d… drh 1520 }
c92989d… drh 1521
c92989d… drh 1522 /* Try to reduce the range of values to be generated based on
c92989d… drh 1523 ** constraints on the "value" column.
c92989d… drh 1524 */
c92989d… drh 1525 if( pCur->bDesc==0 ){
c92989d… drh 1526 if( pCur->iBase<iMin ){
c92989d… drh 1527 sqlite3_uint64 span = span64(iMin,pCur->iBase);
c92989d… drh 1528 pCur->iBase = add64(pCur->iBase, (span/pCur->iStep)*pCur->iStep);
c92989d… drh 1529 if( pCur->iBase<iMin ){
c92989d… drh 1530 if( pCur->iBase > sub64(LARGEST_INT64, pCur->iStep) ){
c92989d… drh 1531 goto series_no_rows;
c92989d… drh 1532 }
c92989d… drh 1533 pCur->iBase = add64(pCur->iBase, pCur->iStep);
c92989d… drh 1534 }
c92989d… drh 1535 }
c92989d… drh 1536 if( pCur->iTerm>iMax ){
c92989d… drh 1537 pCur->iTerm = iMax;
c92989d… drh 1538 }
c92989d… drh 1539 }else{
c92989d… drh 1540 if( pCur->iBase>iMax ){
c92989d… drh 1541 sqlite3_uint64 span = span64(pCur->iBase,iMax);
c92989d… drh 1542 pCur->iBase = sub64(pCur->iBase, (span/pCur->iStep)*pCur->iStep);
c92989d… drh 1543 if( pCur->iBase>iMax ){
c92989d… drh 1544 if( pCur->iBase < add64(SMALLEST_INT64, pCur->iStep) ){
c92989d… drh 1545 goto series_no_rows;
c92989d… drh 1546 }
c92989d… drh 1547 pCur->iBase = sub64(pCur->iBase, pCur->iStep);
c92989d… drh 1548 }
c92989d… drh 1549 }
c92989d… drh 1550 if( pCur->iTerm<iMin ){
c92989d… drh 1551 pCur->iTerm = iMin;
c92989d… drh 1552 }
c92989d… drh 1553 }
c92989d… drh 1554 }
c92989d… drh 1555
c92989d… drh 1556 /* Adjust iTerm so that it is exactly the last value of the series.
c92989d… drh 1557 */
c92989d… drh 1558 if( pCur->bDesc==0 ){
c92989d… drh 1559 if( pCur->iBase>pCur->iTerm ){
c92989d… drh 1560 goto series_no_rows;
c92989d… drh 1561 }
c92989d… drh 1562 pCur->iTerm = sub64(pCur->iTerm,
c92989d… drh 1563 span64(pCur->iTerm,pCur->iBase) % pCur->iStep);
c92989d… drh 1564 }else{
c92989d… drh 1565 if( pCur->iBase<pCur->iTerm ){
c92989d… drh 1566 goto series_no_rows;
c92989d… drh 1567 }
c92989d… drh 1568 pCur->iTerm = add64(pCur->iTerm,
c92989d… drh 1569 span64(pCur->iBase,pCur->iTerm) % pCur->iStep);
c92989d… drh 1570 }
c92989d… drh 1571
c92989d… drh 1572 /* Transform the series generator to output values in the requested
c92989d… drh 1573 ** order.
c92989d… drh 1574 */
c92989d… drh 1575 if( ((idxNum & 0x0008)!=0 && pCur->bDesc==0)
c92989d… drh 1576 || ((idxNum & 0x0010)!=0 && pCur->bDesc!=0)
c92989d… drh 1577 ){
c92989d… drh 1578 sqlite3_int64 tmp = pCur->iBase;
c92989d… drh 1579 pCur->iBase = pCur->iTerm;
c92989d… drh 1580 pCur->iTerm = tmp;
c92989d… drh 1581 pCur->bDesc = !pCur->bDesc;
c92989d… drh 1582 }
c92989d… drh 1583
c92989d… drh 1584 /* Apply LIMIT and OFFSET constraints, if any */
c92989d… drh 1585 assert( pCur->iStep!=0 );
c92989d… drh 1586 if( idxNum & 0x20 ){
c92989d… drh 1587 if( iOffset>0 ){
c92989d… drh 1588 if( seriesSteps(pCur) < (sqlite3_uint64)iOffset ){
c92989d… drh 1589 goto series_no_rows;
c92989d… drh 1590 }else if( pCur->bDesc ){
c92989d… drh 1591 pCur->iBase = sub64(pCur->iBase, pCur->iStep*iOffset);
c92989d… drh 1592 }else{
c92989d… drh 1593 pCur->iBase = add64(pCur->iBase, pCur->iStep*iOffset);
c92989d… drh 1594 }
c92989d… drh 1595 }
c92989d… drh 1596 if( iLimit>=0 && seriesSteps(pCur) > (sqlite3_uint64)iLimit ){
c92989d… drh 1597 pCur->iTerm = add64(pCur->iBase, (iLimit - 1)*pCur->iStep);
c92989d… drh 1598 }
c92989d… drh 1599 }
c92989d… drh 1600 pCur->iValue = pCur->iBase;
c92989d… drh 1601 pCur->bDone = 0;
c92989d… drh 1602 return SQLITE_OK;
c92989d… drh 1603
c92989d… drh 1604 series_no_rows:
c92989d… drh 1605 pCur->iBase = 0;
c92989d… drh 1606 pCur->iTerm = 0;
c92989d… drh 1607 pCur->iStep = 1;
c92989d… drh 1608 pCur->bDesc = 0;
c92989d… drh 1609 pCur->bDone = 1;
c92989d… drh 1610 return SQLITE_OK;
c92989d… drh 1611 }
c92989d… drh 1612
c92989d… drh 1613 /*
c92989d… drh 1614 ** SQLite will invoke this method one or more times while planning a query
c92989d… drh 1615 ** that uses the generate_series virtual table. This routine needs to create
c92989d… drh 1616 ** a query plan for each invocation and compute an estimated cost for that
c92989d… drh 1617 ** plan.
c92989d… drh 1618 **
c92989d… drh 1619 ** In this implementation idxNum is used to represent the
c92989d… drh 1620 ** query plan. idxStr is unused.
c92989d… drh 1621 **
c92989d… drh 1622 ** The query plan is represented by bits in idxNum:
c92989d… drh 1623 **
c92989d… drh 1624 ** 0x0001 start = $num
c92989d… drh 1625 ** 0x0002 stop = $num
c92989d… drh 1626 ** 0x0004 step = $num
c92989d… drh 1627 ** 0x0008 output is in descending order
c92989d… drh 1628 ** 0x0010 output is in ascending order
c92989d… drh 1629 ** 0x0020 LIMIT $num
c92989d… drh 1630 ** 0x0040 OFFSET $num
c92989d… drh 1631 ** 0x0080 value = $num
c92989d… drh 1632 ** 0x0100 value >= $num
c92989d… drh 1633 ** 0x0200 value > $num
c92989d… drh 1634 ** 0x1000 value <= $num
c92989d… drh 1635 ** 0x2000 value < $num
c92989d… drh 1636 **
c92989d… drh 1637 ** Only one of 0x0100 or 0x0200 will be returned. Similarly, only
c92989d… drh 1638 ** one of 0x1000 or 0x2000 will be returned. If the 0x0080 is set, then
c92989d… drh 1639 ** none of the 0xff00 bits will be set.
c92989d… drh 1640 **
c92989d… drh 1641 ** The order of parameters passed to xFilter is as follows:
c92989d… drh 1642 **
c92989d… drh 1643 ** * The argument to start= if bit 0x0001 is in the idxNum mask
c92989d… drh 1644 ** * The argument to stop= if bit 0x0002 is in the idxNum mask
c92989d… drh 1645 ** * The argument to step= if bit 0x0004 is in the idxNum mask
c92989d… drh 1646 ** * The argument to LIMIT if bit 0x0020 is in the idxNum mask
c92989d… drh 1647 ** * The argument to OFFSET if bit 0x0040 is in the idxNum mask
c92989d… drh 1648 ** * The argument to value=, or value>= or value> if any of
c92989d… drh 1649 ** bits 0x0380 are in the idxNum mask
c92989d… drh 1650 ** * The argument to value<= or value< if either of bits 0x3000
c92989d… drh 1651 ** are in the mask
c92989d… drh 1652 **
c92989d… drh 1653 */
c92989d… drh 1654 static int seriesBestIndex(
c92989d… drh 1655 sqlite3_vtab *pVTab,
c92989d… drh 1656 sqlite3_index_info *pIdxInfo
c92989d… drh 1657 ){
c92989d… drh 1658 int i, j; /* Loop over constraints */
c92989d… drh 1659 int idxNum = 0; /* The query plan bitmask */
c92989d… drh 1660 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
c92989d… drh 1661 int bStartSeen = 0; /* EQ constraint seen on the START column */
c92989d… drh 1662 #endif
c92989d… drh 1663 int unusableMask = 0; /* Mask of unusable constraints */
c92989d… drh 1664 int nArg = 0; /* Number of arguments that seriesFilter() expects */
c92989d… drh 1665 int aIdx[7]; /* Constraints on start, stop, step, LIMIT, OFFSET,
c92989d… drh 1666 ** and value. aIdx[5] covers value=, value>=, and
c92989d… drh 1667 ** value>, aIdx[6] covers value<= and value< */
c92989d… drh 1668 const struct sqlite3_index_constraint *pConstraint;
c92989d… drh 1669
c92989d… drh 1670 /* This implementation assumes that the start, stop, and step columns
c92989d… drh 1671 ** are the last three columns in the virtual table. */
c92989d… drh 1672 assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
c92989d… drh 1673 assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
c92989d… drh 1674
c92989d… drh 1675 aIdx[0] = aIdx[1] = aIdx[2] = aIdx[3] = aIdx[4] = aIdx[5] = aIdx[6] = -1;
c92989d… drh 1676 pConstraint = pIdxInfo->aConstraint;
c92989d… drh 1677 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
c92989d… drh 1678 int iCol; /* 0 for start, 1 for stop, 2 for step */
c92989d… drh 1679 int iMask; /* bitmask for those column */
c92989d… drh 1680 int op = pConstraint->op;
c92989d… drh 1681 if( op>=SQLITE_INDEX_CONSTRAINT_LIMIT
c92989d… drh 1682 && op<=SQLITE_INDEX_CONSTRAINT_OFFSET
c92989d… drh 1683 ){
c92989d… drh 1684 if( pConstraint->usable==0 ){
c92989d… drh 1685 /* do nothing */
c92989d… drh 1686 }else if( op==SQLITE_INDEX_CONSTRAINT_LIMIT ){
c92989d… drh 1687 aIdx[3] = i;
c92989d… drh 1688 idxNum |= 0x20;
c92989d… drh 1689 }else{
c92989d… drh 1690 assert( op==SQLITE_INDEX_CONSTRAINT_OFFSET );
c92989d… drh 1691 aIdx[4] = i;
c92989d… drh 1692 idxNum |= 0x40;
c92989d… drh 1693 }
c92989d… drh 1694 continue;
c92989d… drh 1695 }
c92989d… drh 1696 if( pConstraint->iColumn<SERIES_COLUMN_START ){
c92989d… drh 1697 if( (pConstraint->iColumn==SERIES_COLUMN_VALUE ||
c92989d… drh 1698 pConstraint->iColumn==SERIES_COLUMN_ROWID)
c92989d… drh 1699 && pConstraint->usable
c92989d… drh 1700 ){
c92989d… drh 1701 switch( op ){
c92989d… drh 1702 case SQLITE_INDEX_CONSTRAINT_EQ:
c92989d… drh 1703 case SQLITE_INDEX_CONSTRAINT_IS: {
c92989d… drh 1704 idxNum |= 0x0080;
c92989d… drh 1705 idxNum &= ~0x3300;
c92989d… drh 1706 aIdx[5] = i;
c92989d… drh 1707 aIdx[6] = -1;
c92989d… drh 1708 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
c92989d… drh 1709 bStartSeen = 1;
c92989d… drh 1710 #endif
c92989d… drh 1711 break;
c92989d… drh 1712 }
c92989d… drh 1713 case SQLITE_INDEX_CONSTRAINT_GE: {
c92989d… drh 1714 if( idxNum & 0x0080 ) break;
c92989d… drh 1715 idxNum |= 0x0100;
c92989d… drh 1716 idxNum &= ~0x0200;
c92989d… drh 1717 aIdx[5] = i;
c92989d… drh 1718 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
c92989d… drh 1719 bStartSeen = 1;
c92989d… drh 1720 #endif
c92989d… drh 1721 break;
c92989d… drh 1722 }
c92989d… drh 1723 case SQLITE_INDEX_CONSTRAINT_GT: {
c92989d… drh 1724 if( idxNum & 0x0080 ) break;
c92989d… drh 1725 idxNum |= 0x0200;
c92989d… drh 1726 idxNum &= ~0x0100;
c92989d… drh 1727 aIdx[5] = i;
c92989d… drh 1728 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
c92989d… drh 1729 bStartSeen = 1;
c92989d… drh 1730 #endif
c92989d… drh 1731 break;
c92989d… drh 1732 }
c92989d… drh 1733 case SQLITE_INDEX_CONSTRAINT_LE: {
c92989d… drh 1734 if( idxNum & 0x0080 ) break;
c92989d… drh 1735 idxNum |= 0x1000;
c92989d… drh 1736 idxNum &= ~0x2000;
c92989d… drh 1737 aIdx[6] = i;
c92989d… drh 1738 break;
c92989d… drh 1739 }
c92989d… drh 1740 case SQLITE_INDEX_CONSTRAINT_LT: {
c92989d… drh 1741 if( idxNum & 0x0080 ) break;
c92989d… drh 1742 idxNum |= 0x2000;
c92989d… drh 1743 idxNum &= ~0x1000;
c92989d… drh 1744 aIdx[6] = i;
c92989d… drh 1745 break;
c92989d… drh 1746 }
c92989d… drh 1747 }
c92989d… drh 1748 }
c92989d… drh 1749 continue;
c92989d… drh 1750 }
c92989d… drh 1751 iCol = pConstraint->iColumn - SERIES_COLUMN_START;
c92989d… drh 1752 assert( iCol>=0 && iCol<=2 );
c92989d… drh 1753 iMask = 1 << iCol;
c92989d… drh 1754 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
c92989d… drh 1755 if( iCol==0 && op==SQLITE_INDEX_CONSTRAINT_EQ ){
c92989d… drh 1756 bStartSeen = 1;
c92989d… drh 1757 }
c92989d… drh 1758 #endif
c92989d… drh 1759 if( pConstraint->usable==0 ){
c92989d… drh 1760 unusableMask |= iMask;
c92989d… drh 1761 continue;
c92989d… drh 1762 }else if( op==SQLITE_INDEX_CONSTRAINT_EQ ){
c92989d… drh 1763 idxNum |= iMask;
c92989d… drh 1764 aIdx[iCol] = i;
c92989d… drh 1765 }
c92989d… drh 1766 }
c92989d… drh 1767 if( pIdxInfo->nOrderBy>=1 ){
c92989d… drh 1768 int iOB = pIdxInfo->aOrderBy[0].iColumn;
c92989d… drh 1769 if( iOB==SERIES_COLUMN_VALUE || iOB==SERIES_COLUMN_ROWID ){
c92989d… drh 1770 /* The rowid is an alias for value, and both are unique, so the
c92989d… drh 1771 ** series can be generated in the requested order regardless of any
c92989d… drh 1772 ** subsequent ORDER BY terms. */
c92989d… drh 1773 if( pIdxInfo->aOrderBy[0].desc ){
c92989d… drh 1774 idxNum |= 0x08;
c92989d… drh 1775 }else{
c92989d… drh 1776 idxNum |= 0x10;
c92989d… drh 1777 }
c92989d… drh 1778 pIdxInfo->orderByConsumed = 1;
c92989d… drh 1779 }else{
c92989d… drh 1780 /* The core will sort the output, so it needs to see every row.
c92989d… drh 1781 ** A LIMIT or OFFSET applied here would discard rows before the sort */
c92989d… drh 1782 idxNum &= ~0x60;
c92989d… drh 1783 aIdx[3] = aIdx[4] = -1;
c92989d… drh 1784 }
c92989d… drh 1785 }
c92989d… drh 1786 if( aIdx[3]==0 ){
c92989d… drh 1787 /* Ignore OFFSET if LIMIT is omitted */
c92989d… drh 1788 idxNum &= ~0x60;
c92989d… drh 1789 aIdx[4] = 0;
c92989d… drh 1790 }
c92989d… drh 1791 for(i=0; i<7; i++){
c92989d… drh 1792 if( (j = aIdx[i])>=0 ){
c92989d… drh 1793 pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
c92989d… drh 1794 pIdxInfo->aConstraintUsage[j].omit =
c92989d… drh 1795 !SQLITE_SERIES_CONSTRAINT_VERIFY || i>=3;
c92989d… drh 1796 }
c92989d… drh 1797 }
c92989d… drh 1798 /* The current generate_column() implementation requires at least one
c92989d… drh 1799 ** argument (the START value). Legacy versions assumed START=0 if the
c92989d… drh 1800 ** first argument was omitted. Compile with -DZERO_ARGUMENT_GENERATE_SERIES
c92989d… drh 1801 ** to obtain the legacy behavior */
c92989d… drh 1802 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
c92989d… drh 1803 if( !bStartSeen ){
c92989d… drh 1804 sqlite3_free(pVTab->zErrMsg);
c92989d… drh 1805 pVTab->zErrMsg = sqlite3_mprintf(
c92989d… drh 1806 "first argument to \"generate_series()\" missing or unusable");
c92989d… drh 1807 return SQLITE_ERROR;
c92989d… drh 1808 }
c92989d… drh 1809 #endif
c92989d… drh 1810 if( (unusableMask & ~idxNum)!=0 ){
c92989d… drh 1811 /* The start, stop, and step columns are inputs. Therefore if there
c92989d… drh 1812 ** are unusable constraints on any of start, stop, or step then
c92989d… drh 1813 ** this plan is unusable */
c92989d… drh 1814 return SQLITE_CONSTRAINT;
c92989d… drh 1815 }
c92989d… drh 1816 if( (idxNum & 0x03)==0x03 ){
c92989d… drh 1817 /* Both start= and stop= boundaries are available. This is the
c92989d… drh 1818 ** the preferred case */
c92989d… drh 1819 pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
c92989d… drh 1820 pIdxInfo->estimatedRows = 1000;
c92989d… drh 1821 }else if( (idxNum & 0x21)==0x21 ){
c92989d… drh 1822 /* We have start= and LIMIT */
c92989d… drh 1823 pIdxInfo->estimatedRows = 2500;
c92989d… drh 1824 }else{
c92989d… drh 1825 /* If either boundary is missing, we have to generate a huge span
c92989d… drh 1826 ** of numbers. Make this case very expensive so that the query
c92989d… drh 1827 ** planner will work hard to avoid it. */
c92989d… drh 1828 pIdxInfo->estimatedRows = 2147483647;
c92989d… drh 1829 }
c92989d… drh 1830 pIdxInfo->idxNum = idxNum;
c92989d… drh 1831 #ifdef SQLITE_INDEX_SCAN_HEX
c92989d… drh 1832 pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_HEX;
c92989d… drh 1833 #endif
c92989d… drh 1834 return SQLITE_OK;
c92989d… drh 1835 }
c92989d… drh 1836
c92989d… drh 1837 /*
c92989d… drh 1838 ** This following structure defines all the methods for the
c92989d… drh 1839 ** generate_series virtual table.
c92989d… drh 1840 */
c92989d… drh 1841 static sqlite3_module seriesModule = {
c92989d… drh 1842 0, /* iVersion */
c92989d… drh 1843 0, /* xCreate */
c92989d… drh 1844 seriesConnect, /* xConnect */
c92989d… drh 1845 seriesBestIndex, /* xBestIndex */
c92989d… drh 1846 seriesDisconnect, /* xDisconnect */
c92989d… drh 1847 0, /* xDestroy */
c92989d… drh 1848 seriesOpen, /* xOpen - open a cursor */
c92989d… drh 1849 seriesClose, /* xClose - close a cursor */
c92989d… drh 1850 seriesFilter, /* xFilter - configure scan constraints */
c92989d… drh 1851 seriesNext, /* xNext - advance a cursor */
c92989d… drh 1852 seriesEof, /* xEof - check for end of scan */
c92989d… drh 1853 seriesColumn, /* xColumn - read data */
c92989d… drh 1854 seriesRowid, /* xRowid - read data */
c92989d… drh 1855 0, /* xUpdate */
c92989d… drh 1856 0, /* xBegin */
c92989d… drh 1857 0, /* xSync */
c92989d… drh 1858 0, /* xCommit */
c92989d… drh 1859 0, /* xRollback */
c92989d… drh 1860 0, /* xFindMethod */
c92989d… drh 1861 0, /* xRename */
c92989d… drh 1862 0, /* xSavepoint */
c92989d… drh 1863 0, /* xRelease */
c92989d… drh 1864 0, /* xRollbackTo */
c92989d… drh 1865 0, /* xShadowName */
c92989d… drh 1866 0 /* xIntegrity */
c92989d… drh 1867 };
c92989d… drh 1868
c92989d… drh 1869 #endif /* SQLITE_OMIT_VIRTUALTABLE */
c92989d… drh 1870
c92989d… drh 1871 #ifdef _WIN32
c92989d… drh 1872
c92989d… drh 1873 #endif
c92989d… drh 1874 int sqlite3_series_init(
c92989d… drh 1875 sqlite3 *db,
c92989d… drh 1876 char **pzErrMsg,
c92989d… drh 1877 const sqlite3_api_routines *pApi
c92989d… drh 1878 ){
c92989d… drh 1879 int rc = SQLITE_OK;
c92989d… drh 1880 SQLITE_EXTENSION_INIT2(pApi);
c92989d… drh 1881 #ifndef SQLITE_OMIT_VIRTUALTABLE
c92989d… drh 1882 if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
c92989d… drh 1883 *pzErrMsg = sqlite3_mprintf(
c92989d… drh 1884 "generate_series() requires SQLite 3.8.12 or later");
c92989d… drh 1885 return SQLITE_ERROR;
c92989d… drh 1886 }
c92989d… drh 1887 rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
c92989d… drh 1888 #endif
c92989d… drh 1889 return rc;
c92989d… drh 1890 }
c92989d… drh 1891
c92989d… drh 1892 /************************* End ext/misc/series.c ********************/
c92989d… drh 1893 /************************* Begin ext/misc/tryeval.c ******************/
c92989d… drh 1894 /*
c92989d… drh 1895 ** 2026-10-26
c92989d… drh 1896 **
c92989d… drh 1897 ** The author disclaims copyright to this source code. In place of
c92989d… drh 1898 ** a legal notice, here is a blessing:
c92989d… drh 1899 **
c92989d… drh 1900 ** May you do good and not evil.
c92989d… drh 1901 ** May you find forgiveness for yourself and forgive others.
c92989d… drh 1902 ** May you share freely, never taking more than you give.
c92989d… drh 1903 **
c92989d… drh 1904 ******************************************************************************
c92989d… drh 1905 **
c92989d… drh 1906 ** This is an extension used for testing SQLite. It is not intended for
c92989d… drh 1907 ** production use. The interface might change. This file might go out
c92989d… drh 1908 ** of support and disappear at any moment. Do not depend on this extension.
c92989d… drh 1909 **
c92989d… drh 1910 ** Apparent from comments in the code, this extension is undocumented.
c92989d… drh 1911 **
c92989d… drh 1912 ** This SQLite extension implements the SQL function tryeval(). The tryeval()
c92989d… drh 1913 ** function takes zero or more arguments, each of which is an SQL statement.
c92989d… drh 1914 ** The tryeval() function returns the first column of the first row that
c92989d… drh 1915 ** has a non-NULL first column across each of the argument SQL statements.
c92989d… drh 1916 ** Evaluation stops as soon as the first row with a non-NULL first column
c92989d… drh 1917 ** is encountered. Errors in evaluation are silently ignored, moving on
c92989d… drh 1918 ** the next SQL statement argument. If none of the arguments successfully
c92989d… drh 1919 ** executes and returns a row with a non-NULL first column, then NULL is
c92989d… drh 1920 ** returned.
c92989d… drh 1921 **
c92989d… drh 1922 ** Update: Also the expire(V) and expire(V,N) functions. See comments
c92989d… drh 1923 ** below for details.
c92989d… drh 1924 **
c92989d… drh 1925 ** The purpose of this function is to help evaluate recursive
c92989d… drh 1926 ** behavior, and expecially the bug report at
c92989d… drh 1927 ** sqlite.org/bugs/info/3577bc69c52237a4 (2026-10-25T19:26:00Z)
c92989d… drh 1928 ** as well as other bugs.
c92989d… drh 1929 **
c92989d… drh 1930 ** To build (with SODIR being the directory that contains your
c92989d… drh 1931 ** sqlite3.h and sqlite3ext.h headers):
c92989d… drh 1932 **
c92989d… drh 1933 ** Linux: gcc -O2 -shared -I$SQDIR -fPIC -o tryeval.so tryeval.c
c92989d… drh 1934 ** Mac: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o tryeval.dylib tryeval.c
c92989d… drh 1935 ** Win32: cl /Os -I%SQDIR% tryeval.c -link -dll -out:tryeval.dll
c92989d… drh 1936 */
c92989d… drh 1937 /* #include "sqlite3ext.h" */
c92989d… drh 1938 SQLITE_EXTENSION_INIT1
c92989d… drh 1939 #include <string.h>
c92989d… drh 1940
c92989d… drh 1941 /*
c92989d… drh 1942 ** Implementation of the tryeval(...)
c92989d… drh 1943 */
c92989d… drh 1944 static void tryEvalFunc(
c92989d… drh 1945 sqlite3_context *context,
c92989d… drh 1946 int argc,
c92989d… drh 1947 sqlite3_value **argv
c92989d… drh 1948 ){
c92989d… drh 1949 const char *zSql; /* Next SQL statement to evaluate */
c92989d… drh 1950 sqlite3 *db; /* The database connection */
c92989d… drh 1951 sqlite3_stmt *pStmt; /* Compiled bytecode for zSql */
c92989d… drh 1952 int bDone = 0; /* True if a row with non-NULL first column seen */
c92989d… drh 1953 int rc; /* Result from sqlite3 API calls */
c92989d… drh 1954 int i; /* Loop counter */
c92989d… drh 1955
c92989d… drh 1956 db = sqlite3_context_db_handle(context);
c92989d… drh 1957 for(i=0; !bDone && i<argc; i++){
c92989d… drh 1958 zSql = (const char*)sqlite3_value_text(argv[i]);
c92989d… drh 1959 if( zSql==0 ) continue;
c92989d… drh 1960 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
c92989d… drh 1961 if( rc==SQLITE_OK ){
c92989d… drh 1962 while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){
c92989d… drh 1963 if( sqlite3_column_type(pStmt,0)==SQLITE_NULL ) continue;
c92989d… drh 1964 sqlite3_result_value(context, sqlite3_column_value(pStmt,0));
c92989d… drh 1965 bDone = 1;
c92989d… drh 1966 break;
c92989d… drh 1967 }
c92989d… drh 1968 }
c92989d… drh 1969 sqlite3_finalize(pStmt);
c92989d… drh 1970 }
c92989d… drh 1971 }
c92989d… drh 1972
c92989d… drh 1973 /* SQL function: expire(v,n)
c92989d… drh 1974 **
c92989d… drh 1975 ** Return the first argument. But before doing so, expire all prepared
c92989d… drh 1976 ** statements that use schema n (0,1,...) or if n==-1 expire all prepared
c92989d… drh 1977 ** statements. If the second argument is omitted, it is assumed to be -1.
c92989d… drh 1978 **
c92989d… drh 1979 ** This routine requires the (new) SQLITE_TESTCTRL_EXPIRE_STMTS test
c92989d… drh 1980 ** control. If your SQLite does not support that test control, or if
c92989d… drh 1981 ** you compile with test controls disabled (you ought not do that!) then
c92989d… drh 1982 ** this routine is just copies its first argument as its result.
c92989d… drh 1983 */
c92989d… drh 1984 static void expireFunc(
c92989d… drh 1985 sqlite3_context *context,
c92989d… drh 1986 int argc,
c92989d… drh 1987 sqlite3_value **argv
c92989d… drh 1988 ){
c92989d… drh 1989 sqlite3 *db = sqlite3_context_db_handle(context);
c92989d… drh 1990 int iDb = argc>=2 ? sqlite3_value_int(argv[1]) : -1;
c92989d… drh 1991 #ifdef SQLITE_TESTCTRL_EXPIRE_STMTS
c92989d… drh 1992 sqlite3_test_control(SQLITE_TESTCTRL_EXPIRE_STMTS, db, iDb);
c92989d… drh 1993 #endif
c92989d… drh 1994 sqlite3_result_value(context, argv[0]);
c92989d… drh 1995 }
c92989d… drh 1996
c92989d… drh 1997 #ifdef _WIN32
c92989d… drh 1998
c92989d… drh 1999 #endif
c92989d… drh 2000 int sqlite3_tryeval_init(
c92989d… drh 2001 sqlite3 *db,
c92989d… drh 2002 char **pzErrMsg,
c92989d… drh 2003 const sqlite3_api_routines *pApi
c92989d… drh 2004 ){
c92989d… drh 2005 int rc = SQLITE_OK;
c92989d… drh 2006 SQLITE_EXTENSION_INIT2(pApi);
c92989d… drh 2007 (void)pzErrMsg; /* Unused parameter */
c92989d… drh 2008 rc = sqlite3_create_function(db, "tryeval", -1,
c92989d… drh 2009 SQLITE_UTF8, 0,
c92989d… drh 2010 tryEvalFunc, 0, 0);
c92989d… drh 2011 if( rc==SQLITE_OK ){
c92989d… drh 2012 rc = sqlite3_create_function(db, "expire", 1,
c92989d… drh 2013 SQLITE_UTF8|SQLITE_DETERMINISTIC, 0,
c92989d… drh 2014 expireFunc, 0, 0);
c92989d… drh 2015 }
c92989d… drh 2016 if( rc==SQLITE_OK ){
c92989d… drh 2017 rc = sqlite3_create_function(db, "expire", 2,
c92989d… drh 2018 SQLITE_UTF8|SQLITE_DETERMINISTIC, 0,
c92989d… drh 2019 expireFunc, 0, 0);
c92989d… drh 2020 }
c92989d… drh 2021 return rc;
c92989d… drh 2022 }
c92989d… drh 2023
c92989d… drh 2024 /************************* End ext/misc/tryeval.c ********************/
b8ab8b3… drh 2025 # include <limits.h>
b8ab8b3… drh 2026 # include <stdlib.h>
9b67f46… drh 2027 #ifdef _WIN32
9b67f46… drh 2028 /*
9b67f46… drh 2029 ** Convert a UTF-8 string to Microsoft Unicode.
9b67f46… drh 2030 **
9b67f46… drh 2031 ** Space to hold the returned string is obtained from sqlite3_malloc().
9b67f46… drh 2032 */
9b67f46… drh 2033 static wchar_t *winUtf8To16(const char *zText){
9b67f46… drh 2034 int nChar;
9b67f46… drh 2035 wchar_t *zWideText;
9b67f46… drh 2036
9b67f46… drh 2037 nChar = MultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
9b67f46… drh 2038 if( nChar==0 ){
9b67f46… drh 2039 return 0;
9b67f46… drh 2040 }
9b67f46… drh 2041 zWideText = sqlite3_malloc64(nChar*sizeof(WCHAR) );
9b67f46… drh 2042 if( zWideText==0 ){
9b67f46… drh 2043 return 0;
9b67f46… drh 2044 }
9b67f46… drh 2045 nChar = MultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
9b67f46… drh 2046 nChar);
9b67f46… drh 2047 if( nChar==0 ){
9b67f46… drh 2048 sqlite3_free(zWideText);
9b67f46… drh 2049 zWideText = 0;
9b67f46… drh 2050 }
9b67f46… drh 2051 return zWideText;
9b67f46… drh 2052 }
9b67f46… drh 2053 #endif /* _WIN32 */
9b67f46… drh 2054
9b67f46… drh 2055 #ifdef _WIN32
9b67f46… drh 2056 /*
9b67f46… drh 2057 ** Convert a Microsoft Unicode string to UTF-8.
9b67f46… drh 2058 **
9b67f46… drh 2059 ** Space to hold the returned string is obtained from sqlite3_malloc().
9b67f46… drh 2060 */
9b67f46… drh 2061 static char *winUtf16To8(wchar_t *zWideText){
9b67f46… drh 2062 int nByte;
9b67f46… drh 2063 char *zText;
9b67f46… drh 2064
9b67f46… drh 2065 nByte = WideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
9b67f46… drh 2066 if( nByte == 0 ){
9b67f46… drh 2067 return 0;
9b67f46… drh 2068 }
9b67f46… drh 2069 zText = sqlite3_malloc64( nByte );
9b67f46… drh 2070 if( zText==0 ){
9b67f46… drh 2071 return 0;
9b67f46… drh 2072 }
9b67f46… drh 2073 nByte = WideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
9b67f46… drh 2074 0, 0);
9b67f46… drh 2075 if( nByte == 0 ){
9b67f46… drh 2076 sqlite3_free(zText);
9b67f46… drh 2077 zText = 0;
9b67f46… drh 2078 }
9b67f46… drh 2079 return zText;
9b67f46… drh 2080 }
9b67f46… drh 2081 #endif /* _WIN32 */
9b67f46… drh 2082
9b67f46… drh 2083 wchar_t *b1 = winUtf8To16(zPath);
9b67f46… drh 2084 wchar_t *b1 = winUtf8To16(zPath);
e66a8c7… drh 2085 sqlite3_int64 nIn; /* Size of the file according to ftell() */
e66a8c7… drh 2086 sqlite3_int64 nAlloc; /* Bytes allocated for pBuf */
e66a8c7… drh 2087 sqlite3_int64 nRead = 0; /* Bytes read so far */
e66a8c7… drh 2088 unsigned char *pBuf;
e66a8c7… drh 2089 /* The size reported by ftell() is only a hint. It is -1 for pipes and
e66a8c7… drh 2090 ** FIFOs and 0 for many files under /proc. Keep reading until EOF. */
e66a8c7… drh 2091 if( nIn<0 ) nIn = 0;
e66a8c7… drh 2092 /* One extra byte so that EOF on a regular file is seen without a
e66a8c7… drh 2093 ** reallocation. */
e66a8c7… drh 2094 nAlloc = nIn+1;
e66a8c7… drh 2095 pBuf = sqlite3_malloc64( nAlloc );
e66a8c7… drh 2096 while( 1 ){
e66a8c7… drh 2097 unsigned char *pNew;
e66a8c7… drh 2098 nRead += fread(pBuf+nRead, 1, (size_t)(nAlloc-nRead), in);
e66a8c7… drh 2099 if( nRead>mxBlob ){
e66a8c7… drh 2100 sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
e66a8c7… drh 2101 sqlite3_free(pBuf);
e66a8c7… drh 2102 fclose(in);
e66a8c7… drh 2103 return;
e66a8c7… drh 2104 }
e66a8c7… drh 2105 if( nRead<nAlloc ) break; /* Short read means EOF or an error */
e66a8c7… drh 2106 nAlloc *= 2;
e66a8c7… drh 2107 if( nAlloc>(sqlite3_int64)mxBlob+1 ) nAlloc = (sqlite3_int64)mxBlob+1;
e66a8c7… drh 2108 pNew = sqlite3_realloc64(pBuf, nAlloc);
e66a8c7… drh 2109 if( pNew==0 ){
e66a8c7… drh 2110 sqlite3_result_error_nomem(ctx);
e66a8c7… drh 2111 sqlite3_free(pBuf);
e66a8c7… drh 2112 fclose(in);
e66a8c7… drh 2113 return;
e66a8c7… drh 2114 }
e66a8c7… drh 2115 pBuf = pNew;
e66a8c7… drh 2116 }
e66a8c7… drh 2117 if( ferror(in) ){
e66a8c7… drh 2118 }else{
e66a8c7… drh 2119 sqlite3_result_blob64(ctx, pBuf, nRead, sqlite3_free);
b8ab8b3… drh 2120 #endif /* _WIN32 */
9b67f46… drh 2121 wchar_t *b1 = winUtf8To16(zPath);
b8ab8b3… drh 2122 if( rc==0 ){
b8ab8b3… drh 2123 HANDLE hFindFile;
b8ab8b3… drh 2124 WIN32_FIND_DATAW fd;
b8ab8b3… drh 2125 memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
b8ab8b3… drh 2126 hFindFile = FindFirstFileW(b1, &fd);
b8ab8b3… drh 2127 if( hFindFile!=NULL ){
b8ab8b3… drh 2128 pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
b8ab8b3… drh 2129 pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
b8ab8b3… drh 2130 pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
b8ab8b3… drh 2131 FindClose(hFindFile);
b8ab8b3… drh 2132 }
b8ab8b3… drh 2133 }
c92989d… drh 2134 }else if( zCopy[0]==0 ){
c92989d… drh 2135 rc = SQLITE_ERROR;
c92989d… drh 2136 sqlite3_free(zCopy);
c92989d… drh 2137 for(; i<nCopy && zCopy[i]!='/'; i++);
c92989d… drh 2138 if( i>=nCopy ) break;
9b67f46… drh 2139 zUnicodeName = winUtf8To16(zFile);
c92989d… drh 2140 res = makeDirectory(zFile);
c92989d… drh 2141 if( res==SQLITE_OK ){
0201a1e… drh 2142 pNew = (fsdir_tab*)sqlite3_malloc64( sizeof(*pNew) );
0201a1e… drh 2143 pCur = sqlite3_malloc64( sizeof(*pCur) );
ee87371… drh 2144 if( n>0 ){
ee87371… drh 2145 sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
ee87371… drh 2146 }else{
ee87371… drh 2147 sqlite3_result_null(ctx);
ee87371… drh 2148 }
e66a8c7… drh 2149 pCur->mxLvl = 1000000000;
e66a8c7… drh 2150 /* The LEVEL constraint is only used to limit the depth of the
e66a8c7… drh 2151 ** search. SQLite still checks the constraint against every row, so
e66a8c7… drh 2152 ** mxLvl may admit rows that do not match, but must never exclude
e66a8c7… drh 2153 ** a row that does. Only entries with level<mxLvl are visited. */
e66a8c7… drh 2154 sqlite3_value *pMx;
e66a8c7… drh 2155 pMx = argv[i++];
e66a8c7… drh 2156 switch( sqlite3_value_type(pMx) ){
e66a8c7… drh 2157 case SQLITE_NULL: {
e66a8c7… drh 2158 /* No row can match a NULL constraint */
e66a8c7… drh 2159 pCur->mxLvl = 1;
e66a8c7… drh 2160 break;
e66a8c7… drh 2161 }
e66a8c7… drh 2162 case SQLITE_INTEGER:
e66a8c7… drh 2163 case SQLITE_FLOAT: {
e66a8c7… drh 2164 double r = sqlite3_value_double(pMx);
e66a8c7… drh 2165 if( r<1.0 ){
e66a8c7… drh 2166 pCur->mxLvl = 1;
e66a8c7… drh 2167 }else if( r<1.0e9 ){
e66a8c7… drh 2168 int iMx = (int)r;
e66a8c7… drh 2169 if( (idxNum & 0x08)!=0 || (double)iMx<r ) iMx++;
e66a8c7… drh 2170 pCur->mxLvl = iMx;
e66a8c7… drh 2171 }
e66a8c7… drh 2172 break;
e66a8c7… drh 2173 }
e66a8c7… drh 2174 default: {
e66a8c7… drh 2175 /* TEXT or BLOB. Do not limit the search. */
e66a8c7… drh 2176 break;
e66a8c7… drh 2177 }
e66a8c7… drh 2178 }
e66a8c7… drh 2179 ** 0x04 LEVEL< bound is in argv[1] or [2]
e66a8c7… drh 2180 ** 0x08 LEVEL<= or LEVEL= bound is in argv[1] or [2]
e66a8c7… drh 2181 **
e66a8c7… drh 2182 ** The LEVEL constraint is never omitted. It is used only to limit the
e66a8c7… drh 2183 ** depth of the directory search, and SQLite rechecks it for each row.
b8ab8b3… drh 2184 /*
b8ab8b3… drh 2185 ** This version of realpath() works on any system. The string
b8ab8b3… drh 2186 ** returned is held in memory allocated using sqlite3_malloc64().
b8ab8b3… drh 2187 ** The caller is responsible for calling sqlite3_free().
b8ab8b3… drh 2188 */
b8ab8b3… drh 2189 static char *portable_realpath(const char *zPath){
b8ab8b3… drh 2190 #if !defined(_WIN32) /* BEGIN unix */
b8ab8b3… drh 2191
b8ab8b3… drh 2192 char *zOut = 0; /* Result */
b8ab8b3… drh 2193 char *z; /* Temporary buffer */
b8ab8b3… drh 2194 #if defined(PATH_MAX)
b8ab8b3… drh 2195 char zBuf[PATH_MAX+1]; /* Space for the temporary buffer */
b8ab8b3… drh 2196 #endif
b8ab8b3… drh 2197
b8ab8b3… drh 2198 if( zPath==0 ) return 0;
b8ab8b3… drh 2199 #if defined(PATH_MAX)
b8ab8b3… drh 2200 z = realpath(zPath, zBuf);
b8ab8b3… drh 2201 if( z ){
b8ab8b3… drh 2202 zOut = sqlite3_mprintf("%s", zBuf);
b8ab8b3… drh 2203 }
b8ab8b3… drh 2204 #endif /* defined(PATH_MAX) */
b8ab8b3… drh 2205 if( zOut==0 ){
b8ab8b3… drh 2206 /* Try POSIX.1-2008 malloc behavior */
b8ab8b3… drh 2207 z = realpath(zPath, NULL);
b8ab8b3… drh 2208 if( z ){
b8ab8b3… drh 2209 zOut = sqlite3_mprintf("%s", z);
b8ab8b3… drh 2210 free(z);
b8ab8b3… drh 2211 }
b8ab8b3… drh 2212 }
b8ab8b3… drh 2213 return zOut;
b8ab8b3… drh 2214
b8ab8b3… drh 2215 #else /* End UNIX, Begin WINDOWS */
b8ab8b3… drh 2216
b8ab8b3… drh 2217 wchar_t *zPath16; /* UTF16 translation of zPath */
b8ab8b3… drh 2218 char *zOut = 0; /* Result */
b8ab8b3… drh 2219 wchar_t *z = 0; /* Temporary buffer */
b8ab8b3… drh 2220
b8ab8b3… drh 2221 if( zPath==0 ) return 0;
b8ab8b3… drh 2222
9b67f46… drh 2223 zPath16 = winUtf8To16(zPath);
b8ab8b3… drh 2224 if( zPath16==0 ) return 0;
b8ab8b3… drh 2225 z = _wfullpath(NULL, zPath16, 0);
b8ab8b3… drh 2226 sqlite3_free(zPath16);
b8ab8b3… drh 2227 if( z ){
9b67f46… drh 2228 zOut = winUtf16To8(z);
b8ab8b3… drh 2229 free(z);
b8ab8b3… drh 2230 }
b8ab8b3… drh 2231 return zOut;
b8ab8b3… drh 2232
b8ab8b3… drh 2233 #endif /* End WINDOWS, Begin common code */
b8ab8b3… drh 2234 }
b8ab8b3… drh 2235
b8ab8b3… drh 2236 /*
b8ab8b3… drh 2237 ** SQL function: realpath(X)
b8ab8b3… drh 2238 **
b8ab8b3… drh 2239 ** Try to convert file or pathname X into its real, absolute pathname.
b8ab8b3… drh 2240 ** Return NULL if unable.
b8ab8b3… drh 2241 **
b8ab8b3… drh 2242 ** The file or directory X is not required to exist. The answer is formed
b8ab8b3… drh 2243 ** by calling system realpath() on the prefix of X that does exist and
b8ab8b3… drh 2244 ** appending the tail of X that does not (yet) exist.
ba00a43… drh 2245 **
ba00a43… drh 2246 ** FIXME: This routine sometimes returns NULL rather than raising
ba00a43… drh 2247 ** an SQLITE_NOMEM error if an OOM is encountered.
b8ab8b3… drh 2248 */
b8ab8b3… drh 2249 static void realpathFunc(
b8ab8b3… drh 2250 sqlite3_context *context,
b8ab8b3… drh 2251 int argc,
b8ab8b3… drh 2252 sqlite3_value **argv
b8ab8b3… drh 2253 ){
b8ab8b3… drh 2254 const char *zPath; /* Original input path */
b8ab8b3… drh 2255 char *zCopy; /* An editable copy of zPath */
b8ab8b3… drh 2256 char *zOut; /* The result */
b8ab8b3… drh 2257 char cSep = 0; /* Separator turned into \000 */
b8ab8b3… drh 2258 size_t len; /* Prefix length before cSep */
b8ab8b3… drh 2259 #ifdef _WIN32
b8ab8b3… drh 2260 const int isWin = 1;
b8ab8b3… drh 2261 #else
b8ab8b3… drh 2262 const int isWin = 0;
b8ab8b3… drh 2263 #endif
b8ab8b3… drh 2264
b8ab8b3… drh 2265 (void)argc;
b8ab8b3… drh 2266 zPath = (const char*)sqlite3_value_text(argv[0]);
b8ab8b3… drh 2267 if( zPath==0 ) return;
b8ab8b3… drh 2268 if( zPath[0]==0 ) zPath = ".";
b8ab8b3… drh 2269 zCopy = sqlite3_mprintf("%s",zPath);
ba00a43… drh 2270 if( zCopy==0 ) return;
b8ab8b3… drh 2271 len = strlen(zCopy);
b8ab8b3… drh 2272 while( len>1 && (zCopy[len-1]=='/' || (isWin && zCopy[len-1]=='\\')) ){
b8ab8b3… drh 2273 len--;
b8ab8b3… drh 2274 }
b8ab8b3… drh 2275 zCopy[len] = 0;
b8ab8b3… drh 2276 while( 1 /*exit-by-break*/ ){
b8ab8b3… drh 2277 zOut = portable_realpath(zCopy);
b8ab8b3… drh 2278 zCopy[len] = cSep;
b8ab8b3… drh 2279 if( zOut ){
b8ab8b3… drh 2280 if( cSep ){
b8ab8b3… drh 2281 zOut = sqlite3_mprintf("%z%s",zOut,&zCopy[len]);
b8ab8b3… drh 2282 }
b8ab8b3… drh 2283 break;
b8ab8b3… drh 2284 }else{
b8ab8b3… drh 2285 size_t i = len-1;
b8ab8b3… drh 2286 while( i>0 ){
b8ab8b3… drh 2287 if( zCopy[i]=='/' || (isWin && zCopy[i]=='\\') ) break;
b8ab8b3… drh 2288 i--;
b8ab8b3… drh 2289 }
b8ab8b3… drh 2290 if( i<=0 ){
b8ab8b3… drh 2291 if( zCopy[0]=='/' ){
b8ab8b3… drh 2292 zOut = zCopy;
b8ab8b3… drh 2293 zCopy = 0;
b8ab8b3… drh 2294 }else if( (zOut = portable_realpath("."))!=0 ){
b8ab8b3… drh 2295 zOut = sqlite3_mprintf("%z/%s", zOut, zCopy);
b8ab8b3… drh 2296 }
b8ab8b3… drh 2297 break;
b8ab8b3… drh 2298 }
b8ab8b3… drh 2299 cSep = zCopy[i];
b8ab8b3… drh 2300 zCopy[i] = 0;
b8ab8b3… drh 2301 len = i;
b8ab8b3… drh 2302 }
b8ab8b3… drh 2303 }
b8ab8b3… drh 2304 sqlite3_free(zCopy);
b8ab8b3… drh 2305 if( zOut ){
b8ab8b3… drh 2306 /* Simplify any "/./" or "/../" that might have snuck into the
b8ab8b3… drh 2307 ** pathname due to appending of zCopy. We only have to consider
b8ab8b3… drh 2308 ** unix "/" separators, because the _wfilepath() system call on
b8ab8b3… drh 2309 ** Windows will have already done this simplification for us. */
b8ab8b3… drh 2310 size_t i, j, n;
b8ab8b3… drh 2311 n = strlen(zOut);
b8ab8b3… drh 2312 for(i=j=0; i<n; i++){
b8ab8b3… drh 2313 if( zOut[i]=='/' ){
b8ab8b3… drh 2314 if( zOut[i+1]=='/' ) continue;
b8ab8b3… drh 2315 if( zOut[i+1]=='.' && i+2<n && zOut[i+2]=='/' ){
b8ab8b3… drh 2316 i += 1;
b8ab8b3… drh 2317 continue;
b8ab8b3… drh 2318 }
b8ab8b3… drh 2319 if( zOut[i+1]=='.' && i+3<n && zOut[i+2]=='.' && zOut[i+3]=='/' ){
b8ab8b3… drh 2320 while( j>0 && zOut[j-1]!='/' ){ j--; }
b8ab8b3… drh 2321 if( j>0 ){ j--; }
b8ab8b3… drh 2322 i += 2;
b8ab8b3… drh 2323 continue;
b8ab8b3… drh 2324 }
b8ab8b3… drh 2325 }
b8ab8b3… drh 2326 zOut[j++] = zOut[i];
b8ab8b3… drh 2327 }
b8ab8b3… drh 2328 zOut[j] = 0;
b8ab8b3… drh 2329
b8ab8b3… drh 2330 /* Return the result */
b8ab8b3… drh 2331 sqlite3_result_text(context, zOut, -1, sqlite3_free);
b8ab8b3… drh 2332 }
b8ab8b3… drh 2333 }
b8ab8b3… drh 2334
b8ab8b3… drh 2335
c92989d… drh 2336
c92989d… drh 2337 /* REMINDER: Changes here should be reflected in the ".safe" command
c92989d… drh 2338 ** of the CLI.
c92989d… drh 2339 */
b8ab8b3… drh 2340 }
b8ab8b3… drh 2341 if( rc==SQLITE_OK ){
b8ab8b3… drh 2342 rc = sqlite3_create_function(db, "realpath", 1,
b8ab8b3… drh 2343 SQLITE_UTF8, 0,
b8ab8b3… drh 2344 realpathFunc, 0, 0);
0201a1e… drh 2345 pNew = sqlite3_malloc64( sizeof(*pNew) );
0201a1e… drh 2346 pCur = sqlite3_malloc64( sizeof(*pCur) );
17f9878… drh 2347 int rc;
17f9878… drh 2348 sqlite3_str* pStr = sqlite3_str_new(pCur->db);
17f9878… drh 2349 sqlite3_str_appendf(pStr,
17f9878… drh 2350 "%s"
17f9878… drh 2351 zSep, zDb
17f9878… drh 2352 rc = sqlite3_finalize(pS2);
17f9878… drh 2353 zSql = sqlite3_str_finish(pStr);
17f9878… drh 2354 if( zSql==0 ) return SQLITE_NOMEM;
17f9878… drh 2355 if( rc==SQLITE_OK ){
17f9878… drh 2356 sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
17f9878… drh 2357 }
17f9878… drh 2358 if( rc ) return rc;
17f9878… drh 2359 sqlite3_str *pStr = sqlite3_str_new(pCur->db);
17f9878… drh 2360 sqlite3_str_appendf(pStr,
17f9878… drh 2361 "%s"
17f9878… drh 2362 zSep, zDb, zDb
17f9878… drh 2363 rc = sqlite3_finalize(pS2);
17f9878… drh 2364 zSql = sqlite3_str_finish(pStr);
17f9878… drh 2365 if( zSql==0 ) return SQLITE_NOMEM;
17f9878… drh 2366 if( rc==SQLITE_OK ){
17f9878… drh 2367 sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
17f9878… drh 2368 }
17f9878… drh 2369 if( rc ) return rc;
17f9878… drh 2370 rc = sqlite3_finalize(pCur->pStmt);
17f9878… drh 2371 if( rc ) return rc;
1ec45d0… drh 2372 if( iWriteEnd + paf->iPgOne >= APND_MAX_SIZE-APND_MARK_SIZE ){
1ec45d0… drh 2373 return SQLITE_FULL;
1ec45d0… drh 2374 }
1ec45d0… drh 2375 ** * No support for transactions. ROLLBACK is the same as COMMIT.
1ec45d0… drh 2376 ** A crash mid-transaction can leave the ZIP archive in a corrupt state.
e66a8c7… drh 2377 #define ZIPFILE_MX_ENTRY (65535) /* Max entries without zip64 extensions */
c92989d… drh 2378 ZipfileCsr *pCsr;
c92989d… drh 2379
c92989d… drh 2380 /* A cursor that is not reading from a file or from a blob steps through
c92989d… drh 2381 ** the pTab->pFirstEntry list, which is about to be deleted. Such a
c92989d… drh 2382 ** cursor has nothing left to return, so leave it at EOF rather than
c92989d… drh 2383 ** pointing at freed memory. */
c92989d… drh 2384 for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
c92989d… drh 2385 if( pCsr->pFile==0 && pCsr->pFreeEntry==0 ){
c92989d… drh 2386 pCsr->pCurrent = 0;
c92989d… drh 2387 pCsr->bEof = 1;
c92989d… drh 2388 }
c92989d… drh 2389 }
0201a1e… drh 2390 pCsr = sqlite3_malloc64(sizeof(*pCsr));
c92989d… drh 2391 /* File mode: pCurrent is a private copy owned by this cursor. */
c92989d… drh 2392 /* In the other modes pCurrent belongs to pFreeEntry or to the table.
c92989d… drh 2393 ** It must not be left dangling, since a later xFilter() that switches
c92989d… drh 2394 ** this cursor to file mode would free it. */
c92989d… drh 2395 pCsr->pCurrent = 0;
a570ebc… drh 2396 pCsr->pFreeEntry = 0;
ba8756a… drh 2397 /* Stop when there are less than 9 bytes left to scan in the buffer. This
ba8756a… drh 2398 ** is because the timestamp field requires exactly 9 bytes - 4 bytes of
ba8756a… drh 2399 ** header fields and 5 bytes of data. If there are less than 9 bytes
ba8756a… drh 2400 ** remaining, either it is some other field or else the extra data
ba8756a… drh 2401 ** is corrupt. Either way, do not process it. */
ba8756a… drh 2402 while( p+(2*sizeof(u16) + 1 + sizeof(u32))<=pEnd ){
c92989d… drh 2403 if( mUnixTime<=315532800 ){
c92989d… drh 2404 /* Experimentally, I find that Win11 will not report the modification
c92989d… drh 2405 ** time for any ZIP file entry with a date before 1980-01-01 00:00:01.
c92989d… drh 2406 ** So make that the minimum date-time value. */
c92989d… drh 2407 pCds->mDate = 0x0021;
c92989d… drh 2408 pCds->mTime = 0x0001;
c92989d… drh 2409 return;
c92989d… drh 2410 }
c92989d… drh 2411
c92989d… drh 2412 pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
c92989d… drh 2413 pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
c92989d… drh 2414
c92989d… drh 2415 assert( mUnixTime==zipfileMtime(pCds)
c92989d… drh 2416 || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
a570ebc… drh 2417 /* aRead[0..nFile-1] might contain embedded \000 characters
a570ebc… drh 2418 ** See Bug 2026-05-31T11:43:05Z */
a570ebc… drh 2419 pNew->cds.zFile = sqlite3_malloc64(nFile+1);
a570ebc… drh 2420 if( pNew->cds.zFile!=0 ){
a570ebc… drh 2421 memcpy(pNew->cds.zFile, aRead, nFile);
a570ebc… drh 2422 pNew->cds.zFile[nFile] = 0;
a570ebc… drh 2423 }
c92989d… drh 2424 if( !pCsr->bNoop && !pCsr->bEof ){
0201a1e… drh 2425 u8 *aRes = sqlite3_malloc64(nOut);
c92989d… drh 2426 ZipfileCDS *pCDS;
c92989d… drh 2427 if( pCsr->pCurrent==0 ){
c92989d… drh 2428 /* The transaction ended while this row was being processed. */
c92989d… drh 2429 return SQLITE_OK;
c92989d… drh 2430 }
c92989d… drh 2431 pCDS = &pCsr->pCurrent->cds;
0201a1e… drh 2432 pNew = sqlite3_malloc64(sizeof(ZipfileEntry));
471d617… drh 2433 if( pOld==0 ) return SQLITE_OK;
e66a8c7… drh 2434 int nEntry = 0;
e66a8c7… drh 2435 nEntry++;
e66a8c7… drh 2436 }
e66a8c7… drh 2437
e66a8c7… drh 2438 /* The EOCD record stores the number of entries as a 16-bit value.
e66a8c7… drh 2439 ** Refuse to add an entry that would cause it to overflow. */
e66a8c7… drh 2440 if( p==0 && pOld==0 && nEntry>=ZIPFILE_MX_ENTRY ){
e66a8c7… drh 2441 zipfileTableErr(pTab, "too many entries; max: %d", ZIPFILE_MX_ENTRY);
e66a8c7… drh 2442 rc = SQLITE_CONSTRAINT;
e66a8c7… drh 2443 assert( nEntry<=ZIPFILE_MX_ENTRY );
c92989d… drh 2444 if( pCsr && pCsr->pCurrent ){
a570ebc… drh 2445 if( (pBuf->nAlloc-pBuf->n)<nByte ){
a570ebc… drh 2446 i64 nNew = pBuf->n ? (i64)pBuf->n*2 : 512;
a570ebc… drh 2447 i64 nReq = pBuf->n + nByte;
a570ebc… drh 2448 rc = SQLITE_ERROR;
a570ebc… drh 2449 goto zipfile_step_out;
a570ebc… drh 2450 }
e66a8c7… drh 2451 if( p->nEntry>=ZIPFILE_MX_ENTRY ){
e66a8c7… drh 2452 zErr = sqlite3_mprintf("too many entries for zipfile(); max: %d",
e66a8c7… drh 2453 ZIPFILE_MX_ENTRY);
e66a8c7… drh 2454 rc = SQLITE_ERROR;
e66a8c7… drh 2455 goto zipfile_step_out;
e66a8c7… drh 2456 }
e66a8c7… drh 2457 assert( p->nEntry<=ZIPFILE_MX_ENTRY );
8594585… drh 2458 nZip = (i64)p->body.n + (i64)p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
c92989d… drh 2459 /* REMINDER: Changes here should also be reflected in the ".safe"
c92989d… drh 2460 ** command of the CLI
c92989d… drh 2461 */
0201a1e… drh 2462 pOut = (Bytef*)sqlite3_malloc64(nOut);
17f9878… drh 2463 sz = sqlite3_value_int64(argv[1]);
0201a1e… drh 2464 Bytef *pOut = sqlite3_malloc64(sz);
c92989d… drh 2465 pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) + nColl + 1);
c92989d… drh 2466 if( nId==0 ) return 1;
c92989d… drh 2467 if( zId[0]>='0' && zId[0]<='9' ) return 1;
c5bdd31… drh 2468
c5bdd31… drh 2469 if( collisions<10 ){
c5bdd31… drh 2470 for(i=0; zCols[i]; i++){
c5bdd31… drh 2471 h += ((h<<3) + zCols[i]);
c5bdd31… drh 2472 }
c5bdd31… drh 2473 zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
c5bdd31… drh 2474 }else{
c5bdd31… drh 2475 /* After several hash attempts, generate a random name */
c5bdd31… drh 2476 sqlite3_uint64 u;
c5bdd31… drh 2477 sqlite3_randomness(sizeof(u), &u);
c5bdd31… drh 2478 zName = sqlite3_mprintf("%s_idx_%llx", zTable, u);
c5bdd31… drh 2479 }
c5bdd31… drh 2480
c5bdd31… drh 2481 }while( ALWAYS(collisions<500) && zName!=0 );
c5bdd31… drh 2482 if( NEVER(collisions) ){
c92989d… drh 2483 if( rc==SQLITE_OK ){
c5bdd31… drh 2484 sqlite3_free(zName);
a570ebc… drh 2485 zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %Q",
51267fb… drh 2486 if( iSlot<0 || iSlot>=p->nSlot ){
51267fb… drh 2487 sqlite3_result_error(pCtx, "index out of range.", -1);
51267fb… drh 2488 return;
51267fb… drh 2489 }
a570ebc… drh 2490 "%sx.%Q IS sqlite_expert_rem(%d, x.%Q) COLLATE %Q",
c92989d… drh 2491 p->pzErrmsg = pzErr;
c92989d… drh 2492 p->pzErrmsg = 0;
c92989d… drh 2493 if( rc==SQLITE_BUSY_TIMEOUT ){
c92989d… drh 2494 if( pzErr ){
c92989d… drh 2495 *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
c92989d… drh 2496 }
c92989d… drh 2497 return rc;
c92989d… drh 2498 }
ba8756a… drh 2499 while( z[iRet] ){
8594585… drh 2500 while( z[iRet] && z[iRet++]!=']' ){}
8594585… drh 2501 }
ee87371… drh 2502 else if( c==0 ){
ee87371… drh 2503 iRet = 0;
ee87371… drh 2504 }
ee87371… drh 2505 ** Register or unregister special SQL functions implemented by intck.
ee87371… drh 2506 **
ee87371… drh 2507 ** Normally the custom SQL functions used by intck are only available
ee87371… drh 2508 ** in between sqlite3_intck_open() and sqlite3_intck_close(). However,
ee87371… drh 2509 ** for testing and debugging, it is sometimes useful to make those
ee87371… drh 2510 ** functions available generally. This routine provides as a separate
ee87371… drh 2511 ** interface in order to provide that capability.
ee87371… drh 2512 */
ee87371… drh 2513 int sqlite3_intck_register(sqlite3 *db, int bCreate){
ee87371… drh 2514 int rc;
ee87371… drh 2515 rc = sqlite3_create_function(db, "parse_create_index",
ee87371… drh 2516 2, SQLITE_UTF8, 0, bCreate ? intckParseCreateIndexFunc : 0, 0, 0
ee87371… drh 2517 );
ee87371… drh 2518 return rc;
ee87371… drh 2519 }
ee87371… drh 2520
ee87371… drh 2521 /*
ee87371… drh 2522 rc = sqlite3_intck_register(db, 1);
ee87371… drh 2523 sqlite3_intck_register(p->db, 0);
51267fb… drh 2524 p->zTestSql = 0;
51267fb… drh 2525 }else if( p->zObj ){
51267fb… drh 2526 p->zTestSql = intckCheckObjectSql(p, p->zObj, p->zKey, 0);
0201a1e… drh 2527 p = sqlite3_malloc64( sizeof(*p) );
0201a1e… drh 2528 sqlite3_io_methods *pNew = sqlite3_malloc64( sizeof(*pNew) );
71439dc… drh 2529 /************************* Begin ext/misc/diskused.c ******************/
9b67f46… drh 2530 /*
9b67f46… drh 2531 ** 2026-04-13
9b67f46… drh 2532 **
9b67f46… drh 2533 ** The author disclaims copyright to this source code. In place of
9b67f46… drh 2534 ** a legal notice, here is a blessing:
9b67f46… drh 2535 **
9b67f46… drh 2536 ** May you do good and not evil.
9b67f46… drh 2537 ** May you find forgiveness for yourself and forgive others.
9b67f46… drh 2538 ** May you share freely, never taking more than you give.
9b67f46… drh 2539 **
9b67f46… drh 2540 ******************************************************************************
9b67f46… drh 2541 **
71439dc… drh 2542 ** This extension implements an SQL function:
71439dc… drh 2543 **
71439dc… drh 2544 ** diskused(X)
71439dc… drh 2545 **
71439dc… drh 2546 ** Where X is the schema name (typically 'main'). The output is text
71439dc… drh 2547 ** that describes how much filesystem space the various tables and indexes
71439dc… drh 2548 ** of the database consume.
71439dc… drh 2549 **
71439dc… drh 2550 ** This function is a replacement for the (now deprecated)
71439dc… drh 2551 ** "sqlite3_analyzer" utility program. This function is built
71439dc… drh 2552 ** into the CLI and is used to implement the ".diskused" command there.
9b67f46… drh 2553 */
9b67f46… drh 2554 /* #include "sqlite3ext.h" */
9b67f46… drh 2555 SQLITE_EXTENSION_INIT1
9b67f46… drh 2556 #include <assert.h>
9b67f46… drh 2557 #include <string.h>
9b67f46… drh 2558 #include <ctype.h>
9b67f46… drh 2559 #include <math.h>
9b67f46… drh 2560
9b67f46… drh 2561 /*
9b67f46… drh 2562 ** State information for the analysis
9b67f46… drh 2563 */
71439dc… drh 2564 typedef struct DiskUsed DiskUsed;
71439dc… drh 2565 struct DiskUsed {
9b67f46… drh 2566 sqlite3 *db; /* Database connection */
9b67f46… drh 2567 sqlite3_context *context; /* SQL function context */
9b67f46… drh 2568 sqlite3_str *pOut; /* Write output here */
9b67f46… drh 2569 char *zSU; /* Name of the temp.space_used table */
9b67f46… drh 2570 const char *zSchema; /* Schema to be analyzed */
9b67f46… drh 2571 };
9b67f46… drh 2572
9b67f46… drh 2573 /*
71439dc… drh 2574 ** Free all resources that the DiskUsed object references and
71439dc… drh 2575 ** reset the DiskUsed object.
9b67f46… drh 2576 **
71439dc… drh 2577 ** Call this routine multiple times on the same DiskUsed object
9b67f46… drh 2578 ** is a harmless no-op, as long as the memory for the object itself
9b67f46… drh 2579 ** has not been freed.
9b67f46… drh 2580 */
71439dc… drh 2581 static void diskusedReset(DiskUsed *p){
9b67f46… drh 2582 if( p->zSU ){
9b67f46… drh 2583 char *zSql = sqlite3_mprintf("DROP TABLE temp.%s;", p->zSU);
9b67f46… drh 2584 if( zSql ){
9b67f46… drh 2585 sqlite3_exec(p->db, zSql, 0, 0, 0);
9b67f46… drh 2586 sqlite3_free(zSql);
9b67f46… drh 2587 }
9b67f46… drh 2588 }
9b67f46… drh 2589 sqlite3_str_free(p->pOut);
9b67f46… drh 2590 sqlite3_free(p->zSU);
9b67f46… drh 2591 memset(p, 0, sizeof(*p));
9b67f46… drh 2592 }
9b67f46… drh 2593
9b67f46… drh 2594 /*
9b67f46… drh 2595 ** Report an error using formatted text. If zFormat==NULL then report
9b67f46… drh 2596 ** an OOM error.
9b67f46… drh 2597 */
71439dc… drh 2598 static void diskusedError(DiskUsed *p, const char *zFormat, ...){
9b67f46… drh 2599 char *zErr;
9b67f46… drh 2600 if( zFormat ){
9b67f46… drh 2601 va_list ap;
9b67f46… drh 2602 va_start(ap, zFormat);
9b67f46… drh 2603 zErr = sqlite3_vmprintf(zFormat, ap);
9b67f46… drh 2604 va_end(ap);
9b67f46… drh 2605 }else{
9b67f46… drh 2606 zErr = 0;
9b67f46… drh 2607 }
9b67f46… drh 2608 if( zErr==0 ){
9b67f46… drh 2609 sqlite3_result_error_nomem(p->context);
9b67f46… drh 2610 }else{
9b67f46… drh 2611 sqlite3_result_error(p->context, zErr, -1);
9b67f46… drh 2612 sqlite3_free(zErr);
9b67f46… drh 2613 }
71439dc… drh 2614 diskusedReset(p);
9b67f46… drh 2615 }
9b67f46… drh 2616
9b67f46… drh 2617 /*
9b67f46… drh 2618 ** Prepare and return an SQL statement.
9b67f46… drh 2619 */
71439dc… drh 2620 static sqlite3_stmt *diskusedVPrep(DiskUsed *p, const char *zFmt, va_list ap){
9b67f46… drh 2621 char *zSql;
9b67f46… drh 2622 int rc;
9b67f46… drh 2623 sqlite3_stmt *pStmt = 0;
9b67f46… drh 2624 zSql = sqlite3_vmprintf(zFmt, ap);
71439dc… drh 2625 if( zSql==0 ){ diskusedError(p,0); return 0; }
9b67f46… drh 2626 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9b67f46… drh 2627 if( rc ){
71439dc… drh 2628 diskusedError(p, "SQL parse error: %s\nOriginal SQL: %s",
9b67f46… drh 2629 sqlite3_errmsg(p->db), zSql);
9b67f46… drh 2630 sqlite3_finalize(pStmt);
71439dc… drh 2631 diskusedReset(p);
9b67f46… drh 2632 pStmt = 0;
9b67f46… drh 2633 }
9b67f46… drh 2634 sqlite3_free(zSql);
9b67f46… drh 2635 return pStmt;
9b67f46… drh 2636 }
71439dc… drh 2637 static sqlite3_stmt *diskusedPrepare(DiskUsed *p, const char *zFormat, ...){
9b67f46… drh 2638 va_list ap;
9b67f46… drh 2639 sqlite3_stmt *pStmt = 0;
9b67f46… drh 2640 va_start(ap, zFormat);
71439dc… drh 2641 pStmt = diskusedVPrep(p,zFormat,ap);
9b67f46… drh 2642 va_end(ap);
9b67f46… drh 2643 return pStmt;
9b67f46… drh 2644 }
9b67f46… drh 2645
9b67f46… drh 2646 /*
9b67f46… drh 2647 ** If rc is something other than SQLITE_DONE or SQLITE_OK, then report
9b67f46… drh 2648 ** an error and return true.
9b67f46… drh 2649 **
9b67f46… drh 2650 ** If rc is SQLITE_DONE or SQLITE_OK, then return false.
9b67f46… drh 2651 **
9b67f46… drh 2652 ** The prepared statement is closed in either case.
9b67f46… drh 2653 */
71439dc… drh 2654 static int diskusedStmtFinish(DiskUsed *p, int rc, sqlite3_stmt *pStmt){
9b67f46… drh 2655 if( rc==SQLITE_DONE ){
9b67f46… drh 2656 rc = SQLITE_OK;
9b67f46… drh 2657 }
9b67f46… drh 2658 if( rc!=SQLITE_OK || (rc = sqlite3_reset(pStmt))!=SQLITE_OK ){
71439dc… drh 2659 diskusedError(p, "SQL run-time error: %s\nOriginal SQL: %s",
9b67f46… drh 2660 sqlite3_errmsg(p->db), sqlite3_sql(pStmt));
71439dc… drh 2661 diskusedReset(p);
9b67f46… drh 2662 }
9b67f46… drh 2663 sqlite3_finalize(pStmt);
9b67f46… drh 2664 return rc;
9b67f46… drh 2665 }
9b67f46… drh 2666
9b67f46… drh 2667 /*
9b67f46… drh 2668 ** Run SQL. Return the number of errors.
9b67f46… drh 2669 */
71439dc… drh 2670 static int diskusedSql(DiskUsed *p, const char *zFormat, ...){
9b67f46… drh 2671 va_list ap;
9b67f46… drh 2672 int rc;
9b67f46… drh 2673 sqlite3_stmt *pStmt = 0;
9b67f46… drh 2674 va_start(ap, zFormat);
71439dc… drh 2675 pStmt = diskusedVPrep(p,zFormat,ap);
9b67f46… drh 2676 va_end(ap);
9b67f46… drh 2677 if( pStmt==0 ) return 1;
9b67f46… drh 2678 while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){}
9b67f46… drh 2679 if( rc==SQLITE_DONE ){
9b67f46… drh 2680 rc = SQLITE_OK;
9b67f46… drh 2681 }else{
71439dc… drh 2682 diskusedError(p, "SQL run-time error: %s\nOriginal SQL: %s",
9b67f46… drh 2683 sqlite3_errmsg(p->db), sqlite3_sql(pStmt));
71439dc… drh 2684 diskusedReset(p);
9b67f46… drh 2685 }
9b67f46… drh 2686 sqlite3_finalize(pStmt);
9b67f46… drh 2687 return rc;
9b67f46… drh 2688 }
9b67f46… drh 2689
9b67f46… drh 2690 /*
9b67f46… drh 2691 ** Run an SQL query that returns an integer. Write that integer
9b67f46… drh 2692 ** into *piRes. Return the number of errors.
9b67f46… drh 2693 */
71439dc… drh 2694 static int diskusedSqlInt(
71439dc… drh 2695 DiskUsed *p,
9b67f46… drh 2696 sqlite3_int64 *piRes,
9b67f46… drh 2697 const char *zFormat, ...
9b67f46… drh 2698 ){
9b67f46… drh 2699 va_list ap;
9b67f46… drh 2700 int rc;
9b67f46… drh 2701 sqlite3_stmt *pStmt = 0;
9b67f46… drh 2702 va_start(ap, zFormat);
71439dc… drh 2703 pStmt = diskusedVPrep(p,zFormat,ap);
9b67f46… drh 2704 va_end(ap);
9b67f46… drh 2705 if( pStmt==0 ) return 1;
9b67f46… drh 2706 rc = sqlite3_step(pStmt);
9b67f46… drh 2707 if( rc==SQLITE_ROW ){
9b67f46… drh 2708 *piRes = sqlite3_column_int64(pStmt, 0);
9b67f46… drh 2709 rc = SQLITE_OK;
9b67f46… drh 2710 }else if( rc==SQLITE_DONE ){
9b67f46… drh 2711 rc = SQLITE_OK;
9b67f46… drh 2712 }else{
9b67f46… drh 2713 if( p->db ){
9b67f46… drh 2714 /* p->db is NULL if there was some prior error */
71439dc… drh 2715 diskusedError(p, "SQL run-time error: %s\nOriginal SQL: %s",
9b67f46… drh 2716 sqlite3_errmsg(p->db), sqlite3_sql(pStmt));
9b67f46… drh 2717 }
71439dc… drh 2718 diskusedReset(p);
9b67f46… drh 2719 }
9b67f46… drh 2720 sqlite3_finalize(pStmt);
9b67f46… drh 2721 return rc;
9b67f46… drh 2722 }
9b67f46… drh 2723
9b67f46… drh 2724 /*
9b67f46… drh 2725 ** Add to the output a title line that contains the text determined
9b67f46… drh 2726 ** by the format string. If the output is initially empty, begin
9b67f46… drh 2727 ** the title line with "/" so that it forms the beginning of a C-style
9b67f46… drh 2728 ** comment. Otherwise begin with a new-line. Always finish with a
9b67f46… drh 2729 ** newline.
9b67f46… drh 2730 */
71439dc… drh 2731 static void diskusedTitle(DiskUsed *p, const char *zFormat, ...){
9b67f46… drh 2732 char *zFirst;
9b67f46… drh 2733 char *zTitle;
9b67f46… drh 2734 size_t nTitle;
9b67f46… drh 2735 va_list ap;
9b67f46… drh 2736 va_start(ap, zFormat);
9b67f46… drh 2737 zTitle = sqlite3_vmprintf(zFormat, ap);
9b67f46… drh 2738 va_end(ap);
9b67f46… drh 2739 if( zTitle==0 ){
71439dc… drh 2740 diskusedError(p, 0);
9b67f46… drh 2741 return;
9b67f46… drh 2742 }
9b67f46… drh 2743 zFirst = sqlite3_str_length(p->pOut)==0 ? "/" : "\n*";
9b67f46… drh 2744 nTitle = strlen(zTitle);
9b67f46… drh 2745 if( nTitle>=75 ){
9b67f46… drh 2746 sqlite3_str_appendf(p->pOut, "%s** %z\n\n", zFirst, zTitle);
9b67f46… drh 2747 }else{
9b67f46… drh 2748 int nExtra = 74 - (int)nTitle;
9b67f46… drh 2749 sqlite3_str_appendf(p->pOut, "%s** %z %.*c\n\n", zFirst, zTitle,
9b67f46… drh 2750 nExtra, '*');
9b67f46… drh 2751 }
9b67f46… drh 2752 }
9b67f46… drh 2753
9b67f46… drh 2754 /*
9b67f46… drh 2755 ** Add an output line that begins with the zDesc text extended out to
9b67f46… drh 2756 ** 50 columns with "." characters, and followed by whatever text is
9b67f46… drh 2757 ** described by zFormat.
9b67f46… drh 2758 */
71439dc… drh 2759 static void diskusedLine(
71439dc… drh 2760 DiskUsed *p, /* DiskUsed context */
9b67f46… drh 2761 const char *zDesc, /* Description */
9b67f46… drh 2762 const char *zFormat, /* Argument to the description */
9b67f46… drh 2763 ...
9b67f46… drh 2764 ){
9b67f46… drh 2765 char *zTxt;
9b67f46… drh 2766 size_t nDesc;
9b67f46… drh 2767 va_list ap;
9b67f46… drh 2768 va_start(ap, zFormat);
9b67f46… drh 2769 zTxt = sqlite3_vmprintf(zFormat, ap);
9b67f46… drh 2770 va_end(ap);
9b67f46… drh 2771 if( zTxt==0 ){
71439dc… drh 2772 diskusedError(p, 0);
9b67f46… drh 2773 return;
9b67f46… drh 2774 }
71439dc… drh 2775 nDesc = zDesc ? strlen(zDesc) : 0;
9b67f46… drh 2776 if( nDesc>=50 ){
9b67f46… drh 2777 sqlite3_str_appendf(p->pOut, "%s %z", zDesc, zTxt);
9b67f46… drh 2778 }else{
9b67f46… drh 2779 int nExtra = 50 - (int)nDesc;
9b67f46… drh 2780 sqlite3_str_appendf(p->pOut, "%s%.*c %z", zDesc, nExtra, '.', zTxt);
9b67f46… drh 2781 }
9b67f46… drh 2782 }
9b67f46… drh 2783
9b67f46… drh 2784 /*
9b67f46… drh 2785 ** Write a percentage into the output. The number written should show
9b67f46… drh 2786 ** two or three significant digits, with the decimal point being the fourth
9b67f46… drh 2787 ** character.
9b67f46… drh 2788 */
1ec45d0… drh 2789 static void diskusedPercent(
1ec45d0… drh 2790 DiskUsed *p, /* Context of the disk-usage analysis */
1ec45d0… drh 2791 sqlite3_int64 num, /* Numerator of the fraction */
1ec45d0… drh 2792 sqlite3_int64 denom /* Denominator of the fraction. Might be zero! */
1ec45d0… drh 2793 ){
9b67f46… drh 2794 char zNum[100];
9b67f46… drh 2795 char *zDP;
9b67f46… drh 2796 int nLeadingDigit;
9b67f46… drh 2797 int sz;
1ec45d0… drh 2798 double r;
1ec45d0… drh 2799 if( num==0 ){
1ec45d0… drh 2800 r = 0.0;
1ec45d0… drh 2801 }else if( denom==0 ){
1ec45d0… drh 2802 sqlite3_str_appendchar(p->pOut, 1, '\n');
1ec45d0… drh 2803 return;
1ec45d0… drh 2804 }else{
1ec45d0… drh 2805 r = num*100.0/(double)denom;
1ec45d0… drh 2806 }
e66a8c7… drh 2807 if( r>0.0 && r<0.0001 ){
e66a8c7… drh 2808 /* Avoid exponential notation for very small percentages */
e66a8c7… drh 2809 sqlite3_snprintf(sizeof(zNum)-5, zNum, "<0.0001");
e66a8c7… drh 2810 }else{
e66a8c7… drh 2811 sqlite3_snprintf(sizeof(zNum)-5, zNum, r>=10.0 ? "%.3g" :"%.2g", r);
e66a8c7… drh 2812 }
9b67f46… drh 2813 sz = (int)strlen(zNum);
9b67f46… drh 2814 zDP = strchr(zNum, '.');
9b67f46… drh 2815 if( zDP==0 ){
9b67f46… drh 2816 memcpy(zNum+sz,".0",3);
9b67f46… drh 2817 nLeadingDigit = sz;
9b67f46… drh 2818 sz += 2;
9b67f46… drh 2819 }else{
9b67f46… drh 2820 nLeadingDigit = (int)(zDP - zNum);
9b67f46… drh 2821 }
9b67f46… drh 2822 if( nLeadingDigit<3 ){
9b67f46… drh 2823 sqlite3_str_appendchar(p->pOut, 3-nLeadingDigit, ' ');
9b67f46… drh 2824 }
9b67f46… drh 2825 sqlite3_str_append(p->pOut, zNum, sz);
9b67f46… drh 2826 sqlite3_str_append(p->pOut, "%\n", 2);
9b67f46… drh 2827 }
9b67f46… drh 2828
9b67f46… drh 2829 /*
9b67f46… drh 2830 ** Create a subreport on a subset of tables and/or indexes.
9b67f46… drh 2831 **
9b67f46… drh 2832 ** The title if the subreport is given by zTitle. zWhere is
9b67f46… drh 2833 ** a boolean expression that can go in the WHERE clause to select
9b67f46… drh 2834 ** the relevant rows of the s.zSU table.
9b67f46… drh 2835 */
71439dc… drh 2836 static int diskusedSubreport(
71439dc… drh 2837 DiskUsed *p, /* DiskUsed context */
9b67f46… drh 2838 char *zTitle, /* Title for this subreport */
9b67f46… drh 2839 char *zWhere, /* WHERE clause for this subreport */
9b67f46… drh 2840 sqlite3_int64 pgsz, /* Database page size */
9b67f46… drh 2841 sqlite3_int64 nPage /* Number of pages in entire database */
9b67f46… drh 2842 ){
9b67f46… drh 2843 sqlite3_stmt *pStmt; /* Statement to query p->zSU */
9b67f46… drh 2844 sqlite3_int64 nentry; /* Number of btree entires */
9b67f46… drh 2845 sqlite3_int64 payload; /* Payload in bytes */
9b67f46… drh 2846 sqlite3_int64 ovfl_payload; /* overflow payload in bytes */
9b67f46… drh 2847 sqlite3_int64 mx_payload; /* largest individual payload */
9b67f46… drh 2848 sqlite3_int64 ovfl_cnt; /* Number entries using overflow */
9b67f46… drh 2849 sqlite3_int64 leaf_pages; /* Leaf pages */
9b67f46… drh 2850 sqlite3_int64 int_pages; /* internal pages */
9b67f46… drh 2851 sqlite3_int64 ovfl_pages; /* overflow pages */
9b67f46… drh 2852 sqlite3_int64 leaf_unused; /* unused bytes on leaf pages */
9b67f46… drh 2853 sqlite3_int64 int_unused; /* unused bytes on internal pages */
9b67f46… drh 2854 sqlite3_int64 ovfl_unused; /* unused bytes on overflow pages */
9b67f46… drh 2855 sqlite3_int64 int_cell; /* B-tree entries on internal pages */
9b67f46… drh 2856 sqlite3_int64 depth; /* btree depth */
9b67f46… drh 2857 sqlite3_int64 cnt; /* Number of s.zSU entries that match */
9b67f46… drh 2858 sqlite3_int64 storage; /* Total bytes */
9b67f46… drh 2859 sqlite3_int64 total_pages; /* Total page count */
9b67f46… drh 2860 sqlite3_int64 total_unused; /* Total unused bytes */
9b67f46… drh 2861 sqlite3_int64 total_meta; /* Total metadata */
9b67f46… drh 2862 int rc;
9b67f46… drh 2863
9b67f46… drh 2864 if( zTitle==0 || zWhere==0 ){
71439dc… drh 2865 diskusedError(p, 0);
9b67f46… drh 2866 return SQLITE_NOMEM;
9b67f46… drh 2867 }
71439dc… drh 2868 pStmt = diskusedPrepare(p,
9b67f46… drh 2869 "SELECT\n"
9b67f46… drh 2870 " sum(if(is_without_rowid OR is_index,nentry,leaf_entries)),\n" /* 0 */
9b67f46… drh 2871 " sum(payload),\n" /* 1 */
9b67f46… drh 2872 " sum(ovfl_payload),\n" /* 2 */
9b67f46… drh 2873 " max(mx_payload),\n" /* 3 */
9b67f46… drh 2874 " sum(ovfl_cnt),\n" /* 4 */
9b67f46… drh 2875 " sum(leaf_pages),\n" /* 5 */
9b67f46… drh 2876 " sum(int_pages),\n" /* 6 */
9b67f46… drh 2877 " sum(ovfl_pages),\n" /* 7 */
9b67f46… drh 2878 " sum(leaf_unused),\n" /* 8 */
9b67f46… drh 2879 " sum(int_unused),\n" /* 9 */
9b67f46… drh 2880 " sum(ovfl_unused),\n" /* 10 */
9b67f46… drh 2881 " max(depth),\n" /* 11 */
9b67f46… drh 2882 " count(*),\n" /* 12 */
9b67f46… drh 2883 " sum(int_entries)\n" /* 13 */
9b67f46… drh 2884 " FROM temp.%s WHERE %s",
9b67f46… drh 2885 p->zSU, zWhere);
9b67f46… drh 2886 if( pStmt==0 ) return 1;
9b67f46… drh 2887 rc = sqlite3_step(pStmt);
9b67f46… drh 2888 if( rc==SQLITE_ROW ){
71439dc… drh 2889 diskusedTitle(p, "%s", zTitle);
9b67f46… drh 2890
9b67f46… drh 2891 nentry = sqlite3_column_int64(pStmt, 0);
9b67f46… drh 2892 payload = sqlite3_column_int64(pStmt, 1);
9b67f46… drh 2893 ovfl_payload = sqlite3_column_int64(pStmt, 2);
9b67f46… drh 2894 mx_payload = sqlite3_column_int64(pStmt, 3);
9b67f46… drh 2895 ovfl_cnt = sqlite3_column_int64(pStmt, 4);
9b67f46… drh 2896 leaf_pages = sqlite3_column_int64(pStmt, 5);
9b67f46… drh 2897 int_pages = sqlite3_column_int64(pStmt, 6);
9b67f46… drh 2898 ovfl_pages = sqlite3_column_int64(pStmt, 7);
9b67f46… drh 2899 leaf_unused = sqlite3_column_int64(pStmt, 8);
9b67f46… drh 2900 int_unused = sqlite3_column_int64(pStmt, 9);
9b67f46… drh 2901 ovfl_unused = sqlite3_column_int64(pStmt, 10);
9b67f46… drh 2902 depth = sqlite3_column_int64(pStmt, 11);
9b67f46… drh 2903 cnt = sqlite3_column_int64(pStmt, 12);
9b67f46… drh 2904 int_cell = sqlite3_column_int64(pStmt, 13);
9b67f46… drh 2905 rc = SQLITE_DONE;
9b67f46… drh 2906
9b67f46… drh 2907 total_pages = leaf_pages + int_pages + ovfl_pages;
71439dc… drh 2908 diskusedLine(p, "Percentage of total database", "%.3g%%\n",
9b67f46… drh 2909 (total_pages*100.0)/(double)nPage);
71439dc… drh 2910 diskusedLine(p, "Number of entries", "%lld\n", nentry);
9b67f46… drh 2911 storage = total_pages*pgsz;
71439dc… drh 2912 diskusedLine(p, "Bytes of storage consumed", "%lld\n", storage);
71439dc… drh 2913 diskusedLine(p, "Bytes of payload", "%-11lld ", payload);
1ec45d0… drh 2914 diskusedPercent(p, payload, storage);
9b67f46… drh 2915 if( ovfl_cnt>0 ){
71439dc… drh 2916 diskusedLine(p, "Bytes of payload in overflow","%-11lld ",ovfl_payload);
1ec45d0… drh 2917 diskusedPercent(p, ovfl_payload, payload);
9b67f46… drh 2918 }
9b67f46… drh 2919 total_unused = leaf_unused + int_unused + ovfl_unused;
9b67f46… drh 2920 total_meta = storage - payload - total_unused;
71439dc… drh 2921 diskusedLine(p, "Bytes of metadata","%-11lld ", total_meta);
1ec45d0… drh 2922 diskusedPercent(p, total_meta, storage);
9b67f46… drh 2923 if( cnt==1 ){
71439dc… drh 2924 diskusedLine(p, "B-tree depth", "%lld\n", depth);
9b67f46… drh 2925 if( int_cell>1 ){
71439dc… drh 2926 diskusedLine(p, "Average fanout", "%.1f\n",
9b67f46… drh 2927 (double)(int_cell+int_pages)/(double)int_pages);
9b67f46… drh 2928 }
9b67f46… drh 2929 }
9b67f46… drh 2930 if( nentry>0 ){
71439dc… drh 2931 diskusedLine(p, "Average payload per entry", "%.1f\n",
9b67f46… drh 2932 (double)payload/(double)nentry);
71439dc… drh 2933 diskusedLine(p, "Average unused bytes per entry", "%.1f\n",
9b67f46… drh 2934 (double)total_unused/(double)nentry);
71439dc… drh 2935 diskusedLine(p, "Average metadata per entry", "%.1f\n",
9b67f46… drh 2936 (double)total_meta/(double)nentry);
9b67f46… drh 2937 }
71439dc… drh 2938 diskusedLine(p, "Maximum single-entry payload", "%lld\n", mx_payload);
71439dc… drh 2939 if( nentry>0 ){
71439dc… drh 2940 diskusedLine(p, "Entries that use overflow", "%-11lld ", ovfl_cnt);
1ec45d0… drh 2941 diskusedPercent(p, ovfl_cnt, nentry);
71439dc… drh 2942 }
71439dc… drh 2943 if( int_pages>0 ){
71439dc… drh 2944 diskusedLine(p, "Index pages used", "%lld\n", int_pages);
71439dc… drh 2945 }
71439dc… drh 2946 diskusedLine(p, "Primary pages used", "%lld\n", leaf_pages);
71439dc… drh 2947 if( ovfl_cnt ){
71439dc… drh 2948 diskusedLine(p, "Overflow pages used", "%lld\n", ovfl_pages);
71439dc… drh 2949 }
71439dc… drh 2950 diskusedLine(p, "Total pages used", "%lld\n", total_pages);
71439dc… drh 2951 if( int_pages>0 ){
71439dc… drh 2952 diskusedLine(p, "Unused bytes on index pages", "%lld\n", int_unused);
71439dc… drh 2953 }
71439dc… drh 2954 diskusedLine(p, "Unused bytes on primary pages", "%lld\n", leaf_unused);
71439dc… drh 2955 if( ovfl_cnt ){
71439dc… drh 2956 diskusedLine(p, "Unused bytes on overflow pages", "%lld\n", ovfl_unused);
71439dc… drh 2957 }
71439dc… drh 2958 diskusedLine(p, "Unused bytes on all pages", "%-11lld ", total_unused);
1ec45d0… drh 2959 diskusedPercent(p, total_unused, storage);
71439dc… drh 2960 }
71439dc… drh 2961 return diskusedStmtFinish(p, rc, pStmt);
71439dc… drh 2962 }
71439dc… drh 2963
71439dc… drh 2964 /*
71439dc… drh 2965 ** SQL Function: diskused(SCHEMA)
9b67f46… drh 2966 **
9b67f46… drh 2967 ** Analyze the database schema named in the argument. Return text
71439dc… drh 2968 ** containing the space utilization stats.
9b67f46… drh 2969 */
71439dc… drh 2970 static void diskusedFunc(
9b67f46… drh 2971 sqlite3_context *context,
9b67f46… drh 2972 int argc,
9b67f46… drh 2973 sqlite3_value **argv
9b67f46… drh 2974 ){
9b67f46… drh 2975 int rc;
9b67f46… drh 2976 sqlite3_stmt *pStmt;
9b67f46… drh 2977 int n;
40c5397… drh 2978 char *z;
87881e8… drh 2979 sqlite3_int64 ii;
9b67f46… drh 2980 sqlite3_int64 pgsz;
9b67f46… drh 2981 sqlite3_int64 nPage;
9b67f46… drh 2982 sqlite3_int64 nPageInUse;
9b67f46… drh 2983 sqlite3_int64 nFreeList;
9b67f46… drh 2984 sqlite3_int64 nIndex;
9b67f46… drh 2985 sqlite3_int64 nWORowid;
71439dc… drh 2986 DiskUsed s;
9b67f46… drh 2987 sqlite3_uint64 r[2];
9b67f46… drh 2988
87881e8… drh 2989 (void)argc;
9b67f46… drh 2990 memset(&s, 0, sizeof(s));
9b67f46… drh 2991 s.db = sqlite3_context_db_handle(context);
9b67f46… drh 2992 s.context = context;
9b67f46… drh 2993 s.pOut = sqlite3_str_new(0);
9b67f46… drh 2994 if( sqlite3_str_errcode(s.pOut) ){
71439dc… drh 2995 diskusedError(&s, 0);
9b67f46… drh 2996 return;
9b67f46… drh 2997 }
9b67f46… drh 2998 s.zSchema = (const char*)sqlite3_value_text(argv[0]);
9b67f46… drh 2999 if( s.zSchema==0 ){
9b67f46… drh 3000 s.zSchema = "main";
9b67f46… drh 3001 }else if( sqlite3_strlike("temp",s.zSchema,0)==0 ){
71439dc… drh 3002 diskusedReset(&s);
9b67f46… drh 3003 sqlite3_result_text(context, "cannot analyze \"temp\"",-1,SQLITE_STATIC);
9b67f46… drh 3004 return;
9b67f46… drh 3005 }
87881e8… drh 3006 ii = 0;
71439dc… drh 3007 rc = diskusedSqlInt(&s,&ii,"SELECT 1 FROM pragma_database_list"
9b67f46… drh 3008 " WHERE name=%Q COLLATE nocase",s.zSchema);
87881e8… drh 3009 if( rc || ii==0 ){
71439dc… drh 3010 diskusedReset(&s);
9b67f46… drh 3011 sqlite3_result_text(context,"no such database",-1,SQLITE_STATIC);
9b67f46… drh 3012 return;
9b67f46… drh 3013 }
9b67f46… drh 3014 sqlite3_randomness(sizeof(r), &r);
71439dc… drh 3015 s.zSU = sqlite3_mprintf("diskused%016llx%016llx", r[0], r[1]);
71439dc… drh 3016 if( s.zSU==0 ){ diskusedError(&s, 0); return; }
9b67f46… drh 3017
9b67f46… drh 3018 /* The s.zSU table contains the data used for the analysis.
9b67f46… drh 3019 ** The table name contains 128-bits of randomness to avoid
9b67f46… drh 3020 ** collisions with preexisting tables in temp.
9b67f46… drh 3021 */
71439dc… drh 3022 rc = diskusedSql(&s,
9b67f46… drh 3023 "CREATE TABLE temp.%s(\n"
9b67f46… drh 3024 " name text, -- A table or index\n"
9b67f46… drh 3025 " tblname text, -- Table that owns name\n"
9b67f46… drh 3026 " is_index boolean, -- TRUE if it is an index\n"
9b67f46… drh 3027 " is_without_rowid boolean, -- TRUE if WITHOUT ROWID table\n"
9b67f46… drh 3028 " nentry int, -- Number of entries in the BTree\n"
9b67f46… drh 3029 " leaf_entries int, -- Number of leaf entries\n"
9b67f46… drh 3030 " depth int, -- Depth of the b-tree\n"
9b67f46… drh 3031 " payload int, -- Total data stored in this table/index\n"
9b67f46… drh 3032 " ovfl_payload int, -- Total data stored on overflow pages\n"
9b67f46… drh 3033 " ovfl_cnt int, -- Number of entries that use overflow\n"
9b67f46… drh 3034 " mx_payload int, -- Maximum payload size\n"
9b67f46… drh 3035 " int_pages int, -- Interior pages used\n"
9b67f46… drh 3036 " leaf_pages int, -- Leaf pages used\n"
9b67f46… drh 3037 " ovfl_pages int, -- Overflow pages used\n"
9b67f46… drh 3038 " int_unused int, -- Unused bytes on interior pages\n"
9b67f46… drh 3039 " leaf_unused int, -- Unused bytes on primary pages\n"
9b67f46… drh 3040 " ovfl_unused int, -- Unused bytes on overflow pages\n"
9b67f46… drh 3041 " int_entries int -- Btree cells on internal pages\n"
9b67f46… drh 3042 ");",
9b67f46… drh 3043 s.zSU
9b67f46… drh 3044 );
9b67f46… drh 3045 if( rc ) return;
9b67f46… drh 3046
9b67f46… drh 3047 /* Populate the s.zSU table
9b67f46… drh 3048 */
71439dc… drh 3049 rc = diskusedSql(&s,
9b67f46… drh 3050 "WITH\n"
9b67f46… drh 3051 " allidx(idxname) AS (\n"
9b67f46… drh 3052 " SELECT name FROM \"%w\".sqlite_schema WHERE type='index'\n"
9b67f46… drh 3053 " ),\n"
9b67f46… drh 3054 " allobj(allname,tblname,isidx,isworowid) AS (\n"
9b67f46… drh 3055 " SELECT 'sqlite_schema',\n"
9b67f46… drh 3056 " 'sqlite_schema',\n"
9b67f46… drh 3057 " 0,\n"
9b67f46… drh 3058 " 0\n"
9b67f46… drh 3059 " UNION ALL\n"
9b67f46… drh 3060 " SELECT name,\n"
9b67f46… drh 3061 " tbl_name,\n"
9b67f46… drh 3062 " type='index',\n"
9b67f46… drh 3063 " EXISTS(SELECT 1\n"
9b67f46… drh 3064 " FROM pragma_index_list(sqlite_schema.name,%Q)\n"
9b67f46… drh 3065 " WHERE pragma_index_list.origin='pk'\n"
9b67f46… drh 3066 " AND pragma_index_list.name NOT IN allidx)\n"
9b67f46… drh 3067 " FROM \"%w\".sqlite_schema\n"
9b67f46… drh 3068 " )\n"
9b67f46… drh 3069 "INSERT INTO temp.%s\n"
9b67f46… drh 3070 " SELECT\n"
9b67f46… drh 3071 " allname,\n"
9b67f46… drh 3072 " tblname,\n"
9b67f46… drh 3073 " isidx,\n"
9b67f46… drh 3074 " isworowid,\n"
9b67f46… drh 3075 " sum(ncell),\n"
9b67f46… drh 3076 " sum((pagetype='leaf')*ncell),\n"
9b67f46… drh 3077 " max((length(if(path GLOB '*+*','',path))+3)/4),\n"
9b67f46… drh 3078 " sum(payload),\n"
9b67f46… drh 3079 " sum((pagetype='overflow')*payload),\n"
9b67f46… drh 3080 " sum(path GLOB '*+000000'),\n"
9b67f46… drh 3081 " max(mx_payload),\n"
9b67f46… drh 3082 " sum(pagetype='internal'),\n"
9b67f46… drh 3083 " sum(pagetype='leaf'),\n"
9b67f46… drh 3084 " sum(pagetype='overflow'),\n"
9b67f46… drh 3085 " sum((pagetype='internal')*unused),\n"
9b67f46… drh 3086 " sum((pagetype='leaf')*unused),\n"
9b67f46… drh 3087 " sum((pagetype='overflow')*unused),\n"
9b67f46… drh 3088 " sum(if(pagetype='internal',ncell))\n"
9b67f46… drh 3089 " FROM allobj CROSS JOIN dbstat(%Q) \n"
9b67f46… drh 3090 " WHERE dbstat.name=allobj.allname\n"
9b67f46… drh 3091 " GROUP BY allname;\n",
9b67f46… drh 3092 s.zSchema, /* %w.sqlite_schema -- in allidx */
9b67f46… drh 3093 s.zSchema, /* pragma_index_list(...,%Q) */
9b67f46… drh 3094 s.zSchema, /* %w.sqlite_schema */
9b67f46… drh 3095 s.zSU, /* INTO temp.%s */
9b67f46… drh 3096 s.zSchema /* JOIN dbstat(%Q) */
9b67f46… drh 3097 );
9b67f46… drh 3098 if( rc ) return;
9b67f46… drh 3099
9b67f46… drh 3100 nPage = 0;
71439dc… drh 3101 rc = diskusedSqlInt(&s, &nPage, "PRAGMA \"%w\".page_count", s.zSchema);
9b67f46… drh 3102 if( rc ) return;
9b67f46… drh 3103 if( nPage<=0 ){
9b67f46… drh 3104 /* Very brief reply for an empty database */
71439dc… drh 3105 diskusedReset(&s);
9b67f46… drh 3106 sqlite3_result_text(context, "empty database", -1, SQLITE_STATIC);
9b67f46… drh 3107 return;
9b67f46… drh 3108 }
9b67f46… drh 3109
9b67f46… drh 3110 /* Begin generating the report */
71439dc… drh 3111 diskusedTitle(&s, "Database storage utilization report");
9b67f46… drh 3112 pgsz = 0;
71439dc… drh 3113 rc = diskusedSqlInt(&s, &pgsz, "PRAGMA \"%w\".page_size", s.zSchema);
9b67f46… drh 3114 if( rc ) return;
71439dc… drh 3115 diskusedLine(&s, "Page size in bytes","%lld\n",pgsz);
71439dc… drh 3116 diskusedLine(&s, "Pages in the database", "%lld\n", nPage);
9b67f46… drh 3117
9b67f46… drh 3118 nPageInUse = 0;
71439dc… drh 3119 rc = diskusedSqlInt(&s, &nPageInUse,
9b67f46… drh 3120 "SELECT sum(leaf_pages+int_pages+ovfl_pages) FROM temp.%s", s.zSU);
9b67f46… drh 3121 if( rc ) return;
71439dc… drh 3122 diskusedLine(&s, "Pages that store data", "%-11lld ", nPageInUse);
1ec45d0… drh 3123 diskusedPercent(&s, nPageInUse, nPage);
9b67f46… drh 3124
9b67f46… drh 3125 nFreeList = 0;
71439dc… drh 3126 rc = diskusedSqlInt(&s, &nFreeList, "PRAGMA \"%w\".freelist_count",s.zSchema);
87881e8… drh 3127 if( rc ) return;
71439dc… drh 3128 diskusedLine(&s, "Pages on the freelist", "%-11lld ", nFreeList);
1ec45d0… drh 3129 diskusedPercent(&s, nFreeList, nPage);
87881e8… drh 3130
87881e8… drh 3131 ii = 0;
71439dc… drh 3132 rc = diskusedSqlInt(&s, &ii, "PRAGMA \"%w\".auto_vacuum", s.zSchema);
87881e8… drh 3133 if( rc ) return;
87881e8… drh 3134 if( ii==0 || nPage<=1 ){
87881e8… drh 3135 ii = 0;
9b67f46… drh 3136 }else{
9b67f46… drh 3137 double rPtrsPerPage = pgsz/5;
9b67f46… drh 3138 double rAvPage = (nPage-1.0)/(rPtrsPerPage+1.0);
87881e8… drh 3139 ii = (sqlite3_int64)ceil(rAvPage);
9b67f46… drh 3140 }
71439dc… drh 3141 diskusedLine(&s, "Pages of auto-vacuum overhead", "%-11lld ", ii);
1ec45d0… drh 3142 diskusedPercent(&s, ii, nPage);
9b67f46… drh 3143
87881e8… drh 3144 ii = 0;
71439dc… drh 3145 rc = diskusedSqlInt(&s, &ii,
9b67f46… drh 3146 "SELECT count(*)+1 FROM \"%w\".sqlite_schema WHERE type='table'",
9b67f46… drh 3147 s.zSchema);
9b67f46… drh 3148 if( rc ) return;
71439dc… drh 3149 diskusedLine(&s, "Number of tables", "%lld\n", ii);
9b67f46… drh 3150 nWORowid = 0;
71439dc… drh 3151 rc = diskusedSqlInt(&s, &nWORowid,
9b67f46… drh 3152 "SELECT count(*) FROM \"%w\".pragma_table_list WHERE wr",
9b67f46… drh 3153 s.zSchema);
9b67f46… drh 3154 if( rc ) return;
9b67f46… drh 3155 if( nWORowid>0 ){
71439dc… drh 3156 diskusedLine(&s, "Number of WITHOUT ROWID tables", "%lld\n", nWORowid);
71439dc… drh 3157 diskusedLine(&s, "Number of rowid tables", "%lld\n", ii - nWORowid);
9b67f46… drh 3158 }
9b67f46… drh 3159 nIndex = 0;
71439dc… drh 3160 rc = diskusedSqlInt(&s, &nIndex,
9b67f46… drh 3161 "SELECT count(*) FROM \"%w\".sqlite_schema WHERE type='index'",
9b67f46… drh 3162 s.zSchema);
9b67f46… drh 3163 if( rc ) return;
71439dc… drh 3164 diskusedLine(&s, "Number of indexes", "%lld\n", nIndex);
87881e8… drh 3165 ii = 0;
71439dc… drh 3166 rc = diskusedSqlInt(&s, &ii,
9b67f46… drh 3167 "SELECT count(*) FROM \"%w\".sqlite_schema"
9b67f46… drh 3168 " WHERE name GLOB 'sqlite_autoindex_*' AND type='index'",
9b67f46… drh 3169 s.zSchema);
9b67f46… drh 3170 if( rc ) return;
71439dc… drh 3171 diskusedLine(&s, "Number of defined indexes", "%lld\n", nIndex - ii);
71439dc… drh 3172 diskusedLine(&s, "Number of implied indexes", "%lld\n", ii);
71439dc… drh 3173 diskusedLine(&s, "Size of the database in bytes", "%lld\n", pgsz*nPage);
87881e8… drh 3174 ii = 0;
71439dc… drh 3175 rc = diskusedSqlInt(&s, &ii,
9b67f46… drh 3176 "SELECT sum(payload) FROM temp.%s"
9b67f46… drh 3177 " WHERE NOT is_index AND name NOT LIKE 'sqlite_schema'",
9b67f46… drh 3178 s.zSU);
9b67f46… drh 3179 if( rc ) return;
71439dc… drh 3180 diskusedLine(&s, "Bytes of payload", "%-11lld ", ii);
1ec45d0… drh 3181 diskusedPercent(&s, ii, pgsz*nPage);
9b67f46… drh 3182
71439dc… drh 3183 diskusedTitle(&s, "Page counts for all tables with their indexes");
71439dc… drh 3184 pStmt = diskusedPrepare(&s,
9b67f46… drh 3185 "SELECT upper(tblname),\n"
9b67f46… drh 3186 " sum(int_pages+leaf_pages+ovfl_pages)\n"
9b67f46… drh 3187 " FROM temp.%s\n"
71439dc… drh 3188 " WHERE tblname IS NOT NULL\n"
71439dc… drh 3189 " GROUP BY 1\n"
71439dc… drh 3190 " ORDER BY 2 DESC, 1;",
71439dc… drh 3191 s.zSU);
71439dc… drh 3192 if( pStmt==0 ) return;
71439dc… drh 3193 while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){
71439dc… drh 3194 sqlite3_int64 nn = sqlite3_column_int64(pStmt,1);
71439dc… drh 3195 diskusedLine(&s, (const char*)sqlite3_column_text(pStmt,0), "%-11lld ", nn);
1ec45d0… drh 3196 diskusedPercent(&s, nn, nPage);
71439dc… drh 3197 }
71439dc… drh 3198 if( diskusedStmtFinish(&s, rc, pStmt) ) return;
71439dc… drh 3199
71439dc… drh 3200 diskusedTitle(&s, "Page counts for all tables and indexes separately");
71439dc… drh 3201 pStmt = diskusedPrepare(&s,
71439dc… drh 3202 "SELECT upper(name),\n"
71439dc… drh 3203 " sum(int_pages+leaf_pages+ovfl_pages)\n"
71439dc… drh 3204 " FROM temp.%s\n"
71439dc… drh 3205 " WHERE name IS NOT NULL\n"
9b67f46… drh 3206 " GROUP BY 1\n"
9b67f46… drh 3207 " ORDER BY 2 DESC, 1;",
9b67f46… drh 3208 s.zSU);
9b67f46… drh 3209 if( pStmt==0 ) return;
9b67f46… drh 3210 while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){
9b67f46… drh 3211 sqlite3_int64 nn = sqlite3_column_int64(pStmt,1);
71439dc… drh 3212 diskusedLine(&s, (const char*)sqlite3_column_text(pStmt,0), "%-11lld ", nn);
1ec45d0… drh 3213 diskusedPercent(&s, nn, nPage);
71439dc… drh 3214 }
71439dc… drh 3215 if( diskusedStmtFinish(&s, rc, pStmt) ) return;
71439dc… drh 3216
71439dc… drh 3217 rc = diskusedSubreport(&s, "All tables and indexes", "1", pgsz, nPage);
9b67f46… drh 3218 if( rc ) return;
71439dc… drh 3219 rc = diskusedSubreport(&s, "All tables", "NOT is_index", pgsz, nPage);
9b67f46… drh 3220 if( rc ) return;
9b67f46… drh 3221 if( nWORowid>0 ){
71439dc… drh 3222 rc = diskusedSubreport(&s, "All WITHOUT ROWID tables", "is_without_rowid",
9b67f46… drh 3223 pgsz, nPage);
9b67f46… drh 3224 if( rc ) return;
71439dc… drh 3225 rc = diskusedSubreport(&s, "All rowid tables",
9b67f46… drh 3226 "NOT is_without_rowid AND NOT is_index",
9b67f46… drh 3227 pgsz, nPage);
9b67f46… drh 3228 if( rc ) return;
9b67f46… drh 3229 }
71439dc… drh 3230 rc = diskusedSubreport(&s, "All indexes", "is_index", pgsz, nPage);
9b67f46… drh 3231 if( rc ) return;
9b67f46… drh 3232
71439dc… drh 3233 pStmt = diskusedPrepare(&s,
9b67f46… drh 3234 "SELECT upper(tblname), tblname, sum(is_index) FROM temp.%s"
9b67f46… drh 3235 " GROUP BY 1 ORDER BY 1",
9b67f46… drh 3236 s.zSU);
9b67f46… drh 3237 if( pStmt==0 ) return;
9b67f46… drh 3238 while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){
9b67f46… drh 3239 const char *zUpper = (const char*)sqlite3_column_text(pStmt, 0);
9b67f46… drh 3240 const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
9b67f46… drh 3241 int nSubIndex = sqlite3_column_int(pStmt, 2);
9b67f46… drh 3242 if( nSubIndex==0 ){
9b67f46… drh 3243 char *zTitle = sqlite3_mprintf("Table %s", zUpper);
9b67f46… drh 3244 char *zWhere = sqlite3_mprintf("name=%Q", zName);
71439dc… drh 3245 rc = diskusedSubreport(&s, zTitle, zWhere, pgsz, nPage);
9b67f46… drh 3246 sqlite3_free(zTitle);
9b67f46… drh 3247 sqlite3_free(zWhere);
9b67f46… drh 3248 if( rc ) break;
9b67f46… drh 3249 }else{
9b67f46… drh 3250 sqlite3_stmt *pS2;
9b67f46… drh 3251 char *zTitle = sqlite3_mprintf("Table %s and all its indexes", zUpper);
9b67f46… drh 3252 char *zWhere = sqlite3_mprintf("tblname=%Q", zName);
71439dc… drh 3253 rc = diskusedSubreport(&s, zTitle, zWhere, pgsz, nPage);
9b67f46… drh 3254 sqlite3_free(zTitle);
9b67f46… drh 3255 sqlite3_free(zWhere);
9b67f46… drh 3256 if( rc ) break;
9b67f46… drh 3257 zTitle = sqlite3_mprintf("Table %s w/o any indexes", zUpper);
9b67f46… drh 3258 zWhere = sqlite3_mprintf("name=%Q", zName);
71439dc… drh 3259 rc = diskusedSubreport(&s, zTitle, zWhere, pgsz, nPage);
9b67f46… drh 3260 sqlite3_free(zTitle);
9b67f46… drh 3261 sqlite3_free(zWhere);
9b67f46… drh 3262 if( rc ) break;
9b67f46… drh 3263 if( nSubIndex>1 ){
9b67f46… drh 3264 zTitle = sqlite3_mprintf("All indexes of table %s", zUpper);
9b67f46… drh 3265 zWhere = sqlite3_mprintf("tblname=%Q AND is_index", zName);
71439dc… drh 3266 rc = diskusedSubreport(&s, zTitle, zWhere, pgsz, nPage);
9b67f46… drh 3267 sqlite3_free(zTitle);
9b67f46… drh 3268 sqlite3_free(zWhere);
9b67f46… drh 3269 if( rc ) break;
9b67f46… drh 3270 }
71439dc… drh 3271 pS2 = diskusedPrepare(&s,
9b67f46… drh 3272 "SELECT name, upper(name) FROM temp.%s"
9b67f46… drh 3273 " WHERE is_index AND tblname=%Q",
9b67f46… drh 3274 s.zSU, zName);
9b67f46… drh 3275 if( pS2==0 ){
9b67f46… drh 3276 rc = SQLITE_NOMEM;
9b67f46… drh 3277 break;
9b67f46… drh 3278 }
9b67f46… drh 3279 while( (rc = sqlite3_step(pS2))==SQLITE_ROW ){
9b67f46… drh 3280 const char *zU = (const char*)sqlite3_column_text(pS2, 1);
9b67f46… drh 3281 const char *zN = (const char*)sqlite3_column_text(pS2, 0);
9b67f46… drh 3282 zTitle = sqlite3_mprintf("Index %s", zU);
9b67f46… drh 3283 zWhere = sqlite3_mprintf("name=%Q", zN);
71439dc… drh 3284 rc = diskusedSubreport(&s, zTitle, zWhere, pgsz, nPage);
9b67f46… drh 3285 sqlite3_free(zTitle);
9b67f46… drh 3286 sqlite3_free(zWhere);
9b67f46… drh 3287 if( rc ) break;
9b67f46… drh 3288 }
71439dc… drh 3289 rc = diskusedStmtFinish(&s, rc, pS2);
9b67f46… drh 3290 if( rc ) break;
9b67f46… drh 3291 }
9b67f46… drh 3292 }
71439dc… drh 3293 if( diskusedStmtFinish(&s, rc, pStmt) ) return;
9b67f46… drh 3294
9b67f46… drh 3295 /* Append SQL statements that will recreate the raw data used for
9b67f46… drh 3296 ** the analysis.
9b67f46… drh 3297 */
71439dc… drh 3298 diskusedTitle(&s, "Raw data used to generate this report");
9b67f46… drh 3299 sqlite3_str_appendf(s.pOut,
9b67f46… drh 3300 "The following SQL will create a table named \"space_used\" which\n"
9b67f46… drh 3301 "contains most of the information used to generate the report above.\n"
9b67f46… drh 3302 );
40c5397… drh 3303 z = sqlite3_str_value(s.pOut);
40c5397… drh 3304 while( z && (z = strstr(z,"*/"))!=0 ){ z[0] = '+'; }
9b67f46… drh 3305 sqlite3_str_appendf(s.pOut,
40c5397… drh 3306 "*/\n"
9b67f46… drh 3307 "BEGIN;\n"
9b67f46… drh 3308 "CREATE TABLE space_used(\n"
9b67f46… drh 3309 " name text, -- A table or index\n" /* 0 */
9b67f46… drh 3310 " tblname text, -- Table that owns name\n" /* 1 */
9b67f46… drh 3311 " is_index boolean, -- TRUE if it is an index\n" /* 2 */
9b67f46… drh 3312 " is_without_rowid boolean, -- TRUE if WITHOUT ROWID table\n" /* 3 */
9b67f46… drh 3313 " nentry int, -- Number of entries in the BTree\n" /* 4 */
9b67f46… drh 3314 " leaf_entries int, -- Number of leaf entries\n" /* 5 */
9b67f46… drh 3315 " depth int, -- Depth of the b-tree\n" /* 6 */
9b67f46… drh 3316 " payload int, -- Total data in this table/index\n" /* 7 */
9b67f46… drh 3317 " ovfl_payload int, -- Total data on overflow pages\n" /* 8 */
9b67f46… drh 3318 " ovfl_cnt int, -- Entries that use overflow\n" /* 9 */
9b67f46… drh 3319 " mx_payload int, -- Maximum payload size\n" /* 10 */
9b67f46… drh 3320 " int_pages int, -- Interior pages used\n" /* 11 */
9b67f46… drh 3321 " leaf_pages int, -- Leaf pages used\n" /* 12 */
9b67f46… drh 3322 " ovfl_pages int, -- Overflow pages used\n" /* 13 */
9b67f46… drh 3323 " int_unused int, -- Unused bytes on interior pages\n" /* 14 */
9b67f46… drh 3324 " leaf_unused int, -- Unused bytes on primary pages\n" /* 15 */
9b67f46… drh 3325 " ovfl_unused int, -- Unused bytes on overflow pages\n" /* 16 */
9b67f46… drh 3326 " int_entries int -- B-tree entries on internal pages\n"/* 17 */
9b67f46… drh 3327 ");\n"
9b67f46… drh 3328 "INSERT INTO space_used VALUES\n"
9b67f46… drh 3329 );
71439dc… drh 3330 pStmt = diskusedPrepare(&s,
9b67f46… drh 3331 "SELECT quote(name), quote(tblname),\n" /* 0..1 */
9b67f46… drh 3332 " is_index, is_without_rowid, nentry, leaf_entries,\n" /* 2..5 */
9b67f46… drh 3333 " depth, payload, ovfl_payload, ovfl_cnt, mx_payload,\n" /* 6..10 */
9b67f46… drh 3334 " int_pages, leaf_pages, ovfl_pages, int_unused,\n" /* 11..14 */
9b67f46… drh 3335 " leaf_unused, ovfl_unused, int_entries\n" /* 15..17 */
9b67f46… drh 3336 " FROM temp.%s;",
9b67f46… drh 3337 s.zSU);
9b67f46… drh 3338 if( pStmt==0 ) return;
9b67f46… drh 3339 n = 0;
9b67f46… drh 3340 while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){
9b67f46… drh 3341 if( n++ ) sqlite3_str_appendf(s.pOut,",\n");
9b67f46… drh 3342 sqlite3_str_appendf(s.pOut,
9b67f46… drh 3343 " (%s,%s,%lld,%lld,%lld,%lld,%lld,%lld,%lld,"
9b67f46… drh 3344 "%lld,%lld,%lld,%lld,%lld,%lld,%lld,%lld,%lld)",
9b67f46… drh 3345 sqlite3_column_text(pStmt, 0),
9b67f46… drh 3346 sqlite3_column_text(pStmt, 1),
9b67f46… drh 3347 sqlite3_column_int64(pStmt, 2),
9b67f46… drh 3348 sqlite3_column_int64(pStmt, 3),
9b67f46… drh 3349 sqlite3_column_int64(pStmt, 4),
9b67f46… drh 3350 sqlite3_column_int64(pStmt, 5),
9b67f46… drh 3351 sqlite3_column_int64(pStmt, 6),
9b67f46… drh 3352 sqlite3_column_int64(pStmt, 7),
9b67f46… drh 3353 sqlite3_column_int64(pStmt, 8),
9b67f46… drh 3354 sqlite3_column_int64(pStmt, 9),
9b67f46… drh 3355 sqlite3_column_int64(pStmt, 10),
9b67f46… drh 3356 sqlite3_column_int64(pStmt, 11),
9b67f46… drh 3357 sqlite3_column_int64(pStmt, 12),
9b67f46… drh 3358 sqlite3_column_int64(pStmt, 13),
9b67f46… drh 3359 sqlite3_column_int64(pStmt, 14),
9b67f46… drh 3360 sqlite3_column_int64(pStmt, 15),
9b67f46… drh 3361 sqlite3_column_int64(pStmt, 16),
9b67f46… drh 3362 sqlite3_column_int64(pStmt, 17));
9b67f46… drh 3363 }
9b67f46… drh 3364 if( rc!=SQLITE_DONE ){
71439dc… drh 3365 diskusedError(&s, "SQL run-time error: %s\nSQL: %s",
9b67f46… drh 3366 sqlite3_errmsg(s.db), sqlite3_sql(pStmt));
9b67f46… drh 3367 sqlite3_finalize(pStmt);
9b67f46… drh 3368 return;
9b67f46… drh 3369 }
9b67f46… drh 3370 sqlite3_str_appendf(s.pOut,";\nCOMMIT;");
9b67f46… drh 3371 sqlite3_finalize(pStmt);
9b67f46… drh 3372
9b67f46… drh 3373 if( sqlite3_str_length(s.pOut) ){
9b67f46… drh 3374 sqlite3_result_text(context, sqlite3_str_finish(s.pOut), -1,
9b67f46… drh 3375 sqlite3_free);
9b67f46… drh 3376 s.pOut = 0;
9b67f46… drh 3377 }
71439dc… drh 3378 diskusedReset(&s);
9b67f46… drh 3379 }
9b67f46… drh 3380
71439dc… drh 3381
71439dc… drh 3382 #ifdef _WIN32
71439dc… drh 3383
71439dc… drh 3384 #endif
71439dc… drh 3385 int sqlite3_diskused_init(
71439dc… drh 3386 sqlite3 *db,
71439dc… drh 3387 char **pzErrMsg,
71439dc… drh 3388 const sqlite3_api_routines *pApi
71439dc… drh 3389 ){
71439dc… drh 3390 int rc = SQLITE_OK;
71439dc… drh 3391 SQLITE_EXTENSION_INIT2(pApi);
71439dc… drh 3392 (void)pzErrMsg; /* Unused parameter */
71439dc… drh 3393 rc = sqlite3_create_function(db, "diskused", 1,
8594585… drh 3394 SQLITE_UTF8|SQLITE_DIRECTONLY,
71439dc… drh 3395 0, diskusedFunc, 0, 0);
71439dc… drh 3396 return rc;
71439dc… drh 3397 }
71439dc… drh 3398
71439dc… drh 3399 /************************* End ext/misc/diskused.c ********************/
ee87371… drh 3400 /************************* Begin ext/misc/strdup.c ******************/
ee87371… drh 3401 /*
ee87371… drh 3402 ** 2026-07-04
ee87371… drh 3403 **
ee87371… drh 3404 ** The author disclaims copyright to this source code. In place of
ee87371… drh 3405 ** a legal notice, here is a blessing:
ee87371… drh 3406 **
ee87371… drh 3407 ** May you do good and not evil.
ee87371… drh 3408 ** May you find forgiveness for yourself and forgive others.
ee87371… drh 3409 ** May you share freely, never taking more than you give.
ee87371… drh 3410 **
ee87371… drh 3411 ******************************************************************************
ee87371… drh 3412 **
ee87371… drh 3413 ** Since this module was written (coincidentally) on the 250th anniversary
ee87371… drh 3414 ** of the signing of the Declaration of Independence of The United States,
ee87371… drh 3415 ** it seems fitting to quote from that document:
ee87371… drh 3416 **
ee87371… drh 3417 ** We hold these truths to be self-evident, that all men are created
ee87371… drh 3418 ** equal, that they are endowed by their Creator with certain unalienable
ee87371… drh 3419 ** Rights, that among these are Life, Liberty and the pursuit of Happiness
ee87371… drh 3420 ** - That to secure these rights, Governments are instituted among Men,
ee87371… drh 3421 ** deriving their just powers from the consent of the governed,....
ee87371… drh 3422 **
ee87371… drh 3423 ** Two core ideas that (1) rights come from God and not from government,
ee87371… drh 3424 ** and that (2) there should not be special privileged classes of people
ee87371… drh 3425 ** were radical thoughts then, and are indeed disputed even today. Many
ee87371… drh 3426 ** people still hold that human rights derive from the beneficence of
ee87371… drh 3427 ** government and that certain classes of people have special rights and
ee87371… drh 3428 ** privileges not available to all. Yet, were it not for the crazy ideas
ee87371… drh 3429 ** espoused in the original Declaration of Independence, this software
ee87371… drh 3430 ** project, and indeed most of modern technology, would not exist.
ee87371… drh 3431 **
ee87371… drh 3432 ** Therefore let us give thanks for the bold leadership and vision
ee87371… drh 3433 ** demonstrated by the authors of the American Revolution, 250 years ago
ee87371… drh 3434 ** this day.
ee87371… drh 3435 **
ee87371… drh 3436 ******************************************************************************
ee87371… drh 3437 **
ee87371… drh 3438 ** Implementation of the strdup() SQL function. strdup() makes a copy
ee87371… drh 3439 ** of its argument (a string or a BLOB) into memory obtained directly
ee87371… drh 3440 ** from system malloc() (not from sqlite3_malloc()) and sized exactly
ee87371… drh 3441 ** to hold the string or BLOB. This is intended for testing purposes,
ee87371… drh 3442 ** particularly testing with ASAN. This function serves no practical
ee87371… drh 3443 ** purpose beyond testing and not not intended for production use.
ee87371… drh 3444 **
ee87371… drh 3445 ** NULL, BLOB, and TEXT values come through as NULL, BLOB, and TEXT,
ee87371… drh 3446 ** respectively. Numeric values are rendered as strings and come out
ee87371… drh 3447 ** as text.
ee87371… drh 3448 */
ee87371… drh 3449 /* #include "sqlite3ext.h" */
ee87371… drh 3450 SQLITE_EXTENSION_INIT1
ee87371… drh 3451 #include <assert.h>
ee87371… drh 3452 #include <string.h>
ee87371… drh 3453 #include <stdlib.h>
ee87371… drh 3454
ee87371… drh 3455 /*
51267fb… drh 3456 ** No-op wrapper around free() to work around problems with non-CDECL
51267fb… drh 3457 ** calling conventions on 32-bit Windows builds.
51267fb… drh 3458 */
51267fb… drh 3459 static void strdupFree(void *p){
51267fb… drh 3460 free(p);
51267fb… drh 3461 }
51267fb… drh 3462
51267fb… drh 3463 /*
ee87371… drh 3464 ** Make a copy of a string or BLOB in memory obtained from malloc().
ee87371… drh 3465 */
ee87371… drh 3466 static void strdupfunc(
ee87371… drh 3467 sqlite3_context *context,
ee87371… drh 3468 int argc,
ee87371… drh 3469 sqlite3_value **argv
ee87371… drh 3470 ){
ee87371… drh 3471 const unsigned char *zIn;
ee87371… drh 3472 int nIn;
ee87371… drh 3473 unsigned char *zOut;
ee87371… drh 3474
ee87371… drh 3475 assert( argc==1 );
ee87371… drh 3476 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
ee87371… drh 3477 if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
ee87371… drh 3478 zIn = (const unsigned char*)sqlite3_value_blob(argv[0]);
ee87371… drh 3479 nIn = sqlite3_value_bytes(argv[0]);
ee87371… drh 3480 zOut = malloc( nIn==0 ? 1 : nIn );
ee87371… drh 3481 if( zOut==0 ){
ee87371… drh 3482 sqlite3_result_error_nomem(context);
ee87371… drh 3483 return;
ee87371… drh 3484 }
ee87371… drh 3485 if( nIn>0 ) memcpy(zOut, zIn, nIn);
51267fb… drh 3486 sqlite3_result_blob(context, zOut, nIn, strdupFree);
ee87371… drh 3487 }else{
ee87371… drh 3488 zIn = (const unsigned char*)sqlite3_value_text(argv[0]);
ee87371… drh 3489 if( zIn==0 ) return;
ee87371… drh 3490 nIn = (int)strlen((char*)zIn);
ee87371… drh 3491 zOut = malloc( nIn+1 );
ee87371… drh 3492 if( zOut==0 ){
ee87371… drh 3493 sqlite3_result_error_nomem(context);
ee87371… drh 3494 return;
ee87371… drh 3495 }
ee87371… drh 3496 memcpy(zOut, zIn, nIn);
ee87371… drh 3497 zOut[nIn] = 0;
51267fb… drh 3498 sqlite3_result_text64(context, (char*)zOut, nIn, strdupFree,
ee87371… drh 3499 SQLITE_UTF8_ZT);
ee87371… drh 3500 }
ee87371… drh 3501 }
ee87371… drh 3502
ee87371… drh 3503 #ifdef _WIN32
ee87371… drh 3504
ee87371… drh 3505 #endif
ee87371… drh 3506 int sqlite3_strdup_init(
ee87371… drh 3507 sqlite3 *db,
ee87371… drh 3508 char **pzErrMsg,
ee87371… drh 3509 const sqlite3_api_routines *pApi
ee87371… drh 3510 ){
ee87371… drh 3511 int rc = SQLITE_OK;
ee87371… drh 3512 SQLITE_EXTENSION_INIT2(pApi);
ee87371… drh 3513 (void)pzErrMsg; /* Unused parameter */
ee87371… drh 3514 rc = sqlite3_create_function(db, "strdup", 1, SQLITE_UTF8,
ee87371… drh 3515 0, strdupfunc, 0, 0);
ee87371… drh 3516 return rc;
ee87371… drh 3517 }
ee87371… drh 3518
ee87371… drh 3519 /************************* End ext/misc/strdup.c ********************/
e66a8c7… drh 3520 case SQLITE_UTF16LE: {
e66a8c7… drh 3521 /* sqlite3_result_text16be/le() remove a leading BOM. If
e66a8c7… drh 3522 ** the stored text begins with U+FEFF or U+FFFE, prepend
e66a8c7… drh 3523 ** a BOM in the database byte order, so that only the
e66a8c7… drh 3524 ** added BOM is removed. */
e66a8c7… drh 3525 u8 *aBuf = 0;
e66a8c7… drh 3526 if( n>=2 && ((pData[0]==0xFE && pData[1]==0xFF)
e66a8c7… drh 3527 || (pData[0]==0xFF && pData[1]==0xFE))
e66a8c7… drh 3528 ){
e66a8c7… drh 3529 aBuf = (u8*)sqlite3_malloc64(n+2);
e66a8c7… drh 3530 if( aBuf==0 ){
e66a8c7… drh 3531 sqlite3_result_error_nomem(pCtx);
e66a8c7… drh 3532 break;
e66a8c7… drh 3533 }
e66a8c7… drh 3534 aBuf[0] = (enc==SQLITE_UTF16BE) ? 0xFE : 0xFF;
e66a8c7… drh 3535 aBuf[1] = (enc==SQLITE_UTF16BE) ? 0xFF : 0xFE;
e66a8c7… drh 3536 memcpy(&aBuf[2], pData, n);
e66a8c7… drh 3537 }
e66a8c7… drh 3538 if( enc==SQLITE_UTF16BE ){
e66a8c7… drh 3539 if( aBuf ){
e66a8c7… drh 3540 sqlite3_result_text16be(pCtx, aBuf, n+2, sqlite3_free);
e66a8c7… drh 3541 }else{
e66a8c7… drh 3542 sqlite3_result_text16be(pCtx, pData, n, SQLITE_TRANSIENT);
e66a8c7… drh 3543 }
e66a8c7… drh 3544 }else{
e66a8c7… drh 3545 if( aBuf ){
e66a8c7… drh 3546 sqlite3_result_text16le(pCtx, aBuf, n+2, sqlite3_free);
e66a8c7… drh 3547 }else{
e66a8c7… drh 3548 sqlite3_result_text16le(pCtx, pData, n, SQLITE_TRANSIENT);
e66a8c7… drh 3549 }
e66a8c7… drh 3550 }
e66a8c7… drh 3551 }
e66a8c7… drh 3552 ** nField:
e66a8c7… drh 3553 ** The number of fields in each record of the table's b-tree. This may
e66a8c7… drh 3554 ** be less than nCol (VIRTUAL generated columns have no field) or, for
e66a8c7… drh 3555 ** a WITHOUT ROWID table with a column that appears more than once in
e66a8c7… drh 3556 ** the PRIMARY KEY, greater than nCol.
e66a8c7… drh 3557 **
c92989d… drh 3558 ** zRowid:
c92989d… drh 3559 ** If iRowidBind>0, the name used to refer to the rowid in the INSERT
c92989d… drh 3560 ** statement. This is the first of "_rowid_", "rowid" and "oid" that is
c92989d… drh 3561 ** not also the name of a column. If all three are column names, the
c92989d… drh 3562 ** rowid cannot be written and iRowidBind is 0.
c92989d… drh 3563 **
e66a8c7… drh 3564 int nField; /* Number of fields in each record */
c92989d… drh 3565 const char *zRowid; /* Name to use for rowid in INSERT */
e66a8c7… drh 3566 int nMax; /* Max field count in any schema table */
e66a8c7… drh 3567 if( iPg<=pMap->nPg && iPg>0 ){
c93e1c8… drh 3568 ** Run a single SQL statement in zSql. If zSql contains two or more
c93e1c8… drh 3569 ** SQL statements separated by ';', only the first is run.
c93e1c8… drh 3570 **
c93e1c8… drh 3571 ** Return the sqlite3_finalizer() or sqlite3_prepare() result code
c93e1c8… drh 3572 ** from running the zSql statement.
c93e1c8… drh 3573 */
c92989d… drh 3574 static int recoverOneStmt(sqlite3 *db, const char *zSql, const char **pzTail){
c93e1c8… drh 3575 sqlite3_stmt *pStmt = 0;
c93e1c8… drh 3576 int rc;
c93e1c8… drh 3577 if( zSql==0 ) return SQLITE_OK;
c92989d… drh 3578 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, pzTail);
c93e1c8… drh 3579 if( rc ){
c93e1c8… drh 3580 sqlite3_finalize(pStmt);
c93e1c8… drh 3581 return rc;
c93e1c8… drh 3582 }
c93e1c8… drh 3583 while( SQLITE_ROW==sqlite3_step(pStmt) ){}
c93e1c8… drh 3584 return sqlite3_finalize(pStmt);
c93e1c8… drh 3585 }
c93e1c8… drh 3586
c93e1c8… drh 3587 /*
c93e1c8… drh 3588 ** Otherwise, execute a single SQL statment in zSql. Even if zSql contains
c93e1c8… drh 3589 ** two or more SQL statements separated by ';', only execute the first one.
c93e1c8… drh 3590 ** If successful, return SQLITE_OK. Or, if an error occurs, leave an error
c93e1c8… drh 3591 ** code and message in the recover handle and return a copy of the error code.
c92989d… drh 3592 int rc = recoverOneStmt(db, zSql, 0);
c93e1c8… drh 3593 recoverExec(p, db2, "CREATE TABLE t1(a)");
c93e1c8… drh 3594 recoverExec(p, db2, "DROP TABLE t1");
c93e1c8… drh 3595 sqlite3_free(zSql);
c93e1c8… drh 3596 recoverExec(p, p->dbOut, "PRAGMA writable_schema = 1");
c93e1c8… drh 3597 recoverExec(p, p->dbOut,
c93e1c8… drh 3598 "CREATE TABLE recovery.map(pgno INTEGER PRIMARY KEY, parent INT)");
c93e1c8… drh 3599 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql)");
c92989d… drh 3600 "PRAGMA %Q.table_xinfo(%Q)", p->zDb, zName
e66a8c7… drh 3601 pNew->nField = iField;
e66a8c7… drh 3602 /* If this is a WITHOUT ROWID table, the fields of each record are
e66a8c7… drh 3603 ** ordered as reported by PRAGMA index_xinfo on the table. A column may
e66a8c7… drh 3604 ** appear more than once if it is listed more than once in the PRIMARY
e66a8c7… drh 3605 ** KEY (with different collation sequences). In that case use the first
e66a8c7… drh 3606 ** field - the others are redundant copies. */
c92989d… drh 3607 pStmt = recoverPreparePrintf(p, p->dbOut,
c92989d… drh 3608 "PRAGMA %Q.index_xinfo(%Q)", p->zDb, zName);
e66a8c7… drh 3609 assert( iCol>=0 && iCol<pNew->nCol );
e66a8c7… drh 3610 if( pNew->bIntkey ){
e66a8c7… drh 3611 int ii;
e66a8c7… drh 3612 for(ii=0; ii<pNew->nCol; ii++) pNew->aCol[ii].iField = -1;
e66a8c7… drh 3613 pNew->bIntkey = 0;
e66a8c7… drh 3614 }
e66a8c7… drh 3615 if( pNew->aCol[iCol].iField<0 ) pNew->aCol[iCol].iField = iField;
e66a8c7… drh 3616 pNew->nField = iField+1;
e66a8c7… drh 3617
c92989d… drh 3618 /* A column declared as "INTEGER PRIMARY KEY DESC" is not an alias for
c92989d… drh 3619 ** the rowid. Such a table has an automatic index with origin 'pk',
c92989d… drh 3620 ** whereas a table with a true rowid alias does not. */
c92989d… drh 3621 if( iPk>=0 ){
c92989d… drh 3622 pStmt = recoverPreparePrintf(p, p->dbOut,
c92989d… drh 3623 "SELECT 1 FROM pragma_index_list(%Q, %Q) WHERE origin='pk'",
c92989d… drh 3624 zName, p->zDb
c92989d… drh 3625 );
c92989d… drh 3626 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ) iPk = -1;
c92989d… drh 3627 recoverFinalize(p, pStmt);
c92989d… drh 3628 }
c92989d… drh 3629
c92989d… drh 3630 /* Find a name for the rowid that is not also the name of a column */
c92989d… drh 3631 static const char *azRowid[] = { "_rowid_", "rowid", "oid" };
c92989d… drh 3632 int ii, jj;
c92989d… drh 3633 for(ii=0; ii<(int)(sizeof(azRowid)/sizeof(azRowid[0])); ii++){
c92989d… drh 3634 for(jj=0; jj<pNew->nCol; jj++){
c92989d… drh 3635 if( sqlite3_stricmp(azRowid[ii], pNew->aCol[jj].zCol)==0 ) break;
c92989d… drh 3636 }
c92989d… drh 3637 if( jj==pNew->nCol ){
c92989d… drh 3638 pNew->zRowid = azRowid[ii];
c92989d… drh 3639 pNew->iRowidBind = iBind++;
c92989d… drh 3640 break;
c92989d… drh 3641 }
c92989d… drh 3642 }
c93e1c8… drh 3643 " WHERE (tbl OR isIndex) AND sql GLOB 'CREATE *'"
c92989d… drh 3644 const char *zTail = 0;
c92989d… drh 3645 rc = recoverOneStmt(p->dbOut, zSql, &zTail);
c92989d… drh 3646 char *pToFree = 0;
c92989d… drh 3647 if( zTail && zTail[0] ){
c92989d… drh 3648 int n = (int)(zTail - zSql);
c92989d… drh 3649 while( n>0 && (zSql[n-1]==';' || zSql[n-1]<=' ') ){ n--; }
c92989d… drh 3650 pToFree = sqlite3_mprintf("%.*s", n, zSql);
c92989d… drh 3651 zSql = pToFree;
c92989d… drh 3652
c92989d… drh 3653 }
c92989d… drh 3654 sqlite3_free(pToFree);
c93e1c8… drh 3655 " AND sql GLOB 'CREATE *'"
c93e1c8… drh 3656 " AND sql GLOB 'CREATE *'"
c92989d… drh 3657 const char *zTail = 0;
c92989d… drh 3658 int rc = recoverOneStmt(p->dbOut, zSql, &zTail);
c92989d… drh 3659 char *pToFree = 0;
c92989d… drh 3660 if( zTail && zTail[0] ){
c92989d… drh 3661 /* Omit any extraneous text that follows the first SQL statement */
c92989d… drh 3662 int n = (int)(zTail - zSql);
c92989d… drh 3663 while( n>0 && (zSql[n-1]==';' || zSql[n-1]<=' ') ){ n--; }
c92989d… drh 3664 pToFree = sqlite3_mprintf("%.*s", n, zSql);
c92989d… drh 3665 zSql = pToFree;
c92989d… drh 3666 }
c92989d… drh 3667 sqlite3_free(pToFree);
e66a8c7… drh 3668 assert( nField<=pTab->nField );
c92989d… drh 3669 assert( pTab->zRowid );
c92989d… drh 3670 zSql = recoverMPrintf(p, "%z%s", zSql, pTab->zRowid);
e66a8c7… drh 3671 /* Include each column that has a bind parameter and either has a field
e66a8c7… drh 3672 ** in the nField-field record or is the IPK. This must match the set of
e66a8c7… drh 3673 ** parameters bound by recoverWriteDataStep(). Note that nField counts
e66a8c7… drh 3674 ** record fields, not table columns - VIRTUAL generated columns have no
e66a8c7… drh 3675 ** field (iField<0), and the order of fields need not match the order of
e66a8c7… drh 3676 ** columns (WITHOUT ROWID tables). */
e66a8c7… drh 3677 for(ii=0; ii<pTab->nCol; ii++){
e66a8c7… drh 3678 RecoverColumn *pCol = &pTab->aCol[ii];
e66a8c7… drh 3679 if( pCol->iBind>0 && (pCol->iField<nField || pCol->bIPK) ){
e66a8c7… drh 3680 assert( pCol->iField>=0 );
e66a8c7… drh 3681 assert( pCol->eHidden!=RECOVER_EHIDDEN_VIRTUAL );
e66a8c7… drh 3682 assert( pCol->eHidden!=RECOVER_EHIDDEN_STORED );
e66a8c7… drh 3683 /* Figure out the maximum number of fields for any table in the schema */
e66a8c7… drh 3684 if( pTbl->nField>p1->nMax ) p1->nMax = pTbl->nField;
e66a8c7… drh 3685 assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nField );
e66a8c7… drh 3686 }else if( iField<pTab->nField ){
e66a8c7… drh 3687 }else if( pTab->nField==0 ){
e66a8c7… drh 3688 p1->nVal = pTab->nField;
c92989d… drh 3689 && SQLITE_OK==recoverOneStmt(p->dbIn, "ROLLBACK", 0)
c92989d… drh 3690 rc = recoverOneStmt(p->dbIn, "END", 0);
c92989d… drh 3691 rc = recoverOneStmt(p->dbIn, "END", 0);
896a463… drh 3692 #endif
896a463… drh 3693
896a463… drh 3694 /*
896a463… drh 3695 ** Set the SQLITE_SHELL_EDITION to a YYYYMMDD date string and the
896a463… drh 3696 ** code will attempt to use defaults for the prompt and for the
896a463… drh 3697 ** initial output mode (and maybe other feature) that were for
896a463… drh 3698 ** the most recent version not newer than the specified date.
896a463… drh 3699 */
896a463… drh 3700 #ifndef SQLITE_SHELL_EDITION
896a463… drh 3701 # define SQLITE_SHELL_EDITION 99991231 /* Use the latest if unspecified */
471d617… drh 3702 char zIFmt[24]; /* Space to hold the --ifmt value */
471d617… drh 3703 char zFpFmt[24]; /* Space to hold the --fpfmt value */
1d618cc… drh 3704
677842d… drh 3705 /* Bit values for ShellState.mStats
677842d… drh 3706 */
677842d… drh 3707 #define CLISTAT_VMSTEP 0x01 /* Show vmsteps */
677842d… drh 3708 #define CLISTAT_STMT 0x02 /* Stats for each statement */
677842d… drh 3709 #define CLISTAT_MEM 0x04 /* Memory stats */
677842d… drh 3710 #define CLISTAT_XSTMT 0x08 /* Extra statement stats */
677842d… drh 3711 #define CLISTAT_XMEM 0x10 /* Extra memory stats */
677842d… drh 3712 #define CLISTAT_IO 0x20 /* I/O stats (Linux only) */
677842d… drh 3713 #define CLISTAT_ZIPVFS 0x40 /* ZIPVFS stats */
677842d… drh 3714 #define CLISTAT_ON 0x17 /* Usual stats */
677842d… drh 3715 #define CLISTAT_ALL 0x7f /* All stats */
677842d… drh 3716 #define CLISTAT_RESET 0x80 /* Reset stat counters each time */
677842d… drh 3717
677842d… drh 3718
1d618cc… drh 3719 /* A file that needs to be deleted, but only after a delay.
1d618cc… drh 3720 */
1d618cc… drh 3721 typedef struct Unlink {
1d618cc… drh 3722 sqlite3_int64 tm; /* Unlink after this time */
1d618cc… drh 3723 char *zFN; /* Name of file. Space from sqlite3_malloc() */
1d618cc… drh 3724 } Unlink;
677842d… drh 3725
677842d… drh 3726 /*
e66a8c7… drh 3727 ** Maximum nested depth for .if statements.
e66a8c7… drh 3728 */
e66a8c7… drh 3729 #define MX_IF 10
e66a8c7… drh 3730
e66a8c7… drh 3731 /*
677842d… drh 3732 u8 mStats; /* Which stats to display (if any) */
c93e1c8… drh 3733 u8 bDelimitNonprint; /* Add \001...\002 around non-printing in prompts */
564007c… drh 3734 u8 bTestParse; /* Undocumented --test-parse flags */
c92989d… drh 3735 char *zEqpFile; /* Append .eqp output to this file, if not NULL */
e66a8c7… drh 3736 char *zInput; /* Simulated inputs */
e66a8c7… drh 3737 i64 nInputUsed; /* Simulated input read so far */
677842d… drh 3738 char *zAuthIgnore; /* Authorizer returns SQLITE_IGNORE for glob matches */
677842d… drh 3739 char *zAuthDeny; /* Authorizer returns SQLITE_DENY for glob matches */
3361df8… drh 3740 char *azPrompt[2]; /* Main and continuation prompt strings */
1d618cc… drh 3741 Mode *aModeStack; /* Backups */
1d618cc… drh 3742 unsigned nModeStack; /* Number of entries in aModeStack[] */
1d618cc… drh 3743 unsigned nUnlink; /* Number of entries in aDelayUnlink[] */
1d618cc… drh 3744 Unlink *aUnlink; /* Temp files to unlink after a delay */
3361df8… drh 3745 int mFlgs; /* 0x001: Use zDbFilenaem for prompt */
e66a8c7… drh 3746 u32 mIf; /* Mask of false if conditions */
e66a8c7… drh 3747 u32 mElse; /* An else seen at this level */
e66a8c7… drh 3748 u32 mIfHasBeenTrue; /* True branch seen in if-elseif-elseif-else chain */
e66a8c7… drh 3749 int nIfLevel; /* Current number of if levels */
e66a8c7… drh 3750 int nIfAtStart; /* If level at start of current script */
e66a8c7… drh 3751 i64 lnIf[MX_IF]; /* Line number starting an if */
e66a8c7… drh 3752 i64 lnElse[MX_IF]; /* Line number of the else */
3361df8… drh 3753 char zTestcase[30]; /* Name of current test case */
3361df8… drh 3754 char outfile[FILENAME_MAX]; /* Filename for *out */
564007c… drh 3755 { "off","off","sql","csv","html","tcl","json","relaxed"};
c92989d… drh 3756 #define MODE_Test 22 /* list -colsep , -quote on <-- for testing */
c92989d… drh 3757 #define MODE_Www 23 /* Full web-page output */
c92989d… drh 3758 #define MODE_BUILTIN 23 /* Maximum built-in mode */
ee87371… drh 3759 unsigned char mFlg; /* Flags. 1=border-off 2=split-column 4=rowcount */
ee87371… drh 3760 { "box", 0, 0, 9, 1, 1, 0, 3, 1, 2, 0 },
ee87371… drh 3761 { "column", 0, 0, 9, 1, 1, 0, 3, 2, 2, 0 },
564007c… drh 3762 { "csv", 4, 5, 9, 3, 3, 0, 1, 12, 0, 0 },
c92989d… drh 3763 { "html", 0, 0, 11, 4, 4, 0, 3, 7, 0, 0 },
ee87371… drh 3764 { "markdown", 0, 0, 9, 1, 1, 0, 3, 13, 2, 0 },
ee87371… drh 3765 { "psql", 0, 0, 9, 1, 1, 0, 3, 19, 2, 5 },
ee87371… drh 3766 { "qbox", 0, 0, 10, 2, 1, 0, 3, 1, 2, 0 },
ee87371… drh 3767 { "table", 0, 0, 9, 1, 1, 0, 3, 19, 2, 0 },
c92989d… drh 3768 { "www", 0, 0, 11, 4, 4, 0, 3, 7, 0, 0 }
ee87371… drh 3769 }; /* | / / | / / | | / \____
ee87371… drh 3770 ** | / / | / / | | / |
ee87371… drh 3771 ** Index into aModeStr[] | / / | | 2: columnar |
ee87371… drh 3772 ** | / / | | 1: line |
ee87371… drh 3773 ** | / / | | 0: other |
ee87371… drh 3774 ** text encoding |/ | show | | |
ee87371… drh 3775 ** v-------------------' | hdrs? | The QRF style |
ee87371… drh 3776 ** 0: n/a blob | v-----' /
ee87371… drh 3777 ** 1: plain v----------' 0: n/a _________/
ee87371… drh 3778 ** 2: sql 0: auto 1: no |
ee87371… drh 3779 ** 3: csv 1: as-text 2: yes 1: border-off
ee87371… drh 3780 ** 4: html 2: sql 3: always 2: split-column
ee87371… drh 3781 ** 5: c 3: hex 4: rowcount
17f9878… drh 3782 #ifndef DFLT_MULTI_INSERT
17f9878… drh 3783 # define DFLT_MULTI_INSERT 3000
17f9878… drh 3784 #endif
17f9878… drh 3785
17f9878… drh 3786 /*
a10f931… drh 3787 ** If the following flag is set, then command execution stops
a10f931… drh 3788 ** at an error if we are not interactive.
a10f931… drh 3789 */
a10f931… drh 3790 static int bail_on_error = 0;
a10f931… drh 3791
a10f931… drh 3792 /*
a10f931… drh 3793 ** Treat stdin as an interactive input if the following variable
a10f931… drh 3794 ** is true. Otherwise, assume stdin is connected to a file or pipe.
a10f931… drh 3795 */
a10f931… drh 3796 static int stdin_is_interactive = 1;
a10f931… drh 3797
a10f931… drh 3798 /*
a10f931… drh 3799 ** Treat stdout like a TTY if true.
a10f931… drh 3800 */
a10f931… drh 3801 static int stdout_is_console = 1;
a10f931… drh 3802
a10f931… drh 3803 /*
a10f931… drh 3804 ** Use this value as the width of the output device. Or, figure it
a10f931… drh 3805 ** out at runtime if the value is negative. Or use a default width
a10f931… drh 3806 ** if this value is zero.
a10f931… drh 3807 */
a10f931… drh 3808 static int stdout_tty_width = -1;
a10f931… drh 3809
a10f931… drh 3810 /*
a10f931… drh 3811 ** The following is the open SQLite database. We make a pointer
a10f931… drh 3812 ** to this database a static variable so that it can be accessed
a10f931… drh 3813 ** by the SIGINT handler to interrupt database processing.
a10f931… drh 3814 */
a10f931… drh 3815 static sqlite3 *globalDb = 0;
1d618cc… drh 3816
1d618cc… drh 3817 /*
1d618cc… drh 3818 ** This is a global pointer to the main ShellState variable. This
1d618cc… drh 3819 ** exists so that the atexit() callback can access the ShellState
1d618cc… drh 3820 ** object to do some cleanup.
1d618cc… drh 3821 */
1d618cc… drh 3822 static struct ShellState *globalShellState = 0;
9b67f46… drh 3823
9b67f46… drh 3824 /*
a10f931… drh 3825 ** True if an interrupt (Control-C) has been received.
a10f931… drh 3826 */
a10f931… drh 3827 static volatile int seenInterrupt = 0;
a10f931… drh 3828
a10f931… drh 3829 /*
a10f931… drh 3830 ** This is the name of our program. It is set in main(), used
a10f931… drh 3831 ** in a number of other places, mostly for error messages.
a10f931… drh 3832 */
a10f931… drh 3833 static char *Argv0;
a10f931… drh 3834
a10f931… drh 3835 /*
a10f931… drh 3836 ** Write I/O traces to the following stream.
a10f931… drh 3837 */
a10f931… drh 3838 #ifdef SQLITE_ENABLE_IOTRACE
a10f931… drh 3839 static FILE *iotrace = 0;
a10f931… drh 3840 #endif
a10f931… drh 3841
a10f931… drh 3842 /*
a10f931… drh 3843 ** Output routines that are able to redirect to memory rather than
a10f931… drh 3844 ** doing actually I/O.
a10f931… drh 3845 ** Works like.
a10f931… drh 3846 ** --------------
a10f931… drh 3847 ** cli_printf(FILE*, const char*, ...); fprintf()
9b67f46… drh 3848 ** cli_write(FILE*, const char*, int); write()
a10f931… drh 3849 ** cli_puts(const char*, FILE*); fputs()
a10f931… drh 3850 ** cli_vprintf(FILE*, const char*, va_list); vfprintf()
a10f931… drh 3851 **
a10f931… drh 3852 ** These are just thin wrappers with the following added semantics:
a10f931… drh 3853 ** If the file-scope variable cli_output_capture is not NULL, and
a10f931… drh 3854 ** if the FILE* argument is stdout or stderr, then rather than
a10f931… drh 3855 ** writing to stdout/stdout, append the text to the cli_output_capture
a10f931… drh 3856 ** variable.
a10f931… drh 3857 **
a10f931… drh 3858 ** The cli_exit(int) routine works like exit() except that it
a10f931… drh 3859 ** first dumps any capture output to stdout.
a10f931… drh 3860 */
a10f931… drh 3861 static sqlite3_str *cli_output_capture = 0;
a10f931… drh 3862 static int cli_printf(FILE *out, const char *zFormat, ...){
a10f931… drh 3863 va_list ap;
a10f931… drh 3864 int rc;
a10f931… drh 3865 va_start(ap,zFormat);
a10f931… drh 3866 if( cli_output_capture && (out==stdout || out==stderr) ){
a10f931… drh 3867 sqlite3_str_vappendf(cli_output_capture, zFormat, ap);
a10f931… drh 3868 rc = 1;
a10f931… drh 3869 }else{
a10f931… drh 3870 rc = sqlite3_vfprintf(out, zFormat, ap);
a10f931… drh 3871 }
a10f931… drh 3872 va_end(ap);
a10f931… drh 3873 return rc;
a10f931… drh 3874 }
9b67f46… drh 3875 static int cli_write(FILE *out, const char *zData, int nData){
9b67f46… drh 3876 if( cli_output_capture && (out==stdout || out==stderr) ){
9b67f46… drh 3877 sqlite3_str_append(cli_output_capture, zData, nData);
87881e8… drh 3878 #ifdef _WIN32
87881e8… drh 3879 }else if( out==stdout || out==stderr ){
87881e8… drh 3880 nData = sqlite3_fprintf(out, "%.*s", nData, zData);
87881e8… drh 3881 #endif
9b67f46… drh 3882 }else{
9b67f46… drh 3883 nData = (int)fwrite(zData, 1, nData, out);
9b67f46… drh 3884 }
9b67f46… drh 3885 return nData;
9b67f46… drh 3886 }
a10f931… drh 3887 static int cli_puts(const char *zText, FILE *out){
a10f931… drh 3888 if( cli_output_capture && (out==stdout || out==stderr) ){
a10f931… drh 3889 sqlite3_str_appendall(cli_output_capture, zText);
a10f931… drh 3890 return 1;
a10f931… drh 3891 }
a10f931… drh 3892 return sqlite3_fputs(zText, out);
a10f931… drh 3893 }
a10f931… drh 3894 #if 0 /* Not currently used - available if we need it later */
a10f931… drh 3895 static int cli_vprintf(FILE *out, const char *zFormat, va_list ap){
a10f931… drh 3896 if( cli_output_capture && (out==stdout || out==stderr) ){
a10f931… drh 3897 sqlite3_str_vappendf(cli_output_capture, zFormat, ap);
a10f931… drh 3898 return 1;
a10f931… drh 3899 }else{
a10f931… drh 3900 return sqlite3_vfprintf(out, zFormat, ap);
a10f931… drh 3901 }
a10f931… drh 3902 }
a10f931… drh 3903 #endif
a10f931… drh 3904 static void cli_exit(int rc){
a10f931… drh 3905 if( cli_output_capture ){
a10f931… drh 3906 char *z = sqlite3_str_finish(cli_output_capture);
e66a8c7… drh 3907 sqlite3_fputs(z ? z : "", stdout);
a10f931… drh 3908 fflush(stdout);
a10f931… drh 3909 }
a10f931… drh 3910 exit(rc);
a10f931… drh 3911 }
a10f931… drh 3912
a10f931… drh 3913
a10f931… drh 3914 #define eputz(z) cli_puts(z,stderr)
a10f931… drh 3915 #define sputz(fp,z) cli_puts(z,fp)
a10f931… drh 3916
a10f931… drh 3917 /* A version of strcmp() that works with NULL values */
a10f931… drh 3918 static int cli_strcmp(const char *a, const char *b){
a10f931… drh 3919 if( a==0 ) a = "";
a10f931… drh 3920 if( b==0 ) b = "";
a10f931… drh 3921 return strcmp(a,b);
a10f931… drh 3922 }
a10f931… drh 3923 static int cli_strncmp(const char *a, const char *b, size_t n){
a10f931… drh 3924 if( a==0 ) a = "";
a10f931… drh 3925 if( b==0 ) b = "";
a10f931… drh 3926 return strncmp(a,b,n);
a10f931… drh 3927 }
a10f931… drh 3928
a10f931… drh 3929 /* Return the current wall-clock time in microseconds since the
a10f931… drh 3930 ** Unix epoch (1970-01-01T00:00:00Z)
a10f931… drh 3931 */
a10f931… drh 3932 static sqlite3_int64 timeOfDay(void){
a10f931… drh 3933 #if defined(_WIN64) && _WIN32_WINNT >= _WIN32_WINNT_WIN8
a10f931… drh 3934 sqlite3_uint64 t;
a10f931… drh 3935 FILETIME tm;
a10f931… drh 3936 GetSystemTimePreciseAsFileTime(&tm);
a10f931… drh 3937 t = ((u64)tm.dwHighDateTime<<32) | (u64)tm.dwLowDateTime;
a10f931… drh 3938 t += 116444736000000000LL;
a10f931… drh 3939 t /= 10;
a10f931… drh 3940 return t;
a10f931… drh 3941 #elif defined(_WIN32)
a10f931… drh 3942 static sqlite3_vfs *clockVfs = 0;
a10f931… drh 3943 sqlite3_int64 t;
a10f931… drh 3944 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
a10f931… drh 3945 if( clockVfs==0 ) return 0; /* Never actually happens */
a10f931… drh 3946 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
a10f931… drh 3947 clockVfs->xCurrentTimeInt64(clockVfs, &t);
a10f931… drh 3948 }else{
a10f931… drh 3949 double r;
a10f931… drh 3950 clockVfs->xCurrentTime(clockVfs, &r);
a10f931… drh 3951 t = (sqlite3_int64)(r*86400000.0);
a10f931… drh 3952 }
a10f931… drh 3953 return t*1000;
a10f931… drh 3954 #else
a10f931… drh 3955 struct timeval sNow;
a10f931… drh 3956 (void)gettimeofday(&sNow,0);
a10f931… drh 3957 return ((i64)sNow.tv_sec)*1000000 + sNow.tv_usec;
a10f931… drh 3958 #endif
a10f931… drh 3959 }
a10f931… drh 3960
a10f931… drh 3961 /* Indicate out-of-memory and exit. */
a10f931… drh 3962 static void shell_out_of_memory(void){
a10f931… drh 3963 eputz("Error: out of memory\n");
a10f931… drh 3964 cli_exit(1);
a10f931… drh 3965 }
a10f931… drh 3966
a10f931… drh 3967 /* Check a pointer to see if it is NULL. If it is NULL, exit with an
a10f931… drh 3968 ** out-of-memory error.
a10f931… drh 3969 */
a10f931… drh 3970 static void shell_check_oom(const void *p){
a10f931… drh 3971 if( p==0 ) shell_out_of_memory();
a10f931… drh 3972 }
a10f931… drh 3973
a10f931… drh 3974 /*
a10f931… drh 3975 ** This routine works like printf in that its first argument is a
a10f931… drh 3976 ** format string and subsequent arguments are values to be substituted
a10f931… drh 3977 ** in place of % fields. The result of formatting this string
a10f931… drh 3978 ** is written to iotrace.
a10f931… drh 3979 */
a10f931… drh 3980 #ifdef SQLITE_ENABLE_IOTRACE
a10f931… drh 3981 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
a10f931… drh 3982 va_list ap;
a10f931… drh 3983 char *z;
a10f931… drh 3984 if( iotrace==0 ) return;
a10f931… drh 3985 va_start(ap, zFormat);
a10f931… drh 3986 z = sqlite3_vmprintf(zFormat, ap);
a10f931… drh 3987 va_end(ap);
a10f931… drh 3988 cli_printf(iotrace, "%s", z);
a10f931… drh 3989 sqlite3_free(z);
a10f931… drh 3990 }
a10f931… drh 3991 #endif
a10f931… drh 3992
a10f931… drh 3993 /*
a10f931… drh 3994 ** Compute a string length that is limited to what can be stored in
a10f931… drh 3995 ** lower 30 bits of a 32-bit signed integer.
a10f931… drh 3996 */
a10f931… drh 3997 static int strlen30(const char *z){
a10f931… drh 3998 size_t n;
a10f931… drh 3999 if( z==0 ) return 0;
a10f931… drh 4000 n = strlen(z);
a10f931… drh 4001 return n>0x3fffffff ? 0x3fffffff : (int)n;
a10f931… drh 4002 }
a10f931… drh 4003
a10f931… drh 4004 /*
a10f931… drh 4005 ** Return open FILE * if zFile exists, can be opened for read
a10f931… drh 4006 ** and is an ordinary file or a character stream source.
a10f931… drh 4007 ** Otherwise return 0.
a10f931… drh 4008 */
a10f931… drh 4009 static FILE * openChrSource(const char *zFile){
a10f931… drh 4010 #if defined(_WIN32) || defined(WIN32)
a10f931… drh 4011 struct __stat64 x = {0};
a10f931… drh 4012 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
a10f931… drh 4013 /* On Windows, open first, then check the stream nature. This order
a10f931… drh 4014 ** is necessary because _stat() and sibs, when checking a named pipe,
a10f931… drh 4015 ** effectively break the pipe as its supplier sees it. */
a10f931… drh 4016 FILE *rv = sqlite3_fopen(zFile, "rb");
a10f931… drh 4017 if( rv==0 ) return 0;
a10f931… drh 4018 if( _fstat64(_fileno(rv), &x) != 0
a10f931… drh 4019 || !STAT_CHR_SRC(x.st_mode)){
a10f931… drh 4020 fclose(rv);
a10f931… drh 4021 rv = 0;
a10f931… drh 4022 }
a10f931… drh 4023 return rv;
a10f931… drh 4024 #else
a10f931… drh 4025 struct stat x = {0};
a10f931… drh 4026 int rc = stat(zFile, &x);
a10f931… drh 4027 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
a10f931… drh 4028 if( rc!=0 ) return 0;
a10f931… drh 4029 if( STAT_CHR_SRC(x.st_mode) ){
a10f931… drh 4030 return sqlite3_fopen(zFile, "rb");
a10f931… drh 4031 }else{
a10f931… drh 4032 return 0;
a10f931… drh 4033 }
a10f931… drh 4034 #endif
a10f931… drh 4035 #undef STAT_CHR_SRC
a10f931… drh 4036 }
a10f931… drh 4037
a10f931… drh 4038 /*
e66a8c7… drh 4039 ** Works like fgets except that if "in" really points to p->zInput
e66a8c7… drh 4040 ** then text is read out of the p->zInput buffer.
e66a8c7… drh 4041 */
e66a8c7… drh 4042 static char *shell_fgets(ShellState *p, char *zOut, int nOut, FILE *in){
e66a8c7… drh 4043 int i, j;
e66a8c7… drh 4044 char *zIn;
e66a8c7… drh 4045 if( p==0 || in!=(FILE*)&p->zInput ){
e66a8c7… drh 4046 return sqlite3_fgets(zOut, nOut, in);
e66a8c7… drh 4047 }
e66a8c7… drh 4048 zIn = p->zInput;
e66a8c7… drh 4049 for(i=0, j=p->nInputUsed; i<nOut-1 && zIn[j] && zIn[j]!='\n'; i++, j++){}
e66a8c7… drh 4050 if( zIn[j] ){ i++; }
e66a8c7… drh 4051 memcpy(zOut, &zIn[p->nInputUsed], i);
e66a8c7… drh 4052 zOut[i] = 0;
e66a8c7… drh 4053 p->nInputUsed += i;
e66a8c7… drh 4054 return i>0 ? zOut : 0;
e66a8c7… drh 4055 }
e66a8c7… drh 4056
e66a8c7… drh 4057 /*
a10f931… drh 4058 ** This routine reads a line of text from FILE in, stores
a10f931… drh 4059 ** the text in memory obtained from malloc() and returns a pointer
a10f931… drh 4060 ** to the text. NULL is returned at end of file, or if malloc()
a10f931… drh 4061 ** fails, or if the length of the line is longer than about a gigabyte.
a10f931… drh 4062 **
a10f931… drh 4063 ** If zLine is not NULL then it is a malloced buffer returned from
a10f931… drh 4064 ** a previous call to this routine that may be reused.
a10f931… drh 4065 */
e66a8c7… drh 4066 static char *local_getline(ShellState *p, char *zLine, FILE *in){
a10f931… drh 4067 int nLine = zLine==0 ? 0 : 100;
a10f931… drh 4068 int n = 0;
a10f931… drh 4069
896a463… drh 4070 while( seenInterrupt<2 ){
a10f931… drh 4071 if( n+100>nLine ){
a10f931… drh 4072 if( nLine>=1073741773 ){
a10f931… drh 4073 free(zLine);
a10f931… drh 4074 return 0;
a10f931… drh 4075 }
a10f931… drh 4076 nLine = nLine*2 + 100;
a10f931… drh 4077 zLine = realloc(zLine, nLine);
a10f931… drh 4078 shell_check_oom(zLine);
a10f931… drh 4079 }
e66a8c7… drh 4080 if( shell_fgets(p, &zLine[n], nLine - n, in)==0 ){
a10f931… drh 4081 if( n==0 ){
a10f931… drh 4082 free(zLine);
a10f931… drh 4083 return 0;
a10f931… drh 4084 }
a10f931… drh 4085 zLine[n] = 0;
a10f931… drh 4086 break;
a10f931… drh 4087 }
a10f931… drh 4088 while( zLine[n] ) n++;
a10f931… drh 4089 if( n>0 && zLine[n-1]=='\n' ){
a10f931… drh 4090 n--;
a10f931… drh 4091 if( n>0 && zLine[n-1]=='\r' ) n--;
a10f931… drh 4092 zLine[n] = 0;
a10f931… drh 4093 break;
a10f931… drh 4094 }
a10f931… drh 4095 }
a10f931… drh 4096 return zLine;
c93e1c8… drh 4097 }
c93e1c8… drh 4098
c93e1c8… drh 4099 /*
c93e1c8… drh 4100 ** Return true if either the SQLITE_NO_COLOR compile-time option is used
c93e1c8… drh 4101 ** or if the NO_COLOR environment variable exists
c93e1c8… drh 4102 */
c93e1c8… drh 4103 static int shellNoColor(void){
a570ebc… drh 4104 #if defined(SQLITE_NO_COLOR) || defined(SQLITE_SHELL_FIDDLE)
c93e1c8… drh 4105 return 1;
c93e1c8… drh 4106 #else
c93e1c8… drh 4107 return getenv("NO_COLOR")!=0;
c93e1c8… drh 4108 #endif
87881e8… drh 4109 }
87881e8… drh 4110
87881e8… drh 4111 /*
87881e8… drh 4112 ** The SQLITE_PS_APPDEF macro should be set to the name of a function
87881e8… drh 4113 ** that accepts a single "int" argument and returns a "const char *"
87881e8… drh 4114 ** that is guaranteed to be non-NULL. The value returned depends on the
87881e8… drh 4115 ** argument:
87881e8… drh 4116 **
87881e8… drh 4117 ** 1 Default main prompt.
87881e8… drh 4118 ** 2 Default continuation prompt.
87881e8… drh 4119 ** 3 Environment variable to override main prompt ("SQLITE_PS1")
87881e8… drh 4120 ** 4 Environment variable to override continuatio ("SQLITE_PS2")
87881e8… drh 4121 ** 'A' The name of the application. (Nominally "SQLite")
87881e8… drh 4122 ** 'V' Version number including patch. (ex: "3.54.1")
87881e8… drh 4123 ** 'v' Version number without patch. (ex: "3.54")
87881e8… drh 4124 **
87881e8… drh 4125 */
87881e8… drh 4126 #ifdef SQLITE_PS_APPDEF
9b67f46… drh 4127 extern const char *SQLITE_PS_APPDEF(int);
87881e8… drh 4128 #else
87881e8… drh 4129 # define SQLITE_PS_APPDEF shellPromptAppDef
9b67f46… drh 4130 static const char *shellPromptAppDef(int c){
87881e8… drh 4131 switch( c ){
87881e8… drh 4132 /* The default main prompt string */
87881e8… drh 4133 case 1:
896a463… drh 4134 #if SQLITE_SHELL_EDITION<20260423
896a463… drh 4135 return "sqlite> "; /* Legacy prompt for backwards compatibility */
896a463… drh 4136 #elif defined(SQLITE_PS1)
87881e8… drh 4137 return SQLITE_PS1;
87881e8… drh 4138 #else
c93e1c8… drh 4139 if( shellNoColor() ){
055e4d0… drh 4140 return "/A-/v /f-> ";
c93e1c8… drh 4141 }else{
c93e1c8… drh 4142 return "/e[1;32m/A-/v /e[1;/x33/:36/;m/m/e[3m/;/f/;/e[0m-> ";
c93e1c8… drh 4143 }
87881e8… drh 4144 #endif
87881e8… drh 4145
87881e8… drh 4146 /* The default continuation prompt string */
87881e8… drh 4147 case 2:
896a463… drh 4148 #if SQLITE_SHELL_EDITION<20260423
896a463… drh 4149 return " ...> "; /* Legacy continuation prompt */
896a463… drh 4150 #elif defined(SQLITE_PS2)
87881e8… drh 4151 return SQLITE_PS2;
87881e8… drh 4152 #else
c93e1c8… drh 4153 if( shellNoColor() ){
055e4d0… drh 4154 return "/B/C-> ";
c93e1c8… drh 4155 }else{
c93e1c8… drh 4156 return "/B/e[1;/x33/:36/;m/C/e[0m-> ";
c93e1c8… drh 4157 }
87881e8… drh 4158 #endif
87881e8… drh 4159
87881e8… drh 4160 /* Name of environment variables that override the prompt strings
87881e8… drh 4161 ** of cases 1 and 2 */
87881e8… drh 4162 case 3: return "SQLITE_PS1";
87881e8… drh 4163 case 4: return "SQLITE_PS2";
87881e8… drh 4164
87881e8… drh 4165 /* Name of the application */
3b2d0c9… drh 4166 #ifndef SQLITE_CLI_APPNAME
87881e8… drh 4167 case 'A': return "SQLite";
3b2d0c9… drh 4168 #else
3b2d0c9… drh 4169 case 'A': return SHELL_STRINGIFY(SQLITE_CLI_APPNAME);
3b2d0c9… drh 4170 #endif
87881e8… drh 4171
87881e8… drh 4172 /* Full version number of the application, including patch level */
87881e8… drh 4173 case 'V': return sqlite3_libversion();
87881e8… drh 4174
87881e8… drh 4175 /* Version number without the patch level */
87881e8… drh 4176 case 'v': {
87881e8… drh 4177 static char zRel[16];
87881e8… drh 4178 const char *zF = sqlite3_libversion();
87881e8… drh 4179 const char *zD = strrchr(zF,'.');
87881e8… drh 4180 if( zD && (size_t)(zD-zF)<sizeof(zRel)-1 ){
87881e8… drh 4181 memcpy(zRel,zF,(size_t)(zD-zF));
87881e8… drh 4182 zRel[(size_t)(zD-zF)] = 0;
87881e8… drh 4183 return zRel;
87881e8… drh 4184 }else{
87881e8… drh 4185 return zF;
87881e8… drh 4186 }
9b67f46… drh 4187 }
9b67f46… drh 4188 }
9b67f46… drh 4189 return "";
9b67f46… drh 4190 }
87881e8… drh 4191 #endif /* !defined(SQLITE_PS_APPDEF) */
87881e8… drh 4192
40c5397… drh 4193 #ifdef SQLITE_DEBUG
40c5397… drh 4194 /*
40c5397… drh 4195 ** SQL function: sqlite3_incomplete(TEXT)
40c5397… drh 4196 **
40c5397… drh 4197 ** For use internally and for debugging and testing only. This function
40c5397… drh 4198 ** is subject to change or removal in future versions.
40c5397… drh 4199 **
40c5397… drh 4200 ** Invoke the sqlite3_incomplete() interface and return its result.
40c5397… drh 4201 */
40c5397… drh 4202 static void shellIncompleteFunc(
40c5397… drh 4203 sqlite3_context *pCtx,
40c5397… drh 4204 int nVal,
40c5397… drh 4205 sqlite3_value **apVal
40c5397… drh 4206 ){
40c5397… drh 4207 const char *zSql = (const char*)sqlite3_value_text(apVal[0]);
40c5397… drh 4208 sqlite3_result_int64(pCtx, zSql?sqlite3_incomplete(zSql):SQLITE_MISUSE);
40c5397… drh 4209 }
40c5397… drh 4210 #endif /* SQLITE_DEBUG */
3361df8… drh 4211
3361df8… drh 4212 /*
3361df8… drh 4213 ** Return the raw (unexpanded) prompt string. This will be the
3361df8… drh 4214 ** first of the following that exist:
3361df8… drh 4215 **
3361df8… drh 4216 ** * The prompt string specified by the ".prompt" command.
3361df8… drh 4217 ** * The value of the SQLITE_PS1 (or SQLITE_PS2) environment variable.
3361df8… drh 4218 ** * The default prompt string.
3361df8… drh 4219 **
3361df8… drh 4220 ** The main prompt is returned if the argument is zero and the
3361df8… drh 4221 ** continuation prompt is returned if the argument is 1.
3361df8… drh 4222 */
3361df8… drh 4223 static const char *prompt_string(ShellState *p, int bContinue){
3361df8… drh 4224 const char *zPS;
3361df8… drh 4225 assert( bContinue==0 || bContinue==1 );
3361df8… drh 4226 if( p->azPrompt[bContinue] ){
3361df8… drh 4227 return p->azPrompt[bContinue];
3361df8… drh 4228 }
3361df8… drh 4229 #ifndef SQLITE_SHELL_FIDDLE
87881e8… drh 4230 zPS = getenv(SQLITE_PS_APPDEF(3+bContinue));
3361df8… drh 4231 if( zPS ) return zPS;
3361df8… drh 4232 #endif
87881e8… drh 4233 return SQLITE_PS_APPDEF(1+bContinue);
3361df8… drh 4234 }
3361df8… drh 4235
3361df8… drh 4236 /*
3361df8… drh 4237 ** Return the name of the open database file, to be used for prompt
3361df8… drh 4238 ** expansion purposes.
3361df8… drh 4239 */
1d618cc… drh 4240 static const char *prompt_filename(ShellState *p, const char *zMemoryName){
3361df8… drh 4241 sqlite3_filename pFN;
3361df8… drh 4242 const char *zFN = 0;
3361df8… drh 4243 if( p->pAuxDb->mFlgs & 0x01 ){
3361df8… drh 4244 zFN = p->pAuxDb->zDbFilename;
3361df8… drh 4245 }else if( p->db && (pFN = sqlite3_db_filename(p->db,0))!=0 ){
3361df8… drh 4246 zFN = sqlite3_filename_database(pFN);
3361df8… drh 4247 }
3361df8… drh 4248 if( zFN==0 || zFN[0]==0 ){
9b67f46… drh 4249 zFN = p->pAuxDb->zDbFilename;
c93e1c8… drh 4250 }
c93e1c8… drh 4251 if( zFN==0 || zFN[0]==0 || cli_strcmp(zFN,":memory:")==0 ){
c93e1c8… drh 4252 zFN = zMemoryName;
3361df8… drh 4253 }
3361df8… drh 4254 return zFN;
87881e8… drh 4255 }
87881e8… drh 4256
87881e8… drh 4257 /*
87881e8… drh 4258 ** Return the name of the computer on which we are running.
87881e8… drh 4259 */
87881e8… drh 4260 static const char *prompt_hostname(int bFull){
87881e8… drh 4261 #ifdef _WIN32
87881e8… drh 4262 const char *z = getenv("COMPUTERNAME");
87881e8… drh 4263 if( z==0 || z[0]==0 ) z = "?";
87881e8… drh 4264 return z;
87881e8… drh 4265 #else
87881e8… drh 4266 static char zHost[256];
87881e8… drh 4267 if( gethostname(zHost, sizeof(zHost)) ){
87881e8… drh 4268 zHost[0] = '?';
87881e8… drh 4269 zHost[1] = 0;
87881e8… drh 4270 }
87881e8… drh 4271 if( !bFull ){
87881e8… drh 4272 char *p = strchr(zHost,'.');
87881e8… drh 4273 if( p ) p[0] = 0;
87881e8… drh 4274 }
87881e8… drh 4275 return zHost;
87881e8… drh 4276 #endif
87881e8… drh 4277 }
87881e8… drh 4278
87881e8… drh 4279 /*
87881e8… drh 4280 ** Return the username. This is taken from an environment variable
87881e8… drh 4281 ** and can thus be forged. Do not depend on it.
87881e8… drh 4282 */
87881e8… drh 4283 static const char *prompt_user(void){
87881e8… drh 4284 const char *z;
87881e8… drh 4285 #ifdef _WIN32
87881e8… drh 4286 z = getenv("USERNAME");
87881e8… drh 4287 if( z==0 || z[0]==0 ) z = "?";
87881e8… drh 4288 #else
87881e8… drh 4289 z = getenv("USER");
87881e8… drh 4290 if( z==0 || z[0]==0 ) z = getenv("LOGNAME");
87881e8… drh 4291 if( z==0 || z[0]==0 ) z = "?";
87881e8… drh 4292 #endif
87881e8… drh 4293 return z;
c93e1c8… drh 4294 }
c93e1c8… drh 4295
c93e1c8… drh 4296 /* If z[] begins with one or more ANSI X3.64 (VT100) escape sequences
c93e1c8… drh 4297 ** return the number of bytes in all such escape sequences. Return
c93e1c8… drh 4298 ** zero if there are no valid escape sequences.
c93e1c8… drh 4299 */
c93e1c8… drh 4300 static int nAnsiEscape(const char *z){
c93e1c8… drh 4301 int i = 0;
c93e1c8… drh 4302 while( z[i]=='\033' && z[i+1]=='[' ){
c93e1c8… drh 4303 int k = i+2;
c93e1c8… drh 4304 while( z[k]>=0x30 && z[k]<=0x3f ){ k++; }
c93e1c8… drh 4305 while( z[k]>=0x20 && z[k]<=0x2f ){ k++; }
c93e1c8… drh 4306 if( z[k]<0x40 || z[k]>0x7e ) break;
c93e1c8… drh 4307 i = k+1;
c93e1c8… drh 4308 }
c93e1c8… drh 4309 return i;
40c5397… drh 4310 }
40c5397… drh 4311
40c5397… drh 4312 /*
40c5397… drh 4313 ** Append text on pOut that is sufficient to complete the statement zBase
40c5397… drh 4314 ** (according to sqlite3_complete()). eFlags:
40c5397… drh 4315 **
40c5397… drh 4316 ** 0x01 Include the final ";" if needed
40c5397… drh 4317 ** 0x04 Assume zBase ends with '\n'
40c5397… drh 4318 */
40c5397… drh 4319 static void appendCompletion(
40c5397… drh 4320 sqlite3_str *pOut, /* Append the completion here */
40c5397… drh 4321 const char *zBase, /* Existing SQL text */
40c5397… drh 4322 int eFlags /* 0x01: Include ";", 0x04: Assume '\n' */
40c5397… drh 4323 ){
40c5397… drh 4324 sqlite3_int64 R = zBase ? sqlite3_incomplete(zBase) : 0;
40c5397… drh 4325 int cc = (R>>16)&0xff;
40c5397… drh 4326 int nParen = R>>32;
40c5397… drh 4327 int eSemi = (R>>8)&0xff;
40c5397… drh 4328 int eStat = R&0xff;
40c5397… drh 4329 int bSemi = (eFlags & 0x01)!=0;
40c5397… drh 4330 if( cc==0 ){
40c5397… drh 4331 /* no-op */
40c5397… drh 4332 }else if( cc=='-' ){
40c5397… drh 4333 if( (eFlags & 0x04)==0 ) sqlite3_str_appendchar(pOut, 1, '\n');
40c5397… drh 4334 }else if( cc=='/' ){
40c5397… drh 4335 sqlite3_str_append(pOut,"*/",2);
40c5397… drh 4336 }else{
40c5397… drh 4337 sqlite3_str_appendchar(pOut, 1, cc);
40c5397… drh 4338 }
40c5397… drh 4339 if( nParen>0 ){
40c5397… drh 4340 sqlite3_str_appendf(pOut, "%.*c",nParen,')');
40c5397… drh 4341 }
40c5397… drh 4342 if( eStat==SQLITE_OK || eStat==SQLITE_EMPTY ){
40c5397… drh 4343 /* Nothing to add */
40c5397… drh 4344 }else if( eSemi==1 ){
40c5397… drh 4345 if( bSemi ) sqlite3_str_append(pOut, ";", 1);
40c5397… drh 4346 }else if( eSemi==2 ){
40c5397… drh 4347 sqlite3_str_append(pOut, "END;", 3+(bSemi!=0));
40c5397… drh 4348 }else if( eSemi==3 ){
40c5397… drh 4349 sqlite3_str_append(pOut, ";END;", 4+(bSemi!=0));
40c5397… drh 4350 }
40c5397… drh 4351 }
40c5397… drh 4352
40c5397… drh 4353 /*
40c5397… drh 4354 ** SQL function: shell_complete_sql(SQL)
40c5397… drh 4355 ** shell_complete_sql(SQL, FLAGS)
40c5397… drh 4356 **
40c5397… drh 4357 ** For use internally and for debugging and testing only. This function
40c5397… drh 4358 ** is subject to change or removal in future versions.
40c5397… drh 4359 **
40c5397… drh 4360 ** If the SQL input is a string, return a new string which is the same
40c5397… drh 4361 ** text with all pending quotes and comments finish, so that the
40c5397… drh 4362 ** SQL is ready to receive its final semicolon. The optional FLAGS
40c5397… drh 4363 ** parameter can be an integer where bits mean:
40c5397… drh 4364 **
40c5397… drh 4365 ** 0x01 Include the final semicolon
40c5397… drh 4366 ** 0x02 Only return the completion text. Omit the original SQL.
40c5397… drh 4367 ** 0x04 Assume that SQL has a \n at the end.
40c5397… drh 4368 **
40c5397… drh 4369 ** The /C substitution in the CLI prompt is computed using the
40c5397… drh 4370 ** equivalent of shell_complete_sql(SQL,3);
40c5397… drh 4371 */
40c5397… drh 4372 static void shell_complete_sql(
40c5397… drh 4373 sqlite3_context *pCtx,
40c5397… drh 4374 int nVal,
40c5397… drh 4375 sqlite3_value **apVal
40c5397… drh 4376 ){
40c5397… drh 4377 const char *zSql; /* Input SQL text */
40c5397… drh 4378 sqlite3_str *pOut; /* Completed SQL */
40c5397… drh 4379 int flags;
40c5397… drh 4380
40c5397… drh 4381 if( nVal!=1 && nVal!=2 ) return;
40c5397… drh 4382 if( nVal==2 ){
40c5397… drh 4383 flags = 0x7 & sqlite3_value_int64(apVal[1]);
40c5397… drh 4384 }else{
40c5397… drh 4385 flags = 0;
40c5397… drh 4386 }
40c5397… drh 4387 zSql = (const char*)sqlite3_value_text(apVal[0]);
40c5397… drh 4388 if( zSql==0 ) return;
40c5397… drh 4389 pOut = sqlite3_str_new(sqlite3_context_db_handle(pCtx));
40c5397… drh 4390 if( (flags & 0x02)==0 ) sqlite3_str_appendall(pOut, zSql);
40c5397… drh 4391 appendCompletion(pOut, zSql, flags & 0x05);
40c5397… drh 4392 sqlite3_result_str(pCtx, pOut, SQLITE_FINISH);
3361df8… drh 4393 }
3361df8… drh 4394
3361df8… drh 4395 /*
3361df8… drh 4396 ** Expand escapes in the given input prompt string. Return the
3361df8… drh 4397 ** expanded prompt in memory obtained from sqlite3_malloc(). The
3361df8… drh 4398 ** caller is responsible for freeing the memory.
3361df8… drh 4399 **
3361df8… drh 4400 ** Early prototypes use U+005c '\\' as the escape character. But
3361df8… drh 4401 ** that is an escape character for shells and C and many other languages,
3361df8… drh 4402 ** which can lead to nested quoting problems and confusion. The
3361df8… drh 4403 ** U+0025 '%' character was also tried, and that works pretty well on
3361df8… drh 4404 ** unix, but % is special to many formats on Windows. So now we
3361df8… drh 4405 ** use a forward-slash, U+002f '/', which seems to pass through
3361df8… drh 4406 ** every shell and "make" without issue.
3361df8… drh 4407 */
3361df8… drh 4408 static char *expand_prompt(
3361df8… drh 4409 ShellState *p, /* The current shell state */
3361df8… drh 4410 const char *zPrior, /* Prior input lines not yet processed */
3361df8… drh 4411 const char *zPrompt /* Prompt string to be expanded */
3361df8… drh 4412 ){
3361df8… drh 4413 sqlite3_str *pOut = sqlite3_str_new(0);
3361df8… drh 4414 int i;
3361df8… drh 4415 char c;
9b67f46… drh 4416 unsigned int mOff = 0; /* Bitmask of FALSE for if/then/else */
3361df8… drh 4417 int idxSpace = -1;
9b67f46… drh 4418 int iDate = -1;
3361df8… drh 4419 for(i=0; zPrompt[i]; i++){
3361df8… drh 4420 if( zPrompt[i]!='/' ) continue;
3361df8… drh 4421 if( i>0 ){
9b67f46… drh 4422 if( !mOff ) sqlite3_str_append(pOut, zPrompt, i);
3361df8… drh 4423 zPrompt += i;
3361df8… drh 4424 i = 0;
3361df8… drh 4425 }
3361df8… drh 4426 /* At this point zPrompt[0] is a / character and all prior
3361df8… drh 4427 ** characters have already been loaded into pOut. Process the
3361df8… drh 4428 ** escape sequence that zPrompt points to. */
3361df8… drh 4429 c = zPrompt[1];
3361df8… drh 4430 if( c==0 ){
3361df8… drh 4431 /* / at the end of a line is silently ignored */
3361df8… drh 4432 break;
3361df8… drh 4433 }
3361df8… drh 4434 if( c=='/' ){
3361df8… drh 4435 /* // maps into a single / */
3361df8… drh 4436 zPrompt++;
3361df8… drh 4437 continue;
3361df8… drh 4438 }
3361df8… drh 4439 if( c>='0' && c<='7' ){
3361df8… drh 4440 /* /nnn becomes a single byte given by octal nnn */
3361df8… drh 4441 int v = c - '0';
c93e1c8… drh 4442 i++;
3361df8… drh 4443 while( i<=2 && zPrompt[i+1]>='0' && zPrompt[i+1]<='7' ){
3361df8… drh 4444 v = v*8 + zPrompt[++i] - '0';
3361df8… drh 4445 }
9b67f46… drh 4446 if( !mOff ) sqlite3_str_appendchar(pOut, 1, v);
3361df8… drh 4447 zPrompt += i+1;
3361df8… drh 4448 i = -1;
3361df8… drh 4449 continue;
3361df8… drh 4450 }
3361df8… drh 4451 if( c=='e' ){
3361df8… drh 4452 /* /e is shorthand for /033 which is U+001B "Escape" */
9b67f46… drh 4453 if( !mOff ) sqlite3_str_append(pOut, "\033", 1);
9b67f46… drh 4454 zPrompt += 2;
9b67f46… drh 4455 i = -1;
9b67f46… drh 4456 continue;
9b67f46… drh 4457 }
9b67f46… drh 4458 if( c=='A' || c=='V' || c=='v' ){
9b67f46… drh 4459 /* /A expands to the application name */
9b67f46… drh 4460 /* /V expands to the version number with patch level */
9b67f46… drh 4461 /* /v expands to the version number without the patch level */
9b67f46… drh 4462 if( !mOff ) sqlite3_str_appendall(pOut, SQLITE_PS_APPDEF(c));
3361df8… drh 4463 zPrompt += 2;
3361df8… drh 4464 i = -1;
3361df8… drh 4465 continue;
3361df8… drh 4466 }
3361df8… drh 4467
3361df8… drh 4468 /* The intent of the following codes it to provide alternative
3361df8… drh 4469 ** text displays depending on whether or not the connection is
3361df8… drh 4470 ** currently in a transaction. Example 1: Show a "*" before the ">"
3361df8… drh 4471 ** like psql: (Note: We encode the "*" as /052 to avoid closing
3361df8… drh 4472 ** out this comment.)
3361df8… drh 4473 **
3361df8… drh 4474 ** .prompt 'sqlite/x/052/;> '
3361df8… drh 4475 **
3361df8… drh 4476 ** Example 2: Show database filename is blue if not in a transaction,
3361df8… drh 4477 ** or red if within a transaction:
3361df8… drh 4478 **
3361df8… drh 4479 ** .prompt '/e[1;/x31/:34/;m~f>/e[0m '
3361df8… drh 4480 */
3361df8… drh 4481 if( c==':' ){
9b67f46… drh 4482 /* ELSE: toggle display on/off */
9b67f46… drh 4483 mOff ^= 1;
3361df8… drh 4484 zPrompt += 2;
3361df8… drh 4485 i = -1;
3361df8… drh 4486 continue;
3361df8… drh 4487 }
3361df8… drh 4488 if( c==';' ){
9b67f46… drh 4489 /* ENDIF: Turn display on */
9b67f46… drh 4490 mOff >>= 1;
3361df8… drh 4491 zPrompt += 2;
3361df8… drh 4492 i = -1;
3361df8… drh 4493 continue;
3361df8… drh 4494 }
3361df8… drh 4495 if( c=='x' ){
3361df8… drh 4496 /* /x turns display off not in a transaction, on if in txn */
9b67f46… drh 4497 mOff = (mOff<<1) | (p->db==0 || sqlite3_get_autocommit(p->db)!=0);
9b67f46… drh 4498 zPrompt += 2;
9b67f46… drh 4499 i = -1;
9b67f46… drh 4500 continue;
9b67f46… drh 4501 }
9b67f46… drh 4502 if( c=='r' ){
9b67f46… drh 4503 /* /r turns display off if database is read/write, on if read-only */
9b67f46… drh 4504 mOff = (mOff<<1) | (p->db==0 || sqlite3_db_readonly(p->db,0)==0);
9b67f46… drh 4505 zPrompt += 2;
9b67f46… drh 4506 i = -1;
9b67f46… drh 4507 continue;
9b67f46… drh 4508 }
1d618cc… drh 4509 if( c=='m' ){
1d618cc… drh 4510 /* /m turns display on for an in-memory database and off for persistent */
1d618cc… drh 4511 mOff = (mOff<<1) | (p->db && prompt_filename(p,0)!=0);
1d618cc… drh 4512 zPrompt += 2;
1d618cc… drh 4513 i = -1;
1d618cc… drh 4514 continue;
1d618cc… drh 4515 }
3361df8… drh 4516
3361df8… drh 4517 if( c=='f' || c=='F' || c=='~' ){
3361df8… drh 4518 /* /f becomes the tail of the database filename */
3361df8… drh 4519 /* /F becomes the full pathname */
3361df8… drh 4520 /* /~ becomes the full pathname relative to $HOME */
9b67f46… drh 4521 if( !mOff ){
1d618cc… drh 4522 const char *zFN = prompt_filename(p,"memory");
3361df8… drh 4523 if( c=='f' ){
3361df8… drh 4524 #ifdef _WIN32
3361df8… drh 4525 const char *zTail = strrchr(zFN,'\\');
3361df8… drh 4526 #else
3361df8… drh 4527 const char *zTail = strrchr(zFN,'/');
3361df8… drh 4528 #endif
3361df8… drh 4529 if( zTail && zTail[1] ) zFN = &zTail[1];
3361df8… drh 4530 }else if( c=='~' ){
3361df8… drh 4531 const char *zHOME = getenv("HOME");
3361df8… drh 4532 size_t nHOME = zHOME ? strlen(zHOME) : 0;
3361df8… drh 4533 if( nHOME<strlen(zFN)
3361df8… drh 4534 && zHOME!=0 && zFN!=0 /* <--- these silence compiler warnings */
3361df8… drh 4535 && memcmp(zHOME,zFN,nHOME)==0
3361df8… drh 4536 ){
3361df8… drh 4537 sqlite3_str_append(pOut,"~",1);
3361df8… drh 4538 zFN += nHOME;
3361df8… drh 4539 }
3361df8… drh 4540 }
3361df8… drh 4541 sqlite3_str_appendall(pOut, zFN);
3361df8… drh 4542 }
3361df8… drh 4543 zPrompt += 2;
3361df8… drh 4544 i = -1;
3361df8… drh 4545 continue;
3361df8… drh 4546 }
3361df8… drh 4547
87881e8… drh 4548 if( c=='h' || c=='H' ){
87881e8… drh 4549 /* /h becomes hostname up to the first '.' */
87881e8… drh 4550 /* /H is the full hostname */
87881e8… drh 4551 if( !mOff ){
87881e8… drh 4552 sqlite3_str_appendall(pOut, prompt_hostname(c=='H'));
87881e8… drh 4553 }
87881e8… drh 4554 zPrompt += 2;
87881e8… drh 4555 i = -1;
87881e8… drh 4556 continue;
87881e8… drh 4557 }
87881e8… drh 4558 if( c=='u' ){
87881e8… drh 4559 /* /u becomes the username (taken from environment variables) */
87881e8… drh 4560 if( !mOff ){
87881e8… drh 4561 sqlite3_str_appendall(pOut, prompt_user());
87881e8… drh 4562 }
87881e8… drh 4563 zPrompt += 2;
87881e8… drh 4564 i = -1;
87881e8… drh 4565 continue;
87881e8… drh 4566 }
87881e8… drh 4567
87881e8… drh 4568 if( c=='C' ){
87881e8… drh 4569 /* /C becomes text needed to terminate current input */
9b67f46… drh 4570 if( !mOff ){
40c5397… drh 4571 appendCompletion(pOut, zPrior, 0x5);
3361df8… drh 4572 }
3361df8… drh 4573 zPrompt += 2;
3361df8… drh 4574 i = -1;
3361df8… drh 4575 continue;
3361df8… drh 4576 }
3361df8… drh 4577
3361df8… drh 4578 if( c=='B' ){
3361df8… drh 4579 /* /B is a no-op for the main prompt. For the continuation prompt,
3361df8… drh 4580 ** /B expands to zero or more spaces to make the continuation prompt
3361df8… drh 4581 ** at least as wide as the main prompt. */
9b67f46… drh 4582 if( !mOff ) idxSpace = sqlite3_str_length(pOut);
9b67f46… drh 4583 zPrompt += 2;
9b67f46… drh 4584 i = -1;
9b67f46… drh 4585 continue;
9b67f46… drh 4586 }
9b67f46… drh 4587
9b67f46… drh 4588 if( c=='D' ){
9b67f46… drh 4589 /* /D.../D replaces all of the text between the two /D escapes with
9b67f46… drh 4590 ** the result from strftime(). */
9b67f46… drh 4591 if( iDate<0 ){
9b67f46… drh 4592 iDate = sqlite3_str_length(pOut);
9b67f46… drh 4593 }else{
9b67f46… drh 4594 if( !mOff ){
9b67f46… drh 4595 time_t now;
9b67f46… drh 4596 char zBuf[200];
9b67f46… drh 4597 zBuf[0] = 0;
9b67f46… drh 4598 time(&now);
9b67f46… drh 4599 strftime(zBuf, sizeof(zBuf)-1, sqlite3_str_value(pOut)+iDate,
9b67f46… drh 4600 localtime(&now));
9b67f46… drh 4601 zBuf[199] = 0;
9b67f46… drh 4602 sqlite3_str_truncate(pOut, iDate);
9b67f46… drh 4603 sqlite3_str_appendall(pOut, zBuf);
9b67f46… drh 4604 }
9b67f46… drh 4605 iDate = -1;
9b67f46… drh 4606 }
3361df8… drh 4607 zPrompt += 2;
3361df8… drh 4608 i = -1;
3361df8… drh 4609 continue;
3361df8… drh 4610 }
3361df8… drh 4611
9b67f46… drh 4612 /* No match to a known escape. Generate an error. The mOff flag
9b67f46… drh 4613 ** is ignored for this output, so that errors appear even if they
9b67f46… drh 4614 ** are in an unused branch. */
9b67f46… drh 4615 sqlite3_str_appendf(pOut,"UNKNOWN(\"/%c\")",c);
3361df8… drh 4616 zPrompt += 2;
3361df8… drh 4617 i = -1;
3361df8… drh 4618 }
9b67f46… drh 4619 if( i>0 && !mOff ){
3361df8… drh 4620 sqlite3_str_append(pOut, zPrompt, i);
3361df8… drh 4621 }
3361df8… drh 4622
3361df8… drh 4623 /* Expand the /B, if there is one and if this is a continuation prompt */
3361df8… drh 4624 if( idxSpace>=0 && zPrior!=0 && zPrior[0]!=0 ){
3361df8… drh 4625 char *zOther = expand_prompt(p, 0, prompt_string(p,0));
3361df8… drh 4626 size_t wOther = sqlite3_qrf_wcswidth(zOther);
3361df8… drh 4627 size_t wThis = sqlite3_qrf_wcswidth(sqlite3_str_value(pOut));
3361df8… drh 4628 sqlite3_free(zOther);
3361df8… drh 4629 if( wOther>wThis ){
3361df8… drh 4630 char *z;
3361df8… drh 4631 int len;
3361df8… drh 4632 size_t nNew = wOther - wThis;
3361df8… drh 4633 assert( nNew>0 && nNew<0x7fffffff );
3361df8… drh 4634 sqlite3_str_appendchar(pOut, (int)nNew, ' ');
3361df8… drh 4635 len = sqlite3_str_length(pOut);
3361df8… drh 4636 if( len>idxSpace ){
3361df8… drh 4637 z = sqlite3_str_value(pOut);
3361df8… drh 4638 memmove(z+idxSpace+nNew, z+idxSpace, len-nNew-idxSpace);
3361df8… drh 4639 memset(z+idxSpace, ' ', nNew);
3361df8… drh 4640 }
3361df8… drh 4641 }
3361df8… drh 4642 }
9b67f46… drh 4643 if( 0==sqlite3_str_length(pOut) ){
9b67f46… drh 4644 /* Avoid a bogus OOM */
9b67f46… drh 4645 sqlite3_str_appendchar(pOut, 1, '\0');
9b67f46… drh 4646 }
c93e1c8… drh 4647
c93e1c8… drh 4648 /* Editline does not recognize ANSI X3.64 escape sequences. So we have
c93e1c8… drh 4649 ** to find them all and enclose them inside '\001'...'\002' delimiters.
c93e1c8… drh 4650 ** Some versions of readline also require this, but others do not.
c93e1c8… drh 4651 */
c93e1c8… drh 4652 if( p->bDelimitNonprint && strstr(sqlite3_str_value(pOut),"\033[")!=0 ){
c93e1c8… drh 4653 char *zOrig = sqlite3_str_finish(pOut);
c93e1c8… drh 4654 int n;
c93e1c8… drh 4655 pOut = sqlite3_str_new(0);
c93e1c8… drh 4656 for(i=0; zOrig[i]; i++){
c93e1c8… drh 4657 if( zOrig[i]=='\033' && (n = nAnsiEscape(zOrig+i))>0 ){
c93e1c8… drh 4658 sqlite3_str_appendchar(pOut, 1, 1);
c93e1c8… drh 4659 sqlite3_str_append(pOut, &zOrig[i], n);
c93e1c8… drh 4660 sqlite3_str_appendchar(pOut, 1, 2);
c93e1c8… drh 4661 i += n-1;
c93e1c8… drh 4662 }else{
c93e1c8… drh 4663 sqlite3_str_appendchar(pOut, 1, zOrig[i]);
c93e1c8… drh 4664 }
c93e1c8… drh 4665 }
c93e1c8… drh 4666 sqlite3_free(zOrig);
c93e1c8… drh 4667 }
c93e1c8… drh 4668
3361df8… drh 4669 return sqlite3_str_finish(pOut);
3361df8… drh 4670 }
3361df8… drh 4671
3361df8… drh 4672 /*
a10f931… drh 4673 ** Retrieve a single line of input text.
a10f931… drh 4674 **
a10f931… drh 4675 ** If in==0 then read from standard input and prompt before each line.
3361df8… drh 4676 ** If bContinue is true, then a continuation prompt is appropriate.
3361df8… drh 4677 ** If bContinue is zero, then the main prompt should be used.
a10f931… drh 4678 **
a10f931… drh 4679 ** If zPrior is not NULL then it is a buffer from a prior call to this
a10f931… drh 4680 ** routine that can be reused.
a10f931… drh 4681 **
a10f931… drh 4682 ** The result is stored in space obtained from malloc() and must either
a10f931… drh 4683 ** be freed by the caller or else passed back into this routine via the
a10f931… drh 4684 ** zPrior argument for reuse.
a10f931… drh 4685 */
a10f931… drh 4686 #ifndef SQLITE_SHELL_FIDDLE
3361df8… drh 4687 static char *one_input_line(
3361df8… drh 4688 ShellState *p, /* Shell state */
3361df8… drh 4689 char *zPrior, /* Just the previous line */
3361df8… drh 4690 const char *zAll, /* All statement text accumulated so far */
3361df8… drh 4691 int bContinue /* True for a continuation prompt */
3361df8… drh 4692 ){
a10f931… drh 4693 char *zResult;
e66a8c7… drh 4694 if( p->in!=0 ){
e66a8c7… drh 4695 zResult = local_getline(p, zPrior, p->in);
a10f931… drh 4696 }else{
3361df8… drh 4697 const char *zBase = prompt_string(p, bContinue!=0);
3361df8… drh 4698 char *zPrompt = expand_prompt(p, zAll, zBase);
3361df8… drh 4699 shell_check_oom(zPrompt);
896a463… drh 4700 #if SHELL_CMDLINE_EDIT_AVAILABLE
896a463… drh 4701 if( shellCmdLineEdit ){
896a463… drh 4702 free(zPrior);
896a463… drh 4703 zResult = shell_readline(zPrompt);
896a463… drh 4704 while( zResult==0 ){
896a463… drh 4705 /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
896a463… drh 4706 sqlite3_sleep(50);
896a463… drh 4707 if( seenInterrupt==0 ) break;
896a463… drh 4708 zResult = shell_readline("");
896a463… drh 4709 }
896a463… drh 4710 if( zResult && *zResult ) shell_add_history(zResult);
896a463… drh 4711 }else
896a463… drh 4712 #endif
896a463… drh 4713 {
896a463… drh 4714 sputz(stdout, zPrompt);
896a463… drh 4715 fflush(stdout);
896a463… drh 4716 do{
e66a8c7… drh 4717 zResult = local_getline(p, zPrior, stdin);
896a463… drh 4718 zPrior = 0;
896a463… drh 4719 /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
896a463… drh 4720 if( zResult==0 ) sqlite3_sleep(50);
896a463… drh 4721 }while( zResult==0 && seenInterrupt>0 );
896a463… drh 4722 }
3361df8… drh 4723 sqlite3_free(zPrompt);
a10f931… drh 4724 }
a10f931… drh 4725 return zResult;
a10f931… drh 4726 }
a10f931… drh 4727 #endif /* !SQLITE_SHELL_FIDDLE */
a10f931… drh 4728
a10f931… drh 4729 /*
a10f931… drh 4730 ** Return the value of a hexadecimal digit. Return -1 if the input
a10f931… drh 4731 ** is not a hex digit.
a10f931… drh 4732 */
a10f931… drh 4733 static int hexDigitValue(char c){
a10f931… drh 4734 if( c>='0' && c<='9' ) return c - '0';
a10f931… drh 4735 if( c>='a' && c<='f' ) return c - 'a' + 10;
a10f931… drh 4736 if( c>='A' && c<='F' ) return c - 'A' + 10;
a10f931… drh 4737 return -1;
a10f931… drh 4738 }
a10f931… drh 4739
a10f931… drh 4740 /*
a10f931… drh 4741 ** Interpret zArg as an integer value, possibly with suffixes.
a10f931… drh 4742 **
a10f931… drh 4743 ** If the value specified by zArg is outside the range of values that
a10f931… drh 4744 ** can be represented using a 64-bit twos-complement integer, then return
a10f931… drh 4745 ** the nearest representable value.
a10f931… drh 4746 */
a10f931… drh 4747 static sqlite3_int64 integerValue(const char *zArg){
a10f931… drh 4748 sqlite3_uint64 v = 0;
a10f931… drh 4749 static const struct { char *zSuffix; unsigned int iMult; } aMult[] = {
a10f931… drh 4750 { "KiB", 1024 },
a10f931… drh 4751 { "MiB", 1024*1024 },
a10f931… drh 4752 { "GiB", 1024*1024*1024 },
a10f931… drh 4753 { "KB", 1000 },
a10f931… drh 4754 { "MB", 1000000 },
a10f931… drh 4755 { "GB", 1000000000 },
a10f931… drh 4756 { "K", 1000 },
a10f931… drh 4757 { "M", 1000000 },
a10f931… drh 4758 { "G", 1000000000 },
a10f931… drh 4759 };
a10f931… drh 4760 int i;
a10f931… drh 4761 int isNeg = 0;
a10f931… drh 4762 if( zArg[0]=='-' ){
a10f931… drh 4763 isNeg = 1;
a10f931… drh 4764 zArg++;
a10f931… drh 4765 }else if( zArg[0]=='+' ){
a10f931… drh 4766 zArg++;
a10f931… drh 4767 }
a10f931… drh 4768 if( zArg[0]=='0' && zArg[1]=='x' ){
a10f931… drh 4769 int x;
a10f931… drh 4770 zArg += 2;
a10f931… drh 4771 while( (x = hexDigitValue(zArg[0]))>=0 ){
a10f931… drh 4772 if( v > 0x0fffffffffffffffULL ) goto integer_overflow;
a10f931… drh 4773 v = (v<<4) + x;
a10f931… drh 4774 zArg++;
a10f931… drh 4775 }
a10f931… drh 4776 }else{
a10f931… drh 4777 while( IsDigit(zArg[0]) ){
a10f931… drh 4778 if( v>=922337203685477580LL ){
a10f931… drh 4779 if( v>922337203685477580LL || zArg[0]>='8' ) goto integer_overflow;
a10f931… drh 4780 }
a10f931… drh 4781 v = v*10 + (zArg[0] - '0');
a10f931… drh 4782 zArg++;
a10f931… drh 4783 }
a10f931… drh 4784 }
a10f931… drh 4785 for(i=0; i<ArraySize(aMult); i++){
a10f931… drh 4786 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
a10f931… drh 4787 if( 0x7fffffffffffffffULL/aMult[i].iMult < v ) goto integer_overflow;
a10f931… drh 4788 v *= aMult[i].iMult;
a10f931… drh 4789 break;
a10f931… drh 4790 }
a10f931… drh 4791 }
a10f931… drh 4792 if( isNeg && v>0x7fffffffffffffffULL ) goto integer_overflow;
a10f931… drh 4793 return isNeg? -(sqlite3_int64)v : (sqlite3_int64)v;
a10f931… drh 4794 integer_overflow:
a10f931… drh 4795 return isNeg ? (i64)0x8000000000000000LL : 0x7fffffffffffffffLL;
a10f931… drh 4796 }
a10f931… drh 4797
a10f931… drh 4798 /*
a10f931… drh 4799 ** A variable length string to which one can append text.
a10f931… drh 4800 */
a10f931… drh 4801 typedef struct ShellText ShellText;
a10f931… drh 4802 struct ShellText {
a10f931… drh 4803 char *zTxt; /* The text */
a10f931… drh 4804 i64 n; /* Number of bytes of zTxt[] actually used */
a10f931… drh 4805 i64 nAlloc; /* Number of bytes allocated for zTxt[] */
a10f931… drh 4806 };
a10f931… drh 4807
a10f931… drh 4808 /*
a10f931… drh 4809 ** Initialize and destroy a ShellText object
a10f931… drh 4810 */
a10f931… drh 4811 static void initText(ShellText *p){
a10f931… drh 4812 memset(p, 0, sizeof(*p));
a10f931… drh 4813 }
a10f931… drh 4814 static void freeText(ShellText *p){
a10f931… drh 4815 sqlite3_free(p->zTxt);
a10f931… drh 4816 initText(p);
a10f931… drh 4817 }
a10f931… drh 4818
a10f931… drh 4819 /* zIn is either a pointer to a NULL-terminated string in memory obtained
a10f931… drh 4820 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
a10f931… drh 4821 ** added to zIn, and the result returned in memory obtained from malloc().
a10f931… drh 4822 ** zIn, if it was not NULL, is freed.
a10f931… drh 4823 **
a10f931… drh 4824 ** If the third argument, quote, is not '\0', then it is used as a
a10f931… drh 4825 ** quote character for zAppend.
a10f931… drh 4826 */
a10f931… drh 4827 static void appendText(ShellText *p, const char *zAppend, char quote){
a10f931… drh 4828 i64 len;
a10f931… drh 4829 i64 i;
a10f931… drh 4830 i64 nAppend = strlen30(zAppend);
a10f931… drh 4831
a10f931… drh 4832 len = nAppend+p->n+1;
a10f931… drh 4833 if( quote ){
a10f931… drh 4834 len += 2;
a10f931… drh 4835 for(i=0; i<nAppend; i++){
a10f931… drh 4836 if( zAppend[i]==quote ) len++;
a10f931… drh 4837 }
a10f931… drh 4838 }
a10f931… drh 4839
a10f931… drh 4840 if( p->zTxt==0 || p->n+len>=p->nAlloc ){
a10f931… drh 4841 p->nAlloc = p->nAlloc*2 + len + 20;
a10f931… drh 4842 p->zTxt = sqlite3_realloc64(p->zTxt, p->nAlloc);
a10f931… drh 4843 shell_check_oom(p->zTxt);
a10f931… drh 4844 }
a10f931… drh 4845
a10f931… drh 4846 if( quote ){
a10f931… drh 4847 char *zCsr = p->zTxt+p->n;
a10f931… drh 4848 *zCsr++ = quote;
a10f931… drh 4849 for(i=0; i<nAppend; i++){
a10f931… drh 4850 *zCsr++ = zAppend[i];
a10f931… drh 4851 if( zAppend[i]==quote ) *zCsr++ = quote;
a10f931… drh 4852 }
a10f931… drh 4853 *zCsr++ = quote;
a10f931… drh 4854 p->n = (i64)(zCsr - p->zTxt);
a10f931… drh 4855 *zCsr = '\0';
a10f931… drh 4856 }else{
a10f931… drh 4857 memcpy(p->zTxt+p->n, zAppend, nAppend);
a10f931… drh 4858 p->n += nAppend;
a10f931… drh 4859 p->zTxt[p->n] = '\0';
a10f931… drh 4860 }
a10f931… drh 4861 }
a10f931… drh 4862
a10f931… drh 4863 /*
a10f931… drh 4864 ** Attempt to determine if identifier zName needs to be quoted, either
a10f931… drh 4865 ** because it contains non-alphanumeric characters, or because it is an
a10f931… drh 4866 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
a10f931… drh 4867 ** that quoting is required.
a10f931… drh 4868 **
a10f931… drh 4869 ** Return '"' if quoting is required. Return 0 if no quoting is required.
a10f931… drh 4870 */
a10f931… drh 4871 static char quoteChar(const char *zName){
a10f931… drh 4872 int i;
a10f931… drh 4873 if( zName==0 ) return '"';
a10f931… drh 4874 if( !IsAlpha(zName[0]) && zName[0]!='_' ) return '"';
a10f931… drh 4875 for(i=0; zName[i]; i++){
a10f931… drh 4876 if( !IsAlnum(zName[i]) && zName[i]!='_' ) return '"';
a10f931… drh 4877 }
a10f931… drh 4878 return sqlite3_keyword_check(zName, i) ? '"' : 0;
a10f931… drh 4879 }
a10f931… drh 4880
a10f931… drh 4881 /*
a10f931… drh 4882 ** Construct a fake object name and column list to describe the structure
a10f931… drh 4883 ** of the view, virtual table, or table valued function zSchema.zName.
a10f931… drh 4884 **
a10f931… drh 4885 ** The returned string comes from sqlite3_mprintf() and should be freed
a10f931… drh 4886 ** by the caller using sqlite3_free().
a10f931… drh 4887 */
a10f931… drh 4888 static char *shellFakeSchema(
a10f931… drh 4889 sqlite3 *db, /* The database connection containing the vtab */
a10f931… drh 4890 const char *zSchema, /* Schema of the database holding the vtab */
a10f931… drh 4891 const char *zName /* The name of the virtual table */
a10f931… drh 4892 ){
a10f931… drh 4893 sqlite3_stmt *pStmt = 0;
51267fb… drh 4894 char *zSql, *zCom;
a10f931… drh 4895 ShellText s;
a10f931… drh 4896 char cQuote;
a10f931… drh 4897 char *zDiv = "(";
a10f931… drh 4898 int nRow = 0;
a10f931… drh 4899
a10f931… drh 4900 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
a10f931… drh 4901 zSchema ? zSchema : "main", zName);
a10f931… drh 4902 shell_check_oom(zSql);
a10f931… drh 4903 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
a10f931… drh 4904 sqlite3_free(zSql);
a10f931… drh 4905 initText(&s);
a10f931… drh 4906 if( zSchema ){
a10f931… drh 4907 cQuote = quoteChar(zSchema);
a10f931… drh 4908 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
a10f931… drh 4909 appendText(&s, zSchema, cQuote);
a10f931… drh 4910 appendText(&s, ".", 0);
a10f931… drh 4911 }
a10f931… drh 4912 cQuote = quoteChar(zName);
a10f931… drh 4913 appendText(&s, zName, cQuote);
a10f931… drh 4914 while( sqlite3_step(pStmt)==SQLITE_ROW ){
a10f931… drh 4915 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
a10f931… drh 4916 nRow++;
a10f931… drh 4917 appendText(&s, zDiv, 0);
a10f931… drh 4918 zDiv = ",";
a10f931… drh 4919 if( zCol==0 ) zCol = "";
a10f931… drh 4920 cQuote = quoteChar(zCol);
a10f931… drh 4921 appendText(&s, zCol, cQuote);
a10f931… drh 4922 }
a10f931… drh 4923 appendText(&s, ")", 0);
a10f931… drh 4924 sqlite3_finalize(pStmt);
a10f931… drh 4925 if( nRow==0 ){
a10f931… drh 4926 freeText(&s);
a10f931… drh 4927 s.zTxt = 0;
51267fb… drh 4928 }else{
51267fb… drh 4929 while( s.zTxt && (zCom = strstr(s.zTxt,"*/"))!=0 ){ zCom[1] = '*'; }
a10f931… drh 4930 }
a10f931… drh 4931 return s.zTxt;
a10f931… drh 4932 }
e66a8c7… drh 4933
e66a8c7… drh 4934 /*
e66a8c7… drh 4935 ** SQL function: capable(X)
e66a8c7… drh 4936 **
e66a8c7… drh 4937 ** Return true if the current build has capability X. Return 0
e66a8c7… drh 4938 ** if X is not a capability or NULL if X is NULL.
e66a8c7… drh 4939 **
c92989d… drh 4940 ** A build has capability X if any of the following are true:
c92989d… drh 4941 **
c92989d… drh 4942 ** (1) A VFS named X exists.
c92989d… drh 4943 ** (2) A function named X exists.
c92989d… drh 4944 ** (3) A module named X exists.
c92989d… drh 4945 ** (4) A compile-time option X is used for the build.
c92989d… drh 4946 **
c92989d… drh 4947 ** Comparison between X and the various items above is done
c92989d… drh 4948 ** using sqlite_stricmp() so that upper/lower case does not matter.
c92989d… drh 4949 ** So capable('generate_series') and capable('GENERATE_SERIES')
c92989d… drh 4950 ** both work the same.
c92989d… drh 4951 **
c92989d… drh 4952 ** There are also special names "vtab", "fkey", and "load_ext"
c92989d… drh 4953 ** that return true as long as compile-time options
c92989d… drh 4954 ** SQLITE_OMIT_VIRTUALTABLE, SQLITE_OMIT_FOREIGN_KEY, and
c92989d… drh 4955 ** SQLITE_OMIT_LOAD_EXTENSION are omitted from the build,
c92989d… drh 4956 ** respectively. Thus capable('vtab') means that virtual table
c92989d… drh 4957 ** features of SQLite are available in the current build.
c92989d… drh 4958 **
c92989d… drh 4959 ** There is also the special name "unsafe" which is true as long
c92989d… drh 4960 ** as the CLI is not in safe mode. New special names may be added
c92989d… drh 4961 ** in the future.
c92989d… drh 4962 **
c92989d… drh 4963 ** For other "OMIT" options (besides the three special ones noted
c92989d… drh 4964 ** in the previous paragraph) you have to say something like
c92989d… drh 4965 ** "capable('OMIT_EXPLAIN')". And that function returns true
c92989d… drh 4966 ** if the EXPLAIN capability is omitted. It works like a
c92989d… drh 4967 ** double-negative. This is a bit confusing (hence the special
c92989d… drh 4968 ** names for the common cases mentioned above) but it servicable
c92989d… drh 4969 ** for the rare cases when it is needed.
c92989d… drh 4970 **
e66a8c7… drh 4971 ** This function is intended to be used with the ".if" command
e66a8c7… drh 4972 ** to bypass test cases that use features that are not part of
e66a8c7… drh 4973 ** the build. Examples:
e66a8c7… drh 4974 **
e66a8c7… drh 4975 ** .if capable('fts5')
e66a8c7… drh 4976 ** # do tests that require the FTS5 extension
e66a8c7… drh 4977 ** .endif
e66a8c7… drh 4978 **
e66a8c7… drh 4979 ** .if capable('generate_series')
e66a8c7… drh 4980 ** # do tests that require the generate_series() table-valued functions
e66a8c7… drh 4981 ** .endif
e66a8c7… drh 4982 */
e66a8c7… drh 4983 static void shellCapable(
e66a8c7… drh 4984 sqlite3_context *pCtx,
e66a8c7… drh 4985 int nVal,
e66a8c7… drh 4986 sqlite3_value **apVal
e66a8c7… drh 4987 ){
e66a8c7… drh 4988 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
e66a8c7… drh 4989 const char *z = (const char*)sqlite3_value_text(apVal[0]);
e66a8c7… drh 4990 static const char *azSql[] = {
e66a8c7… drh 4991 "PRAGMA compile_options",
e66a8c7… drh 4992 "PRAGMA module_list",
e66a8c7… drh 4993 "PRAGMA function_list"
e66a8c7… drh 4994 };
e66a8c7… drh 4995 static const char *azInversions[] = {
e66a8c7… drh 4996 "vtab", "OMIT_VIRTUALTABLE",
e66a8c7… drh 4997 "fkey", "OMIT_FOREIGN_KEY",
e66a8c7… drh 4998 "load_ext", "OMIT_LOAD_EXTENSION",
e66a8c7… drh 4999 };
e66a8c7… drh 5000 size_t i;
e66a8c7… drh 5001 int invert = 0;
e66a8c7… drh 5002 int res = 0;
c92989d… drh 5003 sqlite3_vfs *pVfs;
e66a8c7… drh 5004
e66a8c7… drh 5005 UNUSED_PARAMETER(nVal);
e66a8c7… drh 5006 if( z==0 ) return;
c92989d… drh 5007
c92989d… drh 5008 /* Check available VFS names */
c92989d… drh 5009 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
c92989d… drh 5010 if( sqlite3_stricmp(z,pVfs->zName)==0 ){
c92989d… drh 5011 res = 1;
c92989d… drh 5012 goto capable_finished;
c92989d… drh 5013 }
c92989d… drh 5014 }
c92989d… drh 5015
c92989d… drh 5016 /* Special case: capable('unsafe') is true if not in safe mode */
c92989d… drh 5017 if( sqlite3_stricmp(z, "unsafe")==0 && p->bSafeMode==0 ){
c92989d… drh 5018 res = 1;
c92989d… drh 5019 goto capable_finished;
c92989d… drh 5020 }
c92989d… drh 5021
c92989d… drh 5022 /* Check special cases likek "vtab" and "fkey" */
e66a8c7… drh 5023 for(i=0; i<sizeof(azInversions)/sizeof(azInversions[0])-1; i+=2){
e66a8c7… drh 5024 if( sqlite3_stricmp(z, azInversions[i])==0 ){
e66a8c7… drh 5025 z = azInversions[i+1];
e66a8c7… drh 5026 invert = 1;
e66a8c7… drh 5027 break;
e66a8c7… drh 5028 }
e66a8c7… drh 5029 }
c92989d… drh 5030
c92989d… drh 5031 /* Run pragmas listing compile-time options, virtual tables, and functions */
e66a8c7… drh 5032 for(i=0; i<sizeof(azSql)/sizeof(azSql[0]); i++){
e66a8c7… drh 5033 sqlite3_stmt *pStmt = 0;
e66a8c7… drh 5034 sqlite3_prepare_v2(p->db, azSql[i], -1, &pStmt, 0);
e66a8c7… drh 5035 while( sqlite3_step(pStmt)==SQLITE_ROW ){
e66a8c7… drh 5036 const char *zRow = (const char*)sqlite3_column_text(pStmt, 0);
c92989d… drh 5037 if( sqlite3_stricmp(z,zRow)==0 ){
e66a8c7… drh 5038 res = 1;
e66a8c7… drh 5039 break;
e66a8c7… drh 5040 }
e66a8c7… drh 5041 }
e66a8c7… drh 5042 sqlite3_finalize(pStmt);
e66a8c7… drh 5043 if( res ) break;
e66a8c7… drh 5044 }
c92989d… drh 5045
c92989d… drh 5046 capable_finished:
e66a8c7… drh 5047 if( invert ) res = !res;
e66a8c7… drh 5048 sqlite3_result_int(pCtx, res);
e66a8c7… drh 5049 }
e66a8c7… drh 5050
564007c… drh 5051
564007c… drh 5052 /*
a10f931… drh 5053 ** SQL function: strtod(X)
40c5397… drh 5054 **
40c5397… drh 5055 ** For use internally and for debugging and testing only. This function
40c5397… drh 5056 ** is subject to change or removal in future versions.
a10f931… drh 5057 **
a10f931… drh 5058 ** Use the C-library strtod() function to convert string X into a double.
a10f931… drh 5059 ** Used for comparing the accuracy of SQLite's internal text-to-float conversion
a10f931… drh 5060 ** routines against the C-library.
a10f931… drh 5061 */
a10f931… drh 5062 static void shellStrtod(
a10f931… drh 5063 sqlite3_context *pCtx,
a10f931… drh 5064 int nVal,
a10f931… drh 5065 sqlite3_value **apVal
a10f931… drh 5066 ){
a10f931… drh 5067 char *z = (char*)sqlite3_value_text(apVal[0]);
a10f931… drh 5068 UNUSED_PARAMETER(nVal);
a10f931… drh 5069 if( z==0 ) return;
a10f931… drh 5070 sqlite3_result_double(pCtx, strtod(z,0));
a10f931… drh 5071 }
a10f931… drh 5072
a10f931… drh 5073 /*
a10f931… drh 5074 ** SQL function: dtostr(X)
a10f931… drh 5075 **
40c5397… drh 5076 ** For use internally and for debugging and testing only. This function
40c5397… drh 5077 ** is subject to change or removal in future versions.
40c5397… drh 5078 **
a10f931… drh 5079 ** Use the C-library printf() function to convert real value X into a string.
a10f931… drh 5080 ** Used for comparing the accuracy of SQLite's internal float-to-text conversion
a10f931… drh 5081 ** routines against the C-library.
a10f931… drh 5082 */
a10f931… drh 5083 static void shellDtostr(
a10f931… drh 5084 sqlite3_context *pCtx,
a10f931… drh 5085 int nVal,
a10f931… drh 5086 sqlite3_value **apVal
a10f931… drh 5087 ){
a10f931… drh 5088 double r = sqlite3_value_double(apVal[0]);
564007c… drh 5089 i64 nn = nVal>=2 ? sqlite3_value_int64(apVal[1]) : 26;
564007c… drh 5090 int n;
a10f931… drh 5091 char z[400];
564007c… drh 5092 if( nn<1 ){
564007c… drh 5093 n = 1;
564007c… drh 5094 }else if( nn>350 ){
564007c… drh 5095 n = 350;
564007c… drh 5096 }else{
564007c… drh 5097 n = (int)nn;
564007c… drh 5098 }
1ec45d0… drh 5099 z[sizeof(z)-1] = 0;
1ec45d0… drh 5100 snprintf(z, sizeof(z)-1, "%#+.*e", n, r);
a10f931… drh 5101 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
a10f931… drh 5102 }
a10f931… drh 5103
a10f931… drh 5104 /*
40c5397… drh 5105 ** SQL function: shell_add_schema(S,X,N)
a10f931… drh 5106 **
40c5397… drh 5107 ** For use internally and for debugging and testing only. This function
40c5397… drh 5108 ** is subject to change or removal in future versions.
40c5397… drh 5109 **
40c5397… drh 5110 ** Add the schema X to the CREATE statement in S for table N and return
40c5397… drh 5111 ** the result.
40c5397… drh 5112 **
a10f931… drh 5113 ** Examples:
a10f931… drh 5114 **
a10f931… drh 5115 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
a10f931… drh 5116 **
a10f931… drh 5117 ** Also works on
a10f931… drh 5118 **
a10f931… drh 5119 ** CREATE INDEX
a10f931… drh 5120 ** CREATE UNIQUE INDEX
a10f931… drh 5121 ** CREATE VIEW
a10f931… drh 5122 ** CREATE TRIGGER
a10f931… drh 5123 ** CREATE VIRTUAL TABLE
a10f931… drh 5124 **
a10f931… drh 5125 ** This UDF is used by the .schema command to insert the schema name of
a10f931… drh 5126 ** attached databases into the middle of the sqlite_schema.sql field.
a10f931… drh 5127 */
a10f931… drh 5128 static void shellAddSchemaName(
a10f931… drh 5129 sqlite3_context *pCtx,
a10f931… drh 5130 int nVal,
a10f931… drh 5131 sqlite3_value **apVal
a10f931… drh 5132 ){
a10f931… drh 5133 static const char *aPrefix[] = {
a10f931… drh 5134 "TABLE",
a10f931… drh 5135 "INDEX",
a10f931… drh 5136 "UNIQUE INDEX",
a10f931… drh 5137 "VIEW",
a10f931… drh 5138 "TRIGGER",
a10f931… drh 5139 "VIRTUAL TABLE"
a10f931… drh 5140 };
a10f931… drh 5141 int i = 0;
a10f931… drh 5142 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
a10f931… drh 5143 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
a10f931… drh 5144 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
a10f931… drh 5145 sqlite3 *db = sqlite3_context_db_handle(pCtx);
a10f931… drh 5146 UNUSED_PARAMETER(nVal);
a10f931… drh 5147 if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
a10f931… drh 5148 for(i=0; i<ArraySize(aPrefix); i++){
a10f931… drh 5149 int n = strlen30(aPrefix[i]);
a10f931… drh 5150 if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
40c5397… drh 5151 sqlite3_str *pOut = sqlite3_str_new(db);
a10f931… drh 5152 char *zFake = 0;
a10f931… drh 5153 if( zSchema ){
a10f931… drh 5154 char cQuote = quoteChar(zSchema);
a10f931… drh 5155 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
40c5397… drh 5156 sqlite3_str_appendf(pOut, "%.*s \"%w\".%s", n+7,zIn,zSchema,zIn+n+8);
a10f931… drh 5157 }else{
40c5397… drh 5158 sqlite3_str_appendf(pOut, "%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
a10f931… drh 5159 }
40c5397… drh 5160 }else{
40c5397… drh 5161 sqlite3_str_appendall(pOut, zIn);
a10f931… drh 5162 }
40c5397… drh 5163 appendCompletion(pOut, sqlite3_str_value(pOut), 1);
a10f931… drh 5164 if( zName
a10f931… drh 5165 && aPrefix[i][0]=='V'
a10f931… drh 5166 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
a10f931… drh 5167 ){
51267fb… drh 5168 assert( strstr(zFake,"*/")==0 );
40c5397… drh 5169 sqlite3_str_appendf(pOut, "\n/* %z */", zFake);
40c5397… drh 5170 }
40c5397… drh 5171 sqlite3_result_str(pCtx, pOut, SQLITE_FINISH);
40c5397… drh 5172 return;
a10f931… drh 5173 }
a10f931… drh 5174 }
a10f931… drh 5175 }
a10f931… drh 5176 sqlite3_result_value(pCtx, apVal[0]);
3361df8… drh 5177 }
3361df8… drh 5178
3361df8… drh 5179 /*
c93e1c8… drh 5180 ** SQL function: shell_prompt_test(PROMPT,PRIOR,FILENAME,FLAGS)
40c5397… drh 5181 **
40c5397… drh 5182 ** For use internally and for debugging and testing only. This function
40c5397… drh 5183 ** is subject to change or removal in future versions.
3361df8… drh 5184 **
3361df8… drh 5185 ** Return the shell prompt, with escapes expanded, for testing purposes.
3361df8… drh 5186 ** The first argument is the raw (unexpanded) prompt string. Or if the
3361df8… drh 5187 ** first argument is NULL, then use whatever prompt string is currently
3361df8… drh 5188 ** configured. If the second argument exists and is not NULL, then the
3361df8… drh 5189 ** second argument is understood to be prior incomplete text and a
3361df8… drh 5190 ** continuation prompt is generated. If a third argument is provided,
c93e1c8… drh 5191 ** it is assumed to be the full pathname of the database file. The
c93e1c8… drh 5192 ** fourth argument, if provided, is an integer of flags:
c93e1c8… drh 5193 **
c93e1c8… drh 5194 ** 0x0001 Always insert \001..\002 delimiters around ANSI escapes
c93e1c8… drh 5195 ** 0x0002 Never insert \001..\002 delimiters
c93e1c8… drh 5196 **
c93e1c8… drh 5197 ** This function is for testing purposes only. The interface may change.
c93e1c8… drh 5198 ** The function itself might be renamed or removed in future releases. Do
c93e1c8… drh 5199 ** not use this function in applications.
3361df8… drh 5200 */
3361df8… drh 5201 static void shellExpandPrompt(
3361df8… drh 5202 sqlite3_context *pCtx,
3361df8… drh 5203 int nVal,
3361df8… drh 5204 sqlite3_value **apVal
3361df8… drh 5205 ){
3361df8… drh 5206 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
3361df8… drh 5207 const char *zPrompt;
3361df8… drh 5208 const char *zPrior;
3361df8… drh 5209 const char *zSavedDbFile;
3361df8… drh 5210 int mSavedFlgs;
3361df8… drh 5211 const char *zFName;
3361df8… drh 5212 char *zRes;
c93e1c8… drh 5213 int mFlags;
c93e1c8… drh 5214 char bSavedDelimit = p->bDelimitNonprint;
3361df8… drh 5215
c93e1c8… drh 5216 if( nVal<1 ) return;
3361df8… drh 5217 if( nVal<2
3361df8… drh 5218 || (zPrior = (const char*)sqlite3_value_text(apVal[1]))==0
3361df8… drh 5219 || zPrior[0]==0
3361df8… drh 5220 ){
3361df8… drh 5221 zPrior = 0;
3361df8… drh 5222 }
3361df8… drh 5223 zPrompt = (const char*)sqlite3_value_text(apVal[0]);
3361df8… drh 5224 if( zPrompt==0 ){
3361df8… drh 5225 zPrompt = prompt_string(p, zPrior!=0);
3361df8… drh 5226 }
3361df8… drh 5227 zSavedDbFile = p->pAuxDb->zDbFilename;
3361df8… drh 5228 mSavedFlgs = p->pAuxDb->mFlgs;
3361df8… drh 5229 if( nVal>=3 && (zFName = (const char*)sqlite3_value_text(apVal[2]))!=0 ){
3361df8… drh 5230 p->pAuxDb->zDbFilename = zFName;
3361df8… drh 5231 p->pAuxDb->mFlgs |= 0x001;
3361df8… drh 5232 }
c93e1c8… drh 5233 mFlags = nVal>=4 ? sqlite3_value_int(apVal[3]) : 0;
c93e1c8… drh 5234 if( mFlags & 0x0001 ){
c93e1c8… drh 5235 p->bDelimitNonprint = 1;
c93e1c8… drh 5236 }else if( mFlags & 0x0002 ){
c93e1c8… drh 5237 p->bDelimitNonprint = 0;
c93e1c8… drh 5238 }
3361df8… drh 5239 zRes = expand_prompt(p, zPrior, zPrompt);
c93e1c8… drh 5240 p->bDelimitNonprint = bSavedDelimit;
3361df8… drh 5241 p->pAuxDb->zDbFilename = zSavedDbFile;
3361df8… drh 5242 p->pAuxDb->mFlgs = mSavedFlgs;
3361df8… drh 5243 sqlite3_result_text(pCtx, zRes, -1, SQLITE_TRANSIENT);
3361df8… drh 5244 sqlite3_free(zRes);
a10f931… drh 5245 }
1d618cc… drh 5246
ee87371… drh 5247 p->spec.iVersion = 2;
471d617… drh 5248 if( pDest->spec.zFpFmt ){
471d617… drh 5249 assert( pDest->spec.zFpFmt==pSrc->zFpFmt );
471d617… drh 5250 pDest->spec.zFpFmt = pDest->zFpFmt;
471d617… drh 5251 }
471d617… drh 5252 if( pDest->spec.zIFmt ){
471d617… drh 5253 assert( pDest->spec.zIFmt==pSrc->zIFmt );
471d617… drh 5254 pDest->spec.zIFmt = pDest->zIFmt;
471d617… drh 5255 }
71439dc… drh 5256 }
71439dc… drh 5257
71439dc… drh 5258 /* Forward reference */
71439dc… drh 5259 static int pickStr(const char *zArg, char **pzErr, ...);
471d617… drh 5260
471d617… drh 5261 /*
c92989d… drh 5262 ** Clamp a user-supplied value into the range 0..32767 or
c92989d… drh 5263 ** 0..2147483647
c92989d… drh 5264 */
c92989d… drh 5265 static short int modeClamp16(i64 x){
c92989d… drh 5266 if( x<0 ) x = 0;
c92989d… drh 5267 if( x>0x7fff ) x = 0x7fff;
c92989d… drh 5268 return (short int)x;
c92989d… drh 5269 }
c92989d… drh 5270 static int modeClamp32(i64 x){
c92989d… drh 5271 if( x<0 ) x = 0;
c92989d… drh 5272 if( x>0x7fffffff ) x = 0x7fffffff;
c92989d… drh 5273 return (int)x;
c92989d… drh 5274 }
c92989d… drh 5275
c92989d… drh 5276 /*
71439dc… drh 5277 ** Change the limits on the display mode. Return 0 on
71439dc… drh 5278 ** success. Return non-zero if zArg is mis-formatted.
71439dc… drh 5279 **
71439dc… drh 5280 ** Valid arguments:
71439dc… drh 5281 **
71439dc… drh 5282 ** "on" Default limits
71439dc… drh 5283 ** "off" All limits turned off
71439dc… drh 5284 ** L,C Line and Characters limits set
71439dc… drh 5285 ** L,C,T Line, Character, and Title limits set
71439dc… drh 5286 **
71439dc… drh 5287 ** Anything else returns non-zero
71439dc… drh 5288 */
71439dc… drh 5289 static int modeSetLimit(ShellState *p, const char *zArg){
71439dc… drh 5290 int k = zArg==0 ? 1 : pickStr(zArg,0,"on","off","");
71439dc… drh 5291 if( k==0 ){
71439dc… drh 5292 p->mode.spec.nLineLimit = DFLT_LINE_LIMIT;
71439dc… drh 5293 p->mode.spec.nCharLimit = DFLT_CHAR_LIMIT;
71439dc… drh 5294 p->mode.spec.nTitleLimit = DFLT_TITLE_LIMIT;
71439dc… drh 5295 }else if( k==1 ){
71439dc… drh 5296 p->mode.spec.nLineLimit = 0;
71439dc… drh 5297 p->mode.spec.nCharLimit = 0;
71439dc… drh 5298 p->mode.spec.nTitleLimit = 0;
71439dc… drh 5299 }else{
71439dc… drh 5300 int L, C, T = 0;
71439dc… drh 5301 int nNum = sscanf(zArg, "%d,%d,%d", &L, &C, &T);
71439dc… drh 5302 if( nNum<2 || L<0 || C<0 || T<0) return 1;
c92989d… drh 5303 p->mode.spec.nLineLimit = modeClamp16(L);
71439dc… drh 5304 p->mode.spec.nCharLimit = C;
c92989d… drh 5305 if( nNum==3 ) p->mode.spec.nTitleLimit = modeClamp16(T);
71439dc… drh 5306 }
71439dc… drh 5307 return 0;
ee87371… drh 5308 if( pI->mFlg & 0x04 ){
ee87371… drh 5309 pM->spec.bRowCount = QRF_Yes;
ee87371… drh 5310 }else{
ee87371… drh 5311 pM->spec.bRowCount = QRF_No;
ee87371… drh 5312 }
71439dc… drh 5313 modeSetLimit(p, "off");
17f9878… drh 5314 p->mode.spec.nMultiInsert = DFLT_MULTI_INSERT;
ee87371… drh 5315 p->mode.spec.iVersion = 2;
896a463… drh 5316 if( (stdin_is_interactive || stdout_is_console)
896a463… drh 5317 && SQLITE_SHELL_EDITION>=20260409
896a463… drh 5318 ){
1d618cc… drh 5319 p->aModeStack = realloc(p->aModeStack, sizeof(Mode)*(1+p->nModeStack));
1d618cc… drh 5320 shell_check_oom(p->aModeStack);
1d618cc… drh 5321 modeDup(&p->aModeStack[p->nModeStack], &p->mode);
1d618cc… drh 5322 p->nModeStack++;
1d618cc… drh 5323 if( p->nModeStack ){
1d618cc… drh 5324 p->nModeStack--;
1d618cc… drh 5325 memcpy(&p->mode, &p->aModeStack[p->nModeStack], sizeof(Mode));
1d618cc… drh 5326 memset(&p->aModeStack[p->nModeStack], 0, sizeof(Mode));
40c5397… drh 5327 **
40c5397… drh 5328 ** For use internally and for debugging and testing only. This function
40c5397… drh 5329 ** is subject to change or removal in future versions.
9b67f46… drh 5330 ** environment variable. If still there is no EDITOR, throw an error.
1d618cc… drh 5331 /* No-masking interrupts (SIGTERM or SIGHUP) */
1d618cc… drh 5332 static void sigterm_handler(int NotUsed){
1d618cc… drh 5333 UNUSED_PARAMETER(NotUsed);
1d618cc… drh 5334 cli_exit(1);
1d618cc… drh 5335 }
81eeb1c… drh 5336 "realpath",
677842d… drh 5337 char *zResult = "OK";
677842d… drh 5338 int rc = SQLITE_OK;
677842d… drh 5339 char *zMsg = sqlite3_mprintf("%s %Q %Q %Q %Q", azAction[op],zA1,zA2,zA3,zA4);
677842d… drh 5340 if( p->zAuthDeny && sqlite3_strglob(p->zAuthDeny, zMsg)==0 ){
677842d… drh 5341 zResult = "DENY";
677842d… drh 5342 rc = SQLITE_DENY;
677842d… drh 5343 }else if( p->zAuthIgnore && sqlite3_strglob(p->zAuthIgnore, zMsg)==0 ){
677842d… drh 5344 zResult = "IGNORE";
677842d… drh 5345 rc = SQLITE_IGNORE;
677842d… drh 5346 }
677842d… drh 5347 cli_printf(p->out, "authorizer: %s -> %s\n", zMsg, zResult);
677842d… drh 5348 sqlite3_free(zMsg);
677842d… drh 5349 return rc;
055e4d0… drh 5350 ** Print a schema statement. This is a helper routine to dump_callback().
40c5397… drh 5351 ** For use internally and for debugging and testing only. This function
40c5397… drh 5352 ** is subject to change or removal in future versions.
40c5397… drh 5353 **
40c5397… drh 5354 ** When FLAGS is zero, this routine is a no-op. If the
40c5397… drh 5355 sqlite3_result_value(pCtx, apVal[0]);
40c5397… drh 5356 return;
40c5397… drh 5357 }
40c5397… drh 5358 zSql = (const char*)sqlite3_value_text(apVal[0]);
40c5397… drh 5359 if( zSql==0 || zSql[0]==0 ){
40c5397… drh 5360 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
40c5397… drh 5361 return;
40c5397… drh 5362 sqlite3_result_value(pCtx, apVal[0]);
40c5397… drh 5363 return;
40c5397… drh 5364 pOut = sqlite3_str_new(sqlite3_context_db_handle(pCtx));
c92989d… drh 5365 ** Return a copy of the text z, obtained from sqlite3_malloc(), that is safe
c92989d… drh 5366 ** to embed inside of a C-style comment in a script of SQL statements and
c92989d… drh 5367 ** dot-commands. Newlines and other control characters are changed to spaces,
c92989d… drh 5368 ** and any end-of-comment sequence is broken up. Otherwise, text taken from
c92989d… drh 5369 ** an untrusted database (for example, a table name in an error message)
c92989d… drh 5370 ** could terminate the comment and put arbitrary SQL, or a line that begins
c92989d… drh 5371 ** with "." and so is interpreted as a dot-command, into the output.
c92989d… drh 5372 */
c92989d… drh 5373 static char *shellSafeCommentText(const char *z){
c92989d… drh 5374 char *zOut = sqlite3_mprintf("%s", z ? z : "");
c92989d… drh 5375 int i;
c92989d… drh 5376 if( zOut==0 ) return 0;
c92989d… drh 5377 for(i=0; zOut[i]; i++){
c92989d… drh 5378 unsigned char c = (unsigned char)zOut[i];
c92989d… drh 5379 if( c<' ' || c==0x7f ){
c92989d… drh 5380 zOut[i] = ' ';
c92989d… drh 5381 }else if( c=='/' && i>0 && zOut[i-1]=='*' ){
c92989d… drh 5382 zOut[i] = ' ';
c92989d… drh 5383 }
c92989d… drh 5384 }
c92989d… drh 5385 return zOut;
c92989d… drh 5386 }
c92989d… drh 5387
c92989d… drh 5388 /*
c92989d… drh 5389 zCode = sqlite3_mprintf("%.*s", (int)len, zSql);
c92989d… drh 5390 char *zMsg = shellSafeCommentText(sqlite3_errmsg(p->db));
c92989d… drh 5391 rc, zMsg, zContext);
c92989d… drh 5392 sqlite3_free(zMsg);
c92989d… drh 5393 char *zMsg = shellSafeCommentText(sqlite3_errmsg(p->db));
c92989d… drh 5394 cli_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, zMsg);
c92989d… drh 5395 sqlite3_free(zMsg);
677842d… drh 5396 ShellState *pArg /* Pointer to ShellState */
5d1b6a2… drh 5397 int bReset;
5d1b6a2… drh 5398
5d1b6a2… drh 5399 bReset = (pArg->mStats & CLISTAT_RESET)!=0;
677842d… drh 5400 if( pArg->pStmt && (pArg->mStats & CLISTAT_XSTMT)!=0 ){
677842d… drh 5401 if( pArg->pStmt && (pArg->mStats & CLISTAT_VMSTEP)!=0 ){
677842d… drh 5402 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
677842d… drh 5403 cli_printf(out, "VM-steps: %d\n", iCur);
677842d… drh 5404 }
677842d… drh 5405
677842d… drh 5406 if( (pArg->mStats & CLISTAT_MEM)!=0 ){
677842d… drh 5407 displayStatLine(out, "Memory Used:",
677842d… drh 5408 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
677842d… drh 5409 displayStatLine(out, "Number of Outstanding Allocations:",
677842d… drh 5410 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
677842d… drh 5411 }
677842d… drh 5412 if( (pArg->mStats & CLISTAT_XMEM)!=0 ){
677842d… drh 5413 if( pArg->shellFlgs & SHFLG_Pagecache ){
677842d… drh 5414 displayStatLine(out, "Number of Pcache Pages Used:",
677842d… drh 5415 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
677842d… drh 5416 }
677842d… drh 5417 displayStatLine(out, "Number of Pcache Overflow Bytes:",
677842d… drh 5418 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
677842d… drh 5419 displayStatLine(out, "Largest Allocation:",
677842d… drh 5420 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
677842d… drh 5421 displayStatLine(out, "Largest Pcache Allocation:",
677842d… drh 5422 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
677842d… drh 5423 displayStatLine(out, "Deepest Parser Stack:",
677842d… drh 5424 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
677842d… drh 5425 #endif
677842d… drh 5426
677842d… drh 5427 if( db ){
677842d… drh 5428 if( pArg->shellFlgs & SHFLG_Lookaside ){
677842d… drh 5429 iHiwtr = iCur = -1;
677842d… drh 5430 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
677842d… drh 5431 &iCur, &iHiwtr, bReset);
677842d… drh 5432 cli_printf(out,
677842d… drh 5433 "Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr);
677842d… drh 5434 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
677842d… drh 5435 &iCur, &iHiwtr, bReset);
677842d… drh 5436 cli_printf(out,
677842d… drh 5437 "Successful lookaside attempts: %d\n", iHiwtr);
677842d… drh 5438 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
677842d… drh 5439 &iCur, &iHiwtr, bReset);
677842d… drh 5440 cli_printf(out,
677842d… drh 5441 "Lookaside failures due to size: %d\n", iHiwtr);
677842d… drh 5442 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
677842d… drh 5443 &iCur, &iHiwtr, bReset);
677842d… drh 5444 cli_printf(out,
677842d… drh 5445 "Lookaside failures due to OOM: %d\n", iHiwtr);
677842d… drh 5446 }
677842d… drh 5447 iHiwtr = iCur = -1;
677842d… drh 5448 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
677842d… drh 5449 cli_printf(out,
677842d… drh 5450 "Pager Heap Usage: %d bytes\n", iCur);
677842d… drh 5451 iHiwtr = iCur = -1;
677842d… drh 5452 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
677842d… drh 5453 cli_printf(out,
677842d… drh 5454 "Page cache hits: %d\n", iCur);
677842d… drh 5455 iHiwtr = iCur = -1;
677842d… drh 5456 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
677842d… drh 5457 cli_printf(out,
677842d… drh 5458 "Page cache misses: %d\n", iCur);
677842d… drh 5459 iHiwtr64 = iCur64 = -1;
677842d… drh 5460 sqlite3_db_status64(db, SQLITE_DBSTATUS_TEMPBUF_SPILL, &iCur64, &iHiwtr64,
677842d… drh 5461 0);
677842d… drh 5462 iHiwtr = iCur = -1;
677842d… drh 5463 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
677842d… drh 5464 cli_printf(out,
677842d… drh 5465 "Page cache writes: %d\n", iCur);
677842d… drh 5466 iHiwtr = iCur = -1;
677842d… drh 5467 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
677842d… drh 5468 cli_printf(out,
677842d… drh 5469 "Page cache spills: %d\n", iCur);
677842d… drh 5470 cli_printf(out,
677842d… drh 5471 "Temporary data spilled to disk: %lld\n", iCur64);
677842d… drh 5472 sqlite3_db_status64(db, SQLITE_DBSTATUS_TEMPBUF_SPILL, &iCur64, &iHiwtr64,
677842d… drh 5473 1);
677842d… drh 5474 iHiwtr = iCur = -1;
677842d… drh 5475 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
677842d… drh 5476 cli_printf(out,
677842d… drh 5477 "Schema Heap Usage: %d bytes\n", iCur);
677842d… drh 5478 iHiwtr = iCur = -1;
677842d… drh 5479 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
677842d… drh 5480 cli_printf(out,
677842d… drh 5481 "Statement Heap/Lookaside Usage: %d bytes\n", iCur);
677842d… drh 5482 }
677842d… drh 5483 }
677842d… drh 5484
677842d… drh 5485 if( pArg->pStmt && (pArg->mStats & CLISTAT_STMT)!=0 ){
677842d… drh 5486 if( (pArg->mStats & CLISTAT_IO)!=0 ){
677842d… drh 5487 displayLinuxIoStats(pArg->out);
677842d… drh 5488 }
677842d… drh 5489 #ifdef SQLITE_ENABLE_ZIPVFS_VTAB
677842d… drh 5490 if( (pArg->mStats & CLISTAT_ZIPVFS)!=0 ){
677842d… drh 5491 /* Do not remove this machine readable comment: extra-stats-output-here */
677842d… drh 5492 }
677842d… drh 5493 #endif
c92989d… drh 5494 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, (int*)0);
c92989d… drh 5495 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, (int*)0);
c92989d… drh 5496 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, (int*)0);
c92989d… drh 5497 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, (int*)0);
c92989d… drh 5498 int inTrace = 0;
c92989d… drh 5499 sqlite3_db_config(pArg->db, SQLITE_DBCONFIG_VDBE_TRACE, -1, &inTrace);
c92989d… drh 5500 sqlite3_db_config(pArg->db, SQLITE_DBCONFIG_VDBE_TRACE, 0, (int*)0);
c92989d… drh 5501 if( inTrace ) cli_printf(pArg->out, "BIND: %s\n", zVar);
c92989d… drh 5502 #endif
c92989d… drh 5503 sqlite3_db_config(pArg->db, SQLITE_DBCONFIG_VDBE_TRACE, inTrace, (int*)0);
9b67f46… drh 5504 cli_write(pArg->out, z, (int)n);
cb89386… drh 5505 if( pArg->mode.eMode==MODE_Insert && ShellHasFlag(pArg,SHFLG_PreserveRowid) ){
cb89386… drh 5506 /* ,- This is true, but it is omitted
cb89386… drh 5507 ** vvvvvvvvvvvvvvvvvvv ----- to avoid compiler warnings. */
cb89386… drh 5508 assert( /*pArg->mode.eMode>=0 &&*/ pArg->mode.eMode<ArraySize(aModeInfo) );
c92989d… drh 5509
c92989d… drh 5510 bind_prepared_stmt(pArg, pStmt);
c92989d… drh 5511 FILE *savedOut = pArg->out;
c92989d… drh 5512 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
c92989d… drh 5513 if( pArg->zEqpFile ){
c92989d… drh 5514 pArg->out = sqlite3_fopen(pArg->zEqpFile, "ab");
c92989d… drh 5515 if( pArg->out==0 ){
c92989d… drh 5516 cli_printf(savedOut, "cannot open .eqp output file \"%s\"\n",
c92989d… drh 5517 pArg->zEqpFile);
c92989d… drh 5518 pArg->out = savedOut;
c92989d… drh 5519 }
c92989d… drh 5520 }
c92989d… drh 5521 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, (int*)0);
c92989d… drh 5522 if( pArg->out!=savedOut ){
c92989d… drh 5523 fclose(pArg->out);
c92989d… drh 5524 pArg->out = savedOut;
c92989d… drh 5525 }
51267fb… drh 5526 rc = sqlite3_format_query_result(pStmt, &spec, pzErrMsg);
51267fb… drh 5527 rc = sqlite3_format_query_result(pStmt, &spec, pzErrMsg);
677842d… drh 5528 if( pArg && pArg->mStats!=0 ){
677842d… drh 5529 display_stats(db, pArg);
51267fb… drh 5530 if( rc2 && rc!=SQLITE_NOMEM ) rc = rc2;
51267fb… drh 5531 }else if( pzErrMsg && pzErrMsg[0]==0 ){
e66a8c7… drh 5532 appendText(&sSelect, " AS ", 0);
e66a8c7… drh 5533 appendText(&sSelect, azCol[0], 0);
17f9878… drh 5534 p->mode.spec.nCharLimit = 0;
e66a8c7… drh 5535 p->mode.spec.bTextJsonb = QRF_No;
e66a8c7… drh 5536 p->mode.spec.zIFmt = 0;
e66a8c7… drh 5537 p->mode.spec.zFpFmt = 0;
c92989d… drh 5538 char *zMsg = shellSafeCommentText(zErr);
c92989d… drh 5539 cli_printf(p->out, "/****** %s ******/\n", zMsg);
c92989d… drh 5540 sqlite3_free(zMsg);
c92989d… drh 5541 char *zMsg = shellSafeCommentText(zErr);
c92989d… drh 5542 cli_printf(p->out, "/****** ERROR: %s ******/\n", zMsg);
c92989d… drh 5543 sqlite3_free(zMsg);
677842d… drh 5544 " Options:",
677842d… drh 5545 " --deny GLOB Return SQLITE_DENY if pattern matches",
677842d… drh 5546 " --ignore GLOB Return SQLITE_IGNORE if pattern matches",
71439dc… drh 5547 ".diskused ?SCHEMA? Report database space and size stats",
9b67f46… drh 5548 ".headers on|off Turn display of headers on or off",
17f9878… drh 5549 ".indexes ?PATTERN? Show names of indexes matching PATTERN",
17f9878… drh 5550 " -a|--all Also show system-generated indexes",
17f9878… drh 5551 " --expr Show only expression indexes",
17f9878… drh 5552 " --sys Show only system-generated indexes",
9b67f46… drh 5553 ".intck ?STEPS? Run an incremental integrity check on the db",
9b67f46… drh 5554 ".prompt MAIN CONTINUE Replace the standard prompts",
9b67f46… drh 5555 " --hard-reset Unset SQLITE_PS1/2 and then --reset",
055e4d0… drh 5556 #ifndef SQLITE_NO_COLOR
055e4d0… drh 5557 " --no-color Disable color prompts. Use --color to re-enable",
055e4d0… drh 5558 #endif
9b67f46… drh 5559 " --reset Revert to default prompts",
9b67f46… drh 5560 " --show Show the current prompt strings",
9b67f46… drh 5561 " -- No more options. Subsequent args are prompts",
c92989d… drh 5562 " --unsafe Do not issue the \".safe\" command in output",
c92989d… drh 5563 #endif
c92989d… drh 5564 ".safe Put the CLI into \"safe mode\"",
c92989d… drh 5565 #ifndef SQLITE_SHELL_FIDDLE
c92989d… drh 5566 },
c92989d… drh 5567 { ".testcase",
c92989d… drh 5568 "USAGE: .testcase [OPTIONS] NAME\n"
c92989d… drh 5569 "\n"
c92989d… drh 5570 "Start a new test case identified by NAME. All output\n"
c92989d… drh 5571 "through the next \".check\" command is captured for comparison. See the\n"
c92989d… drh 5572 "\".check\" command for additional information.\n"
c92989d… drh 5573 "\n"
c92989d… drh 5574 "Options:\n"
c92989d… drh 5575 " --error-prefix TEXT Change error message prefix text to TEXT\n"
c92989d… drh 5576 },
c92989d… drh 5577 { ".once",
c92989d… drh 5578 "USAGE: .once [OPTIONS] FILE ...\n"
c92989d… drh 5579 "\n"
c92989d… drh 5580 "Write the output for the next line of SQL or the next dot-command into\n"
c92989d… drh 5581 "FILE. If FILE begins with \"|\" then it is a program into which output\n"
c92989d… drh 5582 "is written. The FILE argument should be omitted if one of the -e, -w,\n"
c92989d… drh 5583 "or -x options is used.\n"
c92989d… drh 5584 "\n"
c92989d… drh 5585 "Options:\n"
c92989d… drh 5586 " -e Capture output into a temporary file then bring up\n"
c92989d… drh 5587 " a text editor on that temporary file.\n"
c92989d… drh 5588 " --plain Use plain text rather than HTML tables with -w\n"
c92989d… drh 5589 " -w Capture output into an HTML file then bring up that\n"
c92989d… drh 5590 " file in a web browser\n"
c92989d… drh 5591 " -x Show the output in a spreadsheet. Output is\n"
c92989d… drh 5592 " written to a temp file as CSV then the spreadsheet\n"
c92989d… drh 5593 " is launched when\n"
c92989d… drh 5594 },
c92989d… drh 5595 { ".check",
c92989d… drh 5596 "USAGE: .check [OPTIONS] PATTERN\n"
c92989d… drh 5597 "\n"
c92989d… drh 5598 "Verify the output of all commands since the most recent .testcase\n"
c92989d… drh 5599 "command. Both stdout and stderr are captured and compared, so error\n"
c92989d… drh 5600 "messages are part of the text being compared, however output from\n"
c92989d… drh 5601 "the \".echo on\" dot-command is not captured and is not part of the test\n"
c92989d… drh 5602 "result.\n"
c92989d… drh 5603 "\n"
c92989d… drh 5604 "After checking the result, all captured output is discarded and\n"
c92989d… drh 5605 "output starts going back to the console, unless --keep is used.\n"
c92989d… drh 5606 "\n"
c92989d… drh 5607 "The PATTERN is the concatenation (with a single space separator) of\n"
c92989d… drh 5608 "all arguments that are not part of OPTIONS.\n"
c92989d… drh 5609 "\n"
c92989d… drh 5610 "If PATTERN is \"<<ENDMARK\" (for any ENDMARK) then the actual pattern is\n"
c92989d… drh 5611 "taken from subsequent lines of text up to the first line that begins\n"
c92989d… drh 5612 "with ENDMARK.\n"
c92989d… drh 5613 "\n"
c92989d… drh 5614 "The default comparison algorithm is to ignore all leading and trailing\n"
c92989d… drh 5615 "whitespace and compare the pattern against the result byte-for-byte except\n"
c92989d… drh 5616 "that whitespace characters are equal to other whitespace characters.\n"
c92989d… drh 5617 "Thus if the pattern contains a space character and the result contains\n"
c92989d… drh 5618 "a tab in the same spot, they would still compare equal. The number of\n"
c92989d… drh 5619 "whitespace characters must be the same in the pattern and the result.\n"
c92989d… drh 5620 "\n"
c92989d… drh 5621 "The --glob, --notglob, and --allglob comparisons are extended so that\n"
c92989d… drh 5622 "\"#\" in the pattern matches a sequence of one or more digits with an\n"
c92989d… drh 5623 "optional leading \"+\" or \"-\", and a space in the pattern matches a run\n"
c92989d… drh 5624 "of one or more whitespace characters.\n"
c92989d… drh 5625 "\n"
c92989d… drh 5626 "Options:\n"
c92989d… drh 5627 " --allglob PATTERN is a GLOB matching the entire test output except\n"
c92989d… drh 5628 " leading and trailing whitespace.\n"
c92989d… drh 5629 " --any PATTERN is any substring within the test output.\n"
c92989d… drh 5630 " --exact PATTERN matches the entire test output, byte for byte.\n"
c92989d… drh 5631 " --glob PATTERN is a GLOB matching any substring of the test\n"
c92989d… drh 5632 " output. Leading and trailing whitespace on the PATTERN\n"
c92989d… drh 5633 " is ignored.\n"
c92989d… drh 5634 " --keep Do not reset the test output. One or more .check commands\n"
c92989d… drh 5635 " will follow and do additional tests.\n"
c92989d… drh 5636 " --not Pass if the test output does *not* match PATTERN.\n"
c92989d… drh 5637 " --notglob Shorthand for \"--not --glob\".\n"
c92989d… drh 5638 " --nowhere Shorthand for \"--not --any\".\n"
c92989d… drh 5639 " --regexp PATTERN is a regular expression matching any substring\n"
c92989d… drh 5640 " of the test output.\n"
c92989d… drh 5641 " --show Write test output to the screen, for debugging.\n"
c92989d… drh 5642 },
c92989d… drh 5643 { ".safe",
c92989d… drh 5644 "USAGE: .safe\n"
c92989d… drh 5645 "\n"
c92989d… drh 5646 "This command puts the CLI into \"safe mode\". This command cannot be\n"
c92989d… drh 5647 "undone. The only way to restore full capabilities is to exit and\n"
c92989d… drh 5648 "restart the CLI.\n"
c92989d… drh 5649 "\n"
c92989d… drh 5650 "Safe mode restricts SQL statements and dot-commands so that no\n"
c92989d… drh 5651 "changes may be made to the filesystem other than writing to database\n"
c92989d… drh 5652 "files that are already open.\n"
c92989d… drh 5653 "\n"
c92989d… drh 5654 " * The .open command is blocked unless the database is \":memory:\"\n"
c92989d… drh 5655 " or the --hexdb option is used.\n"
c92989d… drh 5656 " * The ATTACH command of SQL may not be used\n"
c92989d… drh 5657 " * SQL functions with side effects (ex: writefile()) are blocked.\n"
c92989d… drh 5658 " * The \".shell\" and \".system\" dot-commands are blocked.\n"
c92989d… drh 5659 " * Dot-command like \".archive\", \".backup\", \".load\", \".log\", \".save\"\n"
c92989d… drh 5660 " are blocked.\n"
c92989d… drh 5661 " * Other commands with deleterious side effects are blocked.\n"
c92989d… drh 5662 "\n"
c92989d… drh 5663 "Unsafe actions might be simply blocked, or the CLI might issue an error\n"
c92989d… drh 5664 "and exit immediately.\n"
c92989d… drh 5665 "\n"
c92989d… drh 5666 "Safe mode does not prevent harm to database files that are already open.\n"
c92989d… drh 5667 "An attacker can still delete content and even use commands like\n"
c92989d… drh 5668 "\"PRAGMA writable_schema=ON\" to corrupt a database file that is already\n"
c92989d… drh 5669 "open. Safe mode only blocks access to other previously unopened files.\n"
c92989d… drh 5670 "\n"
c92989d… drh 5671 "CAUTION: If third-party extensions with system side effects have been\n"
c92989d… drh 5672 "loaded prior to the .safe command, the CLI has no knowledge of those\n"
c92989d… drh 5673 "extensions and does not know to block them. Unsafe actions might still\n"
c92989d… drh 5674 "be possible using those third-party extension.\n"
c92989d… drh 5675 },
c92989d… drh 5676 { ".if",
c92989d… drh 5677 "USAGE: .if SQL-EXPRESSION\n"
c92989d… drh 5678 "\n"
c92989d… drh 5679 "The argument can be any SQL expression, including a subquery in\n"
c92989d… drh 5680 "parentheses. If the expression evalutes to true (if it is non-zero\n"
c92989d… drh 5681 "when converted into an number) then subsequent statements are\n"
c92989d… drh 5682 "evaluated. If SQL-EXPRESSION evalutes to false or NULL or raises\n"
c92989d… drh 5683 "an error, then subsequent statements are skipped, up until the first\n"
c92989d… drh 5684 "matching .elseif, .else, or .endif.\n"
c92989d… drh 5685 "\n"
c92989d… drh 5686 "Maximum nested depth is limited. An error is raised if .if statements\n"
c92989d… drh 5687 "are nested to deep.\n"
c92989d… drh 5688 "\n"
c92989d… drh 5689 "Every .if must be followed by a matching .endif, or an error is raised.\n"
c92989d… drh 5690 },
c92989d… drh 5691 { ".else",
c92989d… drh 5692 "USAGE: .else\n"
c92989d… drh 5693 "\n"
c92989d… drh 5694 "Invert the sense of the inner-most .if. Start processing if the prior\n"
c92989d… drh 5695 ".if was false. Stop processing if the prior .if was true.\n"
e66a8c7… drh 5696 },
677842d… drh 5697 "current output mode and relevant options. Use the --list option to get\n"
677842d… drh 5698 "a list of available MODE values. Use -v to show all the current output\n"
677842d… drh 5699 "mode settings.\n"
51267fb… drh 5700 " found in the output. ESC can be \"auto\", \"off\",\n"
51267fb… drh 5701 " \"ascii\", or \"symbol\". Default is \"auto\"\n"
471d617… drh 5702 " --fpfmt STRING String is a printf-style format string used to\n"
471d617… drh 5703 " render floating-point values.\n"
471d617… drh 5704 " --ifmt STRING String is a printf-style format string used to\n"
471d617… drh 5705 " render integer values.\n"
17f9878… drh 5706 " --multiinsert N In \"insert\" mode, put multiple rows on a single\n"
17f9878… drh 5707 " INSERT statement until the size exceeds N bytes.\n"
ee87371… drh 5708 " --rowcount BOOLEAN Show \"(N rows)\" at the end of query results.\n"
677842d… drh 5709 " --tag NAME Save current settings as a new mode called NAME.\n"
ee87371… drh 5710 " \"always\", \"sql\", \"csv\", \"html\", \"tcl\", or \"json\".\n"
677842d… drh 5711 },
c92989d… drh 5712 { ".eqp",
c92989d… drh 5713 "USAGE: .eqp EQPMODE [>OUTPUTFILE]\n"
c92989d… drh 5714 "\n"
c92989d… drh 5715 "The .eqp command enables or disables the automatic display of EXPLAIN\n"
c92989d… drh 5716 "output for each SQL statement evaluated. The required EQPMODE argument\n"
c92989d… drh 5717 "may be one of the following:\n"
c92989d… drh 5718 "\n"
c92989d… drh 5719 " full Show both EXPLAIN QUERY PLAN and EXPLAIN output.\n"
c92989d… drh 5720 "\n"
c92989d… drh 5721 " off Disable all explain output.\n"
c92989d… drh 5722 "\n"
c92989d… drh 5723 " on Show EXPLAIN QUERY PLAN output only.\n"
c92989d… drh 5724 "\n"
c92989d… drh 5725 " trace Like \"full\" but also enable VDBE tracing using\n"
c92989d… drh 5726 " PRAGMA vdbe_trace=ON. This option only works if the\n"
c92989d… drh 5727 " CLI is compiled with -DSQLITE_DEBUG. The trace output\n"
c92989d… drh 5728 " always appears on stdout and is not redirected to a file.\n"
c92989d… drh 5729 "\n"
c92989d… drh 5730 " trigger Like \"full\" but also show EXPLAIN output for trigger\n"
c92989d… drh 5731 " subprograms.\n"
c92989d… drh 5732 "\n"
c92989d… drh 5733 "The EQPMODE maybe be optionally followed by a filename. If a file is\n"
c92989d… drh 5734 "specified, with or without a single leading \">\", then the file is\n"
c92989d… drh 5735 "deleted and all subsequent explain output is appended to that file.\n"
c92989d… drh 5736 "If the filename begins with \">>\" then the content of the file is retained\n"
c92989d… drh 5737 "and all output is appended. If not redirection argument is provided,\n"
c92989d… drh 5738 "output redirection is cancelled. The ability to redirect is not available\n"
c92989d… drh 5739 "for --safe mode.\n"
c92989d… drh 5740 },
c92989d… drh 5741 { ".endif",
c92989d… drh 5742 "USAGE: .endif\n"
c92989d… drh 5743 "\n"
c92989d… drh 5744 "Terminate an .if statement.\n"
c92989d… drh 5745 },
c92989d… drh 5746 { ".stats",
c92989d… drh 5747 "USAGE: .stats [OPTIONS] ...\n"
c92989d… drh 5748 "\n"
c92989d… drh 5749 "Show status information about the database and database connection.\n"
c92989d… drh 5750 "The stats setting is persistent, unless the --once option is used.\n"
c92989d… drh 5751 "Options are cumulative and are processed from left to right.\n"
c92989d… drh 5752 "If no options are given, that is the same as \".stats all --once\".\n"
c92989d… drh 5753 "\n"
c92989d… drh 5754 "Options:\n"
c92989d… drh 5755 " all Show all available stats.\n"
c92989d… drh 5756 " io Show I/O stats (Linux only).\n"
c92989d… drh 5757 " mem Show basic memory usage.\n"
c92989d… drh 5758 " off Show nothing. Turn off stat display.\n"
c92989d… drh 5759 " on Shorthand for \"stmt xmem\".\n"
c92989d… drh 5760 " --once Show the stats once. Do not change the default stats display.\n"
c92989d… drh 5761 " reset Reset \"max\" values after next display of each that value.\n"
c92989d… drh 5762 " stmt Show information about the last SQL statement.\n"
c92989d… drh 5763 " vmstep Show the number of virtual machine steps taken.\n"
c92989d… drh 5764 " xmem Show detailed memory status information\n"
c92989d… drh 5765 " xstmt Show details about each SQL statement\n"
c92989d… drh 5766 },
c92989d… drh 5767 { ".elseif",
c92989d… drh 5768 "USAGE: .elseif SQL-EXPRESSION\n"
c92989d… drh 5769 "\n"
c92989d… drh 5770 "An \"else-if\". The prior .if is finished and a new condition is applied.\n"
c92989d… drh 5771 },
c92989d… drh 5772 { ".clone",
c92989d… drh 5773 "USAGE: .clone FILE\n"
c92989d… drh 5774 "\n"
c92989d… drh 5775 "The original purpose of the \".clone\" command (when it was first introduced\n"
c92989d… drh 5776 "in 2014) was to try to recover content for a corrupt database file and\n"
c92989d… drh 5777 "write the recovered content into a new database named FILE. However,\n"
c92989d… drh 5778 "the command has always been experimental and undocumented. Today, it\n"
c92989d… drh 5779 "does nothing more than make a copy of the main database into a new\n"
c92989d… drh 5780 "database named by its only argument, FILE. No repair attempts are\n"
c92989d… drh 5781 "made. The command is retained for legacy only.\n"
c92989d… drh 5782 },
c92989d… drh 5783 FILE *in = (zName && zName[0]) ? sqlite3_fopen(zName, "rb") : 0;
e66a8c7… drh 5784 if( nIn<0 ){
e66a8c7… drh 5785 cli_printf(stderr,"Error: cannot read '%s'\n", zName);
e66a8c7… drh 5786 fclose(in);
e66a8c7… drh 5787 return 0;
e66a8c7… drh 5788 }
e66a8c7… drh 5789 nRead = fread(pBuf, 1, nIn, in);
e66a8c7… drh 5790 if( nRead!=(size_t)nIn ){
c92989d… drh 5791 if( sqlite3_strlike("%.clitest",z,0)==0 ) return 1;
e66a8c7… drh 5792 if( shell_fgets(p, zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
e66a8c7… drh 5793 for(nLine++; shell_fgets(p, zLine, sizeof(zLine), in)!=0; nLine++){
e66a8c7… drh 5794 while( shell_fgets(p, zLine, sizeof(zLine), p->in)!=0 ){
c92989d… drh 5795 }
c92989d… drh 5796
c92989d… drh 5797 /*
c92989d… drh 5798 ** SQL function: dualrep(X)
c92989d… drh 5799 **
c92989d… drh 5800 ** Return the value X. But if X is in a numeric representation (an
c92989d… drh 5801 ** integer or a float) then return a dual-representation where the
c92989d… drh 5802 ** result is both numeric and text at the same time. This has no
c92989d… drh 5803 ** known practical application, but is useful in testing SQLite
c92989d… drh 5804 ** internals.
c92989d… drh 5805 */
c92989d… drh 5806 static void shellDualRepFunc(
c92989d… drh 5807 sqlite3_context *context,
c92989d… drh 5808 int argcUnused,
c92989d… drh 5809 sqlite3_value **argv
c92989d… drh 5810 ){
c92989d… drh 5811 (void)argcUnused;
c92989d… drh 5812 sqlite3_value_text(argv[0]);
c92989d… drh 5813 sqlite3_result_value(context, argv[0]);
40c5397… drh 5814 }
40c5397… drh 5815
40c5397… drh 5816 /*
40c5397… drh 5817 **
40c5397… drh 5818 ** For use internally and for debugging and testing only. This function
40c5397… drh 5819 ** is subject to change or removal in future versions.
51267fb… drh 5820 assert( strstr(zFake,"*/")==0 );
1d618cc… drh 5821
1d618cc… drh 5822 /* Forward reference */
1d618cc… drh 5823 static void shellTempFilenameFunc(sqlite3_context*,int,sqlite3_value**);
3361df8… drh 5824
3361df8… drh 5825 const char *zHOME; /* Value of HOME environment variable */
3361df8… drh 5826 char *zToFree = 0; /* Filename with ~/ prefix expansion */
3361df8… drh 5827
3361df8… drh 5828 /* If the zDbFilename does not exist and begins with ~/ then replace
3361df8… drh 5829 ** the ~ with the home directory.
3361df8… drh 5830 */
3361df8… drh 5831 if( zDbFilename && zDbFilename[0]=='~'
3361df8… drh 5832 #ifdef _WIN32
3361df8… drh 5833 && (zDbFilename[1]=='/' || zDbFilename[1]=='\\')
3361df8… drh 5834 #else
3361df8… drh 5835 && zDbFilename[1]=='/'
3361df8… drh 5836 #endif
3361df8… drh 5837 && access(zDbFilename,0)!=0
3361df8… drh 5838 && (zHOME = getenv("HOME"))!=0 && zHOME[0]!=0
3361df8… drh 5839 ){
3361df8… drh 5840 size_t nHOME = strlen(zHOME);
3361df8… drh 5841 size_t nFN = strlen(zDbFilename);
3361df8… drh 5842 zToFree = malloc(nHOME+nFN+1);
3361df8… drh 5843 if( zToFree ){
3361df8… drh 5844 memcpy(zToFree, zHOME, nHOME);
3361df8… drh 5845 memcpy(zToFree+nHOME, zDbFilename+1, nFN);
3361df8… drh 5846 zDbFilename = zToFree;
3361df8… drh 5847 }
3361df8… drh 5848 }
3361df8… drh 5849
c92989d… drh 5850 sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,
c92989d… drh 5851 (int*)0);
c92989d… drh 5852 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,
c92989d… drh 5853 (int*)0);
c92989d… drh 5854 sqlite3_enable_load_extension(p->db, !p->bSafeMode);
71439dc… drh 5855 sqlite3_diskused_init(p->db, 0, 0);
ee87371… drh 5856 sqlite3_strdup_init(p->db, 0, 0);
564007c… drh 5857 if( !p->bSafeMode ){
c92989d… drh 5858 sqlite3_tryeval_init(p->db, 0, 0);
c92989d… drh 5859 #ifndef SQLITE_SHELL_FIDDLE
564007c… drh 5860 sqlite3_fileio_init(p->db, 0, 0);
c92989d… drh 5861 #endif
e66a8c7… drh 5862 sqlite3_create_function(p->db, "capable", 1, SQLITE_UTF8, p,
e66a8c7… drh 5863 shellCapable, 0, 0);
40c5397… drh 5864 sqlite3_create_function(p->db, "shell_complete_sql", 1, SQLITE_UTF8, p,
40c5397… drh 5865 shell_complete_sql, 0, 0);
40c5397… drh 5866 sqlite3_create_function(p->db, "shell_complete_sql", 2, SQLITE_UTF8, p,
40c5397… drh 5867 shell_complete_sql, 0, 0);
c92989d… drh 5868 sqlite3_create_function(p->db, "dualrep",1,SQLITE_UTF8,0,
c92989d… drh 5869 shellDualRepFunc, 0, 0);
c93e1c8… drh 5870 sqlite3_create_function(p->db, "shell_prompt_test", -1, SQLITE_UTF8,
3361df8… drh 5871 p, shellExpandPrompt, 0, 0);
1d618cc… drh 5872 sqlite3_create_function(p->db, "shell_temp_filename", 1, SQLITE_UTF8,
1d618cc… drh 5873 p, shellTempFilenameFunc, 0, 0);
40c5397… drh 5874 #ifdef SQLITE_DEBUG
40c5397… drh 5875 sqlite3_create_function(p->db, "sqlite3_incomplete", 1, SQLITE_UTF8,
40c5397… drh 5876 p, shellIncompleteFunc, 0, 0);
40c5397… drh 5877 #endif
3361df8… drh 5878
3361df8… drh 5879 free(zToFree);
e66a8c7… drh 5880 #ifndef SQLITE_SHELL_FIDDLE
e66a8c7… drh 5881 /*
e66a8c7… drh 5882 ** DOT-COMMAND: .clone
e66a8c7… drh 5883 **
e66a8c7… drh 5884 ** USAGE: .clone FILE
e66a8c7… drh 5885 **
e66a8c7… drh 5886 ** The original purpose of the ".clone" command (when it was first introduced
e66a8c7… drh 5887 ** in 2014) was to try to recover content for a corrupt database file and
e66a8c7… drh 5888 ** write the recovered content into a new database named FILE. However,
e66a8c7… drh 5889 ** the command has always been experimental and undocumented. Today, it
e66a8c7… drh 5890 ** does nothing more than make a copy of the main database into a new
e66a8c7… drh 5891 ** database named by its only argument, FILE. No repair attempts are
e66a8c7… drh 5892 ** made. The command is retained for legacy only.
e66a8c7… drh 5893 */
e66a8c7… drh 5894 static int dotCmdClone(ShellState *p){
e66a8c7… drh 5895 int nArg = p->dot.nArg; /* Number of arguments */
e66a8c7… drh 5896 char **azArg = p->dot.azArg;/* Argument list */
e66a8c7… drh 5897 char *zSql;
e66a8c7… drh 5898 sqlite3_stmt *pStmt = 0;
e66a8c7… drh 5899 int rc;
e66a8c7… drh 5900
e66a8c7… drh 5901 failIfSafeMode(p, "cannot run .clone in safe mode");
e66a8c7… drh 5902 if( nArg!=2 ){
e66a8c7… drh 5903 dotCmdError(p, nArg, 0, "missing FILE argument");
e66a8c7… drh 5904 return 1;
e66a8c7… drh 5905 }
e66a8c7… drh 5906 zSql = sqlite3_mprintf("VACUUM INTO %Q", azArg[1]);
e66a8c7… drh 5907 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
e66a8c7… drh 5908 sqlite3_free(zSql);
e66a8c7… drh 5909 if( rc!=SQLITE_OK || SQLITE_DONE!=sqlite3_step(pStmt) ){
e66a8c7… drh 5910 cli_printf(stderr,"Error: cannot clone into \"%s\"\n", azArg[1]);
e66a8c7… drh 5911 sqlite3_finalize(pStmt);
e66a8c7… drh 5912 return 1;
e66a8c7… drh 5913 }
e66a8c7… drh 5914 sqlite3_finalize(pStmt);
e66a8c7… drh 5915 return 0;
e66a8c7… drh 5916 }
e66a8c7… drh 5917 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
2d6bfab… drh 5918 #ifdef __linux__
2d6bfab… drh 5919 zCmd = sqlite3_mprintf("%s %s 2>/dev/null", zXdgOpenCmd, p->zTempFile);
2d6bfab… drh 5920 #else
2d6bfab… drh 5921 #endif
9b67f46… drh 5922 ** going before we continue and potentially delete the
1d618cc… drh 5923 p->aUnlink = realloc(p->aUnlink, sizeof(Unlink)*(1+p->nUnlink));
1d618cc… drh 5924 shell_check_oom(p->aUnlink);
2d6bfab… drh 5925 p->aUnlink[p->nUnlink].tm = timeOfDay()+10000000;
1d618cc… drh 5926 p->aUnlink[p->nUnlink].zFN = p->zTempFile;
1d618cc… drh 5927 p->nUnlink++;
1d618cc… drh 5928 p->zTempFile = 0;
c92989d… drh 5929 }else if( c=='[' || c=='#' || IsSpace(c) ){
c92989d… drh 5930 /* The next pattern element is not a literal character. Try to
c92989d… drh 5931 ** match it at each position in the remaining text. */
1d618cc… drh 5932 **
1d618cc… drh 5933 ** If unsuccessful on the first attempt and if pRetry!=NULL and pRetry[0]
1d618cc… drh 5934 ** is positive, then delay for pRetry[0] milliseconds and try again. On
1d618cc… drh 5935 ** a retry, pRetry[0] is set to zero. Unsuccessful unlinks usually only
1d618cc… drh 5936 ** happen on Windows. It is possible (in theory) for unlink() to fail
1d618cc… drh 5937 ** on Unix, but it rarely happens.
1d618cc… drh 5938 **
1d618cc… drh 5939 ** Return 0 on success and non-zero if unable.
1d618cc… drh 5940 int shellDeleteFile(const char *zFilename, int *pRetry){
1d618cc… drh 5941 for(;;){
1d618cc… drh 5942 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
1d618cc… drh 5943 rc = _wunlink(z);
1d618cc… drh 5944 if( rc && _waccess(z,0)!=0 ) rc = 0;
1d618cc… drh 5945 sqlite3_free(z);
1d618cc… drh 5946 rc = unlink(zFilename);
1d618cc… drh 5947 if( rc && access(zFilename, 0)!=0 ) rc = 0;
1d618cc… drh 5948 if( rc && pRetry && pRetry[0] ){
1d618cc… drh 5949 sqlite3_sleep(pRetry[0]);
1d618cc… drh 5950 pRetry[0] = 0;
1d618cc… drh 5951 continue;
2d6bfab… drh 5952 }else{
2d6bfab… drh 5953 break;
1d618cc… drh 5954 }
1d618cc… drh 5955 }
1d618cc… drh 5956 ** This routine does two things:
1d618cc… drh 5957 **
1d618cc… drh 5958 ** (1) Delete (unlink) temporary files that are no longer needed.
1d618cc… drh 5959 ** (2) Free memory used to hold the names of those temporary files.
1d618cc… drh 5960 **
1d618cc… drh 5961 ** Temp filenames are stored in p->zTempName and in the p->aUnlink[]
1d618cc… drh 5962 ** array. The p->zTempFile is always subject to immediate deletion. The
1d618cc… drh 5963 ** temp files named in p->aUnlink[] are usually not deleted until after
1d618cc… drh 5964 ** the timestamp stored in the p->aUnlink[].tm field, except if
1d618cc… drh 5965 ** bForce is true, the p->aUnlink[] files will be deleted even if they
1d618cc… drh 5966 ** have not reached their expiration, as long as a delay of at least
1d618cc… drh 5967 ** nDelay milliseconds occurs first.
1d618cc… drh 5968 **
1d618cc… drh 5969 ** If nDelay is non-zero and a deletion attempt is not successful,
1d618cc… drh 5970 ** wait for nDelay milliseconds and try again before giving up. Only
1d618cc… drh 5971 ** a single wait occurs, even if problems are encountered with multiple
1d618cc… drh 5972 ** temp files. Only the first problem seen takes the delay. Thus
2d6bfab… drh 5973 ** the total delay never exceeds nDelay milliseconds.
1d618cc… drh 5974 **
1d618cc… drh 5975 ** If bForce is true, deletion is attempted on p->aUnlink[] files
1d618cc… drh 5976 ** even if their time has not expired. However, there is a pause
2d6bfab… drh 5977 ** of up to nDelay milliseconds before doing the deletion. Memory
2d6bfab… drh 5978 ** used to hold filenames is reclaimed regardless of whether or not
2d6bfab… drh 5979 ** the delete is successful.
1d618cc… drh 5980 **
1d618cc… drh 5981 ** The bForce flag is used only when the process is about to exit. When
1d618cc… drh 5982 ** bForce is set, that indicates that this is our last opportunity to
1d618cc… drh 5983 ** clean up temporary files.
1d618cc… drh 5984 static void clearTempFile(ShellState *p, int nDelay, int bForce){
2d6bfab… drh 5985 int alwaysFree = bForce;
1d618cc… drh 5986 int rc = 0;
1d618cc… drh 5987 if( p->zTempFile && (!p->doXdgOpen || bForce) ){
1d618cc… drh 5988 rc = shellDeleteFile(p->zTempFile, &nDelay);
1d618cc… drh 5989 if( rc==0 || alwaysFree ){
1d618cc… drh 5990 sqlite3_free(p->zTempFile);
1d618cc… drh 5991 p->zTempFile = 0;
1d618cc… drh 5992 }
1d618cc… drh 5993 }
1d618cc… drh 5994 if( p->nUnlink ){
1d618cc… drh 5995 unsigned int i;
1d618cc… drh 5996 for(i=0; i<p->nUnlink; i++){
1d618cc… drh 5997 sqlite3_int64 tmToGo = p->aUnlink[i].tm - timeOfDay();
1d618cc… drh 5998 int doDelete = tmToGo<=0;
1d618cc… drh 5999 if( !doDelete && alwaysFree ){
1d618cc… drh 6000 int tmSleep = nDelay;
2d6bfab… drh 6001 if( tmSleep > tmToGo/1000 ) tmSleep = (int)(tmToGo/1000);
2d6bfab… drh 6002 if( tmSleep>=1000 ){
2d6bfab… drh 6003 cli_printf(p->out,"Waiting about %d.%d seconds to delete temp"
2d6bfab… drh 6004 " file(s)\n", tmSleep/1000, (tmSleep/100)%10);
2d6bfab… drh 6005 }
1d618cc… drh 6006 sqlite3_sleep(tmSleep);
1d618cc… drh 6007 nDelay -= tmSleep;
1d618cc… drh 6008 doDelete = 1;
1d618cc… drh 6009 }
1d618cc… drh 6010 if( doDelete ){
1d618cc… drh 6011 char *zFN = p->aUnlink[i].zFN;
1d618cc… drh 6012 rc = shellDeleteFile(zFN, &nDelay);
1d618cc… drh 6013 if( rc==0 || alwaysFree ){
1d618cc… drh 6014 sqlite3_free(p->aUnlink[i].zFN);
1d618cc… drh 6015 p->nUnlink--;
1d618cc… drh 6016 if( i<p->nUnlink ){
1d618cc… drh 6017 p->aUnlink[i] = p->aUnlink[p->nUnlink];
1d618cc… drh 6018 memset(&p->aUnlink[p->nUnlink], 0, sizeof(Unlink));
1d618cc… drh 6019 }
1d618cc… drh 6020 i--;
1d618cc… drh 6021 }
1d618cc… drh 6022 }
1d618cc… drh 6023 }
1d618cc… drh 6024 if( p->nUnlink==0 ){
1d618cc… drh 6025 free(p->aUnlink);
1d618cc… drh 6026 p->aUnlink = 0;
1d618cc… drh 6027 }
1d618cc… drh 6028 }
1d618cc… drh 6029 clearTempFile(p,10,0);
1d618cc… drh 6030 }
1d618cc… drh 6031
1d618cc… drh 6032 /*
1d618cc… drh 6033 ** SQL function: shell_temp_filename(SUFFIX)
2d6bfab… drh 6034 **
40c5397… drh 6035 ** For use internally and for debugging and testing only. This function
40c5397… drh 6036 ** is subject to change or removal in future versions.
40c5397… drh 6037 **
1d618cc… drh 6038 ** Return a randomly generated temporary filename.
1d618cc… drh 6039 */
1d618cc… drh 6040 static void shellTempFilenameFunc(
1d618cc… drh 6041 sqlite3_context *pCtx,
1d618cc… drh 6042 int nVal,
1d618cc… drh 6043 sqlite3_value **apVal
1d618cc… drh 6044 ){
1d618cc… drh 6045 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1d618cc… drh 6046 const char *zSuffix = (const char*)sqlite3_value_text(apVal[0]);
1d618cc… drh 6047 (void)nVal;
1d618cc… drh 6048 if( zSuffix==0 ) zSuffix = "";
1d618cc… drh 6049 newTempFile(p, zSuffix);
1d618cc… drh 6050 sqlite3_result_text(pCtx, p->zTempFile, -1, SQLITE_TRANSIENT);
1d618cc… drh 6051 sqlite3_free(p->zTempFile);
1d618cc… drh 6052 p->zTempFile = 0;
c92989d… drh 6053 if( strchr(zTarget,'\n') ) zTarget = "(REDACTED)";
c92989d… drh 6054 if( strstr(zFrom,"*/") ) zFrom = "(REDACTED)";
c92989d… drh 6055 if( strstr(zTarget,"*/") ) zTarget = "(REDACTED)";
ba00a43… drh 6056 u8 bDryRun; /* 1 for --dry-run, 2 for --debug */
ba00a43… drh 6057 #define AR_SWITCH_DEBUG 14
ba00a43… drh 6058 if( pAr->bDryRun<2 ) pAr->bDryRun = 1;
ba00a43… drh 6059 break;
ba00a43… drh 6060 case AR_SWITCH_DEBUG:
ba00a43… drh 6061 pAr->bDryRun = 2;
ba00a43… drh 6062 { "debug", 0, AR_SWITCH_DEBUG, 0 },
e66a8c7… drh 6063 if( pSql ) cli_printf(pAr->out, "%s\n", sqlite3_sql(pSql));
ba00a43… drh 6064 /* The zSql1[] string is a template for the query that does the
ba00a43… drh 6065 ** extraction. Notes:
ba00a43… drh 6066 **
ba00a43… drh 6067 ** * $dir is the directory into which the archive is to be extracted
ba00a43… drh 6068 ** * $pass is the integer pass number: 0, 1, or 2
ba00a43… drh 6069 ** * The dest CTE is created so that realpath($dir) only needs
ba00a43… drh 6070 ** to be called once.
ba00a43… drh 6071 */
ba00a43… drh 6072 "WITH dest(dpath,dlen) AS (\n"
ba00a43… drh 6073 #ifdef _WIN32
ba00a43… drh 6074 " SELECT realpath($dir) || '\\',\n"
ba00a43… drh 6075 #else
ba00a43… drh 6076 " SELECT realpath($dir) || '/',\n"
ba00a43… drh 6077 #endif
ba00a43… drh 6078 " 1+length(realpath($dir))\n"
ba00a43… drh 6079 ")\n"
ba00a43… drh 6080 "SELECT\n"
ba00a43… drh 6081 " ($dir || name),\n"
ba00a43… drh 6082 " CASE $dryrun\n" /* vv--- azExtraArg */
ba00a43… drh 6083 " WHEN 0 THEN writefile($dir||name, %s, mode, mtime)\n"
ba00a43… drh 6084 " WHEN 1 THEN 0\n"
ba00a43… drh 6085 " ELSE shell_putsnl(format('writefile(%%Q,%%s,%%0o,%%d)',"
ba00a43… drh 6086 "$dir||name,quote(%s),mode,mtime)) IS NULL\n"
ba00a43… drh 6087 " END\n" /* ^^--- azExtraArg */
b8ab8b3… drh 6088 " FROM dest CROSS JOIN %s\n"
ba00a43… drh 6089 " WHERE (%s)\n" /* ^^-- pAr->zSrcTable */
ba00a43… drh 6090 /* ^^--- zWhere */
ba00a43… drh 6091 " AND (CASE $pass WHEN 0 THEN (mode&0xf000)<>0xa000\n"
ba00a43… drh 6092 " WHEN 1 THEN (mode&0xf000)=0xa000\n"
ba00a43… drh 6093 " ELSE data IS NULL END)\n"
b8ab8b3… drh 6094 " AND dpath=substr(realpath($dir||name),1,dlen)\n" /* No escapes */
b8ab8b3… drh 6095 " AND name NOT GLOB '*..[/\\]*'\n"; /* No /../ in paths */
ba00a43… drh 6096 azExtraArg[pAr->bZip],
ba00a43… drh 6097 azExtraArg[pAr->bZip],
ba00a43… drh 6098 pAr->zSrcTable,
ba00a43… drh 6099 zWhere
b8ab8b3… drh 6100 j = sqlite3_bind_parameter_index(pSql, "$dryrun");
b8ab8b3… drh 6101 sqlite3_bind_int(pSql, j, pAr->bDryRun);
b8ab8b3… drh 6102
b8ab8b3… drh 6103 /* Run the SELECT statement twice
ba00a43… drh 6104 ** (0) writefile() files and directories
ba00a43… drh 6105 ** (1) writefile() symlinks
ba00a43… drh 6106 ** (2) writefile() for directory again
ba00a43… drh 6107 ** The third pass is so that the timestamps for extracted directories
b8ab8b3… drh 6108 ** will be reset to the value in the archive, since populating them
b8ab8b3… drh 6109 ** in the first pass will have changed the timestamp. */
ba00a43… drh 6110 for(i=0; i<3; i++){
ba00a43… drh 6111 if( pAr->bDryRun>=2 ){
ba00a43… drh 6112 cli_printf(pAr->out, "*** BEGIN PASS %d ***\n", i+1);
ba00a43… drh 6113 }
b8ab8b3… drh 6114 j = sqlite3_bind_parameter_index(pSql, "$pass");
ba00a43… drh 6115 if( pAr->bDryRun && i==0 ){
b8ab8b3… drh 6116 }
b8ab8b3… drh 6117 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
b8ab8b3… drh 6118 if( i==0 && pAr->bVerbose ){
b8ab8b3… drh 6119 cli_printf(pAr->out, "%s\n", sqlite3_column_text(pSql, 0));
ba00a43… drh 6120 if( pAr->bDryRun==1 ) break;
ba00a43… drh 6121 if( pAr->bDryRun>=2 ){
ba00a43… drh 6122 cli_printf(pAr->out, "*** END PASS %d ***\n", i+1);
ba00a43… drh 6123 }
40c5397… drh 6124 sqlite3_str *pOut = sqlite3_str_new(pState->db);
40c5397… drh 6125 char *zOut;
40c5397… drh 6126 int rc = SQLITE_OK;
40c5397… drh 6127 sqlite3_str_appendall(pOut, zSql);
40c5397… drh 6128 appendCompletion(pOut, zSql, 0);
40c5397… drh 6129 zOut = sqlite3_str_value(pOut);
40c5397… drh 6130 if( zOut ){
40c5397… drh 6131 cli_printf(pState->out, "%s;\n", zOut);
40c5397… drh 6132 }else{
40c5397… drh 6133 rc = SQLITE_NOMEM;
40c5397… drh 6134 }
40c5397… drh 6135 sqlite3_str_free(pOut);
40c5397… drh 6136 return rc;
c92989d… drh 6137 int bUnsafe = 0; /* 1 if --unsafe */
c92989d… drh 6138 }else
c92989d… drh 6139 if( n<=7 && memcmp("-unsafe", z, n)==0 ){
c92989d… drh 6140 bUnsafe = 1;
c92989d… drh 6141 if( !bUnsafe ) cli_printf(pState->out, ".safe\n");
a570ebc… drh 6142 cname,\
17f9878… drh 6143 "sql LIKE 'CREATE VIRTUAL TABLE%%' AND (%s)", zLike ? zLike : "true"
564007c… drh 6144 }else if( cli_strcmp(z,"-schema")==0 ){
564007c… drh 6145 if( i==nArg-1 ){
564007c… drh 6146 dotCmdError(p, i, "missing argument", 0);
564007c… drh 6147 return 1;
564007c… drh 6148 }
564007c… drh 6149 }else if( cli_strcmp(z,"-skip")==0 ){
564007c… drh 6150 if( i==nArg-1 ){
564007c… drh 6151 dotCmdError(p, i, "missing argument", 0);
564007c… drh 6152 return 1;
564007c… drh 6153 }
1d618cc… drh 6154 if( sCtx.cColSep==0 ) sCtx.cColSep = '\037';
1d618cc… drh 6155 if( sCtx.cRowSep==0 ) sCtx.cRowSep = '\036';
564007c… drh 6156 if( i==nArg-1 ){
564007c… drh 6157 dotCmdError(p, i, "missing argument", 0);
564007c… drh 6158 return 1;
564007c… drh 6159 }
564007c… drh 6160 if( i==nArg-1 ){
564007c… drh 6161 dotCmdError(p, i, "missing argument", 0);
564007c… drh 6162 return 1;
564007c… drh 6163 }
e66a8c7… drh 6164 while( shell_fgets(p, zLine,sizeof(zLine),p->in) ){
e6e6a32… drh 6165 " WHERE name=%Q COLLATE nocase AND type='view'",
c92989d… drh 6166 "Added %d rows with %d errors using %lld lines of input\n",
ee87371… drh 6167 ** 1: Show "--title off"
ee87371… drh 6168 ** 2: Show "--title on"
ee87371… drh 6169 ** 3: Show "--title always"
ee87371… drh 6170 ** 4: Show "--title VALUE" where VALUE is an encoding method
ee87371… drh 6171 ** 5: Show "--title VALUE" as in 3, followed by "--title always"
cb89386… drh 6172 ** vvvvvvvv */
cb89386… drh 6173 sqlite3_uint64 v = UINT64_C(0x0133013311220102);
cb89386… drh 6174 /* ^^^^ ^^^^
ee87371… drh 6175 v &= 3;
ee87371… drh 6176 /* At this point v means:
ee87371… drh 6177 ** 0: The titles do not matter. Never show anything.
ee87371… drh 6178 ** 1: Show "--title off"
ee87371… drh 6179 ** 2: Show "--title on"
ee87371… drh 6180 ** 3: Show "--title VALUE" where VALUE is an encoding method
ee87371… drh 6181 ** to use, one of: plain sql csv html tcl json
ee87371… drh 6182 ** If bTitles is QRF_Always, convert 2->3, 3->5. If bTitles is not
ee87371… drh 6183 ** QRF_Always, convert 3->4.
ee87371… drh 6184 */
ee87371… drh 6185 if( p->mode.spec.bTitles==QRF_Always ){
ee87371… drh 6186 if( v==3 ) v = 5;
ee87371… drh 6187 if( v==2 ) v = 3;
ee87371… drh 6188 }else{
ee87371… drh 6189 if( v==3 ) v = 4;
ee87371… drh 6190 }
ee87371… drh 6191 return v;
677842d… drh 6192 ** current output mode and relevant options. Use the --list option to get
677842d… drh 6193 ** a list of available MODE values. Use -v to show all the current output
677842d… drh 6194 ** mode settings.
51267fb… drh 6195 ** found in the output. ESC can be "auto", "off",
51267fb… drh 6196 ** "ascii", or "symbol". Default is "auto"
471d617… drh 6197 ** --fpfmt STRING String is a printf-style format string used to
471d617… drh 6198 ** render floating-point values.
471d617… drh 6199 ** --ifmt STRING String is a printf-style format string used to
471d617… drh 6200 ** render integer values.
17f9878… drh 6201 ** --multiinsert N In "insert" mode, put multiple rows on a single
17f9878… drh 6202 ** INSERT statement until the size exceeds N bytes.
ee87371… drh 6203 ** --rowcount BOOLEAN Show "(N rows)" at the end of query results.
677842d… drh 6204 ** --tag NAME Save current settings as a new mode called NAME.
ee87371… drh 6205 ** "always", "sql", "csv", "html", "tcl", or "json".
17f9878… drh 6206 }else if( 0<=(k=pickStr(z,0,
17f9878… drh 6207 "-charlimit","-linelimit","-titlelimit","-multiinsert","")) ){
c92989d… drh 6208 i64 w; /* 0 1 2 3 */
c92989d… drh 6209 case 0: p->mode.spec.nCharLimit = modeClamp32(w); break;
c92989d… drh 6210 case 1: p->mode.spec.nLineLimit = modeClamp16(w); break;
c92989d… drh 6211 case 2: p->mode.spec.nTitleLimit = modeClamp16(w); break;
c92989d… drh 6212 default: p->mode.spec.nMultiInsert = modeClamp32(w); break;
51267fb… drh 6213 } /* 0 1 2 3 */
51267fb… drh 6214 k = pickStr(azArg[i],&zErr,"auto", "off","ascii","symbol","");
51267fb… drh 6215 p->mode.spec.eEsc = k;
71439dc… drh 6216 if( modeSetLimit(p, azArg[i]) ){
71439dc… drh 6217 dotCmdError(p, i, "bad argument", "Should be \"on\" or \"off\" or "
71439dc… drh 6218 "\"L,C,T\" where L, C, and T are unsigned integers");
71439dc… drh 6219 return 1;
471d617… drh 6220 }else if( optionMatch(z,"ifmt") ){
471d617… drh 6221 if( i+1>=nArg ){
471d617… drh 6222 dotCmdError(p, i, "missing argument", 0);
471d617… drh 6223 return 1;
471d617… drh 6224 }
471d617… drh 6225 i++;
471d617… drh 6226 if( azArg[i][0]==0 || cli_strcmp(azArg[i],"auto")==0 ){
471d617… drh 6227 p->mode.spec.zIFmt = 0;
471d617… drh 6228 }else if( sqlite3_qrf_ckformat(azArg[i])!=1 ){
471d617… drh 6229 dotCmdError(p, i, "not a valid integer format", 0);
471d617… drh 6230 return 1;
471d617… drh 6231 }else{
471d617… drh 6232 assert( strlen(azArg[i])<sizeof(p->mode.zIFmt)-1 );
471d617… drh 6233 memcpy(p->mode.zIFmt, azArg[i], strlen(azArg[i])+1);
471d617… drh 6234 p->mode.spec.zIFmt = p->mode.zIFmt;
471d617… drh 6235 }
471d617… drh 6236 chng = 1;
471d617… drh 6237 }else if( optionMatch(z,"fpfmt") ){
471d617… drh 6238 if( i+1>=nArg ){
471d617… drh 6239 dotCmdError(p, i, "missing argument", 0);
471d617… drh 6240 return 1;
471d617… drh 6241 }
471d617… drh 6242 i++;
471d617… drh 6243 if( azArg[i][0]==0 || cli_strcmp(azArg[i],"auto")==0 ){
471d617… drh 6244 p->mode.spec.zFpFmt = 0;
471d617… drh 6245 }else if( sqlite3_qrf_ckformat(azArg[i])!=2 ){
471d617… drh 6246 dotCmdError(p, i, "not a valid floating-point format", 0);
471d617… drh 6247 return 1;
471d617… drh 6248 }else{
471d617… drh 6249 assert( strlen(azArg[i])<sizeof(p->mode.zFpFmt)-1 );
471d617… drh 6250 memcpy(p->mode.zFpFmt, azArg[i], strlen(azArg[i])+1);
471d617… drh 6251 p->mode.spec.zFpFmt = p->mode.zFpFmt;
471d617… drh 6252 }
471d617… drh 6253 chng = 1;
c92989d… drh 6254 int saved_eMode = p->mode.eMode; /* Don't change the mode */
c92989d… drh 6255 u8 saved_echo = p->mode.mFlags & MFLG_ECHO; /* Don't reset --echo */
c92989d… drh 6256 modeFree(&p->mode); /* Reset everything else */
c92989d… drh 6257 p->mode.mFlags = saved_echo;
ee87371… drh 6258 }else if( optionMatch(z,"rowcount") ){
ee87371… drh 6259 if( i+1>=nArg ){
ee87371… drh 6260 dotCmdError(p, i, "missing argument", 0);
ee87371… drh 6261 return 1;
ee87371… drh 6262 }
ee87371… drh 6263 p->mode.spec.bRowCount = booleanValue(azArg[++i]) ? QRF_Yes : QRF_No;
ee87371… drh 6264 chng = 1;
ee87371… drh 6265 /* The --titles option controls two fields of the
ee87371… drh 6266 ** sqlite3_qrf_spec object: eTitle and bTitles.
ee87371… drh 6267 **
ee87371… drh 6268 ** --titles eTitle bTitles
ee87371… drh 6269 ** -------- --------------- ---------------------
ee87371… drh 6270 ** "off" (unchanged) QRF_Off
ee87371… drh 6271 ** "on" (unchanged) QRF_On
ee87371… drh 6272 ** "always" (unchanged) QRF_Always
ee87371… drh 6273 ** "auto", (default) (default)
ee87371… drh 6274 ** "plain" QRF_TEXT_Plain QRF_Always or QRF_On
ee87371… drh 6275 ** "sql" QRF_TEXT_Sql QRF_Always or QRF_On
ee87371… drh 6276 ** "csv" QRF_TEXT_Csv QRF_Always or QRF_On
ee87371… drh 6277 ** "html" QRF_TEXT_Html QRF_Always or QRF_On
ee87371… drh 6278 ** "tcl" QRF_TEXT_Tcl QRF_Always or QRF_On
ee87371… drh 6279 ** "json" QRF_TEXT_Json QRF_Always or QRF_On
ee87371… drh 6280 **
ee87371… drh 6281 ** This mapping is different from the -title option to the "format"
ee87371… drh 6282 ** method of the TCL interface. In this mapping:
ee87371… drh 6283 **
ee87371… drh 6284 ** * "off", "on", and "always" affect only bTitles and leave
ee87371… drh 6285 ** eTitle unchanged
ee87371… drh 6286 **
ee87371… drh 6287 ** * "auto" sets both bTitles and eTitle to the default value
ee87371… drh 6288 ** in aModeInfo[] according to the current --style.
ee87371… drh 6289 **
ee87371… drh 6290 ** * "plain" through "json" set eTitle but leave bTitles
ee87371… drh 6291 ** unchanged if it is not QRF_Off. If bTitles is QRF_Off,
ee87371… drh 6292 ** then it is changed QRF_Always.
ee87371… drh 6293 */
ee87371… drh 6294 "off","on","always","auto","plain","sql","csv","html","tcl","json","");
ee87371… drh 6295 /* 0 1 2 3 4 5 6 7 8 9 */
ee87371… drh 6296 if( k<=2 ){
ee87371… drh 6297 p->mode.spec.bTitles = QRF_No+k;
ee87371… drh 6298 }else if( k==3 ){
ee87371… drh 6299 p->mode.spec.eTitle = aModeInfo[p->mode.eMode].eHdr;
ee87371… drh 6300 p->mode.spec.bTitles = aModeInfo[p->mode.eMode].bHdr;
ee87371… drh 6301 }else{
ee87371… drh 6302 p->mode.spec.eTitle = (k-4)+QRF_TEXT_Plain;
ee87371… drh 6303 if( p->mode.spec.bTitles==QRF_No ){
ee87371… drh 6304 p->mode.spec.bTitles = QRF_Always;
ee87371… drh 6305 }
ee87371… drh 6306 }
c5bdd31… drh 6307 /* Every width value except a single-digit final value takes at
c5bdd31… drh 6308 ** least 2 bytes in the input string to specify, so strlen(zW)+1
c5bdd31… drh 6309 ** entries is plenty of space to hold the result. */
c5bdd31… drh 6310 aWidth = malloc( strlen(zW)+1 );
471d617… drh 6311 if( bAll || p->mode.spec.zFpFmt!=0 ){
471d617… drh 6312 const char *z = p->mode.spec.zFpFmt;
471d617… drh 6313 sqlite3_str_appendf(pDesc, " --fpfmt %s", z ? z : "auto");
471d617… drh 6314 }
471d617… drh 6315 if( bAll || p->mode.spec.zIFmt!=0 ){
471d617… drh 6316 const char *z = p->mode.spec.zIFmt;
471d617… drh 6317 sqlite3_str_appendf(pDesc, " --ifmt %s", z ? z : "auto");
471d617… drh 6318 }
17f9878… drh 6319 if( bAll
17f9878… drh 6320 || (p->mode.spec.nMultiInsert && p->mode.spec.eStyle==QRF_STYLE_Insert)
17f9878… drh 6321 ){
17f9878… drh 6322 sqlite3_str_appendf(pDesc, " --multiinsert %u",
17f9878… drh 6323 p->mode.spec.nMultiInsert);
17f9878… drh 6324 }
564007c… drh 6325 sqlite3_str_appendf(pDesc," --quote %s",
564007c… drh 6326 qrfQuoteNames[p->mode.spec.eText]);
ee87371… drh 6327 }
ee87371… drh 6328 if( bAll
ee87371… drh 6329 || ((p->mode.spec.bRowCount==QRF_Yes) != ((pI->mFlg&4)!=0))
ee87371… drh 6330 ){
ee87371… drh 6331 sqlite3_str_appendf(pDesc," --rowcount %s",
ee87371… drh 6332 p->mode.spec.bRowCount==QRF_Yes ? "on" : "off");
ee87371… drh 6333 sqlite3_str_appendall(pDesc, " --titles always");
ee87371… drh 6334 }else if( k>=4 ){
ee87371… drh 6335 if( k==5 ){
ee87371… drh 6336 sqlite3_str_appendf(pDesc, " --titles always");
ee87371… drh 6337 }
9b67f46… drh 6338 }else if( c=='o' && sqlite3_strglob("-[ewx]",z)==0 ){
e66a8c7… drh 6339 if( sqlite3_str_length(cli_output_capture)>0 ){
1d618cc… drh 6340 modeSetStr(&p->mode.spec.zColumnSep, ",");
1d618cc… drh 6341 modeSetStr(&p->mode.spec.zRowSep, "\r\n");
e66a8c7… drh 6342 ** Return true if the argument is <<MARK for some arbitrary mark
e66a8c7… drh 6343 */
e66a8c7… drh 6344 static int isHereDoc(const char *z){
c92989d… drh 6345 return z && z[0]=='<' && z[1]=='<' && z[2]!=0;
e66a8c7… drh 6346 }
e66a8c7… drh 6347
e66a8c7… drh 6348 /*
e66a8c7… drh 6349 ** Capture lines of input text up until a line that matches zTerminator.
e66a8c7… drh 6350 ** Return a memory buffer (allocated using sqlite3_malloc64()) that
e66a8c7… drh 6351 ** contains the complete text, without the terminator.
e66a8c7… drh 6352 */
e66a8c7… drh 6353 static char *captureHereDoc(ShellState *p, const char *zTerminator){
e66a8c7… drh 6354 int nTerminator = strlen30(zTerminator);
e66a8c7… drh 6355 sqlite3_str *pHeredoc = sqlite3_str_new(p->db);
e66a8c7… drh 6356 char zLine[2000];
e66a8c7… drh 6357 while( shell_fgets(p, zLine,sizeof(zLine),p->in) ){
e66a8c7… drh 6358 if( strchr(zLine,'\n') ) p->lineno++;
e66a8c7… drh 6359 if( cli_strncmp(zTerminator,zLine,nTerminator)==0 ) break;
e66a8c7… drh 6360 sqlite3_str_appendall(pHeredoc, zLine);
e66a8c7… drh 6361 }
e66a8c7… drh 6362 return sqlite3_str_finish(pHeredoc);
e66a8c7… drh 6363 }
e66a8c7… drh 6364
e66a8c7… drh 6365 /*
c92989d… drh 6366 ** Return a pointer to the first non-whitespace character in the input
c92989d… drh 6367 ** string, or a pointer to the string terminator if the input contains
c92989d… drh 6368 ** no non-whitespace characters.
c92989d… drh 6369 **
c92989d… drh 6370 ** The number of bytes that follow, excluding trailing whitespace, is
c92989d… drh 6371 ** written into *pN if pN!=0.
c92989d… drh 6372 */
c92989d… drh 6373 static char *trimSpace(char *zIn, int *pN){
c92989d… drh 6374 while( IsSpace(zIn[0]) ){ zIn++; }
c92989d… drh 6375 if( pN ){
c92989d… drh 6376 size_t n = strlen(zIn);
c92989d… drh 6377 assert( n<=0x7fffffff );
c92989d… drh 6378 while( n>0 && IsSpace(zIn[n-1]) ){ n--; }
c92989d… drh 6379 *pN = (int)n;
c92989d… drh 6380 }
c92989d… drh 6381 return zIn;
c92989d… drh 6382 }
c92989d… drh 6383
c92989d… drh 6384 /*
c92989d… drh 6385 ** Verify the output of all commands since the most recent .testcase
c92989d… drh 6386 ** command. Both stdout and stderr are captured and compared, so error
c92989d… drh 6387 ** messages are part of the text being compared, however output from
c92989d… drh 6388 ** the ".echo on" dot-command is not captured and is not part of the test
c92989d… drh 6389 ** result.
c92989d… drh 6390 **
c92989d… drh 6391 ** After checking the result, all captured output is discarded and
c92989d… drh 6392 ** output starts going back to the console, unless --keep is used.
c92989d… drh 6393 **
c92989d… drh 6394 ** The PATTERN is the concatenation (with a single space separator) of
c92989d… drh 6395 ** all arguments that are not part of OPTIONS.
c92989d… drh 6396 **
c92989d… drh 6397 ** If PATTERN is "<<ENDMARK" (for any ENDMARK) then the actual pattern is
c92989d… drh 6398 ** taken from subsequent lines of text up to the first line that begins
c92989d… drh 6399 ** with ENDMARK.
c92989d… drh 6400 **
c92989d… drh 6401 ** The default comparison algorithm is to ignore all leading and trailing
c92989d… drh 6402 ** whitespace and compare the pattern against the result byte-for-byte except
c92989d… drh 6403 ** that whitespace characters are equal to other whitespace characters.
c92989d… drh 6404 ** Thus if the pattern contains a space character and the result contains
c92989d… drh 6405 ** a tab in the same spot, they would still compare equal. The number of
c92989d… drh 6406 ** whitespace characters must be the same in the pattern and the result.
c92989d… drh 6407 ** The --glob, --notglob, and --allglob comparisons are extended so that
c92989d… drh 6408 ** "#" in the pattern matches a sequence of one or more digits with an
c92989d… drh 6409 ** optional leading "+" or "-", and a space in the pattern matches a run
c92989d… drh 6410 ** of one or more whitespace characters.
c92989d… drh 6411 ** --allglob PATTERN is a GLOB matching the entire test output except
c92989d… drh 6412 ** leading and trailing whitespace.
c92989d… drh 6413 ** --any PATTERN is any substring within the test output.
c92989d… drh 6414 ** --exact PATTERN matches the entire test output, byte for byte.
c92989d… drh 6415 ** --glob PATTERN is a GLOB matching any substring of the test
c92989d… drh 6416 ** output. Leading and trailing whitespace on the PATTERN
c92989d… drh 6417 ** is ignored.
c92989d… drh 6418 ** --keep Do not reset the test output. One or more .check commands
c92989d… drh 6419 ** will follow and do additional tests.
c92989d… drh 6420 ** --not Pass if the test output does *not* match PATTERN.
c92989d… drh 6421 ** --notglob Shorthand for "--not --glob".
c92989d… drh 6422 ** --nowhere Shorthand for "--not --any".
c92989d… drh 6423 ** --regexp PATTERN is a regular expression matching any substring
c92989d… drh 6424 ** of the test output.
c92989d… drh 6425 ** --show Write test output to the screen, for debugging.
c92989d… drh 6426 sqlite3_str *pPattern; /* PATTERN argument */
c92989d… drh 6427 char *zPattern = 0; /* Test pattern */
c92989d… drh 6428 char *zToFree = 0; /* Start of test pattern */
c92989d… drh 6429 int eCheck = 0; /* 0: default. Else 1+index of option */
c92989d… drh 6430 int isOk = 0; /* True if results are OK */
c92989d… drh 6431 int bNot = 0; /* Invert the sense of the test */
c92989d… drh 6432 int iPat = -1; /* Location of the pattern */
e66a8c7… drh 6433 if( p->mIf!=0 ){
e66a8c7… drh 6434 /* Unlike most other dot-commands, the .check command runs even if
e66a8c7… drh 6435 ** inside the false branch of a .if. It needs to do this so that it
e66a8c7… drh 6436 ** can capture any "<<MARKER" heredoc text specified. */
e66a8c7… drh 6437 if( nArg>0 && isHereDoc(azArg[nArg-1]) ){
e66a8c7… drh 6438 sqlite3_free(captureHereDoc(p, azArg[nArg-1]+2));
e66a8c7… drh 6439 }
e66a8c7… drh 6440 return 0;
e66a8c7… drh 6441 }
c92989d… drh 6442 pPattern = sqlite3_str_new(p->db);
e66a8c7… drh 6443 if( sqlite3_str_length(cli_output_capture)>0 ){
c92989d… drh 6444 && (k = pickStr(&z[1],0,
c92989d… drh 6445 /* 0 1 2 3 4 5 6 7 */
c92989d… drh 6446 "glob","exact","regexp","any","nowhere","allglob","notglob","not",""))>=0
c92989d… drh 6447 if( k==7 ){
c92989d… drh 6448 bNot = !bNot;
c92989d… drh 6449 }else if( eCheck==0 || eCheck==k+1 ){
c92989d… drh 6450 eCheck = k+1;
c92989d… drh 6451 }else{
c92989d… drh 6452 output_reset(p);
c92989d… drh 6453 sqlite3_str_free(pPattern);
c92989d… drh 6454 if( sqlite3_str_length(pPattern)>0 ){
c92989d… drh 6455 sqlite3_str_appendchar(pPattern, 1, ' ');
c92989d… drh 6456 }else{
c92989d… drh 6457 iPat = i;
c92989d… drh 6458 }
c92989d… drh 6459 sqlite3_str_appendall(pPattern, azArg[i]);
e66a8c7… drh 6460 if( sqlite3_str_length(cli_output_capture) ){
c92989d… drh 6461 zToFree = zPattern = sqlite3_str_finish(pPattern);
c92989d… drh 6462 if( isHereDoc(zPattern) ){
c92989d… drh 6463 zPattern = captureHereDoc(p, zPattern+2);
c92989d… drh 6464 sqlite3_free(zToFree);
c92989d… drh 6465 zToFree = zPattern;
c92989d… drh 6466 }
c92989d… drh 6467 if( zPattern==0 ){
c92989d… drh 6468 zToFree = zPattern = sqlite3_mprintf("");
c92989d… drh 6469 }
c92989d… drh 6470 shell_check_oom(zPattern);
c92989d… drh 6471 switch( eCheck ){
c92989d… drh 6472 case 6: /* --allglob */
c92989d… drh 6473 case 7: /* --notglob */
c92989d… drh 6474 case 1: { /* --glob */
c92989d… drh 6475 int nPat = 0;
c92989d… drh 6476 char *zGlob;
c92989d… drh 6477 zPattern = trimSpace(zPattern, &nPat);
c92989d… drh 6478 zTest = trimSpace(zTest, 0);
c92989d… drh 6479 if( eCheck==6 ){
c92989d… drh 6480 zGlob = sqlite3_mprintf("%.*s", nPat, zPattern);
c92989d… drh 6481 }else{
c92989d… drh 6482 zGlob = sqlite3_mprintf("*%.*s*", nPat, zPattern);
c92989d… drh 6483 }
c92989d… drh 6484 shell_check_oom(zGlob);
c92989d… drh 6485 isOk = testcase_glob(zGlob, zTest)!=0;
c92989d… drh 6486 if( eCheck==7 ) isOk = !isOk;
c92989d… drh 6487 sqlite3_free(zGlob);
c92989d… drh 6488 break;
c92989d… drh 6489 }
c92989d… drh 6490 case 2: { /* --exact */
c92989d… drh 6491 isOk = cli_strcmp(zTest,zPattern)==0;
c92989d… drh 6492 break;
c92989d… drh 6493 }
c92989d… drh 6494 case 3: { /* --regexp */
c92989d… drh 6495 ReCompiled *pRe = 0;
c92989d… drh 6496 const char *zErr = re_compile(&pRe, zPattern, 1000, 0);
c92989d… drh 6497 if( zErr ){
c92989d… drh 6498 re_free(pRe);
c92989d… drh 6499 sqlite3_free(zToFree);
c92989d… drh 6500 output_reset(p);
c92989d… drh 6501 p->nTestErr++;
c92989d… drh 6502 dotCmdError(p, iPat, "bad regexp", "bad regular expression: %s", zErr);
c92989d… drh 6503 return 1;
c92989d… drh 6504 }
c92989d… drh 6505 shell_check_oom(pRe);
c92989d… drh 6506 isOk = re_match(pRe, (const unsigned char*)zTest, -1);
c92989d… drh 6507 re_free(pRe);
c92989d… drh 6508 break;
c92989d… drh 6509 }
c92989d… drh 6510 case 4: { /* --any */
c92989d… drh 6511 isOk = strstr(zTest,zPattern)!=0;
c92989d… drh 6512 break;
c92989d… drh 6513 }
c92989d… drh 6514 case 5: { /* --nowhere */
c92989d… drh 6515 isOk = strstr(zTest,zPattern)==0;
c92989d… drh 6516 break;
c92989d… drh 6517 }
c92989d… drh 6518 default: { /* default matching rule */
c92989d… drh 6519 /* Ignore leading and trailing whitespace on both the pattern and the
c92989d… drh 6520 ** test output. Each interior whitespace character will compare equal
c92989d… drh 6521 ** to exactly one other whitespace character. */
c92989d… drh 6522 int nPat = 0;
c92989d… drh 6523 int nTest = 0;
c92989d… drh 6524 zPattern = trimSpace(zPattern, &nPat);
c92989d… drh 6525 zTest = trimSpace(zTest, &nTest);
c92989d… drh 6526 if( nPat!=nTest ){
c92989d… drh 6527 isOk = 0;
c92989d… drh 6528 }else if( memcmp(zPattern, zTest, nPat)==0 ){
c92989d… drh 6529 isOk = 1;
c92989d… drh 6530 }else{
c92989d… drh 6531 int ii;
c92989d… drh 6532 isOk = 1;
c92989d… drh 6533 for(ii=0; ii<nPat; ii++){
c92989d… drh 6534 if( zPattern[ii]!=zTest[ii]
c92989d… drh 6535 && !(IsSpace(zPattern[ii]) && IsSpace(zTest[ii]))
c92989d… drh 6536 ){
c92989d… drh 6537 isOk = 0;
c92989d… drh 6538 break;
c92989d… drh 6539 }
c92989d… drh 6540 }
c92989d… drh 6541 }
c92989d… drh 6542 break;
c92989d… drh 6543 }
c92989d… drh 6544 }
c92989d… drh 6545 if( bNot ) isOk = !isOk;
c92989d… drh 6546 if( !isOk ){
c92989d… drh 6547 static const char zDL[] = "\342\225\255\342\224\200";
c92989d… drh 6548 static const char zDR[] = "\342\224\200\342\225\256";
c92989d… drh 6549 static const char zUL[] = "\342\225\260\342\224\200";
c92989d… drh 6550 static const char zUR[] = "\342\224\200\342\225\257";
c92989d… drh 6551 static const char zLine[] = "\342\224\200\342\224\200\342\224\200"
c92989d… drh 6552 "\342\224\200\342\224\200\342\224\200"
c92989d… drh 6553 "\342\224\200\342\224\200\342\224\200"
c92989d… drh 6554 "\342\224\200\342\224\200\342\224\200"
c92989d… drh 6555 "\342\224\200\342\224\200";
c92989d… drh 6556 if( sqlite3_strglob("*\n", zPattern)==0 ){
c92989d… drh 6557 sqlite3_fprintf(stderr, "%s%s Expected %s%s\n%s%s%s Expected %s%s\n",
c92989d… drh 6558 zDL, zLine+9, zLine+9, zDR,
c92989d… drh 6559 zPattern,
c92989d… drh 6560 zUL, zLine+9, zLine+9, zUR);
c92989d… drh 6561 }else{
c92989d… drh 6562 sqlite3_fprintf(stderr, "Expected: [%s]\n", zPattern);
c92989d… drh 6563 }
c92989d… drh 6564 if( sqlite3_strglob("*\n", zTest)==0 ){
c92989d… drh 6565 sqlite3_fprintf(stderr, "%s%s Got %s%s\n%s%s%s Got %s%s\n",
c92989d… drh 6566 zDL, zLine+3, zLine, zDR,
c92989d… drh 6567 zTest,
c92989d… drh 6568 zUL, zLine+3, zLine, zUR);
c92989d… drh 6569 }else{
c92989d… drh 6570 sqlite3_fprintf(stderr, "Got: [%s]\n", zTest);
c92989d… drh 6571 }
c92989d… drh 6572 sqlite3_free(zToFree);
677842d… drh 6573 }
677842d… drh 6574 return 0;
677842d… drh 6575 }
677842d… drh 6576
677842d… drh 6577 /*
677842d… drh 6578 ** DOT-COMMAND: .stats
677842d… drh 6579 ** USAGE: .stats [OPTIONS] ...
677842d… drh 6580 **
677842d… drh 6581 ** Show status information about the database and database connection.
677842d… drh 6582 ** The stats setting is persistent, unless the --once option is used.
677842d… drh 6583 ** Options are cumulative and are processed from left to right.
677842d… drh 6584 ** If no options are given, that is the same as ".stats all --once".
677842d… drh 6585 **
677842d… drh 6586 ** Options:
677842d… drh 6587 ** all Show all available stats.
677842d… drh 6588 ** io Show I/O stats (Linux only).
677842d… drh 6589 ** mem Show basic memory usage.
677842d… drh 6590 ** off Show nothing. Turn off stat display.
677842d… drh 6591 ** on Shorthand for "stmt xmem".
677842d… drh 6592 ** --once Show the stats once. Do not change the default stats display.
677842d… drh 6593 ** reset Reset "max" values after next display of each that value.
677842d… drh 6594 ** stmt Show information about the last SQL statement.
677842d… drh 6595 ** vmstep Show the number of virtual machine steps taken.
677842d… drh 6596 ** xmem Show detailed memory status information
677842d… drh 6597 ** xstmt Show details about each SQL statement
677842d… drh 6598 */
677842d… drh 6599 static int dotCmdStats(ShellState *p){
677842d… drh 6600 int nArg = p->dot.nArg; /* Number of arguments */
677842d… drh 6601 char **azArg = p->dot.azArg; /* Text of the arguments */
677842d… drh 6602 int ii; /* Loop counter */
677842d… drh 6603 int bOnce = 0; /* --once option seen */
677842d… drh 6604 u8 mNew = 0; /* New status setting */
677842d… drh 6605 u8 savedStats = p->mStats; /* Current stats setting */
677842d… drh 6606
677842d… drh 6607 if( nArg==1 ){
677842d… drh 6608 p->mStats = CLISTAT_ALL;
677842d… drh 6609 display_stats(p->db, p);
677842d… drh 6610 p->mStats = savedStats;
677842d… drh 6611 return 0;
677842d… drh 6612 }
677842d… drh 6613 for(ii=1; ii<nArg; ii++){
677842d… drh 6614 const char *z = azArg[ii];
677842d… drh 6615 if( z[0]=='-' ){
677842d… drh 6616 z++;
677842d… drh 6617 if( z[0]=='-' && z[1]!=0 ) z++;
677842d… drh 6618 }
677842d… drh 6619 if( cli_strcmp(z,"stmt")==0 ){
677842d… drh 6620 mNew |= CLISTAT_STMT|CLISTAT_VMSTEP;
677842d… drh 6621 }else if( cli_strcmp(z,"xstmt")==0 ){
677842d… drh 6622 mNew |= CLISTAT_STMT|CLISTAT_XSTMT|CLISTAT_VMSTEP;
677842d… drh 6623 }else if( cli_strcmp(z,"vmstep")==0 ){
677842d… drh 6624 mNew |= CLISTAT_VMSTEP;
677842d… drh 6625 }else if( cli_strcmp(z,"mem")==0 ){
677842d… drh 6626 mNew |= CLISTAT_MEM;
677842d… drh 6627 }else if( cli_strcmp(z,"xmem")==0 ){
677842d… drh 6628 mNew |= CLISTAT_XMEM|CLISTAT_MEM;
677842d… drh 6629 }else if( cli_strcmp(z,"io")==0 ){
677842d… drh 6630 mNew |= CLISTAT_IO;
677842d… drh 6631 }else if( cli_strcmp(z,"all")==0 ){
677842d… drh 6632 mNew |= CLISTAT_ALL;
677842d… drh 6633 #ifndef __linux__
677842d… drh 6634 dotCmdError(p, ii, "available only on Linux", 0);
677842d… drh 6635 return 1;
677842d… drh 6636 #endif
677842d… drh 6637 #ifdef SQLITE_ENABLE_ZIPVFS_VTAB
677842d… drh 6638 }else if( cli_strcmp(z,"zipvfs")==0 ){
677842d… drh 6639 mNew |= CLISTAT_ZIPVFS;
677842d… drh 6640 #endif
677842d… drh 6641 }else if( cli_strcmp(z,"reset")==0 ){
677842d… drh 6642 mNew |= CLISTAT_RESET;
677842d… drh 6643 }else if( cli_strcmp(z,"once")==0 ){
677842d… drh 6644 bOnce = 1;
677842d… drh 6645 }else if( IsDigit(z[0]) ){
677842d… drh 6646 if( booleanValue(z) ){
677842d… drh 6647 mNew |= CLISTAT_ON;
677842d… drh 6648 }else{
677842d… drh 6649 mNew = 0;
677842d… drh 6650 }
677842d… drh 6651 }else if( pickStr(z, 0, "on", "yes", "ON", "YES", "")>=0 ){
677842d… drh 6652 mNew |= CLISTAT_ON;
677842d… drh 6653 }else if( pickStr(z, 0, "off", "no", "OFF", "NO", "")>=0 ){
677842d… drh 6654 mNew = 0;
677842d… drh 6655 }else{
677842d… drh 6656 dotCmdError(p, ii, "unknown argument", 0);
677842d… drh 6657 return 1;
677842d… drh 6658 }
677842d… drh 6659 }
677842d… drh 6660 p->mStats = mNew;
677842d… drh 6661 if( bOnce ){
677842d… drh 6662 display_stats(p->db, p);
677842d… drh 6663 p->mStats = savedStats;
c92989d… drh 6664 ** ".check" command for additional information.
c92989d… drh 6665 p->zErrPrefix = (azArg[i] && azArg[i][0]) ? strdup(azArg[i]) : 0;
e66a8c7… drh 6666 ** Evaluate the text of zExpr as an SQL expression. Return true if the
e66a8c7… drh 6667 ** expression is true. Return false if the expression evaluates to
e66a8c7… drh 6668 ** false or NULL. Return false if there is any kind of error, either
e66a8c7… drh 6669 ** a run-time or a compile-time error.
e66a8c7… drh 6670 */
e66a8c7… drh 6671 static int sqlExprIsTrue(ShellState *p, const char *zExpr){
e66a8c7… drh 6672 char *zSql = sqlite3_mprintf("SELECT %s", zExpr);
e66a8c7… drh 6673 sqlite3_stmt *pStmt;
e66a8c7… drh 6674 int rc;
e66a8c7… drh 6675
e66a8c7… drh 6676 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
e66a8c7… drh 6677 sqlite3_free(zSql);
e66a8c7… drh 6678 if( rc ){
e66a8c7… drh 6679 rc = 0;
e66a8c7… drh 6680 }else{
e66a8c7… drh 6681 bind_prepared_stmt(p, pStmt);
e66a8c7… drh 6682 rc = sqlite3_step(pStmt);
e66a8c7… drh 6683 if( rc==SQLITE_ROW ){
e66a8c7… drh 6684 rc = sqlite3_column_double(pStmt,0)!=0.0;
e66a8c7… drh 6685 }else{
e66a8c7… drh 6686 rc = 0;
e66a8c7… drh 6687 }
e66a8c7… drh 6688 }
e66a8c7… drh 6689 sqlite3_finalize(pStmt);
e66a8c7… drh 6690 return rc;
e66a8c7… drh 6691 }
e66a8c7… drh 6692
e66a8c7… drh 6693 /*
e66a8c7… drh 6694 ** DOT-COMMAND: .if
e66a8c7… drh 6695 ** USAGE: .if SQL-EXPRESSION
e66a8c7… drh 6696 **
e66a8c7… drh 6697 ** The argument can be any SQL expression, including a subquery in
e66a8c7… drh 6698 ** parentheses. If the expression evalutes to true (if it is non-zero
e66a8c7… drh 6699 ** when converted into an number) then subsequent statements are
e66a8c7… drh 6700 ** evaluated. If SQL-EXPRESSION evalutes to false or NULL or raises
e66a8c7… drh 6701 ** an error, then subsequent statements are skipped, up until the first
e66a8c7… drh 6702 ** matching .elseif, .else, or .endif.
e66a8c7… drh 6703 **
e66a8c7… drh 6704 ** Maximum nested depth is limited. An error is raised if .if statements
e66a8c7… drh 6705 ** are nested to deep.
e66a8c7… drh 6706 **
e66a8c7… drh 6707 ** Every .if must be followed by a matching .endif, or an error is raised.
e66a8c7… drh 6708 */
e66a8c7… drh 6709 static int dotCmdIf(ShellState *p){
e66a8c7… drh 6710 int jj;
e66a8c7… drh 6711 if( p->nIfLevel==MX_IF ){
e66a8c7… drh 6712 dotCmdError(p, 0, 0, ".if nested too deep");
e66a8c7… drh 6713 return 1;
e66a8c7… drh 6714 }
e66a8c7… drh 6715 jj = p->nIfLevel++;
e66a8c7… drh 6716 open_db(p, 0);
e66a8c7… drh 6717 if( sqlExprIsTrue(p, p->dot.zOrig+3) ){
e66a8c7… drh 6718 p->mIfHasBeenTrue |= 1<<jj;
e66a8c7… drh 6719 }else{
e66a8c7… drh 6720 p->mIf |= 1<<jj;
e66a8c7… drh 6721 }
e66a8c7… drh 6722 p->lnIf[jj] = p->lineno;
e66a8c7… drh 6723 return 0;
e66a8c7… drh 6724 }
e66a8c7… drh 6725
e66a8c7… drh 6726 /*
e66a8c7… drh 6727 ** DOT-COMMAND: .elseif
e66a8c7… drh 6728 ** USAGE: .elseif SQL-EXPRESSION
e66a8c7… drh 6729 **
e66a8c7… drh 6730 ** An "else-if". The prior .if is finished and a new condition is applied.
e66a8c7… drh 6731 */
e66a8c7… drh 6732 static int dotCmdElseif(ShellState *p){
e66a8c7… drh 6733 int jj = p->nIfLevel-1;
e66a8c7… drh 6734 if( jj<p->nIfAtStart ){
e66a8c7… drh 6735 dotCmdError(p, 0, 0, ".elseif with no .if");
e66a8c7… drh 6736 return 1;
e66a8c7… drh 6737 }
e66a8c7… drh 6738 if( (p->mElse & (1<<jj))!=0 ){
e66a8c7… drh 6739 dotCmdError(p, 0, 0, ".elseif follows a .else on line %lld", p->lnElse[jj]);
e66a8c7… drh 6740 p->mIf |= 1<<jj;
e66a8c7… drh 6741 return 1;
e66a8c7… drh 6742 }
e66a8c7… drh 6743 if( p->mIfHasBeenTrue & (1<<jj) ){
e66a8c7… drh 6744 p->mIf |= 1<<jj;
e66a8c7… drh 6745 }else if( sqlExprIsTrue(p, p->dot.zOrig+7) ){
e66a8c7… drh 6746 p->mIf &= ~(1<<jj);
e66a8c7… drh 6747 p->mIfHasBeenTrue |= (1<<jj);
e66a8c7… drh 6748 }else{
e66a8c7… drh 6749 p->mIf |= 1<<jj;
e66a8c7… drh 6750 }
e66a8c7… drh 6751 return 0;
e66a8c7… drh 6752 }
e66a8c7… drh 6753
e66a8c7… drh 6754 /*
e66a8c7… drh 6755 ** DOT-COMMAND: .else
e66a8c7… drh 6756 ** USAGE: .else
e66a8c7… drh 6757 **
e66a8c7… drh 6758 ** Invert the sense of the inner-most .if. Start processing if the prior
e66a8c7… drh 6759 ** .if was false. Stop processing if the prior .if was true.
e66a8c7… drh 6760 */
e66a8c7… drh 6761 static int dotCmdElse(ShellState *p){
e66a8c7… drh 6762 int ii;
e66a8c7… drh 6763 if( p->nIfLevel<=p->nIfAtStart ){
e66a8c7… drh 6764 dotCmdError(p, 0, 0, ".else without a .if");
e66a8c7… drh 6765 return 1;
e66a8c7… drh 6766 }
e66a8c7… drh 6767 ii = p->nIfLevel-1;
e66a8c7… drh 6768 if( (p->mElse & (1<<ii))!=0 ){
e66a8c7… drh 6769 dotCmdError(p, 0, 0, "already saw a .else at line %lld", p->lnElse[ii]);
e66a8c7… drh 6770 return 1;
e66a8c7… drh 6771 }
e66a8c7… drh 6772 if( p->mIfHasBeenTrue & (1<<ii) ){
e66a8c7… drh 6773 p->mIf |= (1<<ii);
e66a8c7… drh 6774 }else{
e66a8c7… drh 6775 p->mIf &= ~(1<<ii);
e66a8c7… drh 6776 }
e66a8c7… drh 6777 p->mElse |= (1<<ii);
e66a8c7… drh 6778 p->lnElse[ii] = p->lineno;
e66a8c7… drh 6779 return 0;
e66a8c7… drh 6780 }
e66a8c7… drh 6781
e66a8c7… drh 6782 /*
e66a8c7… drh 6783 ** DOT-COMMAND: .endif
e66a8c7… drh 6784 ** USAGE: .endif
e66a8c7… drh 6785 **
e66a8c7… drh 6786 ** Terminate an .if statement.
e66a8c7… drh 6787 */
e66a8c7… drh 6788 static int dotCmdEndif(ShellState *p){
e66a8c7… drh 6789 if( p->nIfLevel<=p->nIfAtStart ){
e66a8c7… drh 6790 dotCmdError(p, 0, 0, ".endif without a .if");
e66a8c7… drh 6791 return 1;
e66a8c7… drh 6792 }
e66a8c7… drh 6793 p->nIfLevel--;
e66a8c7… drh 6794 p->mIf &= ~(1<<p->nIfLevel);
e66a8c7… drh 6795 p->mElse &= ~(1<<p->nIfLevel);
e66a8c7… drh 6796 p->mIfHasBeenTrue &= ~(1<<p->nIfLevel);
e66a8c7… drh 6797 return 0;
e66a8c7… drh 6798 }
e66a8c7… drh 6799
c92989d… drh 6800 /*
c92989d… drh 6801 ** DOT-COMMAND: .eqp
c92989d… drh 6802 ** USAGE: .eqp EQPMODE [>OUTPUTFILE]
c92989d… drh 6803 **
c92989d… drh 6804 ** The .eqp command enables or disables the automatic display of EXPLAIN
c92989d… drh 6805 ** output for each SQL statement evaluated. The required EQPMODE argument
c92989d… drh 6806 ** may be one of the following:
c92989d… drh 6807 **
c92989d… drh 6808 ** full Show both EXPLAIN QUERY PLAN and EXPLAIN output.
c92989d… drh 6809 **
c92989d… drh 6810 ** off Disable all explain output.
c92989d… drh 6811 **
c92989d… drh 6812 ** on Show EXPLAIN QUERY PLAN output only.
c92989d… drh 6813 **
c92989d… drh 6814 ** trace Like "full" but also enable VDBE tracing using
c92989d… drh 6815 ** PRAGMA vdbe_trace=ON. This option only works if the
c92989d… drh 6816 ** CLI is compiled with -DSQLITE_DEBUG. The trace output
c92989d… drh 6817 ** always appears on stdout and is not redirected to a file.
c92989d… drh 6818 **
c92989d… drh 6819 ** trigger Like "full" but also show EXPLAIN output for trigger
c92989d… drh 6820 ** subprograms.
c92989d… drh 6821 **
c92989d… drh 6822 ** The EQPMODE maybe be optionally followed by a filename. If a file is
c92989d… drh 6823 ** specified, with or without a single leading ">", then the file is
c92989d… drh 6824 ** deleted and all subsequent explain output is appended to that file.
c92989d… drh 6825 ** If the filename begins with ">>" then the content of the file is retained
c92989d… drh 6826 ** and all output is appended. If not redirection argument is provided,
c92989d… drh 6827 ** output redirection is cancelled. The ability to redirect is not available
c92989d… drh 6828 ** for --safe mode.
c92989d… drh 6829 */
c92989d… drh 6830 static int dotCmdEqp(ShellState *p){
c92989d… drh 6831 int nArg = p->dot.nArg; /* Number of arguments */
c92989d… drh 6832 char **azArg = p->dot.azArg; /* Argument list */
c92989d… drh 6833 if( nArg==2 || nArg==3 ){
c92989d… drh 6834 int isTrace = 0;
c92989d… drh 6835 if( p->db ) sqlite3_db_config(p->db, SQLITE_DBCONFIG_VDBE_TRACE, 0,
c92989d… drh 6836 (int*)0);
c92989d… drh 6837 if( cli_strcmp(azArg[1],"full")==0 ){
c92989d… drh 6838 p->mode.autoEQP = AUTOEQP_full;
c92989d… drh 6839 }else if( cli_strcmp(azArg[1],"trigger")==0 ){
c92989d… drh 6840 p->mode.autoEQP = AUTOEQP_trigger;
c92989d… drh 6841 }else if( cli_strcmp(azArg[1],"trace")==0 ){
c92989d… drh 6842 #ifdef SQLITE_DEBUG
c92989d… drh 6843 p->mode.autoEQP = AUTOEQP_full;
c92989d… drh 6844 if( p->db==0 ){
c92989d… drh 6845 open_db(p, 0);
c92989d… drh 6846 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1",0,0,0);
c92989d… drh 6847 }
c92989d… drh 6848 sqlite3_db_config(p->db, SQLITE_DBCONFIG_VDBE_TRACE, 1, (int*)0);
c92989d… drh 6849 isTrace = 1;
c92989d… drh 6850 #else
c92989d… drh 6851 eputz("\".eqp trace\" is only available in debug builds\n");
c92989d… drh 6852 return 1;
c92989d… drh 6853 #endif
c92989d… drh 6854 }else{
c92989d… drh 6855 p->mode.autoEQP = (u8)booleanValue(azArg[1]);
c92989d… drh 6856 }
c92989d… drh 6857 free(p->zEqpFile);
c92989d… drh 6858 if( nArg==3 ){
c92989d… drh 6859 const char *zOut = azArg[2];
c92989d… drh 6860 int bAppend = 0;
c92989d… drh 6861 failIfSafeMode(p, "cannot redirect .eqp output in safe mode");
c92989d… drh 6862 if( zOut[0]=='>' ) zOut++;
c92989d… drh 6863 if( zOut[0]=='>' ){ bAppend = 1; zOut++; }
c92989d… drh 6864 p->zEqpFile = strdup(zOut);
c92989d… drh 6865 if( !bAppend ){
c92989d… drh 6866 (void)shellDeleteFile(p->zEqpFile, 0);
c92989d… drh 6867 }
c92989d… drh 6868 if( isTrace ){
c92989d… drh 6869 cli_printf(p->out, "WARNING: trace output will not be redirected\n");
c92989d… drh 6870 }
c92989d… drh 6871 }else{
c92989d… drh 6872 p->zEqpFile = 0;
c92989d… drh 6873 }
c92989d… drh 6874 }else{
c92989d… drh 6875 eputz("Usage: .eqp off|on|trace|trigger|full [OUTPUTFILE]\n");
c92989d… drh 6876 return 1;
c92989d… drh 6877 }
c92989d… drh 6878 return 0;
c92989d… drh 6879 }
e66a8c7… drh 6880
c92989d… drh 6881
c92989d… drh 6882 /*
c92989d… drh 6883 ** DOT-COMMAND: .safe
c92989d… drh 6884 ** USAGE: .safe
c92989d… drh 6885 **
c92989d… drh 6886 ** This command puts the CLI into "safe mode". This command cannot be
c92989d… drh 6887 ** undone. The only way to restore full capabilities is to exit and
c92989d… drh 6888 ** restart the CLI.
c92989d… drh 6889 **
c92989d… drh 6890 ** Safe mode restricts SQL statements and dot-commands so that no
c92989d… drh 6891 ** changes may be made to the filesystem other than writing to database
c92989d… drh 6892 ** files that are already open.
c92989d… drh 6893 **
c92989d… drh 6894 ** * The .open command is blocked unless the database is ":memory:"
c92989d… drh 6895 ** or the --hexdb option is used.
c92989d… drh 6896 ** * The ATTACH command of SQL may not be used
c92989d… drh 6897 ** * SQL functions with side effects (ex: writefile()) are blocked.
c92989d… drh 6898 ** * The ".shell" and ".system" dot-commands are blocked.
c92989d… drh 6899 ** * Dot-command like ".archive", ".backup", ".load", ".log", ".save"
c92989d… drh 6900 ** are blocked.
c92989d… drh 6901 ** * Other commands with deleterious side effects are blocked.
c92989d… drh 6902 **
c92989d… drh 6903 ** Unsafe actions might be simply blocked, or the CLI might issue an error
c92989d… drh 6904 ** and exit immediately.
c92989d… drh 6905 **
c92989d… drh 6906 ** Safe mode does not prevent harm to database files that are already open.
c92989d… drh 6907 ** An attacker can still delete content and even use commands like
c92989d… drh 6908 ** "PRAGMA writable_schema=ON" to corrupt a database file that is already
c92989d… drh 6909 ** open. Safe mode only blocks access to other previously unopened files.
c92989d… drh 6910 **
c92989d… drh 6911 ** CAUTION: If third-party extensions with system side effects have been
c92989d… drh 6912 ** loaded prior to the .safe command, the CLI has no knowledge of those
c92989d… drh 6913 ** extensions and does not know to block them. Unsafe actions might still
c92989d… drh 6914 ** be possible using those third-party extension.
c92989d… drh 6915 */
c92989d… drh 6916 static int dotCmdSafe(ShellState *p){
c92989d… drh 6917 int i;
c92989d… drh 6918 p->bSafeMode = 1;
c92989d… drh 6919 p->bSafeModePersist = 1;
c92989d… drh 6920 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
c92989d… drh 6921 if( p->db ) sqlite3_enable_load_extension(p->db, 0);
c92989d… drh 6922 #endif
c92989d… drh 6923 for(i=0; i<ArraySize(p->aAuxDb); i++){
c92989d… drh 6924 sqlite3 *db = p->aAuxDb[i].db;
c92989d… drh 6925 if( db==0 ) continue;
c92989d… drh 6926 #ifndef SQLITE_OMIT_VIRTUALTABLE
c92989d… drh 6927 sqlite3_create_module(db, "fsdir", 0, 0);
c92989d… drh 6928 sqlite3_create_module(db, "zipfile", 0, 0);
c92989d… drh 6929 #endif
c92989d… drh 6930 sqlite3_create_function(db, "writefile", -1, 0, 0, 0, 0, 0);
c92989d… drh 6931 sqlite3_create_function(db, "zipfile", -1, 0, 0, 0, 0, 0);
c92989d… drh 6932 sqlite3_create_function(db, "tryeval", -1, 0, 0, 0, 0, 0);
c92989d… drh 6933 sqlite3_create_function(db, "expire", 1, 0, 0, 0, 0, 0);
c92989d… drh 6934 sqlite3_create_function(db, "expire", 2, 0, 0, 0, 0, 0);
c92989d… drh 6935 }
c92989d… drh 6936 return 0;
c92989d… drh 6937 }
e66a8c7… drh 6938
e66a8c7… drh 6939 /*
1d618cc… drh 6940 clearTempFile(p,0,0);
677842d… drh 6941 int ii;
677842d… drh 6942 int eOnOff = -1;
677842d… drh 6943 open_db(p, 0);
677842d… drh 6944 for(ii=1; ii<nArg && rc==0; ii++){
677842d… drh 6945 const char *z = azArg[ii];
677842d… drh 6946 if( z[0]=='-' && z[1]=='-' ) z++;
677842d… drh 6947 if( strcmp(z,"-deny")==0 ){
677842d… drh 6948 ii++;
677842d… drh 6949 if( ii>=nArg ){
677842d… drh 6950 dotCmdError(p, ii-1, "missing argument", 0);
677842d… drh 6951 rc = 1;
677842d… drh 6952 goto meta_command_exit;
677842d… drh 6953 }else{
677842d… drh 6954 free(p->zAuthDeny);
677842d… drh 6955 p->zAuthDeny = 0;
677842d… drh 6956 if( azArg[ii][0] ){
677842d… drh 6957 p->zAuthDeny = strdup(azArg[ii]);
677842d… drh 6958 shell_check_oom(p->zAuthDeny);
677842d… drh 6959 }
677842d… drh 6960 }
677842d… drh 6961 }else
677842d… drh 6962 if( strcmp(z,"-ignore")==0 ){
677842d… drh 6963 ii++;
677842d… drh 6964 if( ii>=nArg ){
677842d… drh 6965 dotCmdError(p, ii-1, "missing argument", 0);
677842d… drh 6966 rc = 1;
677842d… drh 6967 goto meta_command_exit;
677842d… drh 6968 }else{
677842d… drh 6969 free(p->zAuthIgnore);
677842d… drh 6970 p->zAuthIgnore = 0;
677842d… drh 6971 if( azArg[ii][0] ){
677842d… drh 6972 p->zAuthIgnore = strdup(azArg[ii]);
677842d… drh 6973 shell_check_oom(p->zAuthIgnore);
677842d… drh 6974 }
677842d… drh 6975 }
677842d… drh 6976 }else
677842d… drh 6977 if( eOnOff<0 ){
677842d… drh 6978 eOnOff = booleanValue(z);
677842d… drh 6979 }else
677842d… drh 6980 {
677842d… drh 6981 dotCmdError(p, ii, "unknown argument", 0);
677842d… drh 6982 rc = 1;
677842d… drh 6983 goto meta_command_exit;
677842d… drh 6984 }
677842d… drh 6985 }
677842d… drh 6986 if( eOnOff<0 ){
677842d… drh 6987 cli_printf(stderr, "Usage: .auth ON|OFF [--deny GLOB] [--ignore]\n");
677842d… drh 6988 if( eOnOff ){
e66a8c7… drh 6989 rc = dotCmdClone(p);
b8ab8b3… drh 6990 { "fp_digits", SQLITE_DBCONFIG_FP_DIGITS },
c92989d… drh 6991 #ifdef SQLITE_DEBUG
c92989d… drh 6992 { "vdbe_trace", SQLITE_DBCONFIG_VDBE_TRACE },
c92989d… drh 6993 #endif
b8ab8b3… drh 6994 if( aDbConfig[ii].op==SQLITE_DBCONFIG_FP_DIGITS ){
c92989d… drh 6995 sqlite3_db_config(p->db, aDbConfig[ii].op, atoi(azArg[2]), (int*)0);
b8ab8b3… drh 6996 }else{
c92989d… drh 6997 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]),
c92989d… drh 6998 (int*)0);
b8ab8b3… drh 6999 }
b8ab8b3… drh 7000 if( aDbConfig[ii].op==SQLITE_DBCONFIG_FP_DIGITS ){
b8ab8b3… drh 7001 cli_printf(p->out, "%19s %d\n", aDbConfig[ii].zName, v);
b8ab8b3… drh 7002 }else{
b8ab8b3… drh 7003 cli_printf(p->out, "%19s %s\n",
b8ab8b3… drh 7004 aDbConfig[ii].zName, v ? "on" : "off");
b8ab8b3… drh 7005 }
9b67f46… drh 7006
71439dc… drh 7007 if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbtotxt", n)==0 ){
71439dc… drh 7008 open_db(p, 0);
c92989d… drh 7009 sqlite3_exec(p->db, "PRAGMA page_count", 0, 0, 0);
71439dc… drh 7010 rc = shell_dbtotxt_command(p, nArg, azArg);
71439dc… drh 7011 }else
71439dc… drh 7012
71439dc… drh 7013 if( c=='d' && n==8 && cli_strncmp(azArg[0], "diskused", n)==0 ){
9b67f46… drh 7014 const char *zSchema = 0;
9b67f46… drh 7015 int ii;
9b67f46… drh 7016 char *zSql;
9b67f46… drh 7017 open_db(p, 0);
9b67f46… drh 7018 for(ii=1; ii<nArg; ii++){
9b67f46… drh 7019 const char *z = azArg[ii];
9b67f46… drh 7020 if( z[0]=='-' ){
9b67f46… drh 7021 dotCmdError(p, ii, "unknown option", 0);
9b67f46… drh 7022 rc = 1;
9b67f46… drh 7023 goto meta_command_exit;
9b67f46… drh 7024 }
9b67f46… drh 7025 if( zSchema ){
9b67f46… drh 7026 dotCmdError(p, ii, "unknown argument", 0);
9b67f46… drh 7027 rc = 1;
9b67f46… drh 7028 goto meta_command_exit;
9b67f46… drh 7029 }
9b67f46… drh 7030 zSchema = z;
9b67f46… drh 7031 }
71439dc… drh 7032 zSql = sqlite3_mprintf("SELECT diskused(%Q)", zSchema);
9b67f46… drh 7033 shell_check_oom(zSql);
9b67f46… drh 7034 modePush(p);
9b67f46… drh 7035 modeChange(p, MODE_BATCH);
9b67f46… drh 7036 shell_exec(p, zSql, 0);
9b67f46… drh 7037 modePop(p);
9b67f46… drh 7038 sqlite3_free(zSql);
9b67f46… drh 7039 }else
40c5397… drh 7040 "SELECT name, type, shell_complete_sql(sql) FROM sqlite_schema AS o "
40c5397… drh 7041 "SELECT shell_complete_sql(sql) FROM sqlite_schema AS o "
51267fb… drh 7042 cli_puts(p->nErr?";\nROLLBACK; -- due to errors\n":"COMMIT;\n", p->out);
e66a8c7… drh 7043 if( p->mode.spec.zFpFmt ) p->mode.spec.zFpFmt = p->mode.zFpFmt;
e66a8c7… drh 7044 if( p->mode.spec.zIFmt ) p->mode.spec.zIFmt = p->mode.zIFmt;
e66a8c7… drh 7045 if( c=='e' && n==6 && cli_strcmp(azArg[0],"elseif")==0 ){
e66a8c7… drh 7046 rc = dotCmdElseif(p);
e66a8c7… drh 7047 }else
e66a8c7… drh 7048
e66a8c7… drh 7049 if( c=='e' && n==4 && cli_strcmp(azArg[0],"else")==0 ){
e66a8c7… drh 7050 rc = dotCmdElse(p);
e66a8c7… drh 7051 }else
e66a8c7… drh 7052
e66a8c7… drh 7053 if( c=='e' && n==5 && cli_strcmp(azArg[0],"endif")==0 ){
e66a8c7… drh 7054 rc = dotCmdEndif(p);
e66a8c7… drh 7055 }else
e66a8c7… drh 7056
c92989d… drh 7057 rc = dotCmdEqp(p);
c92989d… drh 7058 int bIndent = 0;
c92989d… drh 7059 bIndent = 1;
40c5397… drh 7060 "SELECT shell_format_schema(shell_complete_sql(sql),%d) FROM"
c92989d… drh 7061 "ORDER BY x", bIndent);
40c5397… drh 7062 data.mode.spec.zRowSep = ";\n";
ee87371… drh 7063 if( cli_strcmp(azArg[1],"always")==0 ){
ee87371… drh 7064 p->mode.spec.bTitles = QRF_Always;
ee87371… drh 7065 }else{
ee87371… drh 7066 p->mode.spec.bTitles = booleanValue(azArg[1]) ? QRF_Yes : QRF_No;
ee87371… drh 7067 }
ee87371… drh 7068 eputz("Usage: .headers off|on|always\n");
e66a8c7… drh 7069 }else
e66a8c7… drh 7070
e66a8c7… drh 7071 if( c=='i' && n==2 && cli_strcmp(azArg[0],"if")==0 ){
e66a8c7… drh 7072 rc = dotCmdIf(p);
17f9878… drh 7073 if( c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
17f9878… drh 7074 || cli_strncmp(azArg[0], "indexes", n)==0)
17f9878… drh 7075 ){
17f9878… drh 7076 sqlite3_str *pSql;
17f9878… drh 7077 int i;
17f9878… drh 7078 int allFlag = 0;
17f9878… drh 7079 int sysFlag = 0;
17f9878… drh 7080 int exprFlag = 0;
17f9878… drh 7081 int debugFlag = 0; /* Undocument --debug flag */
17f9878… drh 7082 const char *zPattern = 0;
17f9878… drh 7083 const char *zSep = "WHERE";
17f9878… drh 7084
17f9878… drh 7085 for(i=1; i<nArg; i++){
17f9878… drh 7086 if( azArg[i][0]=='-' ){
17f9878… drh 7087 const char *z = azArg[i]+1;
17f9878… drh 7088 if( z[0]=='-' ) z++;
17f9878… drh 7089 if( cli_strcmp(z,"all")==0 || cli_strcmp(z,"a")==0 ){
17f9878… drh 7090 allFlag = 1;
17f9878… drh 7091 }else
17f9878… drh 7092 if( cli_strcmp(z,"sys")==0 ){
17f9878… drh 7093 sysFlag = 1;
17f9878… drh 7094 allFlag = 0;
17f9878… drh 7095 }else
17f9878… drh 7096 if( cli_strcmp(z,"expr")==0 ){
17f9878… drh 7097 exprFlag = 1;
17f9878… drh 7098 allFlag = 0;
17f9878… drh 7099 }else
17f9878… drh 7100 if( cli_strcmp(z,"debug")==0 ){
17f9878… drh 7101 debugFlag = 1;
17f9878… drh 7102 }else
17f9878… drh 7103 {
17f9878… drh 7104 dotCmdError(p, i, "unknown option", 0);
17f9878… drh 7105 rc = 1;
17f9878… drh 7106 goto meta_command_exit;
17f9878… drh 7107 }
17f9878… drh 7108 }else if( zPattern==0 ){
17f9878… drh 7109 zPattern = azArg[i];
17f9878… drh 7110 }else{
17f9878… drh 7111 dotCmdError(p, i, "unknown argument", 0);
17f9878… drh 7112 rc = 1;
17f9878… drh 7113 goto meta_command_exit;
17f9878… drh 7114 }
17f9878… drh 7115 }
17f9878… drh 7116
17f9878… drh 7117 open_db(p, 0);
17f9878… drh 7118 pSql = sqlite3_str_new(p->db);
17f9878… drh 7119 sqlite3_str_appendf(pSql,
17f9878… drh 7120 "SELECT if(t.schema='main',i.name,t.schema||'.'||i.name)\n"
17f9878… drh 7121 "FROM pragma_table_list t, pragma_index_list(t.name,t.schema) i\n"
17f9878… drh 7122 );
17f9878… drh 7123 if( exprFlag ){
17f9878… drh 7124 allFlag = 0;
17f9878… drh 7125 sqlite3_str_appendf(pSql,
17f9878… drh 7126 "%s (EXISTS(SELECT 1 FROM pragma_index_xinfo(i.name) WHERE cid=-2)\n"
17f9878… drh 7127 " OR\n"
17f9878… drh 7128 " EXISTS(SELECT cid FROM pragma_table_xinfo(t.name) WHERE hidden=2"
17f9878… drh 7129 " INTERSECT "
17f9878… drh 7130 " SELECT cid FROM pragma_index_info(i.name)))\n", zSep);
17f9878… drh 7131 zSep = "AND";
17f9878… drh 7132 }
17f9878… drh 7133 if( sysFlag ){
17f9878… drh 7134 sqlite3_str_appendf(pSql,
17f9878… drh 7135 "%s i.name LIKE 'sqlite__autoindex__%%' ESCAPE '_'\n", zSep);
17f9878… drh 7136 zSep = "AND";
17f9878… drh 7137 }else if( !allFlag ){
17f9878… drh 7138 sqlite3_str_appendf(pSql,
17f9878… drh 7139 "%s i.name NOT LIKE 'sqlite__%%' ESCAPE '_'\n", zSep);
17f9878… drh 7140 zSep = "AND";
17f9878… drh 7141 }
17f9878… drh 7142 if( zPattern ){
17f9878… drh 7143 sqlite3_str_appendf(pSql, "%s i.name LIKE '%%%q%%'\n", zSep, zPattern);
17f9878… drh 7144 }
17f9878… drh 7145 sqlite3_str_appendf(pSql, "ORDER BY 1");
17f9878… drh 7146
17f9878… drh 7147 /* Run the SQL statement in "split" mode. */
17f9878… drh 7148 if( debugFlag ){
17f9878… drh 7149 cli_printf(stdout,"%s;\n", sqlite3_str_value(pSql));
17f9878… drh 7150 }else{
17f9878… drh 7151 modePush(p);
17f9878… drh 7152 modeChange(p, MODE_Split);
17f9878… drh 7153 shell_exec(p, sqlite3_str_value(pSql), 0);
17f9878… drh 7154 modePop(p);
17f9878… drh 7155 }
17f9878… drh 7156 sqlite3_str_free(pSql);
17f9878… drh 7157 }else
17f9878… drh 7158
ee87371… drh 7159 open_db(p, 0);
ee87371… drh 7160 if( iArg==0 ){
ee87371… drh 7161 if( cli_strcmp(azArg[1],"register")==0 ){
ee87371… drh 7162 sqlite3_intck_register(p->db, 1);
ee87371… drh 7163 rc = 0;
ee87371… drh 7164 goto meta_command_exit;
ee87371… drh 7165 }
ee87371… drh 7166 iArg = -1;
ee87371… drh 7167 }
896a463… drh 7168 { "schema", SQLITE_LIMIT_SCHEMA },
471d617… drh 7169 { "trigger_steps", SQLITE_LIMIT_TRIGGER_STEPS },
e66a8c7… drh 7170 { "ctes", SQLITE_LIMIT_CTES },
e66a8c7… drh 7171 int v = (int)integerValue(azArg[2]);
e66a8c7… drh 7172 sqlite3_limit(p->db, aLimit[iLimit].limitCode, v);
1d618cc… drh 7173 shellDeleteFile(zDel, 0);
1d618cc… drh 7174 shellDeleteFile(zFN, 0);
a10f931… drh 7175 p->tmProgress = atof(azArg[i]);
3361df8… drh 7176 int i;
3361df8… drh 7177 int cnt = 0;
3361df8… drh 7178 int noOpt = 0;
3361df8… drh 7179 for(i=1; i<nArg; i++){
3361df8… drh 7180 const char *z = azArg[i];
3361df8… drh 7181 if( z[0]=='-' && !noOpt ){
3361df8… drh 7182 if( z[1]=='-' ) z++;
9b67f46… drh 7183 if( strcmp(z,"-hard-reset")==0 ){
9b67f46… drh 7184 #ifdef _WIN32
9b67f46… drh 7185 _putenv("SQLITE_PS1=");
9b67f46… drh 7186 _putenv("SQLITE_PS2=");
9b67f46… drh 7187 #else
9b67f46… drh 7188 unsetenv("SQLITE_PS1");
9b67f46… drh 7189 unsetenv("SQLITE_PS2");
9b67f46… drh 7190 #endif
9b67f46… drh 7191 z += 5;
9b67f46… drh 7192 }
3361df8… drh 7193 if( strcmp(z,"-reset")==0 ){
3361df8… drh 7194 free(p->azPrompt[0]);
3361df8… drh 7195 free(p->azPrompt[1]);
3361df8… drh 7196 memset(p->azPrompt, 0, sizeof(p->azPrompt));
3361df8… drh 7197 }else
3361df8… drh 7198 if( strcmp(z,"-show")==0 ){
3361df8… drh 7199 cli_printf(stdout,"Main prompt: '%s'\n", prompt_string(p, 0));
3361df8… drh 7200 cli_printf(stdout,"Continuation: '%s'\n", prompt_string(p, 1));
3361df8… drh 7201 }else
055e4d0… drh 7202 #ifndef SQLITE_NO_COLOR
055e4d0… drh 7203 if( strcmp(z,"-color")==0 ){
055e4d0… drh 7204 #ifdef _WIN32
055e4d0… drh 7205 _putenv("NO_COLOR=");
055e4d0… drh 7206 #else
055e4d0… drh 7207 unsetenv("NO_COLOR");
055e4d0… drh 7208 #endif
055e4d0… drh 7209 }else
055e4d0… drh 7210 if( strcmp(z,"-no-color")==0 ){
055e4d0… drh 7211 #ifdef _WIN32
055e4d0… drh 7212 _putenv("NO_COLOR=1");
055e4d0… drh 7213 #else
055e4d0… drh 7214 setenv("NO_COLOR","1",1);
055e4d0… drh 7215 #endif
055e4d0… drh 7216 }else
055e4d0… drh 7217 #endif
3361df8… drh 7218 if( strcmp(z,"-")==0 ){
3361df8… drh 7219 noOpt = 1;
3361df8… drh 7220 }else
3361df8… drh 7221 {
3361df8… drh 7222 dotCmdError(p, i, "unknown option", 0);
3361df8… drh 7223 rc = 1;
3361df8… drh 7224 goto meta_command_exit;
3361df8… drh 7225 }
3361df8… drh 7226 }else if( cnt>1 ){
3361df8… drh 7227 dotCmdError(p, i, "extra argument", 0);
3361df8… drh 7228 rc = 1;
3361df8… drh 7229 goto meta_command_exit;
9b67f46… drh 7230 }else if( !p->dot.abQuot[i] && sqlite3_strglob("*[^a-z]*",z)!=0 ){
9b67f46… drh 7231 dotCmdError(p, i, "use quotes around the prompt string", 0);
055e4d0… drh 7232 rc = 1;
3361df8… drh 7233 }else{
3361df8… drh 7234 free(p->azPrompt[cnt]);
3361df8… drh 7235 p->azPrompt[cnt] = strdup(z);
9b67f46… drh 7236 cnt++;
3361df8… drh 7237 }
3361df8… drh 7238 }
e66a8c7… drh 7239 if( c=='r' && n==4 && cli_strcmp(azArg[0], "read")==0 ){
e66a8c7… drh 7240 if( p->mIf ){
e66a8c7… drh 7241 if( nArg==2 && isHereDoc(azArg[1]) ){
e66a8c7… drh 7242 sqlite3_free(captureHereDoc(p, azArg[1]+2));
e66a8c7… drh 7243 }
e66a8c7… drh 7244 return 0;
e66a8c7… drh 7245 }
e66a8c7… drh 7246 }
e66a8c7… drh 7247 if( !isHereDoc(azArg[1]) ){
e66a8c7… drh 7248 failIfSafeMode(p, "cannot run .read in safe mode");
e66a8c7… drh 7249 }else if( isHereDoc(azArg[1]) ){
e66a8c7… drh 7250 char *saved_zInput;
e66a8c7… drh 7251 i64 saved_nInputUsed;
e66a8c7… drh 7252 char *zScript = captureHereDoc(p, azArg[1]+2);
e66a8c7… drh 7253 savedLineno = p->lineno;
e66a8c7… drh 7254 saved_zInput = p->zInput;
e66a8c7… drh 7255 saved_nInputUsed = p->nInputUsed;
e66a8c7… drh 7256 p->zInput = zScript;
e66a8c7… drh 7257 p->nInputUsed = 0;
e66a8c7… drh 7258 p->in = (FILE*)&p->zInput;
e66a8c7… drh 7259 rc = process_input(p, "<heredoc>");
e66a8c7… drh 7260 sqlite3_free(p->zInput);
e66a8c7… drh 7261 p->zInput = saved_zInput;
e66a8c7… drh 7262 p->nInputUsed = saved_nInputUsed;
9b67f46… drh 7263
9b67f46… drh 7264 #if SQLITE_SHELL_HAVE_RECOVER
9b67f46… drh 7265 if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
9b67f46… drh 7266 open_db(p, 0);
9b67f46… drh 7267 rc = recoverDatabaseCmd(p, nArg, azArg);
9b67f46… drh 7268 }else
9b67f46… drh 7269 #endif /* SQLITE_SHELL_HAVE_RECOVER */
c92989d… drh 7270
c92989d… drh 7271 if( c=='s' && cli_strcmp(azArg[0], "safe")==0 ){
c92989d… drh 7272 rc = dotCmdSafe(p);
c92989d… drh 7273 }else
40c5397… drh 7274 sqlite3_str_appendf(pSql, "SELECT shell_complete_sql(sql,1) FROM", 0);
ee87371… drh 7275 p->mode.spec.bTitles==QRF_Always ? "always" :
ee87371… drh 7276 azBool[p->mode.spec.bTitles==QRF_Yes]);
677842d… drh 7277 cli_printf(p->out, "%12.12s:", "stats");
677842d… drh 7278 if( p->mStats==0 ){
677842d… drh 7279 cli_printf(p->out, " off\n");
677842d… drh 7280 }else{
677842d… drh 7281 u8 mStats = p->mStats;
677842d… drh 7282 if( (mStats & CLISTAT_ALL)==CLISTAT_ALL ){
677842d… drh 7283 cli_printf(p->out, " all");
677842d… drh 7284 mStats &= ~CLISTAT_ALL;
677842d… drh 7285 }
677842d… drh 7286 if( (mStats & CLISTAT_ON)==CLISTAT_ON ){
677842d… drh 7287 cli_printf(p->out, " on");
677842d… drh 7288 mStats &= ~CLISTAT_ON;
677842d… drh 7289 }
677842d… drh 7290 if( mStats & CLISTAT_XSTMT ){
677842d… drh 7291 cli_printf(p->out, " xstmt");
677842d… drh 7292 }else if( mStats & CLISTAT_STMT ){
677842d… drh 7293 cli_printf(p->out, " stmt");
677842d… drh 7294 }else if( mStats & CLISTAT_VMSTEP ){
677842d… drh 7295 cli_printf(p->out, " vmstep");
677842d… drh 7296 }
677842d… drh 7297 if( mStats & CLISTAT_XMEM ){
677842d… drh 7298 cli_printf(p->out, " xmem");
677842d… drh 7299 }else if( mStats & CLISTAT_MEM ){
677842d… drh 7300 cli_printf(p->out, " mem");
677842d… drh 7301 }
677842d… drh 7302 if( mStats & CLISTAT_IO ){
677842d… drh 7303 cli_printf(p->out, " io");
677842d… drh 7304 }
677842d… drh 7305 if( mStats & CLISTAT_ZIPVFS ){
677842d… drh 7306 cli_printf(p->out, " zipvfs");
677842d… drh 7307 }
677842d… drh 7308 if( mStats & CLISTAT_RESET ){
677842d… drh 7309 cli_printf(p->out, " reset");
677842d… drh 7310 }
677842d… drh 7311 cli_printf(p->out,"\n");
677842d… drh 7312 rc = dotCmdStats(p);
17f9878… drh 7313 if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0) ){
17f9878… drh 7314 sqlite3_str_appendf(pSql,
17f9878… drh 7315 " WHERE type IN ('table','view')"
17f9878… drh 7316 " AND name NOT LIKE 'sqlite__%%' ESCAPE '_'"
17f9878… drh 7317 );
17f9878… drh 7318 if( zPattern ){
17f9878… drh 7319 sqlite3_str_appendf(pSql," AND name LIKE %Q", zPattern);
c92989d… drh 7320 u64 curOpt; /* Current opt-disabled mask */
c92989d… drh 7321 u64 newOpt; /* New opt-disabled mask */
c92989d… drh 7322 u64 m; /* A working mask value */
564007c… drh 7323 int ii, jj; /* Loop counters */
564007c… drh 7324 int nOff; /* Number of disabled optimizations */
564007c… drh 7325 const char *zName; /* Name of an optimization */
c92989d… drh 7326 int bQuiet = 0; /* Suppress output echo */
564007c… drh 7327
c92989d… drh 7328 if( sqlite3_optimization_mask(zLabel,&m)==SQLITE_NOTFOUND ){
c92989d… drh 7329 if( strcmp(zLabel,"q")==0 ){
c92989d… drh 7330 /* Special -q option suppresses output */
c92989d… drh 7331 bQuiet = 1;
c92989d… drh 7332 continue;
c92989d… drh 7333 }
564007c… drh 7334 cli_puts("Should be one of: All", stderr);
564007c… drh 7335 for(jj=0; jj<32; jj++){
564007c… drh 7336 zName = sqlite3_optimization_name(1ull<<jj);
564007c… drh 7337 if( zName ) cli_printf(stderr," %s", zName);
564007c… drh 7338 newOpt &= ~m;
564007c… drh 7339 newOpt |= m;
c92989d… drh 7340 if( !bQuiet ){
c92989d… drh 7341 for(ii=nOff=0, m=1; ii<64; ii++, m <<= 1){
c92989d… drh 7342 if( m & newOpt ) nOff++;
c92989d… drh 7343 }
c92989d… drh 7344 if( nOff<12 ){
c92989d… drh 7345 cli_puts("+All", p->out);
c92989d… drh 7346 for(ii=0, m=1; ii<64; ii++, m <<= 1){
c92989d… drh 7347 if( (newOpt & m)!=0
c92989d… drh 7348 && (zName = sqlite3_optimization_name(m))!=0
c92989d… drh 7349 ){
c92989d… drh 7350 cli_printf(p->out, " -%s", zName);
c92989d… drh 7351 }
c92989d… drh 7352 }
c92989d… drh 7353 }else{
c92989d… drh 7354 cli_puts("-All", p->out);
c92989d… drh 7355 for(ii=0, m=1; ii<64; ii++, m <<= 1){
c92989d… drh 7356 if( (newOpt & m)==0
c92989d… drh 7357 && (zName = sqlite3_optimization_name(m))!=0
c92989d… drh 7358 ){
c92989d… drh 7359 cli_printf(p->out, " +%s", zName);
c92989d… drh 7360 }
c92989d… drh 7361 }
c92989d… drh 7362 }
c92989d… drh 7363 cli_puts("\n", p->out);
c92989d… drh 7364 }
3361df8… drh 7365 /*
3361df8… drh 7366 ** Test to see if a line consists entirely of whitespace.
3361df8… drh 7367 */
3361df8… drh 7368 static int line_is_all_whitespace(const char *z){
3361df8… drh 7369 for(; *z; z++){
3361df8… drh 7370 if( IsSpace(z[0]) ) continue;
3361df8… drh 7371 if( *z=='/' && z[1]=='*' ){
3361df8… drh 7372 z += 2;
3361df8… drh 7373 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
3361df8… drh 7374 if( *z==0 ) return 0;
3361df8… drh 7375 z++;
3361df8… drh 7376 continue;
3361df8… drh 7377 }
3361df8… drh 7378 if( *z=='-' && z[1]=='-' ){
3361df8… drh 7379 z += 2;
3361df8… drh 7380 while( *z && *z!='\n' ){ z++; }
3361df8… drh 7381 if( *z==0 ) return 1;
3361df8… drh 7382 continue;
3361df8… drh 7383 }
3361df8… drh 7384 }
3361df8… drh 7385 return 1;
40c5397… drh 7386 #ifdef SQLITE_SHELL_LEGACY_COMMAND_TERMINATOR
40c5397… drh 7387 ** Return TRUE if the line typed in is an SQL command terminator other
40c5397… drh 7388 ** than a semi-colon. The SQL Server style "go" command is understood
40c5397… drh 7389 ** as is the Oracle "/".
40c5397… drh 7390 static int line_is_command_terminator(
40c5397… drh 7391 const char *zLine, /* Current line of input */
40c5397… drh 7392 char *zSql, /* Total accumulated input text */
40c5397… drh 7393 int nSql /* Bytes of accumulated input text */
40c5397… drh 7394 ){
40c5397… drh 7395 while( IsSpace(zLine[0]) ){ zLine++; };
40c5397… drh 7396 if( (zLine[0]=='/' && line_is_all_whitespace(&zLine[1])) /* Oracle */
40c5397… drh 7397 || (sqlite3_strnicmp(zLine,"go",2)==0
40c5397… drh 7398 && line_is_all_whitespace(&zLine[2])) /* SQL Server */
40c5397… drh 7399 }{
40c5397… drh 7400 int rc;
40c5397… drh 7401 if( zSql==0 ) return 1;
40c5397… drh 7402 zSql[nSql] = ';';
40c5397… drh 7403 zSql[nSql+1] = 0;
40c5397… drh 7404 rc = sqlite3_complete(zSql);
40c5397… drh 7405 zSql[nSql] = 0;
40c5397… drh 7406 return rc;
40c5397… drh 7407 }
40c5397… drh 7408 return 0;
40c5397… drh 7409 }
40c5397… drh 7410 #endif
c92989d… drh 7411
c92989d… drh 7412
c92989d… drh 7413 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, (int*)0);
c92989d… drh 7414 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, (int*)0);
c92989d… drh 7415
c92989d… drh 7416 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, (int*)0);
c92989d… drh 7417 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, (int*)0);
564007c… drh 7418 }
564007c… drh 7419
564007c… drh 7420 /*
564007c… drh 7421 ** When the (undocumented) command-line option --test-parse is used,
564007c… drh 7422 ** this routine is run instead of runOneSqlLine() to process SQL. Don't
564007c… drh 7423 ** actually run any SQL. Instead just provide a one-line summary of the
564007c… drh 7424 ** SQL that would have run.
564007c… drh 7425 */
564007c… drh 7426 static void runTestParse(
564007c… drh 7427 ShellState *p, /* Execution context */
564007c… drh 7428 char *zSql /* SQL to be run */
564007c… drh 7429 ){
564007c… drh 7430 int nNL = 0;
564007c… drh 7431 char *zNL;
564007c… drh 7432 size_t i, j, n;
564007c… drh 7433 int nPre = 0;
564007c… drh 7434 int nSuf = 0;
564007c… drh 7435 int mxPre = 20;
564007c… drh 7436 char zPre[50], zSuf[50];
564007c… drh 7437
564007c… drh 7438 for(zNL=strchr(zSql,'\n'); zNL!=0; zNL=strchr(zNL+1,'\n')){ nNL++; }
564007c… drh 7439 n = strlen(zSql);
564007c… drh 7440 if( n<40 ) mxPre = 40;
564007c… drh 7441 for(i=0; nPre<mxPre && i<n; i++){
564007c… drh 7442 char c = zSql[i];
564007c… drh 7443 if( c=='\n' ){
564007c… drh 7444 zPre[nPre++] = '\\';
564007c… drh 7445 zPre[nPre++] = 'n';
564007c… drh 7446 }else if( c>0 && c<' ' ){
564007c… drh 7447 zPre[nPre++] = '^';
564007c… drh 7448 zPre[nPre++] = c+0x40;
564007c… drh 7449 }else{
564007c… drh 7450 zPre[nPre++] = c;
564007c… drh 7451 }
564007c… drh 7452 }
564007c… drh 7453 zPre[nPre] = 0;
e66a8c7… drh 7454 if( n<=i+20 ){
564007c… drh 7455 j = i;
564007c… drh 7456 }else{
e66a8c7… drh 7457 j = n - 20;
564007c… drh 7458 memcpy(zSuf," ... ", 5);
564007c… drh 7459 nSuf = 5;
564007c… drh 7460 }
564007c… drh 7461 for(i=j; i<n; i++){
564007c… drh 7462 char c = zSql[i];
564007c… drh 7463 if( c=='\n' ){
564007c… drh 7464 zSuf[nSuf++] = '\\';
564007c… drh 7465 zSuf[nSuf++] = 'n';
564007c… drh 7466 }else if( c>0 && c<' ' ){
564007c… drh 7467 zSuf[nSuf++] = '^';
564007c… drh 7468 zSuf[nSuf++] = c+0x40;
564007c… drh 7469 }else{
564007c… drh 7470 zSuf[nSuf++] = c;
564007c… drh 7471 }
564007c… drh 7472 }
564007c… drh 7473 zSuf[nSuf] = 0;
564007c… drh 7474 cli_printf(p->out, "%d line%s: %s%s\n", nNL+1, (nNL?"s":""), zPre, zSuf);
17f9878… drh 7475 }
17f9878… drh 7476
17f9878… drh 7477 /*
17f9878… drh 7478 static int runOneSqlLine(
17f9878… drh 7479 ShellState *p, /* Execution context */
17f9878… drh 7480 char *zSql, /* SQL to be run */
17f9878… drh 7481 const char *zFilename, /* Source file of the sql */
17f9878… drh 7482 int startline /* linenumber */
17f9878… drh 7483 ){
564007c… drh 7484 if( p->bTestParse ){
564007c… drh 7485 runTestParse(p, zSql);
564007c… drh 7486 rc = SQLITE_OK;
564007c… drh 7487 }else{
564007c… drh 7488 BEGIN_TIMER(p);
564007c… drh 7489 rc = shell_exec(p, zSql, &zErrMsg);
564007c… drh 7490 END_TIMER(p);
564007c… drh 7491 }
1d618cc… drh 7492 sqlite3_str *pPrefix = sqlite3_str_new(p->db);
17f9878… drh 7493 if( zFilename || !stdin_is_interactive ){
17f9878… drh 7494 if( cli_strcmp(zFilename,"cmdline")==0 ){
1d618cc… drh 7495 sqlite3_str_appendf(pPrefix,
17f9878… drh 7496 "%s in %r command line argument:", zErrorType, startline);
17f9878… drh 7497 }else if( cli_strcmp(zFilename,"<stdin>")==0 ){
1d618cc… drh 7498 sqlite3_str_appendf(pPrefix,
17f9878… drh 7499 "%s near line %d:", zErrorType, startline);
17f9878… drh 7500 }else{
1d618cc… drh 7501 sqlite3_str_appendf(pPrefix,
17f9878… drh 7502 "%s near line %d of %s:", zErrorType, startline, zFilename);
17f9878… drh 7503 }
1d618cc… drh 7504 sqlite3_str_appendf(pPrefix, "%s:", zErrorType);
1d618cc… drh 7505 cli_printf(stderr,"%s %s\n", sqlite3_str_value(pPrefix), zErrorTail);
1d618cc… drh 7506 sqlite3_str_free(pPrefix);
1d618cc… drh 7507 cli_printf(p->out,
1d618cc… drh 7508 "changes: %lld total_changes: %lld\n",
51267fb… drh 7509 sqlite3_str *savedCliCapture = cli_output_capture;
51267fb… drh 7510 cli_output_capture = 0; /* .echo should not be captured by .testcase */
51267fb… drh 7511 cli_output_capture = savedCliCapture;
3361df8… drh 7512 static char *one_input_line(
3361df8… drh 7513 ShellState *p, /* Shell state */
3361df8… drh 7514 char *zPrior, /* Just the prior line of text */
3361df8… drh 7515 const char *zAll, /* All accumulated statement text */
3361df8… drh 7516 int bContinue /* True if this is an accumulation */
3361df8… drh 7517 ){
a10f931… drh 7518 FILE *in = p->in;
3361df8… drh 7519 UNUSED_PARAMETER(bContinue);
564007c… drh 7520 ** Return true if the input would is complete SQL, or complete SQL
564007c… drh 7521 ** followed by only whitespace. This is similar to sqlite3_complete()
564007c… drh 7522 ** except that if the final semicolon is followed by whitespace, it
564007c… drh 7523 ** still returns true.
564007c… drh 7524 */
564007c… drh 7525 static int line_is_complete(char *zSql, int nSql){
564007c… drh 7526 sqlite3_int64 x;
564007c… drh 7527 assert( nSql>=0 && zSql[nSql]==0 );
564007c… drh 7528 x = sqlite3_incomplete(zSql);
564007c… drh 7529 if( x==0x00 || x==0x10 ) return 1;
564007c… drh 7530 if( x==0x2d0001 ){
564007c… drh 7531 zSql[nSql] = '\n';
564007c… drh 7532 zSql[nSql+1] = 0;
564007c… drh 7533 x = sqlite3_incomplete(zSql);
564007c… drh 7534 zSql[nSql] = 0;
564007c… drh 7535 if( x==0x00 || x==0x10 ) return 1;
564007c… drh 7536 }
564007c… drh 7537 return 0;
564007c… drh 7538 }
564007c… drh 7539
564007c… drh 7540 /*
e66a8c7… drh 7541 ** Return true if zLine is a dot-command that should always be run
e66a8c7… drh 7542 ** even if inside of the false leg of an ".if"
e66a8c7… drh 7543 */
e66a8c7… drh 7544 static int alwaysRun(const char *zLine){
e66a8c7… drh 7545 const char *az[] = {
e66a8c7… drh 7546 "3.if",
e66a8c7… drh 7547 "7.elseif",
e66a8c7… drh 7548 "5.else",
e66a8c7… drh 7549 "6.endif",
e66a8c7… drh 7550 "6.check", /* For its heredoc */
e66a8c7… drh 7551 "5.read", /* For its heredoc */
e66a8c7… drh 7552 "0"
e66a8c7… drh 7553 };
e66a8c7… drh 7554 int jj, n;
e66a8c7… drh 7555 for(jj=0; (n = az[jj][0] - '0')>0; jj++){
e66a8c7… drh 7556 if( strncmp(zLine,az[jj]+1,n)==0 && (IsSpace(zLine[n]) || zLine[n]==0) ){
e66a8c7… drh 7557 return 1;
e66a8c7… drh 7558 }
e66a8c7… drh 7559 }
e66a8c7… drh 7560 return 0;
e66a8c7… drh 7561 }
e66a8c7… drh 7562
e66a8c7… drh 7563
e66a8c7… drh 7564 /*
3361df8… drh 7565 int hasSemi = 0; /* Input line contains a semicolon */
e66a8c7… drh 7566 int saved_nIfAtStart; /* Prior value of p->nIfAtStart */
e66a8c7… drh 7567 saved_nIfAtStart = p->nIfAtStart;
e66a8c7… drh 7568 p->nIfAtStart = p->nIfLevel;
3361df8… drh 7569 zLine = one_input_line(p, zLine, zSql, nSql>0);
3361df8… drh 7570 if( nSql==0 && line_is_all_whitespace(zLine) ){
e66a8c7… drh 7571 if( p->mIf==0 || alwaysRun(zLine) ){
e66a8c7… drh 7572 rc = do_meta_command(zLine, p);
e66a8c7… drh 7573 if( rc==2 ){ /* exit requested */
e66a8c7… drh 7574 p->nIfLevel = p->nIfAtStart;
e66a8c7… drh 7575 break;
e66a8c7… drh 7576 }else if( rc ){
e66a8c7… drh 7577 errCnt++;
e66a8c7… drh 7578 }
40c5397… drh 7579 #ifdef SQLITE_SHELL_LEGACY_COMMAND_TERMINATOR
40c5397… drh 7580 if( line_is_command_terminator(zLine, zSql, nSql) ){
3361df8… drh 7581 memcpy(zLine,";",2);
3361df8… drh 7582 }
40c5397… drh 7583 #endif
564007c… drh 7584 if( strchr(zLine,';')!=0 ) hasSemi = 1;
564007c… drh 7585 if( nSql+nLine+4>=nAlloc ){
3361df8… drh 7586 }
564007c… drh 7587 if( nSql && hasSemi && line_is_complete(zSql, nSql) ){
e66a8c7… drh 7588 if( p->mIf==0 ){
e66a8c7… drh 7589 errCnt += runOneSqlLine(p, zSql, p->zInFile, startline);
e66a8c7… drh 7590 }
1d618cc… drh 7591 clearTempFile(p,0,0);
3361df8… drh 7592 }else if( nSql && line_is_all_whitespace(zSql) ){
e66a8c7… drh 7593 if( p->mIf==0 ){
e66a8c7… drh 7594 errCnt += runOneSqlLine(p, zSql, p->zInFile, startline);
e66a8c7… drh 7595 }
e66a8c7… drh 7596 while( p->nIfLevel > p->nIfAtStart ){
e66a8c7… drh 7597 int ii = --p->nIfLevel;
e66a8c7… drh 7598 cli_printf(stderr,"%s:%lld: unterminated .if\n", zSrc, p->lnIf[ii]);
e66a8c7… drh 7599 p->mIf &= ~(1<<ii);
e66a8c7… drh 7600 p->mElse &= ~(1<<ii);
e66a8c7… drh 7601 p->mIfHasBeenTrue &= ~(1<<ii);
e66a8c7… drh 7602 errCnt++;
e66a8c7… drh 7603 }
e66a8c7… drh 7604 p->nIfAtStart = saved_nIfAtStart;
71439dc… drh 7605 " -ascii set '.mode ascii'\n"
71439dc… drh 7606 " -box set '.mode box'\n"
896a463… drh 7607 " -cmdline-edit BOOL enable or disable command-line editing\n"
71439dc… drh 7608 " -column set '.mode column'\n"
71439dc… drh 7609 " -csv set '.mode csv -limits off'\n"
71439dc… drh 7610 " -html set '.mode html'\n"
71439dc… drh 7611 " -json set '.mode json'\n"
71439dc… drh 7612 " -line set '.mode line'\n"
71439dc… drh 7613 " -list set '.mode list'\n"
71439dc… drh 7614 " -markdown set '.mode markdown'\n"
71439dc… drh 7615 " -quote set '.mode quote'\n"
c92989d… drh 7616 " -runtests SCRIPT... Run multiple *.sql test script in subprocesses\n"
71439dc… drh 7617 " -table set '.mode table'\n"
71439dc… drh 7618 " -tabs set '.mode tabs'\n"
c92989d… drh 7619 /*
c92989d… drh 7620 ** Run a copy of this program as a subprocess
c92989d… drh 7621 */
c92989d… drh 7622 static void runShellSubprocess(
c92989d… drh 7623 const char *zProg,
c92989d… drh 7624 const char *zScript,
c92989d… drh 7625 int *pNErr,
c92989d… drh 7626 int *pNTest
c92989d… drh 7627 ){
c92989d… drh 7628 FILE *in;
c92989d… drh 7629 char *zCmd;
c92989d… drh 7630 const char *zTail;
c92989d… drh 7631 char zIn[1000];
c92989d… drh 7632 zTail = strrchr(zScript, '/');
c92989d… drh 7633 if( zTail ){
c92989d… drh 7634 zTail++;
c92989d… drh 7635 }else{
c92989d… drh 7636 zTail = zScript;
c92989d… drh 7637 }
c92989d… drh 7638 #ifdef _WIN32
c92989d… drh 7639 {
c92989d… drh 7640 const char *zBackslash = strrchr(zTail, '\\');
c92989d… drh 7641 if( zBackslash ) zTail = zBackslash+1;
c92989d… drh 7642 }
c92989d… drh 7643 #endif
c92989d… drh 7644 sqlite3_fprintf(stdout, "%-24s ", zTail);
c92989d… drh 7645 fflush(stdout);
c92989d… drh 7646 if( !isScriptFile(zScript,0) ){
c92989d… drh 7647 sqlite3_fprintf(stdout, "not an SQL script\n");
c92989d… drh 7648 (*pNErr)++;
c92989d… drh 7649 return;
c92989d… drh 7650 }
c92989d… drh 7651 #ifdef _WIN32
c92989d… drh 7652 /* The command runs as "cmd.exe /c COMMAND". If COMMAND starts with a
c92989d… drh 7653 ** double-quote and contains more than two of them, then cmd.exe removes
c92989d… drh 7654 ** the first and the last double-quote before doing anything else.
c92989d… drh 7655 ** The extra pair of quotes around the whole command is there to be
c92989d… drh 7656 ** removed, so that the quotes on the individual arguments survive. */
c92989d… drh 7657 zCmd = sqlite3_mprintf("\"\"%s\" \"%s\" 2>NUL\"", zProg, zScript);
c92989d… drh 7658 #else
c92989d… drh 7659 zCmd = sqlite3_mprintf("\"%s\" \"%s\" 2>/dev/null", zProg, zScript);
c92989d… drh 7660 #endif
c92989d… drh 7661 in = sqlite3_popen(zCmd, "r");
c92989d… drh 7662 if( in==0 ){
c92989d… drh 7663 sqlite3_fprintf(stdout, "cannot start subprocess\n");
c92989d… drh 7664 sqlite3_free(zCmd);
c92989d… drh 7665 (*pNErr)++;
c92989d… drh 7666 return;
c92989d… drh 7667 }
c92989d… drh 7668 while( sqlite3_fgets(zIn, sizeof(zIn), in) ){
c92989d… drh 7669 int n = 0;
c92989d… drh 7670 int m = 0;
c92989d… drh 7671 char *zRunWith;
c92989d… drh 7672 zRunWith = strstr(zIn, " run with ");
c92989d… drh 7673 if( zRunWith==0 ) continue;
c92989d… drh 7674 if( zIn[0]<'0' || zIn[0]>'9' ) continue;
c92989d… drh 7675 if( zRunWith[10]<'0' || zRunWith[10]>'9' ) continue;
c92989d… drh 7676 n = atoi(zIn);
c92989d… drh 7677 m = atoi(&zRunWith[10]);
c92989d… drh 7678 if( m==0 ){
c92989d… drh 7679 sqlite3_fprintf(stdout, "tests %5d\n", n);
c92989d… drh 7680 }else{
c92989d… drh 7681 sqlite3_fprintf(stdout, "tests %5d errors %5d\n", n, m);
c92989d… drh 7682 }
c92989d… drh 7683 (*pNErr) += m;
c92989d… drh 7684 (*pNTest) += n;
c92989d… drh 7685 pclose(in);
c92989d… drh 7686 sqlite3_free(zCmd);
c92989d… drh 7687 return;
c92989d… drh 7688 }
c92989d… drh 7689 pclose(in);
c92989d… drh 7690 sqlite3_free(zCmd);
c92989d… drh 7691 sqlite3_fprintf(stdout, "did not complete\n");
c92989d… drh 7692 fflush(stdout);
c92989d… drh 7693 (*pNErr)++;
c92989d… drh 7694 }
c92989d… drh 7695
c92989d… drh 7696 #ifdef _WIN32
c92989d… drh 7697 /*
c92989d… drh 7698 ** Run a subprocess for each script file that matches the wildcard zPattern.
c92989d… drh 7699 ** CMD.EXE does not expand wildcards, so the application must do it.
c92989d… drh 7700 ** Only the final path component of zPattern may contain wildcards.
c92989d… drh 7701 ** Return the number of scripts run.
c92989d… drh 7702 */
c92989d… drh 7703 static int runShellSubprocessGlob(
c92989d… drh 7704 const char *zProg,
c92989d… drh 7705 const char *zPattern,
c92989d… drh 7706 int *pNErr,
c92989d… drh 7707 int *pNTest
c92989d… drh 7708 ){
c92989d… drh 7709 WIN32_FIND_DATAW sFind;
c92989d… drh 7710 HANDLE hFind;
c92989d… drh 7711 LPWSTR zW = sqlite3_win32_utf8_to_unicode(zPattern);
c92989d… drh 7712 int nDir;
c92989d… drh 7713 int nRun = 0;
c92989d… drh 7714 shell_check_oom(zW);
c92989d… drh 7715 for(nDir=(int)strlen(zPattern); nDir>0; nDir--){
c92989d… drh 7716 char c = zPattern[nDir-1];
c92989d… drh 7717 if( c=='/' || c=='\\' || c==':' ) break;
c92989d… drh 7718 }
c92989d… drh 7719 hFind = FindFirstFileW(zW, &sFind);
c92989d… drh 7720 sqlite3_free(zW);
c92989d… drh 7721 if( hFind==INVALID_HANDLE_VALUE ) return 0;
c92989d… drh 7722 do{
c92989d… drh 7723 char *zName, *zPath;
c92989d… drh 7724 if( sFind.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) continue;
c92989d… drh 7725 zName = sqlite3_win32_unicode_to_utf8(sFind.cFileName);
c92989d… drh 7726 zPath = sqlite3_mprintf("%.*s%s", nDir, zPattern, zName);
c92989d… drh 7727 shell_check_oom(zPath);
c92989d… drh 7728 if( isScriptFile(zPath,0) ){ /* Also rejects 8.3-name false matches */
c92989d… drh 7729 runShellSubprocess(zProg, zPath, pNErr, pNTest);
c92989d… drh 7730 nRun++;
c92989d… drh 7731 }
c92989d… drh 7732 sqlite3_free(zPath);
c92989d… drh 7733 sqlite3_free(zName);
c92989d… drh 7734 }while( FindNextFileW(hFind, &sFind) );
c92989d… drh 7735 FindClose(hFind);
c92989d… drh 7736 return nRun;
c92989d… drh 7737 }
c92989d… drh 7738 #endif
c92989d… drh 7739
055e4d0… drh 7740 #if HAVE_EDITLINE
055e4d0… drh 7741 /*
055e4d0… drh 7742 ** https://sqlite.org/forum/forumpost/aad7a634916ff050:
055e4d0… drh 7743 **
3b2d0c9… drh 7744 ** Calling setlocale(LC_...,"") is required to get libedit to accept
055e4d0… drh 7745 ** non-ASCII input.
055e4d0… drh 7746 */
055e4d0… drh 7747 #define DO_SET_LOCALE 1
055e4d0… drh 7748 #include <locale.h>
055e4d0… drh 7749 #else
055e4d0… drh 7750 #define DO_SET_LOCALE 0
055e4d0… drh 7751 #endif
055e4d0… drh 7752
055e4d0… drh 7753 /*
c92989d… drh 7754 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, (void*)p);
1d618cc… drh 7755 globalShellState = p;
c93e1c8… drh 7756 #if HAVE_EDITLINE || HAVE_READLINE
c93e1c8… drh 7757 /* Editline requires \001...\002 delimiters around ANSI x3.64 escapes in
c93e1c8… drh 7758 ** prompt strings. Readline does sometimes, depending on how it is
c93e1c8… drh 7759 ** compiled and installed. */
c93e1c8… drh 7760 p->bDelimitNonprint = 1;
c93e1c8… drh 7761 #else
c93e1c8… drh 7762 /* No \001...\002 escapes required for linenoise or when not using a
c93e1c8… drh 7763 ** command-line editing library */
c93e1c8… drh 7764 p->bDelimitNonprint = 0;
c93e1c8… drh 7765 #endif
055e4d0… drh 7766 #if DO_SET_LOCALE
055e4d0… drh 7767 setlocale(LC_CTYPE,"");
055e4d0… drh 7768 #endif
055e4d0… drh 7769 #undef DO_SET_LOCALE
c93e1c8… drh 7770 static void printBold(const char *zText){
c93e1c8… drh 7771 if( shellNoColor() ){
c93e1c8… drh 7772 cli_printf(stdout, "%s", zText);
c93e1c8… drh 7773 }else{
c93e1c8… drh 7774 cli_printf(stdout, "\033[1;36m\033[3m%s\033[0m", zText);
c93e1c8… drh 7775 }
c93e1c8… drh 7776 }
1d618cc… drh 7777 /*
1d618cc… drh 7778 ** The callback from atexit().
1d618cc… drh 7779 */
a570ebc… drh 7780 static void SQLITE_CDECL abnormalExit(void){
1d618cc… drh 7781 if( globalShellState ){
1d618cc… drh 7782 clearTempFile(globalShellState, 1, 1);
1d618cc… drh 7783 }
0201a1e… drh 7784
0201a1e… drh 7785 #if defined(SQLITE_DEBUG) && !defined(SQLITE_SHELL_FIDDLE)
0201a1e… drh 7786 /* Ensure that sqlite3_reset_auto_extension() clears auto-extension
0201a1e… drh 7787 ** memory. https://sqlite.org/forum/forumpost/310cb231b07c80d1.
0201a1e… drh 7788 ** Testing this: if we (inadvertently) remove the
0201a1e… drh 7789 ** sqlite3_reset_auto_extension() call from main(), most shell tests
0201a1e… drh 7790 ** will fail because of a leak message in their output. */
0201a1e… drh 7791 static int auto_ext_leak_tester(
3361df8… drh 7792 sqlite3 *db,
3361df8… drh 7793 char **pzErrMsg,
0201a1e… drh 7794 const struct sqlite3_api_routines *pThunk
0201a1e… drh 7795 ){
0201a1e… drh 7796 (void)db; (void)pzErrMsg; (void)pThunk;
0201a1e… drh 7797 return SQLITE_OK;
0201a1e… drh 7798 }
0201a1e… drh 7799 #endif
17f9878… drh 7800
17f9878… drh 7801 #if defined(_WIN32) && !defined(__MINGW32__) && !defined(main)
1d618cc… drh 7802 DWORD mode;
1d618cc… drh 7803 HANDLE hOut;
1d618cc… drh 7804 hOut = GetStdHandle(STD_OUTPUT_HANDLE);
1d618cc… drh 7805 GetConsoleMode(hOut, &mode);
1d618cc… drh 7806 SetConsoleMode(hOut, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
1ec45d0… drh 7807 _setmode(_fileno(stdout),_O_BINARY); /* Bug 2026-08-03T08:52:42Z */
c92989d… drh 7808 int bTestMode = 0; /* --runtests option */
896a463… drh 7809 if( !stdin_is_interactive || !stdout_is_console ){
896a463… drh 7810 shellCmdLineEdit = 0;
896a463… drh 7811 }
1d618cc… drh 7812 atexit(abnormalExit);
1d618cc… drh 7813 #ifdef SIGTERM
1d618cc… drh 7814 signal(SIGTERM, sigterm_handler);
1d618cc… drh 7815 #endif
1d618cc… drh 7816 #ifdef SIGHUP
1d618cc… drh 7817 signal(SIGHUP, sigterm_handler);
1d618cc… drh 7818 #endif
1d618cc… drh 7819
c92989d… drh 7820 if( data.aAuxDb->zDbFilename==0
c92989d… drh 7821 && !bTestMode
c92989d… drh 7822 && (z[0]!='.' || !(z[1]>='a' && z[1]<='z'))
c92989d… drh 7823 && !isScriptFile(z,1)
c92989d… drh 7824 ){
3b2d0c9… drh 7825 shell_check_oom(aiCmd);
564007c… drh 7826 }else if( cli_strcmp(z,"-unsafe-testing")==0
564007c… drh 7827 || cli_strcmp(z,"-unsafe")==0 ){
e66a8c7… drh 7828 noInit = 1; /* --safe implies --noinit */
896a463… drh 7829 }else if( cli_strcmp(z,"-cmdline-edit")==0 ){
896a463… drh 7830 shellCmdLineEdit = booleanValue(cmdline_option_value(argc,argv,++i));
c92989d… drh 7831 }else if( cli_strcmp(z,"-runtests")==0 ){
c92989d… drh 7832 bTestMode = 1;
564007c… drh 7833 }else if( cli_strcmp(z,"-test-parse")==0 ){
564007c… drh 7834 /* Undocumented test option. Read input normally and process all
564007c… drh 7835 ** dot-commands. But do not process any SQL. Instead, whenever input
564007c… drh 7836 ** text would have been processed as SQL, print a one-line summary of
c92989d… drh 7837 ** the input. This is used by test scripts to verify that the end-of-SQL
564007c… drh 7838 ** parsing logic is working correctly. */
564007c… drh 7839 data.bTestParse = 1;
c92989d… drh 7840 #ifndef SQLITE_SHELL_FIDDLE
c92989d… drh 7841 if( bTestMode ){
c92989d… drh 7842 int nErr = 0;
c92989d… drh 7843 int nTest = 0;
c92989d… drh 7844 int nScript = 0;
c92989d… drh 7845 #ifdef _WIN32
c92989d… drh 7846 /* Child processes inherit this. Without it, a crash in a test script
c92989d… drh 7847 ** might raise a dialog box that stalls the run until it is dismissed. */
c92989d… drh 7848 SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
c92989d… drh 7849 #endif
c92989d… drh 7850 for(i=0; i<nCmd; i++){
c92989d… drh 7851 #ifdef _WIN32
c92989d… drh 7852 if( strpbrk(azCmd[i], "*?") ){
c92989d… drh 7853 int n = runShellSubprocessGlob(argv[0], azCmd[i], &nErr, &nTest);
c92989d… drh 7854 if( n>0 ){
c92989d… drh 7855 nScript += n;
c92989d… drh 7856 continue;
c92989d… drh 7857 }
c92989d… drh 7858 }
c92989d… drh 7859 #endif
c92989d… drh 7860 runShellSubprocess(argv[0], azCmd[i], &nErr, &nTest);
c92989d… drh 7861 nScript++;
c92989d… drh 7862 }
c92989d… drh 7863 sqlite3_fprintf(stdout, "%-24s tests %5d errors %5d scripts %5d\n",
c92989d… drh 7864 "TOTAL", nTest, nErr, nScript);
c92989d… drh 7865 rc = nErr>0;
c92989d… drh 7866 goto shell_main_exit;
c92989d… drh 7867 }
c92989d… drh 7868 #endif
0201a1e… drh 7869 #ifdef SQLITE_DEBUG
87881e8… drh 7870 sqlite3_auto_extension( (void(*)(void))auto_ext_leak_tester );
0201a1e… drh 7871 #endif
71439dc… drh 7872 modeSetLimit(&data, "off");
ee87371… drh 7873 data.mode.spec.bTitles = QRF_Always;
ba00a43… drh 7874 data.mode.mFlags |= MFLG_HDR;
ba00a43… drh 7875 data.mode.mFlags |= MFLG_HDR;
677842d… drh 7876 data.mStats = CLISTAT_ON;
896a463… drh 7877 }else if( cli_strcmp(z,"-cmdline-edit")==0 ){
896a463… drh 7878 i+=2;
b8ab8b3… drh 7879 if( rc && (bail_on_error || rc==2) ){
17f9878… drh 7880 rc = runOneSqlLine(&data, z, "cmdline", i);
896a463… drh 7881 char *zSaved = argv[i];
896a463… drh 7882 argv[i] = zSaved;
564007c… drh 7883 }else if( cli_strcmp(z,"-unsafe-testing")==0
564007c… drh 7884 || cli_strcmp(z,"-unsafe")==0 ){
564007c… drh 7885 /* Acted upon in first pass. */
c92989d… drh 7886 }else if( cli_strcmp(z,"-runtests")==0 ){
c92989d… drh 7887 /* Acted upon in first pass. */
564007c… drh 7888 }else if( cli_strcmp(z,"-test-parse")==0 ){
c92989d… drh 7889 if( res && bail_on_error ) i = nCmd;
c92989d… drh 7890 free(data.zErrPrefix);
17f9878… drh 7891 rc = runOneSqlLine(&data, azCmd[i], "cmdline", aiCmd[i]);
3361df8… drh 7892 if( rc ){
3361df8… drh 7893 goto shell_main_exit;
3361df8… drh 7894 }
17f9878… drh 7895 if( data.nPopOutput && azCmd[i][0]!='.' ){
1d618cc… drh 7896 clearTempFile(&data,0,0);
9b67f46… drh 7897 open_db(&data, 0);
2d6bfab… drh 7898 clearTempFile(&data,10000,1);
1d618cc… drh 7899 globalShellState = 0;
1d618cc… drh 7900 while( data.nModeStack ) modePop(&data);
1d618cc… drh 7901 free(data.aModeStack);
c92989d… drh 7902 free(data.zEqpFile);
3361df8… drh 7903 free(data.azPrompt[0]);
3361df8… drh 7904 free(data.azPrompt[1]);
677842d… drh 7905 free(data.zAuthDeny);
677842d… drh 7906 free(data.zAuthIgnore);
0201a1e… drh 7907 sqlite3_reset_auto_extension();
c92989d… drh 7908 rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1,
c92989d… drh 7909 (int*)0);
c92989d… drh 7910 sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0,
c92989d… drh 7911 (int*)0);
3361df8… drh 7912 }
3361df8… drh 7913
3361df8… drh 7914 char *fiddle_get_prompt(void){
3361df8… drh 7915 return expand_prompt(&shellState, 0, prompt_string(&shellState,0));

Keyboard Shortcuts

Open search /
Next entry (timeline) j
Previous entry (timeline) k
Open focused entry Enter
Show this help ?
Toggle theme Top nav button