Fossil SCM

Latest merge from trunk.

brickviking 2026-02-10 08:49 UTC bv-infotool merge
Commit d03791648f6bc0237d8a7464c213899b7632c5e89d812d04665f096075372b99
108 files changed +1027 -523 +1112 -736 +133 -35 +23 +2 -2 +1 -1 +7 -7 +18 -5 +1 -1 +1 -1 +18 -7 +7 -7 +1 -1 +2 -2 +3 -3 +7 -7 +1 -1 +32 -9 +19 -21 +1 -1 +1 -1 +1 -1 +1 -1 +8 -8 +9 -9 +19 -1 +3 -3 +1 -1 +22 -2 +5 -5 +115 -73 +1 -1 +4 -3 +2 -2 +3 -3 +1 -1 +1 -1 +4 -4 +1 -1 +1 -1 +3 -3 +1 -1 +1 -1 +1 -1 +2 -2 +1 -1 +2 -2 +1 -1 +1 -1 +1 -1 +33 -14 +7 +21 -100 +4 -4 +1 -1 +1 -1 +15 -9 +16 -8 +3 -4 +4 -4 +42 -1 +1 -1 +3 -3 +2 -2 +17 -5 +1 -1 +7 -7 +3 -3 +1 -1 +1 -1 +3 -1 +3 -3 +2 -2 +2 -2 +1 -1 +1 -1 +1 -1 +1 -1 +1 -1 +16 -12 +1 -1 +10 -5 +17 -5 +1 -1 +3 -3 +1 -1 +1 -1 +5 -5 +19 -18 +7 -7 +1 -1 +2 -2 +1 -1 +3 -3 +8 -5 +1 -1 +1 -1 +5 -5 +1 -1 +18 -6 +81 -3 +3 -3 +1 -1 +61 -23 +1 -1 +4 +18 -3 +1 -1
~ extsrc/shell.c ~ extsrc/sqlite3.c ~ extsrc/sqlite3.h ~ src/accordion.js ~ src/add.c ~ src/ajax.c ~ src/alerts.c ~ src/allrepo.c ~ src/backlink.c ~ src/bisect.c ~ src/blob.c ~ src/branch.c ~ src/builtin.c ~ src/cache.c ~ src/captcha.c ~ src/cgi.c ~ src/chat.c ~ src/checkin.c ~ src/checkout.c ~ src/color.c ~ src/comformat.c ~ src/config.h ~ src/configure.c ~ src/content.c ~ src/db.c ~ src/default.css ~ src/delta.c ~ src/descendants.c ~ src/diff.c ~ src/diffcmd.c ~ src/dispatch.c ~ src/event.c ~ src/export.c ~ src/file.c ~ src/fileedit.c ~ src/forum.c ~ src/fossil.confirmer.js ~ src/fossil.diff.js ~ src/fossil.dom.js ~ src/fossil.fetch.js ~ src/fossil.page.chat.js ~ src/fossil.page.fileedit.js ~ src/fossil.page.wikiedit.js ~ src/fossil.pikchr.js ~ src/fossil.wikiedit-wysiwyg.js ~ src/fshell.c ~ src/glob.c ~ src/graph.c ~ src/hname.c ~ src/hook.c ~ src/http.c ~ src/http_socket.c ~ src/http_ssl.c ~ src/json.c ~ src/json_report.c ~ src/json_status.c ~ src/login.c ~ src/main.c ~ src/manifest.c ~ src/markdown.c ~ src/markdown_html.c ~ src/match.c ~ src/merge.c ~ src/merge3.c ~ src/name.c ~ src/piechart.c ~ src/printf.c ~ src/purge.c ~ src/regexp.c ~ src/report.c ~ src/robot.c ~ src/schema.c ~ src/search.c ~ src/security_audit.c ~ src/setup.c ~ src/setupuser.c ~ src/sha1.c ~ src/skins.c ~ src/smtp.c ~ src/sqlcmd.c ~ src/stat.c ~ src/style.c ~ src/sync.c ~ src/tag.c ~ src/tar.c ~ src/terminal.c ~ src/th.c ~ src/th_main.c ~ src/timeline.c ~ src/tkt.c ~ src/tktsetup.c ~ src/undo.c ~ src/unicode.c ~ src/update.c ~ src/util.c ~ src/vfile.c ~ src/wiki.c ~ src/wikiformat.c ~ src/winhttp.c ~ src/xfer.c ~ src/xsystem.c ~ src/zip.c ~ tools/codecheck1.c ~ tools/mkindex.c ~ www/antibot.wiki ~ www/changes.wiki ~ www/customskin.md ~ www/serverext.wiki
+1027 -523
--- extsrc/shell.c
+++ extsrc/shell.c
@@ -35,11 +35,11 @@
3535
** ext/recover/sqlite3recover.h
3636
** src/shell.c.in
3737
**
3838
** To modify this program, get a copy of the canonical SQLite source tree,
3939
** edit the src/shell.c.in file and/or some of the other files that are
40
-** listed above, then rerun the rerun "make shell.c".
40
+** listed above, then rerun the command "make shell.c".
4141
*/
4242
/************************* Begin src/shell.c.in ******************/
4343
/*
4444
** 2001 September 15
4545
**
@@ -49,11 +49,11 @@
4949
** May you do good and not evil.
5050
** May you find forgiveness for yourself and forgive others.
5151
** May you share freely, never taking more than you give.
5252
**
5353
*************************************************************************
54
-** This file contains code to implement the "sqlite" command line
54
+** This file contains code to implement the "sqlite3" command line
5555
** utility for accessing SQLite databases.
5656
*/
5757
#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
5858
/* This needs to come before any includes for MSVC compiler */
5959
#define _CRT_SECURE_NO_WARNINGS
@@ -79,10 +79,14 @@
7979
** should only be used when building the "fiddle" web application, as
8080
** the browser-mode build has much different user input requirements
8181
** and this build mode rewires the user input subsystem to account for
8282
** that.
8383
*/
84
+#if defined(SQLITE_SHELL_FIDDLE)
85
+# undef SQLITE_OMIT_LOAD_EXTENSION
86
+# define SQLITE_OMIT_LOAD_EXTENSION 1
87
+#endif
8488
8589
/*
8690
** Warning pragmas copied from msvc.h in the core.
8791
*/
8892
#if defined(_MSC_VER)
@@ -872,10 +876,11 @@
872876
#ifndef SQLITE_QRF_H
873877
#include "qrf.h"
874878
#endif
875879
#include <string.h>
876880
#include <assert.h>
881
+#include <stdint.h>
877882
878883
/* typedef sqlite3_int64 i64; */
879884
880885
/* A single line in the EQP output */
881886
typedef struct qrfEQPGraphRow qrfEQPGraphRow;
@@ -889,11 +894,12 @@
889894
/* All EQP output is collected into an instance of the following */
890895
typedef struct qrfEQPGraph qrfEQPGraph;
891896
struct qrfEQPGraph {
892897
qrfEQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
893898
qrfEQPGraphRow *pLast; /* Last element of the pRow list */
894
- char zPrefix[100]; /* Graph prefix */
899
+ int nWidth; /* Width of the graph */
900
+ char zPrefix[400]; /* Graph prefix */
895901
};
896902
897903
/*
898904
** Private state information. Subject to change from one release to the
899905
** next.
@@ -995,10 +1001,19 @@
9951001
*/
9961002
static void qrfOom(Qrf *p){
9971003
qrfError(p, SQLITE_NOMEM, "out of memory");
9981004
}
9991005
1006
+/*
1007
+** Transfer any error in pStr over into p.
1008
+*/
1009
+static void qrfStrErr(Qrf *p, sqlite3_str *pStr){
1010
+ int rc = pStr ? sqlite3_str_errcode(pStr) : 0;
1011
+ if( rc ){
1012
+ qrfError(p, rc, sqlite3_errstr(rc));
1013
+ }
1014
+}
10001015
10011016
10021017
/*
10031018
** Add a new entry to the EXPLAIN QUERY PLAN data
10041019
*/
@@ -1074,10 +1089,49 @@
10741089
qrfEqpRenderLevel(p, pRow->iEqpId);
10751090
p->u.pGraph->zPrefix[n] = 0;
10761091
}
10771092
}
10781093
}
1094
+
1095
+/*
1096
+** Render the 64-bit value N in a more human-readable format into
1097
+** pOut.
1098
+**
1099
+** + Only show the first three significant digits.
1100
+** + Append suffixes K, M, G, T, P, and E for 1e3, 1e6, ... 1e18
1101
+*/
1102
+static void qrfApproxInt64(sqlite3_str *pOut, i64 N){
1103
+ static const char aSuffix[] = { 'K', 'M', 'G', 'T', 'P', 'E' };
1104
+ int i;
1105
+ if( N<0 ){
1106
+ N = N==INT64_MIN ? INT64_MAX : -N;
1107
+ sqlite3_str_append(pOut, "-", 1);
1108
+ }
1109
+ if( N<10000 ){
1110
+ sqlite3_str_appendf(pOut, "%4lld ", N);
1111
+ return;
1112
+ }
1113
+ for(i=1; i<=18; i++){
1114
+ N = (N+5)/10;
1115
+ if( N<10000 ){
1116
+ int n = (int)N;
1117
+ switch( i%3 ){
1118
+ case 0:
1119
+ sqlite3_str_appendf(pOut, "%d.%02d", n/1000, (n%1000)/10);
1120
+ break;
1121
+ case 1:
1122
+ sqlite3_str_appendf(pOut, "%2d.%d", n/100, (n%100)/10);
1123
+ break;
1124
+ case 2:
1125
+ sqlite3_str_appendf(pOut, "%4d", n/10);
1126
+ break;
1127
+ }
1128
+ sqlite3_str_append(pOut, &aSuffix[i/3], 1);
1129
+ break;
1130
+ }
1131
+ }
1132
+}
10791133
10801134
/*
10811135
** Display and reset the EXPLAIN QUERY PLAN data
10821136
*/
10831137
static void qrfEqpRender(Qrf *p, i64 nCycle){
@@ -1090,11 +1144,30 @@
10901144
}
10911145
sqlite3_str_appendf(p->pOut, "%s\n", pRow->zText+3);
10921146
p->u.pGraph->pRow = pRow->pNext;
10931147
sqlite3_free(pRow);
10941148
}else if( nCycle>0 ){
1095
- sqlite3_str_appendf(p->pOut, "QUERY PLAN (cycles=%lld [100%%])\n",nCycle);
1149
+ int nSp = p->u.pGraph->nWidth - 2;
1150
+ if( p->spec.eStyle==QRF_STYLE_StatsEst ){
1151
+ sqlite3_str_appendchar(p->pOut, nSp, ' ');
1152
+ sqlite3_str_appendall(p->pOut,
1153
+ "Cycles Loops (est) Rows (est)\n");
1154
+ sqlite3_str_appendchar(p->pOut, nSp, ' ');
1155
+ sqlite3_str_appendall(p->pOut,
1156
+ "---------- ------------ ------------\n");
1157
+ }else{
1158
+ sqlite3_str_appendchar(p->pOut, nSp, ' ');
1159
+ sqlite3_str_appendall(p->pOut,
1160
+ "Cycles Loops Rows \n");
1161
+ sqlite3_str_appendchar(p->pOut, nSp, ' ');
1162
+ sqlite3_str_appendall(p->pOut,
1163
+ "---------- ----- -----\n");
1164
+ }
1165
+ sqlite3_str_appendall(p->pOut, "QUERY PLAN");
1166
+ sqlite3_str_appendchar(p->pOut, nSp - 10, ' ');
1167
+ qrfApproxInt64(p->pOut, nCycle);
1168
+ sqlite3_str_appendall(p->pOut, " 100%\n");
10961169
}else{
10971170
sqlite3_str_appendall(p->pOut, "QUERY PLAN\n");
10981171
}
10991172
p->u.pGraph->zPrefix[0] = 0;
11001173
qrfEqpRenderLevel(p, 0);
@@ -1145,10 +1218,12 @@
11451218
static const int f = SQLITE_SCANSTAT_COMPLEX;
11461219
sqlite3_stmt *pS = p->pStmt;
11471220
int i = 0;
11481221
i64 nTotal = 0;
11491222
int nWidth = 0;
1223
+ int prevPid = -1; /* Previous iPid */
1224
+ double rEstCum = 1.0; /* Cumulative row estimate */
11501225
sqlite3_str *pLine = sqlite3_str_new(p->db);
11511226
sqlite3_str *pStats = sqlite3_str_new(p->db);
11521227
qrfEqpReset(p);
11531228
11541229
for(i=0; 1; i++){
@@ -1158,11 +1233,11 @@
11581233
break;
11591234
}
11601235
n = (int)strlen(z) + qrfStatsHeight(pS,i)*3;
11611236
if( n>nWidth ) nWidth = n;
11621237
}
1163
- nWidth += 4;
1238
+ nWidth += 2;
11641239
11651240
sqlite3_stmt_scanstatus_v2(pS,-1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
11661241
for(i=0; 1; i++){
11671242
i64 nLoop = 0;
11681243
i64 nRow = 0;
@@ -1173,55 +1248,67 @@
11731248
const char *zName = 0;
11741249
double rEst = 0.0;
11751250
11761251
if( sqlite3_stmt_scanstatus_v2(pS,i,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&zo) ){
11771252
break;
1253
+ }
1254
+ sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
1255
+ if( iPid!=prevPid ){
1256
+ prevPid = iPid;
1257
+ rEstCum = 1.0;
11781258
}
11791259
sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
1260
+ rEstCum *= rEst;
11801261
sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
11811262
sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
11821263
sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
11831264
sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
1184
- sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
11851265
sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
11861266
11871267
if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
1188
- const char *zSp = "";
1189
- double rpl;
1268
+ int nSp = 0;
11901269
sqlite3_str_reset(pStats);
11911270
if( nCycle>=0 && nTotal>0 ){
1192
- sqlite3_str_appendf(pStats, "cycles=%lld [%d%%]",
1193
- nCycle, ((nCycle*100)+nTotal/2) / nTotal
1271
+ qrfApproxInt64(pStats, nCycle);
1272
+ sqlite3_str_appendf(pStats, " %3d%%",
1273
+ ((nCycle*100)+nTotal/2) / nTotal
11941274
);
1195
- zSp = " ";
1275
+ nSp = 2;
11961276
}
11971277
if( nLoop>=0 ){
1198
- sqlite3_str_appendf(pStats, "%sloops=%lld", zSp, nLoop);
1199
- zSp = " ";
1278
+ if( nSp ) sqlite3_str_appendchar(pStats, nSp, ' ');
1279
+ qrfApproxInt64(pStats, nLoop);
1280
+ nSp = 2;
1281
+ if( p->spec.eStyle==QRF_STYLE_StatsEst ){
1282
+ sqlite3_str_appendf(pStats, " ");
1283
+ qrfApproxInt64(pStats, (i64)(rEstCum/rEst));
1284
+ }
12001285
}
12011286
if( nRow>=0 ){
1202
- sqlite3_str_appendf(pStats, "%srows=%lld", zSp, nRow);
1203
- zSp = " ";
1204
- }
1205
-
1206
- if( p->spec.eStyle==QRF_STYLE_StatsEst ){
1207
- rpl = (double)nRow / (double)nLoop;
1208
- sqlite3_str_appendf(pStats, "%srpl=%.1f est=%.1f", zSp, rpl, rEst);
1209
- }
1210
-
1287
+ if( nSp ) sqlite3_str_appendchar(pStats, nSp, ' ');
1288
+ qrfApproxInt64(pStats, nRow);
1289
+ nSp = 2;
1290
+ if( p->spec.eStyle==QRF_STYLE_StatsEst ){
1291
+ sqlite3_str_appendf(pStats, " ");
1292
+ qrfApproxInt64(pStats, (i64)rEstCum);
1293
+ }
1294
+ }
12111295
sqlite3_str_appendf(pLine,
1212
- "% *s (%s)", -1*(nWidth-qrfStatsHeight(pS,i)*3), zo,
1296
+ "% *s %s", -1*(nWidth-qrfStatsHeight(pS,i)*3), zo,
12131297
sqlite3_str_value(pStats)
12141298
);
12151299
sqlite3_str_reset(pStats);
12161300
qrfEqpAppend(p, iId, iPid, sqlite3_str_value(pLine));
12171301
sqlite3_str_reset(pLine);
12181302
}else{
12191303
qrfEqpAppend(p, iId, iPid, zo);
12201304
}
12211305
}
1306
+ if( p->u.pGraph ) p->u.pGraph->nWidth = nWidth;
1307
+ qrfStrErr(p, pLine);
12221308
sqlite3_free(sqlite3_str_finish(pLine));
1309
+ qrfStrErr(p, pStats);
12231310
sqlite3_free(sqlite3_str_finish(pStats));
12241311
#endif
12251312
}
12261313
12271314
@@ -1581,13 +1668,15 @@
15811668
** (3) z[] does not looks like a numeric literal
15821669
*/
15831670
static int qrfRelaxable(Qrf *p, const char *z){
15841671
size_t i, n;
15851672
if( z[0]=='\'' || qrfSpace(z[0]) ) return 0;
1586
- if( z[0]==0 && (p->spec.zNull==0 || p->spec.zNull[0]==0) ) return 0;
1673
+ if( z[0]==0 ){
1674
+ return (p->spec.zNull!=0 && p->spec.zNull[0]!=0);
1675
+ }
15871676
n = strlen(z);
1588
- if( z[n-1]=='\'' || qrfSpace(z[n-1]) ) return 0;
1677
+ if( n==0 || z[n-1]=='\'' || qrfSpace(z[n-1]) ) return 0;
15891678
if( p->spec.zNull && strcmp(p->spec.zNull,z)==0 ) return 0;
15901679
i = (z[0]=='-' || z[0]=='+');
15911680
if( strcmp(z+i,"Inf")==0 ) return 0;
15921681
if( !qrfDigit(z[i]) ) return 1;
15931682
i++;
@@ -2729,10 +2818,11 @@
27292818
int nNL = 0;
27302819
int n, w;
27312820
pStr = sqlite3_str_new(p->db);
27322821
qrfEncodeText(p, pStr, z ? z : "");
27332822
n = sqlite3_str_length(pStr);
2823
+ qrfStrErr(p, pStr);
27342824
z = data.az[data.n] = sqlite3_str_finish(pStr);
27352825
if( p->spec.nTitleLimit ){
27362826
nNL = 0;
27372827
data.aiWth[data.n] = w = qrfTitleLimit(data.az[data.n],
27382828
p->spec.nTitleLimit );
@@ -2756,10 +2846,11 @@
27562846
int n, w;
27572847
int eType = sqlite3_column_type(p->pStmt,i);
27582848
pStr = sqlite3_str_new(p->db);
27592849
qrfRenderValue(p, pStr, i);
27602850
n = sqlite3_str_length(pStr);
2851
+ qrfStrErr(p, pStr);
27612852
z = data.az[data.n] = sqlite3_str_finish(pStr);
27622853
data.abNum[data.n] = eType==SQLITE_INTEGER || eType==SQLITE_FLOAT;
27632854
data.aiWth[data.n] = w = qrfDisplayWidth(z, n, &nNL);
27642855
data.n++;
27652856
if( w>data.a[i].mxW ) data.a[i].mxW = w;
@@ -2910,11 +3001,11 @@
29103001
){
29113002
bRTrim = 1;
29123003
}else{
29133004
bRTrim = 0;
29143005
}
2915
- for(i=0; i<data.n; i+=nColumn){
3006
+ for(i=0; i<data.n && sqlite3_str_errcode(p->pOut)==SQLITE_OK; i+=nColumn){
29163007
int bMore;
29173008
int nRow = 0;
29183009
29193010
/* Draw a single row of the table. This might be the title line
29203011
** (if there is a title line) or a row in the body of the table.
@@ -3097,11 +3188,11 @@
30973188
assert( 0==sqlite3_stricmp( sqlite3_column_name(p->pStmt, 0), "addr" ) );
30983189
assert( 0==sqlite3_stricmp( sqlite3_column_name(p->pStmt, 1), "opcode" ) );
30993190
assert( 0==sqlite3_stricmp( sqlite3_column_name(p->pStmt, 2), "p1" ) );
31003191
assert( 0==sqlite3_stricmp( sqlite3_column_name(p->pStmt, 3), "p2" ) );
31013192
3102
- for(iOp=0; SQLITE_ROW==sqlite3_step(p->pStmt); iOp++){
3193
+ for(iOp=0; SQLITE_ROW==sqlite3_step(p->pStmt) && !p->iErr; iOp++){
31033194
int iAddr = sqlite3_column_int(p->pStmt, 0);
31043195
const char *zOp = (const char*)sqlite3_column_text(p->pStmt, 1);
31053196
int p1 = sqlite3_column_int(p->pStmt, 2);
31063197
int p2 = sqlite3_column_int(p->pStmt, 3);
31073198
@@ -3154,11 +3245,11 @@
31543245
nWidth = sizeof(aScanExpWidth)/sizeof(int);
31553246
iIndent = 3;
31563247
}
31573248
if( nArg>nWidth ) nArg = nWidth;
31583249
3159
- for(iOp=0; sqlite3_step(p->pStmt)==SQLITE_ROW; iOp++){
3250
+ for(iOp=0; sqlite3_step(p->pStmt)==SQLITE_ROW && !p->iErr; iOp++){
31603251
/* If this is the first row seen, print out the headers */
31613252
if( iOp==0 ){
31623253
for(i=0; i<nArg; i++){
31633254
const char *zCol = sqlite3_column_name(p->pStmt, aMap[i]);
31643255
qrfWidthPrint(p,p->pOut, aWidth[i], zCol);
@@ -3410,10 +3501,11 @@
34103501
sqlite3_str_append(p->pOut, "\n", 1);
34113502
zVal += iNext;
34123503
}while( zVal[0] );
34133504
sqlite3_str_reset(pVal);
34143505
}
3506
+ qrfStrErr(p, pVal);
34153507
sqlite3_free(sqlite3_str_finish(pVal));
34163508
qrfWrite(p);
34173509
break;
34183510
}
34193511
case QRF_STYLE_Eqp: {
@@ -3473,11 +3565,11 @@
34733565
p->pOut = sqlite3_str_new(p->db);
34743566
if( p->pOut==0 ){
34753567
qrfOom(p);
34763568
return;
34773569
}
3478
- p->iErr = 0;
3570
+ p->iErr = SQLITE_OK;
34793571
p->nCol = sqlite3_column_count(p->pStmt);
34803572
p->nRow = 0;
34813573
sz = sizeof(sqlite3_qrf_spec);
34823574
memcpy(&p->spec, pSpec, sz);
34833575
if( p->spec.zNull==0 ) p->spec.zNull = "";
@@ -3644,17 +3736,27 @@
36443736
sqlite3_free(p->u.sLine.azCol);
36453737
}
36463738
break;
36473739
}
36483740
case QRF_STYLE_Stats:
3649
- case QRF_STYLE_StatsEst:
3741
+ case QRF_STYLE_StatsEst: {
3742
+ i64 nCycle = 0;
3743
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3744
+ sqlite3_stmt_scanstatus_v2(p->pStmt, -1, SQLITE_SCANSTAT_NCYCLE,
3745
+ SQLITE_SCANSTAT_COMPLEX, (void*)&nCycle);
3746
+#endif
3747
+ qrfEqpRender(p, nCycle);
3748
+ qrfWrite(p);
3749
+ break;
3750
+ }
36503751
case QRF_STYLE_Eqp: {
36513752
qrfEqpRender(p, 0);
36523753
qrfWrite(p);
36533754
break;
36543755
}
36553756
}
3757
+ qrfStrErr(p, p->pOut);
36563758
if( p->spec.pzOutput ){
36573759
if( p->spec.pzOutput[0] ){
36583760
sqlite3_int64 n, sz;
36593761
char *zCombined;
36603762
sz = strlen(p->spec.pzOutput[0]);
@@ -3815,13 +3917,10 @@
38153917
38163918
38173919
#define eputz(z) cli_puts(z,stderr)
38183920
#define sputz(fp,z) cli_puts(z,fp)
38193921
3820
-/* True if the timer is enabled */
3821
-static int enableTimer = 0;
3822
-
38233922
/* A version of strcmp() that works with NULL values */
38243923
static int cli_strcmp(const char *a, const char *b){
38253924
if( a==0 ) a = "";
38263925
if( b==0 ) b = "";
38273926
return strcmp(a,b);
@@ -3834,11 +3933,11 @@
38343933
38353934
/* Return the current wall-clock time in microseconds since the
38363935
** Unix epoch (1970-01-01T00:00:00Z)
38373936
*/
38383937
static sqlite3_int64 timeOfDay(void){
3839
-#if defined(_WIN64)
3938
+#if defined(_WIN64) && _WIN32_WINNT >= _WIN32_WINNT_WIN8
38403939
sqlite3_uint64 t;
38413940
FILETIME tm;
38423941
GetSystemTimePreciseAsFileTime(&tm);
38433942
t = ((u64)tm.dwHighDateTime<<32) | (u64)tm.dwLowDateTime;
38443943
t += 116444736000000000LL;
@@ -3862,154 +3961,10 @@
38623961
(void)gettimeofday(&sNow,0);
38633962
return ((i64)sNow.tv_sec)*1000000 + sNow.tv_usec;
38643963
#endif
38653964
}
38663965
3867
-#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
3868
-#include <sys/time.h>
3869
-#include <sys/resource.h>
3870
-
3871
-/* VxWorks does not support getrusage() as far as we can determine */
3872
-#if defined(_WRS_KERNEL) || defined(__RTP__)
3873
-struct rusage {
3874
- struct timeval ru_utime; /* user CPU time used */
3875
- struct timeval ru_stime; /* system CPU time used */
3876
-};
3877
-#define getrusage(A,B) memset(B,0,sizeof(*B))
3878
-#endif
3879
-
3880
-
3881
-/* Saved resource information for the beginning of an operation */
3882
-static struct rusage sBegin; /* CPU time at start */
3883
-static sqlite3_int64 iBegin; /* Wall-clock time at start */
3884
-
3885
-/*
3886
-** Begin timing an operation
3887
-*/
3888
-static void beginTimer(void){
3889
- if( enableTimer ){
3890
- getrusage(RUSAGE_SELF, &sBegin);
3891
- iBegin = timeOfDay();
3892
- }
3893
-}
3894
-
3895
-/* Return the difference of two time_structs in seconds */
3896
-static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
3897
- return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
3898
- (double)(pEnd->tv_sec - pStart->tv_sec);
3899
-}
3900
-
3901
-/*
3902
-** Print the timing results.
3903
-*/
3904
-static void endTimer(FILE *out){
3905
- if( enableTimer ){
3906
- sqlite3_int64 iEnd = timeOfDay();
3907
- struct rusage sEnd;
3908
- getrusage(RUSAGE_SELF, &sEnd);
3909
- cli_printf(out, "Run Time: real %.6f user %.6f sys %.6f\n",
3910
- (iEnd - iBegin)*0.000001,
3911
- timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
3912
- timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
3913
- }
3914
-}
3915
-
3916
-#define BEGIN_TIMER beginTimer()
3917
-#define END_TIMER(X) endTimer(X)
3918
-#define HAS_TIMER 1
3919
-
3920
-#elif (defined(_WIN32) || defined(WIN32))
3921
-
3922
-/* Saved resource information for the beginning of an operation */
3923
-static HANDLE hProcess;
3924
-static FILETIME ftKernelBegin;
3925
-static FILETIME ftUserBegin;
3926
-static sqlite3_int64 ftWallBegin;
3927
-typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
3928
- LPFILETIME, LPFILETIME);
3929
-static GETPROCTIMES getProcessTimesAddr = NULL;
3930
-
3931
-/*
3932
-** Check to see if we have timer support. Return 1 if necessary
3933
-** support found (or found previously).
3934
-*/
3935
-static int hasTimer(void){
3936
- if( getProcessTimesAddr ){
3937
- return 1;
3938
- } else {
3939
- /* GetProcessTimes() isn't supported in WIN95 and some other Windows
3940
- ** versions. See if the version we are running on has it, and if it
3941
- ** does, save off a pointer to it and the current process handle.
3942
- */
3943
- hProcess = GetCurrentProcess();
3944
- if( hProcess ){
3945
- HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
3946
- if( NULL != hinstLib ){
3947
- getProcessTimesAddr =
3948
- (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
3949
- if( NULL != getProcessTimesAddr ){
3950
- return 1;
3951
- }
3952
- FreeLibrary(hinstLib);
3953
- }
3954
- }
3955
- }
3956
- return 0;
3957
-}
3958
-
3959
-/*
3960
-** Begin timing an operation
3961
-*/
3962
-static void beginTimer(void){
3963
- if( enableTimer && getProcessTimesAddr ){
3964
- FILETIME ftCreation, ftExit;
3965
- getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
3966
- &ftKernelBegin,&ftUserBegin);
3967
- ftWallBegin = timeOfDay();
3968
- }
3969
-}
3970
-
3971
-/* Return the difference of two FILETIME structs in seconds */
3972
-static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
3973
- sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
3974
- sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
3975
- return (double) ((i64End - i64Start) / 10000000.0);
3976
-}
3977
-
3978
-/*
3979
-** Print the timing results.
3980
-*/
3981
-static void endTimer(FILE *out){
3982
- if( enableTimer && getProcessTimesAddr){
3983
- FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
3984
- sqlite3_int64 ftWallEnd = timeOfDay();
3985
- getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
3986
-#ifdef _WIN64
3987
- /* microsecond precision on 64-bit windows */
3988
- cli_printf(out, "Run Time: real %.6f user %f sys %f\n",
3989
- (ftWallEnd - ftWallBegin)*0.000001,
3990
- timeDiff(&ftUserBegin, &ftUserEnd),
3991
- timeDiff(&ftKernelBegin, &ftKernelEnd));
3992
-#else
3993
- /* millisecond precisino on 32-bit windows */
3994
- cli_printf(out, "Run Time: real %.3f user %.3f sys %.3f\n",
3995
- (ftWallEnd - ftWallBegin)*0.000001,
3996
- timeDiff(&ftUserBegin, &ftUserEnd),
3997
- timeDiff(&ftKernelBegin, &ftKernelEnd));
3998
-#endif
3999
- }
4000
-}
4001
-
4002
-#define BEGIN_TIMER beginTimer()
4003
-#define END_TIMER(X) endTimer(X)
4004
-#define HAS_TIMER hasTimer()
4005
-
4006
-#else
4007
-#define BEGIN_TIMER
4008
-#define END_TIMER(X) /*no-op*/
4009
-#define HAS_TIMER 0
4010
-#endif
40113966
40123967
/*
40133968
** Used to prevent warnings about unused parameters
40143969
*/
40153970
#define UNUSED_PARAMETER(x) (void)(x)
@@ -4068,10 +4023,18 @@
40684023
#define PROMPT_LEN_MAX 128
40694024
/* First line prompt. default: "sqlite> " */
40704025
static char mainPrompt[PROMPT_LEN_MAX];
40714026
/* Continuation prompt. default: " ...> " */
40724027
static char continuePrompt[PROMPT_LEN_MAX];
4028
+
4029
+/*
4030
+** Write I/O traces to the following stream.
4031
+*/
4032
+#ifdef SQLITE_ENABLE_IOTRACE
4033
+static FILE *iotrace = 0;
4034
+#endif
4035
+
40734036
40744037
/* This is variant of the standard-library strncpy() routine with the
40754038
** one change that the destination string is always zero-terminated, even
40764039
** if there is no zero-terminator in the first n-1 characters of the source
40774040
** string.
@@ -4188,17 +4151,10 @@
41884151
*/
41894152
static void shell_check_oom(const void *p){
41904153
if( p==0 ) shell_out_of_memory();
41914154
}
41924155
4193
-/*
4194
-** Write I/O traces to the following stream.
4195
-*/
4196
-#ifdef SQLITE_ENABLE_IOTRACE
4197
-static FILE *iotrace = 0;
4198
-#endif
4199
-
42004156
/*
42014157
** This routine works like printf in that its first argument is a
42024158
** format string and subsequent arguments are values to be substituted
42034159
** in place of % fields. The result of formatting this string
42044160
** is written to iotrace.
@@ -8349,13 +8305,13 @@
83498305
}else if( e<-10000 ){
83508306
e = -10000;
83518307
}
83528308
83538309
if( m<0 ){
8310
+ if( m<(-9223372036854775807LL) ) return;
83548311
isNeg = 1;
83558312
m = -m;
8356
- if( m<0 ) return;
83578313
}else if( m==0 && e>-1000 && e<1000 ){
83588314
sqlite3_result_double(context, 0.0);
83598315
return;
83608316
}
83618317
while( (m>>32)&0xffe00000 ){
@@ -9472,11 +9428,11 @@
94729428
** (X) match X
94739429
** X|Y X or Y
94749430
** ^X X occurring at the beginning of the string
94759431
** X$ X occurring at the end of the string
94769432
** . Match any single character
9477
-** \c Character c where c is one of \{}()[]|*+?.
9433
+** \c Character c where c is one of \{}()[]|*+?-.
94789434
** \c C-language escapes for c in afnrtv. ex: \t or \n
94799435
** \uXXXX Where XXXX is exactly 4 hex digits, unicode value XXXX
94809436
** \xXX Where XX is exactly 2 hex digits, unicode value XX
94819437
** [abc] Any single character from the set abc
94829438
** [^abc] Any single character not in the set abc
@@ -9857,11 +9813,11 @@
98579813
98589814
/* A backslash character has been seen, read the next character and
98599815
** return its interpretation.
98609816
*/
98619817
static unsigned re_esc_char(ReCompiled *p){
9862
- static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
9818
+ static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]-";
98639819
static const char zTrans[] = "\a\f\n\r\t\v";
98649820
int i, v = 0;
98659821
char c;
98669822
if( p->sIn.i>=p->sIn.mx ) return 0;
98679823
c = p->sIn.z[p->sIn.i];
@@ -10180,15 +10136,22 @@
1018010136
}
1018110137
return pRe->zErr;
1018210138
}
1018310139
1018410140
/*
10185
-** Compute a reasonable limit on the length of the REGEXP NFA.
10141
+** The value of LIMIT_MAX_PATTERN_LENGTH.
1018610142
*/
1018710143
static int re_maxlen(sqlite3_context *context){
1018810144
sqlite3 *db = sqlite3_context_db_handle(context);
10189
- return 75 + sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH,-1)/2;
10145
+ return sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH,-1);
10146
+}
10147
+
10148
+/*
10149
+** Maximum NFA size given a maximum pattern length.
10150
+*/
10151
+static int re_maxnfa(int mxlen){
10152
+ return 75+mxlen/2;
1019010153
}
1019110154
1019210155
/*
1019310156
** Implementation of the regexp() SQL function. This function implements
1019410157
** the build-in REGEXP operator. The first argument to the function is the
@@ -10210,14 +10173,21 @@
1021010173
int setAux = 0; /* True to invoke sqlite3_set_auxdata() */
1021110174
1021210175
(void)argc; /* Unused */
1021310176
pRe = sqlite3_get_auxdata(context, 0);
1021410177
if( pRe==0 ){
10178
+ int mxLen = re_maxlen(context);
10179
+ int nPattern;
1021510180
zPattern = (const char*)sqlite3_value_text(argv[0]);
1021610181
if( zPattern==0 ) return;
10217
- zErr = re_compile(&pRe, zPattern, re_maxlen(context),
10218
- sqlite3_user_data(context)!=0);
10182
+ nPattern = sqlite3_value_bytes(argv[0]);
10183
+ if( nPattern>mxLen ){
10184
+ zErr = "REGEXP pattern too big";
10185
+ }else{
10186
+ zErr = re_compile(&pRe, zPattern, re_maxnfa(mxLen),
10187
+ sqlite3_user_data(context)!=0);
10188
+ }
1021910189
if( zErr ){
1022010190
re_free(pRe);
1022110191
sqlite3_result_error(context, zErr, -1);
1022210192
return;
1022310193
}
@@ -10279,11 +10249,11 @@
1027910249
"ATSTART",
1028010250
};
1028110251
1028210252
zPattern = (const char*)sqlite3_value_text(argv[0]);
1028310253
if( zPattern==0 ) return;
10284
- zErr = re_compile(&pRe, zPattern, re_maxlen(context),
10254
+ zErr = re_compile(&pRe, zPattern, re_maxnfa(re_maxlen(context)),
1028510255
sqlite3_user_data(context)!=0);
1028610256
if( zErr ){
1028710257
re_free(pRe);
1028810258
sqlite3_result_error(context, zErr, -1);
1028910259
return;
@@ -13067,11 +13037,11 @@
1306713037
nFile = (int)strlen(zFile)+1;
1306813038
}
1306913039
1307013040
rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
1307113041
if( rc==SQLITE_OK ){
13072
- pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
13042
+ pNew = (ZipfileTab*)sqlite3_malloc64((i64)nByte+nFile);
1307313043
if( pNew==0 ) return SQLITE_NOMEM;
1307413044
memset(pNew, 0, nByte+nFile);
1307513045
pNew->db = db;
1307613046
pNew->aBuffer = (u8*)&pNew[1];
1307713047
if( zFile ){
@@ -13213,18 +13183,19 @@
1321313183
** sqlite3_free().
1321413184
*/
1321513185
static int zipfileReadData(
1321613186
FILE *pFile, /* Read from this file */
1321713187
u8 *aRead, /* Read into this buffer */
13218
- int nRead, /* Number of bytes to read */
13188
+ i64 nRead, /* Number of bytes to read */
1321913189
i64 iOff, /* Offset to read from */
1322013190
char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */
1322113191
){
1322213192
size_t n;
1322313193
fseek(pFile, (long)iOff, SEEK_SET);
13224
- n = fread(aRead, 1, nRead, pFile);
13225
- if( (int)n!=nRead ){
13194
+ n = fread(aRead, 1, (long)nRead, pFile);
13195
+ if( n!=(size_t)nRead ){
13196
+ sqlite3_free(*pzErrmsg);
1322613197
*pzErrmsg = sqlite3_mprintf("error in fread()");
1322713198
return SQLITE_ERROR;
1322813199
}
1322913200
return SQLITE_OK;
1323013201
}
@@ -13237,11 +13208,11 @@
1323713208
if( nWrite>0 ){
1323813209
size_t n = nWrite;
1323913210
fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
1324013211
n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
1324113212
if( (int)n!=nWrite ){
13242
- pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
13213
+ zipfileTableErr(pTab,"error in fwrite()");
1324313214
return SQLITE_ERROR;
1324413215
}
1324513216
pTab->szCurrent += nWrite;
1324613217
}
1324713218
return SQLITE_OK;
@@ -13484,10 +13455,11 @@
1348413455
/*
1348513456
** Set (*pzErr) to point to a buffer from sqlite3_malloc() containing a
1348613457
** generic corruption message and return SQLITE_CORRUPT;
1348713458
*/
1348813459
static int zipfileCorrupt(char **pzErr){
13460
+ sqlite3_free(*pzErr);
1348913461
*pzErr = sqlite3_mprintf("zip archive is corrupt");
1349013462
return SQLITE_CORRUPT;
1349113463
}
1349213464
1349313465
/*
@@ -13502,11 +13474,11 @@
1350213474
** final value of (*ppEntry) undefined.
1350313475
*/
1350413476
static int zipfileGetEntry(
1350513477
ZipfileTab *pTab, /* Store any error message here */
1350613478
const u8 *aBlob, /* Pointer to in-memory file image */
13507
- int nBlob, /* Size of aBlob[] in bytes */
13479
+ i64 nBlob, /* Size of aBlob[] in bytes */
1350813480
FILE *pFile, /* If aBlob==0, read from this file */
1350913481
i64 iOff, /* Offset of CDS record */
1351013482
ZipfileEntry **ppEntry /* OUT: Pointer to new object */
1351113483
){
1351213484
u8 *aRead;
@@ -13542,18 +13514,18 @@
1354213514
rc = SQLITE_NOMEM;
1354313515
}else{
1354413516
memset(pNew, 0, sizeof(ZipfileEntry));
1354513517
rc = zipfileReadCDS(aRead, &pNew->cds);
1354613518
if( rc!=SQLITE_OK ){
13547
- *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
13519
+ zipfileTableErr(pTab, "failed to read CDS at offset %lld", iOff);
1354813520
}else if( aBlob==0 ){
1354913521
rc = zipfileReadData(
1355013522
pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
1355113523
);
1355213524
}else{
1355313525
aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
13554
- if( (iOff + ZIPFILE_LFH_FIXED_SZ + nFile + nExtra)>nBlob ){
13526
+ if( (iOff + ZIPFILE_CDS_FIXED_SZ + nFile + nExtra)>nBlob ){
1355513527
rc = zipfileCorrupt(pzErr);
1355613528
}
1355713529
}
1355813530
}
1355913531
@@ -13574,19 +13546,19 @@
1357413546
ZipfileLFH lfh;
1357513547
if( pFile ){
1357613548
rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
1357713549
}else{
1357813550
aRead = (u8*)&aBlob[pNew->cds.iOffset];
13579
- if( (pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ)>(unsigned)nBlob ){
13551
+ if( ((i64)pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ)>nBlob ){
1358013552
rc = zipfileCorrupt(pzErr);
1358113553
}
1358213554
}
1358313555
1358413556
memset(&lfh, 0, sizeof(lfh));
1358513557
if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
1358613558
if( rc==SQLITE_OK ){
13587
- pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
13559
+ pNew->iDataOff = (i64)pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
1358813560
pNew->iDataOff += lfh.nFile + lfh.nExtra;
1358913561
if( aBlob && pNew->cds.szCompressed ){
1359013562
if( pNew->iDataOff + pNew->cds.szCompressed > nBlob ){
1359113563
rc = zipfileCorrupt(pzErr);
1359213564
}else{
@@ -13593,11 +13565,11 @@
1359313565
pNew->aData = &pNew->aExtra[nExtra];
1359413566
memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
1359513567
}
1359613568
}
1359713569
}else{
13598
- *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
13570
+ zipfileTableErr(pTab, "failed to read LFH at offset %d",
1359913571
(int)pNew->cds.iOffset
1360013572
);
1360113573
}
1360213574
}
1360313575
@@ -13617,11 +13589,11 @@
1361713589
static int zipfileNext(sqlite3_vtab_cursor *cur){
1361813590
ZipfileCsr *pCsr = (ZipfileCsr*)cur;
1361913591
int rc = SQLITE_OK;
1362013592
1362113593
if( pCsr->pFile ){
13622
- i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
13594
+ i64 iEof = (i64)pCsr->eocd.iOffset + (i64)pCsr->eocd.nSize;
1362313595
zipfileEntryFree(pCsr->pCurrent);
1362413596
pCsr->pCurrent = 0;
1362513597
if( pCsr->iNextOff>=iEof ){
1362613598
pCsr->bEof = 1;
1362713599
}else{
@@ -13855,16 +13827,16 @@
1385513827
** an English language error message may be left in virtual-table pTab.
1385613828
*/
1385713829
static int zipfileReadEOCD(
1385813830
ZipfileTab *pTab, /* Return errors here */
1385913831
const u8 *aBlob, /* Pointer to in-memory file image */
13860
- int nBlob, /* Size of aBlob[] in bytes */
13832
+ i64 nBlob, /* Size of aBlob[] in bytes */
1386113833
FILE *pFile, /* Read from this file if aBlob==0 */
1386213834
ZipfileEOCD *pEOCD /* Object to populate */
1386313835
){
1386413836
u8 *aRead = pTab->aBuffer; /* Temporary buffer */
13865
- int nRead; /* Bytes to read from file */
13837
+ i64 nRead; /* Bytes to read from file */
1386613838
int rc = SQLITE_OK;
1386713839
1386813840
memset(pEOCD, 0, sizeof(ZipfileEOCD));
1386913841
if( aBlob==0 ){
1387013842
i64 iOff; /* Offset to read from */
@@ -13881,11 +13853,11 @@
1388113853
nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
1388213854
aRead = (u8*)&aBlob[nBlob-nRead];
1388313855
}
1388413856
1388513857
if( rc==SQLITE_OK ){
13886
- int i;
13858
+ i64 i;
1388713859
1388813860
/* Scan backwards looking for the signature bytes */
1388913861
for(i=nRead-20; i>=0; i--){
1389013862
if( aRead[i]==0x50 && aRead[i+1]==0x4b
1389113863
&& aRead[i+2]==0x05 && aRead[i+3]==0x06
@@ -13892,13 +13864,11 @@
1389213864
){
1389313865
break;
1389413866
}
1389513867
}
1389613868
if( i<0 ){
13897
- pTab->base.zErrMsg = sqlite3_mprintf(
13898
- "cannot find end of central directory record"
13899
- );
13869
+ zipfileTableErr(pTab, "cannot find end of central directory record");
1390013870
return SQLITE_ERROR;
1390113871
}
1390213872
1390313873
aRead += i+4;
1390413874
pEOCD->iDisk = zipfileRead16(aRead);
@@ -13939,11 +13909,11 @@
1393913909
pNew->pNext = pBefore;
1394013910
*pp = pNew;
1394113911
}
1394213912
}
1394313913
13944
-static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
13914
+static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, i64 nBlob){
1394513915
ZipfileEOCD eocd;
1394613916
int rc;
1394713917
int i;
1394813918
i64 iOff;
1394913919
@@ -13987,11 +13957,11 @@
1398713957
zipfileCursorErr(pCsr, "zipfile() function requires an argument");
1398813958
return SQLITE_ERROR;
1398913959
}else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
1399013960
static const u8 aEmptyBlob = 0;
1399113961
const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
13992
- int nBlob = sqlite3_value_bytes(argv[0]);
13962
+ i64 nBlob = sqlite3_value_bytes(argv[0]);
1399313963
assert( pTab->pFirstEntry==0 );
1399413964
if( aBlob==0 ){
1399513965
aBlob = &aEmptyBlob;
1399613966
nBlob = 0;
1399713967
}
@@ -14185,23 +14155,23 @@
1418514155
ZipfileTab *pTab = (ZipfileTab*)pVtab;
1418614156
int rc = SQLITE_OK;
1418714157
1418814158
assert( pTab->pWriteFd==0 );
1418914159
if( pTab->zFile==0 || pTab->zFile[0]==0 ){
14190
- pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
14160
+ zipfileTableErr(pTab, "zipfile: missing filename");
1419114161
return SQLITE_ERROR;
1419214162
}
1419314163
1419414164
/* Open a write fd on the file. Also load the entire central directory
1419514165
** structure into memory. During the transaction any new file data is
1419614166
** appended to the archive file, but the central directory is accumulated
1419714167
** in main-memory until the transaction is committed. */
1419814168
pTab->pWriteFd = sqlite3_fopen(pTab->zFile, "ab+");
1419914169
if( pTab->pWriteFd==0 ){
14200
- pTab->base.zErrMsg = sqlite3_mprintf(
14201
- "zipfile: failed to open file %s for writing", pTab->zFile
14202
- );
14170
+ zipfileTableErr(pTab,
14171
+ "zipfile: failed to open file %s for writing", pTab->zFile
14172
+ );
1420314173
rc = SQLITE_ERROR;
1420414174
}else{
1420514175
fseek(pTab->pWriteFd, 0, SEEK_END);
1420614176
pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
1420714177
rc = zipfileLoadDirectory(pTab, 0, 0);
@@ -14662,11 +14632,11 @@
1466214632
int nEntry;
1466314633
ZipfileBuffer body;
1466414634
ZipfileBuffer cds;
1466514635
};
1466614636
14667
-static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
14637
+static int zipfileBufferGrow(ZipfileBuffer *pBuf, i64 nByte){
1466814638
if( pBuf->n+nByte>pBuf->nAlloc ){
1466914639
u8 *aNew;
1467014640
sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
1467114641
int nReq = pBuf->n + nByte;
1467214642
@@ -14711,11 +14681,11 @@
1471114681
u32 iCrc32 = 0; /* crc32 of uncompressed data */
1471214682
1471314683
char *zName = 0; /* Path (name) of new entry */
1471414684
int nName = 0; /* Size of zName in bytes */
1471514685
char *zFree = 0; /* Free this before returning */
14716
- int nByte;
14686
+ i64 nByte;
1471714687
1471814688
memset(&e, 0, sizeof(e));
1471914689
p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
1472014690
if( p==0 ) return;
1472114691
@@ -24161,28 +24131,28 @@
2416124131
u8 autoExplain; /* Automatically turn on .explain mode */
2416224132
u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
2416324133
u8 autoEQPtrace; /* autoEQP is in trace mode */
2416424134
u8 scanstatsOn; /* True to display scan stats before each finalize */
2416524135
u8 bAutoScreenWidth; /* Using the TTY to determine screen width */
24166
- u8 mFlags; /* MFLG_ECHO and/or MFLG_CRLF */
24136
+ u8 mFlags; /* MFLG_ECHO, MFLG_CRLF, etc. */
2416724137
u8 eMode; /* One of the MODE_ values */
2416824138
sqlite3_qrf_spec spec; /* Spec to be passed into QRF */
2416924139
} Mode;
2417024140
2417124141
/* Flags for Mode.mFlags */
2417224142
#define MFLG_ECHO 0x01 /* Echo inputs to output */
2417324143
#define MFLG_CRLF 0x02 /* Use CR/LF output line endings */
24144
+#define MFLG_HDR 0x04 /* .header used to change headers on/off */
2417424145
2417524146
2417624147
/*
2417724148
** State information about the database connection is contained in an
2417824149
** instance of the following structure.
2417924150
*/
2418024151
typedef struct ShellState ShellState;
2418124152
struct ShellState {
2418224153
sqlite3 *db; /* The database */
24183
- int iCompat; /* Compatibility date YYYYMMDD */
2418424154
u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
2418524155
u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
2418624156
u8 nEqpLevel; /* Depth of the EQP output graph */
2418724157
u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
2418824158
u8 bSafeMode; /* True to prohibit unsafe operations */
@@ -24190,11 +24160,14 @@
2419024160
u8 eRestoreState; /* See comments above doAutoDetectRestore() */
2419124161
unsigned statsOn; /* True to display memory stats before each finalize */
2419224162
unsigned mEqpLines; /* Mask of vertical lines in the EQP output graph */
2419324163
u8 nPopOutput; /* Revert .output settings when reaching zero */
2419424164
u8 nPopMode; /* Revert .mode settings when reaching zero */
24165
+ u8 enableTimer; /* Enable the timer. 2: permanently 1: only once */
2419524166
int inputNesting; /* Track nesting level of .read and other redirects */
24167
+ double prevTimer; /* Last reported timer value */
24168
+ double tmProgress; /* --timeout option for .progress */
2419624169
i64 lineno; /* Line number of last line read from in */
2419724170
const char *zInFile; /* Name of the input file */
2419824171
int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
2419924172
FILE *in; /* Read commands from this stream */
2420024173
FILE *out; /* Write results here */
@@ -24286,10 +24259,11 @@
2428624259
#define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
2428724260
#define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progress
2428824261
** callback limit is reached, and for each
2428924262
** top-level SQL statement */
2429024263
#define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
24264
+#define SHELL_PROGRESS_TMOUT 0x08 /* Stop after tmProgress seconds */
2429124265
2429224266
/* Names of values for Mode.spec.eEsc and Mode.spec.eText
2429324267
*/
2429424268
static const char *qrfEscNames[] = { "auto", "off", "ascii", "symbol" };
2429524269
static const char *qrfQuoteNames[] =
@@ -24447,10 +24421,181 @@
2444724421
** Limit input nesting via .read or any other input redirect.
2444824422
** It's not too expensive, so a generous allowance can be made.
2444924423
*/
2445024424
#define MAX_INPUT_NESTING 25
2445124425
24426
+/************************* BEGIN PERFORMANCE TIMER *****************************/
24427
+#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
24428
+#include <sys/time.h>
24429
+#include <sys/resource.h>
24430
+/* VxWorks does not support getrusage() as far as we can determine */
24431
+#if defined(_WRS_KERNEL) || defined(__RTP__)
24432
+struct rusage {
24433
+ struct timeval ru_utime; /* user CPU time used */
24434
+ struct timeval ru_stime; /* system CPU time used */
24435
+};
24436
+#define getrusage(A,B) memset(B,0,sizeof(*B))
24437
+#endif
24438
+
24439
+/* Saved resource information for the beginning of an operation */
24440
+static struct rusage sBegin; /* CPU time at start */
24441
+static sqlite3_int64 iBegin; /* Wall-clock time at start */
24442
+
24443
+/*
24444
+** Begin timing an operation
24445
+*/
24446
+static void beginTimer(ShellState *p){
24447
+ if( p->enableTimer || (p->flgProgress & SHELL_PROGRESS_TMOUT)!=0 ){
24448
+ getrusage(RUSAGE_SELF, &sBegin);
24449
+ iBegin = timeOfDay();
24450
+ }
24451
+}
24452
+
24453
+/* Return the difference of two time_structs in seconds */
24454
+static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
24455
+ return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
24456
+ (double)(pEnd->tv_sec - pStart->tv_sec);
24457
+}
24458
+
24459
+/* Return the time since the start of the timer in
24460
+** seconds. */
24461
+static double elapseTime(ShellState *NotUsed){
24462
+ (void)NotUsed;
24463
+ if( iBegin==0 ) return 0.0;
24464
+ return (timeOfDay() - iBegin)*0.000001;
24465
+}
24466
+
24467
+/*
24468
+** Print the timing results.
24469
+*/
24470
+static void endTimer(ShellState *p){
24471
+ if( p->enableTimer ){
24472
+ sqlite3_int64 iEnd = timeOfDay();
24473
+ struct rusage sEnd;
24474
+ getrusage(RUSAGE_SELF, &sEnd);
24475
+ p->prevTimer = (iEnd - iBegin)*0.000001;
24476
+ cli_printf(p->out, "Run Time: real %.6f user %.6f sys %.6f\n",
24477
+ p->prevTimer,
24478
+ timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
24479
+ timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
24480
+ if( p->enableTimer==1 ) p->enableTimer = 0;
24481
+ iBegin = 0;
24482
+ }
24483
+}
24484
+
24485
+#define BEGIN_TIMER(X) beginTimer(X)
24486
+#define END_TIMER(X) endTimer(X)
24487
+#define ELAPSE_TIME(X) elapseTime(X)
24488
+#define HAS_TIMER 1
24489
+
24490
+#elif (defined(_WIN32) || defined(WIN32))
24491
+
24492
+/* Saved resource information for the beginning of an operation */
24493
+static HANDLE hProcess;
24494
+static FILETIME ftKernelBegin;
24495
+static FILETIME ftUserBegin;
24496
+static sqlite3_int64 ftWallBegin;
24497
+typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
24498
+ LPFILETIME, LPFILETIME);
24499
+static GETPROCTIMES getProcessTimesAddr = NULL;
24500
+
24501
+/*
24502
+** Check to see if we have timer support. Return 1 if necessary
24503
+** support found (or found previously).
24504
+*/
24505
+static int hasTimer(void){
24506
+ if( getProcessTimesAddr ){
24507
+ return 1;
24508
+ } else {
24509
+ /* GetProcessTimes() isn't supported in WIN95 and some other Windows
24510
+ ** versions. See if the version we are running on has it, and if it
24511
+ ** does, save off a pointer to it and the current process handle.
24512
+ */
24513
+ hProcess = GetCurrentProcess();
24514
+ if( hProcess ){
24515
+ HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
24516
+ if( NULL != hinstLib ){
24517
+ getProcessTimesAddr =
24518
+ (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
24519
+ if( NULL != getProcessTimesAddr ){
24520
+ return 1;
24521
+ }
24522
+ FreeLibrary(hinstLib);
24523
+ }
24524
+ }
24525
+ }
24526
+ return 0;
24527
+}
24528
+
24529
+/*
24530
+** Begin timing an operation
24531
+*/
24532
+static void beginTimer(ShellState *p){
24533
+ if( (p->enableTimer || (p->flgProgress & SHELL_PROGRESS_TMOUT)!=0)
24534
+ && getProcessTimesAddr
24535
+ ){
24536
+ FILETIME ftCreation, ftExit;
24537
+ getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
24538
+ &ftKernelBegin,&ftUserBegin);
24539
+ ftWallBegin = timeOfDay();
24540
+ }
24541
+}
24542
+
24543
+/* Return the difference of two FILETIME structs in seconds */
24544
+static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
24545
+ sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
24546
+ sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
24547
+ return (double) ((i64End - i64Start) / 10000000.0);
24548
+}
24549
+
24550
+/* Return the time since the start of the timer in
24551
+** seconds. */
24552
+static double elapseTime(ShellState *NotUsed){
24553
+ (void)NotUsed;
24554
+ if( ftWallBegin==0 ) return 0.0;
24555
+ return (timeOfDay() - ftWallBegin)*0.000001;
24556
+}
24557
+
24558
+/*
24559
+** Print the timing results.
24560
+*/
24561
+static void endTimer(ShellState *p){
24562
+ if( p->enableTimer && getProcessTimesAddr){
24563
+ FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
24564
+ sqlite3_int64 ftWallEnd = timeOfDay();
24565
+ getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
24566
+ p->prevTimer = (ftWallEnd - ftWallBegin)*0.000001;
24567
+#ifdef _WIN64
24568
+ /* microsecond precision on 64-bit windows */
24569
+ cli_printf(p->out, "Run Time: real %.6f user %f sys %f\n",
24570
+ p->prevTimer,
24571
+ timeDiff(&ftUserBegin, &ftUserEnd),
24572
+ timeDiff(&ftKernelBegin, &ftKernelEnd));
24573
+#else
24574
+ /* millisecond precisino on 32-bit windows */
24575
+ cli_printf(p->out, "Run Time: real %.3f user %.3f sys %.3f\n",
24576
+ p->prevTimer,
24577
+ timeDiff(&ftUserBegin, &ftUserEnd),
24578
+ timeDiff(&ftKernelBegin, &ftKernelEnd));
24579
+#endif
24580
+ if( p->enableTimer==1 ) p->enableTimer = 0;
24581
+ ftWallBegin = 0;
24582
+ }
24583
+}
24584
+
24585
+#define BEGIN_TIMER(X) beginTimer(X)
24586
+#define ELAPSE_TIME(X) elapseTime(X)
24587
+#define END_TIMER(X) endTimer(X)
24588
+#define HAS_TIMER hasTimer()
24589
+
24590
+#else
24591
+#define BEGIN_TIMER(X) /* no-op */
24592
+#define ELAPSE_TIME(X) 0.0
24593
+#define END_TIMER(X) /*no-op*/
24594
+#define HAS_TIMER 0
24595
+#endif
24596
+/************************* END PERFORMANCE TIMER ******************************/
2445224597
2445324598
/*
2445424599
** Clear a display mode, freeing any allocated memory that it
2445524600
** contains.
2445624601
*/
@@ -24534,11 +24679,13 @@
2453424679
if( pI->eCSep ) modeSetStr(&pM->spec.zColumnSep, aModeStr[pI->eCSep]);
2453524680
if( pI->eRSep ) modeSetStr(&pM->spec.zRowSep, aModeStr[pI->eRSep]);
2453624681
if( pI->eNull ) modeSetStr(&pM->spec.zNull, aModeStr[pI->eNull]);
2453724682
pM->spec.eText = pI->eText;
2453824683
pM->spec.eBlob = pI->eBlob;
24539
- pM->spec.bTitles = pI->bHdr;
24684
+ if( (pM->mFlags & MFLG_HDR)==0 ){
24685
+ pM->spec.bTitles = pI->bHdr;
24686
+ }
2454024687
pM->spec.eTitle = pI->eHdr;
2454124688
if( pI->mFlg & 0x01 ){
2454224689
pM->spec.bBorder = QRF_No;
2454324690
}else{
2454424691
pM->spec.bBorder = QRF_Auto;
@@ -24570,18 +24717,17 @@
2457024717
p->mode.mFlags = mFlags;
2457124718
}
2457224719
}
2457324720
2457424721
/*
24575
-** Set the mode to the default according to p->iCompat. It assumed
24576
-** that the mode has already been freed and zeroed prior to calling
24577
-** this routine.
24722
+** Set the mode to the default. It assumed that the mode has
24723
+** already been freed and zeroed prior to calling this routine.
2457824724
*/
2457924725
static void modeDefault(ShellState *p){
2458024726
p->mode.spec.iVersion = 1;
2458124727
p->mode.autoExplain = 1;
24582
- if( p->iCompat>=20251115 && (stdin_is_interactive || stdout_is_console) ){
24728
+ if( stdin_is_interactive || stdout_is_console ){
2458324729
modeChange(p, MODE_TTY);
2458424730
}else{
2458524731
modeChange(p, MODE_BATCH);
2458624732
}
2458724733
}
@@ -25371,10 +25517,17 @@
2537125517
** Progress handler callback.
2537225518
*/
2537325519
static int progress_handler(void *pClientData) {
2537425520
ShellState *p = (ShellState*)pClientData;
2537525521
p->nProgress++;
25522
+ if( (p->flgProgress & SHELL_PROGRESS_TMOUT)!=0
25523
+ && ELAPSE_TIME(p)>=p->tmProgress
25524
+ ){
25525
+ cli_printf(p->out, "Progress timeout after %.6f seconds\n",
25526
+ ELAPSE_TIME(p));
25527
+ return 1;
25528
+ }
2537625529
if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2537725530
cli_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
2537825531
if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2537925532
if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2538025533
return 1;
@@ -25908,10 +26061,12 @@
2590826061
char *zBuf = sqlite3_malloc64( szVar-5 );
2590926062
if( zBuf ){
2591026063
memcpy(zBuf, &zVar[6], szVar-5);
2591126064
sqlite3_bind_text64(pStmt, i, zBuf, szVar-6, sqlite3_free, SQLITE_UTF8);
2591226065
}
26066
+ }else if( strcmp(zVar, "$TIMER")==0 ){
26067
+ sqlite3_bind_double(pStmt, i, pArg->prevTimer);
2591326068
#ifdef SQLITE_ENABLE_CARRAY
2591426069
}else if( strncmp(zVar, "$carray_", 8)==0 ){
2591526070
static char *azColorNames[] = {
2591626071
"azure", "black", "blue", "brown", "cyan", "fuchsia", "gold",
2591726072
"gray", "green", "indigo", "khaki", "lime", "magenta", "maroon",
@@ -26167,27 +26322,36 @@
2616726322
pArg->pStmt = pStmt;
2616826323
}
2616926324
2617026325
/* Show the EXPLAIN QUERY PLAN if .eqp is on */
2617126326
isExplain = sqlite3_stmt_isexplain(pStmt);
26172
- if( pArg && pArg->mode.autoEQP && isExplain==0 ){
26327
+ if( pArg && pArg->mode.autoEQP && isExplain==0 && pArg->dot.nArg==0 ){
2617326328
int triggerEQP = 0;
26329
+ u8 savedEnableTimer = pArg->enableTimer;
26330
+ pArg->enableTimer = 0;
2617426331
disable_debug_trace_modes();
2617526332
sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
2617626333
if( pArg->mode.autoEQP>=AUTOEQP_trigger ){
2617726334
sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
2617826335
}
2617926336
sqlite3_reset(pStmt);
2618026337
spec.eStyle = QRF_STYLE_Auto;
26181
- sqlite3_stmt_explain(pStmt, 2-(pArg->mode.autoEQP>=AUTOEQP_full));
26338
+ sqlite3_stmt_explain(pStmt, 2);
2618226339
sqlite3_format_query_result(pStmt, &spec, 0);
26340
+ if( pArg->mode.autoEQP>=AUTOEQP_full ){
26341
+ sqlite3_reset(pStmt);
26342
+ sqlite3_stmt_explain(pStmt, 1);
26343
+ sqlite3_format_query_result(pStmt, &spec, 0);
26344
+ }
26345
+
2618326346
if( pArg->mode.autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
2618426347
sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
2618526348
}
2618626349
sqlite3_reset(pStmt);
2618726350
sqlite3_stmt_explain(pStmt, 0);
2618826351
restore_debug_trace_modes();
26352
+ pArg->enableTimer = savedEnableTimer;
2618926353
}
2619026354
2619126355
bind_prepared_stmt(pArg, pStmt);
2619226356
if( isExplain && pArg->mode.autoExplain ){
2619326357
spec.eStyle = isExplain==1 ? QRF_STYLE_Explain : QRF_STYLE_Eqp;
@@ -26604,12 +26768,12 @@
2660426768
".bail on|off Stop after hitting an error. Default OFF",
2660526769
#ifndef SQLITE_SHELL_FIDDLE
2660626770
".cd DIRECTORY Change the working directory to DIRECTORY",
2660726771
#endif
2660826772
".changes on|off Show number of rows changed by SQL",
26773
+ ".check OPTIONS ... Verify the results of a .testcase",
2660926774
#ifndef SQLITE_SHELL_FIDDLE
26610
- ".check GLOB Fail if output since .testcase does not match",
2661126775
".clone NEWDB Clone data into NEWDB from the existing database",
2661226776
#endif
2661326777
".connection [close] [#] Open or close an auxiliary database connection",
2661426778
".crlf ?on|off? Whether or not to use \\r\\n line endings",
2661526779
".databases List names and files of attached databases",
@@ -26721,10 +26885,11 @@
2672126885
".progress N Invoke progress handler after every N opcodes",
2672226886
" --limit N Interrupt after N progress callbacks",
2672326887
" --once Do no more than one progress interrupt",
2672426888
" --quiet|-q No output except at interrupts",
2672526889
" --reset Reset the count for each input and interrupt",
26890
+ " --timeout S Halt after running for S seconds",
2672626891
#endif
2672726892
".prompt MAIN CONTINUE Replace the standard prompts",
2672826893
#ifndef SQLITE_SHELL_FIDDLE
2672926894
".quit Stop interpreting input stream, exit if primary.",
2673026895
".read FILE Read input from FILE or command output",
@@ -26785,17 +26950,15 @@
2678526950
" vmstep Show the virtual machine step count only",
2678626951
#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
2678726952
".system CMD ARGS... Run CMD ARGS... in a system shell",
2678826953
#endif
2678926954
".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
26790
-#ifndef SQLITE_SHELL_FIDDLE
26791
- ",testcase NAME Begin redirecting output to 'testcase-out.txt'",
26792
-#endif
26955
+ ".testcase NAME Begin a test case.",
2679326956
",testctrl CMD ... Run various sqlite3_test_control() operations",
2679426957
" Run \".testctrl\" with no arguments for details",
2679526958
".timeout MS Try opening locked tables for MS milliseconds",
26796
- ".timer on|off Turn SQL timer on or off",
26959
+ ".timer on|off|once Turn SQL timer on or off.",
2679726960
#ifndef SQLITE_OMIT_TRACE
2679826961
".trace ?OPTIONS? Output each SQL statement as it is run",
2679926962
" FILE Send output to FILE",
2680026963
" stdout Send output to stdout",
2680126964
" stderr Send output to stderr",
@@ -26836,19 +26999,33 @@
2683626999
"USAGE: .import [OPTIONS] FILE TABLE\n"
2683727000
"\n"
2683827001
"Import CSV or similar text from FILE into TABLE. If TABLE does\n"
2683927002
"not exist, it is created using the first row of FILE as the column\n"
2684027003
"names. If FILE begins with \"|\" then it is a command that is run\n"
26841
-"and the output from the command is used as the input data.\n"
27004
+"and the output from the command is used as the input data. If\n"
27005
+"FILE begins with \"<<\" followed by a label, then content is read from\n"
27006
+"the script until the first line that matches the label.\n"
27007
+"\n"
27008
+"The content of FILE is interpreted using RFC-4180 (\"CSV\") quoting\n"
27009
+"rules unless the current mode is \"ascii\" or \"tabs\" or unless one\n"
27010
+"the --ascii option is used.\n"
2684227011
"\n"
26843
-"FILE is assumed to be in a CSV format, unless the current mode\n"
26844
-"is \"ascii\" or \"tabs\" or unless one of the options below specify\n"
26845
-"an alternative.\n"
27012
+"The column and row separators must be single ASCII characters. If\n"
27013
+"multiple characters or a Unicode character are specified for the\n"
27014
+"separators, then only the first byte of the separator is used. Except,\n"
27015
+"if the row separator is \\n and the mode is not --ascii, then \\r\\n is\n"
27016
+"understood as a row separator too.\n"
2684627017
"\n"
2684727018
"Options:\n"
26848
-" --ascii Use \\037 and \\036 as column and row separators on input\n"
27019
+" --ascii Do not use RFC-4180 quoting. Use \\037 and \\036\n"
27020
+" as column and row separators on input, unless other\n"
27021
+" delimiters are specified using --colsep and/or --rowsep\n"
27022
+" --colsep CHAR Use CHAR as the column separator.\n"
2684927023
" --csv Input is standard RFC-4180 CSV.\n"
27024
+" --esc CHAR Use CHAR as an escape character in unquoted CSV inputs.\n"
27025
+" --qesc CHAR Use CHAR as an escape character in quoted CSV inputs.\n"
27026
+" --rowsep CHAR Use CHAR as the row separator.\n"
2685027027
" --schema S When creating TABLE, put it in schema S\n"
2685127028
" --skip N Ignore the first N rows of input\n"
2685227029
" -v Verbose mode\n"
2685327030
},
2685427031
{ ".mode",
@@ -26930,23 +27107,17 @@
2693027107
" --bom Prepend a byte-order mark to the output\n"
2693127108
" -e Accumulate output in a temporary text file then\n"
2693227109
" launch a text editor when the redirection ends.\n"
2693327110
" --error-prefix X Use X as the left-margin prefix for error messages.\n"
2693427111
" Set to an empty string to restore the default.\n"
26935
-" --glob GLOB Raise an error if the memory buffer does not match\n"
26936
-" the GLOB pattern.\n"
26937
-" --keep Continue using the same \"memory\" buffer. Do not\n"
26938
-" reset it or delete it. Useful in combination with\n"
26939
-" --glob, --not-glob, and/or --verify.\n"
26940
-" ---notglob GLOB Raise an error if the memory buffer does not match\n"
26941
-" the GLOB pattern.\n"
27112
+" --keep Keep redirecting output to its current destination.\n"
27113
+" Use this option in combination with --show or\n"
27114
+" with --error-prefix when you do not want to stop\n"
27115
+" a current redirection.\n"
2694227116
" --plain Use plain text rather than HTML tables with -w\n"
26943
-" --show Write the memory buffer to the screen, for debugging.\n"
26944
-" --verify ENDMARK Read subsequent lines of text until the first line\n"
26945
-" that matches ENDMARK. Discard the ENDMARK. Compare\n"
26946
-" the text against the accumulated output in memory and\n"
26947
-" raise an error if there are any differences.\n"
27117
+" --show Show output text captured by .testcase or by\n"
27118
+" redirecting to \"memory\".\n"
2694827119
" -w Show the output in a web browser. Output is\n"
2694927120
" written into a temporary HTML file until the\n"
2695027121
" redirect ends, then the web browser is launched.\n"
2695127122
" Query results are shown as HTML tables, unless\n"
2695227123
" the --plain is used too.\n"
@@ -26970,10 +27141,39 @@
2697027141
" file in a web browser\n"
2697127142
" -x Show the output in a spreadsheet. Output is\n"
2697227143
" written to a temp file as CSV then the spreadsheet\n"
2697327144
" is launched when\n"
2697427145
},
27146
+ { ".check",
27147
+"USAGE: .check [OPTIONS] PATTERN\n"
27148
+"\n"
27149
+"Verify results of commands since the most recent .testcase command.\n"
27150
+"Restore output to the console, unless --keep is used.\n"
27151
+"\n"
27152
+"If PATTERN starts with \"<<ENDMARK\" then the actual pattern is taken from\n"
27153
+"subsequent lines of text up to the first line that begins with ENDMARK.\n"
27154
+"All pattern lines and the ENDMARK are discarded.\n"
27155
+"\n"
27156
+"Options:\n"
27157
+" --exact Do an exact comparison including leading and\n"
27158
+" trailing whitespace.\n"
27159
+" --glob Treat PATTERN as a GLOB\n"
27160
+" --keep Do not reset the testcase. More .check commands\n"
27161
+" will follow.\n"
27162
+" --notglob Output should not match PATTERN\n"
27163
+" --show Write testcase output to the screen, for debugging.\n"
27164
+ },
27165
+ { ".testcase",
27166
+"USAGE: .testcase [OPTIONS] NAME\n"
27167
+"\n"
27168
+"Start a new test case identified by NAME. All output\n"
27169
+"through the next \".check\" command is captured for comparison. See the\n"
27170
+"\".check\" commandn for additional informatioon.\n"
27171
+"\n"
27172
+"Options:\n"
27173
+" --error-prefix TEXT Change error message prefix text to TEXT\n"
27174
+ },
2697527175
};
2697627176
2697727177
/*
2697827178
** Return a pointer to usage text for zCmd, or NULL if none exists.
2697927179
*/
@@ -27193,10 +27393,56 @@
2719327393
if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
2719427394
}
2719527395
return 1;
2719627396
}
2719727397
#endif
27398
+
27399
+/*
27400
+** Return the size of the named file in bytes. Or return a negative
27401
+** number if the file does not exist.
27402
+*/
27403
+static sqlite3_int64 fileSize(const char *zFile){
27404
+#if defined(_WIN32) || defined(WIN32)
27405
+ struct _stat64 x;
27406
+ if( _stat64(zFile, &x)!=0 ) return -1;
27407
+ return (sqlite3_int64)x.st_size;
27408
+#else
27409
+ struct stat x;
27410
+ if( stat(zFile, &x)!=0 ) return -1;
27411
+ return (sqlite3_int64)x.st_size;
27412
+#endif
27413
+}
27414
+
27415
+/*
27416
+** Return true if zFile is an SQLite database.
27417
+**
27418
+** Algorithm:
27419
+** * If the file does not exist -> return false
27420
+** * If the size of the file is not a multiple of 512 -> return false
27421
+** * If sqlite3_open() fails -> return false
27422
+** * if sqlite3_prepare() or sqlite3_step() fails -> return false
27423
+** * Otherwise -> return true
27424
+*/
27425
+static int isDatabaseFile(const char *zFile, int openFlags){
27426
+ sqlite3 *db = 0;
27427
+ sqlite3_stmt *pStmt = 0;
27428
+ int rc;
27429
+ sqlite3_int64 sz = fileSize(zFile);
27430
+ if( sz<512 || (sz%512)!=0 ) return 0;
27431
+ if( sqlite3_open_v2(zFile, &db, openFlags, 0)==SQLITE_OK
27432
+ && sqlite3_prepare_v2(db,"SELECT count(*) FROM sqlite_schema",-1,&pStmt,0)
27433
+ ==SQLITE_OK
27434
+ && sqlite3_step(pStmt)==SQLITE_ROW
27435
+ ){
27436
+ rc = 1;
27437
+ }else{
27438
+ rc = 0;
27439
+ }
27440
+ sqlite3_finalize(pStmt);
27441
+ sqlite3_close(db);
27442
+ return rc;
27443
+}
2719827444
2719927445
/*
2720027446
** Try to deduce the type of file for zName based on its content. Return
2720127447
** one of the SHELL_OPEN_* constants.
2720227448
**
@@ -27206,24 +27452,16 @@
2720627452
** the type cannot be determined from content.
2720727453
*/
2720827454
int deduceDatabaseType(const char *zName, int dfltZip, int openFlags){
2720927455
FILE *f;
2721027456
size_t n;
27211
- sqlite3 *db = 0;
27212
- sqlite3_stmt *pStmt = 0;
2721327457
int rc = SHELL_OPEN_UNSPEC;
2721427458
char zBuf[100];
2721527459
if( access(zName,0)!=0 ) goto database_type_by_name;
27216
- if( sqlite3_open_v2(zName, &db, openFlags, 0)==SQLITE_OK
27217
- && sqlite3_prepare_v2(db,"SELECT count(*) FROM sqlite_schema",-1,&pStmt,0)
27218
- ==SQLITE_OK
27219
- && sqlite3_step(pStmt)==SQLITE_ROW
27220
- ){
27460
+ if( isDatabaseFile(zName, openFlags) ){
2722127461
rc = SHELL_OPEN_NORMAL;
2722227462
}
27223
- sqlite3_finalize(pStmt);
27224
- sqlite3_close(db);
2722527463
if( rc==SHELL_OPEN_NORMAL ) return SHELL_OPEN_NORMAL;
2722627464
f = sqlite3_fopen(zName, "rb");
2722727465
if( f==0 ) goto database_type_by_name;
2722827466
n = fread(zBuf, 16, 1, f);
2722927467
if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
@@ -27253,10 +27491,39 @@
2725327491
}else{
2725427492
rc = SHELL_OPEN_NORMAL;
2725527493
}
2725627494
return rc;
2725727495
}
27496
+
27497
+/*
27498
+** If the text in z[] is the name of a readable file and that file appears
27499
+** to contain SQL text and/or dot-commands, then return true. If z[] is
27500
+** not a file, or if the file is unreadable, or if the file is a database
27501
+** or anything else that is not SQL text and dot-commands, then return false.
27502
+**
27503
+** If the bLeaveUninit flag is set, then be sure to leave SQLite in an
27504
+** uninitialized state. This means invoking sqlite3_shutdown() after any
27505
+** SQLite API is used.
27506
+**
27507
+** Some amount of guesswork is involved in this decision.
27508
+*/
27509
+static int isScriptFile(const char *z, int bLeaveUninit){
27510
+ sqlite3_int64 sz = fileSize(z);
27511
+ if( sz<=0 ) return 0;
27512
+ if( (sz%512)==0 ){
27513
+ int rc;
27514
+ sqlite3_initialize();
27515
+ rc = isDatabaseFile(z, SQLITE_OPEN_READONLY);
27516
+ if( bLeaveUninit ){
27517
+ sqlite3_shutdown();
27518
+ }
27519
+ if( rc ) return 0; /* Is a database */
27520
+ }
27521
+ if( sqlite3_strlike("%.sql",z,0)==0 ) return 1;
27522
+ if( sqlite3_strlike("%.txt",z,0)==0 ) return 1;
27523
+ return 0;
27524
+}
2725827525
2725927526
#ifndef SQLITE_OMIT_DESERIALIZE
2726027527
/*
2726127528
** Reconstruct an in-memory database using the output from the "dbtotxt"
2726227529
** program. Read content from the file in p->aAuxDb[].zDbFilename.
@@ -27899,20 +28166,24 @@
2789928166
typedef struct ImportCtx ImportCtx;
2790028167
struct ImportCtx {
2790128168
const char *zFile; /* Name of the input file */
2790228169
FILE *in; /* Read the CSV text from this input stream */
2790328170
int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */
28171
+ char *zIn; /* Input text */
2790428172
char *z; /* Accumulated text for a field */
28173
+ i64 nUsed; /* Bytes of zIn[] used so far */
2790528174
i64 n; /* Number of bytes in z */
2790628175
i64 nAlloc; /* Space allocated for z[] */
2790728176
int nLine; /* Current line number */
2790828177
int nRow; /* Number of rows imported */
2790928178
int nErr; /* Number of errors encountered */
2791028179
int bNotFirst; /* True if one or more bytes already read */
2791128180
int cTerm; /* Character that terminated the most recent field */
2791228181
int cColSep; /* The column separator character. (Usually ",") */
2791328182
int cRowSep; /* The row separator character. (Usually "\n") */
28183
+ int cQEscape; /* Escape character with "...". 0 for none */
28184
+ int cUQEscape; /* Escape character not with "...". 0 for none */
2791428185
};
2791528186
2791628187
/* Clean up resourced used by an ImportCtx */
2791728188
static void import_cleanup(ImportCtx *p){
2791828189
if( p->in!=0 && p->xCloser!=0 ){
@@ -27919,13 +28190,32 @@
2791928190
p->xCloser(p->in);
2792028191
p->in = 0;
2792128192
}
2792228193
sqlite3_free(p->z);
2792328194
p->z = 0;
28195
+ if( p->zIn ){
28196
+ sqlite3_free(p->zIn);
28197
+ p->zIn = 0;
28198
+ }
2792428199
}
2792528200
27926
-/* Append a single byte to z[] */
28201
+/* Read a single character of the .import input text. Return EOF
28202
+** at end-of-file.
28203
+*/
28204
+static int import_getc(ImportCtx *p){
28205
+ if( p->in ){
28206
+ return fgetc(p->in);
28207
+ }else if( p->zIn && p->zIn[p->nUsed]!=0 ){
28208
+ return p->zIn[p->nUsed++];
28209
+ }else{
28210
+ return EOF;
28211
+ }
28212
+}
28213
+
28214
+/* Append a single byte to the field value begin constructed
28215
+** in the p->z[] buffer
28216
+*/
2792728217
static void import_append_char(ImportCtx *p, int c){
2792828218
if( p->n+1>=p->nAlloc ){
2792928219
p->nAlloc += p->nAlloc + 100;
2793028220
p->z = sqlite3_realloc64(p->z, p->nAlloc);
2793128221
shell_check_oom(p->z);
@@ -27937,12 +28227,12 @@
2793728227
** with the option of having a separator other than ",".
2793828228
**
2793928229
** + Input comes from p->in.
2794028230
** + Store results in p->z of length p->n. Space to hold p->z comes
2794128231
** from sqlite3_malloc64().
27942
-** + Use p->cSep as the column separator. The default is ",".
27943
-** + Use p->rSep as the row separator. The default is "\n".
28232
+** + Use p->cColSep as the column separator. The default is ",".
28233
+** + Use p->cRowSep as the row separator. The default is "\n".
2794428234
** + Keep track of the line number in p->nLine.
2794528235
** + Store the character that terminates the field in p->cTerm. Store
2794628236
** EOF on end-of-file.
2794728237
** + Report syntax errors on stderr
2794828238
*/
@@ -27949,23 +28239,30 @@
2794928239
static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
2795028240
int c;
2795128241
int cSep = (u8)p->cColSep;
2795228242
int rSep = (u8)p->cRowSep;
2795328243
p->n = 0;
27954
- c = fgetc(p->in);
28244
+ c = import_getc(p);
2795528245
if( c==EOF || seenInterrupt ){
2795628246
p->cTerm = EOF;
2795728247
return 0;
2795828248
}
2795928249
if( c=='"' ){
2796028250
int pc, ppc;
2796128251
int startLine = p->nLine;
2796228252
int cQuote = c;
28253
+ int cEsc = (u8)p->cQEscape;
2796328254
pc = ppc = 0;
2796428255
while( 1 ){
27965
- c = fgetc(p->in);
28256
+ c = import_getc(p);
2796628257
if( c==rSep ) p->nLine++;
28258
+ if( c==cEsc && cEsc!=0 ){
28259
+ c = import_getc(p);
28260
+ import_append_char(p, c);
28261
+ ppc = pc = 0;
28262
+ continue;
28263
+ }
2796728264
if( c==cQuote ){
2796828265
if( pc==cQuote ){
2796928266
pc = 0;
2797028267
continue;
2797128268
}
@@ -27979,11 +28276,11 @@
2797928276
p->cTerm = c;
2798028277
break;
2798128278
}
2798228279
if( pc==cQuote && c!='\r' ){
2798328280
cli_printf(stderr,"%s:%d: unescaped %c character\n",
27984
- p->zFile, p->nLine, cQuote);
28281
+ p->zFile, p->nLine, cQuote);
2798528282
}
2798628283
if( c==EOF ){
2798728284
cli_printf(stderr,"%s:%d: unterminated %c-quoted field\n",
2798828285
p->zFile, startLine, cQuote);
2798928286
p->cTerm = c;
@@ -27994,26 +28291,28 @@
2799428291
pc = c;
2799528292
}
2799628293
}else{
2799728294
/* If this is the first field being parsed and it begins with the
2799828295
** UTF-8 BOM (0xEF BB BF) then skip the BOM */
28296
+ int cEsc = p->cUQEscape;
2799928297
if( (c&0xff)==0xef && p->bNotFirst==0 ){
2800028298
import_append_char(p, c);
28001
- c = fgetc(p->in);
28299
+ c = import_getc(p);
2800228300
if( (c&0xff)==0xbb ){
2800328301
import_append_char(p, c);
28004
- c = fgetc(p->in);
28302
+ c = import_getc(p);
2800528303
if( (c&0xff)==0xbf ){
2800628304
p->bNotFirst = 1;
2800728305
p->n = 0;
2800828306
return csv_read_one_field(p);
2800928307
}
2801028308
}
2801128309
}
2801228310
while( c!=EOF && c!=cSep && c!=rSep ){
28311
+ if( c==cEsc && cEsc!=0 ) c = import_getc(p);
2801328312
import_append_char(p, c);
28014
- c = fgetc(p->in);
28313
+ c = import_getc(p);
2801528314
}
2801628315
if( c==rSep ){
2801728316
p->nLine++;
2801828317
if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
2801928318
}
@@ -28027,12 +28326,12 @@
2802728326
/* Read a single field of ASCII delimited text.
2802828327
**
2802928328
** + Input comes from p->in.
2803028329
** + Store results in p->z of length p->n. Space to hold p->z comes
2803128330
** from sqlite3_malloc64().
28032
-** + Use p->cSep as the column separator. The default is "\x1F".
28033
-** + Use p->rSep as the row separator. The default is "\x1E".
28331
+** + Use p->cColSep as the column separator. The default is "\x1F".
28332
+** + Use p->cRowSep as the row separator. The default is "\x1E".
2803428333
** + Keep track of the row number in p->nLine.
2803528334
** + Store the character that terminates the field in p->cTerm. Store
2803628335
** EOF on end-of-file.
2803728336
** + Report syntax errors on stderr
2803828337
*/
@@ -28039,18 +28338,18 @@
2803928338
static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
2804028339
int c;
2804128340
int cSep = (u8)p->cColSep;
2804228341
int rSep = (u8)p->cRowSep;
2804328342
p->n = 0;
28044
- c = fgetc(p->in);
28343
+ c = import_getc(p);
2804528344
if( c==EOF || seenInterrupt ){
2804628345
p->cTerm = EOF;
2804728346
return 0;
2804828347
}
2804928348
while( c!=EOF && c!=cSep && c!=rSep ){
2805028349
import_append_char(p, c);
28051
- c = fgetc(p->in);
28350
+ c = import_getc(p);
2805228351
}
2805328352
if( c==rSep ){
2805428353
p->nLine++;
2805528354
}
2805628355
p->cTerm = c;
@@ -30151,11 +30450,11 @@
3015130450
;
3015230451
static const char * const zCollectVar = "\
3015330452
SELECT\
3015430453
'('||x'0a'\
3015530454
|| group_concat(\
30156
- cname||' TEXT',\
30455
+ cname||' ANY',\
3015730456
','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
3015830457
||')' AS ColsSpec \
3015930458
FROM (\
3016030459
SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
3016130460
FROM ColNames ORDER BY cpos\
@@ -30351,19 +30650,33 @@
3035130650
** USAGE: .import [OPTIONS] FILE TABLE
3035230651
**
3035330652
** Import CSV or similar text from FILE into TABLE. If TABLE does
3035430653
** not exist, it is created using the first row of FILE as the column
3035530654
** names. If FILE begins with "|" then it is a command that is run
30356
-** and the output from the command is used as the input data.
30655
+** and the output from the command is used as the input data. If
30656
+** FILE begins with "<<" followed by a label, then content is read from
30657
+** the script until the first line that matches the label.
30658
+**
30659
+** The content of FILE is interpreted using RFC-4180 ("CSV") quoting
30660
+** rules unless the current mode is "ascii" or "tabs" or unless one
30661
+** the --ascii option is used.
3035730662
**
30358
-** FILE is assumed to be in a CSV format, unless the current mode
30359
-** is "ascii" or "tabs" or unless one of the options below specify
30360
-** an alternative.
30663
+** The column and row separators must be single ASCII characters. If
30664
+** multiple characters or a Unicode character are specified for the
30665
+** separators, then only the first byte of the separator is used. Except,
30666
+** if the row separator is \n and the mode is not --ascii, then \r\n is
30667
+** understood as a row separator too.
3036130668
**
3036230669
** Options:
30363
-** --ascii Use \037 and \036 as column and row separators on input
30670
+** --ascii Do not use RFC-4180 quoting. Use \037 and \036
30671
+** as column and row separators on input, unless other
30672
+** delimiters are specified using --colsep and/or --rowsep
30673
+** --colsep CHAR Use CHAR as the column separator.
3036430674
** --csv Input is standard RFC-4180 CSV.
30675
+** --esc CHAR Use CHAR as an escape character in unquoted CSV inputs.
30676
+** --qesc CHAR Use CHAR as an escape character in quoted CSV inputs.
30677
+** --rowsep CHAR Use CHAR as the row separator.
3036530678
** --schema S When creating TABLE, put it in schema S
3036630679
** --skip N Ignore the first N rows of input
3036730680
** -v Verbose mode
3036830681
*/
3036930682
static int dotCmdImport(ShellState *p){
@@ -30375,17 +30688,16 @@
3037530688
sqlite3_stmt *pStmt = NULL; /* A statement */
3037630689
int nCol; /* Number of columns in the table */
3037730690
i64 nByte; /* Number of bytes in an SQL string */
3037830691
int i, j; /* Loop counters */
3037930692
int needCommit; /* True to COMMIT or ROLLBACK at end */
30380
- int nSep; /* Number of bytes in spec.zColumnSep */
3038130693
char *zSql = 0; /* An SQL statement */
3038230694
ImportCtx sCtx; /* Reader context */
3038330695
char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
3038430696
int eVerbose = 0; /* Larger for more console output */
3038530697
i64 nSkip = 0; /* Initial lines to skip */
30386
- int useOutputMode = 1; /* Use output mode to determine separators */
30698
+ i64 iLineOffset = 0; /* Offset to the first line of input */
3038730699
char *zCreate = 0; /* CREATE TABLE statement text */
3038830700
int rc; /* Result code */
3038930701
3039030702
failIfSafeMode(p, "cannot run .import in safe mode");
3039130703
memset(&sCtx, 0, sizeof(sCtx));
@@ -30411,70 +30723,71 @@
3041130723
}else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
3041230724
zSchema = azArg[++i];
3041330725
}else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
3041430726
nSkip = integerValue(azArg[++i]);
3041530727
}else if( cli_strcmp(z,"-ascii")==0 ){
30416
- sCtx.cColSep = SEP_Unit[0];
30417
- sCtx.cRowSep = SEP_Record[0];
30728
+ if( sCtx.cColSep==0 ) sCtx.cColSep = SEP_Unit[0];
30729
+ if( sCtx.cRowSep==0 ) sCtx.cRowSep = SEP_Record[0];
3041830730
xRead = ascii_read_one_field;
30419
- useOutputMode = 0;
3042030731
}else if( cli_strcmp(z,"-csv")==0 ){
30421
- sCtx.cColSep = ',';
30422
- sCtx.cRowSep = '\n';
30732
+ if( sCtx.cColSep==0 ) sCtx.cColSep = ',';
30733
+ if( sCtx.cRowSep==0 ) sCtx.cRowSep = '\n';
3042330734
xRead = csv_read_one_field;
30424
- useOutputMode = 0;
30735
+ }else if( cli_strcmp(z,"-esc")==0 ){
30736
+ sCtx.cUQEscape = azArg[++i][0];
30737
+ }else if( cli_strcmp(z,"-qesc")==0 ){
30738
+ sCtx.cQEscape = azArg[++i][0];
30739
+ }else if( cli_strcmp(z,"-colsep")==0 ){
30740
+ if( i==nArg-1 ){
30741
+ dotCmdError(p, i, "missing argument", 0);
30742
+ return 1;
30743
+ }
30744
+ i++;
30745
+ sCtx.cColSep = azArg[i][0];
30746
+ }else if( cli_strcmp(z,"-rowsep")==0 ){
30747
+ if( i==nArg-1 ){
30748
+ dotCmdError(p, i, "missing argument", 0);
30749
+ return 1;
30750
+ }
30751
+ i++;
30752
+ sCtx.cRowSep = azArg[i][0];
3042530753
}else{
3042630754
dotCmdError(p, i, "unknown option", 0);
3042730755
return 1;
3042830756
}
3042930757
}
3043030758
if( zTable==0 ){
30431
- cli_printf(p->out, "ERROR: missing %s argument\n",
30759
+ dotCmdError(p, nArg, 0, "Missing %s argument\n",
3043230760
zFile==0 ? "FILE" : "TABLE");
3043330761
return 1;
3043430762
}
3043530763
seenInterrupt = 0;
3043630764
open_db(p, 0);
30437
- if( useOutputMode ){
30438
- /* If neither the --csv or --ascii options are specified, then set
30439
- ** the column and row separator characters from the output mode. */
30440
- if( p->mode.spec.zColumnSep==0 ){
30441
- modeSetStr(&p->mode.spec.zColumnSep, ",");
30442
- nSep = 1;
30443
- }else if( (nSep = strlen30(p->mode.spec.zColumnSep))==0 ){
30444
- eputz("Error: non-null column separator required for import\n");
30445
- return 1;
30446
- }
30447
- if( nSep>1 ){
30448
- eputz("Error: multi-character column separators not allowed"
30449
- " for import\n");
30450
- return 1;
30451
- }
30452
- if( p->mode.spec.zRowSep==0 ){
30453
- modeSetStr(&p->mode.spec.zRowSep, "\n");
30454
- nSep = 1;
30455
- }else if( (nSep = strlen30(p->mode.spec.zRowSep))==0 ){
30456
- eputz("Error: non-null row separator required for import\n");
30457
- return 1;
30458
- }
30459
- if( nSep==2 && p->mode.eMode==MODE_Csv
30460
- && cli_strcmp(p->mode.spec.zRowSep,SEP_CrLf)==0
30461
- ){
30462
- /* When importing CSV (only), if the row separator is set to the
30463
- ** default output row separator, change it to the default input
30464
- ** row separator. This avoids having to maintain different input
30465
- ** and output row separators. */
30466
- modeSetStr(&p->mode.spec.zRowSep, SEP_Row);
30467
- nSep = strlen30(p->mode.spec.zRowSep);
30468
- }
30469
- if( nSep>1 ){
30470
- eputz("Error: multi-character row separators not allowed"
30471
- " for import\n");
30472
- return 1;
30473
- }
30474
- sCtx.cColSep = (u8)p->mode.spec.zColumnSep[0];
30475
- sCtx.cRowSep = (u8)p->mode.spec.zRowSep[0];
30765
+ if( sCtx.cColSep==0 ){
30766
+ if( p->mode.spec.zColumnSep && p->mode.spec.zColumnSep[0]!=0 ){
30767
+ sCtx.cColSep = p->mode.spec.zColumnSep[0];
30768
+ }else{
30769
+ sCtx.cColSep = ',';
30770
+ }
30771
+ }
30772
+ if( (sCtx.cColSep & 0x80)!=0 ){
30773
+ eputz("Error: .import column separator must be ASCII\n");
30774
+ return 1;
30775
+ }
30776
+ if( sCtx.cRowSep==0 ){
30777
+ if( p->mode.spec.zRowSep && p->mode.spec.zRowSep[0]!=0 ){
30778
+ sCtx.cRowSep = p->mode.spec.zRowSep[0];
30779
+ }else{
30780
+ sCtx.cRowSep = '\n';
30781
+ }
30782
+ }
30783
+ if( sCtx.cRowSep=='\r' && xRead!=ascii_read_one_field ){
30784
+ sCtx.cRowSep = '\n';
30785
+ }
30786
+ if( (sCtx.cRowSep & 0x80)!=0 ){
30787
+ eputz("Error: .import row separator must be ASCII\n");
30788
+ return 1;
3047630789
}
3047730790
sCtx.zFile = zFile;
3047830791
sCtx.nLine = 1;
3047930792
if( sCtx.zFile[0]=='|' ){
3048030793
#ifdef SQLITE_OMIT_POPEN
@@ -30483,19 +30796,58 @@
3048330796
#else
3048430797
sCtx.in = sqlite3_popen(sCtx.zFile+1, "r");
3048530798
sCtx.zFile = "<pipe>";
3048630799
sCtx.xCloser = pclose;
3048730800
#endif
30801
+ }else if( sCtx.zFile[0]=='<' && sCtx.zFile[1]=='<' && sCtx.zFile[2]!=0 ){
30802
+ /* Input text comes from subsequent lines of script until the zFile
30803
+ ** delimiter */
30804
+ int nEndMark = strlen30(zFile)-2;
30805
+ char *zEndMark = &zFile[2];
30806
+ sqlite3_str *pContent = sqlite3_str_new(p->db);
30807
+ int ckEnd = 1;
30808
+ i64 iStart = p->lineno;
30809
+ char zLine[2000];
30810
+ sCtx.zFile = p->zInFile;
30811
+ sCtx.nLine = p->lineno+1;
30812
+ iLineOffset = p->lineno;
30813
+ while( sqlite3_fgets(zLine,sizeof(zLine),p->in) ){
30814
+ if( ckEnd && cli_strncmp(zLine,zEndMark,nEndMark)==0 ){
30815
+ ckEnd = 2;
30816
+ if( strchr(zLine,'\n') ) p->lineno++;
30817
+ break;
30818
+ }
30819
+ if( strchr(zLine,'\n') ){
30820
+ p->lineno++;
30821
+ ckEnd = 1;
30822
+ }else{
30823
+ ckEnd = 0;
30824
+ }
30825
+ sqlite3_str_appendall(pContent, zLine);
30826
+ }
30827
+ sCtx.zIn = sqlite3_str_finish(pContent);
30828
+ if( sCtx.zIn==0 ){
30829
+ sCtx.zIn = sqlite3_mprintf("");
30830
+ }
30831
+ if( ckEnd<2 ){
30832
+ i64 savedLn = p->lineno;
30833
+ p->lineno = iStart;
30834
+ dotCmdError(p, 0, 0,"Content terminator \"%s\" not found.",zEndMark);
30835
+ p->lineno = savedLn;
30836
+ import_cleanup(&sCtx);
30837
+ return 1;
30838
+ }
3048830839
}else{
3048930840
sCtx.in = sqlite3_fopen(sCtx.zFile, "rb");
3049030841
sCtx.xCloser = fclose;
3049130842
}
30492
- if( sCtx.in==0 ){
30493
- cli_printf(stderr,"Error: cannot open \"%s\"\n", zFile);
30843
+ if( sCtx.in==0 && sCtx.zIn==0 ){
30844
+ dotCmdError(p, 0, 0, "cannot open \"%s\"", zFile);
30845
+ import_cleanup(&sCtx);
3049430846
return 1;
3049530847
}
30496
- if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
30848
+ if( eVerbose>=1 ){
3049730849
char zSep[2];
3049830850
zSep[1] = 0;
3049930851
zSep[0] = sCtx.cColSep;
3050030852
cli_puts("Column separator ", p->out);
3050130853
output_c_string(p->out, zSep);
@@ -30648,10 +31000,14 @@
3064831000
if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){
3064931001
z = "";
3065031002
}
3065131003
sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
3065231004
if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
31005
+ if( i==0 && (strcmp(z,"\n")==0 || strcmp(z,"\r\n")==0) ){
31006
+ /* Ignore trailing \n or \r\n when some other row separator */
31007
+ break;
31008
+ }
3065331009
cli_printf(stderr,"%s:%d: expected %d columns but found %d"
3065431010
" - filling the rest with NULL\n",
3065531011
sCtx.zFile, startLine, nCol, i+1);
3065631012
i += 2;
3065731013
while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
@@ -30671,10 +31027,11 @@
3067131027
rc = sqlite3_reset(pStmt);
3067231028
if( rc!=SQLITE_OK ){
3067331029
cli_printf(stderr,"%s:%d: INSERT failed: %s\n",
3067431030
sCtx.zFile, startLine, sqlite3_errmsg(p->db));
3067531031
sCtx.nErr++;
31032
+ if( bail_on_error ) break;
3067631033
}else{
3067731034
sCtx.nRow++;
3067831035
}
3067931036
}
3068031037
}while( sCtx.cTerm!=EOF );
@@ -30683,13 +31040,13 @@
3068331040
sqlite3_finalize(pStmt);
3068431041
if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
3068531042
if( eVerbose>0 ){
3068631043
cli_printf(p->out,
3068731044
"Added %d rows with %d errors using %d lines of input\n",
30688
- sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
31045
+ sCtx.nRow, sCtx.nErr, sCtx.nLine-1-iLineOffset);
3068931046
}
30690
- return 0;
31047
+ return sCtx.nErr ? 1 : 0;
3069131048
}
3069231049
3069331050
3069431051
/*
3069531052
** This function computes what to show the user about the configured
@@ -31100,10 +31457,11 @@
3110031457
if( k<0 ){
3110131458
dotCmdError(p, i, "bad --titles value","%z", zErr);
3110231459
return 1;
3110331460
}
3110431461
p->mode.spec.bTitles = k>=1 ? QRF_Yes : QRF_No;
31462
+ p->mode.mFlags &= ~MFLG_HDR;
3110531463
p->mode.spec.eTitle = k>1 ? k-1 : aModeInfo[p->mode.eMode].eHdr;
3110631464
chng = 1;
3110731465
}else if( optionMatch(z,"widths") || optionMatch(z,"width") ){
3110831466
int nWidth = 0;
3110931467
short int *aWidth;
@@ -31328,23 +31686,17 @@
3132831686
** --bom Prepend a byte-order mark to the output
3132931687
** -e Accumulate output in a temporary text file then
3133031688
** launch a text editor when the redirection ends.
3133131689
** --error-prefix X Use X as the left-margin prefix for error messages.
3133231690
** Set to an empty string to restore the default.
31333
-** --glob GLOB Raise an error if the memory buffer does not match
31334
-** the GLOB pattern.
31335
-** --keep Continue using the same "memory" buffer. Do not
31336
-** reset it or delete it. Useful in combination with
31337
-** --glob, --not-glob, and/or --verify.
31338
-** ---notglob GLOB Raise an error if the memory buffer does not match
31339
-** the GLOB pattern.
31691
+** --keep Keep redirecting output to its current destination.
31692
+** Use this option in combination with --show or
31693
+** with --error-prefix when you do not want to stop
31694
+** a current redirection.
3134031695
** --plain Use plain text rather than HTML tables with -w
31341
-** --show Write the memory buffer to the screen, for debugging.
31342
-** --verify ENDMARK Read subsequent lines of text until the first line
31343
-** that matches ENDMARK. Discard the ENDMARK. Compare
31344
-** the text against the accumulated output in memory and
31345
-** raise an error if there are any differences.
31696
+** --show Show output text captured by .testcase or by
31697
+** redirecting to "memory".
3134631698
** -w Show the output in a web browser. Output is
3134731699
** written into a temporary HTML file until the
3134831700
** redirect ends, then the web browser is launched.
3134931701
** Query results are shown as HTML tables, unless
3135031702
** the --plain is used too.
@@ -31382,13 +31734,11 @@
3138231734
char *zFile = 0; /* The FILE argument */
3138331735
int i; /* Loop counter */
3138431736
int eMode = 0; /* 0: .outout/.once, 'x'=.excel, 'w'=.www */
3138531737
int bOnce = 0; /* 0: .output, 1: .once, 2: .excel/.www */
3138631738
int bPlain = 0; /* --plain option */
31387
- int bKeep = 0; /* --keep option */
31388
- char *zCheck = 0; /* Argument to --glob, --notglob, --verify */
31389
- int eCheck = 0; /* 1: --glob, 2: --notglob, 3: --verify */
31739
+ int bKeep = 0; /* Keep redirecting */
3139031740
static const char *zBomUtf8 = "\357\273\277";
3139131741
const char *zBom = 0;
3139231742
char c = azArg[0][0];
3139331743
int n = strlen30(azArg[0]);
3139431744
@@ -31410,36 +31760,21 @@
3141031760
zBom = zBomUtf8;
3141131761
}else if( cli_strcmp(z,"-plain")==0 ){
3141231762
bPlain = 1;
3141331763
}else if( c=='o' && z[0]=='1' && z[1]!=0 && z[2]==0
3141431764
&& (z[1]=='x' || z[1]=='e' || z[1]=='w') ){
31415
- if( bKeep || eMode || eCheck ){
31765
+ if( bKeep || eMode ){
3141631766
dotCmdError(p, i, "incompatible with prior options",0);
3141731767
goto dotCmdOutput_error;
3141831768
}
3141931769
eMode = z[1];
31420
- }else if( cli_strcmp(z,"-keep")==0 ){
31421
- bKeep = 1;
3142231770
}else if( cli_strcmp(z,"-show")==0 ){
3142331771
if( cli_output_capture ){
3142431772
sqlite3_fprintf(stdout, "%s", sqlite3_str_value(cli_output_capture));
3142531773
}
31774
+ }else if( cli_strcmp(z,"-keep")==0 ){
3142631775
bKeep = 1;
31427
- }else if( cli_strcmp(z,"-glob")==0
31428
- || cli_strcmp(z,"-notglob")==0
31429
- || cli_strcmp(z,"-verify")==0
31430
- ){
31431
- if( eCheck || eMode ){
31432
- dotCmdError(p, i, "incompatible with prior options",0);
31433
- goto dotCmdOutput_error;
31434
- }
31435
- if( i+1>=nArg ){
31436
- dotCmdError(p, i, "missing argument", 0);
31437
- goto dotCmdOutput_error;
31438
- }
31439
- zCheck = azArg[++i];
31440
- eCheck = z[1]=='g' ? 1 : z[1]=='n' ? 2 : 3;
3144131776
}else if( optionMatch(z,"error-prefix") ){
3144231777
if( i+1>=nArg ){
3144331778
dotCmdError(p, i, "missing argument", 0);
3144431779
return 1;
3144531780
}
@@ -31450,11 +31785,11 @@
3145031785
dotCmdError(p, i, "unknown option", 0);
3145131786
sqlite3_free(zFile);
3145231787
return 1;
3145331788
}
3145431789
}else if( zFile==0 && eMode==0 ){
31455
- if( bKeep || eCheck ){
31790
+ if( bKeep ){
3145631791
dotCmdError(p, i, "incompatible with prior options",0);
3145731792
goto dotCmdOutput_error;
3145831793
}
3145931794
if( cli_strcmp(z, "memory")==0 && bOnce ){
3146031795
dotCmdError(p, 0, "cannot redirect to \"memory\"", 0);
@@ -31486,53 +31821,10 @@
3148631821
if( bOnce ){
3148731822
p->nPopOutput = 2;
3148831823
}else{
3148931824
p->nPopOutput = 0;
3149031825
}
31491
- if( eCheck ){
31492
- char *zTest;
31493
- if( cli_output_capture ){
31494
- zTest = sqlite3_str_value(cli_output_capture);
31495
- }else{
31496
- zTest = "";
31497
- }
31498
- p->nTestRun++;
31499
- if( eCheck==3 ){
31500
- int nCheck = strlen30(zCheck);
31501
- sqlite3_str *pPattern = sqlite3_str_new(p->db);
31502
- char *zPattern;
31503
- sqlite3_int64 iStart = p->lineno;
31504
- char zLine[2000];
31505
- while( sqlite3_fgets(zLine,sizeof(zLine),p->in) ){
31506
- if( strchr(zLine,'\n') ) p->lineno++;
31507
- if( cli_strncmp(zCheck,zLine,nCheck)==0 ) break;
31508
- sqlite3_str_appendall(pPattern, zLine);
31509
- }
31510
- zPattern = sqlite3_str_finish(pPattern);
31511
- if( cli_strcmp(zPattern,zTest)!=0 ){
31512
- sqlite3_fprintf(stderr,
31513
- "%s:%lld: --verify does matches prior output\n",
31514
- p->zInFile, iStart);
31515
- p->nTestErr++;
31516
- }
31517
- sqlite3_free(zPattern);
31518
- }else{
31519
- char *zGlob = sqlite3_mprintf("*%s*", zCheck);
31520
- if( eCheck==1 && sqlite3_strglob(zGlob, zTest)!=0 ){
31521
- sqlite3_fprintf(stderr,
31522
- "%s:%lld: --glob \"%s\" does not match prior output\n",
31523
- p->zInFile, p->lineno, zCheck);
31524
- p->nTestErr++;
31525
- }else if( eCheck==2 && sqlite3_strglob(zGlob, zTest)==0 ){
31526
- sqlite3_fprintf(stderr,
31527
- "%s:%lld: --notglob \"%s\" matches prior output\n",
31528
- p->zInFile, p->lineno, zCheck);
31529
- p->nTestErr++;
31530
- }
31531
- sqlite3_free(zGlob);
31532
- }
31533
- }
3153431826
if( !bKeep ) output_reset(p);
3153531827
#ifndef SQLITE_NOHAVE_SYSTEM
3153631828
if( eMode=='e' || eMode=='x' || eMode=='w' ){
3153731829
p->doXdgOpen = 1;
3153831830
modePush(p);
@@ -31609,10 +31901,199 @@
3160931901
3161031902
dotCmdOutput_error:
3161131903
sqlite3_free(zFile);
3161231904
return 1;
3161331905
}
31906
+
31907
+/*
31908
+** DOT-COMMAND: .check
31909
+** USAGE: .check [OPTIONS] PATTERN
31910
+**
31911
+** Verify results of commands since the most recent .testcase command.
31912
+** Restore output to the console, unless --keep is used.
31913
+**
31914
+** If PATTERN starts with "<<ENDMARK" then the actual pattern is taken from
31915
+** subsequent lines of text up to the first line that begins with ENDMARK.
31916
+** All pattern lines and the ENDMARK are discarded.
31917
+**
31918
+** Options:
31919
+** --exact Do an exact comparison including leading and
31920
+** trailing whitespace.
31921
+** --glob Treat PATTERN as a GLOB
31922
+** --keep Do not reset the testcase. More .check commands
31923
+** will follow.
31924
+** --notglob Output should not match PATTERN
31925
+** --show Write testcase output to the screen, for debugging.
31926
+*/
31927
+static int dotCmdCheck(ShellState *p){
31928
+ int nArg = p->dot.nArg; /* Number of arguments */
31929
+ char **azArg = p->dot.azArg; /* Text of the arguments */
31930
+ int i; /* Loop counter */
31931
+ int k; /* Result of pickStr() */
31932
+ char *zTest; /* Textcase result */
31933
+ int bKeep = 0; /* --keep option */
31934
+ char *zCheck = 0; /* PATTERN argument */
31935
+ char *zPattern = 0; /* Actual test pattern */
31936
+ int eCheck = 0; /* 1: --glob, 2: --notglob, 3: --exact */
31937
+ int isOk; /* True if results are OK */
31938
+ sqlite3_int64 iStart = p->lineno; /* Line number of .check statement */
31939
+
31940
+ if( p->zTestcase[0]==0 ){
31941
+ dotCmdError(p, 0, "no .testcase is active", 0);
31942
+ return 1;
31943
+ }
31944
+ for(i=1; i<nArg; i++){
31945
+ char *z = azArg[i];
31946
+ if( z[0]=='-' && z[1]=='-' && z[2]!=0 ) z++;
31947
+ if( cli_strcmp(z,"-keep")==0 ){
31948
+ bKeep = 1;
31949
+ }else if( cli_strcmp(z,"-show")==0 ){
31950
+ if( cli_output_capture ){
31951
+ sqlite3_fprintf(stdout, "%s", sqlite3_str_value(cli_output_capture));
31952
+ }
31953
+ bKeep = 1;
31954
+ }else if( z[0]=='-'
31955
+ && (k = pickStr(&z[1],0,"glob","notglob","exact",""))>=0
31956
+ ){
31957
+ if( eCheck && eCheck!=k+1 ){
31958
+ dotCmdError(p, i, "incompatible with prior options",0);
31959
+ return 1;
31960
+ }
31961
+ eCheck = k+1;
31962
+ }else if( zCheck ){
31963
+ dotCmdError(p, i, "unknown option", 0);
31964
+ return 1;
31965
+ }else{
31966
+ zCheck = azArg[i];
31967
+ }
31968
+ }
31969
+ if( zCheck==0 ){
31970
+ dotCmdError(p, 0, "no PATTERN specified", 0);
31971
+ return 1;
31972
+ }
31973
+ if( cli_output_capture && sqlite3_str_length(cli_output_capture) ){
31974
+ zTest = sqlite3_str_value(cli_output_capture);
31975
+ shell_check_oom(zTest);
31976
+ }else{
31977
+ zTest = "";
31978
+ }
31979
+ p->nTestRun++;
31980
+ if( zCheck[0]=='<' && zCheck[1]=='<' && zCheck[2]!=0 ){
31981
+ int nCheck = strlen30(zCheck);
31982
+ sqlite3_str *pPattern = sqlite3_str_new(p->db);
31983
+ char zLine[2000];
31984
+ while( sqlite3_fgets(zLine,sizeof(zLine),p->in) ){
31985
+ if( strchr(zLine,'\n') ) p->lineno++;
31986
+ if( cli_strncmp(&zCheck[2],zLine,nCheck-2)==0 ) break;
31987
+ sqlite3_str_appendall(pPattern, zLine);
31988
+ }
31989
+ zPattern = sqlite3_str_finish(pPattern);
31990
+ if( zPattern==0 ){
31991
+ zPattern = sqlite3_mprintf("");
31992
+ }
31993
+ }else{
31994
+ zPattern = zCheck;
31995
+ }
31996
+ shell_check_oom(zPattern);
31997
+ switch( eCheck ){
31998
+ case 1: {
31999
+ char *zGlob = sqlite3_mprintf("*%s*", zPattern);
32000
+ isOk = testcase_glob(zGlob, zTest)!=0;
32001
+ sqlite3_free(zGlob);
32002
+ break;
32003
+ }
32004
+ case 2: {
32005
+ char *zGlob = sqlite3_mprintf("*%s*", zPattern);
32006
+ isOk = testcase_glob(zGlob, zTest)==0;
32007
+ sqlite3_free(zGlob);
32008
+ break;
32009
+ }
32010
+ case 3: {
32011
+ isOk = cli_strcmp(zTest,zPattern)==0;
32012
+ break;
32013
+ }
32014
+ default: {
32015
+ /* Skip leading and trailing \n and \r on both pattern and test output */
32016
+ const char *z1 = zPattern;
32017
+ const char *z2 = zTest;
32018
+ size_t n1, n2;
32019
+ while( z1[0]=='\n' || z1[0]=='\r' ) z1++;
32020
+ n1 = strlen(z1);
32021
+ while( n1>0 && (z1[n1-1]=='\n' || z1[n1-1]=='\r') ) n1--;
32022
+ while( z2[0]=='\n' || z2[0]=='\r' ) z2++;
32023
+ n2 = strlen(z2);
32024
+ while( n2>0 && (z2[n2-1]=='\n' || z2[n2-1]=='\r') ) n2--;
32025
+ isOk = n1==n2 && memcmp(z1,z2,n1)==0;
32026
+ break;
32027
+ }
32028
+ }
32029
+ if( !isOk ){
32030
+ sqlite3_fprintf(stderr,
32031
+ "%s:%lld: .check failed for testcase %s\n",
32032
+ p->zInFile, iStart, p->zTestcase);
32033
+ p->nTestErr++;
32034
+ sqlite3_fprintf(stderr, "Expected: [%s]\n", zPattern);
32035
+ sqlite3_fprintf(stderr, "Got: [%s]\n", zTest);
32036
+ }
32037
+ if( zPattern!=zCheck ){
32038
+ sqlite3_free(zPattern);
32039
+ }
32040
+ if( !bKeep ){
32041
+ output_reset(p);
32042
+ p->zTestcase[0] = 0;
32043
+ }
32044
+ return 0;
32045
+}
32046
+
32047
+/*
32048
+** DOT-COMMAND: .testcase
32049
+** USAGE: .testcase [OPTIONS] NAME
32050
+**
32051
+** Start a new test case identified by NAME. All output
32052
+** through the next ".check" command is captured for comparison. See the
32053
+** ".check" commandn for additional informatioon.
32054
+**
32055
+** Options:
32056
+** --error-prefix TEXT Change error message prefix text to TEXT
32057
+*/
32058
+static int dotCmdTestcase(ShellState *p){
32059
+ int nArg = p->dot.nArg; /* Number of arguments */
32060
+ char **azArg = p->dot.azArg; /* Text of the arguments */
32061
+ int i; /* Loop counter */
32062
+ const char *zName = 0; /* Testcase name */
32063
+
32064
+ for(i=1; i<nArg; i++){
32065
+ char *z = azArg[i];
32066
+ if( z[0]=='-' && z[1]=='-' && z[2]!=0 ) z++;
32067
+ if( optionMatch(z,"error-prefix") ){
32068
+ if( i+1>=nArg ){
32069
+ dotCmdError(p, i, "missing argument", 0);
32070
+ return 1;
32071
+ }
32072
+ free(p->zErrPrefix);
32073
+ i++;
32074
+ p->zErrPrefix = azArg[i][0]==0 ? 0 : strdup(azArg[i]);
32075
+ }else if( zName ){
32076
+ dotCmdError(p, i, "unknown option", 0);
32077
+ return 1;
32078
+ }else{
32079
+ zName = azArg[i];
32080
+ }
32081
+ }
32082
+ output_reset(p);
32083
+ if( cli_output_capture ){
32084
+ sqlite3_str_free(cli_output_capture);
32085
+ }
32086
+ cli_output_capture = sqlite3_str_new(0);
32087
+ if( zName ){
32088
+ sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", zName);
32089
+ }else{
32090
+ sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s:%lld",
32091
+ p->zInFile, p->lineno);
32092
+ }
32093
+ return 0;
32094
+}
3161432095
3161532096
/*
3161632097
** Enlarge the space allocated in p->dot so that it can hold more
3161732098
** than nArg parsed command-line arguments.
3161832099
*/
@@ -31641,11 +32122,11 @@
3164132122
free(p->dot.zCopy);
3164232123
z = p->dot.zCopy = strdup(zLine);
3164332124
shell_check_oom(z);
3164432125
szLine = strlen(z);
3164532126
while( szLine>0 && IsSpace(z[szLine-1]) ) szLine--;
31646
- if( szLine>0 && z[szLine-1]==';' && p->iCompat>=20251115 ){
32127
+ if( szLine>0 && z[szLine-1]==';' ){
3164732128
szLine--;
3164832129
while( szLine>0 && IsSpace(z[szLine-1]) ) szLine--;
3164932130
}
3165032131
z[szLine] = 0;
3165132132
parseDotRealloc(p, 2);
@@ -31861,35 +32342,17 @@
3186132342
eputz("Usage: .changes on|off\n");
3186232343
rc = 1;
3186332344
}
3186432345
}else
3186532346
31866
-#ifndef SQLITE_SHELL_FIDDLE
3186732347
/* Cancel output redirection, if it is currently set (by .testcase)
3186832348
** Then read the content of the testcase-out.txt file and compare against
3186932349
** azArg[1]. If there are differences, report an error and exit.
3187032350
*/
3187132351
if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
31872
- char *zRes = 0;
31873
- output_reset(p);
31874
- if( nArg!=2 ){
31875
- eputz("Usage: .check GLOB-PATTERN\n");
31876
- rc = 2;
31877
- }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
31878
- rc = 2;
31879
- }else if( testcase_glob(azArg[1],zRes)==0 ){
31880
- cli_printf(stderr,
31881
- "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
31882
- p->zTestcase, azArg[1], zRes);
31883
- rc = 1;
31884
- }else{
31885
- cli_printf(p->out, "testcase-%s ok\n", p->zTestcase);
31886
- p->nCheck++;
31887
- }
31888
- sqlite3_free(zRes);
32352
+ rc = dotCmdCheck(p);
3188932353
}else
31890
-#endif /* !defined(SQLITE_SHELL_FIDDLE) */
3189132354
3189232355
#ifndef SQLITE_SHELL_FIDDLE
3189332356
if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
3189432357
failIfSafeMode(p, "cannot run .clone in safe mode");
3189532358
if( nArg==2 ){
@@ -32468,10 +32931,11 @@
3246832931
}else
3246932932
3247032933
if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
3247132934
if( nArg==2 ){
3247232935
p->mode.spec.bTitles = booleanValue(azArg[1]) ? QRF_Yes : QRF_No;
32936
+ p->mode.mFlags |= MFLG_HDR;
3247332937
p->mode.spec.eTitle = aModeInfo[p->mode.eMode].eHdr;
3247432938
}else{
3247532939
eputz("Usage: .headers on|off\n");
3247632940
rc = 1;
3247732941
}
@@ -32521,14 +32985,14 @@
3252132985
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
3252232986
goto meta_command_exit;
3252332987
}
3252432988
zSql = sqlite3_mprintf(
3252532989
"SELECT rootpage, 0 FROM sqlite_schema"
32526
- " WHERE name='%q' AND type='index'"
32990
+ " WHERE type='index' AND lower(name)=lower('%q')"
3252732991
"UNION ALL "
3252832992
"SELECT rootpage, 1 FROM sqlite_schema"
32529
- " WHERE name='%q' AND type='table'"
32993
+ " WHERE type='table' AND lower(name)=lower('%q')"
3253032994
" AND sql LIKE '%%without%%rowid%%'",
3253132995
azArg[1], azArg[1]
3253232996
);
3253332997
sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3253432998
sqlite3_free(zSql);
@@ -32682,13 +33146,14 @@
3268233146
goto meta_command_exit;
3268333147
}
3268433148
if( nArg==3 ){
3268533149
sqlite3_limit(p->db, aLimit[iLimit].limitCode,
3268633150
(int)integerValue(azArg[2]));
33151
+ }else{
33152
+ cli_printf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName,
33153
+ sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
3268733154
}
32688
- cli_printf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName,
32689
- sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
3269033155
}
3269133156
}else
3269233157
3269333158
if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
3269433159
open_db(p, 0);
@@ -33027,10 +33492,23 @@
3302733492
continue;
3302833493
}
3302933494
if( cli_strcmp(z,"once")==0 ){
3303033495
p->flgProgress |= SHELL_PROGRESS_ONCE;
3303133496
continue;
33497
+ }
33498
+ if( cli_strcmp(z,"timeout")==0 ){
33499
+ if( i==nArg-1 ){
33500
+ dotCmdError(p, i, "missing argument", 0);
33501
+ return 1;
33502
+ }
33503
+ i++;
33504
+ p->tmProgress = atof(azArg[i]);
33505
+ if( p->tmProgress>0.0 ){
33506
+ p->flgProgress = SHELL_PROGRESS_QUIET|SHELL_PROGRESS_TMOUT;
33507
+ if( nn==0 ) nn = 100;
33508
+ }
33509
+ continue;
3303233510
}
3303333511
if( cli_strcmp(z,"limit")==0 ){
3303433512
if( i+1>=nArg ){
3303533513
eputz("Error: missing argument on --limit\n");
3303633514
rc = 1;
@@ -33233,21 +33711,22 @@
3323333711
|| sqlite3_strlike(zName, "sqlite_schema", '\\')==0
3323433712
|| sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
3323533713
|| sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
3323633714
if( isSchema ){
3323733715
cli_printf(p->out,
33238
- "CREATE TABLE %s (\n"
33716
+ "CREATE TABLE %ssqlite_schema (\n"
3323933717
" type text,\n"
3324033718
" name text,\n"
3324133719
" tbl_name text,\n"
3324233720
" rootpage integer,\n"
3324333721
" sql text\n"
33244
- ");\n", zName);
33722
+ ");\n",
33723
+ sqlite3_strlike("sqlite_t%",zName,0)==0 ? "temp." : ""
33724
+ );
3324533725
}
3324633726
}
33247
- rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
33248
- -1, &pStmt, 0);
33727
+ rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
3324933728
if( rc ){
3325033729
shellDatabaseError(p->db);
3325133730
sqlite3_finalize(pStmt);
3325233731
3325333732
rc = 1;
@@ -33255,11 +33734,11 @@
3325533734
}
3325633735
pSql = sqlite3_str_new(p->db);
3325733736
sqlite3_str_appendf(pSql, "SELECT sql FROM", 0);
3325833737
iSchema = 0;
3325933738
while( sqlite3_step(pStmt)==SQLITE_ROW ){
33260
- const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
33739
+ const char *zDb = (const char*)sqlite3_column_text(pStmt, 1);
3326133740
char zScNum[30];
3326233741
sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
3326333742
sqlite3_str_appendall(pSql, zDiv);
3326433743
zDiv = " UNION ALL ";
3326533744
if( sqlite3_stricmp(zDb, "main")==0 ){
@@ -33275,11 +33754,12 @@
3327533754
" AS sql, type, tbl_name, name, rowid, %d AS snum, %Q as sname",
3327633755
++iSchema, zDb);
3327733756
sqlite3_str_appendf(pSql," FROM \"%w\".sqlite_schema", zDb);
3327833757
}
3327933758
sqlite3_finalize(pStmt);
33280
-#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
33759
+#if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS) \
33760
+ && !defined(SQLITE_OMIT_VIRTUALTABLE)
3328133761
if( zName ){
3328233762
sqlite3_str_appendall(pSql,
3328333763
" UNION ALL SELECT shell_module_schema(name),"
3328433764
" 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list");
3328533765
}
@@ -33299,11 +33779,11 @@
3329933779
}else{
3330033780
sqlite3_str_appendf(pSql, " LIKE %Q ESCAPE '\\' AND ", zName);
3330133781
}
3330233782
}
3330333783
if( bNoSystemTabs ){
33304
- sqlite3_str_appendf(pSql, " name NOT LIKE 'sqlite__%%' ESCALE '_' AND ");
33784
+ sqlite3_str_appendf(pSql, " name NOT LIKE 'sqlite__%%' ESCAPE '_' AND ");
3330533785
}
3330633786
sqlite3_str_appendf(pSql, "sql IS NOT NULL ORDER BY snum, rowid");
3330733787
if( bDebug ){
3330833788
cli_printf(p->out, "SQL: %s;\n", sqlite3_str_value(pSql));
3330933789
}else{
@@ -34017,25 +34497,15 @@
3401734497
sqlite3_str_free(pSql);
3401834498
modePop(p);
3401934499
if( rc ) return shellDatabaseError(p->db);
3402034500
}else
3402134501
34022
-#ifndef SQLITE_SHELL_FIDDLE
34023
- /* Begin redirecting output to the file "testcase-out.txt" */
34502
+ /* Set the p->zTestcase name and begin redirecting output into
34503
+ ** the cli_output_capture sqlite3_str */
3402434504
if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
34025
- output_reset(p);
34026
- p->out = output_file_open(p, "testcase-out.txt");
34027
- if( p->out==0 ){
34028
- eputz("Error: cannot open 'testcase-out.txt'\n");
34029
- }
34030
- if( nArg>=2 ){
34031
- sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
34032
- }else{
34033
- sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
34034
- }
34505
+ rc = dotCmdTestcase(p);
3403534506
}else
34036
-#endif /* !defined(SQLITE_SHELL_FIDDLE) */
3403734507
3403834508
#ifndef SQLITE_UNTESTABLE
3403934509
if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
3404034510
static const struct {
3404134511
const char *zCtrlName; /* Name of a test-control option */
@@ -34527,17 +34997,21 @@
3452734997
sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
3452834998
}else
3452934999
3453035000
if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
3453135001
if( nArg==2 ){
34532
- enableTimer = booleanValue(azArg[1]);
34533
- if( enableTimer && !HAS_TIMER ){
35002
+ if( cli_strcmp(azArg[1],"once")==0 ){
35003
+ p->enableTimer = 1;
35004
+ }else{
35005
+ p->enableTimer = 2*booleanValue(azArg[1]);
35006
+ }
35007
+ if( p->enableTimer && !HAS_TIMER ){
3453435008
eputz("Error: timer not available on this system.\n");
34535
- enableTimer = 0;
35009
+ p->enableTimer = 0;
3453635010
}
3453735011
}else{
34538
- eputz("Usage: .timer on|off\n");
35012
+ eputz("Usage: .timer on|off|once\n");
3453935013
rc = 1;
3454035014
}
3454135015
}else
3454235016
3454335017
#ifndef SQLITE_OMIT_TRACE
@@ -34708,10 +35182,11 @@
3470835182
if( p->nPopOutput ){
3470935183
p->nPopOutput--;
3471035184
if( p->nPopOutput==0 ) output_reset(p);
3471135185
}
3471235186
p->bSafeMode = p->bSafeModePersist;
35187
+ p->dot.nArg = 0;
3471335188
return rc;
3471435189
}
3471535190
3471635191
/* Line scan result and intermediate states (supporting scan resumption)
3471735192
*/
@@ -34944,13 +35419,13 @@
3494435419
char *zErrMsg = 0;
3494535420
3494635421
open_db(p, 0);
3494735422
if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
3494835423
if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
34949
- BEGIN_TIMER;
35424
+ BEGIN_TIMER(p);
3495035425
rc = shell_exec(p, zSql, &zErrMsg);
34951
- END_TIMER(p->out);
35426
+ END_TIMER(p);
3495235427
if( rc || zErrMsg ){
3495335428
char zPrefix[100];
3495435429
const char *zErrorTail;
3495535430
const char *zErrorType;
3495635431
if( zErrMsg==0 ){
@@ -35351,11 +35826,10 @@
3535135826
" -bail stop after hitting an error\n"
3535235827
" -batch force batch I/O\n"
3535335828
" -box set output mode to 'box'\n"
3535435829
" -cmd COMMAND run \"COMMAND\" before reading stdin\n"
3535535830
" -column set output mode to 'column'\n"
35356
- " -compat YYYYMMDD set default options for date YYYYMMDD\n"
3535735831
" -csv set output mode to 'csv'\n"
3535835832
#if !defined(SQLITE_OMIT_DESERIALIZE)
3535935833
" -deserialize open the database using sqlite3_deserialize()\n"
3536035834
#endif
3536135835
" -echo print inputs before execution\n"
@@ -35435,15 +35909,10 @@
3543535909
/*
3543635910
** Initialize the state information in data
3543735911
*/
3543835912
static void main_init(ShellState *p) {
3543935913
memset(p, 0, sizeof(*p));
35440
-#if defined(COMPATIBILITY_DATE)
35441
- p->iCompat = COMPATIBILITY_DATE;
35442
-#else
35443
- p->iCompat = 20251116;
35444
-#endif
3544535914
p->pAuxDb = &p->aAuxDb[0];
3544635915
p->shellFlgs = SHFLG_Lookaside;
3544735916
sqlite3_config(SQLITE_CONFIG_LOG, shellLog, p);
3544835917
#if !defined(SQLITE_SHELL_FIDDLE)
3544935918
verify_uninitialized();
@@ -35498,29 +35967,65 @@
3549835967
cli_puts(z, p->out);
3549935968
fflush(p->out);
3550035969
return 1;
3550135970
}
3550235971
35503
-#ifndef SQLITE_SHELL_IS_UTF8
35504
-# if (defined(_WIN32) || defined(WIN32)) \
35505
- && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
35506
-# define SQLITE_SHELL_IS_UTF8 (0)
35507
-# else
35508
-# define SQLITE_SHELL_IS_UTF8 (1)
35509
-# endif
35510
-#endif
35511
-
35972
+/* Alternative name to the entry point for Fiddle */
3551235973
#ifdef SQLITE_SHELL_FIDDLE
3551335974
# define main fiddle_main
3551435975
#endif
3551535976
35516
-#if SQLITE_SHELL_IS_UTF8
35517
-int SQLITE_CDECL main(int argc, char **argv){
35518
-#else
35977
+/* Use the wmain() entry point on Windows. Translate arguments to
35978
+** UTF8, then invoke the traditional main() entry point which is
35979
+** renamed using a #define to utf8_main() .
35980
+*/
35981
+#if defined(_WIN32) && !defined(main)
35982
+# define main utf8_main /* Rename entry point to utf_main() */
35983
+int SQLITE_CDECL utf8_main(int,char**); /* Forward declaration */
3551935984
int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
35520
- char **argv;
35521
-#endif
35985
+ int rc, i;
35986
+ char **argv = malloc( sizeof(char*) * (argc+1) );
35987
+ char **orig = argv;
35988
+ if( argv==0 ){
35989
+ fprintf(stderr, "malloc failed\n");
35990
+ exit(1);
35991
+ }
35992
+ for(i=0; i<argc; i++){
35993
+ int nByte = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, 0, 0, 0, 0);
35994
+ if( nByte==0 ){
35995
+ argv[i] = 0;
35996
+ }else{
35997
+ argv[i] = malloc( nByte );
35998
+ if( argv[i]==0 ){
35999
+ fprintf(stderr, "malloc failed\n");
36000
+ exit(1);
36001
+ }
36002
+ nByte = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, argv[i],nByte,0,0);
36003
+ if( nByte==0 ){
36004
+ free(argv[i]);
36005
+ argv[i] = 0;
36006
+ }
36007
+ }
36008
+ }
36009
+ argv[argc] = 0;
36010
+ rc = utf8_main(argc, argv);
36011
+ for(i=0; i<argc; i++) free(orig[i]);
36012
+ free(argv);
36013
+ return rc;
36014
+}
36015
+#endif /* WIN32 */
36016
+
36017
+/*
36018
+** This is the main entry point for the process. Everything starts here.
36019
+**
36020
+** The "main" identifier may have been #defined to something else:
36021
+**
36022
+** utf8_main On Windows
36023
+** fiddle_main In Fiddle
36024
+** sqlite3_shell Other projects that use shell.c as a subroutine
36025
+*/
36026
+int SQLITE_CDECL main(int argc, char **argv){
3552236027
#ifdef SQLITE_DEBUG
3552336028
sqlite3_int64 mem_main_enter = 0;
3552436029
#endif
3552536030
char *zErrMsg = 0;
3552636031
#ifdef SQLITE_SHELL_FIDDLE
@@ -35538,14 +36043,10 @@
3553836043
int nOptsEnd = argc;
3553936044
int bEnableVfstrace = 0;
3554036045
char **azCmd = 0;
3554136046
int *aiCmd = 0;
3554236047
const char *zVfs = 0; /* Value of -vfs command-line option */
35543
-#if !SQLITE_SHELL_IS_UTF8
35544
- char **argvToFree = 0;
35545
- int argcToFree = 0;
35546
-#endif
3554736048
setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
3554836049
3554936050
#ifdef SQLITE_SHELL_FIDDLE
3555036051
stdin_is_interactive = 0;
3555136052
stdout_is_console = 1;
@@ -35596,36 +36097,10 @@
3559636097
exit(1);
3559736098
}
3559836099
#endif
3559936100
main_init(&data);
3560036101
35601
- /* On Windows, we must translate command-line arguments into UTF-8.
35602
- ** The SQLite memory allocator subsystem has to be enabled in order to
35603
- ** do this. But we want to run an sqlite3_shutdown() afterwards so that
35604
- ** subsequent sqlite3_config() calls will work. So copy all results into
35605
- ** memory that does not come from the SQLite memory allocator.
35606
- */
35607
-#if !SQLITE_SHELL_IS_UTF8
35608
- sqlite3_initialize();
35609
- argvToFree = malloc(sizeof(argv[0])*argc*2);
35610
- shell_check_oom(argvToFree);
35611
- argcToFree = argc;
35612
- argv = argvToFree + argc;
35613
- for(i=0; i<argc; i++){
35614
- char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
35615
- i64 n;
35616
- shell_check_oom(z);
35617
- n = strlen(z);
35618
- argv[i] = malloc( n+1 );
35619
- shell_check_oom(argv[i]);
35620
- memcpy(argv[i], z, n+1);
35621
- argvToFree[i] = argv[i];
35622
- sqlite3_free(z);
35623
- }
35624
- sqlite3_shutdown();
35625
-#endif
35626
-
3562736102
assert( argc>=1 && argv && argv[0] );
3562836103
Argv0 = argv[0];
3562936104
3563036105
#ifdef SQLITE_SHELL_DBNAME_PROC
3563136106
{
@@ -35637,11 +36112,11 @@
3563736112
SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
3563836113
warnInmemoryDb = 0;
3563936114
}
3564036115
#endif
3564136116
35642
- /* Do an initial pass through the command-line argument to locate
36117
+ /* Do an initial pass through the command-line arguments to locate
3564336118
** the name of the database file, the name of the initialization file,
3564436119
** the size of the alternative malloc heap, options affecting commands
3564536120
** or SQL run from the command line, and the first command to execute.
3564636121
*/
3564736122
#ifndef SQLITE_SHELL_FIDDLE
@@ -35649,11 +36124,11 @@
3564936124
#endif
3565036125
for(i=1; i<argc; i++){
3565136126
char *z;
3565236127
z = argv[i];
3565336128
if( z[0]!='-' || i>nOptsEnd ){
35654
- if( data.aAuxDb->zDbFilename==0 ){
36129
+ if( data.aAuxDb->zDbFilename==0 && !isScriptFile(z,1) ){
3565536130
data.aAuxDb->zDbFilename = z;
3565636131
}else{
3565736132
/* Excess arguments are interpreted as SQL (or dot-commands) and
3565836133
** mean that nothing is read from stdin */
3565936134
readStdin = 0;
@@ -35694,15 +36169,10 @@
3569436169
if( n<2 ){
3569536170
sqlite3_fprintf(stderr,"minimum --screenwidth is 2\n");
3569636171
exit(1);
3569736172
}
3569836173
stdout_tty_width = n;
35699
- }else if( cli_strcmp(z,"-compat")==0 ){
35700
- data.iCompat = atoi(cmdline_option_value(argc, argv, ++i));
35701
- modeFree(&data.mode);
35702
- memset(&data.mode, 0, sizeof(data.mode));
35703
- modeDefault(&data);
3570436174
}else if( cli_strcmp(z,"-utf8")==0 ){
3570536175
}else if( cli_strcmp(z,"-no-utf8")==0 ){
3570636176
}else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
3570736177
int val = 0;
3570836178
sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW, &val);
@@ -35822,10 +36292,20 @@
3582236292
}else if( cli_strcmp(z,"-safe")==0 ){
3582336293
/* no-op - catch this on the second pass */
3582436294
}else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
3582536295
/* skip over the argument */
3582636296
i++;
36297
+ }else if( cli_strcmp(z,"-test-argv")==0 ){
36298
+ /* Undocumented test option. Print the values in argv[] and exit.
36299
+ ** Use this to verify that any translation of the argv[], for example
36300
+ ** on Windows that receives wargv[] from the OS and must convert
36301
+ ** to UTF8 prior to calling this routine. */
36302
+ int kk;
36303
+ for(kk=0; kk<argc; kk++){
36304
+ sqlite3_fprintf(stdout,"argv[%d] = \"%s\"\n", kk, argv[kk]);
36305
+ }
36306
+ return 0;
3582736307
}
3582836308
}
3582936309
#ifndef SQLITE_SHELL_FIDDLE
3583036310
if( !bEnableVfstrace ) verify_uninitialized();
3583136311
#endif
@@ -35848,11 +36328,30 @@
3584836328
3584936329
if( zVfs ){
3585036330
sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
3585136331
if( pVfs ){
3585236332
sqlite3_vfs_register(pVfs, 1);
35853
- }else{
36333
+ }
36334
+#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
36335
+ else if( access(zVfs,0)==0 ){
36336
+ /* If the VFS name is not the name of an existing VFS, but it is
36337
+ ** the name of a file, then try to load that file as an extension.
36338
+ ** Presumably the extension implements the desired VFS. */
36339
+ sqlite3 *db = 0;
36340
+ char *zErr = 0;
36341
+ sqlite3_open(":memory:", &db);
36342
+ sqlite3_enable_load_extension(db, 1);
36343
+ rc = sqlite3_load_extension(db, zVfs, 0, &zErr);
36344
+ sqlite3_close(db);
36345
+ if( (rc&0xff)!=SQLITE_OK ){
36346
+ cli_printf(stderr, "could not load extension VFS \"%s\": %s\n",
36347
+ zVfs, zErr);
36348
+ exit(1);
36349
+ }
36350
+ }
36351
+#endif
36352
+ else{
3585436353
cli_printf(stderr,"no such VFS: \"%s\"\n", zVfs);
3585536354
exit(1);
3585636355
}
3585736356
}
3585836357
@@ -35889,11 +36388,11 @@
3588936388
** is given on the command line, look for a file named ~/.sqliterc and
3589036389
** try to process it.
3589136390
*/
3589236391
if( !noInit ) process_sqliterc(&data,zInitFile);
3589336392
35894
- /* Make a second pass through the command-line argument and set
36393
+ /* Make a second pass through the command-line arguments and set
3589536394
** options. This second pass is delayed until after the initialization
3589636395
** file is processed so that the command-line arguments will override
3589736396
** settings in the initialization file.
3589836397
*/
3589936398
for(i=1; i<argc; i++){
@@ -36015,12 +36514,10 @@
3601536514
stdin_is_interactive = 1;
3601636515
}else if( cli_strcmp(z,"-batch")==0 ){
3601736516
/* already handled */
3601836517
}else if( cli_strcmp(z,"-screenwidth")==0 ){
3601936518
i++;
36020
- }else if( cli_strcmp(z,"-compat")==0 ){
36021
- i++;
3602236519
}else if( cli_strcmp(z,"-utf8")==0 ){
3602336520
/* already handled */
3602436521
}else if( cli_strcmp(z,"-no-utf8")==0 ){
3602536522
/* already handled */
3602636523
}else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
@@ -36116,11 +36613,22 @@
3611636613
** command-line inputs, except for the argToSkip argument which contains
3611736614
** the database filename.
3611836615
*/
3611936616
for(i=0; i<nCmd; i++){
3612036617
echo_group_input(&data, azCmd[i]);
36121
- if( azCmd[i][0]=='.' ){
36618
+ if( isScriptFile(azCmd[i],0) ){
36619
+ FILE *inSaved = data.in;
36620
+ i64 savedLineno = data.lineno;
36621
+ int res = 1;
36622
+ if( (data.in = openChrSource(azCmd[i]))!=0 ){
36623
+ res = process_input(&data, azCmd[i]);
36624
+ fclose(data.in);
36625
+ }
36626
+ data.in = inSaved;
36627
+ data.lineno = savedLineno;
36628
+ if( res ) i = nCmd;
36629
+ }else if( azCmd[i][0]=='.' ){
3612236630
char *zErrCtx = malloc( 64 );
3612336631
shell_check_oom(zErrCtx);
3612436632
sqlite3_snprintf(64,zErrCtx,"argv[%i]:",aiCmd[i]);
3612536633
data.zInFile = "<cmdline>";
3612636634
data.zErrPrefix = zErrCtx;
@@ -36231,14 +36739,10 @@
3623136739
}
3623236740
find_home_dir(1);
3623336741
output_reset(&data);
3623436742
data.doXdgOpen = 0;
3623536743
clearTempFile(&data);
36236
-#if !SQLITE_SHELL_IS_UTF8
36237
- for(i=0; i<argcToFree; i++) free(argvToFree[i]);
36238
- free(argvToFree);
36239
-#endif
3624036744
modeFree(&data.mode);
3624136745
if( data.nSavedModes ){
3624236746
int ii;
3624336747
for(ii=0; ii<data.nSavedModes; ii++){
3624436748
modeFree(&data.aSavedModes[ii].mode);
3624536749
--- extsrc/shell.c
+++ extsrc/shell.c
@@ -35,11 +35,11 @@
35 ** ext/recover/sqlite3recover.h
36 ** src/shell.c.in
37 **
38 ** To modify this program, get a copy of the canonical SQLite source tree,
39 ** edit the src/shell.c.in file and/or some of the other files that are
40 ** listed above, then rerun the rerun "make shell.c".
41 */
42 /************************* Begin src/shell.c.in ******************/
43 /*
44 ** 2001 September 15
45 **
@@ -49,11 +49,11 @@
49 ** May you do good and not evil.
50 ** May you find forgiveness for yourself and forgive others.
51 ** May you share freely, never taking more than you give.
52 **
53 *************************************************************************
54 ** This file contains code to implement the "sqlite" command line
55 ** utility for accessing SQLite databases.
56 */
57 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
58 /* This needs to come before any includes for MSVC compiler */
59 #define _CRT_SECURE_NO_WARNINGS
@@ -79,10 +79,14 @@
79 ** should only be used when building the "fiddle" web application, as
80 ** the browser-mode build has much different user input requirements
81 ** and this build mode rewires the user input subsystem to account for
82 ** that.
83 */
 
 
 
 
84
85 /*
86 ** Warning pragmas copied from msvc.h in the core.
87 */
88 #if defined(_MSC_VER)
@@ -872,10 +876,11 @@
872 #ifndef SQLITE_QRF_H
873 #include "qrf.h"
874 #endif
875 #include <string.h>
876 #include <assert.h>
 
877
878 /* typedef sqlite3_int64 i64; */
879
880 /* A single line in the EQP output */
881 typedef struct qrfEQPGraphRow qrfEQPGraphRow;
@@ -889,11 +894,12 @@
889 /* All EQP output is collected into an instance of the following */
890 typedef struct qrfEQPGraph qrfEQPGraph;
891 struct qrfEQPGraph {
892 qrfEQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
893 qrfEQPGraphRow *pLast; /* Last element of the pRow list */
894 char zPrefix[100]; /* Graph prefix */
 
895 };
896
897 /*
898 ** Private state information. Subject to change from one release to the
899 ** next.
@@ -995,10 +1001,19 @@
995 */
996 static void qrfOom(Qrf *p){
997 qrfError(p, SQLITE_NOMEM, "out of memory");
998 }
999
 
 
 
 
 
 
 
 
 
1000
1001
1002 /*
1003 ** Add a new entry to the EXPLAIN QUERY PLAN data
1004 */
@@ -1074,10 +1089,49 @@
1074 qrfEqpRenderLevel(p, pRow->iEqpId);
1075 p->u.pGraph->zPrefix[n] = 0;
1076 }
1077 }
1078 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1079
1080 /*
1081 ** Display and reset the EXPLAIN QUERY PLAN data
1082 */
1083 static void qrfEqpRender(Qrf *p, i64 nCycle){
@@ -1090,11 +1144,30 @@
1090 }
1091 sqlite3_str_appendf(p->pOut, "%s\n", pRow->zText+3);
1092 p->u.pGraph->pRow = pRow->pNext;
1093 sqlite3_free(pRow);
1094 }else if( nCycle>0 ){
1095 sqlite3_str_appendf(p->pOut, "QUERY PLAN (cycles=%lld [100%%])\n",nCycle);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1096 }else{
1097 sqlite3_str_appendall(p->pOut, "QUERY PLAN\n");
1098 }
1099 p->u.pGraph->zPrefix[0] = 0;
1100 qrfEqpRenderLevel(p, 0);
@@ -1145,10 +1218,12 @@
1145 static const int f = SQLITE_SCANSTAT_COMPLEX;
1146 sqlite3_stmt *pS = p->pStmt;
1147 int i = 0;
1148 i64 nTotal = 0;
1149 int nWidth = 0;
 
 
1150 sqlite3_str *pLine = sqlite3_str_new(p->db);
1151 sqlite3_str *pStats = sqlite3_str_new(p->db);
1152 qrfEqpReset(p);
1153
1154 for(i=0; 1; i++){
@@ -1158,11 +1233,11 @@
1158 break;
1159 }
1160 n = (int)strlen(z) + qrfStatsHeight(pS,i)*3;
1161 if( n>nWidth ) nWidth = n;
1162 }
1163 nWidth += 4;
1164
1165 sqlite3_stmt_scanstatus_v2(pS,-1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
1166 for(i=0; 1; i++){
1167 i64 nLoop = 0;
1168 i64 nRow = 0;
@@ -1173,55 +1248,67 @@
1173 const char *zName = 0;
1174 double rEst = 0.0;
1175
1176 if( sqlite3_stmt_scanstatus_v2(pS,i,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&zo) ){
1177 break;
 
 
 
 
 
1178 }
1179 sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
 
1180 sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
1181 sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
1182 sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
1183 sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
1184 sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
1185 sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
1186
1187 if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
1188 const char *zSp = "";
1189 double rpl;
1190 sqlite3_str_reset(pStats);
1191 if( nCycle>=0 && nTotal>0 ){
1192 sqlite3_str_appendf(pStats, "cycles=%lld [%d%%]",
1193 nCycle, ((nCycle*100)+nTotal/2) / nTotal
 
1194 );
1195 zSp = " ";
1196 }
1197 if( nLoop>=0 ){
1198 sqlite3_str_appendf(pStats, "%sloops=%lld", zSp, nLoop);
1199 zSp = " ";
 
 
 
 
 
1200 }
1201 if( nRow>=0 ){
1202 sqlite3_str_appendf(pStats, "%srows=%lld", zSp, nRow);
1203 zSp = " ";
1204 }
1205
1206 if( p->spec.eStyle==QRF_STYLE_StatsEst ){
1207 rpl = (double)nRow / (double)nLoop;
1208 sqlite3_str_appendf(pStats, "%srpl=%.1f est=%.1f", zSp, rpl, rEst);
1209 }
1210
1211 sqlite3_str_appendf(pLine,
1212 "% *s (%s)", -1*(nWidth-qrfStatsHeight(pS,i)*3), zo,
1213 sqlite3_str_value(pStats)
1214 );
1215 sqlite3_str_reset(pStats);
1216 qrfEqpAppend(p, iId, iPid, sqlite3_str_value(pLine));
1217 sqlite3_str_reset(pLine);
1218 }else{
1219 qrfEqpAppend(p, iId, iPid, zo);
1220 }
1221 }
 
 
1222 sqlite3_free(sqlite3_str_finish(pLine));
 
1223 sqlite3_free(sqlite3_str_finish(pStats));
1224 #endif
1225 }
1226
1227
@@ -1581,13 +1668,15 @@
1581 ** (3) z[] does not looks like a numeric literal
1582 */
1583 static int qrfRelaxable(Qrf *p, const char *z){
1584 size_t i, n;
1585 if( z[0]=='\'' || qrfSpace(z[0]) ) return 0;
1586 if( z[0]==0 && (p->spec.zNull==0 || p->spec.zNull[0]==0) ) return 0;
 
 
1587 n = strlen(z);
1588 if( z[n-1]=='\'' || qrfSpace(z[n-1]) ) return 0;
1589 if( p->spec.zNull && strcmp(p->spec.zNull,z)==0 ) return 0;
1590 i = (z[0]=='-' || z[0]=='+');
1591 if( strcmp(z+i,"Inf")==0 ) return 0;
1592 if( !qrfDigit(z[i]) ) return 1;
1593 i++;
@@ -2729,10 +2818,11 @@
2729 int nNL = 0;
2730 int n, w;
2731 pStr = sqlite3_str_new(p->db);
2732 qrfEncodeText(p, pStr, z ? z : "");
2733 n = sqlite3_str_length(pStr);
 
2734 z = data.az[data.n] = sqlite3_str_finish(pStr);
2735 if( p->spec.nTitleLimit ){
2736 nNL = 0;
2737 data.aiWth[data.n] = w = qrfTitleLimit(data.az[data.n],
2738 p->spec.nTitleLimit );
@@ -2756,10 +2846,11 @@
2756 int n, w;
2757 int eType = sqlite3_column_type(p->pStmt,i);
2758 pStr = sqlite3_str_new(p->db);
2759 qrfRenderValue(p, pStr, i);
2760 n = sqlite3_str_length(pStr);
 
2761 z = data.az[data.n] = sqlite3_str_finish(pStr);
2762 data.abNum[data.n] = eType==SQLITE_INTEGER || eType==SQLITE_FLOAT;
2763 data.aiWth[data.n] = w = qrfDisplayWidth(z, n, &nNL);
2764 data.n++;
2765 if( w>data.a[i].mxW ) data.a[i].mxW = w;
@@ -2910,11 +3001,11 @@
2910 ){
2911 bRTrim = 1;
2912 }else{
2913 bRTrim = 0;
2914 }
2915 for(i=0; i<data.n; i+=nColumn){
2916 int bMore;
2917 int nRow = 0;
2918
2919 /* Draw a single row of the table. This might be the title line
2920 ** (if there is a title line) or a row in the body of the table.
@@ -3097,11 +3188,11 @@
3097 assert( 0==sqlite3_stricmp( sqlite3_column_name(p->pStmt, 0), "addr" ) );
3098 assert( 0==sqlite3_stricmp( sqlite3_column_name(p->pStmt, 1), "opcode" ) );
3099 assert( 0==sqlite3_stricmp( sqlite3_column_name(p->pStmt, 2), "p1" ) );
3100 assert( 0==sqlite3_stricmp( sqlite3_column_name(p->pStmt, 3), "p2" ) );
3101
3102 for(iOp=0; SQLITE_ROW==sqlite3_step(p->pStmt); iOp++){
3103 int iAddr = sqlite3_column_int(p->pStmt, 0);
3104 const char *zOp = (const char*)sqlite3_column_text(p->pStmt, 1);
3105 int p1 = sqlite3_column_int(p->pStmt, 2);
3106 int p2 = sqlite3_column_int(p->pStmt, 3);
3107
@@ -3154,11 +3245,11 @@
3154 nWidth = sizeof(aScanExpWidth)/sizeof(int);
3155 iIndent = 3;
3156 }
3157 if( nArg>nWidth ) nArg = nWidth;
3158
3159 for(iOp=0; sqlite3_step(p->pStmt)==SQLITE_ROW; iOp++){
3160 /* If this is the first row seen, print out the headers */
3161 if( iOp==0 ){
3162 for(i=0; i<nArg; i++){
3163 const char *zCol = sqlite3_column_name(p->pStmt, aMap[i]);
3164 qrfWidthPrint(p,p->pOut, aWidth[i], zCol);
@@ -3410,10 +3501,11 @@
3410 sqlite3_str_append(p->pOut, "\n", 1);
3411 zVal += iNext;
3412 }while( zVal[0] );
3413 sqlite3_str_reset(pVal);
3414 }
 
3415 sqlite3_free(sqlite3_str_finish(pVal));
3416 qrfWrite(p);
3417 break;
3418 }
3419 case QRF_STYLE_Eqp: {
@@ -3473,11 +3565,11 @@
3473 p->pOut = sqlite3_str_new(p->db);
3474 if( p->pOut==0 ){
3475 qrfOom(p);
3476 return;
3477 }
3478 p->iErr = 0;
3479 p->nCol = sqlite3_column_count(p->pStmt);
3480 p->nRow = 0;
3481 sz = sizeof(sqlite3_qrf_spec);
3482 memcpy(&p->spec, pSpec, sz);
3483 if( p->spec.zNull==0 ) p->spec.zNull = "";
@@ -3644,17 +3736,27 @@
3644 sqlite3_free(p->u.sLine.azCol);
3645 }
3646 break;
3647 }
3648 case QRF_STYLE_Stats:
3649 case QRF_STYLE_StatsEst:
 
 
 
 
 
 
 
 
 
3650 case QRF_STYLE_Eqp: {
3651 qrfEqpRender(p, 0);
3652 qrfWrite(p);
3653 break;
3654 }
3655 }
 
3656 if( p->spec.pzOutput ){
3657 if( p->spec.pzOutput[0] ){
3658 sqlite3_int64 n, sz;
3659 char *zCombined;
3660 sz = strlen(p->spec.pzOutput[0]);
@@ -3815,13 +3917,10 @@
3815
3816
3817 #define eputz(z) cli_puts(z,stderr)
3818 #define sputz(fp,z) cli_puts(z,fp)
3819
3820 /* True if the timer is enabled */
3821 static int enableTimer = 0;
3822
3823 /* A version of strcmp() that works with NULL values */
3824 static int cli_strcmp(const char *a, const char *b){
3825 if( a==0 ) a = "";
3826 if( b==0 ) b = "";
3827 return strcmp(a,b);
@@ -3834,11 +3933,11 @@
3834
3835 /* Return the current wall-clock time in microseconds since the
3836 ** Unix epoch (1970-01-01T00:00:00Z)
3837 */
3838 static sqlite3_int64 timeOfDay(void){
3839 #if defined(_WIN64)
3840 sqlite3_uint64 t;
3841 FILETIME tm;
3842 GetSystemTimePreciseAsFileTime(&tm);
3843 t = ((u64)tm.dwHighDateTime<<32) | (u64)tm.dwLowDateTime;
3844 t += 116444736000000000LL;
@@ -3862,154 +3961,10 @@
3862 (void)gettimeofday(&sNow,0);
3863 return ((i64)sNow.tv_sec)*1000000 + sNow.tv_usec;
3864 #endif
3865 }
3866
3867 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
3868 #include <sys/time.h>
3869 #include <sys/resource.h>
3870
3871 /* VxWorks does not support getrusage() as far as we can determine */
3872 #if defined(_WRS_KERNEL) || defined(__RTP__)
3873 struct rusage {
3874 struct timeval ru_utime; /* user CPU time used */
3875 struct timeval ru_stime; /* system CPU time used */
3876 };
3877 #define getrusage(A,B) memset(B,0,sizeof(*B))
3878 #endif
3879
3880
3881 /* Saved resource information for the beginning of an operation */
3882 static struct rusage sBegin; /* CPU time at start */
3883 static sqlite3_int64 iBegin; /* Wall-clock time at start */
3884
3885 /*
3886 ** Begin timing an operation
3887 */
3888 static void beginTimer(void){
3889 if( enableTimer ){
3890 getrusage(RUSAGE_SELF, &sBegin);
3891 iBegin = timeOfDay();
3892 }
3893 }
3894
3895 /* Return the difference of two time_structs in seconds */
3896 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
3897 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
3898 (double)(pEnd->tv_sec - pStart->tv_sec);
3899 }
3900
3901 /*
3902 ** Print the timing results.
3903 */
3904 static void endTimer(FILE *out){
3905 if( enableTimer ){
3906 sqlite3_int64 iEnd = timeOfDay();
3907 struct rusage sEnd;
3908 getrusage(RUSAGE_SELF, &sEnd);
3909 cli_printf(out, "Run Time: real %.6f user %.6f sys %.6f\n",
3910 (iEnd - iBegin)*0.000001,
3911 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
3912 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
3913 }
3914 }
3915
3916 #define BEGIN_TIMER beginTimer()
3917 #define END_TIMER(X) endTimer(X)
3918 #define HAS_TIMER 1
3919
3920 #elif (defined(_WIN32) || defined(WIN32))
3921
3922 /* Saved resource information for the beginning of an operation */
3923 static HANDLE hProcess;
3924 static FILETIME ftKernelBegin;
3925 static FILETIME ftUserBegin;
3926 static sqlite3_int64 ftWallBegin;
3927 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
3928 LPFILETIME, LPFILETIME);
3929 static GETPROCTIMES getProcessTimesAddr = NULL;
3930
3931 /*
3932 ** Check to see if we have timer support. Return 1 if necessary
3933 ** support found (or found previously).
3934 */
3935 static int hasTimer(void){
3936 if( getProcessTimesAddr ){
3937 return 1;
3938 } else {
3939 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
3940 ** versions. See if the version we are running on has it, and if it
3941 ** does, save off a pointer to it and the current process handle.
3942 */
3943 hProcess = GetCurrentProcess();
3944 if( hProcess ){
3945 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
3946 if( NULL != hinstLib ){
3947 getProcessTimesAddr =
3948 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
3949 if( NULL != getProcessTimesAddr ){
3950 return 1;
3951 }
3952 FreeLibrary(hinstLib);
3953 }
3954 }
3955 }
3956 return 0;
3957 }
3958
3959 /*
3960 ** Begin timing an operation
3961 */
3962 static void beginTimer(void){
3963 if( enableTimer && getProcessTimesAddr ){
3964 FILETIME ftCreation, ftExit;
3965 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
3966 &ftKernelBegin,&ftUserBegin);
3967 ftWallBegin = timeOfDay();
3968 }
3969 }
3970
3971 /* Return the difference of two FILETIME structs in seconds */
3972 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
3973 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
3974 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
3975 return (double) ((i64End - i64Start) / 10000000.0);
3976 }
3977
3978 /*
3979 ** Print the timing results.
3980 */
3981 static void endTimer(FILE *out){
3982 if( enableTimer && getProcessTimesAddr){
3983 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
3984 sqlite3_int64 ftWallEnd = timeOfDay();
3985 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
3986 #ifdef _WIN64
3987 /* microsecond precision on 64-bit windows */
3988 cli_printf(out, "Run Time: real %.6f user %f sys %f\n",
3989 (ftWallEnd - ftWallBegin)*0.000001,
3990 timeDiff(&ftUserBegin, &ftUserEnd),
3991 timeDiff(&ftKernelBegin, &ftKernelEnd));
3992 #else
3993 /* millisecond precisino on 32-bit windows */
3994 cli_printf(out, "Run Time: real %.3f user %.3f sys %.3f\n",
3995 (ftWallEnd - ftWallBegin)*0.000001,
3996 timeDiff(&ftUserBegin, &ftUserEnd),
3997 timeDiff(&ftKernelBegin, &ftKernelEnd));
3998 #endif
3999 }
4000 }
4001
4002 #define BEGIN_TIMER beginTimer()
4003 #define END_TIMER(X) endTimer(X)
4004 #define HAS_TIMER hasTimer()
4005
4006 #else
4007 #define BEGIN_TIMER
4008 #define END_TIMER(X) /*no-op*/
4009 #define HAS_TIMER 0
4010 #endif
4011
4012 /*
4013 ** Used to prevent warnings about unused parameters
4014 */
4015 #define UNUSED_PARAMETER(x) (void)(x)
@@ -4068,10 +4023,18 @@
4068 #define PROMPT_LEN_MAX 128
4069 /* First line prompt. default: "sqlite> " */
4070 static char mainPrompt[PROMPT_LEN_MAX];
4071 /* Continuation prompt. default: " ...> " */
4072 static char continuePrompt[PROMPT_LEN_MAX];
 
 
 
 
 
 
 
 
4073
4074 /* This is variant of the standard-library strncpy() routine with the
4075 ** one change that the destination string is always zero-terminated, even
4076 ** if there is no zero-terminator in the first n-1 characters of the source
4077 ** string.
@@ -4188,17 +4151,10 @@
4188 */
4189 static void shell_check_oom(const void *p){
4190 if( p==0 ) shell_out_of_memory();
4191 }
4192
4193 /*
4194 ** Write I/O traces to the following stream.
4195 */
4196 #ifdef SQLITE_ENABLE_IOTRACE
4197 static FILE *iotrace = 0;
4198 #endif
4199
4200 /*
4201 ** This routine works like printf in that its first argument is a
4202 ** format string and subsequent arguments are values to be substituted
4203 ** in place of % fields. The result of formatting this string
4204 ** is written to iotrace.
@@ -8349,13 +8305,13 @@
8349 }else if( e<-10000 ){
8350 e = -10000;
8351 }
8352
8353 if( m<0 ){
 
8354 isNeg = 1;
8355 m = -m;
8356 if( m<0 ) return;
8357 }else if( m==0 && e>-1000 && e<1000 ){
8358 sqlite3_result_double(context, 0.0);
8359 return;
8360 }
8361 while( (m>>32)&0xffe00000 ){
@@ -9472,11 +9428,11 @@
9472 ** (X) match X
9473 ** X|Y X or Y
9474 ** ^X X occurring at the beginning of the string
9475 ** X$ X occurring at the end of the string
9476 ** . Match any single character
9477 ** \c Character c where c is one of \{}()[]|*+?.
9478 ** \c C-language escapes for c in afnrtv. ex: \t or \n
9479 ** \uXXXX Where XXXX is exactly 4 hex digits, unicode value XXXX
9480 ** \xXX Where XX is exactly 2 hex digits, unicode value XX
9481 ** [abc] Any single character from the set abc
9482 ** [^abc] Any single character not in the set abc
@@ -9857,11 +9813,11 @@
9857
9858 /* A backslash character has been seen, read the next character and
9859 ** return its interpretation.
9860 */
9861 static unsigned re_esc_char(ReCompiled *p){
9862 static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
9863 static const char zTrans[] = "\a\f\n\r\t\v";
9864 int i, v = 0;
9865 char c;
9866 if( p->sIn.i>=p->sIn.mx ) return 0;
9867 c = p->sIn.z[p->sIn.i];
@@ -10180,15 +10136,22 @@
10180 }
10181 return pRe->zErr;
10182 }
10183
10184 /*
10185 ** Compute a reasonable limit on the length of the REGEXP NFA.
10186 */
10187 static int re_maxlen(sqlite3_context *context){
10188 sqlite3 *db = sqlite3_context_db_handle(context);
10189 return 75 + sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH,-1)/2;
 
 
 
 
 
 
 
10190 }
10191
10192 /*
10193 ** Implementation of the regexp() SQL function. This function implements
10194 ** the build-in REGEXP operator. The first argument to the function is the
@@ -10210,14 +10173,21 @@
10210 int setAux = 0; /* True to invoke sqlite3_set_auxdata() */
10211
10212 (void)argc; /* Unused */
10213 pRe = sqlite3_get_auxdata(context, 0);
10214 if( pRe==0 ){
 
 
10215 zPattern = (const char*)sqlite3_value_text(argv[0]);
10216 if( zPattern==0 ) return;
10217 zErr = re_compile(&pRe, zPattern, re_maxlen(context),
10218 sqlite3_user_data(context)!=0);
 
 
 
 
 
10219 if( zErr ){
10220 re_free(pRe);
10221 sqlite3_result_error(context, zErr, -1);
10222 return;
10223 }
@@ -10279,11 +10249,11 @@
10279 "ATSTART",
10280 };
10281
10282 zPattern = (const char*)sqlite3_value_text(argv[0]);
10283 if( zPattern==0 ) return;
10284 zErr = re_compile(&pRe, zPattern, re_maxlen(context),
10285 sqlite3_user_data(context)!=0);
10286 if( zErr ){
10287 re_free(pRe);
10288 sqlite3_result_error(context, zErr, -1);
10289 return;
@@ -13067,11 +13037,11 @@
13067 nFile = (int)strlen(zFile)+1;
13068 }
13069
13070 rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
13071 if( rc==SQLITE_OK ){
13072 pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
13073 if( pNew==0 ) return SQLITE_NOMEM;
13074 memset(pNew, 0, nByte+nFile);
13075 pNew->db = db;
13076 pNew->aBuffer = (u8*)&pNew[1];
13077 if( zFile ){
@@ -13213,18 +13183,19 @@
13213 ** sqlite3_free().
13214 */
13215 static int zipfileReadData(
13216 FILE *pFile, /* Read from this file */
13217 u8 *aRead, /* Read into this buffer */
13218 int nRead, /* Number of bytes to read */
13219 i64 iOff, /* Offset to read from */
13220 char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */
13221 ){
13222 size_t n;
13223 fseek(pFile, (long)iOff, SEEK_SET);
13224 n = fread(aRead, 1, nRead, pFile);
13225 if( (int)n!=nRead ){
 
13226 *pzErrmsg = sqlite3_mprintf("error in fread()");
13227 return SQLITE_ERROR;
13228 }
13229 return SQLITE_OK;
13230 }
@@ -13237,11 +13208,11 @@
13237 if( nWrite>0 ){
13238 size_t n = nWrite;
13239 fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
13240 n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
13241 if( (int)n!=nWrite ){
13242 pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
13243 return SQLITE_ERROR;
13244 }
13245 pTab->szCurrent += nWrite;
13246 }
13247 return SQLITE_OK;
@@ -13484,10 +13455,11 @@
13484 /*
13485 ** Set (*pzErr) to point to a buffer from sqlite3_malloc() containing a
13486 ** generic corruption message and return SQLITE_CORRUPT;
13487 */
13488 static int zipfileCorrupt(char **pzErr){
 
13489 *pzErr = sqlite3_mprintf("zip archive is corrupt");
13490 return SQLITE_CORRUPT;
13491 }
13492
13493 /*
@@ -13502,11 +13474,11 @@
13502 ** final value of (*ppEntry) undefined.
13503 */
13504 static int zipfileGetEntry(
13505 ZipfileTab *pTab, /* Store any error message here */
13506 const u8 *aBlob, /* Pointer to in-memory file image */
13507 int nBlob, /* Size of aBlob[] in bytes */
13508 FILE *pFile, /* If aBlob==0, read from this file */
13509 i64 iOff, /* Offset of CDS record */
13510 ZipfileEntry **ppEntry /* OUT: Pointer to new object */
13511 ){
13512 u8 *aRead;
@@ -13542,18 +13514,18 @@
13542 rc = SQLITE_NOMEM;
13543 }else{
13544 memset(pNew, 0, sizeof(ZipfileEntry));
13545 rc = zipfileReadCDS(aRead, &pNew->cds);
13546 if( rc!=SQLITE_OK ){
13547 *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
13548 }else if( aBlob==0 ){
13549 rc = zipfileReadData(
13550 pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
13551 );
13552 }else{
13553 aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
13554 if( (iOff + ZIPFILE_LFH_FIXED_SZ + nFile + nExtra)>nBlob ){
13555 rc = zipfileCorrupt(pzErr);
13556 }
13557 }
13558 }
13559
@@ -13574,19 +13546,19 @@
13574 ZipfileLFH lfh;
13575 if( pFile ){
13576 rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
13577 }else{
13578 aRead = (u8*)&aBlob[pNew->cds.iOffset];
13579 if( (pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ)>(unsigned)nBlob ){
13580 rc = zipfileCorrupt(pzErr);
13581 }
13582 }
13583
13584 memset(&lfh, 0, sizeof(lfh));
13585 if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
13586 if( rc==SQLITE_OK ){
13587 pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
13588 pNew->iDataOff += lfh.nFile + lfh.nExtra;
13589 if( aBlob && pNew->cds.szCompressed ){
13590 if( pNew->iDataOff + pNew->cds.szCompressed > nBlob ){
13591 rc = zipfileCorrupt(pzErr);
13592 }else{
@@ -13593,11 +13565,11 @@
13593 pNew->aData = &pNew->aExtra[nExtra];
13594 memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
13595 }
13596 }
13597 }else{
13598 *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
13599 (int)pNew->cds.iOffset
13600 );
13601 }
13602 }
13603
@@ -13617,11 +13589,11 @@
13617 static int zipfileNext(sqlite3_vtab_cursor *cur){
13618 ZipfileCsr *pCsr = (ZipfileCsr*)cur;
13619 int rc = SQLITE_OK;
13620
13621 if( pCsr->pFile ){
13622 i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
13623 zipfileEntryFree(pCsr->pCurrent);
13624 pCsr->pCurrent = 0;
13625 if( pCsr->iNextOff>=iEof ){
13626 pCsr->bEof = 1;
13627 }else{
@@ -13855,16 +13827,16 @@
13855 ** an English language error message may be left in virtual-table pTab.
13856 */
13857 static int zipfileReadEOCD(
13858 ZipfileTab *pTab, /* Return errors here */
13859 const u8 *aBlob, /* Pointer to in-memory file image */
13860 int nBlob, /* Size of aBlob[] in bytes */
13861 FILE *pFile, /* Read from this file if aBlob==0 */
13862 ZipfileEOCD *pEOCD /* Object to populate */
13863 ){
13864 u8 *aRead = pTab->aBuffer; /* Temporary buffer */
13865 int nRead; /* Bytes to read from file */
13866 int rc = SQLITE_OK;
13867
13868 memset(pEOCD, 0, sizeof(ZipfileEOCD));
13869 if( aBlob==0 ){
13870 i64 iOff; /* Offset to read from */
@@ -13881,11 +13853,11 @@
13881 nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
13882 aRead = (u8*)&aBlob[nBlob-nRead];
13883 }
13884
13885 if( rc==SQLITE_OK ){
13886 int i;
13887
13888 /* Scan backwards looking for the signature bytes */
13889 for(i=nRead-20; i>=0; i--){
13890 if( aRead[i]==0x50 && aRead[i+1]==0x4b
13891 && aRead[i+2]==0x05 && aRead[i+3]==0x06
@@ -13892,13 +13864,11 @@
13892 ){
13893 break;
13894 }
13895 }
13896 if( i<0 ){
13897 pTab->base.zErrMsg = sqlite3_mprintf(
13898 "cannot find end of central directory record"
13899 );
13900 return SQLITE_ERROR;
13901 }
13902
13903 aRead += i+4;
13904 pEOCD->iDisk = zipfileRead16(aRead);
@@ -13939,11 +13909,11 @@
13939 pNew->pNext = pBefore;
13940 *pp = pNew;
13941 }
13942 }
13943
13944 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
13945 ZipfileEOCD eocd;
13946 int rc;
13947 int i;
13948 i64 iOff;
13949
@@ -13987,11 +13957,11 @@
13987 zipfileCursorErr(pCsr, "zipfile() function requires an argument");
13988 return SQLITE_ERROR;
13989 }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
13990 static const u8 aEmptyBlob = 0;
13991 const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
13992 int nBlob = sqlite3_value_bytes(argv[0]);
13993 assert( pTab->pFirstEntry==0 );
13994 if( aBlob==0 ){
13995 aBlob = &aEmptyBlob;
13996 nBlob = 0;
13997 }
@@ -14185,23 +14155,23 @@
14185 ZipfileTab *pTab = (ZipfileTab*)pVtab;
14186 int rc = SQLITE_OK;
14187
14188 assert( pTab->pWriteFd==0 );
14189 if( pTab->zFile==0 || pTab->zFile[0]==0 ){
14190 pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
14191 return SQLITE_ERROR;
14192 }
14193
14194 /* Open a write fd on the file. Also load the entire central directory
14195 ** structure into memory. During the transaction any new file data is
14196 ** appended to the archive file, but the central directory is accumulated
14197 ** in main-memory until the transaction is committed. */
14198 pTab->pWriteFd = sqlite3_fopen(pTab->zFile, "ab+");
14199 if( pTab->pWriteFd==0 ){
14200 pTab->base.zErrMsg = sqlite3_mprintf(
14201 "zipfile: failed to open file %s for writing", pTab->zFile
14202 );
14203 rc = SQLITE_ERROR;
14204 }else{
14205 fseek(pTab->pWriteFd, 0, SEEK_END);
14206 pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
14207 rc = zipfileLoadDirectory(pTab, 0, 0);
@@ -14662,11 +14632,11 @@
14662 int nEntry;
14663 ZipfileBuffer body;
14664 ZipfileBuffer cds;
14665 };
14666
14667 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
14668 if( pBuf->n+nByte>pBuf->nAlloc ){
14669 u8 *aNew;
14670 sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
14671 int nReq = pBuf->n + nByte;
14672
@@ -14711,11 +14681,11 @@
14711 u32 iCrc32 = 0; /* crc32 of uncompressed data */
14712
14713 char *zName = 0; /* Path (name) of new entry */
14714 int nName = 0; /* Size of zName in bytes */
14715 char *zFree = 0; /* Free this before returning */
14716 int nByte;
14717
14718 memset(&e, 0, sizeof(e));
14719 p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
14720 if( p==0 ) return;
14721
@@ -24161,28 +24131,28 @@
24161 u8 autoExplain; /* Automatically turn on .explain mode */
24162 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
24163 u8 autoEQPtrace; /* autoEQP is in trace mode */
24164 u8 scanstatsOn; /* True to display scan stats before each finalize */
24165 u8 bAutoScreenWidth; /* Using the TTY to determine screen width */
24166 u8 mFlags; /* MFLG_ECHO and/or MFLG_CRLF */
24167 u8 eMode; /* One of the MODE_ values */
24168 sqlite3_qrf_spec spec; /* Spec to be passed into QRF */
24169 } Mode;
24170
24171 /* Flags for Mode.mFlags */
24172 #define MFLG_ECHO 0x01 /* Echo inputs to output */
24173 #define MFLG_CRLF 0x02 /* Use CR/LF output line endings */
 
24174
24175
24176 /*
24177 ** State information about the database connection is contained in an
24178 ** instance of the following structure.
24179 */
24180 typedef struct ShellState ShellState;
24181 struct ShellState {
24182 sqlite3 *db; /* The database */
24183 int iCompat; /* Compatibility date YYYYMMDD */
24184 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
24185 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
24186 u8 nEqpLevel; /* Depth of the EQP output graph */
24187 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
24188 u8 bSafeMode; /* True to prohibit unsafe operations */
@@ -24190,11 +24160,14 @@
24190 u8 eRestoreState; /* See comments above doAutoDetectRestore() */
24191 unsigned statsOn; /* True to display memory stats before each finalize */
24192 unsigned mEqpLines; /* Mask of vertical lines in the EQP output graph */
24193 u8 nPopOutput; /* Revert .output settings when reaching zero */
24194 u8 nPopMode; /* Revert .mode settings when reaching zero */
 
24195 int inputNesting; /* Track nesting level of .read and other redirects */
 
 
24196 i64 lineno; /* Line number of last line read from in */
24197 const char *zInFile; /* Name of the input file */
24198 int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
24199 FILE *in; /* Read commands from this stream */
24200 FILE *out; /* Write results here */
@@ -24286,10 +24259,11 @@
24286 #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
24287 #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progress
24288 ** callback limit is reached, and for each
24289 ** top-level SQL statement */
24290 #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
 
24291
24292 /* Names of values for Mode.spec.eEsc and Mode.spec.eText
24293 */
24294 static const char *qrfEscNames[] = { "auto", "off", "ascii", "symbol" };
24295 static const char *qrfQuoteNames[] =
@@ -24447,10 +24421,181 @@
24447 ** Limit input nesting via .read or any other input redirect.
24448 ** It's not too expensive, so a generous allowance can be made.
24449 */
24450 #define MAX_INPUT_NESTING 25
24451
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24452
24453 /*
24454 ** Clear a display mode, freeing any allocated memory that it
24455 ** contains.
24456 */
@@ -24534,11 +24679,13 @@
24534 if( pI->eCSep ) modeSetStr(&pM->spec.zColumnSep, aModeStr[pI->eCSep]);
24535 if( pI->eRSep ) modeSetStr(&pM->spec.zRowSep, aModeStr[pI->eRSep]);
24536 if( pI->eNull ) modeSetStr(&pM->spec.zNull, aModeStr[pI->eNull]);
24537 pM->spec.eText = pI->eText;
24538 pM->spec.eBlob = pI->eBlob;
24539 pM->spec.bTitles = pI->bHdr;
 
 
24540 pM->spec.eTitle = pI->eHdr;
24541 if( pI->mFlg & 0x01 ){
24542 pM->spec.bBorder = QRF_No;
24543 }else{
24544 pM->spec.bBorder = QRF_Auto;
@@ -24570,18 +24717,17 @@
24570 p->mode.mFlags = mFlags;
24571 }
24572 }
24573
24574 /*
24575 ** Set the mode to the default according to p->iCompat. It assumed
24576 ** that the mode has already been freed and zeroed prior to calling
24577 ** this routine.
24578 */
24579 static void modeDefault(ShellState *p){
24580 p->mode.spec.iVersion = 1;
24581 p->mode.autoExplain = 1;
24582 if( p->iCompat>=20251115 && (stdin_is_interactive || stdout_is_console) ){
24583 modeChange(p, MODE_TTY);
24584 }else{
24585 modeChange(p, MODE_BATCH);
24586 }
24587 }
@@ -25371,10 +25517,17 @@
25371 ** Progress handler callback.
25372 */
25373 static int progress_handler(void *pClientData) {
25374 ShellState *p = (ShellState*)pClientData;
25375 p->nProgress++;
 
 
 
 
 
 
 
25376 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
25377 cli_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
25378 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
25379 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
25380 return 1;
@@ -25908,10 +26061,12 @@
25908 char *zBuf = sqlite3_malloc64( szVar-5 );
25909 if( zBuf ){
25910 memcpy(zBuf, &zVar[6], szVar-5);
25911 sqlite3_bind_text64(pStmt, i, zBuf, szVar-6, sqlite3_free, SQLITE_UTF8);
25912 }
 
 
25913 #ifdef SQLITE_ENABLE_CARRAY
25914 }else if( strncmp(zVar, "$carray_", 8)==0 ){
25915 static char *azColorNames[] = {
25916 "azure", "black", "blue", "brown", "cyan", "fuchsia", "gold",
25917 "gray", "green", "indigo", "khaki", "lime", "magenta", "maroon",
@@ -26167,27 +26322,36 @@
26167 pArg->pStmt = pStmt;
26168 }
26169
26170 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
26171 isExplain = sqlite3_stmt_isexplain(pStmt);
26172 if( pArg && pArg->mode.autoEQP && isExplain==0 ){
26173 int triggerEQP = 0;
 
 
26174 disable_debug_trace_modes();
26175 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
26176 if( pArg->mode.autoEQP>=AUTOEQP_trigger ){
26177 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
26178 }
26179 sqlite3_reset(pStmt);
26180 spec.eStyle = QRF_STYLE_Auto;
26181 sqlite3_stmt_explain(pStmt, 2-(pArg->mode.autoEQP>=AUTOEQP_full));
26182 sqlite3_format_query_result(pStmt, &spec, 0);
 
 
 
 
 
 
26183 if( pArg->mode.autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
26184 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
26185 }
26186 sqlite3_reset(pStmt);
26187 sqlite3_stmt_explain(pStmt, 0);
26188 restore_debug_trace_modes();
 
26189 }
26190
26191 bind_prepared_stmt(pArg, pStmt);
26192 if( isExplain && pArg->mode.autoExplain ){
26193 spec.eStyle = isExplain==1 ? QRF_STYLE_Explain : QRF_STYLE_Eqp;
@@ -26604,12 +26768,12 @@
26604 ".bail on|off Stop after hitting an error. Default OFF",
26605 #ifndef SQLITE_SHELL_FIDDLE
26606 ".cd DIRECTORY Change the working directory to DIRECTORY",
26607 #endif
26608 ".changes on|off Show number of rows changed by SQL",
 
26609 #ifndef SQLITE_SHELL_FIDDLE
26610 ".check GLOB Fail if output since .testcase does not match",
26611 ".clone NEWDB Clone data into NEWDB from the existing database",
26612 #endif
26613 ".connection [close] [#] Open or close an auxiliary database connection",
26614 ".crlf ?on|off? Whether or not to use \\r\\n line endings",
26615 ".databases List names and files of attached databases",
@@ -26721,10 +26885,11 @@
26721 ".progress N Invoke progress handler after every N opcodes",
26722 " --limit N Interrupt after N progress callbacks",
26723 " --once Do no more than one progress interrupt",
26724 " --quiet|-q No output except at interrupts",
26725 " --reset Reset the count for each input and interrupt",
 
26726 #endif
26727 ".prompt MAIN CONTINUE Replace the standard prompts",
26728 #ifndef SQLITE_SHELL_FIDDLE
26729 ".quit Stop interpreting input stream, exit if primary.",
26730 ".read FILE Read input from FILE or command output",
@@ -26785,17 +26950,15 @@
26785 " vmstep Show the virtual machine step count only",
26786 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
26787 ".system CMD ARGS... Run CMD ARGS... in a system shell",
26788 #endif
26789 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
26790 #ifndef SQLITE_SHELL_FIDDLE
26791 ",testcase NAME Begin redirecting output to 'testcase-out.txt'",
26792 #endif
26793 ",testctrl CMD ... Run various sqlite3_test_control() operations",
26794 " Run \".testctrl\" with no arguments for details",
26795 ".timeout MS Try opening locked tables for MS milliseconds",
26796 ".timer on|off Turn SQL timer on or off",
26797 #ifndef SQLITE_OMIT_TRACE
26798 ".trace ?OPTIONS? Output each SQL statement as it is run",
26799 " FILE Send output to FILE",
26800 " stdout Send output to stdout",
26801 " stderr Send output to stderr",
@@ -26836,19 +26999,33 @@
26836 "USAGE: .import [OPTIONS] FILE TABLE\n"
26837 "\n"
26838 "Import CSV or similar text from FILE into TABLE. If TABLE does\n"
26839 "not exist, it is created using the first row of FILE as the column\n"
26840 "names. If FILE begins with \"|\" then it is a command that is run\n"
26841 "and the output from the command is used as the input data.\n"
 
 
 
 
 
 
26842 "\n"
26843 "FILE is assumed to be in a CSV format, unless the current mode\n"
26844 "is \"ascii\" or \"tabs\" or unless one of the options below specify\n"
26845 "an alternative.\n"
 
 
26846 "\n"
26847 "Options:\n"
26848 " --ascii Use \\037 and \\036 as column and row separators on input\n"
 
 
 
26849 " --csv Input is standard RFC-4180 CSV.\n"
 
 
 
26850 " --schema S When creating TABLE, put it in schema S\n"
26851 " --skip N Ignore the first N rows of input\n"
26852 " -v Verbose mode\n"
26853 },
26854 { ".mode",
@@ -26930,23 +27107,17 @@
26930 " --bom Prepend a byte-order mark to the output\n"
26931 " -e Accumulate output in a temporary text file then\n"
26932 " launch a text editor when the redirection ends.\n"
26933 " --error-prefix X Use X as the left-margin prefix for error messages.\n"
26934 " Set to an empty string to restore the default.\n"
26935 " --glob GLOB Raise an error if the memory buffer does not match\n"
26936 " the GLOB pattern.\n"
26937 " --keep Continue using the same \"memory\" buffer. Do not\n"
26938 " reset it or delete it. Useful in combination with\n"
26939 " --glob, --not-glob, and/or --verify.\n"
26940 " ---notglob GLOB Raise an error if the memory buffer does not match\n"
26941 " the GLOB pattern.\n"
26942 " --plain Use plain text rather than HTML tables with -w\n"
26943 " --show Write the memory buffer to the screen, for debugging.\n"
26944 " --verify ENDMARK Read subsequent lines of text until the first line\n"
26945 " that matches ENDMARK. Discard the ENDMARK. Compare\n"
26946 " the text against the accumulated output in memory and\n"
26947 " raise an error if there are any differences.\n"
26948 " -w Show the output in a web browser. Output is\n"
26949 " written into a temporary HTML file until the\n"
26950 " redirect ends, then the web browser is launched.\n"
26951 " Query results are shown as HTML tables, unless\n"
26952 " the --plain is used too.\n"
@@ -26970,10 +27141,39 @@
26970 " file in a web browser\n"
26971 " -x Show the output in a spreadsheet. Output is\n"
26972 " written to a temp file as CSV then the spreadsheet\n"
26973 " is launched when\n"
26974 },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26975 };
26976
26977 /*
26978 ** Return a pointer to usage text for zCmd, or NULL if none exists.
26979 */
@@ -27193,10 +27393,56 @@
27193 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
27194 }
27195 return 1;
27196 }
27197 #endif
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27198
27199 /*
27200 ** Try to deduce the type of file for zName based on its content. Return
27201 ** one of the SHELL_OPEN_* constants.
27202 **
@@ -27206,24 +27452,16 @@
27206 ** the type cannot be determined from content.
27207 */
27208 int deduceDatabaseType(const char *zName, int dfltZip, int openFlags){
27209 FILE *f;
27210 size_t n;
27211 sqlite3 *db = 0;
27212 sqlite3_stmt *pStmt = 0;
27213 int rc = SHELL_OPEN_UNSPEC;
27214 char zBuf[100];
27215 if( access(zName,0)!=0 ) goto database_type_by_name;
27216 if( sqlite3_open_v2(zName, &db, openFlags, 0)==SQLITE_OK
27217 && sqlite3_prepare_v2(db,"SELECT count(*) FROM sqlite_schema",-1,&pStmt,0)
27218 ==SQLITE_OK
27219 && sqlite3_step(pStmt)==SQLITE_ROW
27220 ){
27221 rc = SHELL_OPEN_NORMAL;
27222 }
27223 sqlite3_finalize(pStmt);
27224 sqlite3_close(db);
27225 if( rc==SHELL_OPEN_NORMAL ) return SHELL_OPEN_NORMAL;
27226 f = sqlite3_fopen(zName, "rb");
27227 if( f==0 ) goto database_type_by_name;
27228 n = fread(zBuf, 16, 1, f);
27229 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
@@ -27253,10 +27491,39 @@
27253 }else{
27254 rc = SHELL_OPEN_NORMAL;
27255 }
27256 return rc;
27257 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27258
27259 #ifndef SQLITE_OMIT_DESERIALIZE
27260 /*
27261 ** Reconstruct an in-memory database using the output from the "dbtotxt"
27262 ** program. Read content from the file in p->aAuxDb[].zDbFilename.
@@ -27899,20 +28166,24 @@
27899 typedef struct ImportCtx ImportCtx;
27900 struct ImportCtx {
27901 const char *zFile; /* Name of the input file */
27902 FILE *in; /* Read the CSV text from this input stream */
27903 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */
 
27904 char *z; /* Accumulated text for a field */
 
27905 i64 n; /* Number of bytes in z */
27906 i64 nAlloc; /* Space allocated for z[] */
27907 int nLine; /* Current line number */
27908 int nRow; /* Number of rows imported */
27909 int nErr; /* Number of errors encountered */
27910 int bNotFirst; /* True if one or more bytes already read */
27911 int cTerm; /* Character that terminated the most recent field */
27912 int cColSep; /* The column separator character. (Usually ",") */
27913 int cRowSep; /* The row separator character. (Usually "\n") */
 
 
27914 };
27915
27916 /* Clean up resourced used by an ImportCtx */
27917 static void import_cleanup(ImportCtx *p){
27918 if( p->in!=0 && p->xCloser!=0 ){
@@ -27919,13 +28190,32 @@
27919 p->xCloser(p->in);
27920 p->in = 0;
27921 }
27922 sqlite3_free(p->z);
27923 p->z = 0;
 
 
 
 
27924 }
27925
27926 /* Append a single byte to z[] */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27927 static void import_append_char(ImportCtx *p, int c){
27928 if( p->n+1>=p->nAlloc ){
27929 p->nAlloc += p->nAlloc + 100;
27930 p->z = sqlite3_realloc64(p->z, p->nAlloc);
27931 shell_check_oom(p->z);
@@ -27937,12 +28227,12 @@
27937 ** with the option of having a separator other than ",".
27938 **
27939 ** + Input comes from p->in.
27940 ** + Store results in p->z of length p->n. Space to hold p->z comes
27941 ** from sqlite3_malloc64().
27942 ** + Use p->cSep as the column separator. The default is ",".
27943 ** + Use p->rSep as the row separator. The default is "\n".
27944 ** + Keep track of the line number in p->nLine.
27945 ** + Store the character that terminates the field in p->cTerm. Store
27946 ** EOF on end-of-file.
27947 ** + Report syntax errors on stderr
27948 */
@@ -27949,23 +28239,30 @@
27949 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
27950 int c;
27951 int cSep = (u8)p->cColSep;
27952 int rSep = (u8)p->cRowSep;
27953 p->n = 0;
27954 c = fgetc(p->in);
27955 if( c==EOF || seenInterrupt ){
27956 p->cTerm = EOF;
27957 return 0;
27958 }
27959 if( c=='"' ){
27960 int pc, ppc;
27961 int startLine = p->nLine;
27962 int cQuote = c;
 
27963 pc = ppc = 0;
27964 while( 1 ){
27965 c = fgetc(p->in);
27966 if( c==rSep ) p->nLine++;
 
 
 
 
 
 
27967 if( c==cQuote ){
27968 if( pc==cQuote ){
27969 pc = 0;
27970 continue;
27971 }
@@ -27979,11 +28276,11 @@
27979 p->cTerm = c;
27980 break;
27981 }
27982 if( pc==cQuote && c!='\r' ){
27983 cli_printf(stderr,"%s:%d: unescaped %c character\n",
27984 p->zFile, p->nLine, cQuote);
27985 }
27986 if( c==EOF ){
27987 cli_printf(stderr,"%s:%d: unterminated %c-quoted field\n",
27988 p->zFile, startLine, cQuote);
27989 p->cTerm = c;
@@ -27994,26 +28291,28 @@
27994 pc = c;
27995 }
27996 }else{
27997 /* If this is the first field being parsed and it begins with the
27998 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
 
27999 if( (c&0xff)==0xef && p->bNotFirst==0 ){
28000 import_append_char(p, c);
28001 c = fgetc(p->in);
28002 if( (c&0xff)==0xbb ){
28003 import_append_char(p, c);
28004 c = fgetc(p->in);
28005 if( (c&0xff)==0xbf ){
28006 p->bNotFirst = 1;
28007 p->n = 0;
28008 return csv_read_one_field(p);
28009 }
28010 }
28011 }
28012 while( c!=EOF && c!=cSep && c!=rSep ){
 
28013 import_append_char(p, c);
28014 c = fgetc(p->in);
28015 }
28016 if( c==rSep ){
28017 p->nLine++;
28018 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
28019 }
@@ -28027,12 +28326,12 @@
28027 /* Read a single field of ASCII delimited text.
28028 **
28029 ** + Input comes from p->in.
28030 ** + Store results in p->z of length p->n. Space to hold p->z comes
28031 ** from sqlite3_malloc64().
28032 ** + Use p->cSep as the column separator. The default is "\x1F".
28033 ** + Use p->rSep as the row separator. The default is "\x1E".
28034 ** + Keep track of the row number in p->nLine.
28035 ** + Store the character that terminates the field in p->cTerm. Store
28036 ** EOF on end-of-file.
28037 ** + Report syntax errors on stderr
28038 */
@@ -28039,18 +28338,18 @@
28039 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
28040 int c;
28041 int cSep = (u8)p->cColSep;
28042 int rSep = (u8)p->cRowSep;
28043 p->n = 0;
28044 c = fgetc(p->in);
28045 if( c==EOF || seenInterrupt ){
28046 p->cTerm = EOF;
28047 return 0;
28048 }
28049 while( c!=EOF && c!=cSep && c!=rSep ){
28050 import_append_char(p, c);
28051 c = fgetc(p->in);
28052 }
28053 if( c==rSep ){
28054 p->nLine++;
28055 }
28056 p->cTerm = c;
@@ -30151,11 +30450,11 @@
30151 ;
30152 static const char * const zCollectVar = "\
30153 SELECT\
30154 '('||x'0a'\
30155 || group_concat(\
30156 cname||' TEXT',\
30157 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
30158 ||')' AS ColsSpec \
30159 FROM (\
30160 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
30161 FROM ColNames ORDER BY cpos\
@@ -30351,19 +30650,33 @@
30351 ** USAGE: .import [OPTIONS] FILE TABLE
30352 **
30353 ** Import CSV or similar text from FILE into TABLE. If TABLE does
30354 ** not exist, it is created using the first row of FILE as the column
30355 ** names. If FILE begins with "|" then it is a command that is run
30356 ** and the output from the command is used as the input data.
 
 
 
 
 
 
30357 **
30358 ** FILE is assumed to be in a CSV format, unless the current mode
30359 ** is "ascii" or "tabs" or unless one of the options below specify
30360 ** an alternative.
 
 
30361 **
30362 ** Options:
30363 ** --ascii Use \037 and \036 as column and row separators on input
 
 
 
30364 ** --csv Input is standard RFC-4180 CSV.
 
 
 
30365 ** --schema S When creating TABLE, put it in schema S
30366 ** --skip N Ignore the first N rows of input
30367 ** -v Verbose mode
30368 */
30369 static int dotCmdImport(ShellState *p){
@@ -30375,17 +30688,16 @@
30375 sqlite3_stmt *pStmt = NULL; /* A statement */
30376 int nCol; /* Number of columns in the table */
30377 i64 nByte; /* Number of bytes in an SQL string */
30378 int i, j; /* Loop counters */
30379 int needCommit; /* True to COMMIT or ROLLBACK at end */
30380 int nSep; /* Number of bytes in spec.zColumnSep */
30381 char *zSql = 0; /* An SQL statement */
30382 ImportCtx sCtx; /* Reader context */
30383 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
30384 int eVerbose = 0; /* Larger for more console output */
30385 i64 nSkip = 0; /* Initial lines to skip */
30386 int useOutputMode = 1; /* Use output mode to determine separators */
30387 char *zCreate = 0; /* CREATE TABLE statement text */
30388 int rc; /* Result code */
30389
30390 failIfSafeMode(p, "cannot run .import in safe mode");
30391 memset(&sCtx, 0, sizeof(sCtx));
@@ -30411,70 +30723,71 @@
30411 }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
30412 zSchema = azArg[++i];
30413 }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
30414 nSkip = integerValue(azArg[++i]);
30415 }else if( cli_strcmp(z,"-ascii")==0 ){
30416 sCtx.cColSep = SEP_Unit[0];
30417 sCtx.cRowSep = SEP_Record[0];
30418 xRead = ascii_read_one_field;
30419 useOutputMode = 0;
30420 }else if( cli_strcmp(z,"-csv")==0 ){
30421 sCtx.cColSep = ',';
30422 sCtx.cRowSep = '\n';
30423 xRead = csv_read_one_field;
30424 useOutputMode = 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30425 }else{
30426 dotCmdError(p, i, "unknown option", 0);
30427 return 1;
30428 }
30429 }
30430 if( zTable==0 ){
30431 cli_printf(p->out, "ERROR: missing %s argument\n",
30432 zFile==0 ? "FILE" : "TABLE");
30433 return 1;
30434 }
30435 seenInterrupt = 0;
30436 open_db(p, 0);
30437 if( useOutputMode ){
30438 /* If neither the --csv or --ascii options are specified, then set
30439 ** the column and row separator characters from the output mode. */
30440 if( p->mode.spec.zColumnSep==0 ){
30441 modeSetStr(&p->mode.spec.zColumnSep, ",");
30442 nSep = 1;
30443 }else if( (nSep = strlen30(p->mode.spec.zColumnSep))==0 ){
30444 eputz("Error: non-null column separator required for import\n");
30445 return 1;
30446 }
30447 if( nSep>1 ){
30448 eputz("Error: multi-character column separators not allowed"
30449 " for import\n");
30450 return 1;
30451 }
30452 if( p->mode.spec.zRowSep==0 ){
30453 modeSetStr(&p->mode.spec.zRowSep, "\n");
30454 nSep = 1;
30455 }else if( (nSep = strlen30(p->mode.spec.zRowSep))==0 ){
30456 eputz("Error: non-null row separator required for import\n");
30457 return 1;
30458 }
30459 if( nSep==2 && p->mode.eMode==MODE_Csv
30460 && cli_strcmp(p->mode.spec.zRowSep,SEP_CrLf)==0
30461 ){
30462 /* When importing CSV (only), if the row separator is set to the
30463 ** default output row separator, change it to the default input
30464 ** row separator. This avoids having to maintain different input
30465 ** and output row separators. */
30466 modeSetStr(&p->mode.spec.zRowSep, SEP_Row);
30467 nSep = strlen30(p->mode.spec.zRowSep);
30468 }
30469 if( nSep>1 ){
30470 eputz("Error: multi-character row separators not allowed"
30471 " for import\n");
30472 return 1;
30473 }
30474 sCtx.cColSep = (u8)p->mode.spec.zColumnSep[0];
30475 sCtx.cRowSep = (u8)p->mode.spec.zRowSep[0];
30476 }
30477 sCtx.zFile = zFile;
30478 sCtx.nLine = 1;
30479 if( sCtx.zFile[0]=='|' ){
30480 #ifdef SQLITE_OMIT_POPEN
@@ -30483,19 +30796,58 @@
30483 #else
30484 sCtx.in = sqlite3_popen(sCtx.zFile+1, "r");
30485 sCtx.zFile = "<pipe>";
30486 sCtx.xCloser = pclose;
30487 #endif
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30488 }else{
30489 sCtx.in = sqlite3_fopen(sCtx.zFile, "rb");
30490 sCtx.xCloser = fclose;
30491 }
30492 if( sCtx.in==0 ){
30493 cli_printf(stderr,"Error: cannot open \"%s\"\n", zFile);
 
30494 return 1;
30495 }
30496 if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
30497 char zSep[2];
30498 zSep[1] = 0;
30499 zSep[0] = sCtx.cColSep;
30500 cli_puts("Column separator ", p->out);
30501 output_c_string(p->out, zSep);
@@ -30648,10 +31000,14 @@
30648 if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){
30649 z = "";
30650 }
30651 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
30652 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
 
 
 
 
30653 cli_printf(stderr,"%s:%d: expected %d columns but found %d"
30654 " - filling the rest with NULL\n",
30655 sCtx.zFile, startLine, nCol, i+1);
30656 i += 2;
30657 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
@@ -30671,10 +31027,11 @@
30671 rc = sqlite3_reset(pStmt);
30672 if( rc!=SQLITE_OK ){
30673 cli_printf(stderr,"%s:%d: INSERT failed: %s\n",
30674 sCtx.zFile, startLine, sqlite3_errmsg(p->db));
30675 sCtx.nErr++;
 
30676 }else{
30677 sCtx.nRow++;
30678 }
30679 }
30680 }while( sCtx.cTerm!=EOF );
@@ -30683,13 +31040,13 @@
30683 sqlite3_finalize(pStmt);
30684 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
30685 if( eVerbose>0 ){
30686 cli_printf(p->out,
30687 "Added %d rows with %d errors using %d lines of input\n",
30688 sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
30689 }
30690 return 0;
30691 }
30692
30693
30694 /*
30695 ** This function computes what to show the user about the configured
@@ -31100,10 +31457,11 @@
31100 if( k<0 ){
31101 dotCmdError(p, i, "bad --titles value","%z", zErr);
31102 return 1;
31103 }
31104 p->mode.spec.bTitles = k>=1 ? QRF_Yes : QRF_No;
 
31105 p->mode.spec.eTitle = k>1 ? k-1 : aModeInfo[p->mode.eMode].eHdr;
31106 chng = 1;
31107 }else if( optionMatch(z,"widths") || optionMatch(z,"width") ){
31108 int nWidth = 0;
31109 short int *aWidth;
@@ -31328,23 +31686,17 @@
31328 ** --bom Prepend a byte-order mark to the output
31329 ** -e Accumulate output in a temporary text file then
31330 ** launch a text editor when the redirection ends.
31331 ** --error-prefix X Use X as the left-margin prefix for error messages.
31332 ** Set to an empty string to restore the default.
31333 ** --glob GLOB Raise an error if the memory buffer does not match
31334 ** the GLOB pattern.
31335 ** --keep Continue using the same "memory" buffer. Do not
31336 ** reset it or delete it. Useful in combination with
31337 ** --glob, --not-glob, and/or --verify.
31338 ** ---notglob GLOB Raise an error if the memory buffer does not match
31339 ** the GLOB pattern.
31340 ** --plain Use plain text rather than HTML tables with -w
31341 ** --show Write the memory buffer to the screen, for debugging.
31342 ** --verify ENDMARK Read subsequent lines of text until the first line
31343 ** that matches ENDMARK. Discard the ENDMARK. Compare
31344 ** the text against the accumulated output in memory and
31345 ** raise an error if there are any differences.
31346 ** -w Show the output in a web browser. Output is
31347 ** written into a temporary HTML file until the
31348 ** redirect ends, then the web browser is launched.
31349 ** Query results are shown as HTML tables, unless
31350 ** the --plain is used too.
@@ -31382,13 +31734,11 @@
31382 char *zFile = 0; /* The FILE argument */
31383 int i; /* Loop counter */
31384 int eMode = 0; /* 0: .outout/.once, 'x'=.excel, 'w'=.www */
31385 int bOnce = 0; /* 0: .output, 1: .once, 2: .excel/.www */
31386 int bPlain = 0; /* --plain option */
31387 int bKeep = 0; /* --keep option */
31388 char *zCheck = 0; /* Argument to --glob, --notglob, --verify */
31389 int eCheck = 0; /* 1: --glob, 2: --notglob, 3: --verify */
31390 static const char *zBomUtf8 = "\357\273\277";
31391 const char *zBom = 0;
31392 char c = azArg[0][0];
31393 int n = strlen30(azArg[0]);
31394
@@ -31410,36 +31760,21 @@
31410 zBom = zBomUtf8;
31411 }else if( cli_strcmp(z,"-plain")==0 ){
31412 bPlain = 1;
31413 }else if( c=='o' && z[0]=='1' && z[1]!=0 && z[2]==0
31414 && (z[1]=='x' || z[1]=='e' || z[1]=='w') ){
31415 if( bKeep || eMode || eCheck ){
31416 dotCmdError(p, i, "incompatible with prior options",0);
31417 goto dotCmdOutput_error;
31418 }
31419 eMode = z[1];
31420 }else if( cli_strcmp(z,"-keep")==0 ){
31421 bKeep = 1;
31422 }else if( cli_strcmp(z,"-show")==0 ){
31423 if( cli_output_capture ){
31424 sqlite3_fprintf(stdout, "%s", sqlite3_str_value(cli_output_capture));
31425 }
 
31426 bKeep = 1;
31427 }else if( cli_strcmp(z,"-glob")==0
31428 || cli_strcmp(z,"-notglob")==0
31429 || cli_strcmp(z,"-verify")==0
31430 ){
31431 if( eCheck || eMode ){
31432 dotCmdError(p, i, "incompatible with prior options",0);
31433 goto dotCmdOutput_error;
31434 }
31435 if( i+1>=nArg ){
31436 dotCmdError(p, i, "missing argument", 0);
31437 goto dotCmdOutput_error;
31438 }
31439 zCheck = azArg[++i];
31440 eCheck = z[1]=='g' ? 1 : z[1]=='n' ? 2 : 3;
31441 }else if( optionMatch(z,"error-prefix") ){
31442 if( i+1>=nArg ){
31443 dotCmdError(p, i, "missing argument", 0);
31444 return 1;
31445 }
@@ -31450,11 +31785,11 @@
31450 dotCmdError(p, i, "unknown option", 0);
31451 sqlite3_free(zFile);
31452 return 1;
31453 }
31454 }else if( zFile==0 && eMode==0 ){
31455 if( bKeep || eCheck ){
31456 dotCmdError(p, i, "incompatible with prior options",0);
31457 goto dotCmdOutput_error;
31458 }
31459 if( cli_strcmp(z, "memory")==0 && bOnce ){
31460 dotCmdError(p, 0, "cannot redirect to \"memory\"", 0);
@@ -31486,53 +31821,10 @@
31486 if( bOnce ){
31487 p->nPopOutput = 2;
31488 }else{
31489 p->nPopOutput = 0;
31490 }
31491 if( eCheck ){
31492 char *zTest;
31493 if( cli_output_capture ){
31494 zTest = sqlite3_str_value(cli_output_capture);
31495 }else{
31496 zTest = "";
31497 }
31498 p->nTestRun++;
31499 if( eCheck==3 ){
31500 int nCheck = strlen30(zCheck);
31501 sqlite3_str *pPattern = sqlite3_str_new(p->db);
31502 char *zPattern;
31503 sqlite3_int64 iStart = p->lineno;
31504 char zLine[2000];
31505 while( sqlite3_fgets(zLine,sizeof(zLine),p->in) ){
31506 if( strchr(zLine,'\n') ) p->lineno++;
31507 if( cli_strncmp(zCheck,zLine,nCheck)==0 ) break;
31508 sqlite3_str_appendall(pPattern, zLine);
31509 }
31510 zPattern = sqlite3_str_finish(pPattern);
31511 if( cli_strcmp(zPattern,zTest)!=0 ){
31512 sqlite3_fprintf(stderr,
31513 "%s:%lld: --verify does matches prior output\n",
31514 p->zInFile, iStart);
31515 p->nTestErr++;
31516 }
31517 sqlite3_free(zPattern);
31518 }else{
31519 char *zGlob = sqlite3_mprintf("*%s*", zCheck);
31520 if( eCheck==1 && sqlite3_strglob(zGlob, zTest)!=0 ){
31521 sqlite3_fprintf(stderr,
31522 "%s:%lld: --glob \"%s\" does not match prior output\n",
31523 p->zInFile, p->lineno, zCheck);
31524 p->nTestErr++;
31525 }else if( eCheck==2 && sqlite3_strglob(zGlob, zTest)==0 ){
31526 sqlite3_fprintf(stderr,
31527 "%s:%lld: --notglob \"%s\" matches prior output\n",
31528 p->zInFile, p->lineno, zCheck);
31529 p->nTestErr++;
31530 }
31531 sqlite3_free(zGlob);
31532 }
31533 }
31534 if( !bKeep ) output_reset(p);
31535 #ifndef SQLITE_NOHAVE_SYSTEM
31536 if( eMode=='e' || eMode=='x' || eMode=='w' ){
31537 p->doXdgOpen = 1;
31538 modePush(p);
@@ -31609,10 +31901,199 @@
31609
31610 dotCmdOutput_error:
31611 sqlite3_free(zFile);
31612 return 1;
31613 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31614
31615 /*
31616 ** Enlarge the space allocated in p->dot so that it can hold more
31617 ** than nArg parsed command-line arguments.
31618 */
@@ -31641,11 +32122,11 @@
31641 free(p->dot.zCopy);
31642 z = p->dot.zCopy = strdup(zLine);
31643 shell_check_oom(z);
31644 szLine = strlen(z);
31645 while( szLine>0 && IsSpace(z[szLine-1]) ) szLine--;
31646 if( szLine>0 && z[szLine-1]==';' && p->iCompat>=20251115 ){
31647 szLine--;
31648 while( szLine>0 && IsSpace(z[szLine-1]) ) szLine--;
31649 }
31650 z[szLine] = 0;
31651 parseDotRealloc(p, 2);
@@ -31861,35 +32342,17 @@
31861 eputz("Usage: .changes on|off\n");
31862 rc = 1;
31863 }
31864 }else
31865
31866 #ifndef SQLITE_SHELL_FIDDLE
31867 /* Cancel output redirection, if it is currently set (by .testcase)
31868 ** Then read the content of the testcase-out.txt file and compare against
31869 ** azArg[1]. If there are differences, report an error and exit.
31870 */
31871 if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
31872 char *zRes = 0;
31873 output_reset(p);
31874 if( nArg!=2 ){
31875 eputz("Usage: .check GLOB-PATTERN\n");
31876 rc = 2;
31877 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
31878 rc = 2;
31879 }else if( testcase_glob(azArg[1],zRes)==0 ){
31880 cli_printf(stderr,
31881 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
31882 p->zTestcase, azArg[1], zRes);
31883 rc = 1;
31884 }else{
31885 cli_printf(p->out, "testcase-%s ok\n", p->zTestcase);
31886 p->nCheck++;
31887 }
31888 sqlite3_free(zRes);
31889 }else
31890 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
31891
31892 #ifndef SQLITE_SHELL_FIDDLE
31893 if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
31894 failIfSafeMode(p, "cannot run .clone in safe mode");
31895 if( nArg==2 ){
@@ -32468,10 +32931,11 @@
32468 }else
32469
32470 if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
32471 if( nArg==2 ){
32472 p->mode.spec.bTitles = booleanValue(azArg[1]) ? QRF_Yes : QRF_No;
 
32473 p->mode.spec.eTitle = aModeInfo[p->mode.eMode].eHdr;
32474 }else{
32475 eputz("Usage: .headers on|off\n");
32476 rc = 1;
32477 }
@@ -32521,14 +32985,14 @@
32521 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
32522 goto meta_command_exit;
32523 }
32524 zSql = sqlite3_mprintf(
32525 "SELECT rootpage, 0 FROM sqlite_schema"
32526 " WHERE name='%q' AND type='index'"
32527 "UNION ALL "
32528 "SELECT rootpage, 1 FROM sqlite_schema"
32529 " WHERE name='%q' AND type='table'"
32530 " AND sql LIKE '%%without%%rowid%%'",
32531 azArg[1], azArg[1]
32532 );
32533 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
32534 sqlite3_free(zSql);
@@ -32682,13 +33146,14 @@
32682 goto meta_command_exit;
32683 }
32684 if( nArg==3 ){
32685 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
32686 (int)integerValue(azArg[2]));
 
 
 
32687 }
32688 cli_printf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName,
32689 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
32690 }
32691 }else
32692
32693 if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
32694 open_db(p, 0);
@@ -33027,10 +33492,23 @@
33027 continue;
33028 }
33029 if( cli_strcmp(z,"once")==0 ){
33030 p->flgProgress |= SHELL_PROGRESS_ONCE;
33031 continue;
 
 
 
 
 
 
 
 
 
 
 
 
 
33032 }
33033 if( cli_strcmp(z,"limit")==0 ){
33034 if( i+1>=nArg ){
33035 eputz("Error: missing argument on --limit\n");
33036 rc = 1;
@@ -33233,21 +33711,22 @@
33233 || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
33234 || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
33235 || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
33236 if( isSchema ){
33237 cli_printf(p->out,
33238 "CREATE TABLE %s (\n"
33239 " type text,\n"
33240 " name text,\n"
33241 " tbl_name text,\n"
33242 " rootpage integer,\n"
33243 " sql text\n"
33244 ");\n", zName);
 
 
33245 }
33246 }
33247 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
33248 -1, &pStmt, 0);
33249 if( rc ){
33250 shellDatabaseError(p->db);
33251 sqlite3_finalize(pStmt);
33252
33253 rc = 1;
@@ -33255,11 +33734,11 @@
33255 }
33256 pSql = sqlite3_str_new(p->db);
33257 sqlite3_str_appendf(pSql, "SELECT sql FROM", 0);
33258 iSchema = 0;
33259 while( sqlite3_step(pStmt)==SQLITE_ROW ){
33260 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
33261 char zScNum[30];
33262 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
33263 sqlite3_str_appendall(pSql, zDiv);
33264 zDiv = " UNION ALL ";
33265 if( sqlite3_stricmp(zDb, "main")==0 ){
@@ -33275,11 +33754,12 @@
33275 " AS sql, type, tbl_name, name, rowid, %d AS snum, %Q as sname",
33276 ++iSchema, zDb);
33277 sqlite3_str_appendf(pSql," FROM \"%w\".sqlite_schema", zDb);
33278 }
33279 sqlite3_finalize(pStmt);
33280 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
 
33281 if( zName ){
33282 sqlite3_str_appendall(pSql,
33283 " UNION ALL SELECT shell_module_schema(name),"
33284 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list");
33285 }
@@ -33299,11 +33779,11 @@
33299 }else{
33300 sqlite3_str_appendf(pSql, " LIKE %Q ESCAPE '\\' AND ", zName);
33301 }
33302 }
33303 if( bNoSystemTabs ){
33304 sqlite3_str_appendf(pSql, " name NOT LIKE 'sqlite__%%' ESCALE '_' AND ");
33305 }
33306 sqlite3_str_appendf(pSql, "sql IS NOT NULL ORDER BY snum, rowid");
33307 if( bDebug ){
33308 cli_printf(p->out, "SQL: %s;\n", sqlite3_str_value(pSql));
33309 }else{
@@ -34017,25 +34497,15 @@
34017 sqlite3_str_free(pSql);
34018 modePop(p);
34019 if( rc ) return shellDatabaseError(p->db);
34020 }else
34021
34022 #ifndef SQLITE_SHELL_FIDDLE
34023 /* Begin redirecting output to the file "testcase-out.txt" */
34024 if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
34025 output_reset(p);
34026 p->out = output_file_open(p, "testcase-out.txt");
34027 if( p->out==0 ){
34028 eputz("Error: cannot open 'testcase-out.txt'\n");
34029 }
34030 if( nArg>=2 ){
34031 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
34032 }else{
34033 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
34034 }
34035 }else
34036 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
34037
34038 #ifndef SQLITE_UNTESTABLE
34039 if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
34040 static const struct {
34041 const char *zCtrlName; /* Name of a test-control option */
@@ -34527,17 +34997,21 @@
34527 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
34528 }else
34529
34530 if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
34531 if( nArg==2 ){
34532 enableTimer = booleanValue(azArg[1]);
34533 if( enableTimer && !HAS_TIMER ){
 
 
 
 
34534 eputz("Error: timer not available on this system.\n");
34535 enableTimer = 0;
34536 }
34537 }else{
34538 eputz("Usage: .timer on|off\n");
34539 rc = 1;
34540 }
34541 }else
34542
34543 #ifndef SQLITE_OMIT_TRACE
@@ -34708,10 +35182,11 @@
34708 if( p->nPopOutput ){
34709 p->nPopOutput--;
34710 if( p->nPopOutput==0 ) output_reset(p);
34711 }
34712 p->bSafeMode = p->bSafeModePersist;
 
34713 return rc;
34714 }
34715
34716 /* Line scan result and intermediate states (supporting scan resumption)
34717 */
@@ -34944,13 +35419,13 @@
34944 char *zErrMsg = 0;
34945
34946 open_db(p, 0);
34947 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
34948 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
34949 BEGIN_TIMER;
34950 rc = shell_exec(p, zSql, &zErrMsg);
34951 END_TIMER(p->out);
34952 if( rc || zErrMsg ){
34953 char zPrefix[100];
34954 const char *zErrorTail;
34955 const char *zErrorType;
34956 if( zErrMsg==0 ){
@@ -35351,11 +35826,10 @@
35351 " -bail stop after hitting an error\n"
35352 " -batch force batch I/O\n"
35353 " -box set output mode to 'box'\n"
35354 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
35355 " -column set output mode to 'column'\n"
35356 " -compat YYYYMMDD set default options for date YYYYMMDD\n"
35357 " -csv set output mode to 'csv'\n"
35358 #if !defined(SQLITE_OMIT_DESERIALIZE)
35359 " -deserialize open the database using sqlite3_deserialize()\n"
35360 #endif
35361 " -echo print inputs before execution\n"
@@ -35435,15 +35909,10 @@
35435 /*
35436 ** Initialize the state information in data
35437 */
35438 static void main_init(ShellState *p) {
35439 memset(p, 0, sizeof(*p));
35440 #if defined(COMPATIBILITY_DATE)
35441 p->iCompat = COMPATIBILITY_DATE;
35442 #else
35443 p->iCompat = 20251116;
35444 #endif
35445 p->pAuxDb = &p->aAuxDb[0];
35446 p->shellFlgs = SHFLG_Lookaside;
35447 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, p);
35448 #if !defined(SQLITE_SHELL_FIDDLE)
35449 verify_uninitialized();
@@ -35498,29 +35967,65 @@
35498 cli_puts(z, p->out);
35499 fflush(p->out);
35500 return 1;
35501 }
35502
35503 #ifndef SQLITE_SHELL_IS_UTF8
35504 # if (defined(_WIN32) || defined(WIN32)) \
35505 && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
35506 # define SQLITE_SHELL_IS_UTF8 (0)
35507 # else
35508 # define SQLITE_SHELL_IS_UTF8 (1)
35509 # endif
35510 #endif
35511
35512 #ifdef SQLITE_SHELL_FIDDLE
35513 # define main fiddle_main
35514 #endif
35515
35516 #if SQLITE_SHELL_IS_UTF8
35517 int SQLITE_CDECL main(int argc, char **argv){
35518 #else
 
 
 
 
35519 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
35520 char **argv;
35521 #endif
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35522 #ifdef SQLITE_DEBUG
35523 sqlite3_int64 mem_main_enter = 0;
35524 #endif
35525 char *zErrMsg = 0;
35526 #ifdef SQLITE_SHELL_FIDDLE
@@ -35538,14 +36043,10 @@
35538 int nOptsEnd = argc;
35539 int bEnableVfstrace = 0;
35540 char **azCmd = 0;
35541 int *aiCmd = 0;
35542 const char *zVfs = 0; /* Value of -vfs command-line option */
35543 #if !SQLITE_SHELL_IS_UTF8
35544 char **argvToFree = 0;
35545 int argcToFree = 0;
35546 #endif
35547 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
35548
35549 #ifdef SQLITE_SHELL_FIDDLE
35550 stdin_is_interactive = 0;
35551 stdout_is_console = 1;
@@ -35596,36 +36097,10 @@
35596 exit(1);
35597 }
35598 #endif
35599 main_init(&data);
35600
35601 /* On Windows, we must translate command-line arguments into UTF-8.
35602 ** The SQLite memory allocator subsystem has to be enabled in order to
35603 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
35604 ** subsequent sqlite3_config() calls will work. So copy all results into
35605 ** memory that does not come from the SQLite memory allocator.
35606 */
35607 #if !SQLITE_SHELL_IS_UTF8
35608 sqlite3_initialize();
35609 argvToFree = malloc(sizeof(argv[0])*argc*2);
35610 shell_check_oom(argvToFree);
35611 argcToFree = argc;
35612 argv = argvToFree + argc;
35613 for(i=0; i<argc; i++){
35614 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
35615 i64 n;
35616 shell_check_oom(z);
35617 n = strlen(z);
35618 argv[i] = malloc( n+1 );
35619 shell_check_oom(argv[i]);
35620 memcpy(argv[i], z, n+1);
35621 argvToFree[i] = argv[i];
35622 sqlite3_free(z);
35623 }
35624 sqlite3_shutdown();
35625 #endif
35626
35627 assert( argc>=1 && argv && argv[0] );
35628 Argv0 = argv[0];
35629
35630 #ifdef SQLITE_SHELL_DBNAME_PROC
35631 {
@@ -35637,11 +36112,11 @@
35637 SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
35638 warnInmemoryDb = 0;
35639 }
35640 #endif
35641
35642 /* Do an initial pass through the command-line argument to locate
35643 ** the name of the database file, the name of the initialization file,
35644 ** the size of the alternative malloc heap, options affecting commands
35645 ** or SQL run from the command line, and the first command to execute.
35646 */
35647 #ifndef SQLITE_SHELL_FIDDLE
@@ -35649,11 +36124,11 @@
35649 #endif
35650 for(i=1; i<argc; i++){
35651 char *z;
35652 z = argv[i];
35653 if( z[0]!='-' || i>nOptsEnd ){
35654 if( data.aAuxDb->zDbFilename==0 ){
35655 data.aAuxDb->zDbFilename = z;
35656 }else{
35657 /* Excess arguments are interpreted as SQL (or dot-commands) and
35658 ** mean that nothing is read from stdin */
35659 readStdin = 0;
@@ -35694,15 +36169,10 @@
35694 if( n<2 ){
35695 sqlite3_fprintf(stderr,"minimum --screenwidth is 2\n");
35696 exit(1);
35697 }
35698 stdout_tty_width = n;
35699 }else if( cli_strcmp(z,"-compat")==0 ){
35700 data.iCompat = atoi(cmdline_option_value(argc, argv, ++i));
35701 modeFree(&data.mode);
35702 memset(&data.mode, 0, sizeof(data.mode));
35703 modeDefault(&data);
35704 }else if( cli_strcmp(z,"-utf8")==0 ){
35705 }else if( cli_strcmp(z,"-no-utf8")==0 ){
35706 }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
35707 int val = 0;
35708 sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW, &val);
@@ -35822,10 +36292,20 @@
35822 }else if( cli_strcmp(z,"-safe")==0 ){
35823 /* no-op - catch this on the second pass */
35824 }else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
35825 /* skip over the argument */
35826 i++;
 
 
 
 
 
 
 
 
 
 
35827 }
35828 }
35829 #ifndef SQLITE_SHELL_FIDDLE
35830 if( !bEnableVfstrace ) verify_uninitialized();
35831 #endif
@@ -35848,11 +36328,30 @@
35848
35849 if( zVfs ){
35850 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
35851 if( pVfs ){
35852 sqlite3_vfs_register(pVfs, 1);
35853 }else{
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35854 cli_printf(stderr,"no such VFS: \"%s\"\n", zVfs);
35855 exit(1);
35856 }
35857 }
35858
@@ -35889,11 +36388,11 @@
35889 ** is given on the command line, look for a file named ~/.sqliterc and
35890 ** try to process it.
35891 */
35892 if( !noInit ) process_sqliterc(&data,zInitFile);
35893
35894 /* Make a second pass through the command-line argument and set
35895 ** options. This second pass is delayed until after the initialization
35896 ** file is processed so that the command-line arguments will override
35897 ** settings in the initialization file.
35898 */
35899 for(i=1; i<argc; i++){
@@ -36015,12 +36514,10 @@
36015 stdin_is_interactive = 1;
36016 }else if( cli_strcmp(z,"-batch")==0 ){
36017 /* already handled */
36018 }else if( cli_strcmp(z,"-screenwidth")==0 ){
36019 i++;
36020 }else if( cli_strcmp(z,"-compat")==0 ){
36021 i++;
36022 }else if( cli_strcmp(z,"-utf8")==0 ){
36023 /* already handled */
36024 }else if( cli_strcmp(z,"-no-utf8")==0 ){
36025 /* already handled */
36026 }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
@@ -36116,11 +36613,22 @@
36116 ** command-line inputs, except for the argToSkip argument which contains
36117 ** the database filename.
36118 */
36119 for(i=0; i<nCmd; i++){
36120 echo_group_input(&data, azCmd[i]);
36121 if( azCmd[i][0]=='.' ){
 
 
 
 
 
 
 
 
 
 
 
36122 char *zErrCtx = malloc( 64 );
36123 shell_check_oom(zErrCtx);
36124 sqlite3_snprintf(64,zErrCtx,"argv[%i]:",aiCmd[i]);
36125 data.zInFile = "<cmdline>";
36126 data.zErrPrefix = zErrCtx;
@@ -36231,14 +36739,10 @@
36231 }
36232 find_home_dir(1);
36233 output_reset(&data);
36234 data.doXdgOpen = 0;
36235 clearTempFile(&data);
36236 #if !SQLITE_SHELL_IS_UTF8
36237 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
36238 free(argvToFree);
36239 #endif
36240 modeFree(&data.mode);
36241 if( data.nSavedModes ){
36242 int ii;
36243 for(ii=0; ii<data.nSavedModes; ii++){
36244 modeFree(&data.aSavedModes[ii].mode);
36245
--- extsrc/shell.c
+++ extsrc/shell.c
@@ -35,11 +35,11 @@
35 ** ext/recover/sqlite3recover.h
36 ** src/shell.c.in
37 **
38 ** To modify this program, get a copy of the canonical SQLite source tree,
39 ** edit the src/shell.c.in file and/or some of the other files that are
40 ** listed above, then rerun the command "make shell.c".
41 */
42 /************************* Begin src/shell.c.in ******************/
43 /*
44 ** 2001 September 15
45 **
@@ -49,11 +49,11 @@
49 ** May you do good and not evil.
50 ** May you find forgiveness for yourself and forgive others.
51 ** May you share freely, never taking more than you give.
52 **
53 *************************************************************************
54 ** This file contains code to implement the "sqlite3" command line
55 ** utility for accessing SQLite databases.
56 */
57 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
58 /* This needs to come before any includes for MSVC compiler */
59 #define _CRT_SECURE_NO_WARNINGS
@@ -79,10 +79,14 @@
79 ** should only be used when building the "fiddle" web application, as
80 ** the browser-mode build has much different user input requirements
81 ** and this build mode rewires the user input subsystem to account for
82 ** that.
83 */
84 #if defined(SQLITE_SHELL_FIDDLE)
85 # undef SQLITE_OMIT_LOAD_EXTENSION
86 # define SQLITE_OMIT_LOAD_EXTENSION 1
87 #endif
88
89 /*
90 ** Warning pragmas copied from msvc.h in the core.
91 */
92 #if defined(_MSC_VER)
@@ -872,10 +876,11 @@
876 #ifndef SQLITE_QRF_H
877 #include "qrf.h"
878 #endif
879 #include <string.h>
880 #include <assert.h>
881 #include <stdint.h>
882
883 /* typedef sqlite3_int64 i64; */
884
885 /* A single line in the EQP output */
886 typedef struct qrfEQPGraphRow qrfEQPGraphRow;
@@ -889,11 +894,12 @@
894 /* All EQP output is collected into an instance of the following */
895 typedef struct qrfEQPGraph qrfEQPGraph;
896 struct qrfEQPGraph {
897 qrfEQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
898 qrfEQPGraphRow *pLast; /* Last element of the pRow list */
899 int nWidth; /* Width of the graph */
900 char zPrefix[400]; /* Graph prefix */
901 };
902
903 /*
904 ** Private state information. Subject to change from one release to the
905 ** next.
@@ -995,10 +1001,19 @@
1001 */
1002 static void qrfOom(Qrf *p){
1003 qrfError(p, SQLITE_NOMEM, "out of memory");
1004 }
1005
1006 /*
1007 ** Transfer any error in pStr over into p.
1008 */
1009 static void qrfStrErr(Qrf *p, sqlite3_str *pStr){
1010 int rc = pStr ? sqlite3_str_errcode(pStr) : 0;
1011 if( rc ){
1012 qrfError(p, rc, sqlite3_errstr(rc));
1013 }
1014 }
1015
1016
1017 /*
1018 ** Add a new entry to the EXPLAIN QUERY PLAN data
1019 */
@@ -1074,10 +1089,49 @@
1089 qrfEqpRenderLevel(p, pRow->iEqpId);
1090 p->u.pGraph->zPrefix[n] = 0;
1091 }
1092 }
1093 }
1094
1095 /*
1096 ** Render the 64-bit value N in a more human-readable format into
1097 ** pOut.
1098 **
1099 ** + Only show the first three significant digits.
1100 ** + Append suffixes K, M, G, T, P, and E for 1e3, 1e6, ... 1e18
1101 */
1102 static void qrfApproxInt64(sqlite3_str *pOut, i64 N){
1103 static const char aSuffix[] = { 'K', 'M', 'G', 'T', 'P', 'E' };
1104 int i;
1105 if( N<0 ){
1106 N = N==INT64_MIN ? INT64_MAX : -N;
1107 sqlite3_str_append(pOut, "-", 1);
1108 }
1109 if( N<10000 ){
1110 sqlite3_str_appendf(pOut, "%4lld ", N);
1111 return;
1112 }
1113 for(i=1; i<=18; i++){
1114 N = (N+5)/10;
1115 if( N<10000 ){
1116 int n = (int)N;
1117 switch( i%3 ){
1118 case 0:
1119 sqlite3_str_appendf(pOut, "%d.%02d", n/1000, (n%1000)/10);
1120 break;
1121 case 1:
1122 sqlite3_str_appendf(pOut, "%2d.%d", n/100, (n%100)/10);
1123 break;
1124 case 2:
1125 sqlite3_str_appendf(pOut, "%4d", n/10);
1126 break;
1127 }
1128 sqlite3_str_append(pOut, &aSuffix[i/3], 1);
1129 break;
1130 }
1131 }
1132 }
1133
1134 /*
1135 ** Display and reset the EXPLAIN QUERY PLAN data
1136 */
1137 static void qrfEqpRender(Qrf *p, i64 nCycle){
@@ -1090,11 +1144,30 @@
1144 }
1145 sqlite3_str_appendf(p->pOut, "%s\n", pRow->zText+3);
1146 p->u.pGraph->pRow = pRow->pNext;
1147 sqlite3_free(pRow);
1148 }else if( nCycle>0 ){
1149 int nSp = p->u.pGraph->nWidth - 2;
1150 if( p->spec.eStyle==QRF_STYLE_StatsEst ){
1151 sqlite3_str_appendchar(p->pOut, nSp, ' ');
1152 sqlite3_str_appendall(p->pOut,
1153 "Cycles Loops (est) Rows (est)\n");
1154 sqlite3_str_appendchar(p->pOut, nSp, ' ');
1155 sqlite3_str_appendall(p->pOut,
1156 "---------- ------------ ------------\n");
1157 }else{
1158 sqlite3_str_appendchar(p->pOut, nSp, ' ');
1159 sqlite3_str_appendall(p->pOut,
1160 "Cycles Loops Rows \n");
1161 sqlite3_str_appendchar(p->pOut, nSp, ' ');
1162 sqlite3_str_appendall(p->pOut,
1163 "---------- ----- -----\n");
1164 }
1165 sqlite3_str_appendall(p->pOut, "QUERY PLAN");
1166 sqlite3_str_appendchar(p->pOut, nSp - 10, ' ');
1167 qrfApproxInt64(p->pOut, nCycle);
1168 sqlite3_str_appendall(p->pOut, " 100%\n");
1169 }else{
1170 sqlite3_str_appendall(p->pOut, "QUERY PLAN\n");
1171 }
1172 p->u.pGraph->zPrefix[0] = 0;
1173 qrfEqpRenderLevel(p, 0);
@@ -1145,10 +1218,12 @@
1218 static const int f = SQLITE_SCANSTAT_COMPLEX;
1219 sqlite3_stmt *pS = p->pStmt;
1220 int i = 0;
1221 i64 nTotal = 0;
1222 int nWidth = 0;
1223 int prevPid = -1; /* Previous iPid */
1224 double rEstCum = 1.0; /* Cumulative row estimate */
1225 sqlite3_str *pLine = sqlite3_str_new(p->db);
1226 sqlite3_str *pStats = sqlite3_str_new(p->db);
1227 qrfEqpReset(p);
1228
1229 for(i=0; 1; i++){
@@ -1158,11 +1233,11 @@
1233 break;
1234 }
1235 n = (int)strlen(z) + qrfStatsHeight(pS,i)*3;
1236 if( n>nWidth ) nWidth = n;
1237 }
1238 nWidth += 2;
1239
1240 sqlite3_stmt_scanstatus_v2(pS,-1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
1241 for(i=0; 1; i++){
1242 i64 nLoop = 0;
1243 i64 nRow = 0;
@@ -1173,55 +1248,67 @@
1248 const char *zName = 0;
1249 double rEst = 0.0;
1250
1251 if( sqlite3_stmt_scanstatus_v2(pS,i,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&zo) ){
1252 break;
1253 }
1254 sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
1255 if( iPid!=prevPid ){
1256 prevPid = iPid;
1257 rEstCum = 1.0;
1258 }
1259 sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
1260 rEstCum *= rEst;
1261 sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
1262 sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
1263 sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
1264 sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
 
1265 sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
1266
1267 if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
1268 int nSp = 0;
 
1269 sqlite3_str_reset(pStats);
1270 if( nCycle>=0 && nTotal>0 ){
1271 qrfApproxInt64(pStats, nCycle);
1272 sqlite3_str_appendf(pStats, " %3d%%",
1273 ((nCycle*100)+nTotal/2) / nTotal
1274 );
1275 nSp = 2;
1276 }
1277 if( nLoop>=0 ){
1278 if( nSp ) sqlite3_str_appendchar(pStats, nSp, ' ');
1279 qrfApproxInt64(pStats, nLoop);
1280 nSp = 2;
1281 if( p->spec.eStyle==QRF_STYLE_StatsEst ){
1282 sqlite3_str_appendf(pStats, " ");
1283 qrfApproxInt64(pStats, (i64)(rEstCum/rEst));
1284 }
1285 }
1286 if( nRow>=0 ){
1287 if( nSp ) sqlite3_str_appendchar(pStats, nSp, ' ');
1288 qrfApproxInt64(pStats, nRow);
1289 nSp = 2;
1290 if( p->spec.eStyle==QRF_STYLE_StatsEst ){
1291 sqlite3_str_appendf(pStats, " ");
1292 qrfApproxInt64(pStats, (i64)rEstCum);
1293 }
1294 }
 
1295 sqlite3_str_appendf(pLine,
1296 "% *s %s", -1*(nWidth-qrfStatsHeight(pS,i)*3), zo,
1297 sqlite3_str_value(pStats)
1298 );
1299 sqlite3_str_reset(pStats);
1300 qrfEqpAppend(p, iId, iPid, sqlite3_str_value(pLine));
1301 sqlite3_str_reset(pLine);
1302 }else{
1303 qrfEqpAppend(p, iId, iPid, zo);
1304 }
1305 }
1306 if( p->u.pGraph ) p->u.pGraph->nWidth = nWidth;
1307 qrfStrErr(p, pLine);
1308 sqlite3_free(sqlite3_str_finish(pLine));
1309 qrfStrErr(p, pStats);
1310 sqlite3_free(sqlite3_str_finish(pStats));
1311 #endif
1312 }
1313
1314
@@ -1581,13 +1668,15 @@
1668 ** (3) z[] does not looks like a numeric literal
1669 */
1670 static int qrfRelaxable(Qrf *p, const char *z){
1671 size_t i, n;
1672 if( z[0]=='\'' || qrfSpace(z[0]) ) return 0;
1673 if( z[0]==0 ){
1674 return (p->spec.zNull!=0 && p->spec.zNull[0]!=0);
1675 }
1676 n = strlen(z);
1677 if( n==0 || z[n-1]=='\'' || qrfSpace(z[n-1]) ) return 0;
1678 if( p->spec.zNull && strcmp(p->spec.zNull,z)==0 ) return 0;
1679 i = (z[0]=='-' || z[0]=='+');
1680 if( strcmp(z+i,"Inf")==0 ) return 0;
1681 if( !qrfDigit(z[i]) ) return 1;
1682 i++;
@@ -2729,10 +2818,11 @@
2818 int nNL = 0;
2819 int n, w;
2820 pStr = sqlite3_str_new(p->db);
2821 qrfEncodeText(p, pStr, z ? z : "");
2822 n = sqlite3_str_length(pStr);
2823 qrfStrErr(p, pStr);
2824 z = data.az[data.n] = sqlite3_str_finish(pStr);
2825 if( p->spec.nTitleLimit ){
2826 nNL = 0;
2827 data.aiWth[data.n] = w = qrfTitleLimit(data.az[data.n],
2828 p->spec.nTitleLimit );
@@ -2756,10 +2846,11 @@
2846 int n, w;
2847 int eType = sqlite3_column_type(p->pStmt,i);
2848 pStr = sqlite3_str_new(p->db);
2849 qrfRenderValue(p, pStr, i);
2850 n = sqlite3_str_length(pStr);
2851 qrfStrErr(p, pStr);
2852 z = data.az[data.n] = sqlite3_str_finish(pStr);
2853 data.abNum[data.n] = eType==SQLITE_INTEGER || eType==SQLITE_FLOAT;
2854 data.aiWth[data.n] = w = qrfDisplayWidth(z, n, &nNL);
2855 data.n++;
2856 if( w>data.a[i].mxW ) data.a[i].mxW = w;
@@ -2910,11 +3001,11 @@
3001 ){
3002 bRTrim = 1;
3003 }else{
3004 bRTrim = 0;
3005 }
3006 for(i=0; i<data.n && sqlite3_str_errcode(p->pOut)==SQLITE_OK; i+=nColumn){
3007 int bMore;
3008 int nRow = 0;
3009
3010 /* Draw a single row of the table. This might be the title line
3011 ** (if there is a title line) or a row in the body of the table.
@@ -3097,11 +3188,11 @@
3188 assert( 0==sqlite3_stricmp( sqlite3_column_name(p->pStmt, 0), "addr" ) );
3189 assert( 0==sqlite3_stricmp( sqlite3_column_name(p->pStmt, 1), "opcode" ) );
3190 assert( 0==sqlite3_stricmp( sqlite3_column_name(p->pStmt, 2), "p1" ) );
3191 assert( 0==sqlite3_stricmp( sqlite3_column_name(p->pStmt, 3), "p2" ) );
3192
3193 for(iOp=0; SQLITE_ROW==sqlite3_step(p->pStmt) && !p->iErr; iOp++){
3194 int iAddr = sqlite3_column_int(p->pStmt, 0);
3195 const char *zOp = (const char*)sqlite3_column_text(p->pStmt, 1);
3196 int p1 = sqlite3_column_int(p->pStmt, 2);
3197 int p2 = sqlite3_column_int(p->pStmt, 3);
3198
@@ -3154,11 +3245,11 @@
3245 nWidth = sizeof(aScanExpWidth)/sizeof(int);
3246 iIndent = 3;
3247 }
3248 if( nArg>nWidth ) nArg = nWidth;
3249
3250 for(iOp=0; sqlite3_step(p->pStmt)==SQLITE_ROW && !p->iErr; iOp++){
3251 /* If this is the first row seen, print out the headers */
3252 if( iOp==0 ){
3253 for(i=0; i<nArg; i++){
3254 const char *zCol = sqlite3_column_name(p->pStmt, aMap[i]);
3255 qrfWidthPrint(p,p->pOut, aWidth[i], zCol);
@@ -3410,10 +3501,11 @@
3501 sqlite3_str_append(p->pOut, "\n", 1);
3502 zVal += iNext;
3503 }while( zVal[0] );
3504 sqlite3_str_reset(pVal);
3505 }
3506 qrfStrErr(p, pVal);
3507 sqlite3_free(sqlite3_str_finish(pVal));
3508 qrfWrite(p);
3509 break;
3510 }
3511 case QRF_STYLE_Eqp: {
@@ -3473,11 +3565,11 @@
3565 p->pOut = sqlite3_str_new(p->db);
3566 if( p->pOut==0 ){
3567 qrfOom(p);
3568 return;
3569 }
3570 p->iErr = SQLITE_OK;
3571 p->nCol = sqlite3_column_count(p->pStmt);
3572 p->nRow = 0;
3573 sz = sizeof(sqlite3_qrf_spec);
3574 memcpy(&p->spec, pSpec, sz);
3575 if( p->spec.zNull==0 ) p->spec.zNull = "";
@@ -3644,17 +3736,27 @@
3736 sqlite3_free(p->u.sLine.azCol);
3737 }
3738 break;
3739 }
3740 case QRF_STYLE_Stats:
3741 case QRF_STYLE_StatsEst: {
3742 i64 nCycle = 0;
3743 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3744 sqlite3_stmt_scanstatus_v2(p->pStmt, -1, SQLITE_SCANSTAT_NCYCLE,
3745 SQLITE_SCANSTAT_COMPLEX, (void*)&nCycle);
3746 #endif
3747 qrfEqpRender(p, nCycle);
3748 qrfWrite(p);
3749 break;
3750 }
3751 case QRF_STYLE_Eqp: {
3752 qrfEqpRender(p, 0);
3753 qrfWrite(p);
3754 break;
3755 }
3756 }
3757 qrfStrErr(p, p->pOut);
3758 if( p->spec.pzOutput ){
3759 if( p->spec.pzOutput[0] ){
3760 sqlite3_int64 n, sz;
3761 char *zCombined;
3762 sz = strlen(p->spec.pzOutput[0]);
@@ -3815,13 +3917,10 @@
3917
3918
3919 #define eputz(z) cli_puts(z,stderr)
3920 #define sputz(fp,z) cli_puts(z,fp)
3921
 
 
 
3922 /* A version of strcmp() that works with NULL values */
3923 static int cli_strcmp(const char *a, const char *b){
3924 if( a==0 ) a = "";
3925 if( b==0 ) b = "";
3926 return strcmp(a,b);
@@ -3834,11 +3933,11 @@
3933
3934 /* Return the current wall-clock time in microseconds since the
3935 ** Unix epoch (1970-01-01T00:00:00Z)
3936 */
3937 static sqlite3_int64 timeOfDay(void){
3938 #if defined(_WIN64) && _WIN32_WINNT >= _WIN32_WINNT_WIN8
3939 sqlite3_uint64 t;
3940 FILETIME tm;
3941 GetSystemTimePreciseAsFileTime(&tm);
3942 t = ((u64)tm.dwHighDateTime<<32) | (u64)tm.dwLowDateTime;
3943 t += 116444736000000000LL;
@@ -3862,154 +3961,10 @@
3961 (void)gettimeofday(&sNow,0);
3962 return ((i64)sNow.tv_sec)*1000000 + sNow.tv_usec;
3963 #endif
3964 }
3965
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3966
3967 /*
3968 ** Used to prevent warnings about unused parameters
3969 */
3970 #define UNUSED_PARAMETER(x) (void)(x)
@@ -4068,10 +4023,18 @@
4023 #define PROMPT_LEN_MAX 128
4024 /* First line prompt. default: "sqlite> " */
4025 static char mainPrompt[PROMPT_LEN_MAX];
4026 /* Continuation prompt. default: " ...> " */
4027 static char continuePrompt[PROMPT_LEN_MAX];
4028
4029 /*
4030 ** Write I/O traces to the following stream.
4031 */
4032 #ifdef SQLITE_ENABLE_IOTRACE
4033 static FILE *iotrace = 0;
4034 #endif
4035
4036
4037 /* This is variant of the standard-library strncpy() routine with the
4038 ** one change that the destination string is always zero-terminated, even
4039 ** if there is no zero-terminator in the first n-1 characters of the source
4040 ** string.
@@ -4188,17 +4151,10 @@
4151 */
4152 static void shell_check_oom(const void *p){
4153 if( p==0 ) shell_out_of_memory();
4154 }
4155
 
 
 
 
 
 
 
4156 /*
4157 ** This routine works like printf in that its first argument is a
4158 ** format string and subsequent arguments are values to be substituted
4159 ** in place of % fields. The result of formatting this string
4160 ** is written to iotrace.
@@ -8349,13 +8305,13 @@
8305 }else if( e<-10000 ){
8306 e = -10000;
8307 }
8308
8309 if( m<0 ){
8310 if( m<(-9223372036854775807LL) ) return;
8311 isNeg = 1;
8312 m = -m;
 
8313 }else if( m==0 && e>-1000 && e<1000 ){
8314 sqlite3_result_double(context, 0.0);
8315 return;
8316 }
8317 while( (m>>32)&0xffe00000 ){
@@ -9472,11 +9428,11 @@
9428 ** (X) match X
9429 ** X|Y X or Y
9430 ** ^X X occurring at the beginning of the string
9431 ** X$ X occurring at the end of the string
9432 ** . Match any single character
9433 ** \c Character c where c is one of \{}()[]|*+?-.
9434 ** \c C-language escapes for c in afnrtv. ex: \t or \n
9435 ** \uXXXX Where XXXX is exactly 4 hex digits, unicode value XXXX
9436 ** \xXX Where XX is exactly 2 hex digits, unicode value XX
9437 ** [abc] Any single character from the set abc
9438 ** [^abc] Any single character not in the set abc
@@ -9857,11 +9813,11 @@
9813
9814 /* A backslash character has been seen, read the next character and
9815 ** return its interpretation.
9816 */
9817 static unsigned re_esc_char(ReCompiled *p){
9818 static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]-";
9819 static const char zTrans[] = "\a\f\n\r\t\v";
9820 int i, v = 0;
9821 char c;
9822 if( p->sIn.i>=p->sIn.mx ) return 0;
9823 c = p->sIn.z[p->sIn.i];
@@ -10180,15 +10136,22 @@
10136 }
10137 return pRe->zErr;
10138 }
10139
10140 /*
10141 ** The value of LIMIT_MAX_PATTERN_LENGTH.
10142 */
10143 static int re_maxlen(sqlite3_context *context){
10144 sqlite3 *db = sqlite3_context_db_handle(context);
10145 return sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH,-1);
10146 }
10147
10148 /*
10149 ** Maximum NFA size given a maximum pattern length.
10150 */
10151 static int re_maxnfa(int mxlen){
10152 return 75+mxlen/2;
10153 }
10154
10155 /*
10156 ** Implementation of the regexp() SQL function. This function implements
10157 ** the build-in REGEXP operator. The first argument to the function is the
@@ -10210,14 +10173,21 @@
10173 int setAux = 0; /* True to invoke sqlite3_set_auxdata() */
10174
10175 (void)argc; /* Unused */
10176 pRe = sqlite3_get_auxdata(context, 0);
10177 if( pRe==0 ){
10178 int mxLen = re_maxlen(context);
10179 int nPattern;
10180 zPattern = (const char*)sqlite3_value_text(argv[0]);
10181 if( zPattern==0 ) return;
10182 nPattern = sqlite3_value_bytes(argv[0]);
10183 if( nPattern>mxLen ){
10184 zErr = "REGEXP pattern too big";
10185 }else{
10186 zErr = re_compile(&pRe, zPattern, re_maxnfa(mxLen),
10187 sqlite3_user_data(context)!=0);
10188 }
10189 if( zErr ){
10190 re_free(pRe);
10191 sqlite3_result_error(context, zErr, -1);
10192 return;
10193 }
@@ -10279,11 +10249,11 @@
10249 "ATSTART",
10250 };
10251
10252 zPattern = (const char*)sqlite3_value_text(argv[0]);
10253 if( zPattern==0 ) return;
10254 zErr = re_compile(&pRe, zPattern, re_maxnfa(re_maxlen(context)),
10255 sqlite3_user_data(context)!=0);
10256 if( zErr ){
10257 re_free(pRe);
10258 sqlite3_result_error(context, zErr, -1);
10259 return;
@@ -13067,11 +13037,11 @@
13037 nFile = (int)strlen(zFile)+1;
13038 }
13039
13040 rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
13041 if( rc==SQLITE_OK ){
13042 pNew = (ZipfileTab*)sqlite3_malloc64((i64)nByte+nFile);
13043 if( pNew==0 ) return SQLITE_NOMEM;
13044 memset(pNew, 0, nByte+nFile);
13045 pNew->db = db;
13046 pNew->aBuffer = (u8*)&pNew[1];
13047 if( zFile ){
@@ -13213,18 +13183,19 @@
13183 ** sqlite3_free().
13184 */
13185 static int zipfileReadData(
13186 FILE *pFile, /* Read from this file */
13187 u8 *aRead, /* Read into this buffer */
13188 i64 nRead, /* Number of bytes to read */
13189 i64 iOff, /* Offset to read from */
13190 char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */
13191 ){
13192 size_t n;
13193 fseek(pFile, (long)iOff, SEEK_SET);
13194 n = fread(aRead, 1, (long)nRead, pFile);
13195 if( n!=(size_t)nRead ){
13196 sqlite3_free(*pzErrmsg);
13197 *pzErrmsg = sqlite3_mprintf("error in fread()");
13198 return SQLITE_ERROR;
13199 }
13200 return SQLITE_OK;
13201 }
@@ -13237,11 +13208,11 @@
13208 if( nWrite>0 ){
13209 size_t n = nWrite;
13210 fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
13211 n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
13212 if( (int)n!=nWrite ){
13213 zipfileTableErr(pTab,"error in fwrite()");
13214 return SQLITE_ERROR;
13215 }
13216 pTab->szCurrent += nWrite;
13217 }
13218 return SQLITE_OK;
@@ -13484,10 +13455,11 @@
13455 /*
13456 ** Set (*pzErr) to point to a buffer from sqlite3_malloc() containing a
13457 ** generic corruption message and return SQLITE_CORRUPT;
13458 */
13459 static int zipfileCorrupt(char **pzErr){
13460 sqlite3_free(*pzErr);
13461 *pzErr = sqlite3_mprintf("zip archive is corrupt");
13462 return SQLITE_CORRUPT;
13463 }
13464
13465 /*
@@ -13502,11 +13474,11 @@
13474 ** final value of (*ppEntry) undefined.
13475 */
13476 static int zipfileGetEntry(
13477 ZipfileTab *pTab, /* Store any error message here */
13478 const u8 *aBlob, /* Pointer to in-memory file image */
13479 i64 nBlob, /* Size of aBlob[] in bytes */
13480 FILE *pFile, /* If aBlob==0, read from this file */
13481 i64 iOff, /* Offset of CDS record */
13482 ZipfileEntry **ppEntry /* OUT: Pointer to new object */
13483 ){
13484 u8 *aRead;
@@ -13542,18 +13514,18 @@
13514 rc = SQLITE_NOMEM;
13515 }else{
13516 memset(pNew, 0, sizeof(ZipfileEntry));
13517 rc = zipfileReadCDS(aRead, &pNew->cds);
13518 if( rc!=SQLITE_OK ){
13519 zipfileTableErr(pTab, "failed to read CDS at offset %lld", iOff);
13520 }else if( aBlob==0 ){
13521 rc = zipfileReadData(
13522 pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
13523 );
13524 }else{
13525 aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
13526 if( (iOff + ZIPFILE_CDS_FIXED_SZ + nFile + nExtra)>nBlob ){
13527 rc = zipfileCorrupt(pzErr);
13528 }
13529 }
13530 }
13531
@@ -13574,19 +13546,19 @@
13546 ZipfileLFH lfh;
13547 if( pFile ){
13548 rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
13549 }else{
13550 aRead = (u8*)&aBlob[pNew->cds.iOffset];
13551 if( ((i64)pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ)>nBlob ){
13552 rc = zipfileCorrupt(pzErr);
13553 }
13554 }
13555
13556 memset(&lfh, 0, sizeof(lfh));
13557 if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
13558 if( rc==SQLITE_OK ){
13559 pNew->iDataOff = (i64)pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
13560 pNew->iDataOff += lfh.nFile + lfh.nExtra;
13561 if( aBlob && pNew->cds.szCompressed ){
13562 if( pNew->iDataOff + pNew->cds.szCompressed > nBlob ){
13563 rc = zipfileCorrupt(pzErr);
13564 }else{
@@ -13593,11 +13565,11 @@
13565 pNew->aData = &pNew->aExtra[nExtra];
13566 memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
13567 }
13568 }
13569 }else{
13570 zipfileTableErr(pTab, "failed to read LFH at offset %d",
13571 (int)pNew->cds.iOffset
13572 );
13573 }
13574 }
13575
@@ -13617,11 +13589,11 @@
13589 static int zipfileNext(sqlite3_vtab_cursor *cur){
13590 ZipfileCsr *pCsr = (ZipfileCsr*)cur;
13591 int rc = SQLITE_OK;
13592
13593 if( pCsr->pFile ){
13594 i64 iEof = (i64)pCsr->eocd.iOffset + (i64)pCsr->eocd.nSize;
13595 zipfileEntryFree(pCsr->pCurrent);
13596 pCsr->pCurrent = 0;
13597 if( pCsr->iNextOff>=iEof ){
13598 pCsr->bEof = 1;
13599 }else{
@@ -13855,16 +13827,16 @@
13827 ** an English language error message may be left in virtual-table pTab.
13828 */
13829 static int zipfileReadEOCD(
13830 ZipfileTab *pTab, /* Return errors here */
13831 const u8 *aBlob, /* Pointer to in-memory file image */
13832 i64 nBlob, /* Size of aBlob[] in bytes */
13833 FILE *pFile, /* Read from this file if aBlob==0 */
13834 ZipfileEOCD *pEOCD /* Object to populate */
13835 ){
13836 u8 *aRead = pTab->aBuffer; /* Temporary buffer */
13837 i64 nRead; /* Bytes to read from file */
13838 int rc = SQLITE_OK;
13839
13840 memset(pEOCD, 0, sizeof(ZipfileEOCD));
13841 if( aBlob==0 ){
13842 i64 iOff; /* Offset to read from */
@@ -13881,11 +13853,11 @@
13853 nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
13854 aRead = (u8*)&aBlob[nBlob-nRead];
13855 }
13856
13857 if( rc==SQLITE_OK ){
13858 i64 i;
13859
13860 /* Scan backwards looking for the signature bytes */
13861 for(i=nRead-20; i>=0; i--){
13862 if( aRead[i]==0x50 && aRead[i+1]==0x4b
13863 && aRead[i+2]==0x05 && aRead[i+3]==0x06
@@ -13892,13 +13864,11 @@
13864 ){
13865 break;
13866 }
13867 }
13868 if( i<0 ){
13869 zipfileTableErr(pTab, "cannot find end of central directory record");
 
 
13870 return SQLITE_ERROR;
13871 }
13872
13873 aRead += i+4;
13874 pEOCD->iDisk = zipfileRead16(aRead);
@@ -13939,11 +13909,11 @@
13909 pNew->pNext = pBefore;
13910 *pp = pNew;
13911 }
13912 }
13913
13914 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, i64 nBlob){
13915 ZipfileEOCD eocd;
13916 int rc;
13917 int i;
13918 i64 iOff;
13919
@@ -13987,11 +13957,11 @@
13957 zipfileCursorErr(pCsr, "zipfile() function requires an argument");
13958 return SQLITE_ERROR;
13959 }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
13960 static const u8 aEmptyBlob = 0;
13961 const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
13962 i64 nBlob = sqlite3_value_bytes(argv[0]);
13963 assert( pTab->pFirstEntry==0 );
13964 if( aBlob==0 ){
13965 aBlob = &aEmptyBlob;
13966 nBlob = 0;
13967 }
@@ -14185,23 +14155,23 @@
14155 ZipfileTab *pTab = (ZipfileTab*)pVtab;
14156 int rc = SQLITE_OK;
14157
14158 assert( pTab->pWriteFd==0 );
14159 if( pTab->zFile==0 || pTab->zFile[0]==0 ){
14160 zipfileTableErr(pTab, "zipfile: missing filename");
14161 return SQLITE_ERROR;
14162 }
14163
14164 /* Open a write fd on the file. Also load the entire central directory
14165 ** structure into memory. During the transaction any new file data is
14166 ** appended to the archive file, but the central directory is accumulated
14167 ** in main-memory until the transaction is committed. */
14168 pTab->pWriteFd = sqlite3_fopen(pTab->zFile, "ab+");
14169 if( pTab->pWriteFd==0 ){
14170 zipfileTableErr(pTab,
14171 "zipfile: failed to open file %s for writing", pTab->zFile
14172 );
14173 rc = SQLITE_ERROR;
14174 }else{
14175 fseek(pTab->pWriteFd, 0, SEEK_END);
14176 pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
14177 rc = zipfileLoadDirectory(pTab, 0, 0);
@@ -14662,11 +14632,11 @@
14632 int nEntry;
14633 ZipfileBuffer body;
14634 ZipfileBuffer cds;
14635 };
14636
14637 static int zipfileBufferGrow(ZipfileBuffer *pBuf, i64 nByte){
14638 if( pBuf->n+nByte>pBuf->nAlloc ){
14639 u8 *aNew;
14640 sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
14641 int nReq = pBuf->n + nByte;
14642
@@ -14711,11 +14681,11 @@
14681 u32 iCrc32 = 0; /* crc32 of uncompressed data */
14682
14683 char *zName = 0; /* Path (name) of new entry */
14684 int nName = 0; /* Size of zName in bytes */
14685 char *zFree = 0; /* Free this before returning */
14686 i64 nByte;
14687
14688 memset(&e, 0, sizeof(e));
14689 p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
14690 if( p==0 ) return;
14691
@@ -24161,28 +24131,28 @@
24131 u8 autoExplain; /* Automatically turn on .explain mode */
24132 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
24133 u8 autoEQPtrace; /* autoEQP is in trace mode */
24134 u8 scanstatsOn; /* True to display scan stats before each finalize */
24135 u8 bAutoScreenWidth; /* Using the TTY to determine screen width */
24136 u8 mFlags; /* MFLG_ECHO, MFLG_CRLF, etc. */
24137 u8 eMode; /* One of the MODE_ values */
24138 sqlite3_qrf_spec spec; /* Spec to be passed into QRF */
24139 } Mode;
24140
24141 /* Flags for Mode.mFlags */
24142 #define MFLG_ECHO 0x01 /* Echo inputs to output */
24143 #define MFLG_CRLF 0x02 /* Use CR/LF output line endings */
24144 #define MFLG_HDR 0x04 /* .header used to change headers on/off */
24145
24146
24147 /*
24148 ** State information about the database connection is contained in an
24149 ** instance of the following structure.
24150 */
24151 typedef struct ShellState ShellState;
24152 struct ShellState {
24153 sqlite3 *db; /* The database */
 
24154 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
24155 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
24156 u8 nEqpLevel; /* Depth of the EQP output graph */
24157 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
24158 u8 bSafeMode; /* True to prohibit unsafe operations */
@@ -24190,11 +24160,14 @@
24160 u8 eRestoreState; /* See comments above doAutoDetectRestore() */
24161 unsigned statsOn; /* True to display memory stats before each finalize */
24162 unsigned mEqpLines; /* Mask of vertical lines in the EQP output graph */
24163 u8 nPopOutput; /* Revert .output settings when reaching zero */
24164 u8 nPopMode; /* Revert .mode settings when reaching zero */
24165 u8 enableTimer; /* Enable the timer. 2: permanently 1: only once */
24166 int inputNesting; /* Track nesting level of .read and other redirects */
24167 double prevTimer; /* Last reported timer value */
24168 double tmProgress; /* --timeout option for .progress */
24169 i64 lineno; /* Line number of last line read from in */
24170 const char *zInFile; /* Name of the input file */
24171 int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
24172 FILE *in; /* Read commands from this stream */
24173 FILE *out; /* Write results here */
@@ -24286,10 +24259,11 @@
24259 #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
24260 #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progress
24261 ** callback limit is reached, and for each
24262 ** top-level SQL statement */
24263 #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
24264 #define SHELL_PROGRESS_TMOUT 0x08 /* Stop after tmProgress seconds */
24265
24266 /* Names of values for Mode.spec.eEsc and Mode.spec.eText
24267 */
24268 static const char *qrfEscNames[] = { "auto", "off", "ascii", "symbol" };
24269 static const char *qrfQuoteNames[] =
@@ -24447,10 +24421,181 @@
24421 ** Limit input nesting via .read or any other input redirect.
24422 ** It's not too expensive, so a generous allowance can be made.
24423 */
24424 #define MAX_INPUT_NESTING 25
24425
24426 /************************* BEGIN PERFORMANCE TIMER *****************************/
24427 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
24428 #include <sys/time.h>
24429 #include <sys/resource.h>
24430 /* VxWorks does not support getrusage() as far as we can determine */
24431 #if defined(_WRS_KERNEL) || defined(__RTP__)
24432 struct rusage {
24433 struct timeval ru_utime; /* user CPU time used */
24434 struct timeval ru_stime; /* system CPU time used */
24435 };
24436 #define getrusage(A,B) memset(B,0,sizeof(*B))
24437 #endif
24438
24439 /* Saved resource information for the beginning of an operation */
24440 static struct rusage sBegin; /* CPU time at start */
24441 static sqlite3_int64 iBegin; /* Wall-clock time at start */
24442
24443 /*
24444 ** Begin timing an operation
24445 */
24446 static void beginTimer(ShellState *p){
24447 if( p->enableTimer || (p->flgProgress & SHELL_PROGRESS_TMOUT)!=0 ){
24448 getrusage(RUSAGE_SELF, &sBegin);
24449 iBegin = timeOfDay();
24450 }
24451 }
24452
24453 /* Return the difference of two time_structs in seconds */
24454 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
24455 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
24456 (double)(pEnd->tv_sec - pStart->tv_sec);
24457 }
24458
24459 /* Return the time since the start of the timer in
24460 ** seconds. */
24461 static double elapseTime(ShellState *NotUsed){
24462 (void)NotUsed;
24463 if( iBegin==0 ) return 0.0;
24464 return (timeOfDay() - iBegin)*0.000001;
24465 }
24466
24467 /*
24468 ** Print the timing results.
24469 */
24470 static void endTimer(ShellState *p){
24471 if( p->enableTimer ){
24472 sqlite3_int64 iEnd = timeOfDay();
24473 struct rusage sEnd;
24474 getrusage(RUSAGE_SELF, &sEnd);
24475 p->prevTimer = (iEnd - iBegin)*0.000001;
24476 cli_printf(p->out, "Run Time: real %.6f user %.6f sys %.6f\n",
24477 p->prevTimer,
24478 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
24479 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
24480 if( p->enableTimer==1 ) p->enableTimer = 0;
24481 iBegin = 0;
24482 }
24483 }
24484
24485 #define BEGIN_TIMER(X) beginTimer(X)
24486 #define END_TIMER(X) endTimer(X)
24487 #define ELAPSE_TIME(X) elapseTime(X)
24488 #define HAS_TIMER 1
24489
24490 #elif (defined(_WIN32) || defined(WIN32))
24491
24492 /* Saved resource information for the beginning of an operation */
24493 static HANDLE hProcess;
24494 static FILETIME ftKernelBegin;
24495 static FILETIME ftUserBegin;
24496 static sqlite3_int64 ftWallBegin;
24497 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
24498 LPFILETIME, LPFILETIME);
24499 static GETPROCTIMES getProcessTimesAddr = NULL;
24500
24501 /*
24502 ** Check to see if we have timer support. Return 1 if necessary
24503 ** support found (or found previously).
24504 */
24505 static int hasTimer(void){
24506 if( getProcessTimesAddr ){
24507 return 1;
24508 } else {
24509 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
24510 ** versions. See if the version we are running on has it, and if it
24511 ** does, save off a pointer to it and the current process handle.
24512 */
24513 hProcess = GetCurrentProcess();
24514 if( hProcess ){
24515 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
24516 if( NULL != hinstLib ){
24517 getProcessTimesAddr =
24518 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
24519 if( NULL != getProcessTimesAddr ){
24520 return 1;
24521 }
24522 FreeLibrary(hinstLib);
24523 }
24524 }
24525 }
24526 return 0;
24527 }
24528
24529 /*
24530 ** Begin timing an operation
24531 */
24532 static void beginTimer(ShellState *p){
24533 if( (p->enableTimer || (p->flgProgress & SHELL_PROGRESS_TMOUT)!=0)
24534 && getProcessTimesAddr
24535 ){
24536 FILETIME ftCreation, ftExit;
24537 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
24538 &ftKernelBegin,&ftUserBegin);
24539 ftWallBegin = timeOfDay();
24540 }
24541 }
24542
24543 /* Return the difference of two FILETIME structs in seconds */
24544 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
24545 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
24546 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
24547 return (double) ((i64End - i64Start) / 10000000.0);
24548 }
24549
24550 /* Return the time since the start of the timer in
24551 ** seconds. */
24552 static double elapseTime(ShellState *NotUsed){
24553 (void)NotUsed;
24554 if( ftWallBegin==0 ) return 0.0;
24555 return (timeOfDay() - ftWallBegin)*0.000001;
24556 }
24557
24558 /*
24559 ** Print the timing results.
24560 */
24561 static void endTimer(ShellState *p){
24562 if( p->enableTimer && getProcessTimesAddr){
24563 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
24564 sqlite3_int64 ftWallEnd = timeOfDay();
24565 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
24566 p->prevTimer = (ftWallEnd - ftWallBegin)*0.000001;
24567 #ifdef _WIN64
24568 /* microsecond precision on 64-bit windows */
24569 cli_printf(p->out, "Run Time: real %.6f user %f sys %f\n",
24570 p->prevTimer,
24571 timeDiff(&ftUserBegin, &ftUserEnd),
24572 timeDiff(&ftKernelBegin, &ftKernelEnd));
24573 #else
24574 /* millisecond precisino on 32-bit windows */
24575 cli_printf(p->out, "Run Time: real %.3f user %.3f sys %.3f\n",
24576 p->prevTimer,
24577 timeDiff(&ftUserBegin, &ftUserEnd),
24578 timeDiff(&ftKernelBegin, &ftKernelEnd));
24579 #endif
24580 if( p->enableTimer==1 ) p->enableTimer = 0;
24581 ftWallBegin = 0;
24582 }
24583 }
24584
24585 #define BEGIN_TIMER(X) beginTimer(X)
24586 #define ELAPSE_TIME(X) elapseTime(X)
24587 #define END_TIMER(X) endTimer(X)
24588 #define HAS_TIMER hasTimer()
24589
24590 #else
24591 #define BEGIN_TIMER(X) /* no-op */
24592 #define ELAPSE_TIME(X) 0.0
24593 #define END_TIMER(X) /*no-op*/
24594 #define HAS_TIMER 0
24595 #endif
24596 /************************* END PERFORMANCE TIMER ******************************/
24597
24598 /*
24599 ** Clear a display mode, freeing any allocated memory that it
24600 ** contains.
24601 */
@@ -24534,11 +24679,13 @@
24679 if( pI->eCSep ) modeSetStr(&pM->spec.zColumnSep, aModeStr[pI->eCSep]);
24680 if( pI->eRSep ) modeSetStr(&pM->spec.zRowSep, aModeStr[pI->eRSep]);
24681 if( pI->eNull ) modeSetStr(&pM->spec.zNull, aModeStr[pI->eNull]);
24682 pM->spec.eText = pI->eText;
24683 pM->spec.eBlob = pI->eBlob;
24684 if( (pM->mFlags & MFLG_HDR)==0 ){
24685 pM->spec.bTitles = pI->bHdr;
24686 }
24687 pM->spec.eTitle = pI->eHdr;
24688 if( pI->mFlg & 0x01 ){
24689 pM->spec.bBorder = QRF_No;
24690 }else{
24691 pM->spec.bBorder = QRF_Auto;
@@ -24570,18 +24717,17 @@
24717 p->mode.mFlags = mFlags;
24718 }
24719 }
24720
24721 /*
24722 ** Set the mode to the default. It assumed that the mode has
24723 ** already been freed and zeroed prior to calling this routine.
 
24724 */
24725 static void modeDefault(ShellState *p){
24726 p->mode.spec.iVersion = 1;
24727 p->mode.autoExplain = 1;
24728 if( stdin_is_interactive || stdout_is_console ){
24729 modeChange(p, MODE_TTY);
24730 }else{
24731 modeChange(p, MODE_BATCH);
24732 }
24733 }
@@ -25371,10 +25517,17 @@
25517 ** Progress handler callback.
25518 */
25519 static int progress_handler(void *pClientData) {
25520 ShellState *p = (ShellState*)pClientData;
25521 p->nProgress++;
25522 if( (p->flgProgress & SHELL_PROGRESS_TMOUT)!=0
25523 && ELAPSE_TIME(p)>=p->tmProgress
25524 ){
25525 cli_printf(p->out, "Progress timeout after %.6f seconds\n",
25526 ELAPSE_TIME(p));
25527 return 1;
25528 }
25529 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
25530 cli_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
25531 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
25532 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
25533 return 1;
@@ -25908,10 +26061,12 @@
26061 char *zBuf = sqlite3_malloc64( szVar-5 );
26062 if( zBuf ){
26063 memcpy(zBuf, &zVar[6], szVar-5);
26064 sqlite3_bind_text64(pStmt, i, zBuf, szVar-6, sqlite3_free, SQLITE_UTF8);
26065 }
26066 }else if( strcmp(zVar, "$TIMER")==0 ){
26067 sqlite3_bind_double(pStmt, i, pArg->prevTimer);
26068 #ifdef SQLITE_ENABLE_CARRAY
26069 }else if( strncmp(zVar, "$carray_", 8)==0 ){
26070 static char *azColorNames[] = {
26071 "azure", "black", "blue", "brown", "cyan", "fuchsia", "gold",
26072 "gray", "green", "indigo", "khaki", "lime", "magenta", "maroon",
@@ -26167,27 +26322,36 @@
26322 pArg->pStmt = pStmt;
26323 }
26324
26325 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
26326 isExplain = sqlite3_stmt_isexplain(pStmt);
26327 if( pArg && pArg->mode.autoEQP && isExplain==0 && pArg->dot.nArg==0 ){
26328 int triggerEQP = 0;
26329 u8 savedEnableTimer = pArg->enableTimer;
26330 pArg->enableTimer = 0;
26331 disable_debug_trace_modes();
26332 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
26333 if( pArg->mode.autoEQP>=AUTOEQP_trigger ){
26334 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
26335 }
26336 sqlite3_reset(pStmt);
26337 spec.eStyle = QRF_STYLE_Auto;
26338 sqlite3_stmt_explain(pStmt, 2);
26339 sqlite3_format_query_result(pStmt, &spec, 0);
26340 if( pArg->mode.autoEQP>=AUTOEQP_full ){
26341 sqlite3_reset(pStmt);
26342 sqlite3_stmt_explain(pStmt, 1);
26343 sqlite3_format_query_result(pStmt, &spec, 0);
26344 }
26345
26346 if( pArg->mode.autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
26347 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
26348 }
26349 sqlite3_reset(pStmt);
26350 sqlite3_stmt_explain(pStmt, 0);
26351 restore_debug_trace_modes();
26352 pArg->enableTimer = savedEnableTimer;
26353 }
26354
26355 bind_prepared_stmt(pArg, pStmt);
26356 if( isExplain && pArg->mode.autoExplain ){
26357 spec.eStyle = isExplain==1 ? QRF_STYLE_Explain : QRF_STYLE_Eqp;
@@ -26604,12 +26768,12 @@
26768 ".bail on|off Stop after hitting an error. Default OFF",
26769 #ifndef SQLITE_SHELL_FIDDLE
26770 ".cd DIRECTORY Change the working directory to DIRECTORY",
26771 #endif
26772 ".changes on|off Show number of rows changed by SQL",
26773 ".check OPTIONS ... Verify the results of a .testcase",
26774 #ifndef SQLITE_SHELL_FIDDLE
 
26775 ".clone NEWDB Clone data into NEWDB from the existing database",
26776 #endif
26777 ".connection [close] [#] Open or close an auxiliary database connection",
26778 ".crlf ?on|off? Whether or not to use \\r\\n line endings",
26779 ".databases List names and files of attached databases",
@@ -26721,10 +26885,11 @@
26885 ".progress N Invoke progress handler after every N opcodes",
26886 " --limit N Interrupt after N progress callbacks",
26887 " --once Do no more than one progress interrupt",
26888 " --quiet|-q No output except at interrupts",
26889 " --reset Reset the count for each input and interrupt",
26890 " --timeout S Halt after running for S seconds",
26891 #endif
26892 ".prompt MAIN CONTINUE Replace the standard prompts",
26893 #ifndef SQLITE_SHELL_FIDDLE
26894 ".quit Stop interpreting input stream, exit if primary.",
26895 ".read FILE Read input from FILE or command output",
@@ -26785,17 +26950,15 @@
26950 " vmstep Show the virtual machine step count only",
26951 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
26952 ".system CMD ARGS... Run CMD ARGS... in a system shell",
26953 #endif
26954 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
26955 ".testcase NAME Begin a test case.",
 
 
26956 ",testctrl CMD ... Run various sqlite3_test_control() operations",
26957 " Run \".testctrl\" with no arguments for details",
26958 ".timeout MS Try opening locked tables for MS milliseconds",
26959 ".timer on|off|once Turn SQL timer on or off.",
26960 #ifndef SQLITE_OMIT_TRACE
26961 ".trace ?OPTIONS? Output each SQL statement as it is run",
26962 " FILE Send output to FILE",
26963 " stdout Send output to stdout",
26964 " stderr Send output to stderr",
@@ -26836,19 +26999,33 @@
26999 "USAGE: .import [OPTIONS] FILE TABLE\n"
27000 "\n"
27001 "Import CSV or similar text from FILE into TABLE. If TABLE does\n"
27002 "not exist, it is created using the first row of FILE as the column\n"
27003 "names. If FILE begins with \"|\" then it is a command that is run\n"
27004 "and the output from the command is used as the input data. If\n"
27005 "FILE begins with \"<<\" followed by a label, then content is read from\n"
27006 "the script until the first line that matches the label.\n"
27007 "\n"
27008 "The content of FILE is interpreted using RFC-4180 (\"CSV\") quoting\n"
27009 "rules unless the current mode is \"ascii\" or \"tabs\" or unless one\n"
27010 "the --ascii option is used.\n"
27011 "\n"
27012 "The column and row separators must be single ASCII characters. If\n"
27013 "multiple characters or a Unicode character are specified for the\n"
27014 "separators, then only the first byte of the separator is used. Except,\n"
27015 "if the row separator is \\n and the mode is not --ascii, then \\r\\n is\n"
27016 "understood as a row separator too.\n"
27017 "\n"
27018 "Options:\n"
27019 " --ascii Do not use RFC-4180 quoting. Use \\037 and \\036\n"
27020 " as column and row separators on input, unless other\n"
27021 " delimiters are specified using --colsep and/or --rowsep\n"
27022 " --colsep CHAR Use CHAR as the column separator.\n"
27023 " --csv Input is standard RFC-4180 CSV.\n"
27024 " --esc CHAR Use CHAR as an escape character in unquoted CSV inputs.\n"
27025 " --qesc CHAR Use CHAR as an escape character in quoted CSV inputs.\n"
27026 " --rowsep CHAR Use CHAR as the row separator.\n"
27027 " --schema S When creating TABLE, put it in schema S\n"
27028 " --skip N Ignore the first N rows of input\n"
27029 " -v Verbose mode\n"
27030 },
27031 { ".mode",
@@ -26930,23 +27107,17 @@
27107 " --bom Prepend a byte-order mark to the output\n"
27108 " -e Accumulate output in a temporary text file then\n"
27109 " launch a text editor when the redirection ends.\n"
27110 " --error-prefix X Use X as the left-margin prefix for error messages.\n"
27111 " Set to an empty string to restore the default.\n"
27112 " --keep Keep redirecting output to its current destination.\n"
27113 " Use this option in combination with --show or\n"
27114 " with --error-prefix when you do not want to stop\n"
27115 " a current redirection.\n"
 
 
 
27116 " --plain Use plain text rather than HTML tables with -w\n"
27117 " --show Show output text captured by .testcase or by\n"
27118 " redirecting to \"memory\".\n"
 
 
 
27119 " -w Show the output in a web browser. Output is\n"
27120 " written into a temporary HTML file until the\n"
27121 " redirect ends, then the web browser is launched.\n"
27122 " Query results are shown as HTML tables, unless\n"
27123 " the --plain is used too.\n"
@@ -26970,10 +27141,39 @@
27141 " file in a web browser\n"
27142 " -x Show the output in a spreadsheet. Output is\n"
27143 " written to a temp file as CSV then the spreadsheet\n"
27144 " is launched when\n"
27145 },
27146 { ".check",
27147 "USAGE: .check [OPTIONS] PATTERN\n"
27148 "\n"
27149 "Verify results of commands since the most recent .testcase command.\n"
27150 "Restore output to the console, unless --keep is used.\n"
27151 "\n"
27152 "If PATTERN starts with \"<<ENDMARK\" then the actual pattern is taken from\n"
27153 "subsequent lines of text up to the first line that begins with ENDMARK.\n"
27154 "All pattern lines and the ENDMARK are discarded.\n"
27155 "\n"
27156 "Options:\n"
27157 " --exact Do an exact comparison including leading and\n"
27158 " trailing whitespace.\n"
27159 " --glob Treat PATTERN as a GLOB\n"
27160 " --keep Do not reset the testcase. More .check commands\n"
27161 " will follow.\n"
27162 " --notglob Output should not match PATTERN\n"
27163 " --show Write testcase output to the screen, for debugging.\n"
27164 },
27165 { ".testcase",
27166 "USAGE: .testcase [OPTIONS] NAME\n"
27167 "\n"
27168 "Start a new test case identified by NAME. All output\n"
27169 "through the next \".check\" command is captured for comparison. See the\n"
27170 "\".check\" commandn for additional informatioon.\n"
27171 "\n"
27172 "Options:\n"
27173 " --error-prefix TEXT Change error message prefix text to TEXT\n"
27174 },
27175 };
27176
27177 /*
27178 ** Return a pointer to usage text for zCmd, or NULL if none exists.
27179 */
@@ -27193,10 +27393,56 @@
27393 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
27394 }
27395 return 1;
27396 }
27397 #endif
27398
27399 /*
27400 ** Return the size of the named file in bytes. Or return a negative
27401 ** number if the file does not exist.
27402 */
27403 static sqlite3_int64 fileSize(const char *zFile){
27404 #if defined(_WIN32) || defined(WIN32)
27405 struct _stat64 x;
27406 if( _stat64(zFile, &x)!=0 ) return -1;
27407 return (sqlite3_int64)x.st_size;
27408 #else
27409 struct stat x;
27410 if( stat(zFile, &x)!=0 ) return -1;
27411 return (sqlite3_int64)x.st_size;
27412 #endif
27413 }
27414
27415 /*
27416 ** Return true if zFile is an SQLite database.
27417 **
27418 ** Algorithm:
27419 ** * If the file does not exist -> return false
27420 ** * If the size of the file is not a multiple of 512 -> return false
27421 ** * If sqlite3_open() fails -> return false
27422 ** * if sqlite3_prepare() or sqlite3_step() fails -> return false
27423 ** * Otherwise -> return true
27424 */
27425 static int isDatabaseFile(const char *zFile, int openFlags){
27426 sqlite3 *db = 0;
27427 sqlite3_stmt *pStmt = 0;
27428 int rc;
27429 sqlite3_int64 sz = fileSize(zFile);
27430 if( sz<512 || (sz%512)!=0 ) return 0;
27431 if( sqlite3_open_v2(zFile, &db, openFlags, 0)==SQLITE_OK
27432 && sqlite3_prepare_v2(db,"SELECT count(*) FROM sqlite_schema",-1,&pStmt,0)
27433 ==SQLITE_OK
27434 && sqlite3_step(pStmt)==SQLITE_ROW
27435 ){
27436 rc = 1;
27437 }else{
27438 rc = 0;
27439 }
27440 sqlite3_finalize(pStmt);
27441 sqlite3_close(db);
27442 return rc;
27443 }
27444
27445 /*
27446 ** Try to deduce the type of file for zName based on its content. Return
27447 ** one of the SHELL_OPEN_* constants.
27448 **
@@ -27206,24 +27452,16 @@
27452 ** the type cannot be determined from content.
27453 */
27454 int deduceDatabaseType(const char *zName, int dfltZip, int openFlags){
27455 FILE *f;
27456 size_t n;
 
 
27457 int rc = SHELL_OPEN_UNSPEC;
27458 char zBuf[100];
27459 if( access(zName,0)!=0 ) goto database_type_by_name;
27460 if( isDatabaseFile(zName, openFlags) ){
 
 
 
 
27461 rc = SHELL_OPEN_NORMAL;
27462 }
 
 
27463 if( rc==SHELL_OPEN_NORMAL ) return SHELL_OPEN_NORMAL;
27464 f = sqlite3_fopen(zName, "rb");
27465 if( f==0 ) goto database_type_by_name;
27466 n = fread(zBuf, 16, 1, f);
27467 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
@@ -27253,10 +27491,39 @@
27491 }else{
27492 rc = SHELL_OPEN_NORMAL;
27493 }
27494 return rc;
27495 }
27496
27497 /*
27498 ** If the text in z[] is the name of a readable file and that file appears
27499 ** to contain SQL text and/or dot-commands, then return true. If z[] is
27500 ** not a file, or if the file is unreadable, or if the file is a database
27501 ** or anything else that is not SQL text and dot-commands, then return false.
27502 **
27503 ** If the bLeaveUninit flag is set, then be sure to leave SQLite in an
27504 ** uninitialized state. This means invoking sqlite3_shutdown() after any
27505 ** SQLite API is used.
27506 **
27507 ** Some amount of guesswork is involved in this decision.
27508 */
27509 static int isScriptFile(const char *z, int bLeaveUninit){
27510 sqlite3_int64 sz = fileSize(z);
27511 if( sz<=0 ) return 0;
27512 if( (sz%512)==0 ){
27513 int rc;
27514 sqlite3_initialize();
27515 rc = isDatabaseFile(z, SQLITE_OPEN_READONLY);
27516 if( bLeaveUninit ){
27517 sqlite3_shutdown();
27518 }
27519 if( rc ) return 0; /* Is a database */
27520 }
27521 if( sqlite3_strlike("%.sql",z,0)==0 ) return 1;
27522 if( sqlite3_strlike("%.txt",z,0)==0 ) return 1;
27523 return 0;
27524 }
27525
27526 #ifndef SQLITE_OMIT_DESERIALIZE
27527 /*
27528 ** Reconstruct an in-memory database using the output from the "dbtotxt"
27529 ** program. Read content from the file in p->aAuxDb[].zDbFilename.
@@ -27899,20 +28166,24 @@
28166 typedef struct ImportCtx ImportCtx;
28167 struct ImportCtx {
28168 const char *zFile; /* Name of the input file */
28169 FILE *in; /* Read the CSV text from this input stream */
28170 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */
28171 char *zIn; /* Input text */
28172 char *z; /* Accumulated text for a field */
28173 i64 nUsed; /* Bytes of zIn[] used so far */
28174 i64 n; /* Number of bytes in z */
28175 i64 nAlloc; /* Space allocated for z[] */
28176 int nLine; /* Current line number */
28177 int nRow; /* Number of rows imported */
28178 int nErr; /* Number of errors encountered */
28179 int bNotFirst; /* True if one or more bytes already read */
28180 int cTerm; /* Character that terminated the most recent field */
28181 int cColSep; /* The column separator character. (Usually ",") */
28182 int cRowSep; /* The row separator character. (Usually "\n") */
28183 int cQEscape; /* Escape character with "...". 0 for none */
28184 int cUQEscape; /* Escape character not with "...". 0 for none */
28185 };
28186
28187 /* Clean up resourced used by an ImportCtx */
28188 static void import_cleanup(ImportCtx *p){
28189 if( p->in!=0 && p->xCloser!=0 ){
@@ -27919,13 +28190,32 @@
28190 p->xCloser(p->in);
28191 p->in = 0;
28192 }
28193 sqlite3_free(p->z);
28194 p->z = 0;
28195 if( p->zIn ){
28196 sqlite3_free(p->zIn);
28197 p->zIn = 0;
28198 }
28199 }
28200
28201 /* Read a single character of the .import input text. Return EOF
28202 ** at end-of-file.
28203 */
28204 static int import_getc(ImportCtx *p){
28205 if( p->in ){
28206 return fgetc(p->in);
28207 }else if( p->zIn && p->zIn[p->nUsed]!=0 ){
28208 return p->zIn[p->nUsed++];
28209 }else{
28210 return EOF;
28211 }
28212 }
28213
28214 /* Append a single byte to the field value begin constructed
28215 ** in the p->z[] buffer
28216 */
28217 static void import_append_char(ImportCtx *p, int c){
28218 if( p->n+1>=p->nAlloc ){
28219 p->nAlloc += p->nAlloc + 100;
28220 p->z = sqlite3_realloc64(p->z, p->nAlloc);
28221 shell_check_oom(p->z);
@@ -27937,12 +28227,12 @@
28227 ** with the option of having a separator other than ",".
28228 **
28229 ** + Input comes from p->in.
28230 ** + Store results in p->z of length p->n. Space to hold p->z comes
28231 ** from sqlite3_malloc64().
28232 ** + Use p->cColSep as the column separator. The default is ",".
28233 ** + Use p->cRowSep as the row separator. The default is "\n".
28234 ** + Keep track of the line number in p->nLine.
28235 ** + Store the character that terminates the field in p->cTerm. Store
28236 ** EOF on end-of-file.
28237 ** + Report syntax errors on stderr
28238 */
@@ -27949,23 +28239,30 @@
28239 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
28240 int c;
28241 int cSep = (u8)p->cColSep;
28242 int rSep = (u8)p->cRowSep;
28243 p->n = 0;
28244 c = import_getc(p);
28245 if( c==EOF || seenInterrupt ){
28246 p->cTerm = EOF;
28247 return 0;
28248 }
28249 if( c=='"' ){
28250 int pc, ppc;
28251 int startLine = p->nLine;
28252 int cQuote = c;
28253 int cEsc = (u8)p->cQEscape;
28254 pc = ppc = 0;
28255 while( 1 ){
28256 c = import_getc(p);
28257 if( c==rSep ) p->nLine++;
28258 if( c==cEsc && cEsc!=0 ){
28259 c = import_getc(p);
28260 import_append_char(p, c);
28261 ppc = pc = 0;
28262 continue;
28263 }
28264 if( c==cQuote ){
28265 if( pc==cQuote ){
28266 pc = 0;
28267 continue;
28268 }
@@ -27979,11 +28276,11 @@
28276 p->cTerm = c;
28277 break;
28278 }
28279 if( pc==cQuote && c!='\r' ){
28280 cli_printf(stderr,"%s:%d: unescaped %c character\n",
28281 p->zFile, p->nLine, cQuote);
28282 }
28283 if( c==EOF ){
28284 cli_printf(stderr,"%s:%d: unterminated %c-quoted field\n",
28285 p->zFile, startLine, cQuote);
28286 p->cTerm = c;
@@ -27994,26 +28291,28 @@
28291 pc = c;
28292 }
28293 }else{
28294 /* If this is the first field being parsed and it begins with the
28295 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
28296 int cEsc = p->cUQEscape;
28297 if( (c&0xff)==0xef && p->bNotFirst==0 ){
28298 import_append_char(p, c);
28299 c = import_getc(p);
28300 if( (c&0xff)==0xbb ){
28301 import_append_char(p, c);
28302 c = import_getc(p);
28303 if( (c&0xff)==0xbf ){
28304 p->bNotFirst = 1;
28305 p->n = 0;
28306 return csv_read_one_field(p);
28307 }
28308 }
28309 }
28310 while( c!=EOF && c!=cSep && c!=rSep ){
28311 if( c==cEsc && cEsc!=0 ) c = import_getc(p);
28312 import_append_char(p, c);
28313 c = import_getc(p);
28314 }
28315 if( c==rSep ){
28316 p->nLine++;
28317 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
28318 }
@@ -28027,12 +28326,12 @@
28326 /* Read a single field of ASCII delimited text.
28327 **
28328 ** + Input comes from p->in.
28329 ** + Store results in p->z of length p->n. Space to hold p->z comes
28330 ** from sqlite3_malloc64().
28331 ** + Use p->cColSep as the column separator. The default is "\x1F".
28332 ** + Use p->cRowSep as the row separator. The default is "\x1E".
28333 ** + Keep track of the row number in p->nLine.
28334 ** + Store the character that terminates the field in p->cTerm. Store
28335 ** EOF on end-of-file.
28336 ** + Report syntax errors on stderr
28337 */
@@ -28039,18 +28338,18 @@
28338 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
28339 int c;
28340 int cSep = (u8)p->cColSep;
28341 int rSep = (u8)p->cRowSep;
28342 p->n = 0;
28343 c = import_getc(p);
28344 if( c==EOF || seenInterrupt ){
28345 p->cTerm = EOF;
28346 return 0;
28347 }
28348 while( c!=EOF && c!=cSep && c!=rSep ){
28349 import_append_char(p, c);
28350 c = import_getc(p);
28351 }
28352 if( c==rSep ){
28353 p->nLine++;
28354 }
28355 p->cTerm = c;
@@ -30151,11 +30450,11 @@
30450 ;
30451 static const char * const zCollectVar = "\
30452 SELECT\
30453 '('||x'0a'\
30454 || group_concat(\
30455 cname||' ANY',\
30456 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
30457 ||')' AS ColsSpec \
30458 FROM (\
30459 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
30460 FROM ColNames ORDER BY cpos\
@@ -30351,19 +30650,33 @@
30650 ** USAGE: .import [OPTIONS] FILE TABLE
30651 **
30652 ** Import CSV or similar text from FILE into TABLE. If TABLE does
30653 ** not exist, it is created using the first row of FILE as the column
30654 ** names. If FILE begins with "|" then it is a command that is run
30655 ** and the output from the command is used as the input data. If
30656 ** FILE begins with "<<" followed by a label, then content is read from
30657 ** the script until the first line that matches the label.
30658 **
30659 ** The content of FILE is interpreted using RFC-4180 ("CSV") quoting
30660 ** rules unless the current mode is "ascii" or "tabs" or unless one
30661 ** the --ascii option is used.
30662 **
30663 ** The column and row separators must be single ASCII characters. If
30664 ** multiple characters or a Unicode character are specified for the
30665 ** separators, then only the first byte of the separator is used. Except,
30666 ** if the row separator is \n and the mode is not --ascii, then \r\n is
30667 ** understood as a row separator too.
30668 **
30669 ** Options:
30670 ** --ascii Do not use RFC-4180 quoting. Use \037 and \036
30671 ** as column and row separators on input, unless other
30672 ** delimiters are specified using --colsep and/or --rowsep
30673 ** --colsep CHAR Use CHAR as the column separator.
30674 ** --csv Input is standard RFC-4180 CSV.
30675 ** --esc CHAR Use CHAR as an escape character in unquoted CSV inputs.
30676 ** --qesc CHAR Use CHAR as an escape character in quoted CSV inputs.
30677 ** --rowsep CHAR Use CHAR as the row separator.
30678 ** --schema S When creating TABLE, put it in schema S
30679 ** --skip N Ignore the first N rows of input
30680 ** -v Verbose mode
30681 */
30682 static int dotCmdImport(ShellState *p){
@@ -30375,17 +30688,16 @@
30688 sqlite3_stmt *pStmt = NULL; /* A statement */
30689 int nCol; /* Number of columns in the table */
30690 i64 nByte; /* Number of bytes in an SQL string */
30691 int i, j; /* Loop counters */
30692 int needCommit; /* True to COMMIT or ROLLBACK at end */
 
30693 char *zSql = 0; /* An SQL statement */
30694 ImportCtx sCtx; /* Reader context */
30695 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
30696 int eVerbose = 0; /* Larger for more console output */
30697 i64 nSkip = 0; /* Initial lines to skip */
30698 i64 iLineOffset = 0; /* Offset to the first line of input */
30699 char *zCreate = 0; /* CREATE TABLE statement text */
30700 int rc; /* Result code */
30701
30702 failIfSafeMode(p, "cannot run .import in safe mode");
30703 memset(&sCtx, 0, sizeof(sCtx));
@@ -30411,70 +30723,71 @@
30723 }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
30724 zSchema = azArg[++i];
30725 }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
30726 nSkip = integerValue(azArg[++i]);
30727 }else if( cli_strcmp(z,"-ascii")==0 ){
30728 if( sCtx.cColSep==0 ) sCtx.cColSep = SEP_Unit[0];
30729 if( sCtx.cRowSep==0 ) sCtx.cRowSep = SEP_Record[0];
30730 xRead = ascii_read_one_field;
 
30731 }else if( cli_strcmp(z,"-csv")==0 ){
30732 if( sCtx.cColSep==0 ) sCtx.cColSep = ',';
30733 if( sCtx.cRowSep==0 ) sCtx.cRowSep = '\n';
30734 xRead = csv_read_one_field;
30735 }else if( cli_strcmp(z,"-esc")==0 ){
30736 sCtx.cUQEscape = azArg[++i][0];
30737 }else if( cli_strcmp(z,"-qesc")==0 ){
30738 sCtx.cQEscape = azArg[++i][0];
30739 }else if( cli_strcmp(z,"-colsep")==0 ){
30740 if( i==nArg-1 ){
30741 dotCmdError(p, i, "missing argument", 0);
30742 return 1;
30743 }
30744 i++;
30745 sCtx.cColSep = azArg[i][0];
30746 }else if( cli_strcmp(z,"-rowsep")==0 ){
30747 if( i==nArg-1 ){
30748 dotCmdError(p, i, "missing argument", 0);
30749 return 1;
30750 }
30751 i++;
30752 sCtx.cRowSep = azArg[i][0];
30753 }else{
30754 dotCmdError(p, i, "unknown option", 0);
30755 return 1;
30756 }
30757 }
30758 if( zTable==0 ){
30759 dotCmdError(p, nArg, 0, "Missing %s argument\n",
30760 zFile==0 ? "FILE" : "TABLE");
30761 return 1;
30762 }
30763 seenInterrupt = 0;
30764 open_db(p, 0);
30765 if( sCtx.cColSep==0 ){
30766 if( p->mode.spec.zColumnSep && p->mode.spec.zColumnSep[0]!=0 ){
30767 sCtx.cColSep = p->mode.spec.zColumnSep[0];
30768 }else{
30769 sCtx.cColSep = ',';
30770 }
30771 }
30772 if( (sCtx.cColSep & 0x80)!=0 ){
30773 eputz("Error: .import column separator must be ASCII\n");
30774 return 1;
30775 }
30776 if( sCtx.cRowSep==0 ){
30777 if( p->mode.spec.zRowSep && p->mode.spec.zRowSep[0]!=0 ){
30778 sCtx.cRowSep = p->mode.spec.zRowSep[0];
30779 }else{
30780 sCtx.cRowSep = '\n';
30781 }
30782 }
30783 if( sCtx.cRowSep=='\r' && xRead!=ascii_read_one_field ){
30784 sCtx.cRowSep = '\n';
30785 }
30786 if( (sCtx.cRowSep & 0x80)!=0 ){
30787 eputz("Error: .import row separator must be ASCII\n");
30788 return 1;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30789 }
30790 sCtx.zFile = zFile;
30791 sCtx.nLine = 1;
30792 if( sCtx.zFile[0]=='|' ){
30793 #ifdef SQLITE_OMIT_POPEN
@@ -30483,19 +30796,58 @@
30796 #else
30797 sCtx.in = sqlite3_popen(sCtx.zFile+1, "r");
30798 sCtx.zFile = "<pipe>";
30799 sCtx.xCloser = pclose;
30800 #endif
30801 }else if( sCtx.zFile[0]=='<' && sCtx.zFile[1]=='<' && sCtx.zFile[2]!=0 ){
30802 /* Input text comes from subsequent lines of script until the zFile
30803 ** delimiter */
30804 int nEndMark = strlen30(zFile)-2;
30805 char *zEndMark = &zFile[2];
30806 sqlite3_str *pContent = sqlite3_str_new(p->db);
30807 int ckEnd = 1;
30808 i64 iStart = p->lineno;
30809 char zLine[2000];
30810 sCtx.zFile = p->zInFile;
30811 sCtx.nLine = p->lineno+1;
30812 iLineOffset = p->lineno;
30813 while( sqlite3_fgets(zLine,sizeof(zLine),p->in) ){
30814 if( ckEnd && cli_strncmp(zLine,zEndMark,nEndMark)==0 ){
30815 ckEnd = 2;
30816 if( strchr(zLine,'\n') ) p->lineno++;
30817 break;
30818 }
30819 if( strchr(zLine,'\n') ){
30820 p->lineno++;
30821 ckEnd = 1;
30822 }else{
30823 ckEnd = 0;
30824 }
30825 sqlite3_str_appendall(pContent, zLine);
30826 }
30827 sCtx.zIn = sqlite3_str_finish(pContent);
30828 if( sCtx.zIn==0 ){
30829 sCtx.zIn = sqlite3_mprintf("");
30830 }
30831 if( ckEnd<2 ){
30832 i64 savedLn = p->lineno;
30833 p->lineno = iStart;
30834 dotCmdError(p, 0, 0,"Content terminator \"%s\" not found.",zEndMark);
30835 p->lineno = savedLn;
30836 import_cleanup(&sCtx);
30837 return 1;
30838 }
30839 }else{
30840 sCtx.in = sqlite3_fopen(sCtx.zFile, "rb");
30841 sCtx.xCloser = fclose;
30842 }
30843 if( sCtx.in==0 && sCtx.zIn==0 ){
30844 dotCmdError(p, 0, 0, "cannot open \"%s\"", zFile);
30845 import_cleanup(&sCtx);
30846 return 1;
30847 }
30848 if( eVerbose>=1 ){
30849 char zSep[2];
30850 zSep[1] = 0;
30851 zSep[0] = sCtx.cColSep;
30852 cli_puts("Column separator ", p->out);
30853 output_c_string(p->out, zSep);
@@ -30648,10 +31000,14 @@
31000 if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){
31001 z = "";
31002 }
31003 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
31004 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
31005 if( i==0 && (strcmp(z,"\n")==0 || strcmp(z,"\r\n")==0) ){
31006 /* Ignore trailing \n or \r\n when some other row separator */
31007 break;
31008 }
31009 cli_printf(stderr,"%s:%d: expected %d columns but found %d"
31010 " - filling the rest with NULL\n",
31011 sCtx.zFile, startLine, nCol, i+1);
31012 i += 2;
31013 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
@@ -30671,10 +31027,11 @@
31027 rc = sqlite3_reset(pStmt);
31028 if( rc!=SQLITE_OK ){
31029 cli_printf(stderr,"%s:%d: INSERT failed: %s\n",
31030 sCtx.zFile, startLine, sqlite3_errmsg(p->db));
31031 sCtx.nErr++;
31032 if( bail_on_error ) break;
31033 }else{
31034 sCtx.nRow++;
31035 }
31036 }
31037 }while( sCtx.cTerm!=EOF );
@@ -30683,13 +31040,13 @@
31040 sqlite3_finalize(pStmt);
31041 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
31042 if( eVerbose>0 ){
31043 cli_printf(p->out,
31044 "Added %d rows with %d errors using %d lines of input\n",
31045 sCtx.nRow, sCtx.nErr, sCtx.nLine-1-iLineOffset);
31046 }
31047 return sCtx.nErr ? 1 : 0;
31048 }
31049
31050
31051 /*
31052 ** This function computes what to show the user about the configured
@@ -31100,10 +31457,11 @@
31457 if( k<0 ){
31458 dotCmdError(p, i, "bad --titles value","%z", zErr);
31459 return 1;
31460 }
31461 p->mode.spec.bTitles = k>=1 ? QRF_Yes : QRF_No;
31462 p->mode.mFlags &= ~MFLG_HDR;
31463 p->mode.spec.eTitle = k>1 ? k-1 : aModeInfo[p->mode.eMode].eHdr;
31464 chng = 1;
31465 }else if( optionMatch(z,"widths") || optionMatch(z,"width") ){
31466 int nWidth = 0;
31467 short int *aWidth;
@@ -31328,23 +31686,17 @@
31686 ** --bom Prepend a byte-order mark to the output
31687 ** -e Accumulate output in a temporary text file then
31688 ** launch a text editor when the redirection ends.
31689 ** --error-prefix X Use X as the left-margin prefix for error messages.
31690 ** Set to an empty string to restore the default.
31691 ** --keep Keep redirecting output to its current destination.
31692 ** Use this option in combination with --show or
31693 ** with --error-prefix when you do not want to stop
31694 ** a current redirection.
 
 
 
31695 ** --plain Use plain text rather than HTML tables with -w
31696 ** --show Show output text captured by .testcase or by
31697 ** redirecting to "memory".
 
 
 
31698 ** -w Show the output in a web browser. Output is
31699 ** written into a temporary HTML file until the
31700 ** redirect ends, then the web browser is launched.
31701 ** Query results are shown as HTML tables, unless
31702 ** the --plain is used too.
@@ -31382,13 +31734,11 @@
31734 char *zFile = 0; /* The FILE argument */
31735 int i; /* Loop counter */
31736 int eMode = 0; /* 0: .outout/.once, 'x'=.excel, 'w'=.www */
31737 int bOnce = 0; /* 0: .output, 1: .once, 2: .excel/.www */
31738 int bPlain = 0; /* --plain option */
31739 int bKeep = 0; /* Keep redirecting */
 
 
31740 static const char *zBomUtf8 = "\357\273\277";
31741 const char *zBom = 0;
31742 char c = azArg[0][0];
31743 int n = strlen30(azArg[0]);
31744
@@ -31410,36 +31760,21 @@
31760 zBom = zBomUtf8;
31761 }else if( cli_strcmp(z,"-plain")==0 ){
31762 bPlain = 1;
31763 }else if( c=='o' && z[0]=='1' && z[1]!=0 && z[2]==0
31764 && (z[1]=='x' || z[1]=='e' || z[1]=='w') ){
31765 if( bKeep || eMode ){
31766 dotCmdError(p, i, "incompatible with prior options",0);
31767 goto dotCmdOutput_error;
31768 }
31769 eMode = z[1];
 
 
31770 }else if( cli_strcmp(z,"-show")==0 ){
31771 if( cli_output_capture ){
31772 sqlite3_fprintf(stdout, "%s", sqlite3_str_value(cli_output_capture));
31773 }
31774 }else if( cli_strcmp(z,"-keep")==0 ){
31775 bKeep = 1;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31776 }else if( optionMatch(z,"error-prefix") ){
31777 if( i+1>=nArg ){
31778 dotCmdError(p, i, "missing argument", 0);
31779 return 1;
31780 }
@@ -31450,11 +31785,11 @@
31785 dotCmdError(p, i, "unknown option", 0);
31786 sqlite3_free(zFile);
31787 return 1;
31788 }
31789 }else if( zFile==0 && eMode==0 ){
31790 if( bKeep ){
31791 dotCmdError(p, i, "incompatible with prior options",0);
31792 goto dotCmdOutput_error;
31793 }
31794 if( cli_strcmp(z, "memory")==0 && bOnce ){
31795 dotCmdError(p, 0, "cannot redirect to \"memory\"", 0);
@@ -31486,53 +31821,10 @@
31821 if( bOnce ){
31822 p->nPopOutput = 2;
31823 }else{
31824 p->nPopOutput = 0;
31825 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31826 if( !bKeep ) output_reset(p);
31827 #ifndef SQLITE_NOHAVE_SYSTEM
31828 if( eMode=='e' || eMode=='x' || eMode=='w' ){
31829 p->doXdgOpen = 1;
31830 modePush(p);
@@ -31609,10 +31901,199 @@
31901
31902 dotCmdOutput_error:
31903 sqlite3_free(zFile);
31904 return 1;
31905 }
31906
31907 /*
31908 ** DOT-COMMAND: .check
31909 ** USAGE: .check [OPTIONS] PATTERN
31910 **
31911 ** Verify results of commands since the most recent .testcase command.
31912 ** Restore output to the console, unless --keep is used.
31913 **
31914 ** If PATTERN starts with "<<ENDMARK" then the actual pattern is taken from
31915 ** subsequent lines of text up to the first line that begins with ENDMARK.
31916 ** All pattern lines and the ENDMARK are discarded.
31917 **
31918 ** Options:
31919 ** --exact Do an exact comparison including leading and
31920 ** trailing whitespace.
31921 ** --glob Treat PATTERN as a GLOB
31922 ** --keep Do not reset the testcase. More .check commands
31923 ** will follow.
31924 ** --notglob Output should not match PATTERN
31925 ** --show Write testcase output to the screen, for debugging.
31926 */
31927 static int dotCmdCheck(ShellState *p){
31928 int nArg = p->dot.nArg; /* Number of arguments */
31929 char **azArg = p->dot.azArg; /* Text of the arguments */
31930 int i; /* Loop counter */
31931 int k; /* Result of pickStr() */
31932 char *zTest; /* Textcase result */
31933 int bKeep = 0; /* --keep option */
31934 char *zCheck = 0; /* PATTERN argument */
31935 char *zPattern = 0; /* Actual test pattern */
31936 int eCheck = 0; /* 1: --glob, 2: --notglob, 3: --exact */
31937 int isOk; /* True if results are OK */
31938 sqlite3_int64 iStart = p->lineno; /* Line number of .check statement */
31939
31940 if( p->zTestcase[0]==0 ){
31941 dotCmdError(p, 0, "no .testcase is active", 0);
31942 return 1;
31943 }
31944 for(i=1; i<nArg; i++){
31945 char *z = azArg[i];
31946 if( z[0]=='-' && z[1]=='-' && z[2]!=0 ) z++;
31947 if( cli_strcmp(z,"-keep")==0 ){
31948 bKeep = 1;
31949 }else if( cli_strcmp(z,"-show")==0 ){
31950 if( cli_output_capture ){
31951 sqlite3_fprintf(stdout, "%s", sqlite3_str_value(cli_output_capture));
31952 }
31953 bKeep = 1;
31954 }else if( z[0]=='-'
31955 && (k = pickStr(&z[1],0,"glob","notglob","exact",""))>=0
31956 ){
31957 if( eCheck && eCheck!=k+1 ){
31958 dotCmdError(p, i, "incompatible with prior options",0);
31959 return 1;
31960 }
31961 eCheck = k+1;
31962 }else if( zCheck ){
31963 dotCmdError(p, i, "unknown option", 0);
31964 return 1;
31965 }else{
31966 zCheck = azArg[i];
31967 }
31968 }
31969 if( zCheck==0 ){
31970 dotCmdError(p, 0, "no PATTERN specified", 0);
31971 return 1;
31972 }
31973 if( cli_output_capture && sqlite3_str_length(cli_output_capture) ){
31974 zTest = sqlite3_str_value(cli_output_capture);
31975 shell_check_oom(zTest);
31976 }else{
31977 zTest = "";
31978 }
31979 p->nTestRun++;
31980 if( zCheck[0]=='<' && zCheck[1]=='<' && zCheck[2]!=0 ){
31981 int nCheck = strlen30(zCheck);
31982 sqlite3_str *pPattern = sqlite3_str_new(p->db);
31983 char zLine[2000];
31984 while( sqlite3_fgets(zLine,sizeof(zLine),p->in) ){
31985 if( strchr(zLine,'\n') ) p->lineno++;
31986 if( cli_strncmp(&zCheck[2],zLine,nCheck-2)==0 ) break;
31987 sqlite3_str_appendall(pPattern, zLine);
31988 }
31989 zPattern = sqlite3_str_finish(pPattern);
31990 if( zPattern==0 ){
31991 zPattern = sqlite3_mprintf("");
31992 }
31993 }else{
31994 zPattern = zCheck;
31995 }
31996 shell_check_oom(zPattern);
31997 switch( eCheck ){
31998 case 1: {
31999 char *zGlob = sqlite3_mprintf("*%s*", zPattern);
32000 isOk = testcase_glob(zGlob, zTest)!=0;
32001 sqlite3_free(zGlob);
32002 break;
32003 }
32004 case 2: {
32005 char *zGlob = sqlite3_mprintf("*%s*", zPattern);
32006 isOk = testcase_glob(zGlob, zTest)==0;
32007 sqlite3_free(zGlob);
32008 break;
32009 }
32010 case 3: {
32011 isOk = cli_strcmp(zTest,zPattern)==0;
32012 break;
32013 }
32014 default: {
32015 /* Skip leading and trailing \n and \r on both pattern and test output */
32016 const char *z1 = zPattern;
32017 const char *z2 = zTest;
32018 size_t n1, n2;
32019 while( z1[0]=='\n' || z1[0]=='\r' ) z1++;
32020 n1 = strlen(z1);
32021 while( n1>0 && (z1[n1-1]=='\n' || z1[n1-1]=='\r') ) n1--;
32022 while( z2[0]=='\n' || z2[0]=='\r' ) z2++;
32023 n2 = strlen(z2);
32024 while( n2>0 && (z2[n2-1]=='\n' || z2[n2-1]=='\r') ) n2--;
32025 isOk = n1==n2 && memcmp(z1,z2,n1)==0;
32026 break;
32027 }
32028 }
32029 if( !isOk ){
32030 sqlite3_fprintf(stderr,
32031 "%s:%lld: .check failed for testcase %s\n",
32032 p->zInFile, iStart, p->zTestcase);
32033 p->nTestErr++;
32034 sqlite3_fprintf(stderr, "Expected: [%s]\n", zPattern);
32035 sqlite3_fprintf(stderr, "Got: [%s]\n", zTest);
32036 }
32037 if( zPattern!=zCheck ){
32038 sqlite3_free(zPattern);
32039 }
32040 if( !bKeep ){
32041 output_reset(p);
32042 p->zTestcase[0] = 0;
32043 }
32044 return 0;
32045 }
32046
32047 /*
32048 ** DOT-COMMAND: .testcase
32049 ** USAGE: .testcase [OPTIONS] NAME
32050 **
32051 ** Start a new test case identified by NAME. All output
32052 ** through the next ".check" command is captured for comparison. See the
32053 ** ".check" commandn for additional informatioon.
32054 **
32055 ** Options:
32056 ** --error-prefix TEXT Change error message prefix text to TEXT
32057 */
32058 static int dotCmdTestcase(ShellState *p){
32059 int nArg = p->dot.nArg; /* Number of arguments */
32060 char **azArg = p->dot.azArg; /* Text of the arguments */
32061 int i; /* Loop counter */
32062 const char *zName = 0; /* Testcase name */
32063
32064 for(i=1; i<nArg; i++){
32065 char *z = azArg[i];
32066 if( z[0]=='-' && z[1]=='-' && z[2]!=0 ) z++;
32067 if( optionMatch(z,"error-prefix") ){
32068 if( i+1>=nArg ){
32069 dotCmdError(p, i, "missing argument", 0);
32070 return 1;
32071 }
32072 free(p->zErrPrefix);
32073 i++;
32074 p->zErrPrefix = azArg[i][0]==0 ? 0 : strdup(azArg[i]);
32075 }else if( zName ){
32076 dotCmdError(p, i, "unknown option", 0);
32077 return 1;
32078 }else{
32079 zName = azArg[i];
32080 }
32081 }
32082 output_reset(p);
32083 if( cli_output_capture ){
32084 sqlite3_str_free(cli_output_capture);
32085 }
32086 cli_output_capture = sqlite3_str_new(0);
32087 if( zName ){
32088 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", zName);
32089 }else{
32090 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s:%lld",
32091 p->zInFile, p->lineno);
32092 }
32093 return 0;
32094 }
32095
32096 /*
32097 ** Enlarge the space allocated in p->dot so that it can hold more
32098 ** than nArg parsed command-line arguments.
32099 */
@@ -31641,11 +32122,11 @@
32122 free(p->dot.zCopy);
32123 z = p->dot.zCopy = strdup(zLine);
32124 shell_check_oom(z);
32125 szLine = strlen(z);
32126 while( szLine>0 && IsSpace(z[szLine-1]) ) szLine--;
32127 if( szLine>0 && z[szLine-1]==';' ){
32128 szLine--;
32129 while( szLine>0 && IsSpace(z[szLine-1]) ) szLine--;
32130 }
32131 z[szLine] = 0;
32132 parseDotRealloc(p, 2);
@@ -31861,35 +32342,17 @@
32342 eputz("Usage: .changes on|off\n");
32343 rc = 1;
32344 }
32345 }else
32346
 
32347 /* Cancel output redirection, if it is currently set (by .testcase)
32348 ** Then read the content of the testcase-out.txt file and compare against
32349 ** azArg[1]. If there are differences, report an error and exit.
32350 */
32351 if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
32352 rc = dotCmdCheck(p);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32353 }else
 
32354
32355 #ifndef SQLITE_SHELL_FIDDLE
32356 if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
32357 failIfSafeMode(p, "cannot run .clone in safe mode");
32358 if( nArg==2 ){
@@ -32468,10 +32931,11 @@
32931 }else
32932
32933 if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
32934 if( nArg==2 ){
32935 p->mode.spec.bTitles = booleanValue(azArg[1]) ? QRF_Yes : QRF_No;
32936 p->mode.mFlags |= MFLG_HDR;
32937 p->mode.spec.eTitle = aModeInfo[p->mode.eMode].eHdr;
32938 }else{
32939 eputz("Usage: .headers on|off\n");
32940 rc = 1;
32941 }
@@ -32521,14 +32985,14 @@
32985 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
32986 goto meta_command_exit;
32987 }
32988 zSql = sqlite3_mprintf(
32989 "SELECT rootpage, 0 FROM sqlite_schema"
32990 " WHERE type='index' AND lower(name)=lower('%q')"
32991 "UNION ALL "
32992 "SELECT rootpage, 1 FROM sqlite_schema"
32993 " WHERE type='table' AND lower(name)=lower('%q')"
32994 " AND sql LIKE '%%without%%rowid%%'",
32995 azArg[1], azArg[1]
32996 );
32997 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
32998 sqlite3_free(zSql);
@@ -32682,13 +33146,14 @@
33146 goto meta_command_exit;
33147 }
33148 if( nArg==3 ){
33149 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
33150 (int)integerValue(azArg[2]));
33151 }else{
33152 cli_printf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName,
33153 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
33154 }
 
 
33155 }
33156 }else
33157
33158 if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
33159 open_db(p, 0);
@@ -33027,10 +33492,23 @@
33492 continue;
33493 }
33494 if( cli_strcmp(z,"once")==0 ){
33495 p->flgProgress |= SHELL_PROGRESS_ONCE;
33496 continue;
33497 }
33498 if( cli_strcmp(z,"timeout")==0 ){
33499 if( i==nArg-1 ){
33500 dotCmdError(p, i, "missing argument", 0);
33501 return 1;
33502 }
33503 i++;
33504 p->tmProgress = atof(azArg[i]);
33505 if( p->tmProgress>0.0 ){
33506 p->flgProgress = SHELL_PROGRESS_QUIET|SHELL_PROGRESS_TMOUT;
33507 if( nn==0 ) nn = 100;
33508 }
33509 continue;
33510 }
33511 if( cli_strcmp(z,"limit")==0 ){
33512 if( i+1>=nArg ){
33513 eputz("Error: missing argument on --limit\n");
33514 rc = 1;
@@ -33233,21 +33711,22 @@
33711 || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
33712 || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
33713 || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
33714 if( isSchema ){
33715 cli_printf(p->out,
33716 "CREATE TABLE %ssqlite_schema (\n"
33717 " type text,\n"
33718 " name text,\n"
33719 " tbl_name text,\n"
33720 " rootpage integer,\n"
33721 " sql text\n"
33722 ");\n",
33723 sqlite3_strlike("sqlite_t%",zName,0)==0 ? "temp." : ""
33724 );
33725 }
33726 }
33727 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
 
33728 if( rc ){
33729 shellDatabaseError(p->db);
33730 sqlite3_finalize(pStmt);
33731
33732 rc = 1;
@@ -33255,11 +33734,11 @@
33734 }
33735 pSql = sqlite3_str_new(p->db);
33736 sqlite3_str_appendf(pSql, "SELECT sql FROM", 0);
33737 iSchema = 0;
33738 while( sqlite3_step(pStmt)==SQLITE_ROW ){
33739 const char *zDb = (const char*)sqlite3_column_text(pStmt, 1);
33740 char zScNum[30];
33741 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
33742 sqlite3_str_appendall(pSql, zDiv);
33743 zDiv = " UNION ALL ";
33744 if( sqlite3_stricmp(zDb, "main")==0 ){
@@ -33275,11 +33754,12 @@
33754 " AS sql, type, tbl_name, name, rowid, %d AS snum, %Q as sname",
33755 ++iSchema, zDb);
33756 sqlite3_str_appendf(pSql," FROM \"%w\".sqlite_schema", zDb);
33757 }
33758 sqlite3_finalize(pStmt);
33759 #if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS) \
33760 && !defined(SQLITE_OMIT_VIRTUALTABLE)
33761 if( zName ){
33762 sqlite3_str_appendall(pSql,
33763 " UNION ALL SELECT shell_module_schema(name),"
33764 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list");
33765 }
@@ -33299,11 +33779,11 @@
33779 }else{
33780 sqlite3_str_appendf(pSql, " LIKE %Q ESCAPE '\\' AND ", zName);
33781 }
33782 }
33783 if( bNoSystemTabs ){
33784 sqlite3_str_appendf(pSql, " name NOT LIKE 'sqlite__%%' ESCAPE '_' AND ");
33785 }
33786 sqlite3_str_appendf(pSql, "sql IS NOT NULL ORDER BY snum, rowid");
33787 if( bDebug ){
33788 cli_printf(p->out, "SQL: %s;\n", sqlite3_str_value(pSql));
33789 }else{
@@ -34017,25 +34497,15 @@
34497 sqlite3_str_free(pSql);
34498 modePop(p);
34499 if( rc ) return shellDatabaseError(p->db);
34500 }else
34501
34502 /* Set the p->zTestcase name and begin redirecting output into
34503 ** the cli_output_capture sqlite3_str */
34504 if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
34505 rc = dotCmdTestcase(p);
 
 
 
 
 
 
 
 
 
34506 }else
 
34507
34508 #ifndef SQLITE_UNTESTABLE
34509 if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
34510 static const struct {
34511 const char *zCtrlName; /* Name of a test-control option */
@@ -34527,17 +34997,21 @@
34997 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
34998 }else
34999
35000 if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
35001 if( nArg==2 ){
35002 if( cli_strcmp(azArg[1],"once")==0 ){
35003 p->enableTimer = 1;
35004 }else{
35005 p->enableTimer = 2*booleanValue(azArg[1]);
35006 }
35007 if( p->enableTimer && !HAS_TIMER ){
35008 eputz("Error: timer not available on this system.\n");
35009 p->enableTimer = 0;
35010 }
35011 }else{
35012 eputz("Usage: .timer on|off|once\n");
35013 rc = 1;
35014 }
35015 }else
35016
35017 #ifndef SQLITE_OMIT_TRACE
@@ -34708,10 +35182,11 @@
35182 if( p->nPopOutput ){
35183 p->nPopOutput--;
35184 if( p->nPopOutput==0 ) output_reset(p);
35185 }
35186 p->bSafeMode = p->bSafeModePersist;
35187 p->dot.nArg = 0;
35188 return rc;
35189 }
35190
35191 /* Line scan result and intermediate states (supporting scan resumption)
35192 */
@@ -34944,13 +35419,13 @@
35419 char *zErrMsg = 0;
35420
35421 open_db(p, 0);
35422 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
35423 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
35424 BEGIN_TIMER(p);
35425 rc = shell_exec(p, zSql, &zErrMsg);
35426 END_TIMER(p);
35427 if( rc || zErrMsg ){
35428 char zPrefix[100];
35429 const char *zErrorTail;
35430 const char *zErrorType;
35431 if( zErrMsg==0 ){
@@ -35351,11 +35826,10 @@
35826 " -bail stop after hitting an error\n"
35827 " -batch force batch I/O\n"
35828 " -box set output mode to 'box'\n"
35829 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
35830 " -column set output mode to 'column'\n"
 
35831 " -csv set output mode to 'csv'\n"
35832 #if !defined(SQLITE_OMIT_DESERIALIZE)
35833 " -deserialize open the database using sqlite3_deserialize()\n"
35834 #endif
35835 " -echo print inputs before execution\n"
@@ -35435,15 +35909,10 @@
35909 /*
35910 ** Initialize the state information in data
35911 */
35912 static void main_init(ShellState *p) {
35913 memset(p, 0, sizeof(*p));
 
 
 
 
 
35914 p->pAuxDb = &p->aAuxDb[0];
35915 p->shellFlgs = SHFLG_Lookaside;
35916 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, p);
35917 #if !defined(SQLITE_SHELL_FIDDLE)
35918 verify_uninitialized();
@@ -35498,29 +35967,65 @@
35967 cli_puts(z, p->out);
35968 fflush(p->out);
35969 return 1;
35970 }
35971
35972 /* Alternative name to the entry point for Fiddle */
 
 
 
 
 
 
 
 
35973 #ifdef SQLITE_SHELL_FIDDLE
35974 # define main fiddle_main
35975 #endif
35976
35977 /* Use the wmain() entry point on Windows. Translate arguments to
35978 ** UTF8, then invoke the traditional main() entry point which is
35979 ** renamed using a #define to utf8_main() .
35980 */
35981 #if defined(_WIN32) && !defined(main)
35982 # define main utf8_main /* Rename entry point to utf_main() */
35983 int SQLITE_CDECL utf8_main(int,char**); /* Forward declaration */
35984 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
35985 int rc, i;
35986 char **argv = malloc( sizeof(char*) * (argc+1) );
35987 char **orig = argv;
35988 if( argv==0 ){
35989 fprintf(stderr, "malloc failed\n");
35990 exit(1);
35991 }
35992 for(i=0; i<argc; i++){
35993 int nByte = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, 0, 0, 0, 0);
35994 if( nByte==0 ){
35995 argv[i] = 0;
35996 }else{
35997 argv[i] = malloc( nByte );
35998 if( argv[i]==0 ){
35999 fprintf(stderr, "malloc failed\n");
36000 exit(1);
36001 }
36002 nByte = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, argv[i],nByte,0,0);
36003 if( nByte==0 ){
36004 free(argv[i]);
36005 argv[i] = 0;
36006 }
36007 }
36008 }
36009 argv[argc] = 0;
36010 rc = utf8_main(argc, argv);
36011 for(i=0; i<argc; i++) free(orig[i]);
36012 free(argv);
36013 return rc;
36014 }
36015 #endif /* WIN32 */
36016
36017 /*
36018 ** This is the main entry point for the process. Everything starts here.
36019 **
36020 ** The "main" identifier may have been #defined to something else:
36021 **
36022 ** utf8_main On Windows
36023 ** fiddle_main In Fiddle
36024 ** sqlite3_shell Other projects that use shell.c as a subroutine
36025 */
36026 int SQLITE_CDECL main(int argc, char **argv){
36027 #ifdef SQLITE_DEBUG
36028 sqlite3_int64 mem_main_enter = 0;
36029 #endif
36030 char *zErrMsg = 0;
36031 #ifdef SQLITE_SHELL_FIDDLE
@@ -35538,14 +36043,10 @@
36043 int nOptsEnd = argc;
36044 int bEnableVfstrace = 0;
36045 char **azCmd = 0;
36046 int *aiCmd = 0;
36047 const char *zVfs = 0; /* Value of -vfs command-line option */
 
 
 
 
36048 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
36049
36050 #ifdef SQLITE_SHELL_FIDDLE
36051 stdin_is_interactive = 0;
36052 stdout_is_console = 1;
@@ -35596,36 +36097,10 @@
36097 exit(1);
36098 }
36099 #endif
36100 main_init(&data);
36101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36102 assert( argc>=1 && argv && argv[0] );
36103 Argv0 = argv[0];
36104
36105 #ifdef SQLITE_SHELL_DBNAME_PROC
36106 {
@@ -35637,11 +36112,11 @@
36112 SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
36113 warnInmemoryDb = 0;
36114 }
36115 #endif
36116
36117 /* Do an initial pass through the command-line arguments to locate
36118 ** the name of the database file, the name of the initialization file,
36119 ** the size of the alternative malloc heap, options affecting commands
36120 ** or SQL run from the command line, and the first command to execute.
36121 */
36122 #ifndef SQLITE_SHELL_FIDDLE
@@ -35649,11 +36124,11 @@
36124 #endif
36125 for(i=1; i<argc; i++){
36126 char *z;
36127 z = argv[i];
36128 if( z[0]!='-' || i>nOptsEnd ){
36129 if( data.aAuxDb->zDbFilename==0 && !isScriptFile(z,1) ){
36130 data.aAuxDb->zDbFilename = z;
36131 }else{
36132 /* Excess arguments are interpreted as SQL (or dot-commands) and
36133 ** mean that nothing is read from stdin */
36134 readStdin = 0;
@@ -35694,15 +36169,10 @@
36169 if( n<2 ){
36170 sqlite3_fprintf(stderr,"minimum --screenwidth is 2\n");
36171 exit(1);
36172 }
36173 stdout_tty_width = n;
 
 
 
 
 
36174 }else if( cli_strcmp(z,"-utf8")==0 ){
36175 }else if( cli_strcmp(z,"-no-utf8")==0 ){
36176 }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
36177 int val = 0;
36178 sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW, &val);
@@ -35822,10 +36292,20 @@
36292 }else if( cli_strcmp(z,"-safe")==0 ){
36293 /* no-op - catch this on the second pass */
36294 }else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
36295 /* skip over the argument */
36296 i++;
36297 }else if( cli_strcmp(z,"-test-argv")==0 ){
36298 /* Undocumented test option. Print the values in argv[] and exit.
36299 ** Use this to verify that any translation of the argv[], for example
36300 ** on Windows that receives wargv[] from the OS and must convert
36301 ** to UTF8 prior to calling this routine. */
36302 int kk;
36303 for(kk=0; kk<argc; kk++){
36304 sqlite3_fprintf(stdout,"argv[%d] = \"%s\"\n", kk, argv[kk]);
36305 }
36306 return 0;
36307 }
36308 }
36309 #ifndef SQLITE_SHELL_FIDDLE
36310 if( !bEnableVfstrace ) verify_uninitialized();
36311 #endif
@@ -35848,11 +36328,30 @@
36328
36329 if( zVfs ){
36330 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
36331 if( pVfs ){
36332 sqlite3_vfs_register(pVfs, 1);
36333 }
36334 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
36335 else if( access(zVfs,0)==0 ){
36336 /* If the VFS name is not the name of an existing VFS, but it is
36337 ** the name of a file, then try to load that file as an extension.
36338 ** Presumably the extension implements the desired VFS. */
36339 sqlite3 *db = 0;
36340 char *zErr = 0;
36341 sqlite3_open(":memory:", &db);
36342 sqlite3_enable_load_extension(db, 1);
36343 rc = sqlite3_load_extension(db, zVfs, 0, &zErr);
36344 sqlite3_close(db);
36345 if( (rc&0xff)!=SQLITE_OK ){
36346 cli_printf(stderr, "could not load extension VFS \"%s\": %s\n",
36347 zVfs, zErr);
36348 exit(1);
36349 }
36350 }
36351 #endif
36352 else{
36353 cli_printf(stderr,"no such VFS: \"%s\"\n", zVfs);
36354 exit(1);
36355 }
36356 }
36357
@@ -35889,11 +36388,11 @@
36388 ** is given on the command line, look for a file named ~/.sqliterc and
36389 ** try to process it.
36390 */
36391 if( !noInit ) process_sqliterc(&data,zInitFile);
36392
36393 /* Make a second pass through the command-line arguments and set
36394 ** options. This second pass is delayed until after the initialization
36395 ** file is processed so that the command-line arguments will override
36396 ** settings in the initialization file.
36397 */
36398 for(i=1; i<argc; i++){
@@ -36015,12 +36514,10 @@
36514 stdin_is_interactive = 1;
36515 }else if( cli_strcmp(z,"-batch")==0 ){
36516 /* already handled */
36517 }else if( cli_strcmp(z,"-screenwidth")==0 ){
36518 i++;
 
 
36519 }else if( cli_strcmp(z,"-utf8")==0 ){
36520 /* already handled */
36521 }else if( cli_strcmp(z,"-no-utf8")==0 ){
36522 /* already handled */
36523 }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
@@ -36116,11 +36613,22 @@
36613 ** command-line inputs, except for the argToSkip argument which contains
36614 ** the database filename.
36615 */
36616 for(i=0; i<nCmd; i++){
36617 echo_group_input(&data, azCmd[i]);
36618 if( isScriptFile(azCmd[i],0) ){
36619 FILE *inSaved = data.in;
36620 i64 savedLineno = data.lineno;
36621 int res = 1;
36622 if( (data.in = openChrSource(azCmd[i]))!=0 ){
36623 res = process_input(&data, azCmd[i]);
36624 fclose(data.in);
36625 }
36626 data.in = inSaved;
36627 data.lineno = savedLineno;
36628 if( res ) i = nCmd;
36629 }else if( azCmd[i][0]=='.' ){
36630 char *zErrCtx = malloc( 64 );
36631 shell_check_oom(zErrCtx);
36632 sqlite3_snprintf(64,zErrCtx,"argv[%i]:",aiCmd[i]);
36633 data.zInFile = "<cmdline>";
36634 data.zErrPrefix = zErrCtx;
@@ -36231,14 +36739,10 @@
36739 }
36740 find_home_dir(1);
36741 output_reset(&data);
36742 data.doXdgOpen = 0;
36743 clearTempFile(&data);
 
 
 
 
36744 modeFree(&data.mode);
36745 if( data.nSavedModes ){
36746 int ii;
36747 for(ii=0; ii<data.nSavedModes; ii++){
36748 modeFree(&data.aSavedModes[ii].mode);
36749
+1112 -736
--- extsrc/sqlite3.c
+++ extsrc/sqlite3.c
@@ -16,11 +16,11 @@
1616
** if you want a wrapper to interface SQLite with your choice of programming
1717
** language. The code for the "sqlite3" command-line shell is also in a
1818
** separate file. This file contains only code for the core SQLite library.
1919
**
2020
** The content in this amalgamation comes from Fossil check-in
21
-** 01409738afc2c0d5bdaa248ffb508aa5f36a with changes in files:
21
+** c476d956d0bd3065cf894de6f9d393b999ff with changes in files:
2222
**
2323
**
2424
*/
2525
#ifndef SQLITE_AMALGAMATION
2626
#define SQLITE_CORE 1
@@ -467,14 +467,14 @@
467467
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
468468
** [sqlite_version()] and [sqlite_source_id()].
469469
*/
470470
#define SQLITE_VERSION "3.52.0"
471471
#define SQLITE_VERSION_NUMBER 3052000
472
-#define SQLITE_SOURCE_ID "2025-12-11 23:24:05 01409738afc2c0d5bdaa248ffb508aa5f36a66390f6b8e4834734529ee8ed2fa"
472
+#define SQLITE_SOURCE_ID "2026-02-04 20:51:27 c476d956d0bd3065cf894de6f9d393b999ff7d2268a35f01a6d88804789ab58f"
473473
#define SQLITE_SCM_BRANCH "trunk"
474474
#define SQLITE_SCM_TAGS ""
475
-#define SQLITE_SCM_DATETIME "2025-12-11T23:24:05.667Z"
475
+#define SQLITE_SCM_DATETIME "2026-02-04T20:51:27.822Z"
476476
477477
/*
478478
** CAPI3REF: Run-Time Library Version Numbers
479479
** KEYWORDS: sqlite3_version sqlite3_sourceid
480480
**
@@ -4752,16 +4752,32 @@
47524752
** compiles to see if some SQL syntax is well-formed, without generating
47534753
** messages on the global error log when it is not. If the test compile
47544754
** fails, the sqlite3_prepare_v3() call returns the same error indications
47554755
** with or without this flag; it just omits the call to [sqlite3_log()] that
47564756
** logs the error.
4757
+**
4758
+** [[SQLITE_PREPARE_FROM_DDL]] <dt>SQLITE_PREPARE_FROM_DDL</dt>
4759
+** <dd>The SQLITE_PREPARE_FROM_DDL flag causes the SQL compiler to behave as if
4760
+** the SQL statement is part of a database schema. This makes a difference
4761
+** when the [SQLITE_DBCONFIG_TRUSTED_SCHEMA] option is set to off.
4762
+** When this option is used and SQLITE_DBCONFIG_TRUSTED_SCHEMA is off,
4763
+** SQL functions may not be called unless they are tagged with
4764
+** [SQLITE_INNOCUOUS] and virtual tables may not be used unless tagged
4765
+** with [SQLITE_VTAB_INNOCUOUS]. Use the SQLITE_PREPARE_FROM_DDL option
4766
+** when preparing SQL that is derived from parts of the database
4767
+** schema. In particular, virtual table implementations that
4768
+** run SQL statements based on the arguments to their CREATE VIRTUAL
4769
+** TABLE statement should use [sqlite3_prepare_v3()] and set the
4770
+** SQLITE_PREPARE_FROM_DLL flag to prevent bypass of the
4771
+** [SQLITE_DBCONFIG_TRUSTED_SCHEMA] security checks.
47574772
** </dl>
47584773
*/
47594774
#define SQLITE_PREPARE_PERSISTENT 0x01
47604775
#define SQLITE_PREPARE_NORMALIZE 0x02
47614776
#define SQLITE_PREPARE_NO_VTAB 0x04
47624777
#define SQLITE_PREPARE_DONT_LOG 0x10
4778
+#define SQLITE_PREPARE_FROM_DDL 0x20
47634779
47644780
/*
47654781
** CAPI3REF: Compiling An SQL Statement
47664782
** KEYWORDS: {SQL statement compiler}
47674783
** METHOD: sqlite3
@@ -4771,12 +4787,13 @@
47714787
** program using one of these routines. Or, in other words, these routines
47724788
** are constructors for the [prepared statement] object.
47734789
**
47744790
** The preferred routine to use is [sqlite3_prepare_v2()]. The
47754791
** [sqlite3_prepare()] interface is legacy and should be avoided.
4776
-** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
4777
-** for special purposes.
4792
+** [sqlite3_prepare_v3()] has an extra
4793
+** [SQLITE_PREPARE_FROM_DDL|"prepFlags" option] that is some times
4794
+** needed for special purpose or to pass along security restrictions.
47784795
**
47794796
** The use of the UTF-8 interfaces is preferred, as SQLite currently
47804797
** does all parsing using UTF-8. The UTF-16 interfaces are provided
47814798
** as a convenience. The UTF-16 interfaces work by converting the
47824799
** input text into UTF-8, then invoking the corresponding UTF-8 interface.
@@ -5177,12 +5194,12 @@
51775194
** it should be a pointer to well-formed UTF8 text.
51785195
** ^If the third parameter to sqlite3_bind_text16() is not NULL, then
51795196
** it should be a pointer to well-formed UTF16 text.
51805197
** ^If the third parameter to sqlite3_bind_text64() is not NULL, then
51815198
** it should be a pointer to a well-formed unicode string that is
5182
-** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF16
5183
-** otherwise.
5199
+** either UTF8 if the sixth parameter is SQLITE_UTF8 or SQLITE_UTF8_ZT,
5200
+** or UTF16 otherwise.
51845201
**
51855202
** [[byte-order determination rules]] ^The byte-order of
51865203
** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF)
51875204
** found in the first character, which is removed, or in the absence of a BOM
51885205
** the byte order is the native byte order of the host
@@ -5224,14 +5241,19 @@
52245241
** ^ (3) The constant, [SQLITE_TRANSIENT], may be passed to indicate that the
52255242
** object is to be copied prior to the return from sqlite3_bind_*(). ^The
52265243
** object and pointer to it must remain valid until then. ^SQLite will then
52275244
** manage the lifetime of its private copy.
52285245
**
5229
-** ^The sixth argument to sqlite3_bind_text64() must be one of
5230
-** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
5231
-** to specify the encoding of the text in the third parameter. If
5232
-** the sixth argument to sqlite3_bind_text64() is not one of the
5246
+** ^The sixth argument (the E argument)
5247
+** to sqlite3_bind_text64(S,K,Z,N,D,E) must be one of
5248
+** [SQLITE_UTF8], [SQLITE_UTF8_ZT], [SQLITE_UTF16], [SQLITE_UTF16BE],
5249
+** or [SQLITE_UTF16LE] to specify the encoding of the text in the
5250
+** third parameter, Z. The special value [SQLITE_UTF8_ZT] means that the
5251
+** string argument is both UTF-8 encoded and is zero-terminated. In other
5252
+** words, SQLITE_UTF8_ZT means that the Z array is allocated to hold at
5253
+** least N+1 bytes and that the Z&#91;N&#93; byte is zero. If
5254
+** the E argument to sqlite3_bind_text64(S,K,Z,N,D,E) is not one of the
52335255
** allowed values shown above, or if the text encoding is different
52345256
** from the encoding specified by the sixth parameter, then the behavior
52355257
** is undefined.
52365258
**
52375259
** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
@@ -6094,17 +6116,63 @@
60946116
/*
60956117
** CAPI3REF: Text Encodings
60966118
**
60976119
** These constants define integer codes that represent the various
60986120
** text encodings supported by SQLite.
6121
+**
6122
+** <dl>
6123
+** [[SQLITE_UTF8]] <dt>SQLITE_UTF8</dt><dd>Text is encoding as UTF-8</dd>
6124
+**
6125
+** [[SQLITE_UTF16LE]] <dt>SQLITE_UTF16LE</dt><dd>Text is encoding as UTF-16
6126
+** with each code point being expressed "little endian" - the least significant
6127
+** byte first. This is the usual encoding, for example on Windows.</dd>
6128
+**
6129
+** [[SQLITE_UTF16BE]] <dt>SQLITE_UTF16BE</dt><dd>Text is encoding as UTF-16
6130
+** with each code point being expressed "big endian" - the most significant
6131
+** byte first. This encoding is less common, but is still sometimes seen,
6132
+** specially on older systems.
6133
+**
6134
+** [[SQLITE_UTF16]] <dt>SQLITE_UTF16</dt><dd>Text is encoding as UTF-16
6135
+** with each code point being expressed either little endian or as big
6136
+** endian, according to the native endianness of the host computer.
6137
+**
6138
+** [[SQLITE_ANY]] <dt>SQLITE_ANY</dt><dd>This encoding value may only be used
6139
+** to declare the preferred text for [application-defined SQL functions]
6140
+** created using [sqlite3_create_function()] and similar. If the preferred
6141
+** encoding (the 4th parameter to sqlite3_create_function() - the eTextRep
6142
+** parameter) is SQLITE_ANY, that indicates that the function does not have
6143
+** a preference regarding the text encoding of its parameters and can take
6144
+** any text encoding that the SQLite core find convenient to supply. This
6145
+** option is deprecated. Please do not use it in new applications.
6146
+**
6147
+** [[SQLITE_UTF16_ALIGNED]] <dt>SQLITE_UTF16_ALIGNED</dt><dd>This encoding
6148
+** value may be used as the 3rd parameter (the eTextRep parameter) to
6149
+** [sqlite3_create_collation()] and similar. This encoding value means
6150
+** that the application-defined collating sequence created expects its
6151
+** input strings to be in UTF16 in native byte order, and that the start
6152
+** of the strings must be aligned to a 2-byte boundary.
6153
+**
6154
+** [[SQLITE_UTF8_ZT]] <dt>SQLITE_UTF8_ZT</dt><dd>This option can only be
6155
+** used to specify the text encoding to strings input to [sqlite3_result_text64()]
6156
+** and [sqlite3_bind_text64()]. It means that the input string (call it "z")
6157
+** is UTF-8 encoded and that it is zero-terminated. If the length parameter
6158
+** (call it "n") is non-negative, this encoding option means that the caller
6159
+** guarantees that z array contains at least n+1 bytes and that the z&#91;n&#93;
6160
+** byte has a value of zero.
6161
+** This option gives the same output as SQLITE_UTF8, but can be more efficient
6162
+** by avoiding the need to make a copy of the input string, in some cases.
6163
+** However, if z is allocated to hold fewer than n+1 bytes or if the
6164
+** z&#91;n&#93; byte is not zero, undefined behavior may result.
6165
+** </dl>
60996166
*/
61006167
#define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
61016168
#define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
61026169
#define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
61036170
#define SQLITE_UTF16 4 /* Use native byte order */
61046171
#define SQLITE_ANY 5 /* Deprecated */
61056172
#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
6173
+#define SQLITE_UTF8_ZT 16 /* Zero-terminated UTF8 */
61066174
61076175
/*
61086176
** CAPI3REF: Function Flags
61096177
**
61106178
** These constants may be ORed together with the
@@ -6606,14 +6674,18 @@
66066674
** use for client data is to provide a mechanism for wrapper libraries
66076675
** to store additional information about an SQLite database connection.
66086676
**
66096677
** There is no limit (other than available memory) on the number of different
66106678
** client data pointers (with different names) that can be attached to a
6611
-** single database connection. However, the implementation is optimized
6612
-** for the case of having only one or two different client data names.
6613
-** Applications and wrapper libraries are discouraged from using more than
6614
-** one client data name each.
6679
+** single database connection. However, the current implementation stores
6680
+** the content on a linked list. Insert and retrieval performance will
6681
+** be proportional to the number of entries. The design use case, and
6682
+** the use case for which the implementation is optimized, is
6683
+** that an application will store only small number of client data names,
6684
+** typically just one or two. This interface is not intended to be a
6685
+** generalized key/value store for thousands or millions of keys. It
6686
+** will work for that, but performance might be disappointing.
66156687
**
66166688
** There is no way to enumerate the client data pointers
66176689
** associated with a database connection. The N parameter can be thought
66186690
** of as a secret key such that only code that knows the secret key is able
66196691
** to access the associated data.
@@ -6717,14 +6789,18 @@
67176789
** ^The sqlite3_result_text(), sqlite3_result_text16(),
67186790
** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
67196791
** set the return value of the application-defined function to be
67206792
** a text string which is represented as UTF-8, UTF-16 native byte order,
67216793
** UTF-16 little endian, or UTF-16 big endian, respectively.
6722
-** ^The sqlite3_result_text64() interface sets the return value of an
6794
+** ^The sqlite3_result_text64(C,Z,N,D,E) interface sets the return value of an
67236795
** application-defined function to be a text string in an encoding
6724
-** specified by the fifth (and last) parameter, which must be one
6725
-** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
6796
+** specified the E parameter, which must be one
6797
+** of [SQLITE_UTF8], [SQLITE_UTF8_ZT], [SQLITE_UTF16], [SQLITE_UTF16BE],
6798
+** or [SQLITE_UTF16LE]. ^The special value [SQLITE_UTF8_ZT] means that
6799
+** the result text is both UTF-8 and zero-terminated. In other words,
6800
+** SQLITE_UTF8_ZT means that the Z array holds at least N+1 byes and that
6801
+** the Z&#91;N&#93; is zero.
67266802
** ^SQLite takes the text result from the application from
67276803
** the 2nd parameter of the sqlite3_result_text* interfaces.
67286804
** ^If the 3rd parameter to any of the sqlite3_result_text* interfaces
67296805
** other than sqlite3_result_text64() is negative, then SQLite computes
67306806
** the string length itself by searching the 2nd parameter for the first
@@ -6807,11 +6883,11 @@
68076883
SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
68086884
SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
68096885
SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
68106886
SQLITE_API void sqlite3_result_null(sqlite3_context*);
68116887
SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
6812
-SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
6888
+SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char *z, sqlite3_uint64 n,
68136889
void(*)(void*), unsigned char encoding);
68146890
SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
68156891
SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
68166892
SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
68176893
SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
@@ -7746,22 +7822,22 @@
77467822
** ^This interface loads an SQLite extension library from the named file.
77477823
**
77487824
** ^The sqlite3_load_extension() interface attempts to load an
77497825
** [SQLite extension] library contained in the file zFile. If
77507826
** the file cannot be loaded directly, attempts are made to load
7751
-** with various operating-system specific extensions added.
7827
+** with various operating-system specific filename extensions added.
77527828
** So for example, if "samplelib" cannot be loaded, then names like
77537829
** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
77547830
** be tried also.
77557831
**
77567832
** ^The entry point is zProc.
77577833
** ^(zProc may be 0, in which case SQLite will try to come up with an
77587834
** entry point name on its own. It first tries "sqlite3_extension_init".
7759
-** If that does not work, it constructs a name "sqlite3_X_init" where
7760
-** X consists of the lower-case equivalent of all ASCII alphabetic
7761
-** characters in the filename from the last "/" to the first following
7762
-** "." and omitting any initial "lib".)^
7835
+** If that does not work, it tries names of the form "sqlite3_X_init"
7836
+** where X consists of the lower-case equivalent of all ASCII alphabetic
7837
+** characters or all ASCII alphanumeric characters in the filename from
7838
+** the last "/" to the first following "." and omitting any initial "lib".)^
77637839
** ^The sqlite3_load_extension() interface returns
77647840
** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
77657841
** ^If an error occurs and pzErrMsg is not 0, then the
77667842
** [sqlite3_load_extension()] interface shall attempt to
77677843
** fill *pzErrMsg with error message text stored in memory
@@ -11495,23 +11571,45 @@
1149511571
#define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */
1149611572
1149711573
/*
1149811574
** CAPI3REF: Bind array values to the CARRAY table-valued function
1149911575
**
11500
-** The sqlite3_carray_bind(S,I,P,N,F,X) interface binds an array value to
11501
-** one of the first argument of the [carray() table-valued function]. The
11502
-** S parameter is a pointer to the [prepared statement] that uses the carray()
11503
-** functions. I is the parameter index to be bound. P is a pointer to the
11504
-** array to be bound, and N is the number of eements in the array. The
11505
-** F argument is one of constants [SQLITE_CARRAY_INT32], [SQLITE_CARRAY_INT64],
11506
-** [SQLITE_CARRAY_DOUBLE], [SQLITE_CARRAY_TEXT], or [SQLITE_CARRAY_BLOB] to
11507
-** indicate the datatype of the array being bound. The X argument is not a
11508
-** NULL pointer, then SQLite will invoke the function X on the P parameter
11509
-** after it has finished using P, even if the call to
11510
-** sqlite3_carray_bind() fails. The special-case finalizer
11511
-** SQLITE_TRANSIENT has no effect here.
11576
+** The sqlite3_carray_bind_v2(S,I,P,N,F,X,D) interface binds an array value to
11577
+** parameter that is the first argument of the [carray() table-valued function].
11578
+** The S parameter is a pointer to the [prepared statement] that uses the carray()
11579
+** functions. I is the parameter index to be bound. I must be the index of the
11580
+** parameter that is the first argument to the carray() table-valued function.
11581
+** P is a pointer to the array to be bound, and N is the number of elements in
11582
+** the array. The F argument is one of constants [SQLITE_CARRAY_INT32],
11583
+** [SQLITE_CARRAY_INT64], [SQLITE_CARRAY_DOUBLE], [SQLITE_CARRAY_TEXT],
11584
+** or [SQLITE_CARRAY_BLOB] to indicate the datatype of the array P.
11585
+**
11586
+** If the X argument is not a NULL pointer or one of the special
11587
+** values [SQLITE_STATIC] or [SQLITE_TRANSIENT], then SQLite will invoke
11588
+** the function X with argument D when it is finished using the data in P.
11589
+** The call to X(D) is a destructor for the array P. The destructor X(D)
11590
+** is invoked even if the call to sqlite3_carray_bind() fails. If the X
11591
+** parameter is the special-case value [SQLITE_STATIC], then SQLite assumes
11592
+** that the data static and the destructor is never invoked. If the X
11593
+** parameter is the special-case value [SQLITE_TRANSIENT], then
11594
+** sqlite3_carray_bind_v2() makes its own private copy of the data prior
11595
+** to returning and never invokes the destructor X.
11596
+**
11597
+** The sqlite3_carray_bind() function works the same as sqlite_carray_bind_v2()
11598
+** with a D parameter set to P. In other words,
11599
+** sqlite3_carray_bind(S,I,P,N,F,X) is same as
11600
+** sqlite3_carray_bind(S,I,P,N,F,X,P).
1151211601
*/
11602
+SQLITE_API int sqlite3_carray_bind_v2(
11603
+ sqlite3_stmt *pStmt, /* Statement to be bound */
11604
+ int i, /* Parameter index */
11605
+ void *aData, /* Pointer to array data */
11606
+ int nData, /* Number of data elements */
11607
+ int mFlags, /* CARRAY flags */
11608
+ void (*xDel)(void*), /* Destructor for aData */
11609
+ void *pDel /* Optional argument to xDel() */
11610
+);
1151311611
SQLITE_API int sqlite3_carray_bind(
1151411612
sqlite3_stmt *pStmt, /* Statement to be bound */
1151511613
int i, /* Parameter index */
1151611614
void *aData, /* Pointer to array data */
1151711615
int nData, /* Number of data elements */
@@ -14352,10 +14450,31 @@
1435214450
#ifndef SQLITE_MAX_LENGTH
1435314451
# define SQLITE_MAX_LENGTH 1000000000
1435414452
#endif
1435514453
#define SQLITE_MIN_LENGTH 30 /* Minimum value for the length limit */
1435614454
14455
+/*
14456
+** Maximum size of any single memory allocation.
14457
+**
14458
+** This is not a limit on the total amount of memory used. This is
14459
+** a limit on the size parameter to sqlite3_malloc() and sqlite3_realloc().
14460
+**
14461
+** The upper bound is slightly less than 2GiB: 0x7ffffeff == 2,147,483,391
14462
+** This provides a 256-byte safety margin for defense against 32-bit
14463
+** signed integer overflow bugs when computing memory allocation sizes.
14464
+** Paranoid applications might want to reduce the maximum allocation size
14465
+** further for an even larger safety margin. 0x3fffffff or 0x0fffffff
14466
+** or even smaller would be reasonable upper bounds on the size of a memory
14467
+** allocations for most applications.
14468
+*/
14469
+#ifndef SQLITE_MAX_ALLOCATION_SIZE
14470
+# define SQLITE_MAX_ALLOCATION_SIZE 2147483391
14471
+#endif
14472
+#if SQLITE_MAX_ALLOCATION_SIZE>2147483391
14473
+# error Maximum size for SQLITE_MAX_ALLOCATION_SIZE is 2147483391
14474
+#endif
14475
+
1435714476
/*
1435814477
** This is the maximum number of
1435914478
**
1436014479
** * Columns in a table
1436114480
** * Columns in an index
@@ -17529,11 +17648,11 @@
1752917648
1753017649
/*
1753117650
** Additional non-public SQLITE_PREPARE_* flags
1753217651
*/
1753317652
#define SQLITE_PREPARE_SAVESQL 0x80 /* Preserve SQL text */
17534
-#define SQLITE_PREPARE_MASK 0x1f /* Mask of public flags */
17653
+#define SQLITE_PREPARE_MASK 0x3f /* Mask of public flags */
1753517654
1753617655
/*
1753717656
** Prototypes for the VDBE interface. See comments on the implementation
1753817657
** for a description of what each of these routines does.
1753917658
*/
@@ -20202,31 +20321,17 @@
2020220321
};
2020320322
2020420323
/*
2020520324
** An instance of the following structure contains all information
2020620325
** needed to generate code for a single SELECT statement.
20207
-**
20208
-** See the header comment on the computeLimitRegisters() routine for a
20209
-** detailed description of the meaning of the iLimit and iOffset fields.
20210
-**
20211
-** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
20212
-** These addresses must be stored so that we can go back and fill in
20213
-** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
20214
-** the number of columns in P2 can be computed at the same time
20215
-** as the OP_OpenEphm instruction is coded because not
20216
-** enough information about the compound query is known at that point.
20217
-** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
20218
-** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
20219
-** sequences for the ORDER BY clause.
2022020326
*/
2022120327
struct Select {
2022220328
u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
2022320329
LogEst nSelectRow; /* Estimated number of result rows */
2022420330
u32 selFlags; /* Various SF_* values */
2022520331
int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
2022620332
u32 selId; /* Unique identifier number for this SELECT */
20227
- int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
2022820333
ExprList *pEList; /* The fields of the result */
2022920334
SrcList *pSrc; /* The FROM clause */
2023020335
Expr *pWhere; /* The WHERE clause */
2023120336
ExprList *pGroupBy; /* The GROUP BY clause */
2023220337
Expr *pHaving; /* The HAVING clause */
@@ -20254,28 +20359,28 @@
2025420359
#define SF_Distinct 0x0000001 /* Output should be DISTINCT */
2025520360
#define SF_All 0x0000002 /* Includes the ALL keyword */
2025620361
#define SF_Resolved 0x0000004 /* Identifiers have been resolved */
2025720362
#define SF_Aggregate 0x0000008 /* Contains agg functions or a GROUP BY */
2025820363
#define SF_HasAgg 0x0000010 /* Contains aggregate functions */
20259
-#define SF_UsesEphemeral 0x0000020 /* Uses the OpenEphemeral opcode */
20364
+/* 0x0000020 // available for reuse */
2026020365
#define SF_Expanded 0x0000040 /* sqlite3SelectExpand() called on this */
2026120366
#define SF_HasTypeInfo 0x0000080 /* FROM subqueries have Table metadata */
2026220367
#define SF_Compound 0x0000100 /* Part of a compound query */
2026320368
#define SF_Values 0x0000200 /* Synthesized from VALUES clause */
2026420369
#define SF_MultiValue 0x0000400 /* Single VALUES term with multiple rows */
2026520370
#define SF_NestedFrom 0x0000800 /* Part of a parenthesized FROM clause */
2026620371
#define SF_MinMaxAgg 0x0001000 /* Aggregate containing min() or max() */
2026720372
#define SF_Recursive 0x0002000 /* The recursive part of a recursive CTE */
2026820373
#define SF_FixedLimit 0x0004000 /* nSelectRow set by a constant LIMIT */
20269
-#define SF_MaybeConvert 0x0008000 /* Need convertCompoundSelectToSubquery() */
20374
+/* 0x0008000 // available for reuse */
2027020375
#define SF_Converted 0x0010000 /* By convertCompoundSelectToSubquery() */
2027120376
#define SF_IncludeHidden 0x0020000 /* Include hidden columns in output */
2027220377
#define SF_ComplexResult 0x0040000 /* Result contains subquery or function */
2027320378
#define SF_WhereBegin 0x0080000 /* Really a WhereBegin() call. Debug Only */
2027420379
#define SF_WinRewrite 0x0100000 /* Window function rewrite accomplished */
2027520380
#define SF_View 0x0200000 /* SELECT statement is a view */
20276
-#define SF_NoopOrderBy 0x0400000 /* ORDER BY is ignored for this query */
20381
+/* 0x0400000 // available for reuse */
2027720382
#define SF_UFSrcCheck 0x0800000 /* Check pSrc as required by UPDATE...FROM */
2027820383
#define SF_PushDown 0x1000000 /* Modified by WHERE-clause push-down opt */
2027920384
#define SF_MultiPart 0x2000000 /* Has multiple incompatible PARTITIONs */
2028020385
#define SF_CopyCte 0x4000000 /* SELECT statement is a copy of a CTE */
2028120386
#define SF_OrderByReqd 0x8000000 /* The ORDER BY clause may not be omitted */
@@ -20291,15 +20396,10 @@
2029120396
/*
2029220397
** The results of a SELECT can be distributed in several ways, as defined
2029320398
** by one of the following macros. The "SRT" prefix means "SELECT Result
2029420399
** Type".
2029520400
**
20296
-** SRT_Union Store results as a key in a temporary index
20297
-** identified by pDest->iSDParm.
20298
-**
20299
-** SRT_Except Remove results from the temporary index pDest->iSDParm.
20300
-**
2030120401
** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
2030220402
** set is not empty.
2030320403
**
2030420404
** SRT_Discard Throw the results away. This is used by SELECT
2030520405
** statements within triggers whose only purpose is
@@ -20359,34 +20459,32 @@
2035920459
** column returned by the SELECT is used as the integer
2036020460
** key. If (pDest->iSDParm>0), then the table is an index
2036120461
** table. (pDest->iSDParm) is the number of key columns in
2036220462
** each index record in this case.
2036320463
*/
20364
-#define SRT_Union 1 /* Store result as keys in an index */
20365
-#define SRT_Except 2 /* Remove result from a UNION index */
20366
-#define SRT_Exists 3 /* Store 1 if the result is not empty */
20367
-#define SRT_Discard 4 /* Do not save the results anywhere */
20368
-#define SRT_DistFifo 5 /* Like SRT_Fifo, but unique results only */
20369
-#define SRT_DistQueue 6 /* Like SRT_Queue, but unique results only */
20464
+#define SRT_Exists 1 /* Store 1 if the result is not empty */
20465
+#define SRT_Discard 2 /* Do not save the results anywhere */
20466
+#define SRT_DistFifo 3 /* Like SRT_Fifo, but unique results only */
20467
+#define SRT_DistQueue 4 /* Like SRT_Queue, but unique results only */
2037020468
2037120469
/* The DISTINCT clause is ignored for all of the above. Not that
2037220470
** IgnorableDistinct() implies IgnorableOrderby() */
2037320471
#define IgnorableDistinct(X) ((X->eDest)<=SRT_DistQueue)
2037420472
20375
-#define SRT_Queue 7 /* Store result in an queue */
20376
-#define SRT_Fifo 8 /* Store result as data with an automatic rowid */
20473
+#define SRT_Queue 5 /* Store result in an queue */
20474
+#define SRT_Fifo 6 /* Store result as data with an automatic rowid */
2037720475
2037820476
/* The ORDER BY clause is ignored for all of the above */
2037920477
#define IgnorableOrderby(X) ((X->eDest)<=SRT_Fifo)
2038020478
20381
-#define SRT_Output 9 /* Output each row of result */
20382
-#define SRT_Mem 10 /* Store result in a memory cell */
20383
-#define SRT_Set 11 /* Store results as keys in an index */
20384
-#define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
20385
-#define SRT_Coroutine 13 /* Generate a single row of result */
20386
-#define SRT_Table 14 /* Store result as data with an automatic rowid */
20387
-#define SRT_Upfrom 15 /* Store result as data with rowid */
20479
+#define SRT_Output 7 /* Output each row of result */
20480
+#define SRT_Mem 8 /* Store result in a memory cell */
20481
+#define SRT_Set 9 /* Store results as keys in an index */
20482
+#define SRT_EphemTab 10 /* Create transient tab and store like SRT_Table */
20483
+#define SRT_Coroutine 11 /* Generate a single row of result */
20484
+#define SRT_Table 12 /* Store result as data with an automatic rowid */
20485
+#define SRT_Upfrom 13 /* Store result as data with rowid */
2038820486
2038920487
/*
2039020488
** An instance of this object describes where to put of the results of
2039120489
** a SELECT statement.
2039220490
*/
@@ -21018,10 +21116,11 @@
2101821116
u16 mWFlags; /* Use-dependent flags */
2101921117
union { /* Extra data for callback */
2102021118
NameContext *pNC; /* Naming context */
2102121119
int n; /* A counter */
2102221120
int iCur; /* A cursor number */
21121
+ int sz; /* String literal length */
2102321122
SrcList *pSrcList; /* FROM clause */
2102421123
struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
2102521124
struct RefSrcList *pRefSrcList; /* sqlite3ReferencesSrcList() */
2102621125
int *aiCol; /* array of column indexes */
2102721126
struct IdxCover *pIdxCover; /* Check for index coverage */
@@ -21801,10 +21900,11 @@
2180121900
SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
2180221901
#endif
2180321902
SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr*, int*, Parse*);
2180421903
SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
2180521904
SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
21905
+SQLITE_PRIVATE int sqlite3ExprIsLikeOperator(const Expr*);
2180621906
SQLITE_PRIVATE int sqlite3IsRowid(const char*);
2180721907
SQLITE_PRIVATE const char *sqlite3RowidAlias(Table *pTab);
2180821908
SQLITE_PRIVATE void sqlite3GenerateRowDelete(
2180921909
Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
2181021910
SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
@@ -24489,10 +24589,11 @@
2448924589
SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
2449024590
SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
2449124591
SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
2449224592
SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
2449324593
SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, i64, u8, void(*)(void*));
24594
+SQLITE_PRIVATE int sqlite3VdbeMemSetText(Mem*, const char*, i64, void(*)(void*));
2449424595
SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
2449524596
#ifdef SQLITE_OMIT_FLOATING_POINT
2449624597
# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
2449724598
#else
2449824599
SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
@@ -31335,31 +31436,10 @@
3133531436
sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
3133631437
}
3133731438
*pp = p;
3133831439
}
3133931440
31340
-/*
31341
-** Maximum size of any single memory allocation.
31342
-**
31343
-** This is not a limit on the total amount of memory used. This is
31344
-** a limit on the size parameter to sqlite3_malloc() and sqlite3_realloc().
31345
-**
31346
-** The upper bound is slightly less than 2GiB: 0x7ffffeff == 2,147,483,391
31347
-** This provides a 256-byte safety margin for defense against 32-bit
31348
-** signed integer overflow bugs when computing memory allocation sizes.
31349
-** Paranoid applications might want to reduce the maximum allocation size
31350
-** further for an even larger safety margin. 0x3fffffff or 0x0fffffff
31351
-** or even smaller would be reasonable upper bounds on the size of a memory
31352
-** allocations for most applications.
31353
-*/
31354
-#ifndef SQLITE_MAX_ALLOCATION_SIZE
31355
-# define SQLITE_MAX_ALLOCATION_SIZE 2147483391
31356
-#endif
31357
-#if SQLITE_MAX_ALLOCATION_SIZE>2147483391
31358
-# error Maximum size for SQLITE_MAX_ALLOCATION_SIZE is 2147483391
31359
-#endif
31360
-
3136131441
/*
3136231442
** Allocate memory. This routine is like sqlite3_malloc() except that it
3136331443
** assumes the memory subsystem has already been initialized.
3136431444
*/
3136531445
SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
@@ -31579,12 +31659,11 @@
3157931659
}
3158031660
if( nBytes==0 ){
3158131661
sqlite3_free(pOld); /* IMP: R-26507-47431 */
3158231662
return 0;
3158331663
}
31584
- if( nBytes>=0x7fffff00 ){
31585
- /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
31664
+ if( nBytes>SQLITE_MAX_ALLOCATION_SIZE ){
3158631665
return 0;
3158731666
}
3158831667
nOld = sqlite3MallocSize(pOld);
3158931668
/* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
3159031669
** argument to xRealloc is always a value returned by a prior call to
@@ -48881,78 +48960,54 @@
4888148960
{ "WriteFile", (SYSCALL)WriteFile, 0 },
4888248961
4888348962
#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
4888448963
LPOVERLAPPED))aSyscall[61].pCurrent)
4888548964
48886
- { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
48887
-
48888
-#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
48889
- DWORD,DWORD))aSyscall[62].pCurrent)
48890
-
4889148965
/*
4889248966
** For WaitForSingleObject(), MSDN says:
4889348967
**
4889448968
** Minimum supported client: Windows XP [desktop apps | UWP apps]
4889548969
** Minimum supported server: Windows Server 2003 [desktop apps | UWP apps]
4889648970
*/
4889748971
{ "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
4889848972
4889948973
#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
48900
- DWORD))aSyscall[63].pCurrent)
48974
+ DWORD))aSyscall[62].pCurrent)
4890148975
4890248976
#if !SQLITE_OS_WINCE
4890348977
{ "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
4890448978
#else
4890548979
{ "WaitForSingleObjectEx", (SYSCALL)0, 0 },
4890648980
#endif
4890748981
4890848982
#define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
48909
- BOOL))aSyscall[64].pCurrent)
48910
-
48911
- { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
48912
-
48913
-#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
48914
- PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
48915
-
48916
- { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
48917
-
48918
-#define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
48919
- FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
48920
-
48921
- { "CreateFile2", (SYSCALL)CreateFile2, 0 },
48922
-
48923
-#define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
48924
- LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
48925
-
48926
- { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
48927
-
48928
-#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
48983
+ BOOL))aSyscall[63].pCurrent)
4892948984
4893048985
{ "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
4893148986
4893248987
#define osGetNativeSystemInfo ((VOID(WINAPI*)( \
48933
- LPSYSTEM_INFO))aSyscall[71].pCurrent)
48988
+ LPSYSTEM_INFO))aSyscall[64].pCurrent)
4893448989
4893548990
#if defined(SQLITE_WIN32_HAS_ANSI)
4893648991
{ "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
4893748992
#else
4893848993
{ "OutputDebugStringA", (SYSCALL)0, 0 },
4893948994
#endif
4894048995
48941
-#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
48996
+#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[65].pCurrent)
4894248997
4894348998
#if defined(SQLITE_WIN32_HAS_WIDE)
4894448999
{ "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
4894549000
#else
4894649001
{ "OutputDebugStringW", (SYSCALL)0, 0 },
4894749002
#endif
4894849003
48949
-#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
49004
+#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[66].pCurrent)
4895049005
4895149006
{ "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
4895249007
48953
-#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
49008
+#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[67].pCurrent)
4895449009
4895549010
/*
4895649011
** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
4895749012
** is really just a macro that uses a compiler intrinsic (e.g. x64).
4895849013
** So do not try to make this is into a redefinable interface.
@@ -48963,38 +49018,38 @@
4896349018
#define osInterlockedCompareExchange InterlockedCompareExchange
4896449019
#else
4896549020
{ "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
4896649021
4896749022
#define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
48968
- SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
49023
+ SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[68].pCurrent)
4896949024
#endif /* defined(InterlockedCompareExchange) */
4897049025
4897149026
#if !SQLITE_OS_WINCE && SQLITE_WIN32_USE_UUID
4897249027
{ "UuidCreate", (SYSCALL)UuidCreate, 0 },
4897349028
#else
4897449029
{ "UuidCreate", (SYSCALL)0, 0 },
4897549030
#endif
4897649031
48977
-#define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
49032
+#define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[69].pCurrent)
4897849033
4897949034
#if !SQLITE_OS_WINCE && SQLITE_WIN32_USE_UUID
4898049035
{ "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
4898149036
#else
4898249037
{ "UuidCreateSequential", (SYSCALL)0, 0 },
4898349038
#endif
4898449039
4898549040
#define osUuidCreateSequential \
48986
- ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
49041
+ ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[70].pCurrent)
4898749042
4898849043
#if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
4898949044
{ "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
4899049045
#else
4899149046
{ "FlushViewOfFile", (SYSCALL)0, 0 },
4899249047
#endif
4899349048
4899449049
#define osFlushViewOfFile \
48995
- ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
49050
+ ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[71].pCurrent)
4899649051
4899749052
/*
4899849053
** If SQLITE_ENABLE_SETLK_TIMEOUT is defined, we require CreateEvent()
4899949054
** to implement blocking locks with timeouts. MSDN says:
4900049055
**
@@ -49007,11 +49062,11 @@
4900749062
{ "CreateEvent", (SYSCALL)0, 0 },
4900849063
#endif
4900949064
4901049065
#define osCreateEvent ( \
4901149066
(HANDLE(WINAPI*) (LPSECURITY_ATTRIBUTES,BOOL,BOOL,LPCSTR)) \
49012
- aSyscall[80].pCurrent \
49067
+ aSyscall[72].pCurrent \
4901349068
)
4901449069
4901549070
/*
4901649071
** If SQLITE_ENABLE_SETLK_TIMEOUT is defined, we require CancelIo()
4901749072
** for the case where a timeout expires and a lock request must be
@@ -49024,68 +49079,68 @@
4902449079
{ "CancelIo", (SYSCALL)CancelIo, 0 },
4902549080
#else
4902649081
{ "CancelIo", (SYSCALL)0, 0 },
4902749082
#endif
4902849083
49029
-#define osCancelIo ((BOOL(WINAPI*)(HANDLE))aSyscall[81].pCurrent)
49084
+#define osCancelIo ((BOOL(WINAPI*)(HANDLE))aSyscall[73].pCurrent)
4903049085
4903149086
#if defined(SQLITE_WIN32_HAS_WIDE) && defined(_WIN32)
4903249087
{ "GetModuleHandleW", (SYSCALL)GetModuleHandleW, 0 },
4903349088
#else
4903449089
{ "GetModuleHandleW", (SYSCALL)0, 0 },
4903549090
#endif
4903649091
49037
-#define osGetModuleHandleW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[82].pCurrent)
49092
+#define osGetModuleHandleW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[74].pCurrent)
4903849093
4903949094
#ifndef _WIN32
4904049095
{ "getenv", (SYSCALL)getenv, 0 },
4904149096
#else
4904249097
{ "getenv", (SYSCALL)0, 0 },
4904349098
#endif
4904449099
49045
-#define osGetenv ((const char *(*)(const char *))aSyscall[83].pCurrent)
49100
+#define osGetenv ((const char *(*)(const char *))aSyscall[75].pCurrent)
4904649101
4904749102
#ifndef _WIN32
4904849103
{ "getcwd", (SYSCALL)getcwd, 0 },
4904949104
#else
4905049105
{ "getcwd", (SYSCALL)0, 0 },
4905149106
#endif
4905249107
49053
-#define osGetcwd ((char*(*)(char*,size_t))aSyscall[84].pCurrent)
49108
+#define osGetcwd ((char*(*)(char*,size_t))aSyscall[76].pCurrent)
4905449109
4905549110
#ifndef _WIN32
4905649111
{ "readlink", (SYSCALL)readlink, 0 },
4905749112
#else
4905849113
{ "readlink", (SYSCALL)0, 0 },
4905949114
#endif
4906049115
49061
-#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[85].pCurrent)
49116
+#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[77].pCurrent)
4906249117
4906349118
#ifndef _WIN32
4906449119
{ "lstat", (SYSCALL)lstat, 0 },
4906549120
#else
4906649121
{ "lstat", (SYSCALL)0, 0 },
4906749122
#endif
4906849123
49069
-#define osLstat ((int(*)(const char*,struct stat*))aSyscall[86].pCurrent)
49124
+#define osLstat ((int(*)(const char*,struct stat*))aSyscall[78].pCurrent)
4907049125
4907149126
#ifndef _WIN32
4907249127
{ "__errno", (SYSCALL)__errno, 0 },
4907349128
#else
4907449129
{ "__errno", (SYSCALL)0, 0 },
4907549130
#endif
4907649131
49077
-#define osErrno (*((int*(*)(void))aSyscall[87].pCurrent)())
49132
+#define osErrno (*((int*(*)(void))aSyscall[79].pCurrent)())
4907849133
4907949134
#ifndef _WIN32
4908049135
{ "cygwin_conv_path", (SYSCALL)cygwin_conv_path, 0 },
4908149136
#else
4908249137
{ "cygwin_conv_path", (SYSCALL)0, 0 },
4908349138
#endif
4908449139
4908549140
#define osCygwin_conv_path ((size_t(*)(unsigned int, \
49086
- const void *, void *, size_t))aSyscall[88].pCurrent)
49141
+ const void *, void *, size_t))aSyscall[80].pCurrent)
4908749142
4908849143
}; /* End of the overrideable system calls */
4908949144
4909049145
/*
4909149146
** This is the xSetSystemCall() method of sqlite3_vfs for all of the
@@ -53659,10 +53714,11 @@
5365953714
attr = INVALID_FILE_ATTRIBUTES;
5366053715
}else{
5366153716
attr = sAttrData.dwFileAttributes;
5366253717
}
5366353718
}else{
53719
+ if( noRetry ) lastErrno = osGetLastError();
5366453720
winLogIoerr(cnt, __LINE__);
5366553721
if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
5366653722
sqlite3_free(zConverted);
5366753723
return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
5366853724
zFilename);
@@ -54399,11 +54455,16 @@
5439954455
};
5440054456
#endif
5440154457
5440254458
/* Double-check that the aSyscall[] array has been constructed
5440354459
** correctly. See ticket [bb3a86e890c8e96ab] */
54404
- assert( ArraySize(aSyscall)==86 );
54460
+ assert( ArraySize(aSyscall)==81 );
54461
+ assert( strcmp(aSyscall[0].zName,"AreFileApisANSI")==0 );
54462
+ assert( strcmp(aSyscall[20].zName,"GetFileAttributesA")==0 );
54463
+ assert( strcmp(aSyscall[40].zName,"HeapReAlloc")==0 );
54464
+ assert( strcmp(aSyscall[60].zName,"WideCharToMultiByte")==0 );
54465
+ assert( strcmp(aSyscall[80].zName,"cygwin_conv_path")==0 );
5440554466
5440654467
/* get memory map allocation granularity */
5440754468
memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
5440854469
osGetSystemInfo(&winSysInfo);
5440954470
assert( winSysInfo.dwAllocationGranularity>0 );
@@ -77426,11 +77487,11 @@
7742677487
}
7742777488
assert( cursorHoldsMutex(pCur) );
7742877489
7742977490
getCellInfo(pCur);
7743077491
aPayload = pCur->info.pPayload;
77431
- assert( offset+amt <= pCur->info.nPayload );
77492
+ assert( (u64)offset+(u64)amt <= (u64)pCur->info.nPayload );
7743277493
7743377494
assert( aPayload > pPage->aData );
7743477495
if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
7743577496
/* Trying to read or write past the end of the data is an error. The
7743677497
** conditional above is really:
@@ -77983,11 +78044,11 @@
7798378044
SQLITE_PRIVATE int sqlite3BtreeIsEmpty(BtCursor *pCur, int *pRes){
7798478045
int rc;
7798578046
7798678047
assert( cursorOwnsBtShared(pCur) );
7798778048
assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
77988
- if( pCur->eState==CURSOR_VALID ){
78049
+ if( NEVER(pCur->eState==CURSOR_VALID) ){
7798978050
*pRes = 0;
7799078051
return SQLITE_OK;
7799178052
}
7799278053
rc = moveToRoot(pCur);
7799378054
if( rc==SQLITE_EMPTY ){
@@ -85876,10 +85937,88 @@
8587685937
#endif
8587785938
8587885939
8587985940
return SQLITE_OK;
8588085941
}
85942
+
85943
+/* Like sqlite3VdbeMemSetStr() except:
85944
+**
85945
+** enc is always SQLITE_UTF8
85946
+** pMem->db is always non-NULL
85947
+*/
85948
+SQLITE_PRIVATE int sqlite3VdbeMemSetText(
85949
+ Mem *pMem, /* Memory cell to set to string value */
85950
+ const char *z, /* String pointer */
85951
+ i64 n, /* Bytes in string, or negative */
85952
+ void (*xDel)(void*) /* Destructor function */
85953
+){
85954
+ i64 nByte = n; /* New value for pMem->n */
85955
+ u16 flags;
85956
+
85957
+ assert( pMem!=0 );
85958
+ assert( pMem->db!=0 );
85959
+ assert( sqlite3_mutex_held(pMem->db->mutex) );
85960
+ assert( !sqlite3VdbeMemIsRowSet(pMem) );
85961
+
85962
+ /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
85963
+ if( !z ){
85964
+ sqlite3VdbeMemSetNull(pMem);
85965
+ return SQLITE_OK;
85966
+ }
85967
+
85968
+ if( nByte<0 ){
85969
+ nByte = strlen(z);
85970
+ flags = MEM_Str|MEM_Term;
85971
+ }else{
85972
+ flags = MEM_Str;
85973
+ }
85974
+ if( nByte>(i64)pMem->db->aLimit[SQLITE_LIMIT_LENGTH] ){
85975
+ if( xDel && xDel!=SQLITE_TRANSIENT ){
85976
+ if( xDel==SQLITE_DYNAMIC ){
85977
+ sqlite3DbFree(pMem->db, (void*)z);
85978
+ }else{
85979
+ xDel((void*)z);
85980
+ }
85981
+ }
85982
+ sqlite3VdbeMemSetNull(pMem);
85983
+ return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG);
85984
+ }
85985
+
85986
+ /* The following block sets the new values of Mem.z and Mem.xDel. It
85987
+ ** also sets a flag in local variable "flags" to indicate the memory
85988
+ ** management (one of MEM_Dyn or MEM_Static).
85989
+ */
85990
+ if( xDel==SQLITE_TRANSIENT ){
85991
+ i64 nAlloc = nByte + 1;
85992
+ testcase( nAlloc==31 );
85993
+ testcase( nAlloc==32 );
85994
+ if( sqlite3VdbeMemClearAndResize(pMem, (int)MAX(nAlloc,32)) ){
85995
+ return SQLITE_NOMEM_BKPT;
85996
+ }
85997
+ assert( pMem->z!=0 );
85998
+ memcpy(pMem->z, z, nByte);
85999
+ pMem->z[nByte] = 0;
86000
+ }else{
86001
+ sqlite3VdbeMemRelease(pMem);
86002
+ pMem->z = (char *)z;
86003
+ if( xDel==SQLITE_DYNAMIC ){
86004
+ pMem->zMalloc = pMem->z;
86005
+ pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
86006
+ pMem->xDel = 0;
86007
+ }else if( xDel==SQLITE_STATIC ){
86008
+ pMem->xDel = xDel;
86009
+ flags |= MEM_Static;
86010
+ }else{
86011
+ pMem->xDel = xDel;
86012
+ flags |= MEM_Dyn;
86013
+ }
86014
+ }
86015
+ pMem->flags = flags;
86016
+ pMem->n = (int)(nByte & 0x7fffffff);
86017
+ pMem->enc = SQLITE_UTF8;
86018
+ return SQLITE_OK;
86019
+}
8588186020
8588286021
/*
8588386022
** Move data out of a btree key or data field and into a Mem structure.
8588486023
** The data is payload from the entry that pCur is currently pointing
8588586024
** to. offset and amt determine what portion of the data or key to retrieve.
@@ -85900,11 +86039,16 @@
8590086039
u32 amt, /* Number of bytes to return. */
8590186040
Mem *pMem /* OUT: Return data in this Mem structure. */
8590286041
){
8590386042
int rc;
8590486043
pMem->flags = MEM_Null;
85905
- if( sqlite3BtreeMaxRecordSize(pCur)<offset+amt ){
86044
+ testcase( amt==SQLITE_MAX_ALLOCATION_SIZE-1 );
86045
+ testcase( amt==SQLITE_MAX_ALLOCATION_SIZE );
86046
+ if( amt>=SQLITE_MAX_ALLOCATION_SIZE ){
86047
+ return SQLITE_NOMEM_BKPT;
86048
+ }
86049
+ if( (u64)amt + (u64)offset > (u64)sqlite3BtreeMaxRecordSize(pCur) ){
8590686050
return SQLITE_CORRUPT_BKPT;
8590786051
}
8590886052
if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
8590986053
rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
8591086054
if( rc==SQLITE_OK ){
@@ -86568,10 +86712,15 @@
8656886712
** the column value into *ppVal. If *ppVal is initially NULL then a new
8656986713
** sqlite3_value object is allocated.
8657086714
**
8657186715
** If *ppVal is initially NULL then the caller is responsible for
8657286716
** ensuring that the value written into *ppVal is eventually freed.
86717
+**
86718
+** If the buffer does not contain a well-formed record, this routine may
86719
+** read several bytes past the end of the buffer. Callers must therefore
86720
+** ensure that any buffer which may contain a corrupt record is padded
86721
+** with at least 8 bytes of addressable memory.
8657386722
*/
8657486723
SQLITE_PRIVATE int sqlite3Stat4Column(
8657586724
sqlite3 *db, /* Database handle */
8657686725
const void *pRec, /* Pointer to buffer containing record */
8657786726
int nRec, /* Size of buffer pRec in bytes */
@@ -89584,11 +89733,11 @@
8958489733
assert( !zName || xDel!=SQLITE_DYNAMIC );
8958589734
return SQLITE_NOMEM_BKPT;
8958689735
}
8958789736
assert( p->aColName!=0 );
8958889737
pColName = &(p->aColName[idx+var*p->nResAlloc]);
89589
- rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
89738
+ rc = sqlite3VdbeMemSetText(pColName, zName, -1, xDel);
8959089739
assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
8959189740
return rc;
8959289741
}
8959389742
8959489743
/*
@@ -92662,11 +92811,27 @@
9266292811
int n, /* Bytes in string, or negative */
9266392812
u8 enc, /* Encoding of z. 0 for BLOBs */
9266492813
void (*xDel)(void*) /* Destructor function */
9266592814
){
9266692815
Mem *pOut = pCtx->pOut;
92667
- int rc = sqlite3VdbeMemSetStr(pOut, z, n, enc, xDel);
92816
+ int rc;
92817
+ if( enc==SQLITE_UTF8 ){
92818
+ rc = sqlite3VdbeMemSetText(pOut, z, n, xDel);
92819
+ }else if( enc==SQLITE_UTF8_ZT ){
92820
+ /* It is usually considered improper to assert() on an input. However,
92821
+ ** the following assert() is checking for inputs that are documented
92822
+ ** to result in undefined behavior. */
92823
+ assert( z==0
92824
+ || n<0
92825
+ || n>pOut->db->aLimit[SQLITE_LIMIT_LENGTH]
92826
+ || z[n]==0
92827
+ );
92828
+ rc = sqlite3VdbeMemSetText(pOut, z, n, xDel);
92829
+ pOut->flags |= MEM_Term;
92830
+ }else{
92831
+ rc = sqlite3VdbeMemSetStr(pOut, z, n, enc, xDel);
92832
+ }
9266892833
if( rc ){
9266992834
if( rc==SQLITE_TOOBIG ){
9267092835
sqlite3_result_error_toobig(pCtx);
9267192836
}else{
9267292837
/* The only errors possible from sqlite3VdbeMemSetStr are
@@ -92855,11 +93020,11 @@
9285593020
return;
9285693021
}
9285793022
#endif
9285893023
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
9285993024
assert( xDel!=SQLITE_DYNAMIC );
92860
- if( enc!=SQLITE_UTF8 ){
93025
+ if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF8_ZT ){
9286193026
if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
9286293027
n &= ~(u64)1;
9286393028
}
9286493029
if( n>0x7fffffff ){
9286593030
(void)invokeValueDestructor(z, xDel, pCtx);
@@ -93315,11 +93480,11 @@
9331593480
if( rc==SQLITE_OK ){
9331693481
u32 sz; /* Size of current row in bytes */
9331793482
Mem sMem; /* Raw content of current row */
9331893483
memset(&sMem, 0, sizeof(sMem));
9331993484
sz = sqlite3BtreePayloadSize(pRhs->pCsr);
93320
- rc = sqlite3VdbeMemFromBtreeZeroOffset(pRhs->pCsr,(int)sz,&sMem);
93485
+ rc = sqlite3VdbeMemFromBtreeZeroOffset(pRhs->pCsr,sz,&sMem);
9332193486
if( rc==SQLITE_OK ){
9332293487
u8 *zBuf = (u8*)sMem.z;
9332393488
u32 iSerial;
9332493489
sqlite3_value *pOut = pRhs->pOut;
9332593490
int iOff = 1 + getVarint32(&zBuf[1], iSerial);
@@ -93964,17 +94129,29 @@
9396494129
rc = vdbeUnbind(p, (u32)(i-1));
9396594130
if( rc==SQLITE_OK ){
9396694131
assert( p!=0 && p->aVar!=0 && i>0 && i<=p->nVar ); /* tag-20240917-01 */
9396794132
if( zData!=0 ){
9396894133
pVar = &p->aVar[i-1];
93969
- rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
93970
- if( rc==SQLITE_OK ){
93971
- if( encoding==0 ){
93972
- pVar->enc = ENC(p->db);
93973
- }else{
93974
- rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
93975
- }
94134
+ if( encoding==SQLITE_UTF8 ){
94135
+ rc = sqlite3VdbeMemSetText(pVar, zData, nData, xDel);
94136
+ }else if( encoding==SQLITE_UTF8_ZT ){
94137
+ /* It is usually consider improper to assert() on an input.
94138
+ ** However, the following assert() is checking for inputs
94139
+ ** that are documented to result in undefined behavior. */
94140
+ assert( zData==0
94141
+ || nData<0
94142
+ || nData>pVar->db->aLimit[SQLITE_LIMIT_LENGTH]
94143
+ || ((u8*)zData)[nData]==0
94144
+ );
94145
+ rc = sqlite3VdbeMemSetText(pVar, zData, nData, xDel);
94146
+ pVar->flags |= MEM_Term;
94147
+ }else{
94148
+ rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
94149
+ if( encoding==0 ) pVar->enc = ENC(p->db);
94150
+ }
94151
+ if( rc==SQLITE_OK && encoding!=0 ){
94152
+ rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
9397694153
}
9397794154
if( rc ){
9397894155
sqlite3Error(p->db, rc);
9397994156
rc = sqlite3ApiExit(p->db, rc);
9398094157
}
@@ -94082,11 +94259,11 @@
9408294259
sqlite3_uint64 nData,
9408394260
void (*xDel)(void*),
9408494261
unsigned char enc
9408594262
){
9408694263
assert( xDel!=SQLITE_DYNAMIC );
94087
- if( enc!=SQLITE_UTF8 ){
94264
+ if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF8_ZT ){
9408894265
if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
9408994266
nData &= ~(u64)1;
9409094267
}
9409194268
return bindText(pStmt, i, zData, nData, xDel, enc);
9409294269
}
@@ -101780,24 +101957,19 @@
101780101957
rc = sqlite3VdbeSorterWrite(pC, pIn2);
101781101958
if( rc) goto abort_due_to_error;
101782101959
break;
101783101960
}
101784101961
101785
-/* Opcode: IdxDelete P1 P2 P3 * P5
101962
+/* Opcode: IdxDelete P1 P2 P3 * *
101786101963
** Synopsis: key=r[P2@P3]
101787101964
**
101788101965
** The content of P3 registers starting at register P2 form
101789101966
** an unpacked index key. This opcode removes that entry from the
101790101967
** index opened by cursor P1.
101791101968
**
101792
-** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error
101793
-** if no matching index entry is found. This happens when running
101794
-** an UPDATE or DELETE statement and the index entry to be updated
101795
-** or deleted is not found. For some uses of IdxDelete
101796
-** (example: the EXCEPT operator) it does not matter that no matching
101797
-** entry is found. For those cases, P5 is zero. Also, do not raise
101798
-** this (self-correcting and non-critical) error if in writable_schema mode.
101969
+** Raise an SQLITE_CORRUPT_INDEX error if no matching index entry is found
101970
+** and not in writable_schema mode.
101799101971
*/
101800101972
case OP_IdxDelete: {
101801101973
VdbeCursor *pC;
101802101974
BtCursor *pCrsr;
101803101975
int res;
@@ -101819,11 +101991,11 @@
101819101991
rc = sqlite3BtreeIndexMoveto(pCrsr, &r, &res);
101820101992
if( rc ) goto abort_due_to_error;
101821101993
if( res==0 ){
101822101994
rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
101823101995
if( rc ) goto abort_due_to_error;
101824
- }else if( pOp->p5 && !sqlite3WritableSchema(db) ){
101996
+ }else if( !sqlite3WritableSchema(db) ){
101825101997
rc = sqlite3ReportError(SQLITE_CORRUPT_INDEX, __LINE__, "index corruption");
101826101998
goto abort_due_to_error;
101827101999
}
101828102000
assert( pC->deferredMoveto==0 );
101829102001
pC->cacheStatus = CACHE_STALE;
@@ -110988,14 +111160,10 @@
110988111160
}
110989111161
}
110990111162
}
110991111163
#endif
110992111164
110993
- /* The ORDER BY and GROUP BY clauses may not refer to terms in
110994
- ** outer queries
110995
- */
110996
- sNC.pNext = 0;
110997111165
sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
110998111166
110999111167
/* If this is a converted compound query, move the ORDER BY clause from
111000111168
** the sub-query back to the parent query. At this point each term
111001111169
** within the ORDER BY clause has been transformed to an integer value.
@@ -112575,11 +112743,13 @@
112575112743
const Expr *pExpr, /* The function invocation */
112576112744
const FuncDef *pDef /* The function being invoked */
112577112745
){
112578112746
assert( !IN_RENAME_OBJECT );
112579112747
assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );
112580
- if( ExprHasProperty(pExpr, EP_FromDDL) ){
112748
+ if( ExprHasProperty(pExpr, EP_FromDDL)
112749
+ || pParse->prepFlags & SQLITE_PREPARE_FROM_DDL
112750
+ ){
112581112751
if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
112582112752
|| (pParse->db->flags & SQLITE_TrustedSchema)==0
112583112753
){
112584112754
/* Functions prohibited in triggers and views if:
112585112755
** (1) tagged with SQLITE_DIRECTONLY
@@ -113271,13 +113441,11 @@
113271113441
pNew->pNext = pNext;
113272113442
pNew->pPrior = 0;
113273113443
pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
113274113444
pNew->iLimit = 0;
113275113445
pNew->iOffset = 0;
113276
- pNew->selFlags = p->selFlags & ~(u32)SF_UsesEphemeral;
113277
- pNew->addrOpenEphm[0] = -1;
113278
- pNew->addrOpenEphm[1] = -1;
113446
+ pNew->selFlags = p->selFlags;
113279113447
pNew->nSelectRow = p->nSelectRow;
113280113448
pNew->pWith = sqlite3WithDup(db, p->pWith);
113281113449
#ifndef SQLITE_OMIT_WINDOWFUNC
113282113450
pNew->pWin = 0;
113283113451
pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
@@ -115495,12 +115663,13 @@
115495115663
if( destIfFalse==destIfNull ){
115496115664
/* Combine Step 3 and Step 5 into a single opcode */
115497115665
if( ExprHasProperty(pExpr, EP_Subrtn) ){
115498115666
const VdbeOp *pOp = sqlite3VdbeGetOp(v, pExpr->y.sub.iAddr);
115499115667
assert( pOp->opcode==OP_Once || pParse->nErr );
115500
- if( pOp->opcode==OP_Once && pOp->p3>0 ){ /* tag-202407032019 */
115501
- assert( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) );
115668
+ if( pOp->p3>0 ){ /* tag-202407032019 */
115669
+ assert( OptimizationEnabled(pParse->db, SQLITE_BloomFilter)
115670
+ || pParse->nErr );
115502115671
sqlite3VdbeAddOp4Int(v, OP_Filter, pOp->p3, destIfFalse,
115503115672
rLhs, nVector); VdbeCoverage(v);
115504115673
}
115505115674
}
115506115675
sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
@@ -118687,11 +118856,14 @@
118687118856
if( sqlite3ExprCompare(0, pExpr, pIEpr->pExpr, iDataCur)==0 ) break;
118688118857
}
118689118858
if( pIEpr==0 ) break;
118690118859
if( NEVER(!ExprUseYTab(pExpr)) ) break;
118691118860
for(i=0; i<pSrcList->nSrc; i++){
118692
- if( pSrcList->a[0].iCursor==pIEpr->iDataCur ) break;
118861
+ if( pSrcList->a[i].iCursor==pIEpr->iDataCur ){
118862
+ testcase( i>0 );
118863
+ break;
118864
+ }
118693118865
}
118694118866
if( i>=pSrcList->nSrc ) break;
118695118867
if( NEVER(pExpr->pAggInfo!=0) ) break; /* Resolved by outer context */
118696118868
if( pParse->nErr ){ return WRC_Abort; }
118697118869
@@ -131401,11 +131573,11 @@
131401131573
** * Do not allow DELETE, INSERT, or UPDATE of SQLITE_VTAB_DIRECTONLY
131402131574
** virtual tables
131403131575
** * Only allow DELETE, INSERT, or UPDATE of non-SQLITE_VTAB_INNOCUOUS
131404131576
** virtual tables if PRAGMA trusted_schema=ON.
131405131577
*/
131406
- if( pParse->pToplevel!=0
131578
+ if( (pParse->pToplevel!=0 || (pParse->prepFlags & SQLITE_PREPARE_FROM_DDL))
131407131579
&& pTab->u.vtab.p->eVtabRisk >
131408131580
((pParse->db->flags & SQLITE_TrustedSchema)!=0)
131409131581
){
131410131582
sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"",
131411131583
pTab->zName);
@@ -132239,11 +132411,10 @@
132239132411
VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
132240132412
r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
132241132413
&iPartIdxLabel, pPrior, r1);
132242132414
sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
132243132415
pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
132244
- sqlite3VdbeChangeP5(v, 1); /* Cause IdxDelete to error if no entry found */
132245132416
sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
132246132417
pPrior = pIdx;
132247132418
}
132248132419
}
132249132420
@@ -133586,11 +133757,11 @@
133586133757
}else{
133587133758
goto unistr_error;
133588133759
}
133589133760
}
133590133761
zOut[j] = 0;
133591
- sqlite3_result_text64(context, zOut, j, sqlite3_free, SQLITE_UTF8);
133762
+ sqlite3_result_text64(context, zOut, j, sqlite3_free, SQLITE_UTF8_ZT);
133592133763
return;
133593133764
133594133765
unistr_error:
133595133766
sqlite3_free(zOut);
133596133767
sqlite3_result_error(context, "invalid Unicode escape", -1);
@@ -133679,11 +133850,11 @@
133679133850
*zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
133680133851
*zOut++ = 0x80 + (u8)(c & 0x3F);
133681133852
} \
133682133853
}
133683133854
*zOut = 0;
133684
- sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
133855
+ sqlite3_result_text64(context, (char*)z, zOut-z,sqlite3_free,SQLITE_UTF8_ZT);
133685133856
}
133686133857
133687133858
/*
133688133859
** The hex() function. Interpret the argument as a blob. Return
133689133860
** a hexadecimal rendering as text.
@@ -133708,11 +133879,11 @@
133708133879
*(z++) = hexdigits[(c>>4)&0xf];
133709133880
*(z++) = hexdigits[c&0xf];
133710133881
}
133711133882
*z = 0;
133712133883
sqlite3_result_text64(context, zHex, (u64)(z-zHex),
133713
- sqlite3_free, SQLITE_UTF8);
133884
+ sqlite3_free, SQLITE_UTF8_ZT);
133714133885
}
133715133886
}
133716133887
133717133888
/*
133718133889
** Buffer zStr contains nStr bytes of utf-8 encoded text. Return 1 if zStr
@@ -134046,11 +134217,11 @@
134046134217
}
134047134218
}
134048134219
}
134049134220
z[j] = 0;
134050134221
assert( j<=n );
134051
- sqlite3_result_text64(context, z, j, sqlite3_free, SQLITE_UTF8);
134222
+ sqlite3_result_text64(context, z, j, sqlite3_free, SQLITE_UTF8_ZT);
134052134223
}
134053134224
134054134225
/*
134055134226
** The CONCAT(...) function. Generate a string result that is the
134056134227
** concatentation of all non-null arguments.
@@ -141234,10 +141405,12 @@
141234141405
int (*set_errmsg)(sqlite3*,int,const char*);
141235141406
int (*db_status64)(sqlite3*,int,sqlite3_int64*,sqlite3_int64*,int);
141236141407
/* Version 3.52.0 and later */
141237141408
void (*str_truncate)(sqlite3_str*,int);
141238141409
void (*str_free)(sqlite3_str*);
141410
+ int (*carray_bind)(sqlite3_stmt*,int,void*,int,int,void(*)(void*));
141411
+ int (*carray_bind_v2)(sqlite3_stmt*,int,void*,int,int,void(*)(void*),void*);
141239141412
};
141240141413
141241141414
/*
141242141415
** This is the function signature used for all extension entry points. It
141243141416
** is also defined in the file "loadext.c".
@@ -141575,10 +141748,12 @@
141575141748
#define sqlite3_set_errmsg sqlite3_api->set_errmsg
141576141749
#define sqlite3_db_status64 sqlite3_api->db_status64
141577141750
/* Version 3.52.0 and later */
141578141751
#define sqlite3_str_truncate sqlite3_api->str_truncate
141579141752
#define sqlite3_str_free sqlite3_api->str_free
141753
+#define sqlite3_carray_bind sqlite3_api->carray_bind
141754
+#define sqlite3_carray_bind_v2 sqlite3_api->carray_bind_v2
141580141755
#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
141581141756
141582141757
#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
141583141758
/* This case when the file really is being compiled as a loadable
141584141759
** extension */
@@ -142104,11 +142279,18 @@
142104142279
/* Version 3.51.0 and later */
142105142280
sqlite3_set_errmsg,
142106142281
sqlite3_db_status64,
142107142282
/* Version 3.52.0 and later */
142108142283
sqlite3_str_truncate,
142109
- sqlite3_str_free
142284
+ sqlite3_str_free,
142285
+#ifdef SQLITE_ENABLE_CARRAY
142286
+ sqlite3_carray_bind,
142287
+ sqlite3_carray_bind_v2
142288
+#else
142289
+ 0,
142290
+ 0
142291
+#endif
142110142292
};
142111142293
142112142294
/* True if x is the directory separator character
142113142295
*/
142114142296
#if SQLITE_OS_WIN
@@ -142206,37 +142388,46 @@
142206142388
142207142389
/* If no entry point was specified and the default legacy
142208142390
** entry point name "sqlite3_extension_init" was not found, then
142209142391
** construct an entry point name "sqlite3_X_init" where the X is
142210142392
** replaced by the lowercase value of every ASCII alphabetic
142211
- ** character in the filename after the last "/" upto the first ".",
142212
- ** and eliding the first three characters if they are "lib".
142393
+ ** character in the filename after the last "/" up to the first ".",
142394
+ ** and skipping the first three characters if they are "lib".
142213142395
** Examples:
142214142396
**
142215142397
** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
142216142398
** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
142399
+ **
142400
+ ** If that still finds no entry point, repeat a second time but this
142401
+ ** time include both alphabetic and numeric characters up to the first
142402
+ ** ".". Example:
142403
+ **
142404
+ ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example5_init
142217142405
*/
142218142406
if( xInit==0 && zProc==0 ){
142219142407
int iFile, iEntry, c;
142220142408
int ncFile = sqlite3Strlen30(zFile);
142409
+ int cnt = 0;
142221142410
zAltEntry = sqlite3_malloc64(ncFile+30);
142222142411
if( zAltEntry==0 ){
142223142412
sqlite3OsDlClose(pVfs, handle);
142224142413
return SQLITE_NOMEM_BKPT;
142225142414
}
142226
- memcpy(zAltEntry, "sqlite3_", 8);
142227
- for(iFile=ncFile-1; iFile>=0 && !DirSep(zFile[iFile]); iFile--){}
142228
- iFile++;
142229
- if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
142230
- for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
142231
- if( sqlite3Isalpha(c) ){
142232
- zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
142233
- }
142234
- }
142235
- memcpy(zAltEntry+iEntry, "_init", 6);
142236
- zEntry = zAltEntry;
142237
- xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
142415
+ do{
142416
+ memcpy(zAltEntry, "sqlite3_", 8);
142417
+ for(iFile=ncFile-1; iFile>=0 && !DirSep(zFile[iFile]); iFile--){}
142418
+ iFile++;
142419
+ if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
142420
+ for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
142421
+ if( sqlite3Isalpha(c) || (cnt && sqlite3Isdigit(c)) ){
142422
+ zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
142423
+ }
142424
+ }
142425
+ memcpy(zAltEntry+iEntry, "_init", 6);
142426
+ zEntry = zAltEntry;
142427
+ xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
142428
+ }while( xInit==0 && (++cnt)<2 );
142238142429
}
142239142430
if( xInit==0 ){
142240142431
if( pzErrMsg ){
142241142432
nMsg += strlen(zEntry) + 300;
142242142433
*pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
@@ -147518,12 +147709,10 @@
147518147709
pNew->op = TK_SELECT;
147519147710
pNew->selFlags = selFlags;
147520147711
pNew->iLimit = 0;
147521147712
pNew->iOffset = 0;
147522147713
pNew->selId = ++pParse->nSelect;
147523
- pNew->addrOpenEphm[0] = -1;
147524
- pNew->addrOpenEphm[1] = -1;
147525147714
pNew->nSelectRow = 0;
147526147715
if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, SZ_SRCLIST_1);
147527147716
pNew->pSrc = pSrc;
147528147717
pNew->pWhere = pWhere;
147529147718
pNew->pGroupBy = pGroupBy;
@@ -148667,33 +148856,10 @@
148667148856
codeOffset(v, p->iOffset, iContinue);
148668148857
}
148669148858
}
148670148859
148671148860
switch( eDest ){
148672
- /* In this mode, write each query result to the key of the temporary
148673
- ** table iParm.
148674
- */
148675
-#ifndef SQLITE_OMIT_COMPOUND_SELECT
148676
- case SRT_Union: {
148677
- int r1;
148678
- r1 = sqlite3GetTempReg(pParse);
148679
- sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
148680
- sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
148681
- sqlite3ReleaseTempReg(pParse, r1);
148682
- break;
148683
- }
148684
-
148685
- /* Construct a record from the query result, but instead of
148686
- ** saving that record, use it as a key to delete elements from
148687
- ** the temporary table iParm.
148688
- */
148689
- case SRT_Except: {
148690
- sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
148691
- break;
148692
- }
148693
-#endif /* SQLITE_OMIT_COMPOUND_SELECT */
148694
-
148695148861
/* Store the result as data using a unique key.
148696148862
*/
148697148863
case SRT_Fifo:
148698148864
case SRT_DistFifo:
148699148865
case SRT_Table:
@@ -149976,13 +150142,13 @@
149976150142
**
149977150143
** Space to hold the KeyInfo structure is obtained from malloc. The calling
149978150144
** function is responsible for ensuring that this structure is eventually
149979150145
** freed.
149980150146
*/
149981
-static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
150147
+static KeyInfo *multiSelectByMergeKeyInfo(Parse *pParse, Select *p, int nExtra){
149982150148
ExprList *pOrderBy = p->pOrderBy;
149983
- int nOrderBy = ALWAYS(pOrderBy!=0) ? pOrderBy->nExpr : 0;
150149
+ int nOrderBy = (pOrderBy!=0) ? pOrderBy->nExpr : 0;
149984150150
sqlite3 *db = pParse->db;
149985150151
KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
149986150152
if( pRet ){
149987150153
int i;
149988150154
for(i=0; i<nOrderBy; i++){
@@ -150111,21 +150277,41 @@
150111150277
150112150278
/* Allocate cursors for Current, Queue, and Distinct. */
150113150279
regCurrent = ++pParse->nMem;
150114150280
sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
150115150281
if( pOrderBy ){
150116
- KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
150282
+ KeyInfo *pKeyInfo = multiSelectByMergeKeyInfo(pParse, p, 1);
150117150283
sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
150118150284
(char*)pKeyInfo, P4_KEYINFO);
150119150285
destQueue.pOrderBy = pOrderBy;
150120150286
}else{
150121150287
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
150122150288
}
150123150289
VdbeComment((v, "Queue table"));
150124150290
if( iDistinct ){
150125
- p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
150126
- p->selFlags |= SF_UsesEphemeral;
150291
+ /* Generate an ephemeral table used to enforce distinctness on the
150292
+ ** output of the recursive part of the CTE.
150293
+ */
150294
+ KeyInfo *pKeyInfo; /* Collating sequence for the result set */
150295
+ CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
150296
+
150297
+ assert( p->pNext==0 );
150298
+ assert( p->pEList!=0 );
150299
+ nCol = p->pEList->nExpr;
150300
+ pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nCol, 1);
150301
+ if( pKeyInfo ){
150302
+ for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
150303
+ *apColl = multiSelectCollSeq(pParse, p, i);
150304
+ if( 0==*apColl ){
150305
+ *apColl = pParse->db->pDfltColl;
150306
+ }
150307
+ }
150308
+ sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iDistinct, nCol, 0,
150309
+ (void*)pKeyInfo, P4_KEYINFO);
150310
+ }else{
150311
+ assert( pParse->nErr>0 );
150312
+ }
150127150313
}
150128150314
150129150315
/* Detach the ORDER BY clause from the compound SELECT */
150130150316
p->pOrderBy = 0;
150131150317
@@ -150196,11 +150382,11 @@
150196150382
return;
150197150383
}
150198150384
#endif /* SQLITE_OMIT_CTE */
150199150385
150200150386
/* Forward references */
150201
-static int multiSelectOrderBy(
150387
+static int multiSelectByMerge(
150202150388
Parse *pParse, /* Parsing context */
150203150389
Select *p, /* The right-most of SELECTs to be coded */
150204150390
SelectDest *pDest /* What to do with query results */
150205150391
);
150206150392
@@ -150345,317 +150531,80 @@
150345150531
#ifndef SQLITE_OMIT_CTE
150346150532
if( (p->selFlags & SF_Recursive)!=0 && hasAnchor(p) ){
150347150533
generateWithRecursiveQuery(pParse, p, &dest);
150348150534
}else
150349150535
#endif
150350
-
150351
- /* Compound SELECTs that have an ORDER BY clause are handled separately.
150352
- */
150353150536
if( p->pOrderBy ){
150354
- return multiSelectOrderBy(pParse, p, pDest);
150537
+ /* If the compound has an ORDER BY clause, then always use the merge
150538
+ ** algorithm. */
150539
+ return multiSelectByMerge(pParse, p, pDest);
150540
+ }else if( p->op!=TK_ALL ){
150541
+ /* If the compound is EXCEPT, INTERSECT, or UNION (anything other than
150542
+ ** UNION ALL) then also always use the merge algorithm. However, the
150543
+ ** multiSelectByMerge() routine requires that the compound have an
150544
+ ** ORDER BY clause, and it doesn't right now. So invent one first. */
150545
+ Expr *pOne = sqlite3ExprInt32(db, 1);
150546
+ p->pOrderBy = sqlite3ExprListAppend(pParse, 0, pOne);
150547
+ if( pParse->nErr ) goto multi_select_end;
150548
+ assert( p->pOrderBy!=0 );
150549
+ p->pOrderBy->a[0].u.x.iOrderByCol = 1;
150550
+ return multiSelectByMerge(pParse, p, pDest);
150355150551
}else{
150552
+ /* For a UNION ALL compound without ORDER BY, simply run the left
150553
+ ** query, then run the right query */
150554
+ int addr = 0;
150555
+ int nLimit = 0; /* Initialize to suppress harmless compiler warning */
150356150556
150357150557
#ifndef SQLITE_OMIT_EXPLAIN
150358150558
if( pPrior->pPrior==0 ){
150359150559
ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
150360150560
ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
150361150561
}
150362150562
#endif
150363
-
150364
- /* Generate code for the left and right SELECT statements.
150365
- */
150366
- switch( p->op ){
150367
- case TK_ALL: {
150368
- int addr = 0;
150369
- int nLimit = 0; /* Initialize to suppress harmless compiler warning */
150370
- assert( !pPrior->pLimit );
150371
- pPrior->iLimit = p->iLimit;
150372
- pPrior->iOffset = p->iOffset;
150373
- pPrior->pLimit = p->pLimit;
150374
- TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL left...\n"));
150375
- rc = sqlite3Select(pParse, pPrior, &dest);
150376
- pPrior->pLimit = 0;
150377
- if( rc ){
150378
- goto multi_select_end;
150379
- }
150380
- p->pPrior = 0;
150381
- p->iLimit = pPrior->iLimit;
150382
- p->iOffset = pPrior->iOffset;
150383
- if( p->iLimit ){
150384
- addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
150385
- VdbeComment((v, "Jump ahead if LIMIT reached"));
150386
- if( p->iOffset ){
150387
- sqlite3VdbeAddOp3(v, OP_OffsetLimit,
150388
- p->iLimit, p->iOffset+1, p->iOffset);
150389
- }
150390
- }
150391
- ExplainQueryPlan((pParse, 1, "UNION ALL"));
150392
- TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL right...\n"));
150393
- rc = sqlite3Select(pParse, p, &dest);
150394
- testcase( rc!=SQLITE_OK );
150395
- pDelete = p->pPrior;
150396
- p->pPrior = pPrior;
150397
- p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
150398
- if( p->pLimit
150399
- && sqlite3ExprIsInteger(p->pLimit->pLeft, &nLimit, pParse)
150400
- && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
150401
- ){
150402
- p->nSelectRow = sqlite3LogEst((u64)nLimit);
150403
- }
150404
- if( addr ){
150405
- sqlite3VdbeJumpHere(v, addr);
150406
- }
150407
- break;
150408
- }
150409
- case TK_EXCEPT:
150410
- case TK_UNION: {
150411
- int unionTab; /* Cursor number of the temp table holding result */
150412
- u8 op = 0; /* One of the SRT_ operations to apply to self */
150413
- int priorOp; /* The SRT_ operation to apply to prior selects */
150414
- Expr *pLimit; /* Saved values of p->nLimit */
150415
- int addr;
150416
- int emptyBypass = 0; /* IfEmpty opcode to bypass RHS */
150417
- SelectDest uniondest;
150418
-
150419
-
150420
- testcase( p->op==TK_EXCEPT );
150421
- testcase( p->op==TK_UNION );
150422
- priorOp = SRT_Union;
150423
- if( dest.eDest==priorOp ){
150424
- /* We can reuse a temporary table generated by a SELECT to our
150425
- ** right.
150426
- */
150427
- assert( p->pLimit==0 ); /* Not allowed on leftward elements */
150428
- unionTab = dest.iSDParm;
150429
- }else{
150430
- /* We will need to create our own temporary table to hold the
150431
- ** intermediate results.
150432
- */
150433
- unionTab = pParse->nTab++;
150434
- assert( p->pOrderBy==0 );
150435
- addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
150436
- assert( p->addrOpenEphm[0] == -1 );
150437
- p->addrOpenEphm[0] = addr;
150438
- findRightmost(p)->selFlags |= SF_UsesEphemeral;
150439
- assert( p->pEList );
150440
- }
150441
-
150442
-
150443
- /* Code the SELECT statements to our left
150444
- */
150445
- assert( !pPrior->pOrderBy );
150446
- sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
150447
- TREETRACE(0x200, pParse, p, ("multiSelect EXCEPT/UNION left...\n"));
150448
- rc = sqlite3Select(pParse, pPrior, &uniondest);
150449
- if( rc ){
150450
- goto multi_select_end;
150451
- }
150452
-
150453
- /* Code the current SELECT statement
150454
- */
150455
- if( p->op==TK_EXCEPT ){
150456
- op = SRT_Except;
150457
- emptyBypass = sqlite3VdbeAddOp1(v, OP_IfEmpty, unionTab);
150458
- VdbeCoverage(v);
150459
- }else{
150460
- assert( p->op==TK_UNION );
150461
- op = SRT_Union;
150462
- }
150463
- p->pPrior = 0;
150464
- pLimit = p->pLimit;
150465
- p->pLimit = 0;
150466
- uniondest.eDest = op;
150467
- ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
150468
- sqlite3SelectOpName(p->op)));
150469
- TREETRACE(0x200, pParse, p, ("multiSelect EXCEPT/UNION right...\n"));
150470
- rc = sqlite3Select(pParse, p, &uniondest);
150471
- testcase( rc!=SQLITE_OK );
150472
- assert( p->pOrderBy==0 );
150473
- pDelete = p->pPrior;
150474
- p->pPrior = pPrior;
150475
- p->pOrderBy = 0;
150476
- if( p->op==TK_UNION ){
150477
- p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
150478
- }
150479
- if( emptyBypass ) sqlite3VdbeJumpHere(v, emptyBypass);
150480
- sqlite3ExprDelete(db, p->pLimit);
150481
- p->pLimit = pLimit;
150482
- p->iLimit = 0;
150483
- p->iOffset = 0;
150484
-
150485
- /* Convert the data in the temporary table into whatever form
150486
- ** it is that we currently need.
150487
- */
150488
- assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
150489
- assert( p->pEList || db->mallocFailed );
150490
- if( dest.eDest!=priorOp && db->mallocFailed==0 ){
150491
- int iCont, iBreak, iStart;
150492
- iBreak = sqlite3VdbeMakeLabel(pParse);
150493
- iCont = sqlite3VdbeMakeLabel(pParse);
150494
- computeLimitRegisters(pParse, p, iBreak);
150495
- sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
150496
- iStart = sqlite3VdbeCurrentAddr(v);
150497
- selectInnerLoop(pParse, p, unionTab,
150498
- 0, 0, &dest, iCont, iBreak);
150499
- sqlite3VdbeResolveLabel(v, iCont);
150500
- sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
150501
- sqlite3VdbeResolveLabel(v, iBreak);
150502
- sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
150503
- }
150504
- break;
150505
- }
150506
- default: assert( p->op==TK_INTERSECT ); {
150507
- int tab1, tab2;
150508
- int iCont, iBreak, iStart;
150509
- Expr *pLimit;
150510
- int addr, iLimit, iOffset;
150511
- SelectDest intersectdest;
150512
- int r1;
150513
- int emptyBypass;
150514
-
150515
- /* INTERSECT is different from the others since it requires
150516
- ** two temporary tables. Hence it has its own case. Begin
150517
- ** by allocating the tables we will need.
150518
- */
150519
- tab1 = pParse->nTab++;
150520
- tab2 = pParse->nTab++;
150521
- assert( p->pOrderBy==0 );
150522
-
150523
- addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
150524
- assert( p->addrOpenEphm[0] == -1 );
150525
- p->addrOpenEphm[0] = addr;
150526
- findRightmost(p)->selFlags |= SF_UsesEphemeral;
150527
- assert( p->pEList );
150528
-
150529
- /* Code the SELECTs to our left into temporary table "tab1".
150530
- */
150531
- sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
150532
- TREETRACE(0x400, pParse, p, ("multiSelect INTERSECT left...\n"));
150533
- rc = sqlite3Select(pParse, pPrior, &intersectdest);
150534
- if( rc ){
150535
- goto multi_select_end;
150536
- }
150537
-
150538
- /* Initialize LIMIT counters before checking to see if the LHS
150539
- ** is empty, in case the jump is taken */
150540
- iBreak = sqlite3VdbeMakeLabel(pParse);
150541
- computeLimitRegisters(pParse, p, iBreak);
150542
- emptyBypass = sqlite3VdbeAddOp1(v, OP_IfEmpty, tab1); VdbeCoverage(v);
150543
-
150544
- /* Code the current SELECT into temporary table "tab2"
150545
- */
150546
- addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
150547
- assert( p->addrOpenEphm[1] == -1 );
150548
- p->addrOpenEphm[1] = addr;
150549
-
150550
- /* Disable prior SELECTs and the LIMIT counters during the computation
150551
- ** of the RHS select */
150552
- pLimit = p->pLimit;
150553
- iLimit = p->iLimit;
150554
- iOffset = p->iOffset;
150555
- p->pPrior = 0;
150556
- p->pLimit = 0;
150557
- p->iLimit = 0;
150558
- p->iOffset = 0;
150559
-
150560
- intersectdest.iSDParm = tab2;
150561
- ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
150562
- sqlite3SelectOpName(p->op)));
150563
- TREETRACE(0x400, pParse, p, ("multiSelect INTERSECT right...\n"));
150564
- rc = sqlite3Select(pParse, p, &intersectdest);
150565
- testcase( rc!=SQLITE_OK );
150566
- pDelete = p->pPrior;
150567
- p->pPrior = pPrior;
150568
- if( p->nSelectRow>pPrior->nSelectRow ){
150569
- p->nSelectRow = pPrior->nSelectRow;
150570
- }
150571
- sqlite3ExprDelete(db, p->pLimit);
150572
-
150573
- /* Reinstate the LIMIT counters prior to running the final intersect */
150574
- p->pLimit = pLimit;
150575
- p->iLimit = iLimit;
150576
- p->iOffset = iOffset;
150577
-
150578
- /* Generate code to take the intersection of the two temporary
150579
- ** tables.
150580
- */
150581
- if( rc ) break;
150582
- assert( p->pEList );
150583
- sqlite3VdbeAddOp1(v, OP_Rewind, tab1);
150584
- r1 = sqlite3GetTempReg(pParse);
150585
- iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
150586
- iCont = sqlite3VdbeMakeLabel(pParse);
150587
- sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
150588
- VdbeCoverage(v);
150589
- sqlite3ReleaseTempReg(pParse, r1);
150590
- selectInnerLoop(pParse, p, tab1,
150591
- 0, 0, &dest, iCont, iBreak);
150592
- sqlite3VdbeResolveLabel(v, iCont);
150593
- sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
150594
- sqlite3VdbeResolveLabel(v, iBreak);
150595
- sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
150596
- sqlite3VdbeJumpHere(v, emptyBypass);
150597
- sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
150598
- break;
150599
- }
150600
- }
150601
-
150602
- #ifndef SQLITE_OMIT_EXPLAIN
150563
+ assert( !pPrior->pLimit );
150564
+ pPrior->iLimit = p->iLimit;
150565
+ pPrior->iOffset = p->iOffset;
150566
+ pPrior->pLimit = sqlite3ExprDup(db, p->pLimit, 0);
150567
+ TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL left...\n"));
150568
+ rc = sqlite3Select(pParse, pPrior, &dest);
150569
+ sqlite3ExprDelete(db, pPrior->pLimit);
150570
+ pPrior->pLimit = 0;
150571
+ if( rc ){
150572
+ goto multi_select_end;
150573
+ }
150574
+ p->pPrior = 0;
150575
+ p->iLimit = pPrior->iLimit;
150576
+ p->iOffset = pPrior->iOffset;
150577
+ if( p->iLimit ){
150578
+ addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
150579
+ VdbeComment((v, "Jump ahead if LIMIT reached"));
150580
+ if( p->iOffset ){
150581
+ sqlite3VdbeAddOp3(v, OP_OffsetLimit,
150582
+ p->iLimit, p->iOffset+1, p->iOffset);
150583
+ }
150584
+ }
150585
+ ExplainQueryPlan((pParse, 1, "UNION ALL"));
150586
+ TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL right...\n"));
150587
+ rc = sqlite3Select(pParse, p, &dest);
150588
+ testcase( rc!=SQLITE_OK );
150589
+ pDelete = p->pPrior;
150590
+ p->pPrior = pPrior;
150591
+ p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
150592
+ if( p->pLimit
150593
+ && sqlite3ExprIsInteger(p->pLimit->pLeft, &nLimit, pParse)
150594
+ && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
150595
+ ){
150596
+ p->nSelectRow = sqlite3LogEst((u64)nLimit);
150597
+ }
150598
+ if( addr ){
150599
+ sqlite3VdbeJumpHere(v, addr);
150600
+ }
150601
+#ifndef SQLITE_OMIT_EXPLAIN
150603150602
if( p->pNext==0 ){
150604150603
ExplainQueryPlanPop(pParse);
150605150604
}
150606
- #endif
150607
- }
150608
- if( pParse->nErr ) goto multi_select_end;
150609
-
150610
- /* Compute collating sequences used by
150611
- ** temporary tables needed to implement the compound select.
150612
- ** Attach the KeyInfo structure to all temporary tables.
150613
- **
150614
- ** This section is run by the right-most SELECT statement only.
150615
- ** SELECT statements to the left always skip this part. The right-most
150616
- ** SELECT might also skip this part if it has no ORDER BY clause and
150617
- ** no temp tables are required.
150618
- */
150619
- if( p->selFlags & SF_UsesEphemeral ){
150620
- int i; /* Loop counter */
150621
- KeyInfo *pKeyInfo; /* Collating sequence for the result set */
150622
- Select *pLoop; /* For looping through SELECT statements */
150623
- CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
150624
- int nCol; /* Number of columns in result set */
150625
-
150626
- assert( p->pNext==0 );
150627
- assert( p->pEList!=0 );
150628
- nCol = p->pEList->nExpr;
150629
- pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
150630
- if( !pKeyInfo ){
150631
- rc = SQLITE_NOMEM_BKPT;
150632
- goto multi_select_end;
150633
- }
150634
- for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
150635
- *apColl = multiSelectCollSeq(pParse, p, i);
150636
- if( 0==*apColl ){
150637
- *apColl = db->pDfltColl;
150638
- }
150639
- }
150640
-
150641
- for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
150642
- for(i=0; i<2; i++){
150643
- int addr = pLoop->addrOpenEphm[i];
150644
- if( addr<0 ){
150645
- /* If [0] is unused then [1] is also unused. So we can
150646
- ** always safely abort as soon as the first unused slot is found */
150647
- assert( pLoop->addrOpenEphm[1]<0 );
150648
- break;
150649
- }
150650
- sqlite3VdbeChangeP2(v, addr, nCol);
150651
- sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
150652
- P4_KEYINFO);
150653
- pLoop->addrOpenEphm[i] = -1;
150654
- }
150655
- }
150656
- sqlite3KeyInfoUnref(pKeyInfo);
150605
+#endif
150657150606
}
150658150607
150659150608
multi_select_end:
150660150609
pDest->iSdst = dest.iSdst;
150661150610
pDest->nSdst = dest.nSdst;
@@ -150683,12 +150632,12 @@
150683150632
150684150633
/*
150685150634
** Code an output subroutine for a coroutine implementation of a
150686150635
** SELECT statement.
150687150636
**
150688
-** The data to be output is contained in pIn->iSdst. There are
150689
-** pIn->nSdst columns to be output. pDest is where the output should
150637
+** The data to be output is contained in an array of pIn->nSdst registers
150638
+** starting at register pIn->iSdst. pDest is where the output should
150690150639
** be sent.
150691150640
**
150692150641
** regReturn is the number of the register holding the subroutine
150693150642
** return address.
150694150643
**
@@ -150713,10 +150662,12 @@
150713150662
){
150714150663
Vdbe *v = pParse->pVdbe;
150715150664
int iContinue;
150716150665
int addr;
150717150666
150667
+ assert( pIn->eDest==SRT_Coroutine );
150668
+
150718150669
addr = sqlite3VdbeCurrentAddr(v);
150719150670
iContinue = sqlite3VdbeMakeLabel(pParse);
150720150671
150721150672
/* Suppress duplicates for UNION, EXCEPT, and INTERSECT
150722150673
*/
@@ -150734,26 +150685,63 @@
150734150685
150735150686
/* Suppress the first OFFSET entries if there is an OFFSET clause
150736150687
*/
150737150688
codeOffset(v, p->iOffset, iContinue);
150738150689
150739
- assert( pDest->eDest!=SRT_Exists );
150740
- assert( pDest->eDest!=SRT_Table );
150741150690
switch( pDest->eDest ){
150742150691
/* Store the result as data using a unique key.
150743150692
*/
150693
+ case SRT_Fifo:
150694
+ case SRT_DistFifo:
150695
+ case SRT_Table:
150744150696
case SRT_EphemTab: {
150745150697
int r1 = sqlite3GetTempReg(pParse);
150746150698
int r2 = sqlite3GetTempReg(pParse);
150699
+ int iParm = pDest->iSDParm;
150700
+ testcase( pDest->eDest==SRT_Table );
150701
+ testcase( pDest->eDest==SRT_EphemTab );
150702
+ testcase( pDest->eDest==SRT_Fifo );
150703
+ testcase( pDest->eDest==SRT_DistFifo );
150747150704
sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
150748
- sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
150749
- sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
150705
+#if !defined(SQLITE_ENABLE_NULL_TRIM) && defined(SQLITE_DEBUG)
150706
+ /* A destination of SRT_Table and a non-zero iSDParm2 parameter means
150707
+ ** that this is an "UPDATE ... FROM" on a virtual table or view. In this
150708
+ ** case set the p5 parameter of the OP_MakeRecord to OPFLAG_NOCHNG_MAGIC.
150709
+ ** This does not affect operation in any way - it just allows MakeRecord
150710
+ ** to process OPFLAG_NOCHANGE values without an assert() failing. */
150711
+ if( pDest->eDest==SRT_Table && pDest->iSDParm2 ){
150712
+ sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
150713
+ }
150714
+#endif
150715
+#ifndef SQLITE_OMIT_CTE
150716
+ if( pDest->eDest==SRT_DistFifo ){
150717
+ /* If the destination is DistFifo, then cursor (iParm+1) is open
150718
+ ** on an ephemeral index that is used to enforce uniqueness on the
150719
+ ** total result. At this point, we are processing the setup portion
150720
+ ** of the recursive CTE using the merge algorithm, so the results are
150721
+ ** guaranteed to be unique anyhow. But we still need to populate the
150722
+ ** (iParm+1) cursor for use by the subsequent recursive phase.
150723
+ */
150724
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,
150725
+ pIn->iSdst, pIn->nSdst);
150726
+ }
150727
+#endif
150728
+ sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
150729
+ sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
150750150730
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
150751150731
sqlite3ReleaseTempReg(pParse, r2);
150752150732
sqlite3ReleaseTempReg(pParse, r1);
150753150733
break;
150754150734
}
150735
+
150736
+ /* If any row exist in the result set, record that fact and abort.
150737
+ */
150738
+ case SRT_Exists: {
150739
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
150740
+ /* The LIMIT clause will terminate the loop for us */
150741
+ break;
150742
+ }
150755150743
150756150744
#ifndef SQLITE_OMIT_SUBQUERY
150757150745
/* If we are creating a set for an "expr IN (SELECT ...)".
150758150746
*/
150759150747
case SRT_Set: {
@@ -150796,14 +150784,74 @@
150796150784
}
150797150785
sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
150798150786
sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
150799150787
break;
150800150788
}
150789
+
150790
+#ifndef SQLITE_OMIT_CTE
150791
+ /* Write the results into a priority queue that is order according to
150792
+ ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
150793
+ ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
150794
+ ** pSO->nExpr columns, then make sure all keys are unique by adding a
150795
+ ** final OP_Sequence column. The last column is the record as a blob.
150796
+ */
150797
+ case SRT_DistQueue:
150798
+ case SRT_Queue: {
150799
+ int nKey;
150800
+ int r1, r2, r3, ii;
150801
+ ExprList *pSO;
150802
+ int iParm = pDest->iSDParm;
150803
+ pSO = pDest->pOrderBy;
150804
+ assert( pSO );
150805
+ nKey = pSO->nExpr;
150806
+ r1 = sqlite3GetTempReg(pParse);
150807
+ r2 = sqlite3GetTempRange(pParse, nKey+2);
150808
+ r3 = r2+nKey+1;
150809
+
150810
+#if 0 /* <-- Why the next block of code is commented out: (tag-20260125-a)
150811
+ **
150812
+ ** If the destination is DistQueue, then cursor (iParm+1) is open
150813
+ ** on a second ephemeral index that holds all values previously
150814
+ ** added to the queue. This code only runs during the setup phase
150815
+ ** using the merge algorithm, and so the values here are already
150816
+ ** guaranteed to be unique.
150817
+ */
150818
+ if( pDest->eDest==SRT_DistQueue ){
150819
+ addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
150820
+ pIn->iSdst, pIn->nSdst);
150821
+ VdbeCoverage(v);
150822
+ }
150823
+#endif
150824
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r3);
150825
+ if( pDest->eDest==SRT_DistQueue ){
150826
+ sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
150827
+ sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
150828
+ }
150829
+ for(ii=0; ii<nKey; ii++){
150830
+ sqlite3VdbeAddOp2(v, OP_SCopy,
150831
+ pIn->iSdst + pSO->a[ii].u.x.iOrderByCol - 1,
150832
+ r2+ii);
150833
+ }
150834
+ sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
150835
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
150836
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
150837
+#if 0 /* tag-20260125-a */
150838
+ if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
150839
+#endif
150840
+ sqlite3ReleaseTempReg(pParse, r1);
150841
+ sqlite3ReleaseTempRange(pParse, r2, nKey+2);
150842
+ break;
150843
+ }
150844
+#endif /* SQLITE_OMIT_CTE */
150845
+
150846
+ /* Ignore the output */
150847
+ case SRT_Discard: {
150848
+ break;
150849
+ }
150801150850
150802150851
/* If none of the above, then the result destination must be
150803
- ** SRT_Output. This routine is never called with any other
150804
- ** destination other than the ones handled above or SRT_Output.
150852
+ ** SRT_Output.
150805150853
**
150806150854
** For SRT_Output, results are stored in a sequence of registers.
150807150855
** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
150808150856
** return the next row of result.
150809150857
*/
@@ -150827,12 +150875,13 @@
150827150875
150828150876
return addr;
150829150877
}
150830150878
150831150879
/*
150832
-** Alternative compound select code generator for cases when there
150833
-** is an ORDER BY clause.
150880
+** Generate code for a compound SELECT statement using a merge
150881
+** algorithm. The compound must have an ORDER BY clause for this
150882
+** to work.
150834150883
**
150835150884
** We assume a query of the following form:
150836150885
**
150837150886
** <selectA> <operator> <selectB> ORDER BY <orderbylist>
150838150887
**
@@ -150845,11 +150894,11 @@
150845150894
** outA: Move the output of the selectA coroutine into the output
150846150895
** of the compound query.
150847150896
**
150848150897
** outB: Move the output of the selectB coroutine into the output
150849150898
** of the compound query. (Only generated for UNION and
150850
-** UNION ALL. EXCEPT and INSERTSECT never output a row that
150899
+** UNION ALL. EXCEPT and INTERSECT never output a row that
150851150900
** appears only in B.)
150852150901
**
150853150902
** AltB: Called when there is data from both coroutines and A<B.
150854150903
**
150855150904
** AeqB: Called when there is data from both coroutines and A==B.
@@ -150898,25 +150947,23 @@
150898150947
** EofB: ...
150899150948
** AltB: ...
150900150949
** AeqB: ...
150901150950
** AgtB: ...
150902150951
** Init: initialize coroutine registers
150903
-** yield coA
150904
-** if eof(A) goto EofA
150905
-** yield coB
150906
-** if eof(B) goto EofB
150952
+** yield coA, on eof goto EofA
150953
+** yield coB, on eof goto EofB
150907150954
** Cmpr: Compare A, B
150908150955
** Jump AltB, AeqB, AgtB
150909150956
** End: ...
150910150957
**
150911150958
** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
150912150959
** actually called using Gosub and they do not Return. EofA and EofB loop
150913150960
** until all data is exhausted then jump to the "end" label. AltB, AeqB,
150914
-** and AgtB jump to either L2 or to one of EofA or EofB.
150961
+** and AgtB jump to either Cmpr or to one of EofA or EofB.
150915150962
*/
150916150963
#ifndef SQLITE_OMIT_COMPOUND_SELECT
150917
-static int multiSelectOrderBy(
150964
+static int multiSelectByMerge(
150918150965
Parse *pParse, /* Parsing context */
150919150966
Select *p, /* The right-most of SELECTs to be coded */
150920150967
SelectDest *pDest /* What to do with query results */
150921150968
){
150922150969
int i, j; /* Loop counters */
@@ -150993,30 +151040,33 @@
150993151040
}
150994151041
}
150995151042
}
150996151043
150997151044
/* Compute the comparison permutation and keyinfo that is used with
150998
- ** the permutation used to determine if the next
150999
- ** row of results comes from selectA or selectB. Also add explicit
151000
- ** collations to the ORDER BY clause terms so that when the subqueries
151001
- ** to the right and the left are evaluated, they use the correct
151002
- ** collation.
151045
+ ** the permutation to determine if the next row of results comes
151046
+ ** from selectA or selectB. Also add literal collations to the
151047
+ ** ORDER BY clause terms so that when selectA and selectB are
151048
+ ** evaluated, they use the correct collation.
151003151049
*/
151004151050
aPermute = sqlite3DbMallocRawNN(db, sizeof(u32)*(nOrderBy + 1));
151005151051
if( aPermute ){
151006151052
struct ExprList_item *pItem;
151053
+ int bKeep = 0;
151007151054
aPermute[0] = nOrderBy;
151008151055
for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
151009151056
assert( pItem!=0 );
151010151057
assert( pItem->u.x.iOrderByCol>0 );
151011151058
assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
151012151059
aPermute[i] = pItem->u.x.iOrderByCol - 1;
151060
+ if( aPermute[i]!=(u32)i-1 ) bKeep = 1;
151013151061
}
151014
- pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
151015
- }else{
151016
- pKeyMerge = 0;
151062
+ if( bKeep==0 ){
151063
+ sqlite3DbFreeNN(db, aPermute);
151064
+ aPermute = 0;
151065
+ }
151017151066
}
151067
+ pKeyMerge = multiSelectByMergeKeyInfo(pParse, p, 1);
151018151068
151019151069
/* Allocate a range of temporary registers and the KeyInfo needed
151020151070
** for the logic that removes duplicate result rows when the
151021151071
** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
151022151072
*/
@@ -151091,11 +151141,11 @@
151091151141
/* Generate a coroutine to evaluate the SELECT statement to the
151092151142
** left of the compound operator - the "A" select.
151093151143
*/
151094151144
addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
151095151145
addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
151096
- VdbeComment((v, "left SELECT"));
151146
+ VdbeComment((v, "SUBR: next-A"));
151097151147
pPrior->iLimit = regLimitA;
151098151148
ExplainQueryPlan((pParse, 1, "LEFT"));
151099151149
sqlite3Select(pParse, pPrior, &destA);
151100151150
sqlite3VdbeEndCoroutine(v, regAddrA);
151101151151
sqlite3VdbeJumpHere(v, addr1);
@@ -151103,11 +151153,11 @@
151103151153
/* Generate a coroutine to evaluate the SELECT statement on
151104151154
** the right - the "B" select
151105151155
*/
151106151156
addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
151107151157
addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
151108
- VdbeComment((v, "right SELECT"));
151158
+ VdbeComment((v, "SUBR: next-B"));
151109151159
savedLimit = p->iLimit;
151110151160
savedOffset = p->iOffset;
151111151161
p->iLimit = regLimitB;
151112151162
p->iOffset = 0;
151113151163
ExplainQueryPlan((pParse, 1, "RIGHT"));
@@ -151117,20 +151167,20 @@
151117151167
sqlite3VdbeEndCoroutine(v, regAddrB);
151118151168
151119151169
/* Generate a subroutine that outputs the current row of the A
151120151170
** select as the next output row of the compound select.
151121151171
*/
151122
- VdbeNoopComment((v, "Output routine for A"));
151172
+ VdbeNoopComment((v, "SUBR: out-A"));
151123151173
addrOutA = generateOutputSubroutine(pParse,
151124151174
p, &destA, pDest, regOutA,
151125151175
regPrev, pKeyDup, labelEnd);
151126151176
151127151177
/* Generate a subroutine that outputs the current row of the B
151128151178
** select as the next output row of the compound select.
151129151179
*/
151130151180
if( op==TK_ALL || op==TK_UNION ){
151131
- VdbeNoopComment((v, "Output routine for B"));
151181
+ VdbeNoopComment((v, "SUBR: out-B"));
151132151182
addrOutB = generateOutputSubroutine(pParse,
151133151183
p, &destB, pDest, regOutB,
151134151184
regPrev, pKeyDup, labelEnd);
151135151185
}
151136151186
sqlite3KeyInfoUnref(pKeyDup);
@@ -151139,14 +151189,16 @@
151139151189
** are exhausted and only data in select B remains.
151140151190
*/
151141151191
if( op==TK_EXCEPT || op==TK_INTERSECT ){
151142151192
addrEofA_noB = addrEofA = labelEnd;
151143151193
}else{
151144
- VdbeNoopComment((v, "eof-A subroutine"));
151194
+ VdbeNoopComment((v, "SUBR: eof-A"));
151145151195
addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
151196
+ VdbeComment((v, "out-B"));
151146151197
addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
151147151198
VdbeCoverage(v);
151199
+ VdbeComment((v, "next-B"));
151148151200
sqlite3VdbeGoto(v, addrEofA);
151149151201
p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
151150151202
}
151151151203
151152151204
/* Generate a subroutine to run when the results from select B
@@ -151154,21 +151206,24 @@
151154151206
*/
151155151207
if( op==TK_INTERSECT ){
151156151208
addrEofB = addrEofA;
151157151209
if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
151158151210
}else{
151159
- VdbeNoopComment((v, "eof-B subroutine"));
151211
+ VdbeNoopComment((v, "SUBR: eof-B"));
151160151212
addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
151213
+ VdbeComment((v, "out-A"));
151161151214
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
151215
+ VdbeComment((v, "next-A"));
151162151216
sqlite3VdbeGoto(v, addrEofB);
151163151217
}
151164151218
151165151219
/* Generate code to handle the case of A<B
151166151220
*/
151167
- VdbeNoopComment((v, "A-lt-B subroutine"));
151168151221
addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
151222
+ VdbeComment((v, "out-A"));
151169151223
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
151224
+ VdbeComment((v, "next-A"));
151170151225
sqlite3VdbeGoto(v, labelCmpr);
151171151226
151172151227
/* Generate code to handle the case of A==B
151173151228
*/
151174151229
if( op==TK_ALL ){
@@ -151175,40 +151230,52 @@
151175151230
addrAeqB = addrAltB;
151176151231
}else if( op==TK_INTERSECT ){
151177151232
addrAeqB = addrAltB;
151178151233
addrAltB++;
151179151234
}else{
151180
- VdbeNoopComment((v, "A-eq-B subroutine"));
151181
- addrAeqB =
151182
- sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
151183
- sqlite3VdbeGoto(v, labelCmpr);
151235
+ addrAeqB = addrAltB + 1;
151184151236
}
151185151237
151186151238
/* Generate code to handle the case of A>B
151187151239
*/
151188
- VdbeNoopComment((v, "A-gt-B subroutine"));
151189151240
addrAgtB = sqlite3VdbeCurrentAddr(v);
151190151241
if( op==TK_ALL || op==TK_UNION ){
151191151242
sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
151243
+ VdbeComment((v, "out-B"));
151244
+ sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
151245
+ VdbeComment((v, "next-B"));
151246
+ sqlite3VdbeGoto(v, labelCmpr);
151247
+ }else{
151248
+ addrAgtB++; /* Just do next-B. Might as well use the next-B call
151249
+ ** in the next code block */
151192151250
}
151193
- sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
151194
- sqlite3VdbeGoto(v, labelCmpr);
151195151251
151196151252
/* This code runs once to initialize everything.
151197151253
*/
151198151254
sqlite3VdbeJumpHere(v, addr1);
151199151255
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
151256
+ VdbeComment((v, "next-A"));
151257
+ /* v--- Also the A>B case for EXCEPT and INTERSECT */
151200151258
sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
151259
+ VdbeComment((v, "next-B"));
151201151260
151202151261
/* Implement the main merge loop
151203151262
*/
151263
+ if( aPermute!=0 ){
151264
+ sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
151265
+ }
151204151266
sqlite3VdbeResolveLabel(v, labelCmpr);
151205
- sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
151206151267
sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
151207151268
(char*)pKeyMerge, P4_KEYINFO);
151208
- sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
151209
- sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
151269
+ if( aPermute!=0 ){
151270
+ sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
151271
+ }
151272
+ sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
151273
+ VdbeCoverageIf(v, op==TK_ALL);
151274
+ VdbeCoverageIf(v, op==TK_UNION);
151275
+ VdbeCoverageIf(v, op==TK_EXCEPT);
151276