Fossil SCM

Update the built-in SQLite to the latest 3.55.0-alpha trunk version, for beta-testing of SQLite.

drh 2026-11-15 16:10 UTC trunk
Commit c92989d3a84fa0f85bedc43dd8036c2e1870195a81d7d616d1b9db02341989c2
3 files changed +2303 -1337 +2422 -953 +16 -6
+2303 -1337
--- extsrc/shell.c
+++ extsrc/shell.c
@@ -25,10 +25,11 @@
2525
** ext/misc/sqlar.c
2626
** ext/misc/sqlite3_stdio.c
2727
** ext/misc/sqlite3_stdio.h
2828
** ext/misc/stmtrand.c
2929
** ext/misc/strdup.c
30
+** ext/misc/tryeval.c
3031
** ext/misc/uint.c
3132
** ext/misc/vfstrace.c
3233
** ext/misc/windirent.h
3334
** ext/misc/zipfile.c
3435
** ext/qrf/qrf.c
@@ -1655,10 +1656,16 @@
16551656
n = (n+8)&~7;
16561657
}else if( z[0]=='\n' || z[0]=='\r' ){
16571658
nNL++;
16581659
if( n>mx ) mx = n;
16591660
n = 0;
1661
+ }else{
1662
+ /* Any other control character is shown by qrfAppendWithTabs()
1663
+ ** as a one-column-wide Control Picture symbol, and is counted as
1664
+ ** one column by qrfWrapLine(). Count it as one column here too,
1665
+ ** so that columns are wide enough to hold it. */
1666
+ n++;
16601667
}
16611668
z++;
16621669
}
16631670
}else if( (0x80&z[0])==0 ){
16641671
n++;
@@ -2009,10 +2016,11 @@
20092016
*/
20102017
static int qrfTitleLimit(char *zIn, int N){
20112018
unsigned char *z = (unsigned char*)zIn;
20122019
int n = 0;
20132020
unsigned char *zEllipsis = 0;
2021
+ int nEllipsis = 0; /* Display width of the text before zEllipsis */
20142022
while( 1 /*exit-by-break*/ ){
20152023
if( z[0]<' ' ){
20162024
int k;
20172025
if( z[0]==0 ){
20182026
zEllipsis = 0;
@@ -2025,24 +2033,28 @@
20252033
z[0] = ' ';
20262034
}else{
20272035
z++;
20282036
}
20292037
}else if( (0x80&z[0])==0 ){
2030
- if( n>=(N-3) && zEllipsis==0 ) zEllipsis = z;
2038
+ if( n>=(N-3) && zEllipsis==0 ){ zEllipsis = z; nEllipsis = n; }
20312039
if( n==N ){ z[0] = 0; break; }
20322040
n++;
20332041
z++;
20342042
}else{
20352043
int u = 0;
20362044
int len = sqlite3_qrf_decode_utf8(z, &u);
2037
- if( n+len>(N-3) && zEllipsis==0 ) zEllipsis = z;
2038
- if( n+len>N ){ z[0] = 0; break; }
2045
+ int w = sqlite3_qrf_wcwidth(u); /* Display width, not byte count */
2046
+ if( n+w>(N-3) && zEllipsis==0 ){ zEllipsis = z; nEllipsis = n; }
2047
+ if( n+w>N ){ z[0] = 0; break; }
20392048
z += len;
2040
- n += sqlite3_qrf_wcwidth(u);
2049
+ n += w;
20412050
}
20422051
}
2043
- if( zEllipsis && N>=3 ) memcpy(zEllipsis,"...",4);
2052
+ if( zEllipsis && N>=3 ){
2053
+ memcpy(zEllipsis,"...",4);
2054
+ n = nEllipsis + 3; /* Width of the text kept plus the "..." */
2055
+ }
20442056
return n;
20452057
}
20462058
20472059
20482060
/*
@@ -2178,11 +2190,16 @@
21782190
}
21792191
}
21802192
break;
21812193
}
21822194
case SQLITE_NULL: {
2183
- sqlite3_str_appendall(pOut, p->spec.zNull);
2195
+ if( p->spec.eText==QRF_TEXT_Html ){
2196
+ /* The NULL text is user-supplied (--null) and must be escaped */
2197
+ qrfEncodeText(p, pOut, p->spec.zNull);
2198
+ }else{
2199
+ sqlite3_str_appendall(pOut, p->spec.zNull);
2200
+ }
21842201
break;
21852202
}
21862203
case SQLITE_TEXT: {
21872204
const char *zTxt = (const char*)sqlite3_column_text(p->pStmt,iCol);
21882205
qrfEncodeText(p, pOut, zTxt);
@@ -2240,11 +2257,12 @@
22402257
22412258
/*
22422259
** Store string zUtf to pOut as w characters. If w is negative,
22432260
** then right-justify the text. W is the width in display characters, not
22442261
** in bytes. Double-width unicode characters count as two characters.
2245
-** VT100 escape sequences count as zero. And so forth.
2262
+** VT100 escape sequences and other control characters count as zero.
2263
+** And so forth.
22462264
*/
22472265
static void qrfWidthPrint(Qrf *p, sqlite3_str *pOut, int w, const char *zUtf){
22482266
const unsigned char *a = (const unsigned char*)zUtf;
22492267
static const int mxW = 10000000;
22502268
unsigned char c;
@@ -2270,10 +2288,14 @@
22702288
}
22712289
i += len;
22722290
n += x;
22732291
}else if( c==0x1b && (k = qrfIsVt100(&a[i]))>0 ){
22742292
i += k;
2293
+ }else if( c<0x20 ){
2294
+ /* Other control characters are zero-width, as in
2295
+ ** sqlite3_qrf_wcswidth() */
2296
+ i++;
22752297
}else if( n>=aw ){
22762298
break;
22772299
}else{
22782300
n++;
22792301
i++;
@@ -3865,11 +3887,11 @@
38653887
if( p->spec.zFpFmt==0 ) p->spec.zFpFmt = "%!0.17g";
38663888
break;
38673889
}
38683890
case QRF_STYLE_Html: {
38693891
p->spec.eText = QRF_TEXT_Html;
3870
- p->spec.zNull = "null";
3892
+ if( pSpec->zNull==0 ) p->spec.zNull = "null";
38713893
break;
38723894
}
38733895
case QRF_STYLE_Insert: {
38743896
p->spec.eText = QRF_TEXT_Sql;
38753897
p->spec.zNull = "NULL";
@@ -6314,14 +6336,15 @@
63146336
z = sqlite3_malloc64( (sqlite3_int64)p->nDigit+8 );
63156337
if( z==0 ){
63166338
sqlite3_result_error_nomem(pCtx);
63176339
return;
63186340
}
6341
+ if( p->sign ){
6342
+ for(i=0; i<p->nDigit && p->a[i]==0; i++){}
6343
+ if( i==p->nDigit ) p->sign = 0;
6344
+ }
63196345
i = 0;
6320
- if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
6321
- p->sign = 0;
6322
- }
63236346
if( p->sign ){
63246347
z[0] = '-';
63256348
i = 1;
63266349
}
63276350
n = p->nDigit - p->nFrac;
@@ -7205,45 +7228,62 @@
72057228
char c;
72067229
while( nc-- > 0 && (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s;
72077230
return s;
72087231
}
72097232
7210
-/* Decode base64 text into a byte buffer. */
7233
+/* Decode base64 text into a byte buffer.
7234
+**
7235
+** Whitespace is ignored wherever it appears, including inside a group
7236
+** of four base64 digits. A pad character fills one position of its
7237
+** group with zero bits. Any other non-base64 character inside a group
7238
+** ends the decode. Each group yields only the whole bytes encoded by
7239
+** the base64 digits actually present in it.
7240
+*/
72117241
static u8* fromBase64( char *pIn, int ncIn, u8 *pOut ){
72127242
if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
72137243
while( ncIn>0 && *pIn!=PAD_CHAR ){
72147244
static signed char nboi[] = { 0, 0, 1, 2, 3 };
72157245
char *pUse = skipNonB64(pIn, ncIn);
72167246
unsigned long qv = 0L;
7217
- int nti, nbo, nac;
7247
+ int nbo, nac = 0, ndg = 0;
72187248
ncIn -= (pUse - pIn);
72197249
pIn = pUse;
7220
- nti = (ncIn>4)? 4 : ncIn;
7221
- ncIn -= nti;
7222
- nbo = nboi[nti];
7223
- if( nbo==0 ) break;
7224
- for( nac=0; nac<4; ++nac ){
7225
- char c = (nac<nti)? *pIn++ : b64Numerals[0];
7226
- u8 bdp = BX_DV_PROTO(c);
7227
- switch( bdp ){
7228
- case ND:
7229
- /* Treat dark non-digits as pad, but they terminate decode too. */
7230
- ncIn = 0;
7231
- deliberate_fall_through; /* FALLTHRU */
7232
- case WS:
7233
- /* Treat whitespace as pad and terminate this group.*/
7234
- nti = nac;
7235
- deliberate_fall_through; /* FALLTHRU */
7236
- case PC:
7237
- bdp = 0;
7238
- --nbo;
7239
- deliberate_fall_through; /* FALLTHRU */
7240
- default: /* bdp is the digit value. */
7250
+ if( ncIn>=4 ){
7251
+ /* Fast path: a complete group of four base64 digits. */
7252
+ u8 d0 = BX_DV_PROTO(pIn[0]), d1 = BX_DV_PROTO(pIn[1]);
7253
+ u8 d2 = BX_DV_PROTO(pIn[2]), d3 = BX_DV_PROTO(pIn[3]);
7254
+ if( IS_BX_DIGIT(d0|d1|d2|d3) ){
7255
+ qv = (unsigned long)d0<<18 | (unsigned long)d1<<12 | d2<<6 | d3;
7256
+ pOut[0] = (qv>>16) & 0xff;
7257
+ pOut[1] = (qv>>8) & 0xff;
7258
+ pOut[2] = (qv) & 0xff;
7259
+ pOut += 3;
7260
+ pIn += 4;
7261
+ ncIn -= 4;
7262
+ continue;
7263
+ }
7264
+ }
7265
+ /* Gather up to four group positions: digits and pad characters. */
7266
+ while( nac<4 && ncIn>0 ){
7267
+ u8 bdp = BX_DV_PROTO(*pIn);
7268
+ if( IS_BX_DIGIT(bdp) ){
72417269
qv = qv<<6 | bdp;
7270
+ ++nac;
7271
+ ++ndg;
7272
+ }else if( IS_BX_PAD(bdp) ){
7273
+ qv <<= 6;
7274
+ ++nac;
7275
+ }else if( !IS_BX_WS(bdp) ){
7276
+ /* Dark non-digits terminate the decode. */
7277
+ ncIn = 0;
72427278
break;
72437279
}
7280
+ ++pIn;
7281
+ --ncIn;
72447282
}
7283
+ qv <<= 6*(4-nac);
7284
+ nbo = nboi[ndg];
72457285
switch( nbo ){
72467286
case 3:
72477287
pOut[2] = (qv) & 0xff;
72487288
deliberate_fall_through; /* FALLTHRU */
72497289
case 2:
@@ -7867,11 +7907,11 @@
78677907
{ OPT_MASK(16), "PropagateConst" },
78687908
{ OPT_MASK(17), "MinMaxOpt" },
78697909
{ OPT_MASK(18), "SeekScan" },
78707910
{ OPT_MASK(19), "OmitOrderBy" },
78717911
{ OPT_MASK(20), "BloomFilter" },
7872
- /* 21 currently unused */
7912
+ { OPT_MASK(21), "DevTest" },
78737913
{ OPT_MASK(22), "BalancedMerge" },
78747914
{ OPT_MASK(23), "ReleaseReg" },
78757915
{ OPT_MASK(24), "FlttnUnionAll" },
78767916
{ OPT_MASK(25), "IndexedExpr" },
78777917
{ OPT_MASK(26), "Coroutines" },
@@ -7880,10 +7920,11 @@
78807920
{ OPT_MASK(29), "OrderBySubq" },
78817921
{ OPT_MASK(29), "OrderBySubquery" }, /* Alias for prior */
78827922
{ OPT_MASK(30), "StarQuery" },
78837923
{ OPT_MASK(31), "ExistsToJoin" },
78847924
{ OPT_MASK(32), "UnionLimit" },
7925
+ { OPT_MASK(33), "HavingToWhere" },
78857926
/* Special names */
78867927
{ 0xffffffffffffffffULL, "All" },
78877928
{ 0x0000000000000000ULL, "None" },
78887929
};
78897930
@@ -8284,970 +8325,10 @@
82848325
}
82858326
return rc;
82868327
}
82878328
82888329
/************************* End ext/misc/ieee754.c ********************/
8289
-/************************* Begin ext/misc/series.c ******************/
8290
-/*
8291
-** 2015-08-18, 2023-04-28
8292
-**
8293
-** The author disclaims copyright to this source code. In place of
8294
-** a legal notice, here is a blessing:
8295
-**
8296
-** May you do good and not evil.
8297
-** May you find forgiveness for yourself and forgive others.
8298
-** May you share freely, never taking more than you give.
8299
-**
8300
-*************************************************************************
8301
-**
8302
-** This file demonstrates how to create a table-valued-function using
8303
-** a virtual table. This demo implements the generate_series() function
8304
-** which gives the same results as the eponymous function in PostgreSQL,
8305
-** within the limitation that its arguments are signed 64-bit integers.
8306
-**
8307
-** Considering its equivalents to generate_series(start,stop,step): A
8308
-** value V[n] sequence is produced for integer n ascending from 0 where
8309
-** ( V[n] == start + n * step && sgn(V[n] - stop) * sgn(step) >= 0 )
8310
-** for each produced value (independent of production time ordering.)
8311
-**
8312
-** All parameters must be either integer or convertable to integer.
8313
-** The start parameter is required.
8314
-** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
8315
-** The step parameter defaults to 1 and 0 is treated as 1.
8316
-**
8317
-** Examples:
8318
-**
8319
-** SELECT * FROM generate_series(0,100,5);
8320
-**
8321
-** The query above returns integers from 0 through 100 counting by steps
8322
-** of 5. In other words, 0, 5, 10, 15, ..., 90, 95, 100. There are a total
8323
-** of 21 rows.
8324
-**
8325
-** SELECT * FROM generate_series(0,100);
8326
-**
8327
-** Integers from 0 through 100 with a step size of 1. 101 rows.
8328
-**
8329
-** SELECT * FROM generate_series(20) LIMIT 10;
8330
-**
8331
-** Integers 20 through 29. 10 rows.
8332
-**
8333
-** SELECT * FROM generate_series(0,-100,-5);
8334
-**
8335
-** Integers 0 -5 -10 ... -100. 21 rows.
8336
-**
8337
-** SELECT * FROM generate_series(0,-1);
8338
-**
8339
-** Empty sequence.
8340
-**
8341
-** HOW IT WORKS
8342
-**
8343
-** The generate_series "function" is really a virtual table with the
8344
-** following schema:
8345
-**
8346
-** CREATE TABLE generate_series(
8347
-** value,
8348
-** start HIDDEN,
8349
-** stop HIDDEN,
8350
-** step HIDDEN
8351
-** );
8352
-**
8353
-** The virtual table also has a rowid which is an alias for the value.
8354
-**
8355
-** Function arguments in queries against this virtual table are translated
8356
-** into equality constraints against successive hidden columns. In other
8357
-** words, the following pairs of queries are equivalent to each other:
8358
-**
8359
-** SELECT * FROM generate_series(0,100,5);
8360
-** SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
8361
-**
8362
-** SELECT * FROM generate_series(0,100);
8363
-** SELECT * FROM generate_series WHERE start=0 AND stop=100;
8364
-**
8365
-** SELECT * FROM generate_series(20) LIMIT 10;
8366
-** SELECT * FROM generate_series WHERE start=20 LIMIT 10;
8367
-**
8368
-** The generate_series virtual table implementation leaves the xCreate method
8369
-** set to NULL. This means that it is not possible to do a CREATE VIRTUAL
8370
-** TABLE command with "generate_series" as the USING argument. Instead, there
8371
-** is a single generate_series virtual table that is always available without
8372
-** having to be created first.
8373
-**
8374
-** The xBestIndex method looks for equality constraints against the hidden
8375
-** start, stop, and step columns, and if present, it uses those constraints
8376
-** to bound the sequence of generated values. If the equality constraints
8377
-** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
8378
-** xBestIndex returns a small cost when both start and stop are available,
8379
-** and a very large cost if either start or stop are unavailable. This
8380
-** encourages the query planner to order joins such that the bounds of the
8381
-** series are well-defined.
8382
-**
8383
-** Update on 2024-08-22:
8384
-** xBestIndex now also looks for equality and inequality constraints against
8385
-** the value column and uses those constraints as additional bounds against
8386
-** the sequence range. Thus, a query like this:
8387
-**
8388
-** SELECT value FROM generate_series($SA,$EA)
8389
-** WHERE value BETWEEN $SB AND $EB;
8390
-**
8391
-** Is logically the same as:
8392
-**
8393
-** SELECT value FROM generate_series(max($SA,$SB),min($EA,$EB));
8394
-**
8395
-** Constraints on the value column can server as substitutes for constraints
8396
-** on the hidden start and stop columns. So, the following two queries
8397
-** are equivalent:
8398
-**
8399
-** SELECT value FROM generate_series($S,$E);
8400
-** SELECT value FROM generate_series WHERE value BETWEEN $S and $E;
8401
-**
8402
-*/
8403
-/* #include "sqlite3ext.h" */
8404
-SQLITE_EXTENSION_INIT1
8405
-#include <assert.h>
8406
-#include <string.h>
8407
-#include <limits.h>
8408
-#include <math.h>
8409
-
8410
-#ifndef SQLITE_OMIT_VIRTUALTABLE
8411
-
8412
-/* series_cursor is a subclass of sqlite3_vtab_cursor which will
8413
-** serve as the underlying representation of a cursor that scans
8414
-** over rows of the result.
8415
-**
8416
-** iOBase, iOTerm, and iOStep are the original values of the
8417
-** start=, stop=, and step= constraints on the query. These are
8418
-** the values reported by the start, stop, and step columns of the
8419
-** virtual table.
8420
-**
8421
-** iBase, iTerm, iStep, and bDescp are the actual values used to generate
8422
-** the sequence. These might be different from the iOxxxx values.
8423
-** For example in
8424
-**
8425
-** SELECT value FROM generate_series(1,11,2)
8426
-** WHERE value BETWEEN 4 AND 8;
8427
-**
8428
-** The iOBase is 1, but the iBase is 5. iOTerm is 11 but iTerm is 7.
8429
-** Another example:
8430
-**
8431
-** SELECT value FROM generate_series(1,15,3) ORDER BY value DESC;
8432
-**
8433
-** The cursor initialization for the above query is:
8434
-**
8435
-** iOBase = 1 iBase = 13
8436
-** iOTerm = 15 iTerm = 1
8437
-** iOStep = 3 iStep = 3 bDesc = 1
8438
-**
8439
-** The actual step size is unsigned so that can have a value of
8440
-** +9223372036854775808 which is needed for querys like this:
8441
-**
8442
-** SELECT value
8443
-** FROM generate_series(9223372036854775807,
8444
-** -9223372036854775808,
8445
-** -9223372036854775808)
8446
-** ORDER BY value ASC;
8447
-**
8448
-** The setup for the previous query will be:
8449
-**
8450
-** iOBase = 9223372036854775807 iBase = -1
8451
-** iOTerm = -9223372036854775808 iTerm = 9223372036854775807
8452
-** iOStep = -9223372036854775808 iStep = 9223372036854775808 bDesc = 0
8453
-*/
8454
-/* typedef unsigned char u8; */
8455
-typedef struct series_cursor series_cursor;
8456
-struct series_cursor {
8457
- sqlite3_vtab_cursor base; /* Base class - must be first */
8458
- sqlite3_int64 iOBase; /* Original starting value ("start") */
8459
- sqlite3_int64 iOTerm; /* Original terminal value ("stop") */
8460
- sqlite3_int64 iOStep; /* Original step value */
8461
- sqlite3_int64 iBase; /* Starting value to actually use */
8462
- sqlite3_int64 iTerm; /* Terminal value to actually use */
8463
- sqlite3_uint64 iStep; /* The step size */
8464
- sqlite3_int64 iValue; /* Current value */
8465
- u8 bDesc; /* iStep is really negative */
8466
- u8 bDone; /* True if stepped past last element */
8467
- u8 bLimit; /* There exists a limit clause */
8468
-};
8469
-
8470
-/*
8471
-** Computed the difference between two 64-bit signed integers using a
8472
-** convoluted computation designed to work around the silly restriction
8473
-** against signed integer overflow in C.
8474
-*/
8475
-static sqlite3_uint64 span64(sqlite3_int64 a, sqlite3_int64 b){
8476
- assert( a>=b );
8477
- return (*(sqlite3_uint64*)&a) - (*(sqlite3_uint64*)&b);
8478
-}
8479
-
8480
-/*
8481
-** Add or substract an unsigned 64-bit integer from a signed 64-bit integer
8482
-** and return the new signed 64-bit integer.
8483
-*/
8484
-static sqlite3_int64 add64(sqlite3_int64 a, sqlite3_uint64 b){
8485
- sqlite3_uint64 x = *(sqlite3_uint64*)&a;
8486
- x += b;
8487
- return *(sqlite3_int64*)&x;
8488
-}
8489
-static sqlite3_int64 sub64(sqlite3_int64 a, sqlite3_uint64 b){
8490
- sqlite3_uint64 x = *(sqlite3_uint64*)&a;
8491
- x -= b;
8492
- return *(sqlite3_int64*)&x;
8493
-}
8494
-
8495
-/*
8496
-** The seriesConnect() method is invoked to create a new
8497
-** series_vtab that describes the generate_series virtual table.
8498
-**
8499
-** Think of this routine as the constructor for series_vtab objects.
8500
-**
8501
-** All this routine needs to do is:
8502
-**
8503
-** (1) Allocate the series_vtab object and initialize all fields.
8504
-**
8505
-** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
8506
-** result set of queries against generate_series will look like.
8507
-*/
8508
-static int seriesConnect(
8509
- sqlite3 *db,
8510
- void *pUnused,
8511
- int argcUnused, const char *const*argvUnused,
8512
- sqlite3_vtab **ppVtab,
8513
- char **pzErrUnused
8514
-){
8515
- sqlite3_vtab *pNew;
8516
- int rc;
8517
-
8518
-/* Column numbers */
8519
-#define SERIES_COLUMN_ROWID (-1)
8520
-#define SERIES_COLUMN_VALUE 0
8521
-#define SERIES_COLUMN_START 1
8522
-#define SERIES_COLUMN_STOP 2
8523
-#define SERIES_COLUMN_STEP 3
8524
-
8525
- (void)pUnused;
8526
- (void)argcUnused;
8527
- (void)argvUnused;
8528
- (void)pzErrUnused;
8529
- rc = sqlite3_declare_vtab(db,
8530
- "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
8531
- if( rc==SQLITE_OK ){
8532
- pNew = *ppVtab = sqlite3_malloc64( sizeof(*pNew) );
8533
- if( pNew==0 ) return SQLITE_NOMEM;
8534
- memset(pNew, 0, sizeof(*pNew));
8535
- sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
8536
- }
8537
- return rc;
8538
-}
8539
-
8540
-/*
8541
-** This method is the destructor for series_cursor objects.
8542
-*/
8543
-static int seriesDisconnect(sqlite3_vtab *pVtab){
8544
- sqlite3_free(pVtab);
8545
- return SQLITE_OK;
8546
-}
8547
-
8548
-/*
8549
-** Constructor for a new series_cursor object.
8550
-*/
8551
-static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
8552
- series_cursor *pCur;
8553
- (void)pUnused;
8554
- pCur = sqlite3_malloc64( sizeof(*pCur) );
8555
- if( pCur==0 ) return SQLITE_NOMEM;
8556
- memset(pCur, 0, sizeof(*pCur));
8557
- *ppCursor = &pCur->base;
8558
- return SQLITE_OK;
8559
-}
8560
-
8561
-/*
8562
-** Destructor for a series_cursor.
8563
-*/
8564
-static int seriesClose(sqlite3_vtab_cursor *cur){
8565
- sqlite3_free(cur);
8566
- return SQLITE_OK;
8567
-}
8568
-
8569
-
8570
-/*
8571
-** Advance a series_cursor to its next row of output.
8572
-*/
8573
-static int seriesNext(sqlite3_vtab_cursor *cur){
8574
- series_cursor *pCur = (series_cursor*)cur;
8575
- if( pCur->iValue==pCur->iTerm ){
8576
- pCur->bDone = 1;
8577
- }else if( pCur->bDesc ){
8578
- pCur->iValue = sub64(pCur->iValue, pCur->iStep);
8579
- assert( pCur->iValue>=pCur->iTerm || pCur->bLimit );
8580
- }else{
8581
- pCur->iValue = add64(pCur->iValue, pCur->iStep);
8582
- assert( pCur->iValue<=pCur->iTerm || pCur->bLimit );
8583
- }
8584
- return SQLITE_OK;
8585
-}
8586
-
8587
-/*
8588
-** Return values of columns for the row at which the series_cursor
8589
-** is currently pointing.
8590
-*/
8591
-static int seriesColumn(
8592
- sqlite3_vtab_cursor *cur, /* The cursor */
8593
- sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
8594
- int i /* Which column to return */
8595
-){
8596
- series_cursor *pCur = (series_cursor*)cur;
8597
- sqlite3_int64 x = 0;
8598
- switch( i ){
8599
- case SERIES_COLUMN_START: x = pCur->iOBase; break;
8600
- case SERIES_COLUMN_STOP: x = pCur->iOTerm; break;
8601
- case SERIES_COLUMN_STEP: x = pCur->iOStep; break;
8602
- default: x = pCur->iValue; break;
8603
- }
8604
- sqlite3_result_int64(ctx, x);
8605
- return SQLITE_OK;
8606
-}
8607
-
8608
-#ifndef LARGEST_UINT64
8609
-#define LARGEST_INT64 ((sqlite3_int64)0x7fffffffffffffffLL)
8610
-#define LARGEST_UINT64 ((sqlite3_uint64)0xffffffffffffffffULL)
8611
-#define SMALLEST_INT64 ((sqlite3_int64)0x8000000000000000LL)
8612
-#endif
8613
-
8614
-/*
8615
-** The rowid is the same as the value.
8616
-*/
8617
-static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
8618
- series_cursor *pCur = (series_cursor*)cur;
8619
- *pRowid = pCur->iValue;
8620
- return SQLITE_OK;
8621
-}
8622
-
8623
-/*
8624
-** Return TRUE if the cursor has been moved off of the last
8625
-** row of output.
8626
-*/
8627
-static int seriesEof(sqlite3_vtab_cursor *cur){
8628
- series_cursor *pCur = (series_cursor*)cur;
8629
- return pCur->bDone;
8630
-}
8631
-
8632
-/* True to cause run-time checking of the start=, stop=, and/or step=
8633
-** parameters. The only reason to do this is for testing the
8634
-** constraint checking logic for virtual tables in the SQLite core.
8635
-*/
8636
-#ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
8637
-# define SQLITE_SERIES_CONSTRAINT_VERIFY 0
8638
-#endif
8639
-
8640
-/*
8641
-** Return the number of steps between pCur->iBase and pCur->iTerm if
8642
-** the step width is pCur->iStep.
8643
-*/
8644
-static sqlite3_uint64 seriesSteps(series_cursor *pCur){
8645
- if( pCur->bDesc ){
8646
- assert( pCur->iBase >= pCur->iTerm );
8647
- return span64(pCur->iBase, pCur->iTerm)/pCur->iStep;
8648
- }else{
8649
- assert( pCur->iBase <= pCur->iTerm );
8650
- return span64(pCur->iTerm, pCur->iBase)/pCur->iStep;
8651
- }
8652
-}
8653
-
8654
-#if defined(SQLITE_ENABLE_MATH_FUNCTIONS) || defined(_WIN32)
8655
-/*
8656
-** Case 1 (the most common case):
8657
-** The standard math library is available so use ceil() and floor() from there.
8658
-*/
8659
-static double seriesCeil(double r){ return ceil(r); }
8660
-static double seriesFloor(double r){ return floor(r); }
8661
-#elif defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
8662
-/*
8663
-** Case 2 (2nd most common): Use GCC/Clang builtins
8664
-*/
8665
-static double seriesCeil(double r){ return __builtin_ceil(r); }
8666
-static double seriesFloor(double r){ return __builtin_floor(r); }
8667
-#else
8668
-/*
8669
-** Case 3 (rarely happens): Use home-grown ceil() and floor() routines.
8670
-*/
8671
-static double seriesCeil(double r){
8672
- sqlite3_int64 x;
8673
- if( r!=r ) return r;
8674
- if( r<=(-4503599627370496.0) ) return r;
8675
- if( r>=(+4503599627370496.0) ) return r;
8676
- x = (sqlite3_int64)r;
8677
- if( r==(double)x ) return r;
8678
- if( r>(double)x ) x++;
8679
- return (double)x;
8680
-}
8681
-static double seriesFloor(double r){
8682
- sqlite3_int64 x;
8683
- if( r!=r ) return r;
8684
- if( r<=(-4503599627370496.0) ) return r;
8685
- if( r>=(+4503599627370496.0) ) return r;
8686
- x = (sqlite3_int64)r;
8687
- if( r==(double)x ) return r;
8688
- if( r<(double)x ) x--;
8689
- return (double)x;
8690
-}
8691
-#endif
8692
-
8693
-/* Convert a floating point value to its closest integer. Do so in
8694
-** a way that avoids 'outside the range of representable values' warnings
8695
-** from UBSAN.
8696
-*/
8697
-static sqlite3_int64 seriesRealToI64(double r){
8698
- if( r<-9223372036854774784.0 ) return SMALLEST_INT64;
8699
- if( r>+9223372036854774784.0 ) return LARGEST_INT64;
8700
- return (sqlite3_int64)r;
8701
-}
8702
-
8703
-/*
8704
-** This method is called to "rewind" the series_cursor object back
8705
-** to the first row of output. This method is always called at least
8706
-** once prior to any call to seriesColumn() or seriesRowid() or
8707
-** seriesEof().
8708
-**
8709
-** The query plan selected by seriesBestIndex is passed in the idxNum
8710
-** parameter. (idxStr is not used in this implementation.) idxNum
8711
-** is a bitmask showing which constraints are available:
8712
-**
8713
-** 0x0001: start=VALUE
8714
-** 0x0002: stop=VALUE
8715
-** 0x0004: step=VALUE
8716
-** 0x0008: descending order
8717
-** 0x0010: ascending order
8718
-** 0x0020: LIMIT VALUE
8719
-** 0x0040: OFFSET VALUE
8720
-** 0x0080: value=VALUE
8721
-** 0x0100: value>=VALUE
8722
-** 0x0200: value>VALUE
8723
-** 0x1000: value<=VALUE
8724
-** 0x2000: value<VALUE
8725
-**
8726
-** This routine should initialize the cursor and position it so that it
8727
-** is pointing at the first row, or pointing off the end of the table
8728
-** (so that seriesEof() will return true) if the table is empty.
8729
-*/
8730
-static int seriesFilter(
8731
- sqlite3_vtab_cursor *pVtabCursor,
8732
- int idxNum, const char *idxStrUnused,
8733
- int argc, sqlite3_value **argv
8734
-){
8735
- series_cursor *pCur = (series_cursor *)pVtabCursor;
8736
- int iArg = 0; /* Arguments used so far */
8737
- int i; /* Loop counter */
8738
- sqlite3_int64 iMin = SMALLEST_INT64; /* Smallest allowed output value */
8739
- sqlite3_int64 iMax = LARGEST_INT64; /* Largest allowed output value */
8740
- sqlite3_int64 iLimit = 0; /* if >0, the value of the LIMIT */
8741
- sqlite3_int64 iOffset = 0; /* if >0, the value of the OFFSET */
8742
-
8743
- (void)idxStrUnused;
8744
-
8745
- /* If any constraints have a NULL value, then return no rows.
8746
- ** See ticket https://sqlite.org/src/info/fac496b61722daf2
8747
- */
8748
- for(i=0; i<argc; i++){
8749
- if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
8750
- goto series_no_rows;
8751
- }
8752
- }
8753
-
8754
- /* Capture the three HIDDEN parameters to the virtual table and insert
8755
- ** default values for any parameters that are omitted.
8756
- */
8757
- if( idxNum & 0x01 ){
8758
- pCur->iOBase = sqlite3_value_int64(argv[iArg++]);
8759
- }else{
8760
- pCur->iOBase = 0;
8761
- }
8762
- if( idxNum & 0x02 ){
8763
- pCur->iOTerm = sqlite3_value_int64(argv[iArg++]);
8764
- }else{
8765
- pCur->iOTerm = 0xffffffff;
8766
- }
8767
- if( idxNum & 0x04 ){
8768
- pCur->iOStep = sqlite3_value_int64(argv[iArg++]);
8769
- if( pCur->iOStep==0 ) pCur->iOStep = 1;
8770
- }else{
8771
- pCur->iOStep = 1;
8772
- }
8773
-
8774
- /* If there are constraints on the value column but there are
8775
- ** no constraints on the start, stop, and step columns, then
8776
- ** initialize the default range to be the entire range of 64-bit signed
8777
- ** integers. This range will contracted by the value column constraints
8778
- ** further below.
8779
- */
8780
- if( (idxNum & 0x05)==0 && (idxNum & 0x0380)!=0 ){
8781
- pCur->iOBase = SMALLEST_INT64;
8782
- }
8783
- if( (idxNum & 0x06)==0 && (idxNum & 0x3080)!=0 ){
8784
- pCur->iOTerm = LARGEST_INT64;
8785
- }
8786
- pCur->iBase = pCur->iOBase;
8787
- pCur->iTerm = pCur->iOTerm;
8788
- if( pCur->iOStep>0 ){
8789
- pCur->iStep = pCur->iOStep;
8790
- }else if( pCur->iOStep>SMALLEST_INT64 ){
8791
- pCur->iStep = -pCur->iOStep;
8792
- }else{
8793
- pCur->iStep = LARGEST_INT64;
8794
- pCur->iStep++;
8795
- }
8796
- pCur->bDesc = pCur->iOStep<0;
8797
- if( pCur->bDesc==0 && pCur->iBase>pCur->iTerm ){
8798
- goto series_no_rows;
8799
- }
8800
- if( pCur->bDesc!=0 && pCur->iBase<pCur->iTerm ){
8801
- goto series_no_rows;
8802
- }
8803
-
8804
- /* Extract the LIMIT and OFFSET values, but do not apply them yet.
8805
- ** The range must first be constrained by the limits on value.
8806
- */
8807
- if( idxNum & 0x20 ){
8808
- iLimit = sqlite3_value_int64(argv[iArg++]);
8809
- if( idxNum & 0x40 ){
8810
- iOffset = sqlite3_value_int64(argv[iArg++]);
8811
- }
8812
- if( iLimit>0 ) pCur->bLimit = 1;
8813
- }
8814
-
8815
- /* Narrow the range of iMin and iMax (the minimum and maximum outputs)
8816
- ** based on equality and inequality constraints on the "value" column.
8817
- */
8818
- if( idxNum & 0x3380 ){
8819
- if( idxNum & 0x0080 ){ /* value=X */
8820
- if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
8821
- double r = sqlite3_value_double(argv[iArg++]);
8822
- if( r==seriesCeil(r)
8823
- && r>=(double)SMALLEST_INT64
8824
- && r<=(double)LARGEST_INT64
8825
- ){
8826
- iMin = iMax = seriesRealToI64(r);
8827
- }else{
8828
- goto series_no_rows;
8829
- }
8830
- }else{
8831
- iMin = iMax = sqlite3_value_int64(argv[iArg++]);
8832
- }
8833
- }else{
8834
- if( idxNum & 0x0300 ){ /* value>X (0x200) or value>=X (0x100) */
8835
- if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
8836
- double r = sqlite3_value_double(argv[iArg++]);
8837
- if( r<=(double)SMALLEST_INT64 ){
8838
- iMin = SMALLEST_INT64;
8839
- }else if( r>(double)LARGEST_INT64 ){
8840
- goto series_no_rows;
8841
- }else{
8842
- iMin = seriesRealToI64(seriesCeil(r));
8843
- if( (idxNum & 0x0200)!=0 && r==seriesCeil(r) ){
8844
- if( iMin==LARGEST_INT64 ) goto series_no_rows;
8845
- iMin++;
8846
- }
8847
- }
8848
- }else{
8849
- iMin = sqlite3_value_int64(argv[iArg++]);
8850
- if( (idxNum & 0x0200)!=0 ){
8851
- if( iMin==LARGEST_INT64 ){
8852
- goto series_no_rows;
8853
- }else{
8854
- iMin++;
8855
- }
8856
- }
8857
- }
8858
- }
8859
- if( idxNum & 0x3000 ){ /* value<X (0x2000) or value<=X (0x1000) */
8860
- if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
8861
- double r = sqlite3_value_double(argv[iArg++]);
8862
- if( r>=(double)LARGEST_INT64 ){
8863
- iMax = LARGEST_INT64;
8864
- }else if( r<=(double)SMALLEST_INT64 ){
8865
- goto series_no_rows;
8866
- }else{
8867
- iMax = seriesRealToI64(seriesFloor(r));
8868
- if( (idxNum & 0x2000)!=0 && r==seriesFloor(r) ){
8869
- if( iMax==SMALLEST_INT64 ) goto series_no_rows;
8870
- iMax--;
8871
- }
8872
- }
8873
- }else{
8874
- iMax = sqlite3_value_int64(argv[iArg++]);
8875
- if( idxNum & 0x2000 ){
8876
- if( iMax==SMALLEST_INT64 ){
8877
- goto series_no_rows;
8878
- }else{
8879
- iMax--;
8880
- }
8881
- }
8882
- }
8883
- }
8884
- if( iMin>iMax ){
8885
- goto series_no_rows;
8886
- }
8887
- }
8888
-
8889
- /* Try to reduce the range of values to be generated based on
8890
- ** constraints on the "value" column.
8891
- */
8892
- if( pCur->bDesc==0 ){
8893
- if( pCur->iBase<iMin ){
8894
- sqlite3_uint64 span = span64(iMin,pCur->iBase);
8895
- pCur->iBase = add64(pCur->iBase, (span/pCur->iStep)*pCur->iStep);
8896
- if( pCur->iBase<iMin ){
8897
- if( pCur->iBase > sub64(LARGEST_INT64, pCur->iStep) ){
8898
- goto series_no_rows;
8899
- }
8900
- pCur->iBase = add64(pCur->iBase, pCur->iStep);
8901
- }
8902
- }
8903
- if( pCur->iTerm>iMax ){
8904
- pCur->iTerm = iMax;
8905
- }
8906
- }else{
8907
- if( pCur->iBase>iMax ){
8908
- sqlite3_uint64 span = span64(pCur->iBase,iMax);
8909
- pCur->iBase = sub64(pCur->iBase, (span/pCur->iStep)*pCur->iStep);
8910
- if( pCur->iBase>iMax ){
8911
- if( pCur->iBase < add64(SMALLEST_INT64, pCur->iStep) ){
8912
- goto series_no_rows;
8913
- }
8914
- pCur->iBase = sub64(pCur->iBase, pCur->iStep);
8915
- }
8916
- }
8917
- if( pCur->iTerm<iMin ){
8918
- pCur->iTerm = iMin;
8919
- }
8920
- }
8921
- }
8922
-
8923
- /* Adjust iTerm so that it is exactly the last value of the series.
8924
- */
8925
- if( pCur->bDesc==0 ){
8926
- if( pCur->iBase>pCur->iTerm ){
8927
- goto series_no_rows;
8928
- }
8929
- pCur->iTerm = sub64(pCur->iTerm,
8930
- span64(pCur->iTerm,pCur->iBase) % pCur->iStep);
8931
- }else{
8932
- if( pCur->iBase<pCur->iTerm ){
8933
- goto series_no_rows;
8934
- }
8935
- pCur->iTerm = add64(pCur->iTerm,
8936
- span64(pCur->iBase,pCur->iTerm) % pCur->iStep);
8937
- }
8938
-
8939
- /* Transform the series generator to output values in the requested
8940
- ** order.
8941
- */
8942
- if( ((idxNum & 0x0008)!=0 && pCur->bDesc==0)
8943
- || ((idxNum & 0x0010)!=0 && pCur->bDesc!=0)
8944
- ){
8945
- sqlite3_int64 tmp = pCur->iBase;
8946
- pCur->iBase = pCur->iTerm;
8947
- pCur->iTerm = tmp;
8948
- pCur->bDesc = !pCur->bDesc;
8949
- }
8950
-
8951
- /* Apply LIMIT and OFFSET constraints, if any */
8952
- assert( pCur->iStep!=0 );
8953
- if( idxNum & 0x20 ){
8954
- if( iOffset>0 ){
8955
- if( seriesSteps(pCur) < (sqlite3_uint64)iOffset ){
8956
- goto series_no_rows;
8957
- }else if( pCur->bDesc ){
8958
- pCur->iBase = sub64(pCur->iBase, pCur->iStep*iOffset);
8959
- }else{
8960
- pCur->iBase = add64(pCur->iBase, pCur->iStep*iOffset);
8961
- }
8962
- }
8963
- if( iLimit>=0 && seriesSteps(pCur) > (sqlite3_uint64)iLimit ){
8964
- pCur->iTerm = add64(pCur->iBase, (iLimit - 1)*pCur->iStep);
8965
- }
8966
- }
8967
- pCur->iValue = pCur->iBase;
8968
- pCur->bDone = 0;
8969
- return SQLITE_OK;
8970
-
8971
-series_no_rows:
8972
- pCur->iBase = 0;
8973
- pCur->iTerm = 0;
8974
- pCur->iStep = 1;
8975
- pCur->bDesc = 0;
8976
- pCur->bDone = 1;
8977
- return SQLITE_OK;
8978
-}
8979
-
8980
-/*
8981
-** SQLite will invoke this method one or more times while planning a query
8982
-** that uses the generate_series virtual table. This routine needs to create
8983
-** a query plan for each invocation and compute an estimated cost for that
8984
-** plan.
8985
-**
8986
-** In this implementation idxNum is used to represent the
8987
-** query plan. idxStr is unused.
8988
-**
8989
-** The query plan is represented by bits in idxNum:
8990
-**
8991
-** 0x0001 start = $num
8992
-** 0x0002 stop = $num
8993
-** 0x0004 step = $num
8994
-** 0x0008 output is in descending order
8995
-** 0x0010 output is in ascending order
8996
-** 0x0020 LIMIT $num
8997
-** 0x0040 OFFSET $num
8998
-** 0x0080 value = $num
8999
-** 0x0100 value >= $num
9000
-** 0x0200 value > $num
9001
-** 0x1000 value <= $num
9002
-** 0x2000 value < $num
9003
-**
9004
-** Only one of 0x0100 or 0x0200 will be returned. Similarly, only
9005
-** one of 0x1000 or 0x2000 will be returned. If the 0x0080 is set, then
9006
-** none of the 0xff00 bits will be set.
9007
-**
9008
-** The order of parameters passed to xFilter is as follows:
9009
-**
9010
-** * The argument to start= if bit 0x0001 is in the idxNum mask
9011
-** * The argument to stop= if bit 0x0002 is in the idxNum mask
9012
-** * The argument to step= if bit 0x0004 is in the idxNum mask
9013
-** * The argument to LIMIT if bit 0x0020 is in the idxNum mask
9014
-** * The argument to OFFSET if bit 0x0040 is in the idxNum mask
9015
-** * The argument to value=, or value>= or value> if any of
9016
-** bits 0x0380 are in the idxNum mask
9017
-** * The argument to value<= or value< if either of bits 0x3000
9018
-** are in the mask
9019
-**
9020
-*/
9021
-static int seriesBestIndex(
9022
- sqlite3_vtab *pVTab,
9023
- sqlite3_index_info *pIdxInfo
9024
-){
9025
- int i, j; /* Loop over constraints */
9026
- int idxNum = 0; /* The query plan bitmask */
9027
-#ifndef ZERO_ARGUMENT_GENERATE_SERIES
9028
- int bStartSeen = 0; /* EQ constraint seen on the START column */
9029
-#endif
9030
- int unusableMask = 0; /* Mask of unusable constraints */
9031
- int nArg = 0; /* Number of arguments that seriesFilter() expects */
9032
- int aIdx[7]; /* Constraints on start, stop, step, LIMIT, OFFSET,
9033
- ** and value. aIdx[5] covers value=, value>=, and
9034
- ** value>, aIdx[6] covers value<= and value< */
9035
- const struct sqlite3_index_constraint *pConstraint;
9036
-
9037
- /* This implementation assumes that the start, stop, and step columns
9038
- ** are the last three columns in the virtual table. */
9039
- assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
9040
- assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
9041
-
9042
- aIdx[0] = aIdx[1] = aIdx[2] = aIdx[3] = aIdx[4] = aIdx[5] = aIdx[6] = -1;
9043
- pConstraint = pIdxInfo->aConstraint;
9044
- for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
9045
- int iCol; /* 0 for start, 1 for stop, 2 for step */
9046
- int iMask; /* bitmask for those column */
9047
- int op = pConstraint->op;
9048
- if( op>=SQLITE_INDEX_CONSTRAINT_LIMIT
9049
- && op<=SQLITE_INDEX_CONSTRAINT_OFFSET
9050
- ){
9051
- if( pConstraint->usable==0 ){
9052
- /* do nothing */
9053
- }else if( op==SQLITE_INDEX_CONSTRAINT_LIMIT ){
9054
- aIdx[3] = i;
9055
- idxNum |= 0x20;
9056
- }else{
9057
- assert( op==SQLITE_INDEX_CONSTRAINT_OFFSET );
9058
- aIdx[4] = i;
9059
- idxNum |= 0x40;
9060
- }
9061
- continue;
9062
- }
9063
- if( pConstraint->iColumn<SERIES_COLUMN_START ){
9064
- if( (pConstraint->iColumn==SERIES_COLUMN_VALUE ||
9065
- pConstraint->iColumn==SERIES_COLUMN_ROWID)
9066
- && pConstraint->usable
9067
- ){
9068
- switch( op ){
9069
- case SQLITE_INDEX_CONSTRAINT_EQ:
9070
- case SQLITE_INDEX_CONSTRAINT_IS: {
9071
- idxNum |= 0x0080;
9072
- idxNum &= ~0x3300;
9073
- aIdx[5] = i;
9074
- aIdx[6] = -1;
9075
-#ifndef ZERO_ARGUMENT_GENERATE_SERIES
9076
- bStartSeen = 1;
9077
-#endif
9078
- break;
9079
- }
9080
- case SQLITE_INDEX_CONSTRAINT_GE: {
9081
- if( idxNum & 0x0080 ) break;
9082
- idxNum |= 0x0100;
9083
- idxNum &= ~0x0200;
9084
- aIdx[5] = i;
9085
-#ifndef ZERO_ARGUMENT_GENERATE_SERIES
9086
- bStartSeen = 1;
9087
-#endif
9088
- break;
9089
- }
9090
- case SQLITE_INDEX_CONSTRAINT_GT: {
9091
- if( idxNum & 0x0080 ) break;
9092
- idxNum |= 0x0200;
9093
- idxNum &= ~0x0100;
9094
- aIdx[5] = i;
9095
-#ifndef ZERO_ARGUMENT_GENERATE_SERIES
9096
- bStartSeen = 1;
9097
-#endif
9098
- break;
9099
- }
9100
- case SQLITE_INDEX_CONSTRAINT_LE: {
9101
- if( idxNum & 0x0080 ) break;
9102
- idxNum |= 0x1000;
9103
- idxNum &= ~0x2000;
9104
- aIdx[6] = i;
9105
- break;
9106
- }
9107
- case SQLITE_INDEX_CONSTRAINT_LT: {
9108
- if( idxNum & 0x0080 ) break;
9109
- idxNum |= 0x2000;
9110
- idxNum &= ~0x1000;
9111
- aIdx[6] = i;
9112
- break;
9113
- }
9114
- }
9115
- }
9116
- continue;
9117
- }
9118
- iCol = pConstraint->iColumn - SERIES_COLUMN_START;
9119
- assert( iCol>=0 && iCol<=2 );
9120
- iMask = 1 << iCol;
9121
-#ifndef ZERO_ARGUMENT_GENERATE_SERIES
9122
- if( iCol==0 && op==SQLITE_INDEX_CONSTRAINT_EQ ){
9123
- bStartSeen = 1;
9124
- }
9125
-#endif
9126
- if( pConstraint->usable==0 ){
9127
- unusableMask |= iMask;
9128
- continue;
9129
- }else if( op==SQLITE_INDEX_CONSTRAINT_EQ ){
9130
- idxNum |= iMask;
9131
- aIdx[iCol] = i;
9132
- }
9133
- }
9134
- if( aIdx[3]==0 ){
9135
- /* Ignore OFFSET if LIMIT is omitted */
9136
- idxNum &= ~0x60;
9137
- aIdx[4] = 0;
9138
- }
9139
- for(i=0; i<7; i++){
9140
- if( (j = aIdx[i])>=0 ){
9141
- pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
9142
- pIdxInfo->aConstraintUsage[j].omit =
9143
- !SQLITE_SERIES_CONSTRAINT_VERIFY || i>=3;
9144
- }
9145
- }
9146
- /* The current generate_column() implementation requires at least one
9147
- ** argument (the START value). Legacy versions assumed START=0 if the
9148
- ** first argument was omitted. Compile with -DZERO_ARGUMENT_GENERATE_SERIES
9149
- ** to obtain the legacy behavior */
9150
-#ifndef ZERO_ARGUMENT_GENERATE_SERIES
9151
- if( !bStartSeen ){
9152
- sqlite3_free(pVTab->zErrMsg);
9153
- pVTab->zErrMsg = sqlite3_mprintf(
9154
- "first argument to \"generate_series()\" missing or unusable");
9155
- return SQLITE_ERROR;
9156
- }
9157
-#endif
9158
- if( (unusableMask & ~idxNum)!=0 ){
9159
- /* The start, stop, and step columns are inputs. Therefore if there
9160
- ** are unusable constraints on any of start, stop, or step then
9161
- ** this plan is unusable */
9162
- return SQLITE_CONSTRAINT;
9163
- }
9164
- if( (idxNum & 0x03)==0x03 ){
9165
- /* Both start= and stop= boundaries are available. This is the
9166
- ** the preferred case */
9167
- pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
9168
- pIdxInfo->estimatedRows = 1000;
9169
- if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
9170
- if( pIdxInfo->aOrderBy[0].desc ){
9171
- idxNum |= 0x08;
9172
- }else{
9173
- idxNum |= 0x10;
9174
- }
9175
- pIdxInfo->orderByConsumed = 1;
9176
- }
9177
- }else if( (idxNum & 0x21)==0x21 ){
9178
- /* We have start= and LIMIT */
9179
- pIdxInfo->estimatedRows = 2500;
9180
- }else{
9181
- /* If either boundary is missing, we have to generate a huge span
9182
- ** of numbers. Make this case very expensive so that the query
9183
- ** planner will work hard to avoid it. */
9184
- pIdxInfo->estimatedRows = 2147483647;
9185
- }
9186
- pIdxInfo->idxNum = idxNum;
9187
-#ifdef SQLITE_INDEX_SCAN_HEX
9188
- pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_HEX;
9189
-#endif
9190
- return SQLITE_OK;
9191
-}
9192
-
9193
-/*
9194
-** This following structure defines all the methods for the
9195
-** generate_series virtual table.
9196
-*/
9197
-static sqlite3_module seriesModule = {
9198
- 0, /* iVersion */
9199
- 0, /* xCreate */
9200
- seriesConnect, /* xConnect */
9201
- seriesBestIndex, /* xBestIndex */
9202
- seriesDisconnect, /* xDisconnect */
9203
- 0, /* xDestroy */
9204
- seriesOpen, /* xOpen - open a cursor */
9205
- seriesClose, /* xClose - close a cursor */
9206
- seriesFilter, /* xFilter - configure scan constraints */
9207
- seriesNext, /* xNext - advance a cursor */
9208
- seriesEof, /* xEof - check for end of scan */
9209
- seriesColumn, /* xColumn - read data */
9210
- seriesRowid, /* xRowid - read data */
9211
- 0, /* xUpdate */
9212
- 0, /* xBegin */
9213
- 0, /* xSync */
9214
- 0, /* xCommit */
9215
- 0, /* xRollback */
9216
- 0, /* xFindMethod */
9217
- 0, /* xRename */
9218
- 0, /* xSavepoint */
9219
- 0, /* xRelease */
9220
- 0, /* xRollbackTo */
9221
- 0, /* xShadowName */
9222
- 0 /* xIntegrity */
9223
-};
9224
-
9225
-#endif /* SQLITE_OMIT_VIRTUALTABLE */
9226
-
9227
-#ifdef _WIN32
9228
-
9229
-#endif
9230
-int sqlite3_series_init(
9231
- sqlite3 *db,
9232
- char **pzErrMsg,
9233
- const sqlite3_api_routines *pApi
9234
-){
9235
- int rc = SQLITE_OK;
9236
- SQLITE_EXTENSION_INIT2(pApi);
9237
-#ifndef SQLITE_OMIT_VIRTUALTABLE
9238
- if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
9239
- *pzErrMsg = sqlite3_mprintf(
9240
- "generate_series() requires SQLite 3.8.12 or later");
9241
- return SQLITE_ERROR;
9242
- }
9243
- rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
9244
-#endif
9245
- return rc;
9246
-}
9247
-
9248
-/************************* End ext/misc/series.c ********************/
92498330
/************************* Begin ext/misc/regexp.c ******************/
92508331
/*
92518332
** 2012-11-13
92528333
**
92538334
** The author disclaims copyright to this source code. In place of
@@ -9938,15 +9019,11 @@
99389019
if( re_resize(pRe, 30) ){
99399020
zErr = pRe->zErr;
99409021
re_free(pRe);
99419022
return zErr;
99429023
}
9943
- if( zIn[0]=='^' ){
9944
- zIn++;
9945
- }else{
9946
- re_append(pRe, RE_OP_ANYSTAR, 0);
9947
- }
9024
+ re_append(pRe, RE_OP_ANYSTAR, 0);
99489025
pRe->sIn.z = (unsigned char*)zIn;
99499026
pRe->sIn.i = 0;
99509027
pRe->sIn.mx = (int)strlen(zIn);
99519028
zErr = re_subcompile_re(pRe);
99529029
if( zErr ){
@@ -9958,10 +9035,23 @@
99589035
*ppRe = pRe;
99599036
}else{
99609037
re_free(pRe);
99619038
return "unrecognized character";
99629039
}
9040
+
9041
+ /* If the regex begins with "^" and has no "|" at the top level, then
9042
+ ** the whole regex is anchored at the start of the input and the
9043
+ ** initial ".*" is not needed. Convert it into a no-op so that
9044
+ ** re_match() can stop as soon as the start of the input fails to
9045
+ ** match. A "|" at the top level would have caused a FORK to be
9046
+ ** inserted at aOp[1], so aOp[1]==RE_OP_ATSTART is sufficient. Do
9047
+ ** not remove the initial "^" itself, as there might be jumps back
9048
+ ** to it, as in "^+". */
9049
+ if( pRe->aOp[1]==RE_OP_ATSTART ){
9050
+ pRe->aOp[0] = RE_OP_GOTO;
9051
+ pRe->aArg[0] = 1;
9052
+ }
99639053
99649054
/* The following is a performance optimization. If the regex begins with
99659055
** ".*" (if the input regex lacks an initial "^") and afterwards there are
99669056
** one or more matching characters, enter those matching characters into
99679057
** zInit[]. The re_match() routine can then search ahead in the input
@@ -10177,10 +9267,1133 @@
101779267
}
101789268
return rc;
101799269
}
101809270
101819271
/************************* End ext/misc/regexp.c ********************/
9272
+/************************* Begin ext/misc/series.c ******************/
9273
+/*
9274
+** 2015-08-18, 2023-04-28
9275
+**
9276
+** The author disclaims copyright to this source code. In place of
9277
+** a legal notice, here is a blessing:
9278
+**
9279
+** May you do good and not evil.
9280
+** May you find forgiveness for yourself and forgive others.
9281
+** May you share freely, never taking more than you give.
9282
+**
9283
+*************************************************************************
9284
+**
9285
+** This file demonstrates how to create a table-valued-function using
9286
+** a virtual table. This demo implements the generate_series() function
9287
+** which gives the same results as the eponymous function in PostgreSQL,
9288
+** within the limitation that its arguments are signed 64-bit integers.
9289
+**
9290
+** Considering its equivalents to generate_series(start,stop,step): A
9291
+** value V[n] sequence is produced for integer n ascending from 0 where
9292
+** ( V[n] == start + n * step && sgn(V[n] - stop) * sgn(step) >= 0 )
9293
+** for each produced value (independent of production time ordering.)
9294
+**
9295
+** All parameters must be either integer or convertable to integer.
9296
+** The start parameter is required.
9297
+** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
9298
+** The step parameter defaults to 1 and 0 is treated as 1.
9299
+**
9300
+** Examples:
9301
+**
9302
+** SELECT * FROM generate_series(0,100,5);
9303
+**
9304
+** The query above returns integers from 0 through 100 counting by steps
9305
+** of 5. In other words, 0, 5, 10, 15, ..., 90, 95, 100. There are a total
9306
+** of 21 rows.
9307
+**
9308
+** SELECT * FROM generate_series(0,100);
9309
+**
9310
+** Integers from 0 through 100 with a step size of 1. 101 rows.
9311
+**
9312
+** SELECT * FROM generate_series(20) LIMIT 10;
9313
+**
9314
+** Integers 20 through 29. 10 rows.
9315
+**
9316
+** SELECT * FROM generate_series(0,-100,-5);
9317
+**
9318
+** Integers 0 -5 -10 ... -100. 21 rows.
9319
+**
9320
+** SELECT * FROM generate_series(0,-1);
9321
+**
9322
+** Empty sequence.
9323
+**
9324
+** HOW IT WORKS
9325
+**
9326
+** The generate_series "function" is really a virtual table with the
9327
+** following schema:
9328
+**
9329
+** CREATE TABLE generate_series(
9330
+** value,
9331
+** start HIDDEN,
9332
+** stop HIDDEN,
9333
+** step HIDDEN
9334
+** );
9335
+**
9336
+** The virtual table also has a rowid which is an alias for the value.
9337
+**
9338
+** Function arguments in queries against this virtual table are translated
9339
+** into equality constraints against successive hidden columns. In other
9340
+** words, the following pairs of queries are equivalent to each other:
9341
+**
9342
+** SELECT * FROM generate_series(0,100,5);
9343
+** SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
9344
+**
9345
+** SELECT * FROM generate_series(0,100);
9346
+** SELECT * FROM generate_series WHERE start=0 AND stop=100;
9347
+**
9348
+** SELECT * FROM generate_series(20) LIMIT 10;
9349
+** SELECT * FROM generate_series WHERE start=20 LIMIT 10;
9350
+**
9351
+** The generate_series virtual table implementation leaves the xCreate method
9352
+** set to NULL. This means that it is not possible to do a CREATE VIRTUAL
9353
+** TABLE command with "generate_series" as the USING argument. Instead, there
9354
+** is a single generate_series virtual table that is always available without
9355
+** having to be created first.
9356
+**
9357
+** The xBestIndex method looks for equality constraints against the hidden
9358
+** start, stop, and step columns, and if present, it uses those constraints
9359
+** to bound the sequence of generated values. If the equality constraints
9360
+** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
9361
+** xBestIndex returns a small cost when both start and stop are available,
9362
+** and a very large cost if either start or stop are unavailable. This
9363
+** encourages the query planner to order joins such that the bounds of the
9364
+** series are well-defined.
9365
+**
9366
+** Update on 2024-08-22:
9367
+** xBestIndex now also looks for equality and inequality constraints against
9368
+** the value column and uses those constraints as additional bounds against
9369
+** the sequence range. Thus, a query like this:
9370
+**
9371
+** SELECT value FROM generate_series($SA,$EA)
9372
+** WHERE value BETWEEN $SB AND $EB;
9373
+**
9374
+** Is logically the same as:
9375
+**
9376
+** SELECT value FROM generate_series(max($SA,$SB),min($EA,$EB));
9377
+**
9378
+** Constraints on the value column can server as substitutes for constraints
9379
+** on the hidden start and stop columns. So, the following two queries
9380
+** are equivalent:
9381
+**
9382
+** SELECT value FROM generate_series($S,$E);
9383
+** SELECT value FROM generate_series WHERE value BETWEEN $S and $E;
9384
+**
9385
+*/
9386
+/* #include "sqlite3ext.h" */
9387
+SQLITE_EXTENSION_INIT1
9388
+#include <assert.h>
9389
+#include <string.h>
9390
+#include <limits.h>
9391
+#include <math.h>
9392
+
9393
+#ifndef SQLITE_OMIT_VIRTUALTABLE
9394
+
9395
+/* series_cursor is a subclass of sqlite3_vtab_cursor which will
9396
+** serve as the underlying representation of a cursor that scans
9397
+** over rows of the result.
9398
+**
9399
+** iOBase, iOTerm, and iOStep are the original values of the
9400
+** start=, stop=, and step= constraints on the query. These are
9401
+** the values reported by the start, stop, and step columns of the
9402
+** virtual table.
9403
+**
9404
+** iBase, iTerm, iStep, and bDescp are the actual values used to generate
9405
+** the sequence. These might be different from the iOxxxx values.
9406
+** For example in
9407
+**
9408
+** SELECT value FROM generate_series(1,11,2)
9409
+** WHERE value BETWEEN 4 AND 8;
9410
+**
9411
+** The iOBase is 1, but the iBase is 5. iOTerm is 11 but iTerm is 7.
9412
+** Another example:
9413
+**
9414
+** SELECT value FROM generate_series(1,15,3) ORDER BY value DESC;
9415
+**
9416
+** The cursor initialization for the above query is:
9417
+**
9418
+** iOBase = 1 iBase = 13
9419
+** iOTerm = 15 iTerm = 1
9420
+** iOStep = 3 iStep = 3 bDesc = 1
9421
+**
9422
+** The actual step size is unsigned so that can have a value of
9423
+** +9223372036854775808 which is needed for querys like this:
9424
+**
9425
+** SELECT value
9426
+** FROM generate_series(9223372036854775807,
9427
+** -9223372036854775808,
9428
+** -9223372036854775808)
9429
+** ORDER BY value ASC;
9430
+**
9431
+** The setup for the previous query will be:
9432
+**
9433
+** iOBase = 9223372036854775807 iBase = -1
9434
+** iOTerm = -9223372036854775808 iTerm = 9223372036854775807
9435
+** iOStep = -9223372036854775808 iStep = 9223372036854775808 bDesc = 0
9436
+*/
9437
+/* typedef unsigned char u8; */
9438
+typedef struct series_cursor series_cursor;
9439
+struct series_cursor {
9440
+ sqlite3_vtab_cursor base; /* Base class - must be first */
9441
+ sqlite3_int64 iOBase; /* Original starting value ("start") */
9442
+ sqlite3_int64 iOTerm; /* Original terminal value ("stop") */
9443
+ sqlite3_int64 iOStep; /* Original step value */
9444
+ sqlite3_int64 iBase; /* Starting value to actually use */
9445
+ sqlite3_int64 iTerm; /* Terminal value to actually use */
9446
+ sqlite3_uint64 iStep; /* The step size */
9447
+ sqlite3_int64 iValue; /* Current value */
9448
+ u8 bDesc; /* iStep is really negative */
9449
+ u8 bDone; /* True if stepped past last element */
9450
+ u8 bLimit; /* There exists a limit clause */
9451
+};
9452
+
9453
+/*
9454
+** Computed the difference between two 64-bit signed integers using a
9455
+** convoluted computation designed to work around the silly restriction
9456
+** against signed integer overflow in C.
9457
+*/
9458
+static sqlite3_uint64 span64(sqlite3_int64 a, sqlite3_int64 b){
9459
+ assert( a>=b );
9460
+ return (*(sqlite3_uint64*)&a) - (*(sqlite3_uint64*)&b);
9461
+}
9462
+
9463
+/*
9464
+** Add or substract an unsigned 64-bit integer from a signed 64-bit integer
9465
+** and return the new signed 64-bit integer.
9466
+*/
9467
+static sqlite3_int64 add64(sqlite3_int64 a, sqlite3_uint64 b){
9468
+ sqlite3_uint64 x = *(sqlite3_uint64*)&a;
9469
+ x += b;
9470
+ return *(sqlite3_int64*)&x;
9471
+}
9472
+static sqlite3_int64 sub64(sqlite3_int64 a, sqlite3_uint64 b){
9473
+ sqlite3_uint64 x = *(sqlite3_uint64*)&a;
9474
+ x -= b;
9475
+ return *(sqlite3_int64*)&x;
9476
+}
9477
+
9478
+/*
9479
+** The seriesConnect() method is invoked to create a new
9480
+** series_vtab that describes the generate_series virtual table.
9481
+**
9482
+** Think of this routine as the constructor for series_vtab objects.
9483
+**
9484
+** All this routine needs to do is:
9485
+**
9486
+** (1) Allocate the series_vtab object and initialize all fields.
9487
+**
9488
+** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
9489
+** result set of queries against generate_series will look like.
9490
+*/
9491
+static int seriesConnect(
9492
+ sqlite3 *db,
9493
+ void *pUnused,
9494
+ int argcUnused, const char *const*argvUnused,
9495
+ sqlite3_vtab **ppVtab,
9496
+ char **pzErrUnused
9497
+){
9498
+ sqlite3_vtab *pNew;
9499
+ int rc;
9500
+
9501
+/* Column numbers */
9502
+#define SERIES_COLUMN_ROWID (-1)
9503
+#define SERIES_COLUMN_VALUE 0
9504
+#define SERIES_COLUMN_START 1
9505
+#define SERIES_COLUMN_STOP 2
9506
+#define SERIES_COLUMN_STEP 3
9507
+
9508
+ (void)pUnused;
9509
+ (void)argcUnused;
9510
+ (void)argvUnused;
9511
+ (void)pzErrUnused;
9512
+ rc = sqlite3_declare_vtab(db,
9513
+ "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
9514
+ if( rc==SQLITE_OK ){
9515
+ pNew = *ppVtab = sqlite3_malloc64( sizeof(*pNew) );
9516
+ if( pNew==0 ) return SQLITE_NOMEM;
9517
+ memset(pNew, 0, sizeof(*pNew));
9518
+ sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
9519
+ }
9520
+ return rc;
9521
+}
9522
+
9523
+/*
9524
+** This method is the destructor for series_cursor objects.
9525
+*/
9526
+static int seriesDisconnect(sqlite3_vtab *pVtab){
9527
+ sqlite3_free(pVtab);
9528
+ return SQLITE_OK;
9529
+}
9530
+
9531
+/*
9532
+** Constructor for a new series_cursor object.
9533
+*/
9534
+static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
9535
+ series_cursor *pCur;
9536
+ (void)pUnused;
9537
+ pCur = sqlite3_malloc64( sizeof(*pCur) );
9538
+ if( pCur==0 ) return SQLITE_NOMEM;
9539
+ memset(pCur, 0, sizeof(*pCur));
9540
+ *ppCursor = &pCur->base;
9541
+ return SQLITE_OK;
9542
+}
9543
+
9544
+/*
9545
+** Destructor for a series_cursor.
9546
+*/
9547
+static int seriesClose(sqlite3_vtab_cursor *cur){
9548
+ sqlite3_free(cur);
9549
+ return SQLITE_OK;
9550
+}
9551
+
9552
+
9553
+/*
9554
+** Advance a series_cursor to its next row of output.
9555
+*/
9556
+static int seriesNext(sqlite3_vtab_cursor *cur){
9557
+ series_cursor *pCur = (series_cursor*)cur;
9558
+ if( pCur->iValue==pCur->iTerm ){
9559
+ pCur->bDone = 1;
9560
+ }else if( pCur->bDesc ){
9561
+ pCur->iValue = sub64(pCur->iValue, pCur->iStep);
9562
+ assert( pCur->iValue>=pCur->iTerm || pCur->bLimit );
9563
+ }else{
9564
+ pCur->iValue = add64(pCur->iValue, pCur->iStep);
9565
+ assert( pCur->iValue<=pCur->iTerm || pCur->bLimit );
9566
+ }
9567
+ return SQLITE_OK;
9568
+}
9569
+
9570
+/*
9571
+** Return values of columns for the row at which the series_cursor
9572
+** is currently pointing.
9573
+*/
9574
+static int seriesColumn(
9575
+ sqlite3_vtab_cursor *cur, /* The cursor */
9576
+ sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
9577
+ int i /* Which column to return */
9578
+){
9579
+ series_cursor *pCur = (series_cursor*)cur;
9580
+ sqlite3_int64 x = 0;
9581
+ switch( i ){
9582
+ case SERIES_COLUMN_START: x = pCur->iOBase; break;
9583
+ case SERIES_COLUMN_STOP: x = pCur->iOTerm; break;
9584
+ case SERIES_COLUMN_STEP: x = pCur->iOStep; break;
9585
+ default: x = pCur->iValue; break;
9586
+ }
9587
+ sqlite3_result_int64(ctx, x);
9588
+ return SQLITE_OK;
9589
+}
9590
+
9591
+#ifndef LARGEST_UINT64
9592
+#define LARGEST_INT64 ((sqlite3_int64)0x7fffffffffffffffLL)
9593
+#define LARGEST_UINT64 ((sqlite3_uint64)0xffffffffffffffffULL)
9594
+#define SMALLEST_INT64 ((sqlite3_int64)0x8000000000000000LL)
9595
+#endif
9596
+
9597
+/*
9598
+** The rowid is the same as the value.
9599
+*/
9600
+static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
9601
+ series_cursor *pCur = (series_cursor*)cur;
9602
+ *pRowid = pCur->iValue;
9603
+ return SQLITE_OK;
9604
+}
9605
+
9606
+/*
9607
+** Return TRUE if the cursor has been moved off of the last
9608
+** row of output.
9609
+*/
9610
+static int seriesEof(sqlite3_vtab_cursor *cur){
9611
+ series_cursor *pCur = (series_cursor*)cur;
9612
+ return pCur->bDone;
9613
+}
9614
+
9615
+/* True to cause run-time checking of the start=, stop=, and/or step=
9616
+** parameters. The only reason to do this is for testing the
9617
+** constraint checking logic for virtual tables in the SQLite core.
9618
+*/
9619
+#ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
9620
+# define SQLITE_SERIES_CONSTRAINT_VERIFY 0
9621
+#endif
9622
+
9623
+/*
9624
+** Return the number of steps between pCur->iBase and pCur->iTerm if
9625
+** the step width is pCur->iStep.
9626
+*/
9627
+static sqlite3_uint64 seriesSteps(series_cursor *pCur){
9628
+ if( pCur->bDesc ){
9629
+ assert( pCur->iBase >= pCur->iTerm );
9630
+ return span64(pCur->iBase, pCur->iTerm)/pCur->iStep;
9631
+ }else{
9632
+ assert( pCur->iBase <= pCur->iTerm );
9633
+ return span64(pCur->iTerm, pCur->iBase)/pCur->iStep;
9634
+ }
9635
+}
9636
+
9637
+#if defined(SQLITE_ENABLE_MATH_FUNCTIONS) || defined(_WIN32)
9638
+/*
9639
+** Case 1 (the most common case):
9640
+** The standard math library is available so use ceil() and floor() from there.
9641
+*/
9642
+static double seriesCeil(double r){ return ceil(r); }
9643
+static double seriesFloor(double r){ return floor(r); }
9644
+#elif defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
9645
+/*
9646
+** Case 2 (2nd most common): Use GCC/Clang builtins
9647
+*/
9648
+static double seriesCeil(double r){ return __builtin_ceil(r); }
9649
+static double seriesFloor(double r){ return __builtin_floor(r); }
9650
+#else
9651
+/*
9652
+** Case 3 (rarely happens): Use home-grown ceil() and floor() routines.
9653
+*/
9654
+static double seriesCeil(double r){
9655
+ sqlite3_int64 x;
9656
+ if( r!=r ) return r;
9657
+ if( r<=(-4503599627370496.0) ) return r;
9658
+ if( r>=(+4503599627370496.0) ) return r;
9659
+ x = (sqlite3_int64)r;
9660
+ if( r==(double)x ) return r;
9661
+ if( r>(double)x ) x++;
9662
+ return (double)x;
9663
+}
9664
+static double seriesFloor(double r){
9665
+ sqlite3_int64 x;
9666
+ if( r!=r ) return r;
9667
+ if( r<=(-4503599627370496.0) ) return r;
9668
+ if( r>=(+4503599627370496.0) ) return r;
9669
+ x = (sqlite3_int64)r;
9670
+ if( r==(double)x ) return r;
9671
+ if( r<(double)x ) x--;
9672
+ return (double)x;
9673
+}
9674
+#endif
9675
+
9676
+/* Convert a floating point value to its closest integer. Do so in
9677
+** a way that avoids 'outside the range of representable values' warnings
9678
+** from UBSAN.
9679
+*/
9680
+static sqlite3_int64 seriesRealToI64(double r){
9681
+ if( r<-9223372036854774784.0 ) return SMALLEST_INT64;
9682
+ if( r>+9223372036854774784.0 ) return LARGEST_INT64;
9683
+ return (sqlite3_int64)r;
9684
+}
9685
+
9686
+/* Return true if the type of the value is TEXT or BLOB.
9687
+*/
9688
+static int seriesIsTextOrBlob(sqlite3_value *pVal){
9689
+ int eType = sqlite3_value_type(pVal);
9690
+ return eType==SQLITE_TEXT || eType==SQLITE_BLOB;
9691
+}
9692
+
9693
+/*
9694
+** This method is called to "rewind" the series_cursor object back
9695
+** to the first row of output. This method is always called at least
9696
+** once prior to any call to seriesColumn() or seriesRowid() or
9697
+** seriesEof().
9698
+**
9699
+** The query plan selected by seriesBestIndex is passed in the idxNum
9700
+** parameter. (idxStr is not used in this implementation.) idxNum
9701
+** is a bitmask showing which constraints are available:
9702
+**
9703
+** 0x0001: start=VALUE
9704
+** 0x0002: stop=VALUE
9705
+** 0x0004: step=VALUE
9706
+** 0x0008: descending order
9707
+** 0x0010: ascending order
9708
+** 0x0020: LIMIT VALUE
9709
+** 0x0040: OFFSET VALUE
9710
+** 0x0080: value=VALUE
9711
+** 0x0100: value>=VALUE
9712
+** 0x0200: value>VALUE
9713
+** 0x1000: value<=VALUE
9714
+** 0x2000: value<VALUE
9715
+**
9716
+** This routine should initialize the cursor and position it so that it
9717
+** is pointing at the first row, or pointing off the end of the table
9718
+** (so that seriesEof() will return true) if the table is empty.
9719
+*/
9720
+static int seriesFilter(
9721
+ sqlite3_vtab_cursor *pVtabCursor,
9722
+ int idxNum, const char *idxStrUnused,
9723
+ int argc, sqlite3_value **argv
9724
+){
9725
+ series_cursor *pCur = (series_cursor *)pVtabCursor;
9726
+ int iArg = 0; /* Arguments used so far */
9727
+ int i; /* Loop counter */
9728
+ sqlite3_int64 iMin = SMALLEST_INT64; /* Smallest allowed output value */
9729
+ sqlite3_int64 iMax = LARGEST_INT64; /* Largest allowed output value */
9730
+ sqlite3_int64 iLimit = 0; /* if >0, the value of the LIMIT */
9731
+ sqlite3_int64 iOffset = 0; /* if >0, the value of the OFFSET */
9732
+
9733
+ (void)idxStrUnused;
9734
+
9735
+ /* If any constraints have a NULL value, then return no rows.
9736
+ ** See ticket https://sqlite.org/src/info/fac496b61722daf2
9737
+ */
9738
+ for(i=0; i<argc; i++){
9739
+ if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
9740
+ goto series_no_rows;
9741
+ }
9742
+ }
9743
+
9744
+ /* Capture the three HIDDEN parameters to the virtual table and insert
9745
+ ** default values for any parameters that are omitted.
9746
+ */
9747
+ if( idxNum & 0x01 ){
9748
+ pCur->iOBase = sqlite3_value_int64(argv[iArg++]);
9749
+ }else{
9750
+ pCur->iOBase = 0;
9751
+ }
9752
+ if( idxNum & 0x02 ){
9753
+ pCur->iOTerm = sqlite3_value_int64(argv[iArg++]);
9754
+ }else{
9755
+ pCur->iOTerm = 0xffffffff;
9756
+ }
9757
+ if( idxNum & 0x04 ){
9758
+ pCur->iOStep = sqlite3_value_int64(argv[iArg++]);
9759
+ if( pCur->iOStep==0 ) pCur->iOStep = 1;
9760
+ }else{
9761
+ pCur->iOStep = 1;
9762
+ }
9763
+
9764
+ /* If there are constraints on the value column but there are
9765
+ ** no constraints on the start, stop, and step columns, then
9766
+ ** initialize the default range to be the entire range of 64-bit signed
9767
+ ** integers. This range will contracted by the value column constraints
9768
+ ** further below.
9769
+ */
9770
+ if( (idxNum & 0x05)==0 && (idxNum & 0x0380)!=0 ){
9771
+ pCur->iOBase = SMALLEST_INT64;
9772
+ }
9773
+ if( (idxNum & 0x06)==0 && (idxNum & 0x3080)!=0 ){
9774
+ pCur->iOTerm = LARGEST_INT64;
9775
+ }
9776
+ pCur->iBase = pCur->iOBase;
9777
+ pCur->iTerm = pCur->iOTerm;
9778
+ if( pCur->iOStep>0 ){
9779
+ pCur->iStep = pCur->iOStep;
9780
+ }else if( pCur->iOStep>SMALLEST_INT64 ){
9781
+ pCur->iStep = -pCur->iOStep;
9782
+ }else{
9783
+ pCur->iStep = LARGEST_INT64;
9784
+ pCur->iStep++;
9785
+ }
9786
+ pCur->bDesc = pCur->iOStep<0;
9787
+ if( pCur->bDesc==0 && pCur->iBase>pCur->iTerm ){
9788
+ goto series_no_rows;
9789
+ }
9790
+ if( pCur->bDesc!=0 && pCur->iBase<pCur->iTerm ){
9791
+ goto series_no_rows;
9792
+ }
9793
+
9794
+ /* Extract the LIMIT and OFFSET values, but do not apply them yet.
9795
+ ** The range must first be constrained by the limits on value.
9796
+ */
9797
+ if( idxNum & 0x20 ){
9798
+ iLimit = sqlite3_value_int64(argv[iArg++]);
9799
+ if( idxNum & 0x40 ){
9800
+ iOffset = sqlite3_value_int64(argv[iArg++]);
9801
+ }
9802
+ if( iLimit>0 ) pCur->bLimit = 1;
9803
+ }
9804
+
9805
+ /* Narrow the range of iMin and iMax (the minimum and maximum outputs)
9806
+ ** based on equality and inequality constraints on the "value" column.
9807
+ **
9808
+ ** The "value" column has no affinity, so a TEXT or BLOB operand X is
9809
+ ** not converted into a number. Every INTEGER is less than any TEXT
9810
+ ** or BLOB, so "value=X", "value>X" and "value>=X" are never true and
9811
+ ** "value<X" and "value<=X" are always true. The type must be checked
9812
+ ** before sqlite3_value_numeric_type(), which would convert a TEXT
9813
+ ** value such as '3' into a number.
9814
+ */
9815
+ if( idxNum & 0x3380 ){
9816
+ if( idxNum & 0x0080 ){ /* value=X */
9817
+ if( seriesIsTextOrBlob(argv[iArg]) ){
9818
+ goto series_no_rows;
9819
+ }else if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
9820
+ double r = sqlite3_value_double(argv[iArg++]);
9821
+ if( r==seriesCeil(r)
9822
+ && r>=(double)SMALLEST_INT64
9823
+ && r<=(double)LARGEST_INT64
9824
+ ){
9825
+ iMin = iMax = seriesRealToI64(r);
9826
+ }else{
9827
+ goto series_no_rows;
9828
+ }
9829
+ }else{
9830
+ iMin = iMax = sqlite3_value_int64(argv[iArg++]);
9831
+ }
9832
+ }else{
9833
+ if( idxNum & 0x0300 ){ /* value>X (0x200) or value>=X (0x100) */
9834
+ if( seriesIsTextOrBlob(argv[iArg]) ){
9835
+ goto series_no_rows;
9836
+ }else if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
9837
+ double r = sqlite3_value_double(argv[iArg++]);
9838
+ if( r<=(double)SMALLEST_INT64 ){
9839
+ iMin = SMALLEST_INT64;
9840
+ }else if( r>(double)LARGEST_INT64 ){
9841
+ goto series_no_rows;
9842
+ }else{
9843
+ iMin = seriesRealToI64(seriesCeil(r));
9844
+ if( (idxNum & 0x0200)!=0 && r==seriesCeil(r) ){
9845
+ if( iMin==LARGEST_INT64 ) goto series_no_rows;
9846
+ iMin++;
9847
+ }
9848
+ }
9849
+ }else{
9850
+ iMin = sqlite3_value_int64(argv[iArg++]);
9851
+ if( (idxNum & 0x0200)!=0 ){
9852
+ if( iMin==LARGEST_INT64 ){
9853
+ goto series_no_rows;
9854
+ }else{
9855
+ iMin++;
9856
+ }
9857
+ }
9858
+ }
9859
+ }
9860
+ if( idxNum & 0x3000 ){ /* value<X (0x2000) or value<=X (0x1000) */
9861
+ if( seriesIsTextOrBlob(argv[iArg]) ){
9862
+ iArg++; /* No upper bound */
9863
+ }else if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
9864
+ double r = sqlite3_value_double(argv[iArg++]);
9865
+ if( r>=(double)LARGEST_INT64 ){
9866
+ iMax = LARGEST_INT64;
9867
+ }else if( r<=(double)SMALLEST_INT64 ){
9868
+ goto series_no_rows;
9869
+ }else{
9870
+ iMax = seriesRealToI64(seriesFloor(r));
9871
+ if( (idxNum & 0x2000)!=0 && r==seriesFloor(r) ){
9872
+ if( iMax==SMALLEST_INT64 ) goto series_no_rows;
9873
+ iMax--;
9874
+ }
9875
+ }
9876
+ }else{
9877
+ iMax = sqlite3_value_int64(argv[iArg++]);
9878
+ if( idxNum & 0x2000 ){
9879
+ if( iMax==SMALLEST_INT64 ){
9880
+ goto series_no_rows;
9881
+ }else{
9882
+ iMax--;
9883
+ }
9884
+ }
9885
+ }
9886
+ }
9887
+ if( iMin>iMax ){
9888
+ goto series_no_rows;
9889
+ }
9890
+ }
9891
+
9892
+ /* Try to reduce the range of values to be generated based on
9893
+ ** constraints on the "value" column.
9894
+ */
9895
+ if( pCur->bDesc==0 ){
9896
+ if( pCur->iBase<iMin ){
9897
+ sqlite3_uint64 span = span64(iMin,pCur->iBase);
9898
+ pCur->iBase = add64(pCur->iBase, (span/pCur->iStep)*pCur->iStep);
9899
+ if( pCur->iBase<iMin ){
9900
+ if( pCur->iBase > sub64(LARGEST_INT64, pCur->iStep) ){
9901
+ goto series_no_rows;
9902
+ }
9903
+ pCur->iBase = add64(pCur->iBase, pCur->iStep);
9904
+ }
9905
+ }
9906
+ if( pCur->iTerm>iMax ){
9907
+ pCur->iTerm = iMax;
9908
+ }
9909
+ }else{
9910
+ if( pCur->iBase>iMax ){
9911
+ sqlite3_uint64 span = span64(pCur->iBase,iMax);
9912
+ pCur->iBase = sub64(pCur->iBase, (span/pCur->iStep)*pCur->iStep);
9913
+ if( pCur->iBase>iMax ){
9914
+ if( pCur->iBase < add64(SMALLEST_INT64, pCur->iStep) ){
9915
+ goto series_no_rows;
9916
+ }
9917
+ pCur->iBase = sub64(pCur->iBase, pCur->iStep);
9918
+ }
9919
+ }
9920
+ if( pCur->iTerm<iMin ){
9921
+ pCur->iTerm = iMin;
9922
+ }
9923
+ }
9924
+ }
9925
+
9926
+ /* Adjust iTerm so that it is exactly the last value of the series.
9927
+ */
9928
+ if( pCur->bDesc==0 ){
9929
+ if( pCur->iBase>pCur->iTerm ){
9930
+ goto series_no_rows;
9931
+ }
9932
+ pCur->iTerm = sub64(pCur->iTerm,
9933
+ span64(pCur->iTerm,pCur->iBase) % pCur->iStep);
9934
+ }else{
9935
+ if( pCur->iBase<pCur->iTerm ){
9936
+ goto series_no_rows;
9937
+ }
9938
+ pCur->iTerm = add64(pCur->iTerm,
9939
+ span64(pCur->iBase,pCur->iTerm) % pCur->iStep);
9940
+ }
9941
+
9942
+ /* Transform the series generator to output values in the requested
9943
+ ** order.
9944
+ */
9945
+ if( ((idxNum & 0x0008)!=0 && pCur->bDesc==0)
9946
+ || ((idxNum & 0x0010)!=0 && pCur->bDesc!=0)
9947
+ ){
9948
+ sqlite3_int64 tmp = pCur->iBase;
9949
+ pCur->iBase = pCur->iTerm;
9950
+ pCur->iTerm = tmp;
9951
+ pCur->bDesc = !pCur->bDesc;
9952
+ }
9953
+
9954
+ /* Apply LIMIT and OFFSET constraints, if any */
9955
+ assert( pCur->iStep!=0 );
9956
+ if( idxNum & 0x20 ){
9957
+ if( iOffset>0 ){
9958
+ if( seriesSteps(pCur) < (sqlite3_uint64)iOffset ){
9959
+ goto series_no_rows;
9960
+ }else if( pCur->bDesc ){
9961
+ pCur->iBase = sub64(pCur->iBase, pCur->iStep*iOffset);
9962
+ }else{
9963
+ pCur->iBase = add64(pCur->iBase, pCur->iStep*iOffset);
9964
+ }
9965
+ }
9966
+ if( iLimit>=0 && seriesSteps(pCur) > (sqlite3_uint64)iLimit ){
9967
+ pCur->iTerm = add64(pCur->iBase, (iLimit - 1)*pCur->iStep);
9968
+ }
9969
+ }
9970
+ pCur->iValue = pCur->iBase;
9971
+ pCur->bDone = 0;
9972
+ return SQLITE_OK;
9973
+
9974
+series_no_rows:
9975
+ pCur->iBase = 0;
9976
+ pCur->iTerm = 0;
9977
+ pCur->iStep = 1;
9978
+ pCur->bDesc = 0;
9979
+ pCur->bDone = 1;
9980
+ return SQLITE_OK;
9981
+}
9982
+
9983
+/*
9984
+** SQLite will invoke this method one or more times while planning a query
9985
+** that uses the generate_series virtual table. This routine needs to create
9986
+** a query plan for each invocation and compute an estimated cost for that
9987
+** plan.
9988
+**
9989
+** In this implementation idxNum is used to represent the
9990
+** query plan. idxStr is unused.
9991
+**
9992
+** The query plan is represented by bits in idxNum:
9993
+**
9994
+** 0x0001 start = $num
9995
+** 0x0002 stop = $num
9996
+** 0x0004 step = $num
9997
+** 0x0008 output is in descending order
9998
+** 0x0010 output is in ascending order
9999
+** 0x0020 LIMIT $num
10000
+** 0x0040 OFFSET $num
10001
+** 0x0080 value = $num
10002
+** 0x0100 value >= $num
10003
+** 0x0200 value > $num
10004
+** 0x1000 value <= $num
10005
+** 0x2000 value < $num
10006
+**
10007
+** Only one of 0x0100 or 0x0200 will be returned. Similarly, only
10008
+** one of 0x1000 or 0x2000 will be returned. If the 0x0080 is set, then
10009
+** none of the 0xff00 bits will be set.
10010
+**
10011
+** The order of parameters passed to xFilter is as follows:
10012
+**
10013
+** * The argument to start= if bit 0x0001 is in the idxNum mask
10014
+** * The argument to stop= if bit 0x0002 is in the idxNum mask
10015
+** * The argument to step= if bit 0x0004 is in the idxNum mask
10016
+** * The argument to LIMIT if bit 0x0020 is in the idxNum mask
10017
+** * The argument to OFFSET if bit 0x0040 is in the idxNum mask
10018
+** * The argument to value=, or value>= or value> if any of
10019
+** bits 0x0380 are in the idxNum mask
10020
+** * The argument to value<= or value< if either of bits 0x3000
10021
+** are in the mask
10022
+**
10023
+*/
10024
+static int seriesBestIndex(
10025
+ sqlite3_vtab *pVTab,
10026
+ sqlite3_index_info *pIdxInfo
10027
+){
10028
+ int i, j; /* Loop over constraints */
10029
+ int idxNum = 0; /* The query plan bitmask */
10030
+#ifndef ZERO_ARGUMENT_GENERATE_SERIES
10031
+ int bStartSeen = 0; /* EQ constraint seen on the START column */
10032
+#endif
10033
+ int unusableMask = 0; /* Mask of unusable constraints */
10034
+ int nArg = 0; /* Number of arguments that seriesFilter() expects */
10035
+ int aIdx[7]; /* Constraints on start, stop, step, LIMIT, OFFSET,
10036
+ ** and value. aIdx[5] covers value=, value>=, and
10037
+ ** value>, aIdx[6] covers value<= and value< */
10038
+ const struct sqlite3_index_constraint *pConstraint;
10039
+
10040
+ /* This implementation assumes that the start, stop, and step columns
10041
+ ** are the last three columns in the virtual table. */
10042
+ assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
10043
+ assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
10044
+
10045
+ aIdx[0] = aIdx[1] = aIdx[2] = aIdx[3] = aIdx[4] = aIdx[5] = aIdx[6] = -1;
10046
+ pConstraint = pIdxInfo->aConstraint;
10047
+ for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
10048
+ int iCol; /* 0 for start, 1 for stop, 2 for step */
10049
+ int iMask; /* bitmask for those column */
10050
+ int op = pConstraint->op;
10051
+ if( op>=SQLITE_INDEX_CONSTRAINT_LIMIT
10052
+ && op<=SQLITE_INDEX_CONSTRAINT_OFFSET
10053
+ ){
10054
+ if( pConstraint->usable==0 ){
10055
+ /* do nothing */
10056
+ }else if( op==SQLITE_INDEX_CONSTRAINT_LIMIT ){
10057
+ aIdx[3] = i;
10058
+ idxNum |= 0x20;
10059
+ }else{
10060
+ assert( op==SQLITE_INDEX_CONSTRAINT_OFFSET );
10061
+ aIdx[4] = i;
10062
+ idxNum |= 0x40;
10063
+ }
10064
+ continue;
10065
+ }
10066
+ if( pConstraint->iColumn<SERIES_COLUMN_START ){
10067
+ if( (pConstraint->iColumn==SERIES_COLUMN_VALUE ||
10068
+ pConstraint->iColumn==SERIES_COLUMN_ROWID)
10069
+ && pConstraint->usable
10070
+ ){
10071
+ switch( op ){
10072
+ case SQLITE_INDEX_CONSTRAINT_EQ:
10073
+ case SQLITE_INDEX_CONSTRAINT_IS: {
10074
+ idxNum |= 0x0080;
10075
+ idxNum &= ~0x3300;
10076
+ aIdx[5] = i;
10077
+ aIdx[6] = -1;
10078
+#ifndef ZERO_ARGUMENT_GENERATE_SERIES
10079
+ bStartSeen = 1;
10080
+#endif
10081
+ break;
10082
+ }
10083
+ case SQLITE_INDEX_CONSTRAINT_GE: {
10084
+ if( idxNum & 0x0080 ) break;
10085
+ idxNum |= 0x0100;
10086
+ idxNum &= ~0x0200;
10087
+ aIdx[5] = i;
10088
+#ifndef ZERO_ARGUMENT_GENERATE_SERIES
10089
+ bStartSeen = 1;
10090
+#endif
10091
+ break;
10092
+ }
10093
+ case SQLITE_INDEX_CONSTRAINT_GT: {
10094
+ if( idxNum & 0x0080 ) break;
10095
+ idxNum |= 0x0200;
10096
+ idxNum &= ~0x0100;
10097
+ aIdx[5] = i;
10098
+#ifndef ZERO_ARGUMENT_GENERATE_SERIES
10099
+ bStartSeen = 1;
10100
+#endif
10101
+ break;
10102
+ }
10103
+ case SQLITE_INDEX_CONSTRAINT_LE: {
10104
+ if( idxNum & 0x0080 ) break;
10105
+ idxNum |= 0x1000;
10106
+ idxNum &= ~0x2000;
10107
+ aIdx[6] = i;
10108
+ break;
10109
+ }
10110
+ case SQLITE_INDEX_CONSTRAINT_LT: {
10111
+ if( idxNum & 0x0080 ) break;
10112
+ idxNum |= 0x2000;
10113
+ idxNum &= ~0x1000;
10114
+ aIdx[6] = i;
10115
+ break;
10116
+ }
10117
+ }
10118
+ }
10119
+ continue;
10120
+ }
10121
+ iCol = pConstraint->iColumn - SERIES_COLUMN_START;
10122
+ assert( iCol>=0 && iCol<=2 );
10123
+ iMask = 1 << iCol;
10124
+#ifndef ZERO_ARGUMENT_GENERATE_SERIES
10125
+ if( iCol==0 && op==SQLITE_INDEX_CONSTRAINT_EQ ){
10126
+ bStartSeen = 1;
10127
+ }
10128
+#endif
10129
+ if( pConstraint->usable==0 ){
10130
+ unusableMask |= iMask;
10131
+ continue;
10132
+ }else if( op==SQLITE_INDEX_CONSTRAINT_EQ ){
10133
+ idxNum |= iMask;
10134
+ aIdx[iCol] = i;
10135
+ }
10136
+ }
10137
+ if( pIdxInfo->nOrderBy>=1 ){
10138
+ int iOB = pIdxInfo->aOrderBy[0].iColumn;
10139
+ if( iOB==SERIES_COLUMN_VALUE || iOB==SERIES_COLUMN_ROWID ){
10140
+ /* The rowid is an alias for value, and both are unique, so the
10141
+ ** series can be generated in the requested order regardless of any
10142
+ ** subsequent ORDER BY terms. */
10143
+ if( pIdxInfo->aOrderBy[0].desc ){
10144
+ idxNum |= 0x08;
10145
+ }else{
10146
+ idxNum |= 0x10;
10147
+ }
10148
+ pIdxInfo->orderByConsumed = 1;
10149
+ }else{
10150
+ /* The core will sort the output, so it needs to see every row.
10151
+ ** A LIMIT or OFFSET applied here would discard rows before the sort */
10152
+ idxNum &= ~0x60;
10153
+ aIdx[3] = aIdx[4] = -1;
10154
+ }
10155
+ }
10156
+ if( aIdx[3]==0 ){
10157
+ /* Ignore OFFSET if LIMIT is omitted */
10158
+ idxNum &= ~0x60;
10159
+ aIdx[4] = 0;
10160
+ }
10161
+ for(i=0; i<7; i++){
10162
+ if( (j = aIdx[i])>=0 ){
10163
+ pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
10164
+ pIdxInfo->aConstraintUsage[j].omit =
10165
+ !SQLITE_SERIES_CONSTRAINT_VERIFY || i>=3;
10166
+ }
10167
+ }
10168
+ /* The current generate_column() implementation requires at least one
10169
+ ** argument (the START value). Legacy versions assumed START=0 if the
10170
+ ** first argument was omitted. Compile with -DZERO_ARGUMENT_GENERATE_SERIES
10171
+ ** to obtain the legacy behavior */
10172
+#ifndef ZERO_ARGUMENT_GENERATE_SERIES
10173
+ if( !bStartSeen ){
10174
+ sqlite3_free(pVTab->zErrMsg);
10175
+ pVTab->zErrMsg = sqlite3_mprintf(
10176
+ "first argument to \"generate_series()\" missing or unusable");
10177
+ return SQLITE_ERROR;
10178
+ }
10179
+#endif
10180
+ if( (unusableMask & ~idxNum)!=0 ){
10181
+ /* The start, stop, and step columns are inputs. Therefore if there
10182
+ ** are unusable constraints on any of start, stop, or step then
10183
+ ** this plan is unusable */
10184
+ return SQLITE_CONSTRAINT;
10185
+ }
10186
+ if( (idxNum & 0x03)==0x03 ){
10187
+ /* Both start= and stop= boundaries are available. This is the
10188
+ ** the preferred case */
10189
+ pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
10190
+ pIdxInfo->estimatedRows = 1000;
10191
+ }else if( (idxNum & 0x21)==0x21 ){
10192
+ /* We have start= and LIMIT */
10193
+ pIdxInfo->estimatedRows = 2500;
10194
+ }else{
10195
+ /* If either boundary is missing, we have to generate a huge span
10196
+ ** of numbers. Make this case very expensive so that the query
10197
+ ** planner will work hard to avoid it. */
10198
+ pIdxInfo->estimatedRows = 2147483647;
10199
+ }
10200
+ pIdxInfo->idxNum = idxNum;
10201
+#ifdef SQLITE_INDEX_SCAN_HEX
10202
+ pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_HEX;
10203
+#endif
10204
+ return SQLITE_OK;
10205
+}
10206
+
10207
+/*
10208
+** This following structure defines all the methods for the
10209
+** generate_series virtual table.
10210
+*/
10211
+static sqlite3_module seriesModule = {
10212
+ 0, /* iVersion */
10213
+ 0, /* xCreate */
10214
+ seriesConnect, /* xConnect */
10215
+ seriesBestIndex, /* xBestIndex */
10216
+ seriesDisconnect, /* xDisconnect */
10217
+ 0, /* xDestroy */
10218
+ seriesOpen, /* xOpen - open a cursor */
10219
+ seriesClose, /* xClose - close a cursor */
10220
+ seriesFilter, /* xFilter - configure scan constraints */
10221
+ seriesNext, /* xNext - advance a cursor */
10222
+ seriesEof, /* xEof - check for end of scan */
10223
+ seriesColumn, /* xColumn - read data */
10224
+ seriesRowid, /* xRowid - read data */
10225
+ 0, /* xUpdate */
10226
+ 0, /* xBegin */
10227
+ 0, /* xSync */
10228
+ 0, /* xCommit */
10229
+ 0, /* xRollback */
10230
+ 0, /* xFindMethod */
10231
+ 0, /* xRename */
10232
+ 0, /* xSavepoint */
10233
+ 0, /* xRelease */
10234
+ 0, /* xRollbackTo */
10235
+ 0, /* xShadowName */
10236
+ 0 /* xIntegrity */
10237
+};
10238
+
10239
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
10240
+
10241
+#ifdef _WIN32
10242
+
10243
+#endif
10244
+int sqlite3_series_init(
10245
+ sqlite3 *db,
10246
+ char **pzErrMsg,
10247
+ const sqlite3_api_routines *pApi
10248
+){
10249
+ int rc = SQLITE_OK;
10250
+ SQLITE_EXTENSION_INIT2(pApi);
10251
+#ifndef SQLITE_OMIT_VIRTUALTABLE
10252
+ if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
10253
+ *pzErrMsg = sqlite3_mprintf(
10254
+ "generate_series() requires SQLite 3.8.12 or later");
10255
+ return SQLITE_ERROR;
10256
+ }
10257
+ rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
10258
+#endif
10259
+ return rc;
10260
+}
10261
+
10262
+/************************* End ext/misc/series.c ********************/
10263
+/************************* Begin ext/misc/tryeval.c ******************/
10264
+/*
10265
+** 2026-10-26
10266
+**
10267
+** The author disclaims copyright to this source code. In place of
10268
+** a legal notice, here is a blessing:
10269
+**
10270
+** May you do good and not evil.
10271
+** May you find forgiveness for yourself and forgive others.
10272
+** May you share freely, never taking more than you give.
10273
+**
10274
+******************************************************************************
10275
+**
10276
+** This is an extension used for testing SQLite. It is not intended for
10277
+** production use. The interface might change. This file might go out
10278
+** of support and disappear at any moment. Do not depend on this extension.
10279
+**
10280
+** Apparent from comments in the code, this extension is undocumented.
10281
+**
10282
+** This SQLite extension implements the SQL function tryeval(). The tryeval()
10283
+** function takes zero or more arguments, each of which is an SQL statement.
10284
+** The tryeval() function returns the first column of the first row that
10285
+** has a non-NULL first column across each of the argument SQL statements.
10286
+** Evaluation stops as soon as the first row with a non-NULL first column
10287
+** is encountered. Errors in evaluation are silently ignored, moving on
10288
+** the next SQL statement argument. If none of the arguments successfully
10289
+** executes and returns a row with a non-NULL first column, then NULL is
10290
+** returned.
10291
+**
10292
+** Update: Also the expire(V) and expire(V,N) functions. See comments
10293
+** below for details.
10294
+**
10295
+** The purpose of this function is to help evaluate recursive
10296
+** behavior, and expecially the bug report at
10297
+** sqlite.org/bugs/info/3577bc69c52237a4 (2026-10-25T19:26:00Z)
10298
+** as well as other bugs.
10299
+**
10300
+** To build (with SODIR being the directory that contains your
10301
+** sqlite3.h and sqlite3ext.h headers):
10302
+**
10303
+** Linux: gcc -O2 -shared -I$SQDIR -fPIC -o tryeval.so tryeval.c
10304
+** Mac: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o tryeval.dylib tryeval.c
10305
+** Win32: cl /Os -I%SQDIR% tryeval.c -link -dll -out:tryeval.dll
10306
+*/
10307
+/* #include "sqlite3ext.h" */
10308
+SQLITE_EXTENSION_INIT1
10309
+#include <string.h>
10310
+
10311
+/*
10312
+** Implementation of the tryeval(...)
10313
+*/
10314
+static void tryEvalFunc(
10315
+ sqlite3_context *context,
10316
+ int argc,
10317
+ sqlite3_value **argv
10318
+){
10319
+ const char *zSql; /* Next SQL statement to evaluate */
10320
+ sqlite3 *db; /* The database connection */
10321
+ sqlite3_stmt *pStmt; /* Compiled bytecode for zSql */
10322
+ int bDone = 0; /* True if a row with non-NULL first column seen */
10323
+ int rc; /* Result from sqlite3 API calls */
10324
+ int i; /* Loop counter */
10325
+
10326
+ db = sqlite3_context_db_handle(context);
10327
+ for(i=0; !bDone && i<argc; i++){
10328
+ zSql = (const char*)sqlite3_value_text(argv[i]);
10329
+ if( zSql==0 ) continue;
10330
+ rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
10331
+ if( rc==SQLITE_OK ){
10332
+ while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){
10333
+ if( sqlite3_column_type(pStmt,0)==SQLITE_NULL ) continue;
10334
+ sqlite3_result_value(context, sqlite3_column_value(pStmt,0));
10335
+ bDone = 1;
10336
+ break;
10337
+ }
10338
+ }
10339
+ sqlite3_finalize(pStmt);
10340
+ }
10341
+}
10342
+
10343
+/* SQL function: expire(v,n)
10344
+**
10345
+** Return the first argument. But before doing so, expire all prepared
10346
+** statements that use schema n (0,1,...) or if n==-1 expire all prepared
10347
+** statements. If the second argument is omitted, it is assumed to be -1.
10348
+**
10349
+** This routine requires the (new) SQLITE_TESTCTRL_EXPIRE_STMTS test
10350
+** control. If your SQLite does not support that test control, or if
10351
+** you compile with test controls disabled (you ought not do that!) then
10352
+** this routine is just copies its first argument as its result.
10353
+*/
10354
+static void expireFunc(
10355
+ sqlite3_context *context,
10356
+ int argc,
10357
+ sqlite3_value **argv
10358
+){
10359
+ sqlite3 *db = sqlite3_context_db_handle(context);
10360
+ int iDb = argc>=2 ? sqlite3_value_int(argv[1]) : -1;
10361
+#ifdef SQLITE_TESTCTRL_EXPIRE_STMTS
10362
+ sqlite3_test_control(SQLITE_TESTCTRL_EXPIRE_STMTS, db, iDb);
10363
+#endif
10364
+ sqlite3_result_value(context, argv[0]);
10365
+}
10366
+
10367
+#ifdef _WIN32
10368
+
10369
+#endif
10370
+int sqlite3_tryeval_init(
10371
+ sqlite3 *db,
10372
+ char **pzErrMsg,
10373
+ const sqlite3_api_routines *pApi
10374
+){
10375
+ int rc = SQLITE_OK;
10376
+ SQLITE_EXTENSION_INIT2(pApi);
10377
+ (void)pzErrMsg; /* Unused parameter */
10378
+ rc = sqlite3_create_function(db, "tryeval", -1,
10379
+ SQLITE_UTF8, 0,
10380
+ tryEvalFunc, 0, 0);
10381
+ if( rc==SQLITE_OK ){
10382
+ rc = sqlite3_create_function(db, "expire", 1,
10383
+ SQLITE_UTF8|SQLITE_DETERMINISTIC, 0,
10384
+ expireFunc, 0, 0);
10385
+ }
10386
+ if( rc==SQLITE_OK ){
10387
+ rc = sqlite3_create_function(db, "expire", 2,
10388
+ SQLITE_UTF8|SQLITE_DETERMINISTIC, 0,
10389
+ expireFunc, 0, 0);
10390
+ }
10391
+ return rc;
10392
+}
10393
+
10394
+/************************* End ext/misc/tryeval.c ********************/
1018210395
#ifndef SQLITE_SHELL_FIDDLE
1018310396
/************************* Begin ext/misc/fileio.c ******************/
1018410397
/*
1018510398
** 2014-06-13
1018610399
**
@@ -10593,20 +10806,23 @@
1059310806
char *zCopy = sqlite3_mprintf("%s", zFile);
1059410807
int rc = SQLITE_OK;
1059510808
1059610809
if( zCopy==0 ){
1059710810
rc = SQLITE_NOMEM;
10811
+ }else if( zCopy[0]==0 ){
10812
+ rc = SQLITE_ERROR;
10813
+ sqlite3_free(zCopy);
1059810814
}else{
1059910815
int nCopy = (int)strlen(zCopy);
1060010816
int i = 1;
1060110817
1060210818
while( rc==SQLITE_OK ){
1060310819
STRUCT_STAT sStat;
1060410820
int rc2;
1060510821
10606
- for(; zCopy[i]!='/' && i<nCopy; i++);
10607
- if( i==nCopy ) break;
10822
+ for(; i<nCopy && zCopy[i]!='/'; i++);
10823
+ if( i>=nCopy ) break;
1060810824
zCopy[i] = '\0';
1060910825
1061010826
rc2 = fileStat(zCopy, &sStat);
1061110827
if( rc2!=0 ){
1061210828
if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
@@ -10773,11 +10989,12 @@
1077310989
mtime = sqlite3_value_int64(argv[3]);
1077410990
}
1077510991
1077610992
res = writeFile(context, zFile, argv[1], mode, mtime);
1077710993
if( res==1 && errno==ENOENT ){
10778
- if( makeDirectory(zFile)==SQLITE_OK ){
10994
+ res = makeDirectory(zFile);
10995
+ if( res==SQLITE_OK ){
1077910996
res = writeFile(context, zFile, argv[1], mode, mtime);
1078010997
}
1078110998
}
1078210999
1078311000
if( argc>2 && res!=0 ){
@@ -11505,10 +11722,14 @@
1150511722
const sqlite3_api_routines *pApi
1150611723
){
1150711724
int rc = SQLITE_OK;
1150811725
SQLITE_EXTENSION_INIT2(pApi);
1150911726
(void)pzErrMsg; /* Unused parameter */
11727
+
11728
+ /* REMINDER: Changes here should be reflected in the ".safe" command
11729
+ ** of the CLI.
11730
+ */
1151011731
rc = sqlite3_create_function(db, "readfile", 1,
1151111732
SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
1151211733
readfileFunc, 0, 0);
1151311734
if( rc==SQLITE_OK ){
1151411735
rc = sqlite3_create_function(db, "writefile", -1,
@@ -13165,10 +13386,22 @@
1316513386
** transaction.
1316613387
*/
1316713388
static void zipfileCleanupTransaction(ZipfileTab *pTab){
1316813389
ZipfileEntry *pEntry;
1316913390
ZipfileEntry *pNext;
13391
+ ZipfileCsr *pCsr;
13392
+
13393
+ /* A cursor that is not reading from a file or from a blob steps through
13394
+ ** the pTab->pFirstEntry list, which is about to be deleted. Such a
13395
+ ** cursor has nothing left to return, so leave it at EOF rather than
13396
+ ** pointing at freed memory. */
13397
+ for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
13398
+ if( pCsr->pFile==0 && pCsr->pFreeEntry==0 ){
13399
+ pCsr->pCurrent = 0;
13400
+ pCsr->bEof = 1;
13401
+ }
13402
+ }
1317013403
1317113404
if( pTab->pWriteFd ){
1317213405
fclose(pTab->pWriteFd);
1317313406
pTab->pWriteFd = 0;
1317413407
}
@@ -13217,15 +13450,19 @@
1321713450
ZipfileEntry *p;
1321813451
ZipfileEntry *pNext;
1321913452
1322013453
pCsr->bEof = 0;
1322113454
if( pCsr->pFile ){
13455
+ /* File mode: pCurrent is a private copy owned by this cursor. */
1322213456
fclose(pCsr->pFile);
1322313457
pCsr->pFile = 0;
1322413458
zipfileEntryFree(pCsr->pCurrent);
13225
- pCsr->pCurrent = 0;
1322613459
}
13460
+ /* In the other modes pCurrent belongs to pFreeEntry or to the table.
13461
+ ** It must not be left dangling, since a later xFilter() that switches
13462
+ ** this cursor to file mode would free it. */
13463
+ pCsr->pCurrent = 0;
1322713464
1322813465
for(p=pCsr->pFreeEntry; p; p=pNext){
1322913466
pNext = p->pNext;
1323013467
zipfileEntryFree(p);
1323113468
}
@@ -13521,10 +13758,19 @@
1352113758
i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
1352213759
1352313760
int A, B, C, D, E;
1352413761
int yr, mon, day;
1352513762
int hr, min, sec;
13763
+
13764
+ if( mUnixTime<=315532800 ){
13765
+ /* Experimentally, I find that Win11 will not report the modification
13766
+ ** time for any ZIP file entry with a date before 1980-01-01 00:00:01.
13767
+ ** So make that the minimum date-time value. */
13768
+ pCds->mDate = 0x0021;
13769
+ pCds->mTime = 0x0001;
13770
+ return;
13771
+ }
1352613772
1352713773
A = (int)((JD - 1867216.25)/36524.25);
1352813774
A = (int)(JD + 1 + A - (A/4));
1352913775
B = A + 1524;
1353013776
C = (int)((B - 122.1)/365.25);
@@ -13537,21 +13783,15 @@
1353713783
1353813784
hr = (mUnixTime % (24*60*60)) / (60*60);
1353913785
min = (mUnixTime % (60*60)) / 60;
1354013786
sec = (mUnixTime % 60);
1354113787
13542
- if( yr>=1980 ){
13543
- pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
13544
- pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
13545
- }else{
13546
- pCds->mDate = pCds->mTime = 0;
13547
- }
13548
-
13549
- assert( mUnixTime<315507600
13550
- || mUnixTime==zipfileMtime(pCds)
13551
- || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
13552
- /* || (mUnixTime % 2) */
13788
+ pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
13789
+ pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
13790
+
13791
+ assert( mUnixTime==zipfileMtime(pCds)
13792
+ || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
1355313793
);
1355413794
}
1355513795
1355613796
/*
1355713797
** Set (*pzErr) to point to a buffer from sqlite3_malloc() containing a
@@ -13712,11 +13952,11 @@
1371213952
pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
1371313953
}
1371413954
pCsr->pCurrent = p;
1371513955
}
1371613956
}else{
13717
- if( !pCsr->bNoop ){
13957
+ if( !pCsr->bNoop && !pCsr->bEof ){
1371813958
pCsr->pCurrent = pCsr->pCurrent->pNext;
1371913959
}
1372013960
if( pCsr->pCurrent==0 ){
1372113961
pCsr->bEof = 1;
1372213962
}
@@ -13832,12 +14072,17 @@
1383214072
sqlite3_vtab_cursor *cur, /* The cursor */
1383314073
sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
1383414074
int i /* Which column to return */
1383514075
){
1383614076
ZipfileCsr *pCsr = (ZipfileCsr*)cur;
13837
- ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
14077
+ ZipfileCDS *pCDS;
1383814078
int rc = SQLITE_OK;
14079
+ if( pCsr->pCurrent==0 ){
14080
+ /* The transaction ended while this row was being processed. */
14081
+ return SQLITE_OK;
14082
+ }
14083
+ pCDS = &pCsr->pCurrent->cds;
1383914084
switch( i ){
1384014085
case 0: /* name */
1384114086
sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
1384214087
break;
1384314088
case 1: /* mode */
@@ -14678,11 +14923,11 @@
1467814923
ZipfileCsr *pCsr;
1467914924
ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
1468014925
assert( argc>0 );
1468114926
1468214927
pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
14683
- if( pCsr ){
14928
+ if( pCsr && pCsr->pCurrent ){
1468414929
ZipfileCDS *p = &pCsr->pCurrent->cds;
1468514930
char *zRes = sqlite3_mprintf("{"
1468614931
"\"version-made-by\" : %u, "
1468714932
"\"version-to-extract\" : %u, "
1468814933
"\"flags\" : %u, "
@@ -15025,10 +15270,13 @@
1502515270
0, /* xRollback */
1502615271
0, /* xShadowName */
1502715272
0 /* xIntegrity */
1502815273
};
1502915274
15275
+ /* REMINDER: Changes here should also be reflected in the ".safe"
15276
+ ** command of the CLI
15277
+ */
1503015278
int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0);
1503115279
if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
1503215280
if( rc==SQLITE_OK ){
1503315281
rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
1503415282
zipfileStep, zipfileFinal
@@ -15660,11 +15908,11 @@
1566015908
static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
1566115909
IdxConstraint *pNew;
1566215910
int nColl = STRLEN(zColl);
1566315911
1566415912
assert( *pRc==SQLITE_OK );
15665
- pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
15913
+ pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) + nColl + 1);
1566615914
if( pNew ){
1566715915
pNew->zColl = (char*)&pNew[1];
1566815916
memcpy(pNew->zColl, zColl, nColl+1);
1566915917
}
1567015918
return pNew;
@@ -16184,10 +16432,12 @@
1618416432
*/
1618516433
static int idxIdentifierRequiresQuotes(const char *zId){
1618616434
int i;
1618716435
int nId = STRLEN(zId);
1618816436
16437
+ if( nId==0 ) return 1;
16438
+ if( zId[0]>='0' && zId[0]<='9' ) return 1;
1618916439
if( sqlite3_keyword_check(zId, nId) ) return 1;
1619016440
1619116441
for(i=0; zId[i]; i++){
1619216442
if( !(zId[i]=='_')
1619316443
&& !(zId[i]>='0' && zId[i]<='9')
@@ -16398,13 +16648,11 @@
1639816648
zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
1639916649
if( !zIdx ){
1640016650
rc = SQLITE_NOMEM;
1640116651
}else{
1640216652
rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
16403
- if( rc!=SQLITE_OK ){
16404
- rc = SQLITE_BUSY_TIMEOUT;
16405
- }else{
16653
+ if( rc==SQLITE_OK ){
1640616654
idxHashAdd(&rc, &p->hIdx, zName, zIdx);
1640716655
}
1640816656
}
1640916657
sqlite3_free(zIdx);
1641016658
}
@@ -17521,15 +17769,19 @@
1752117769
/* Do trigger processing to collect any extra IdxScan structures */
1752217770
rc = idxProcessTriggers(p, pzErr);
1752317771
1752417772
/* Create candidate indexes within the in-memory database file */
1752517773
if( rc==SQLITE_OK ){
17774
+ p->pzErrmsg = pzErr;
1752617775
rc = idxCreateCandidates(p);
17527
- }else if ( rc==SQLITE_BUSY_TIMEOUT ){
17528
- if( pzErr )
17529
- *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
17530
- return rc;
17776
+ p->pzErrmsg = 0;
17777
+ if( rc==SQLITE_BUSY_TIMEOUT ){
17778
+ if( pzErr ){
17779
+ *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
17780
+ }
17781
+ return rc;
17782
+ }
1753117783
}
1753217784
1753317785
/* Generate the stat1 data */
1753417786
if( rc==SQLITE_OK ){
1753517787
rc = idxPopulateStat1(p, pzErr);
@@ -22443,10 +22695,16 @@
2244322695
** index of the bind paramater to which the rowid value should be bound.
2244422696
** Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
2244522697
** KEY column, then the rowid value should be bound to the index associated
2244622698
** with the column.
2244722699
**
22700
+** zRowid:
22701
+** If iRowidBind>0, the name used to refer to the rowid in the INSERT
22702
+** statement. This is the first of "_rowid_", "rowid" and "oid" that is
22703
+** not also the name of a column. If all three are column names, the
22704
+** rowid cannot be written and iRowidBind is 0.
22705
+**
2244822706
** pNext:
2244922707
** All RecoverTable objects used by the recovery operation are allocated
2245022708
** and populated as part of creating the recovered database schema in
2245122709
** the output database, before any non-schema data are recovered. They
2245222710
** are then stored in a singly-linked list linked by this variable beginning
@@ -22458,10 +22716,11 @@
2245822716
int nCol; /* Number of columns in table */
2245922717
int nField; /* Number of fields in each record */
2246022718
RecoverColumn *aCol; /* Array of columns */
2246122719
int bIntkey; /* True for intkey, false for without rowid */
2246222720
int iRowidBind; /* If >0, bind rowid to INSERT here */
22721
+ const char *zRowid; /* Name to use for rowid in INSERT */
2246322722
RecoverTable *pNext;
2246422723
};
2246522724
2246622725
/*
2246722726
** Each database column is represented by an instance of the following object
@@ -22908,15 +23167,15 @@
2290823167
** SQL statements separated by ';', only the first is run.
2290923168
**
2291023169
** Return the sqlite3_finalizer() or sqlite3_prepare() result code
2291123170
** from running the zSql statement.
2291223171
*/
22913
-static int recoverOneStmt(sqlite3 *db, const char *zSql){
23172
+static int recoverOneStmt(sqlite3 *db, const char *zSql, const char **pzTail){
2291423173
sqlite3_stmt *pStmt = 0;
2291523174
int rc;
2291623175
if( zSql==0 ) return SQLITE_OK;
22917
- rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
23176
+ rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, pzTail);
2291823177
if( rc ){
2291923178
sqlite3_finalize(pStmt);
2292023179
return rc;
2292123180
}
2292223181
while( SQLITE_ROW==sqlite3_step(pStmt) ){}
@@ -22933,11 +23192,11 @@
2293323192
** If successful, return SQLITE_OK. Or, if an error occurs, leave an error
2293423193
** code and message in the recover handle and return a copy of the error code.
2293523194
*/
2293623195
static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){
2293723196
if( p->errCode==SQLITE_OK ){
22938
- int rc = recoverOneStmt(db, zSql);
23197
+ int rc = recoverOneStmt(db, zSql, 0);
2293923198
if( rc ){
2294023199
recoverDbError(p, db);
2294123200
}
2294223201
}
2294323202
return p->errCode;
@@ -23444,11 +23703,11 @@
2344423703
sqlite3_recover *p,
2344523704
const char *zName, /* Name of table created in output db */
2344623705
i64 iRoot /* Root page of same table in INPUT db */
2344723706
){
2344823707
sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut,
23449
- "PRAGMA table_xinfo(%Q)", zName
23708
+ "PRAGMA %Q.table_xinfo(%Q)", p->zDb, zName
2345023709
);
2345123710
2345223711
if( pStmt ){
2345323712
int iPk = -1;
2345423713
int iBind = 1;
@@ -23511,11 +23770,12 @@
2351123770
/* If this is a WITHOUT ROWID table, the fields of each record are
2351223771
** ordered as reported by PRAGMA index_xinfo on the table. A column may
2351323772
** appear more than once if it is listed more than once in the PRIMARY
2351423773
** KEY (with different collation sequences). In that case use the first
2351523774
** field - the others are redundant copies. */
23516
- pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName);
23775
+ pStmt = recoverPreparePrintf(p, p->dbOut,
23776
+ "PRAGMA %Q.index_xinfo(%Q)", p->zDb, zName);
2351723777
while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
2351823778
int iField = sqlite3_column_int(pStmt, 0);
2351923779
int iCol = sqlite3_column_int(pStmt, 1);
2352023780
2352123781
assert( iCol>=0 && iCol<pNew->nCol );
@@ -23527,16 +23787,40 @@
2352723787
if( pNew->aCol[iCol].iField<0 ) pNew->aCol[iCol].iField = iField;
2352823788
pNew->nField = iField+1;
2352923789
iPk = -2;
2353023790
}
2353123791
recoverFinalize(p, pStmt);
23792
+
23793
+ /* A column declared as "INTEGER PRIMARY KEY DESC" is not an alias for
23794
+ ** the rowid. Such a table has an automatic index with origin 'pk',
23795
+ ** whereas a table with a true rowid alias does not. */
23796
+ if( iPk>=0 ){
23797
+ pStmt = recoverPreparePrintf(p, p->dbOut,
23798
+ "SELECT 1 FROM pragma_index_list(%Q, %Q) WHERE origin='pk'",
23799
+ zName, p->zDb
23800
+ );
23801
+ if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ) iPk = -1;
23802
+ recoverFinalize(p, pStmt);
23803
+ }
2353223804
2353323805
if( p->errCode==SQLITE_OK ){
2353423806
if( iPk>=0 ){
2353523807
pNew->aCol[iPk].bIPK = 1;
2353623808
}else if( pNew->bIntkey ){
23537
- pNew->iRowidBind = iBind++;
23809
+ /* Find a name for the rowid that is not also the name of a column */
23810
+ static const char *azRowid[] = { "_rowid_", "rowid", "oid" };
23811
+ int ii, jj;
23812
+ for(ii=0; ii<(int)(sizeof(azRowid)/sizeof(azRowid[0])); ii++){
23813
+ for(jj=0; jj<pNew->nCol; jj++){
23814
+ if( sqlite3_stricmp(azRowid[ii], pNew->aCol[jj].zCol)==0 ) break;
23815
+ }
23816
+ if( jj==pNew->nCol ){
23817
+ pNew->zRowid = azRowid[ii];
23818
+ pNew->iRowidBind = iBind++;
23819
+ break;
23820
+ }
23821
+ }
2353823822
}
2353923823
}
2354023824
}
2354123825
}
2354223826
@@ -23590,27 +23874,37 @@
2359023874
int bVirtual = sqlite3_column_int(pSelect, 2);
2359123875
const char *zName = (const char*)sqlite3_column_text(pSelect, 3);
2359223876
const char *zSql = (const char*)sqlite3_column_text(pSelect, 4);
2359323877
char *zFree = 0;
2359423878
int rc = SQLITE_OK;
23879
+ const char *zTail = 0;
2359523880
2359623881
if( bVirtual ){
2359723882
zSql = (const char*)(zFree = recoverMPrintf(p,
2359823883
"INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
2359923884
zName, zName, zSql
2360023885
));
2360123886
}
23602
- rc = recoverOneStmt(p->dbOut, zSql);
23887
+ rc = recoverOneStmt(p->dbOut, zSql, &zTail);
2360323888
if( rc==SQLITE_OK ){
23889
+ char *pToFree = 0;
23890
+ if( zTail && zTail[0] ){
23891
+ int n = (int)(zTail - zSql);
23892
+ while( n>0 && (zSql[n-1]==';' || zSql[n-1]<=' ') ){ n--; }
23893
+ pToFree = sqlite3_mprintf("%.*s", n, zSql);
23894
+ zSql = pToFree;
23895
+
23896
+ }
2360423897
recoverSqlCallback(p, zSql);
2360523898
if( bTable && !bVirtual ){
2360623899
if( SQLITE_ROW==sqlite3_step(pTblname) ){
2360723900
const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0);
2360823901
if( zTbl ) recoverAddTable(p, zTbl, iRoot);
2360923902
}
2361023903
recoverReset(p, pTblname);
2361123904
}
23905
+ sqlite3_free(pToFree);
2361223906
}else if( rc!=SQLITE_ERROR ){
2361323907
recoverDbError(p, p->dbOut);
2361423908
}
2361523909
sqlite3_free(zFree);
2361623910
}
@@ -23649,13 +23943,23 @@
2364923943
);
2365023944
2365123945
if( pSelect ){
2365223946
while( sqlite3_step(pSelect)==SQLITE_ROW ){
2365323947
const char *zSql = (const char*)sqlite3_column_text(pSelect, 1);
23654
- int rc = recoverOneStmt(p->dbOut, zSql);
23948
+ const char *zTail = 0;
23949
+ int rc = recoverOneStmt(p->dbOut, zSql, &zTail);
2365523950
if( rc==SQLITE_OK ){
23951
+ char *pToFree = 0;
23952
+ if( zTail && zTail[0] ){
23953
+ /* Omit any extraneous text that follows the first SQL statement */
23954
+ int n = (int)(zTail - zSql);
23955
+ while( n>0 && (zSql[n-1]==';' || zSql[n-1]<=' ') ){ n--; }
23956
+ pToFree = sqlite3_mprintf("%.*s", n, zSql);
23957
+ zSql = pToFree;
23958
+ }
2365623959
recoverSqlCallback(p, zSql);
23960
+ sqlite3_free(pToFree);
2365723961
}else if( rc!=SQLITE_ERROR ){
2365823962
recoverDbError(p, p->dbOut);
2365923963
}
2366023964
}
2366123965
}
@@ -23719,11 +24023,12 @@
2371924023
2372024024
zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab);
2372124025
2372224026
if( pTab->iRowidBind ){
2372324027
assert( pTab->bIntkey );
23724
- zSql = recoverMPrintf(p, "%z_rowid_", zSql);
24028
+ assert( pTab->zRowid );
24029
+ zSql = recoverMPrintf(p, "%z%s", zSql, pTab->zRowid);
2372524030
if( bSql ){
2372624031
zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind);
2372724032
}else{
2372824033
zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind);
2372924034
}
@@ -25033,11 +25338,11 @@
2503325338
recoverCacheSchema(p);
2503425339
2503525340
if( bUseWrapper ) recoverUninstallWrapper(p);
2503625341
}while( p->errCode==SQLITE_NOTADB
2503725342
&& (bUseWrapper--)
25038
- && SQLITE_OK==recoverOneStmt(p->dbIn, "ROLLBACK")
25343
+ && SQLITE_OK==recoverOneStmt(p->dbIn, "ROLLBACK", 0)
2503925344
);
2504025345
}
2504125346
2504225347
recoverLeaveMutex();
2504325348
recoverExec(p, p->dbOut, "BEGIN");
@@ -25098,11 +25403,11 @@
2509825403
2509925404
/* If no error has occurred, commit the write transaction on the output
2510025405
** database. Regardless of whether or not an error has occurred, make
2510125406
** an attempt to end the read transaction on the input database. */
2510225407
recoverExec(p, p->dbOut, "COMMIT");
25103
- rc = recoverOneStmt(p->dbIn, "END");
25408
+ rc = recoverOneStmt(p->dbIn, "END", 0);
2510425409
if( p->errCode==SQLITE_OK ) p->errCode = rc;
2510525410
2510625411
recoverSqlCallback(p, "PRAGMA writable_schema = off");
2510725412
recoverSqlCallback(p, "COMMIT");
2510825413
p->eState = RECOVER_STATE_DONE;
@@ -25294,11 +25599,11 @@
2529425599
if( p==0 ){
2529525600
rc = SQLITE_NOMEM;
2529625601
}else{
2529725602
recoverFinalCleanup(p);
2529825603
if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){
25299
- rc = recoverOneStmt(p->dbIn, "END");
25604
+ rc = recoverOneStmt(p->dbIn, "END", 0);
2530025605
if( p->errCode==SQLITE_OK ) p->errCode = rc;
2530125606
}
2530225607
rc = p->errCode;
2530325608
sqlite3_free(p->zErrMsg);
2530425609
sqlite3_free(p->zStateDb);
@@ -25352,11 +25657,10 @@
2535225657
/* All the parameters that determine how to render query results.
2535325658
*/
2535425659
typedef struct Mode {
2535525660
u8 autoExplain; /* Automatically turn on .explain mode */
2535625661
u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
25357
- u8 autoEQPtrace; /* autoEQP is in trace mode */
2535825662
u8 scanstatsOn; /* True to display scan stats before each finalize */
2535925663
u8 bAutoScreenWidth; /* Using the TTY to determine screen width */
2536025664
u8 mFlags; /* MFLG_ECHO, MFLG_CRLF, etc. */
2536125665
u8 eMode; /* One of the MODE_ values */
2536225666
char zIFmt[24]; /* Space to hold the --ifmt value */
@@ -25423,10 +25727,11 @@
2542325727
const char *zInFile; /* Name of the input file */
2542425728
int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
2542525729
FILE *in; /* Read commands from this stream */
2542625730
FILE *out; /* Write results here */
2542725731
FILE *traceOut; /* Output for sqlite3_trace() */
25732
+ char *zEqpFile; /* Append .eqp output to this file, if not NULL */
2542825733
int nErr; /* Number of errors seen */
2542925734
int writableSchema; /* True if PRAGMA writable_schema=ON */
2543025735
int nCheck; /* Number of ".check" commands run */
2543125736
unsigned nProgress; /* Number of progress callbacks encountered */
2543225737
unsigned mxProgress; /* Maximum progress callbacks before failing */
@@ -25583,13 +25888,14 @@
2558325888
#define MODE_Quote 17 /* Quote values as for SQL */
2558425889
#define MODE_Split 18 /* Split-column mode */
2558525890
#define MODE_Table 19 /* MySQL-style table formatting */
2558625891
#define MODE_Tabs 20 /* Tab-separated values */
2558725892
#define MODE_Tcl 21 /* Space-separated list of TCL strings */
25588
-#define MODE_Www 22 /* Full web-page output */
25893
+#define MODE_Test 22 /* list -colsep , -quote on <-- for testing */
25894
+#define MODE_Www 23 /* Full web-page output */
2558925895
25590
-#define MODE_BUILTIN 22 /* Maximum built-in mode */
25896
+#define MODE_BUILTIN 23 /* Maximum built-in mode */
2559125897
#define MODE_BATCH 50 /* Default mode for batch processing */
2559225898
#define MODE_TTY 51 /* Default mode for interactive processing */
2559325899
#define MODE_USER 75 /* First user-defined mode */
2559425900
#define MODE_N_USER 25 /* Maximum number of user-defined modes */
2559525901
@@ -25624,11 +25930,11 @@
2562425930
{ "box", 0, 0, 9, 1, 1, 0, 3, 1, 2, 0 },
2562525931
{ "c", 4, 1, 10, 5, 5, 4, 1, 12, 0, 0 },
2562625932
{ "column", 0, 0, 9, 1, 1, 0, 3, 2, 2, 0 },
2562725933
{ "count", 0, 0, 0, 0, 0, 0, 0, 3, 0, 0 },
2562825934
{ "csv", 4, 5, 9, 3, 3, 0, 1, 12, 0, 0 },
25629
- { "html", 0, 0, 9, 4, 4, 0, 3, 7, 0, 0 },
25935
+ { "html", 0, 0, 11, 4, 4, 0, 3, 7, 0, 0 },
2563025936
{ "insert", 0, 0, 10, 2, 2, 0, 1, 8, 0, 0 },
2563125937
{ "jatom", 4, 1, 11, 6, 6, 0, 1, 12, 0, 0 },
2563225938
{ "jobject", 0, 1, 11, 6, 6, 0, 0, 10, 0, 0 },
2563325939
{ "json", 0, 0, 11, 6, 6, 0, 0, 9, 0, 0 },
2563425940
{ "line", 13, 1, 9, 1, 1, 0, 0, 11, 1, 0 },
@@ -25640,11 +25946,11 @@
2564025946
{ "quote", 4, 1, 10, 2, 2, 0, 1, 12, 0, 0 },
2564125947
{ "split", 0, 0, 9, 1, 1, 0, 1, 2, 2, 2 },
2564225948
{ "table", 0, 0, 9, 1, 1, 0, 3, 19, 2, 0 },
2564325949
{ "tabs", 8, 1, 9, 3, 3, 0, 1, 12, 0, 0 },
2564425950
{ "tcl", 3, 1, 12, 5, 5, 4, 1, 12, 0, 0 },
25645
- { "www", 0, 0, 9, 4, 4, 0, 3, 7, 0, 0 }
25951
+ { "www", 0, 0, 11, 4, 4, 0, 3, 7, 0, 0 }
2564625952
}; /* | / / | / / | | / \____
2564725953
** | / / | / / | | / |
2564825954
** Index into aModeStr[] | / / | | 2: columnar |
2564925955
** | / / | | 1: line |
2565025956
** | / / | | 0: other |
@@ -26828,10 +27134,41 @@
2682827134
/*
2682927135
** SQL function: capable(X)
2683027136
**
2683127137
** Return true if the current build has capability X. Return 0
2683227138
** if X is not a capability or NULL if X is NULL.
27139
+**
27140
+** A build has capability X if any of the following are true:
27141
+**
27142
+** (1) A VFS named X exists.
27143
+** (2) A function named X exists.
27144
+** (3) A module named X exists.
27145
+** (4) A compile-time option X is used for the build.
27146
+**
27147
+** Comparison between X and the various items above is done
27148
+** using sqlite_stricmp() so that upper/lower case does not matter.
27149
+** So capable('generate_series') and capable('GENERATE_SERIES')
27150
+** both work the same.
27151
+**
27152
+** There are also special names "vtab", "fkey", and "load_ext"
27153
+** that return true as long as compile-time options
27154
+** SQLITE_OMIT_VIRTUALTABLE, SQLITE_OMIT_FOREIGN_KEY, and
27155
+** SQLITE_OMIT_LOAD_EXTENSION are omitted from the build,
27156
+** respectively. Thus capable('vtab') means that virtual table
27157
+** features of SQLite are available in the current build.
27158
+**
27159
+** There is also the special name "unsafe" which is true as long
27160
+** as the CLI is not in safe mode. New special names may be added
27161
+** in the future.
27162
+**
27163
+** For other "OMIT" options (besides the three special ones noted
27164
+** in the previous paragraph) you have to say something like
27165
+** "capable('OMIT_EXPLAIN')". And that function returns true
27166
+** if the EXPLAIN capability is omitted. It works like a
27167
+** double-negative. This is a bit confusing (hence the special
27168
+** names for the common cases mentioned above) but it servicable
27169
+** for the rare cases when it is needed.
2683327170
**
2683427171
** This function is intended to be used with the ".if" command
2683527172
** to bypass test cases that use features that are not part of
2683627173
** the build. Examples:
2683727174
**
@@ -26861,33 +27198,54 @@
2686127198
"load_ext", "OMIT_LOAD_EXTENSION",
2686227199
};
2686327200
size_t i;
2686427201
int invert = 0;
2686527202
int res = 0;
27203
+ sqlite3_vfs *pVfs;
2686627204
2686727205
UNUSED_PARAMETER(nVal);
2686827206
if( z==0 ) return;
27207
+
27208
+ /* Check available VFS names */
27209
+ for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
27210
+ if( sqlite3_stricmp(z,pVfs->zName)==0 ){
27211
+ res = 1;
27212
+ goto capable_finished;
27213
+ }
27214
+ }
27215
+
27216
+ /* Special case: capable('unsafe') is true if not in safe mode */
27217
+ if( sqlite3_stricmp(z, "unsafe")==0 && p->bSafeMode==0 ){
27218
+ res = 1;
27219
+ goto capable_finished;
27220
+ }
27221
+
27222
+ /* Check special cases likek "vtab" and "fkey" */
2686927223
for(i=0; i<sizeof(azInversions)/sizeof(azInversions[0])-1; i+=2){
2687027224
if( sqlite3_stricmp(z, azInversions[i])==0 ){
2687127225
z = azInversions[i+1];
2687227226
invert = 1;
2687327227
break;
2687427228
}
2687527229
}
27230
+
27231
+ /* Run pragmas listing compile-time options, virtual tables, and functions */
2687627232
for(i=0; i<sizeof(azSql)/sizeof(azSql[0]); i++){
2687727233
sqlite3_stmt *pStmt = 0;
2687827234
sqlite3_prepare_v2(p->db, azSql[i], -1, &pStmt, 0);
2687927235
while( sqlite3_step(pStmt)==SQLITE_ROW ){
2688027236
const char *zRow = (const char*)sqlite3_column_text(pStmt, 0);
26881
- if( sqlite3_stricmp(zRow, z)==0 ){
27237
+ if( sqlite3_stricmp(z,zRow)==0 ){
2688227238
res = 1;
2688327239
break;
2688427240
}
2688527241
}
2688627242
sqlite3_finalize(pStmt);
2688727243
if( res ) break;
2688827244
}
27245
+
27246
+capable_finished:
2688927247
if( invert ) res = !res;
2689027248
sqlite3_result_int(pCtx, res);
2689127249
}
2689227250
2689327251
@@ -27343,10 +27701,25 @@
2734327701
}
2734427702
}
2734527703
2734627704
/* Forward reference */
2734727705
static int pickStr(const char *zArg, char **pzErr, ...);
27706
+
27707
+/*
27708
+** Clamp a user-supplied value into the range 0..32767 or
27709
+** 0..2147483647
27710
+*/
27711
+static short int modeClamp16(i64 x){
27712
+ if( x<0 ) x = 0;
27713
+ if( x>0x7fff ) x = 0x7fff;
27714
+ return (short int)x;
27715
+}
27716
+static int modeClamp32(i64 x){
27717
+ if( x<0 ) x = 0;
27718
+ if( x>0x7fffffff ) x = 0x7fffffff;
27719
+ return (int)x;
27720
+}
2734827721
2734927722
/*
2735027723
** Change the limits on the display mode. Return 0 on
2735127724
** success. Return non-zero if zArg is mis-formatted.
2735227725
**
@@ -27371,13 +27744,13 @@
2737127744
p->mode.spec.nTitleLimit = 0;
2737227745
}else{
2737327746
int L, C, T = 0;
2737427747
int nNum = sscanf(zArg, "%d,%d,%d", &L, &C, &T);
2737527748
if( nNum<2 || L<0 || C<0 || T<0) return 1;
27376
- p->mode.spec.nLineLimit = L;
27749
+ p->mode.spec.nLineLimit = modeClamp16(L);
2737727750
p->mode.spec.nCharLimit = C;
27378
- if( nNum==3 ) p->mode.spec.nTitleLimit = T;
27751
+ if( nNum==3 ) p->mode.spec.nTitleLimit = modeClamp16(T);
2737927752
}
2738027753
return 0;
2738127754
}
2738227755
2738327756
/*
@@ -28324,10 +28697,34 @@
2832428697
}
2832528698
if( zName==0 ) return;
2832628699
p->zDestTable = sqlite3_mprintf("%s", zName);
2832728700
shell_check_oom(p->zDestTable);
2832828701
}
28702
+
28703
+/*
28704
+** Return a copy of the text z, obtained from sqlite3_malloc(), that is safe
28705
+** to embed inside of a C-style comment in a script of SQL statements and
28706
+** dot-commands. Newlines and other control characters are changed to spaces,
28707
+** and any end-of-comment sequence is broken up. Otherwise, text taken from
28708
+** an untrusted database (for example, a table name in an error message)
28709
+** could terminate the comment and put arbitrary SQL, or a line that begins
28710
+** with "." and so is interpreted as a dot-command, into the output.
28711
+*/
28712
+static char *shellSafeCommentText(const char *z){
28713
+ char *zOut = sqlite3_mprintf("%s", z ? z : "");
28714
+ int i;
28715
+ if( zOut==0 ) return 0;
28716
+ for(i=0; zOut[i]; i++){
28717
+ unsigned char c = (unsigned char)zOut[i];
28718
+ if( c<' ' || c==0x7f ){
28719
+ zOut[i] = ' ';
28720
+ }else if( c=='/' && i>0 && zOut[i-1]=='*' ){
28721
+ zOut[i] = ' ';
28722
+ }
28723
+ }
28724
+ return zOut;
28725
+}
2832928726
2833028727
/*
2833128728
** Maybe construct two lines of text that point out the position of a
2833228729
** syntax error. Return a pointer to the text, in memory obtained from
2833328730
** sqlite3_malloc(). Or, if the most recent error does not involve a
@@ -28357,11 +28754,11 @@
2835728754
len = strlen(zSql);
2835828755
if( len>78 ){
2835928756
len = 78;
2836028757
while( len>0 && (zSql[len]&0xc0)==0x80 ) len--;
2836128758
}
28362
- zCode = sqlite3_mprintf("%.*s", len, zSql);
28759
+ zCode = sqlite3_mprintf("%.*s", (int)len, zSql);
2836328760
shell_check_oom(zCode);
2836428761
for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2836528762
if( iOffset<25 ){
2836628763
zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode,iOffset,"");
2836728764
}else{
@@ -28391,12 +28788,14 @@
2839128788
int i;
2839228789
const char *z;
2839328790
rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2839428791
if( rc!=SQLITE_OK || !pSelect ){
2839528792
char *zContext = shell_error_context(zSelect, p->db);
28793
+ char *zMsg = shellSafeCommentText(sqlite3_errmsg(p->db));
2839628794
cli_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s",
28397
- rc, sqlite3_errmsg(p->db), zContext);
28795
+ rc, zMsg, zContext);
28796
+ sqlite3_free(zMsg);
2839828797
sqlite3_free(zContext);
2839928798
if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2840028799
return rc;
2840128800
}
2840228801
rc = sqlite3_step(pSelect);
@@ -28416,12 +28815,13 @@
2841628815
}
2841728816
rc = sqlite3_step(pSelect);
2841828817
}
2841928818
rc = sqlite3_finalize(pSelect);
2842028819
if( rc!=SQLITE_OK ){
28421
- cli_printf(p->out, "/**** ERROR: (%d) %s *****/\n",
28422
- rc, sqlite3_errmsg(p->db));
28820
+ char *zMsg = shellSafeCommentText(sqlite3_errmsg(p->db));
28821
+ cli_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, zMsg);
28822
+ sqlite3_free(zMsg);
2842328823
if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2842428824
}
2842528825
return rc;
2842628826
}
2842728827
@@ -28705,21 +29105,21 @@
2870529105
/* Create the TEMP table used to store parameter bindings */
2870629106
static void bind_table_init(ShellState *p){
2870729107
int wrSchema = 0;
2870829108
int defensiveMode = 0;
2870929109
sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
28710
- sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
29110
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, (int*)0);
2871129111
sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
28712
- sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
29112
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, (int*)0);
2871329113
sqlite3_exec(p->db,
2871429114
"CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
2871529115
" key TEXT PRIMARY KEY,\n"
2871629116
" value\n"
2871729117
") WITHOUT ROWID;",
2871829118
0, 0, 0);
28719
- sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
28720
- sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
29119
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, (int*)0);
29120
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, (int*)0);
2872129121
}
2872229122
2872329123
/*
2872429124
** Bind parameters on a prepared statement.
2872529125
**
@@ -28735,13 +29135,16 @@
2873529135
static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
2873629136
int nVar;
2873729137
int i;
2873829138
int rc;
2873929139
sqlite3_stmt *pQ = 0;
29140
+ int inTrace = 0;
2874029141
2874129142
nVar = sqlite3_bind_parameter_count(pStmt);
2874229143
if( nVar==0 ) return; /* Nothing to do */
29144
+ sqlite3_db_config(pArg->db, SQLITE_DBCONFIG_VDBE_TRACE, -1, &inTrace);
29145
+ sqlite3_db_config(pArg->db, SQLITE_DBCONFIG_VDBE_TRACE, 0, (int*)0);
2874329146
if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
2874429147
"key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
2874529148
rc = SQLITE_NOTFOUND;
2874629149
pQ = 0;
2874729150
}else{
@@ -28754,10 +29157,11 @@
2875429157
const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
2875529158
if( zVar==0 ){
2875629159
sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
2875729160
zVar = zNum;
2875829161
}
29162
+ if( inTrace ) cli_printf(pArg->out, "BIND: %s\n", zVar);
2875929163
sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
2876029164
if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){
2876129165
sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
2876229166
#ifdef NAN
2876329167
}else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){
@@ -28805,17 +29209,18 @@
2880529209
&& ShellHasFlag(pArg,SHFLG_TestingMode) ){
2880629210
sqlite3_bind_pointer(pStmt,i,aPrimes,"carray",0);
2880729211
}else{
2880829212
sqlite3_bind_null(pStmt, i);
2880929213
}
28810
-#endif
29214
+#endif
2881129215
}else{
2881229216
sqlite3_bind_null(pStmt, i);
2881329217
}
2881429218
sqlite3_reset(pQ);
2881529219
}
2881629220
sqlite3_finalize(pQ);
29221
+ sqlite3_db_config(pArg->db, SQLITE_DBCONFIG_VDBE_TRACE, inTrace, (int*)0);
2881729222
}
2881829223
2881929224
#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION)
2882029225
/*
2882129226
** This function is called to process SQL if the previous shell command
@@ -29034,42 +29439,55 @@
2903429439
2903529440
/* save off the prepared statement handle */
2903629441
if( pArg ){
2903729442
pArg->pStmt = pStmt;
2903829443
}
29039
-
29444
+
2904029445
/* Show the EXPLAIN QUERY PLAN if .eqp is on */
29446
+ bind_prepared_stmt(pArg, pStmt);
2904129447
isExplain = sqlite3_stmt_isexplain(pStmt);
2904229448
if( pArg && pArg->mode.autoEQP && isExplain==0 && pArg->dot.nArg==0 ){
2904329449
int triggerEQP = 0;
2904429450
u8 savedEnableTimer = pArg->enableTimer;
29451
+ FILE *savedOut = pArg->out;
2904529452
pArg->enableTimer = 0;
2904629453
disable_debug_trace_modes();
2904729454
sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
2904829455
if( pArg->mode.autoEQP>=AUTOEQP_trigger ){
29049
- sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
29456
+ sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
2905029457
}
2905129458
sqlite3_reset(pStmt);
2905229459
spec.eStyle = QRF_STYLE_Auto;
2905329460
sqlite3_stmt_explain(pStmt, 2);
29461
+ if( pArg->zEqpFile ){
29462
+ pArg->out = sqlite3_fopen(pArg->zEqpFile, "ab");
29463
+ if( pArg->out==0 ){
29464
+ cli_printf(savedOut, "cannot open .eqp output file \"%s\"\n",
29465
+ pArg->zEqpFile);
29466
+ pArg->out = savedOut;
29467
+ }
29468
+ }
2905429469
sqlite3_format_query_result(pStmt, &spec, 0);
2905529470
if( pArg->mode.autoEQP>=AUTOEQP_full ){
2905629471
sqlite3_reset(pStmt);
2905729472
sqlite3_stmt_explain(pStmt, 1);
2905829473
sqlite3_format_query_result(pStmt, &spec, 0);
2905929474
}
2906029475
2906129476
if( pArg->mode.autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
29062
- sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
29477
+ sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, (int*)0);
2906329478
}
2906429479
sqlite3_reset(pStmt);
2906529480
sqlite3_stmt_explain(pStmt, 0);
29481
+ if( pArg->out!=savedOut ){
29482
+ fclose(pArg->out);
29483
+ pArg->out = savedOut;
29484
+ }
2906629485
restore_debug_trace_modes();
2906729486
pArg->enableTimer = savedEnableTimer;
2906829487
}
2906929488
29070
- bind_prepared_stmt(pArg, pStmt);
2907129489
if( isExplain && pArg->mode.autoExplain ){
2907229490
spec.eStyle = isExplain==1 ? QRF_STYLE_Explain : QRF_STYLE_Eqp;
2907329491
rc = sqlite3_format_query_result(pStmt, &spec, pzErrMsg);
2907429492
}else if( pArg->mode.eMode==MODE_Www ){
2907529493
cli_printf(pArg->out,
@@ -29422,20 +29840,24 @@
2942229840
if( rc==SQLITE_CORRUPT ){
2942329841
char *zQ2;
2942429842
int len = strlen30(zQuery);
2942529843
cli_puts("/****** CORRUPTION ERROR *******/\n", p->out);
2942629844
if( zErr ){
29427
- cli_printf(p->out, "/****** %s ******/\n", zErr);
29845
+ char *zMsg = shellSafeCommentText(zErr);
29846
+ cli_printf(p->out, "/****** %s ******/\n", zMsg);
29847
+ sqlite3_free(zMsg);
2942829848
sqlite3_free(zErr);
2942929849
zErr = 0;
2943029850
}
2943129851
zQ2 = malloc( len+100 );
2943229852
if( zQ2==0 ) return rc;
2943329853
sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
2943429854
rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
2943529855
if( rc ){
29436
- cli_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
29856
+ char *zMsg = shellSafeCommentText(zErr);
29857
+ cli_printf(p->out, "/****** ERROR: %s ******/\n", zMsg);
29858
+ sqlite3_free(zMsg);
2943729859
}else{
2943829860
rc = SQLITE_CORRUPT;
2943929861
}
2944029862
free(zQ2);
2944129863
}
@@ -29632,13 +30054,17 @@
2963230054
".recover Recover as much data as possible from corrupt db.",
2963330055
" --ignore-freelist Ignore pages that appear to be on db freelist",
2963430056
" --lost-and-found TABLE Alternative name for the lost-and-found table",
2963530057
" --no-rowids Do not attempt to recover rowid values",
2963630058
" that are not also INTEGER PRIMARY KEYs",
30059
+ " --unsafe Do not issue the \".safe\" command in output",
2963730060
#endif
2963830061
#ifndef SQLITE_SHELL_FIDDLE
2963930062
".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
30063
+#endif
30064
+ ".safe Put the CLI into \"safe mode\"",
30065
+#ifndef SQLITE_SHELL_FIDDLE
2964030066
".save ?OPTIONS? FILE Write database to FILE (an alias for .backup ...)",
2964130067
#endif
2964230068
".scanstats on|off|est Turn sqlite3_stmt_scanstatus() metrics on or off",
2964330069
".schema ?PATTERN? Show the CREATE statements matching PATTERN",
2964430070
" Options:",
@@ -29726,21 +30152,10 @@
2972630152
** "Usage" help text automatically generated from comments */
2972730153
static const struct {
2972830154
const char *zCmd; /* Name of the dot-command */
2972930155
const char *zUsage; /* Documentation */
2973030156
} aUsage[] = {
29731
- { ".clone",
29732
-"USAGE: .clone FILE\n"
29733
-"\n"
29734
-"The original purpose of the \".clone\" command (when it was first introduced\n"
29735
-"in 2014) was to try to recover content for a corrupt database file and\n"
29736
-"write the recovered content into a new database named FILE. However,\n"
29737
-"the command has always been experimental and undocumented. Today, it\n"
29738
-"does nothing more than make a copy of the main database into a new\n"
29739
-"database named by its only argument, FILE. No repair attempts are\n"
29740
-"made. The command is retained for legacy only.\n"
29741
- },
2974230157
{ ".import",
2974330158
"USAGE: .import [OPTIONS] FILE TABLE\n"
2974430159
"\n"
2974530160
"Import CSV or similar text from FILE into TABLE. If TABLE does\n"
2974630161
"not exist, it is created using the first row of FILE as the column\n"
@@ -29770,10 +30185,140 @@
2977030185
" --rowsep CHAR Use CHAR as the row separator.\n"
2977130186
" --schema S When creating TABLE, put it in schema S\n"
2977230187
" --skip N Ignore the first N rows of input\n"
2977330188
" -v Verbose mode\n"
2977430189
},
30190
+ { ".testcase",
30191
+"USAGE: .testcase [OPTIONS] NAME\n"
30192
+"\n"
30193
+"Start a new test case identified by NAME. All output\n"
30194
+"through the next \".check\" command is captured for comparison. See the\n"
30195
+"\".check\" command for additional information.\n"
30196
+"\n"
30197
+"Options:\n"
30198
+" --error-prefix TEXT Change error message prefix text to TEXT\n"
30199
+ },
30200
+ { ".once",
30201
+"USAGE: .once [OPTIONS] FILE ...\n"
30202
+"\n"
30203
+"Write the output for the next line of SQL or the next dot-command into\n"
30204
+"FILE. If FILE begins with \"|\" then it is a program into which output\n"
30205
+"is written. The FILE argument should be omitted if one of the -e, -w,\n"
30206
+"or -x options is used.\n"
30207
+"\n"
30208
+"Options:\n"
30209
+" -e Capture output into a temporary file then bring up\n"
30210
+" a text editor on that temporary file.\n"
30211
+" --plain Use plain text rather than HTML tables with -w\n"
30212
+" -w Capture output into an HTML file then bring up that\n"
30213
+" file in a web browser\n"
30214
+" -x Show the output in a spreadsheet. Output is\n"
30215
+" written to a temp file as CSV then the spreadsheet\n"
30216
+" is launched when\n"
30217
+ },
30218
+ { ".check",
30219
+"USAGE: .check [OPTIONS] PATTERN\n"
30220
+"\n"
30221
+"Verify the output of all commands since the most recent .testcase\n"
30222
+"command. Both stdout and stderr are captured and compared, so error\n"
30223
+"messages are part of the text being compared, however output from\n"
30224
+"the \".echo on\" dot-command is not captured and is not part of the test\n"
30225
+"result.\n"
30226
+"\n"
30227
+"After checking the result, all captured output is discarded and\n"
30228
+"output starts going back to the console, unless --keep is used.\n"
30229
+"\n"
30230
+"The PATTERN is the concatenation (with a single space separator) of\n"
30231
+"all arguments that are not part of OPTIONS.\n"
30232
+"\n"
30233
+"If PATTERN is \"<<ENDMARK\" (for any ENDMARK) then the actual pattern is\n"
30234
+"taken from subsequent lines of text up to the first line that begins\n"
30235
+"with ENDMARK.\n"
30236
+"\n"
30237
+"The default comparison algorithm is to ignore all leading and trailing\n"
30238
+"whitespace and compare the pattern against the result byte-for-byte except\n"
30239
+"that whitespace characters are equal to other whitespace characters.\n"
30240
+"Thus if the pattern contains a space character and the result contains\n"
30241
+"a tab in the same spot, they would still compare equal. The number of\n"
30242
+"whitespace characters must be the same in the pattern and the result.\n"
30243
+"\n"
30244
+"The --glob, --notglob, and --allglob comparisons are extended so that\n"
30245
+"\"#\" in the pattern matches a sequence of one or more digits with an\n"
30246
+"optional leading \"+\" or \"-\", and a space in the pattern matches a run\n"
30247
+"of one or more whitespace characters.\n"
30248
+"\n"
30249
+"Options:\n"
30250
+" --allglob PATTERN is a GLOB matching the entire test output except\n"
30251
+" leading and trailing whitespace.\n"
30252
+" --any PATTERN is any substring within the test output.\n"
30253
+" --exact PATTERN matches the entire test output, byte for byte.\n"
30254
+" --glob PATTERN is a GLOB matching any substring of the test\n"
30255
+" output. Leading and trailing whitespace on the PATTERN\n"
30256
+" is ignored.\n"
30257
+" --keep Do not reset the test output. One or more .check commands\n"
30258
+" will follow and do additional tests.\n"
30259
+" --not Pass if the test output does *not* match PATTERN.\n"
30260
+" --notglob Shorthand for \"--not --glob\".\n"
30261
+" --nowhere Shorthand for \"--not --any\".\n"
30262
+" --regexp PATTERN is a regular expression matching any substring\n"
30263
+" of the test output.\n"
30264
+" --show Write test output to the screen, for debugging.\n"
30265
+ },
30266
+ { ".safe",
30267
+"USAGE: .safe\n"
30268
+"\n"
30269
+"This command puts the CLI into \"safe mode\". This command cannot be\n"
30270
+"undone. The only way to restore full capabilities is to exit and\n"
30271
+"restart the CLI.\n"
30272
+"\n"
30273
+"Safe mode restricts SQL statements and dot-commands so that no\n"
30274
+"changes may be made to the filesystem other than writing to database\n"
30275
+"files that are already open.\n"
30276
+"\n"
30277
+" * The .open command is blocked unless the database is \":memory:\"\n"
30278
+" or the --hexdb option is used.\n"
30279
+" * The ATTACH command of SQL may not be used\n"
30280
+" * SQL functions with side effects (ex: writefile()) are blocked.\n"
30281
+" * The \".shell\" and \".system\" dot-commands are blocked.\n"
30282
+" * Dot-command like \".archive\", \".backup\", \".load\", \".log\", \".save\"\n"
30283
+" are blocked.\n"
30284
+" * Other commands with deleterious side effects are blocked.\n"
30285
+"\n"
30286
+"Unsafe actions might be simply blocked, or the CLI might issue an error\n"
30287
+"and exit immediately.\n"
30288
+"\n"
30289
+"Safe mode does not prevent harm to database files that are already open.\n"
30290
+"An attacker can still delete content and even use commands like\n"
30291
+"\"PRAGMA writable_schema=ON\" to corrupt a database file that is already\n"
30292
+"open. Safe mode only blocks access to other previously unopened files.\n"
30293
+"\n"
30294
+"CAUTION: If third-party extensions with system side effects have been\n"
30295
+"loaded prior to the .safe command, the CLI has no knowledge of those\n"
30296
+"extensions and does not know to block them. Unsafe actions might still\n"
30297
+"be possible using those third-party extension.\n"
30298
+ },
30299
+ { ".if",
30300
+"USAGE: .if SQL-EXPRESSION\n"
30301
+"\n"
30302
+"The argument can be any SQL expression, including a subquery in\n"
30303
+"parentheses. If the expression evalutes to true (if it is non-zero\n"
30304
+"when converted into an number) then subsequent statements are\n"
30305
+"evaluated. If SQL-EXPRESSION evalutes to false or NULL or raises\n"
30306
+"an error, then subsequent statements are skipped, up until the first\n"
30307
+"matching .elseif, .else, or .endif.\n"
30308
+"\n"
30309
+"Maximum nested depth is limited. An error is raised if .if statements\n"
30310
+"are nested to deep.\n"
30311
+"\n"
30312
+"Every .if must be followed by a matching .endif, or an error is raised.\n"
30313
+ },
30314
+ { ".else",
30315
+"USAGE: .else\n"
30316
+"\n"
30317
+"Invert the sense of the inner-most .if. Start processing if the prior\n"
30318
+".if was false. Stop processing if the prior .if was true.\n"
30319
+ },
2977530320
{ ".mode",
2977630321
"USAGE: .mode [MODE] [OPTIONS]\n"
2977730322
"\n"
2977830323
"Change the output mode to MODE and/or apply OPTIONS to the output mode.\n"
2977930324
"Arguments are processed from left to right. If no arguments, show the\n"
@@ -29844,10 +30389,81 @@
2984430389
" for the unspecified widths.\n"
2984530390
" --wordwrap BOOLEAN Enable/disable word wrapping\n"
2984630391
" --wrap N Wrap columns wider than N characters\n"
2984730392
" --ww Shorthand for \"--wordwrap on\"\n"
2984830393
},
30394
+ { ".eqp",
30395
+"USAGE: .eqp EQPMODE [>OUTPUTFILE]\n"
30396
+"\n"
30397
+"The .eqp command enables or disables the automatic display of EXPLAIN\n"
30398
+"output for each SQL statement evaluated. The required EQPMODE argument\n"
30399
+"may be one of the following:\n"
30400
+"\n"
30401
+" full Show both EXPLAIN QUERY PLAN and EXPLAIN output.\n"
30402
+"\n"
30403
+" off Disable all explain output.\n"
30404
+"\n"
30405
+" on Show EXPLAIN QUERY PLAN output only.\n"
30406
+"\n"
30407
+" trace Like \"full\" but also enable VDBE tracing using\n"
30408
+" PRAGMA vdbe_trace=ON. This option only works if the\n"
30409
+" CLI is compiled with -DSQLITE_DEBUG. The trace output\n"
30410
+" always appears on stdout and is not redirected to a file.\n"
30411
+"\n"
30412
+" trigger Like \"full\" but also show EXPLAIN output for trigger\n"
30413
+" subprograms.\n"
30414
+"\n"
30415
+"The EQPMODE maybe be optionally followed by a filename. If a file is\n"
30416
+"specified, with or without a single leading \">\", then the file is\n"
30417
+"deleted and all subsequent explain output is appended to that file.\n"
30418
+"If the filename begins with \">>\" then the content of the file is retained\n"
30419
+"and all output is appended. If not redirection argument is provided,\n"
30420
+"output redirection is cancelled. The ability to redirect is not available\n"
30421
+"for --safe mode.\n"
30422
+ },
30423
+ { ".endif",
30424
+"USAGE: .endif\n"
30425
+"\n"
30426
+"Terminate an .if statement.\n"
30427
+ },
30428
+ { ".stats",
30429
+"USAGE: .stats [OPTIONS] ...\n"
30430
+"\n"
30431
+"Show status information about the database and database connection.\n"
30432
+"The stats setting is persistent, unless the --once option is used.\n"
30433
+"Options are cumulative and are processed from left to right.\n"
30434
+"If no options are given, that is the same as \".stats all --once\".\n"
30435
+"\n"
30436
+"Options:\n"
30437
+" all Show all available stats.\n"
30438
+" io Show I/O stats (Linux only).\n"
30439
+" mem Show basic memory usage.\n"
30440
+" off Show nothing. Turn off stat display.\n"
30441
+" on Shorthand for \"stmt xmem\".\n"
30442
+" --once Show the stats once. Do not change the default stats display.\n"
30443
+" reset Reset \"max\" values after next display of each that value.\n"
30444
+" stmt Show information about the last SQL statement.\n"
30445
+" vmstep Show the number of virtual machine steps taken.\n"
30446
+" xmem Show detailed memory status information\n"
30447
+" xstmt Show details about each SQL statement\n"
30448
+ },
30449
+ { ".elseif",
30450
+"USAGE: .elseif SQL-EXPRESSION\n"
30451
+"\n"
30452
+"An \"else-if\". The prior .if is finished and a new condition is applied.\n"
30453
+ },
30454
+ { ".clone",
30455
+"USAGE: .clone FILE\n"
30456
+"\n"
30457
+"The original purpose of the \".clone\" command (when it was first introduced\n"
30458
+"in 2014) was to try to recover content for a corrupt database file and\n"
30459
+"write the recovered content into a new database named FILE. However,\n"
30460
+"the command has always been experimental and undocumented. Today, it\n"
30461
+"does nothing more than make a copy of the main database into a new\n"
30462
+"database named by its only argument, FILE. No repair attempts are\n"
30463
+"made. The command is retained for legacy only.\n"
30464
+ },
2984930465
{ ".output",
2985030466
"USAGE: .output [OPTIONS] [FILE]\n"
2985130467
"\n"
2985230468
"Begin redirecting output to FILE. Or if FILE is omitted, revert\n"
2985330469
"to sending output to the console. If FILE begins with \"|\" then\n"
@@ -29876,109 +30492,10 @@
2987630492
" the --plain is used too.\n"
2987730493
" -x Show the output in a spreadsheet. Output is\n"
2987830494
" written to a temp file as CSV then the spreadsheet\n"
2987930495
" is launched when\n"
2988030496
},
29881
- { ".once",
29882
-"USAGE: .once [OPTIONS] FILE ...\n"
29883
-"\n"
29884
-"Write the output for the next line of SQL or the next dot-command into\n"
29885
-"FILE. If FILE begins with \"|\" then it is a program into which output\n"
29886
-"is written. The FILE argument should be omitted if one of the -e, -w,\n"
29887
-"or -x options is used.\n"
29888
-"\n"
29889
-"Options:\n"
29890
-" -e Capture output into a temporary file then bring up\n"
29891
-" a text editor on that temporary file.\n"
29892
-" --plain Use plain text rather than HTML tables with -w\n"
29893
-" -w Capture output into an HTML file then bring up that\n"
29894
-" file in a web browser\n"
29895
-" -x Show the output in a spreadsheet. Output is\n"
29896
-" written to a temp file as CSV then the spreadsheet\n"
29897
-" is launched when\n"
29898
- },
29899
- { ".check",
29900
-"USAGE: .check [OPTIONS] PATTERN\n"
29901
-"\n"
29902
-"Verify results of commands since the most recent .testcase command.\n"
29903
-"Restore output to the console, unless --keep is used.\n"
29904
-"\n"
29905
-"If PATTERN starts with \"<<ENDMARK\" then the actual pattern is taken from\n"
29906
-"subsequent lines of text up to the first line that begins with ENDMARK.\n"
29907
-"All pattern lines and the ENDMARK are discarded.\n"
29908
-"\n"
29909
-"Options:\n"
29910
-" --exact Do an exact comparison including leading and\n"
29911
-" trailing whitespace.\n"
29912
-" --glob Treat PATTERN as a GLOB\n"
29913
-" --keep Do not reset the testcase. More .check commands\n"
29914
-" will follow.\n"
29915
-" --notglob Output should not match PATTERN\n"
29916
-" --show Write testcase output to the screen, for debugging.\n"
29917
- },
29918
- { ".stats",
29919
-"USAGE: .stats [OPTIONS] ...\n"
29920
-"\n"
29921
-"Show status information about the database and database connection.\n"
29922
-"The stats setting is persistent, unless the --once option is used.\n"
29923
-"Options are cumulative and are processed from left to right.\n"
29924
-"If no options are given, that is the same as \".stats all --once\".\n"
29925
-"\n"
29926
-"Options:\n"
29927
-" all Show all available stats.\n"
29928
-" io Show I/O stats (Linux only).\n"
29929
-" mem Show basic memory usage.\n"
29930
-" off Show nothing. Turn off stat display.\n"
29931
-" on Shorthand for \"stmt xmem\".\n"
29932
-" --once Show the stats once. Do not change the default stats display.\n"
29933
-" reset Reset \"max\" values after next display of each that value.\n"
29934
-" stmt Show information about the last SQL statement.\n"
29935
-" vmstep Show the number of virtual machine steps taken.\n"
29936
-" xmem Show detailed memory status information\n"
29937
-" xstmt Show details about each SQL statement\n"
29938
- },
29939
- { ".testcase",
29940
-"USAGE: .testcase [OPTIONS] NAME\n"
29941
-"\n"
29942
-"Start a new test case identified by NAME. All output\n"
29943
-"through the next \".check\" command is captured for comparison. See the\n"
29944
-"\".check\" command for additional informatioon.\n"
29945
-"\n"
29946
-"Options:\n"
29947
-" --error-prefix TEXT Change error message prefix text to TEXT\n"
29948
- },
29949
- { ".if",
29950
-"USAGE: .if SQL-EXPRESSION\n"
29951
-"\n"
29952
-"The argument can be any SQL expression, including a subquery in\n"
29953
-"parentheses. If the expression evalutes to true (if it is non-zero\n"
29954
-"when converted into an number) then subsequent statements are\n"
29955
-"evaluated. If SQL-EXPRESSION evalutes to false or NULL or raises\n"
29956
-"an error, then subsequent statements are skipped, up until the first\n"
29957
-"matching .elseif, .else, or .endif.\n"
29958
-"\n"
29959
-"Maximum nested depth is limited. An error is raised if .if statements\n"
29960
-"are nested to deep.\n"
29961
-"\n"
29962
-"Every .if must be followed by a matching .endif, or an error is raised.\n"
29963
- },
29964
- { ".elseif",
29965
-"USAGE: .elseif SQL-EXPRESSION\n"
29966
-"\n"
29967
-"An \"else-if\". The prior .if is finished and a new condition is applied.\n"
29968
- },
29969
- { ".else",
29970
-"USAGE: .else\n"
29971
-"\n"
29972
-"Invert the sense of the inner-most .if. Start processing if the prior\n"
29973
-".if was false. Stop processing if the prior .if was true.\n"
29974
- },
29975
- { ".endif",
29976
-"USAGE: .endif\n"
29977
-"\n"
29978
-"Terminate an .if statement.\n"
29979
- },
2998030497
};
2998130498
2998230499
/*
2998330500
** Return a pointer to usage text for zCmd, or NULL if none exists.
2998430501
*/
@@ -30119,11 +30636,11 @@
3011930636
**
3012030637
** NULL is returned if any error is encountered. The final value of *pnByte
3012130638
** is undefined in this case.
3012230639
*/
3012330640
static char *readFile(const char *zName, int *pnByte){
30124
- FILE *in = sqlite3_fopen(zName, "rb");
30641
+ FILE *in = (zName && zName[0]) ? sqlite3_fopen(zName, "rb") : 0;
3012530642
long nIn;
3012630643
size_t nRead;
3012730644
char *pBuf;
3012830645
int rc;
3012930646
if( in==0 ) return 0;
@@ -30328,10 +30845,11 @@
3032830845
}
3032930846
if( rc ) return 0; /* Is a database */
3033030847
}
3033130848
if( sqlite3_strlike("%.sql",z,0)==0 ) return 1;
3033230849
if( sqlite3_strlike("%.txt",z,0)==0 ) return 1;
30850
+ if( sqlite3_strlike("%.clitest",z,0)==0 ) return 1;
3033330851
return 0;
3033430852
}
3033530853
3033630854
#ifndef SQLITE_OMIT_DESERIALIZE
3033730855
/*
@@ -30438,10 +30956,29 @@
3043830956
int sleep = sqlite3_value_int(argv[0]);
3043930957
(void)argcUnused;
3044030958
sqlite3_sleep(sleep/1000);
3044130959
sqlite3_result_int(context, sleep);
3044230960
}
30961
+
30962
+/*
30963
+** SQL function: dualrep(X)
30964
+**
30965
+** Return the value X. But if X is in a numeric representation (an
30966
+** integer or a float) then return a dual-representation where the
30967
+** result is both numeric and text at the same time. This has no
30968
+** known practical application, but is useful in testing SQLite
30969
+** internals.
30970
+*/
30971
+static void shellDualRepFunc(
30972
+ sqlite3_context *context,
30973
+ int argcUnused,
30974
+ sqlite3_value **argv
30975
+){
30976
+ (void)argcUnused;
30977
+ sqlite3_value_text(argv[0]);
30978
+ sqlite3_result_value(context, argv[0]);
30979
+}
3044330980
3044430981
/*
3044530982
** SQL function: shell_module_schema(X)
3044630983
**
3044730984
** For use internally and for debugging and testing only. This function
@@ -30580,16 +31117,18 @@
3058031117
sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
3058131118
3058231119
/* Reflect the use or absence of --unsafe-testing invocation. */
3058331120
{
3058431121
int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
30585
- sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0);
30586
- sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0);
31122
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,
31123
+ (int*)0);
31124
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,
31125
+ (int*)0);
3058731126
}
3058831127
3058931128
#ifndef SQLITE_OMIT_LOAD_EXTENSION
30590
- sqlite3_enable_load_extension(p->db, 1);
31129
+ sqlite3_enable_load_extension(p->db, !p->bSafeMode);
3059131130
#endif
3059231131
sqlite3_sha_init(p->db, 0, 0);
3059331132
sqlite3_shathree_init(p->db, 0, 0);
3059431133
sqlite3_uint_init(p->db, 0, 0);
3059531134
sqlite3_stmtrand_init(p->db, 0, 0);
@@ -30599,22 +31138,20 @@
3059931138
sqlite3_regexp_init(p->db, 0, 0);
3060031139
sqlite3_ieee_init(p->db, 0, 0);
3060131140
sqlite3_series_init(p->db, 0, 0);
3060231141
sqlite3_diskused_init(p->db, 0, 0);
3060331142
sqlite3_strdup_init(p->db, 0, 0);
30604
-#ifndef SQLITE_SHELL_FIDDLE
3060531143
if( !p->bSafeMode ){
31144
+ sqlite3_tryeval_init(p->db, 0, 0);
31145
+#ifndef SQLITE_SHELL_FIDDLE
3060631146
sqlite3_fileio_init(p->db, 0, 0);
30607
- }
30608
- sqlite3_completion_init(p->db, 0, 0);
3060931147
#endif
3061031148
#ifdef SQLITE_HAVE_ZLIB
30611
- if( !p->bSafeModePersist ){
3061231149
sqlite3_zipfile_init(p->db, 0, 0);
3061331150
sqlite3_sqlar_init(p->db, 0, 0);
31151
+#endif
3061431152
}
30615
-#endif
3061631153
#ifdef SQLITE_SHELL_EXTFUNCS
3061731154
/* Create a preprocessing mechanism for extensions to make
3061831155
* their own provisions for being built into the shell.
3061931156
* This is a short-span macro. See further below for usage.
3062031157
*/
@@ -30661,10 +31198,12 @@
3066131198
shell_complete_sql, 0, 0);
3066231199
sqlite3_create_function(p->db, "shell_complete_sql", 2, SQLITE_UTF8, p,
3066331200
shell_complete_sql, 0, 0);
3066431201
sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
3066531202
shellUSleepFunc, 0, 0);
31203
+ sqlite3_create_function(p->db, "dualrep",1,SQLITE_UTF8,0,
31204
+ shellDualRepFunc, 0, 0);
3066631205
#ifndef SQLITE_NOHAVE_SYSTEM
3066731206
sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
3066831207
editFunc, 0, 0);
3066931208
sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
3067031209
editFunc, 0, 0);
@@ -31624,11 +32163,13 @@
3162432163
while( (c=(*(zGlob++))) == '*' || c=='?' ){
3162532164
if( c=='?' && (*(z++))==0 ) return 0;
3162632165
}
3162732166
if( c==0 ){
3162832167
return 1;
31629
- }else if( c=='[' ){
32168
+ }else if( c=='[' || c=='#' || IsSpace(c) ){
32169
+ /* The next pattern element is not a literal character. Try to
32170
+ ** match it at each position in the remaining text. */
3163032171
while( *z && testcase_glob(zGlob-1,z)==0 ){
3163132172
z++;
3163232173
}
3163332174
return (*z)!=0;
3163432175
}
@@ -32103,12 +32644,15 @@
3210332644
sqlite3_free(zPrev);
3210432645
zPrev = sqlite3_mprintf("%s", zParent);
3210532646
}
3210632647
3210732648
if( res==0 ){
32649
+ if( strchr(zTarget,'\n') ) zTarget = "(REDACTED)";
3210832650
cli_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
3210932651
}else if( bVerbose ){
32652
+ if( strstr(zFrom,"*/") ) zFrom = "(REDACTED)";
32653
+ if( strstr(zTarget,"*/") ) zTarget = "(REDACTED)";
3211032654
cli_printf(out,
3211132655
"%s/* no extra indexes required for %s -> %s */\n",
3211232656
zIndent, zFrom, zTarget
3211332657
);
3211432658
}
@@ -33081,10 +33625,11 @@
3308133625
int rc = SQLITE_OK;
3308233626
const char *zRecoveryDb = ""; /* Name of "recovery" database. Debug only */
3308333627
const char *zLAF = "lost_and_found";
3308433628
int bFreelist = 1; /* 0 if --ignore-freelist is specified */
3308533629
int bRowids = 1; /* 0 if --no-rowids */
33630
+ int bUnsafe = 0; /* 1 if --unsafe */
3308633631
sqlite3_recover *p = 0;
3308733632
int i = 0;
3308833633
3308933634
for(i=1; i<nArg; i++){
3309033635
char *z = azArg[i];
@@ -33107,10 +33652,13 @@
3310733652
i++;
3310833653
zLAF = azArg[i];
3310933654
}else
3311033655
if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
3311133656
bRowids = 0;
33657
+ }else
33658
+ if( n<=7 && memcmp("-unsafe", z, n)==0 ){
33659
+ bUnsafe = 1;
3311233660
}
3311333661
else{
3311433662
cli_printf(stderr,"unexpected option: %s\n", azArg[i]);
3311533663
showHelp(pState->out, azArg[0]);
3311633664
return 1;
@@ -33127,10 +33675,11 @@
3312733675
sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
3312833676
sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
3312933677
sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
3313033678
3313133679
cli_printf(pState->out, ".dbconfig defensive off\n");
33680
+ if( !bUnsafe ) cli_printf(pState->out, ".safe\n");
3313233681
sqlite3_recover_run(p);
3313333682
if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
3313433683
const char *zErr = sqlite3_recover_errmsg(p);
3313533684
int errCode = sqlite3_recover_errcode(p);
3313633685
cli_printf(stderr,"sql error: %s (%d)\n", zErr, errCode);
@@ -33910,11 +34459,11 @@
3391034459
import_cleanup(&sCtx);
3391134460
sqlite3_finalize(pStmt);
3391234461
if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
3391334462
if( eVerbose>0 ){
3391434463
cli_printf(p->out,
33915
- "Added %d rows with %d errors using %d lines of input\n",
34464
+ "Added %d rows with %d errors using %lld lines of input\n",
3391634465
sCtx.nRow, sCtx.nErr, sCtx.nLine-1-iLineOffset);
3391734466
}
3391834467
return sCtx.nErr ? 1 : 0;
3391934468
}
3392034469
@@ -34144,21 +34693,21 @@
3414434693
p->mode.spec.bBorder = k & 0x3;
3414534694
}
3414634695
chng = 1;
3414734696
}else if( 0<=(k=pickStr(z,0,
3414834697
"-charlimit","-linelimit","-titlelimit","-multiinsert","")) ){
34149
- int w; /* 0 1 2 3 */
34698
+ i64 w; /* 0 1 2 3 */
3415034699
if( i+1>=nArg ){
3415134700
dotCmdError(p, i, "missing argument", 0);
3415234701
return 1;
3415334702
}
3415434703
w = integerValue(azArg[++i]);
3415534704
switch( k ){
34156
- case 0: p->mode.spec.nCharLimit = w; break;
34157
- case 1: p->mode.spec.nLineLimit = w; break;
34158
- case 2: p->mode.spec.nTitleLimit = w; break;
34159
- default: p->mode.spec.nMultiInsert = w; break;
34705
+ case 0: p->mode.spec.nCharLimit = modeClamp32(w); break;
34706
+ case 1: p->mode.spec.nLineLimit = modeClamp16(w); break;
34707
+ case 2: p->mode.spec.nTitleLimit = modeClamp16(w); break;
34708
+ default: p->mode.spec.nMultiInsert = modeClamp32(w); break;
3416034709
}
3416134710
chng = 1;
3416234711
}else if( 0<=(k=pickStr(z,0,"-tablename","-rowsep","-colsep","-null","")) ){
3416334712
/* 0 1 2 3 */
3416434713
if( i+1>=nArg ){
@@ -34305,13 +34854,15 @@
3430534854
memcpy(p->mode.zFpFmt, azArg[i], strlen(azArg[i])+1);
3430634855
p->mode.spec.zFpFmt = p->mode.zFpFmt;
3430734856
}
3430834857
chng = 1;
3430934858
}else if( optionMatch(z,"reset") ){
34310
- int saved_eMode = p->mode.eMode;
34311
- modeFree(&p->mode);
34859
+ int saved_eMode = p->mode.eMode; /* Don't change the mode */
34860
+ u8 saved_echo = p->mode.mFlags & MFLG_ECHO; /* Don't reset --echo */
34861
+ modeFree(&p->mode); /* Reset everything else */
3431234862
modeChange(p, saved_eMode);
34863
+ p->mode.mFlags = saved_echo;
3431334864
}else if( optionMatch(z,"rowcount") ){
3431434865
if( i+1>=nArg ){
3431534866
dotCmdError(p, i, "missing argument", 0);
3431634867
return 1;
3431734868
}
@@ -34893,11 +35444,11 @@
3489335444
3489435445
/*
3489535446
** Return true if the argument is <<MARK for some arbitrary mark
3489635447
*/
3489735448
static int isHereDoc(const char *z){
34898
- return z[0]=='<' && z[1]=='<' && z[2]!=0;
35449
+ return z && z[0]=='<' && z[1]=='<' && z[2]!=0;
3489935450
}
3490035451
3490135452
/*
3490235453
** Capture lines of input text up until a line that matches zTerminator.
3490335454
** Return a memory buffer (allocated using sqlite3_malloc64()) that
@@ -34912,42 +35463,93 @@
3491235463
if( cli_strncmp(zTerminator,zLine,nTerminator)==0 ) break;
3491335464
sqlite3_str_appendall(pHeredoc, zLine);
3491435465
}
3491535466
return sqlite3_str_finish(pHeredoc);
3491635467
}
35468
+
35469
+/*
35470
+** Return a pointer to the first non-whitespace character in the input
35471
+** string, or a pointer to the string terminator if the input contains
35472
+** no non-whitespace characters.
35473
+**
35474
+** The number of bytes that follow, excluding trailing whitespace, is
35475
+** written into *pN if pN!=0.
35476
+*/
35477
+static char *trimSpace(char *zIn, int *pN){
35478
+ while( IsSpace(zIn[0]) ){ zIn++; }
35479
+ if( pN ){
35480
+ size_t n = strlen(zIn);
35481
+ assert( n<=0x7fffffff );
35482
+ while( n>0 && IsSpace(zIn[n-1]) ){ n--; }
35483
+ *pN = (int)n;
35484
+ }
35485
+ return zIn;
35486
+}
3491735487
3491835488
/*
3491935489
** DOT-COMMAND: .check
3492035490
** USAGE: .check [OPTIONS] PATTERN
3492135491
**
34922
-** Verify results of commands since the most recent .testcase command.
34923
-** Restore output to the console, unless --keep is used.
35492
+** Verify the output of all commands since the most recent .testcase
35493
+** command. Both stdout and stderr are captured and compared, so error
35494
+** messages are part of the text being compared, however output from
35495
+** the ".echo on" dot-command is not captured and is not part of the test
35496
+** result.
35497
+**
35498
+** After checking the result, all captured output is discarded and
35499
+** output starts going back to the console, unless --keep is used.
35500
+**
35501
+** The PATTERN is the concatenation (with a single space separator) of
35502
+** all arguments that are not part of OPTIONS.
35503
+**
35504
+** If PATTERN is "<<ENDMARK" (for any ENDMARK) then the actual pattern is
35505
+** taken from subsequent lines of text up to the first line that begins
35506
+** with ENDMARK.
35507
+**
35508
+** The default comparison algorithm is to ignore all leading and trailing
35509
+** whitespace and compare the pattern against the result byte-for-byte except
35510
+** that whitespace characters are equal to other whitespace characters.
35511
+** Thus if the pattern contains a space character and the result contains
35512
+** a tab in the same spot, they would still compare equal. The number of
35513
+** whitespace characters must be the same in the pattern and the result.
3492435514
**
34925
-** If PATTERN starts with "<<ENDMARK" then the actual pattern is taken from
34926
-** subsequent lines of text up to the first line that begins with ENDMARK.
34927
-** All pattern lines and the ENDMARK are discarded.
35515
+** The --glob, --notglob, and --allglob comparisons are extended so that
35516
+** "#" in the pattern matches a sequence of one or more digits with an
35517
+** optional leading "+" or "-", and a space in the pattern matches a run
35518
+** of one or more whitespace characters.
3492835519
**
3492935520
** Options:
34930
-** --exact Do an exact comparison including leading and
34931
-** trailing whitespace.
34932
-** --glob Treat PATTERN as a GLOB
34933
-** --keep Do not reset the testcase. More .check commands
34934
-** will follow.
34935
-** --notglob Output should not match PATTERN
34936
-** --show Write testcase output to the screen, for debugging.
35521
+** --allglob PATTERN is a GLOB matching the entire test output except
35522
+** leading and trailing whitespace.
35523
+** --any PATTERN is any substring within the test output.
35524
+** --exact PATTERN matches the entire test output, byte for byte.
35525
+** --glob PATTERN is a GLOB matching any substring of the test
35526
+** output. Leading and trailing whitespace on the PATTERN
35527
+** is ignored.
35528
+** --keep Do not reset the test output. One or more .check commands
35529
+** will follow and do additional tests.
35530
+** --not Pass if the test output does *not* match PATTERN.
35531
+** --notglob Shorthand for "--not --glob".
35532
+** --nowhere Shorthand for "--not --any".
35533
+** --regexp PATTERN is a regular expression matching any substring
35534
+** of the test output.
35535
+** --show Write test output to the screen, for debugging.
3493735536
*/
3493835537
static int dotCmdCheck(ShellState *p){
3493935538
int nArg = p->dot.nArg; /* Number of arguments */
3494035539
char **azArg = p->dot.azArg; /* Text of the arguments */
3494135540
int i; /* Loop counter */
3494235541
int k; /* Result of pickStr() */
3494335542
char *zTest; /* Textcase result */
3494435543
int bKeep = 0; /* --keep option */
34945
- char *zCheck = 0; /* PATTERN argument */
34946
- char *zPattern = 0; /* Actual test pattern */
34947
- int eCheck = 0; /* 1: --glob, 2: --notglob, 3: --exact */
34948
- int isOk; /* True if results are OK */
35544
+ sqlite3_str *pPattern; /* PATTERN argument */
35545
+ char *zPattern = 0; /* Test pattern */
35546
+ char *zToFree = 0; /* Start of test pattern */
35547
+ int eCheck = 0; /* 0: default. Else 1+index of option */
35548
+ int isOk = 0; /* True if results are OK */
35549
+ int bNot = 0; /* Invert the sense of the test */
35550
+ int iPat = -1; /* Location of the pattern */
3494935551
sqlite3_int64 iStart = p->lineno; /* Line number of .check statement */
3495035552
3495135553
if( p->mIf!=0 ){
3495235554
/* Unlike most other dot-commands, the .check command runs even if
3495335555
** inside the false branch of a .if. It needs to do this so that it
@@ -34959,10 +35561,11 @@
3495935561
}
3496035562
if( p->zTestcase[0]==0 ){
3496135563
dotCmdError(p, 0, "no .testcase is active", 0);
3496235564
return 1;
3496335565
}
35566
+ pPattern = sqlite3_str_new(p->db);
3496435567
for(i=1; i<nArg; i++){
3496535568
char *z = azArg[i];
3496635569
if( z[0]=='-' && z[1]=='-' && z[2]!=0 ) z++;
3496735570
if( cli_strcmp(z,"-keep")==0 ){
3496835571
bKeep = 1;
@@ -34970,87 +35573,157 @@
3497035573
if( sqlite3_str_length(cli_output_capture)>0 ){
3497135574
sqlite3_fprintf(stdout, "%s", sqlite3_str_value(cli_output_capture));
3497235575
}
3497335576
bKeep = 1;
3497435577
}else if( z[0]=='-'
34975
- && (k = pickStr(&z[1],0,"glob","notglob","exact",""))>=0
35578
+ && (k = pickStr(&z[1],0,
35579
+ /* 0 1 2 3 4 5 6 7 */
35580
+ "glob","exact","regexp","any","nowhere","allglob","notglob","not",""))>=0
3497635581
){
34977
- if( eCheck && eCheck!=k+1 ){
35582
+ if( k==7 ){
35583
+ bNot = !bNot;
35584
+ }else if( eCheck==0 || eCheck==k+1 ){
35585
+ eCheck = k+1;
35586
+ }else{
35587
+ output_reset(p);
35588
+ sqlite3_str_free(pPattern);
3497835589
dotCmdError(p, i, "incompatible with prior options",0);
3497935590
return 1;
3498035591
}
34981
- eCheck = k+1;
34982
- }else if( zCheck ){
34983
- dotCmdError(p, i, "unknown option", 0);
34984
- return 1;
3498535592
}else{
34986
- zCheck = azArg[i];
35593
+ if( sqlite3_str_length(pPattern)>0 ){
35594
+ sqlite3_str_appendchar(pPattern, 1, ' ');
35595
+ }else{
35596
+ iPat = i;
35597
+ }
35598
+ sqlite3_str_appendall(pPattern, azArg[i]);
3498735599
}
3498835600
}
34989
- if( zCheck==0 ){
34990
- dotCmdError(p, 0, "no PATTERN specified", 0);
34991
- return 1;
34992
- }
3499335601
if( sqlite3_str_length(cli_output_capture) ){
3499435602
zTest = sqlite3_str_value(cli_output_capture);
3499535603
shell_check_oom(zTest);
3499635604
}else{
3499735605
zTest = "";
3499835606
}
3499935607
p->nTestRun++;
35000
- if( isHereDoc(zCheck) ){
35001
- zPattern = captureHereDoc(p, zCheck+2);
35002
- if( zPattern==0 ){
35003
- zPattern = sqlite3_mprintf("");
35004
- }
35005
- }else{
35006
- zPattern = zCheck;
35007
- }
35008
- shell_check_oom(zPattern);
35009
- switch( eCheck ){
35010
- case 1: {
35011
- char *zGlob = sqlite3_mprintf("*%s*", zPattern);
35012
- isOk = testcase_glob(zGlob, zTest)!=0;
35013
- sqlite3_free(zGlob);
35014
- break;
35015
- }
35016
- case 2: {
35017
- char *zGlob = sqlite3_mprintf("*%s*", zPattern);
35018
- isOk = testcase_glob(zGlob, zTest)==0;
35019
- sqlite3_free(zGlob);
35020
- break;
35021
- }
35022
- case 3: {
35023
- isOk = cli_strcmp(zTest,zPattern)==0;
35024
- break;
35025
- }
35026
- default: {
35027
- /* Skip leading and trailing \n and \r on both pattern and test output */
35028
- const char *z1 = zPattern;
35029
- const char *z2 = zTest;
35030
- size_t n1, n2;
35031
- while( z1[0]=='\n' || z1[0]=='\r' ) z1++;
35032
- n1 = strlen(z1);
35033
- while( n1>0 && (z1[n1-1]=='\n' || z1[n1-1]=='\r') ) n1--;
35034
- while( z2[0]=='\n' || z2[0]=='\r' ) z2++;
35035
- n2 = strlen(z2);
35036
- while( n2>0 && (z2[n2-1]=='\n' || z2[n2-1]=='\r') ) n2--;
35037
- isOk = n1==n2 && memcmp(z1,z2,n1)==0;
35038
- break;
35039
- }
35040
- }
35041
- if( !isOk ){
35608
+ zToFree = zPattern = sqlite3_str_finish(pPattern);
35609
+ if( isHereDoc(zPattern) ){
35610
+ zPattern = captureHereDoc(p, zPattern+2);
35611
+ sqlite3_free(zToFree);
35612
+ zToFree = zPattern;
35613
+ }
35614
+ if( zPattern==0 ){
35615
+ zToFree = zPattern = sqlite3_mprintf("");
35616
+ }
35617
+ shell_check_oom(zPattern);
35618
+ switch( eCheck ){
35619
+ case 6: /* --allglob */
35620
+ case 7: /* --notglob */
35621
+ case 1: { /* --glob */
35622
+ int nPat = 0;
35623
+ char *zGlob;
35624
+ zPattern = trimSpace(zPattern, &nPat);
35625
+ zTest = trimSpace(zTest, 0);
35626
+ if( eCheck==6 ){
35627
+ zGlob = sqlite3_mprintf("%.*s", nPat, zPattern);
35628
+ }else{
35629
+ zGlob = sqlite3_mprintf("*%.*s*", nPat, zPattern);
35630
+ }
35631
+ shell_check_oom(zGlob);
35632
+ isOk = testcase_glob(zGlob, zTest)!=0;
35633
+ if( eCheck==7 ) isOk = !isOk;
35634
+ sqlite3_free(zGlob);
35635
+ break;
35636
+ }
35637
+ case 2: { /* --exact */
35638
+ isOk = cli_strcmp(zTest,zPattern)==0;
35639
+ break;
35640
+ }
35641
+ case 3: { /* --regexp */
35642
+ ReCompiled *pRe = 0;
35643
+ const char *zErr = re_compile(&pRe, zPattern, 1000, 0);
35644
+ if( zErr ){
35645
+ re_free(pRe);
35646
+ sqlite3_free(zToFree);
35647
+ output_reset(p);
35648
+ p->nTestErr++;
35649
+ dotCmdError(p, iPat, "bad regexp", "bad regular expression: %s", zErr);
35650
+ return 1;
35651
+ }
35652
+ shell_check_oom(pRe);
35653
+ isOk = re_match(pRe, (const unsigned char*)zTest, -1);
35654
+ re_free(pRe);
35655
+ break;
35656
+ }
35657
+ case 4: { /* --any */
35658
+ isOk = strstr(zTest,zPattern)!=0;
35659
+ break;
35660
+ }
35661
+ case 5: { /* --nowhere */
35662
+ isOk = strstr(zTest,zPattern)==0;
35663
+ break;
35664
+ }
35665
+ default: { /* default matching rule */
35666
+ /* Ignore leading and trailing whitespace on both the pattern and the
35667
+ ** test output. Each interior whitespace character will compare equal
35668
+ ** to exactly one other whitespace character. */
35669
+ int nPat = 0;
35670
+ int nTest = 0;
35671
+ zPattern = trimSpace(zPattern, &nPat);
35672
+ zTest = trimSpace(zTest, &nTest);
35673
+ if( nPat!=nTest ){
35674
+ isOk = 0;
35675
+ }else if( memcmp(zPattern, zTest, nPat)==0 ){
35676
+ isOk = 1;
35677
+ }else{
35678
+ int ii;
35679
+ isOk = 1;
35680
+ for(ii=0; ii<nPat; ii++){
35681
+ if( zPattern[ii]!=zTest[ii]
35682
+ && !(IsSpace(zPattern[ii]) && IsSpace(zTest[ii]))
35683
+ ){
35684
+ isOk = 0;
35685
+ break;
35686
+ }
35687
+ }
35688
+ }
35689
+ break;
35690
+ }
35691
+ }
35692
+ if( bNot ) isOk = !isOk;
35693
+ if( !isOk ){
35694
+ static const char zDL[] = "\342\225\255\342\224\200";
35695
+ static const char zDR[] = "\342\224\200\342\225\256";
35696
+ static const char zUL[] = "\342\225\260\342\224\200";
35697
+ static const char zUR[] = "\342\224\200\342\225\257";
35698
+ static const char zLine[] = "\342\224\200\342\224\200\342\224\200"
35699
+ "\342\224\200\342\224\200\342\224\200"
35700
+ "\342\224\200\342\224\200\342\224\200"
35701
+ "\342\224\200\342\224\200\342\224\200"
35702
+ "\342\224\200\342\224\200";
3504235703
sqlite3_fprintf(stderr,
3504335704
"%s:%lld: .check failed for testcase %s\n",
3504435705
p->zInFile, iStart, p->zTestcase);
3504535706
p->nTestErr++;
35046
- sqlite3_fprintf(stderr, "Expected: [%s]\n", zPattern);
35047
- sqlite3_fprintf(stderr, "Got: [%s]\n", zTest);
35707
+ if( sqlite3_strglob("*\n", zPattern)==0 ){
35708
+ sqlite3_fprintf(stderr, "%s%s Expected %s%s\n%s%s%s Expected %s%s\n",
35709
+ zDL, zLine+9, zLine+9, zDR,
35710
+ zPattern,
35711
+ zUL, zLine+9, zLine+9, zUR);
35712
+ }else{
35713
+ sqlite3_fprintf(stderr, "Expected: [%s]\n", zPattern);
35714
+ }
35715
+ if( sqlite3_strglob("*\n", zTest)==0 ){
35716
+ sqlite3_fprintf(stderr, "%s%s Got %s%s\n%s%s%s Got %s%s\n",
35717
+ zDL, zLine+3, zLine, zDR,
35718
+ zTest,
35719
+ zUL, zLine+3, zLine, zUR);
35720
+ }else{
35721
+ sqlite3_fprintf(stderr, "Got: [%s]\n", zTest);
35722
+ }
3504835723
}
35049
- if( zPattern!=zCheck ){
35050
- sqlite3_free(zPattern);
35051
- }
35724
+ sqlite3_free(zToFree);
3505235725
if( !bKeep ){
3505335726
output_reset(p);
3505435727
p->zTestcase[0] = 0;
3505535728
}
3505635729
return 0;
@@ -35151,11 +35824,11 @@
3515135824
** DOT-COMMAND: .testcase
3515235825
** USAGE: .testcase [OPTIONS] NAME
3515335826
**
3515435827
** Start a new test case identified by NAME. All output
3515535828
** through the next ".check" command is captured for comparison. See the
35156
-** ".check" command for additional informatioon.
35829
+** ".check" command for additional information.
3515735830
**
3515835831
** Options:
3515935832
** --error-prefix TEXT Change error message prefix text to TEXT
3516035833
*/
3516135834
static int dotCmdTestcase(ShellState *p){
@@ -35172,11 +35845,11 @@
3517235845
dotCmdError(p, i, "missing argument", 0);
3517335846
return 1;
3517435847
}
3517535848
free(p->zErrPrefix);
3517635849
i++;
35177
- p->zErrPrefix = azArg[i][0]==0 ? 0 : strdup(azArg[i]);
35850
+ p->zErrPrefix = (azArg[i] && azArg[i][0]) ? strdup(azArg[i]) : 0;
3517835851
}else if( zName ){
3517935852
dotCmdError(p, i, "unknown option", 0);
3518035853
return 1;
3518135854
}else{
3518235855
zName = azArg[i];
@@ -35329,11 +36002,148 @@
3532936002
p->mElse &= ~(1<<p->nIfLevel);
3533036003
p->mIfHasBeenTrue &= ~(1<<p->nIfLevel);
3533136004
return 0;
3533236005
}
3533336006
36007
+/*
36008
+** DOT-COMMAND: .eqp
36009
+** USAGE: .eqp EQPMODE [>OUTPUTFILE]
36010
+**
36011
+** The .eqp command enables or disables the automatic display of EXPLAIN
36012
+** output for each SQL statement evaluated. The required EQPMODE argument
36013
+** may be one of the following:
36014
+**
36015
+** full Show both EXPLAIN QUERY PLAN and EXPLAIN output.
36016
+**
36017
+** off Disable all explain output.
36018
+**
36019
+** on Show EXPLAIN QUERY PLAN output only.
36020
+**
36021
+** trace Like "full" but also enable VDBE tracing using
36022
+** PRAGMA vdbe_trace=ON. This option only works if the
36023
+** CLI is compiled with -DSQLITE_DEBUG. The trace output
36024
+** always appears on stdout and is not redirected to a file.
36025
+**
36026
+** trigger Like "full" but also show EXPLAIN output for trigger
36027
+** subprograms.
36028
+**
36029
+** The EQPMODE maybe be optionally followed by a filename. If a file is
36030
+** specified, with or without a single leading ">", then the file is
36031
+** deleted and all subsequent explain output is appended to that file.
36032
+** If the filename begins with ">>" then the content of the file is retained
36033
+** and all output is appended. If not redirection argument is provided,
36034
+** output redirection is cancelled. The ability to redirect is not available
36035
+** for --safe mode.
36036
+*/
36037
+static int dotCmdEqp(ShellState *p){
36038
+ int nArg = p->dot.nArg; /* Number of arguments */
36039
+ char **azArg = p->dot.azArg; /* Argument list */
36040
+ if( nArg==2 || nArg==3 ){
36041
+ int isTrace = 0;
36042
+ if( p->db ) sqlite3_db_config(p->db, SQLITE_DBCONFIG_VDBE_TRACE, 0,
36043
+ (int*)0);
36044
+ if( cli_strcmp(azArg[1],"full")==0 ){
36045
+ p->mode.autoEQP = AUTOEQP_full;
36046
+ }else if( cli_strcmp(azArg[1],"trigger")==0 ){
36047
+ p->mode.autoEQP = AUTOEQP_trigger;
36048
+ }else if( cli_strcmp(azArg[1],"trace")==0 ){
36049
+#ifdef SQLITE_DEBUG
36050
+ p->mode.autoEQP = AUTOEQP_full;
36051
+ if( p->db==0 ){
36052
+ open_db(p, 0);
36053
+ sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1",0,0,0);
36054
+ }
36055
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_VDBE_TRACE, 1, (int*)0);
36056
+ isTrace = 1;
36057
+#else
36058
+ eputz("\".eqp trace\" is only available in debug builds\n");
36059
+ return 1;
36060
+#endif
36061
+ }else{
36062
+ p->mode.autoEQP = (u8)booleanValue(azArg[1]);
36063
+ }
36064
+ free(p->zEqpFile);
36065
+ if( nArg==3 ){
36066
+ const char *zOut = azArg[2];
36067
+ int bAppend = 0;
36068
+ failIfSafeMode(p, "cannot redirect .eqp output in safe mode");
36069
+ if( zOut[0]=='>' ) zOut++;
36070
+ if( zOut[0]=='>' ){ bAppend = 1; zOut++; }
36071
+ p->zEqpFile = strdup(zOut);
36072
+ if( !bAppend ){
36073
+ (void)shellDeleteFile(p->zEqpFile, 0);
36074
+ }
36075
+ if( isTrace ){
36076
+ cli_printf(p->out, "WARNING: trace output will not be redirected\n");
36077
+ }
36078
+ }else{
36079
+ p->zEqpFile = 0;
36080
+ }
36081
+ }else{
36082
+ eputz("Usage: .eqp off|on|trace|trigger|full [OUTPUTFILE]\n");
36083
+ return 1;
36084
+ }
36085
+ return 0;
36086
+}
3533436087
36088
+
36089
+/*
36090
+** DOT-COMMAND: .safe
36091
+** USAGE: .safe
36092
+**
36093
+** This command puts the CLI into "safe mode". This command cannot be
36094
+** undone. The only way to restore full capabilities is to exit and
36095
+** restart the CLI.
36096
+**
36097
+** Safe mode restricts SQL statements and dot-commands so that no
36098
+** changes may be made to the filesystem other than writing to database
36099
+** files that are already open.
36100
+**
36101
+** * The .open command is blocked unless the database is ":memory:"
36102
+** or the --hexdb option is used.
36103
+** * The ATTACH command of SQL may not be used
36104
+** * SQL functions with side effects (ex: writefile()) are blocked.
36105
+** * The ".shell" and ".system" dot-commands are blocked.
36106
+** * Dot-command like ".archive", ".backup", ".load", ".log", ".save"
36107
+** are blocked.
36108
+** * Other commands with deleterious side effects are blocked.
36109
+**
36110
+** Unsafe actions might be simply blocked, or the CLI might issue an error
36111
+** and exit immediately.
36112
+**
36113
+** Safe mode does not prevent harm to database files that are already open.
36114
+** An attacker can still delete content and even use commands like
36115
+** "PRAGMA writable_schema=ON" to corrupt a database file that is already
36116
+** open. Safe mode only blocks access to other previously unopened files.
36117
+**
36118
+** CAUTION: If third-party extensions with system side effects have been
36119
+** loaded prior to the .safe command, the CLI has no knowledge of those
36120
+** extensions and does not know to block them. Unsafe actions might still
36121
+** be possible using those third-party extension.
36122
+*/
36123
+static int dotCmdSafe(ShellState *p){
36124
+ int i;
36125
+ p->bSafeMode = 1;
36126
+ p->bSafeModePersist = 1;
36127
+#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
36128
+ if( p->db ) sqlite3_enable_load_extension(p->db, 0);
36129
+#endif
36130
+ for(i=0; i<ArraySize(p->aAuxDb); i++){
36131
+ sqlite3 *db = p->aAuxDb[i].db;
36132
+ if( db==0 ) continue;
36133
+#ifndef SQLITE_OMIT_VIRTUALTABLE
36134
+ sqlite3_create_module(db, "fsdir", 0, 0);
36135
+ sqlite3_create_module(db, "zipfile", 0, 0);
36136
+#endif
36137
+ sqlite3_create_function(db, "writefile", -1, 0, 0, 0, 0, 0);
36138
+ sqlite3_create_function(db, "zipfile", -1, 0, 0, 0, 0, 0);
36139
+ sqlite3_create_function(db, "tryeval", -1, 0, 0, 0, 0, 0);
36140
+ sqlite3_create_function(db, "expire", 1, 0, 0, 0, 0, 0);
36141
+ sqlite3_create_function(db, "expire", 2, 0, 0, 0, 0, 0);
36142
+ }
36143
+ return 0;
36144
+}
3533536145
3533636146
/*
3533736147
** Enlarge the space allocated in p->dot so that it can hold more
3533836148
** than nArg parsed command-line arguments.
3533936149
*/
@@ -35344,11 +36154,10 @@
3534436154
p->dot.aiOfst = realloc(p->dot.aiOfst,p->dot.nAlloc*sizeof(int));
3534536155
shell_check_oom(p->dot.aiOfst);
3534636156
p->dot.abQuot = realloc(p->dot.abQuot,p->dot.nAlloc);
3534736157
shell_check_oom(p->dot.abQuot);
3534836158
}
35349
-
3535036159
3535136160
/*
3535236161
** Parse input line zLine up into individual arguments. Retain the
3535336162
** parse in the p->dot substructure.
3535436163
*/
@@ -35768,21 +36577,25 @@
3576836577
{ "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
3576936578
{ "reverse_scanorder", SQLITE_DBCONFIG_REVERSE_SCANORDER },
3577036579
{ "stmt_scanstatus", SQLITE_DBCONFIG_STMT_SCANSTATUS },
3577136580
{ "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
3577236581
{ "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA },
36582
+#ifdef SQLITE_DEBUG
36583
+ { "vdbe_trace", SQLITE_DBCONFIG_VDBE_TRACE },
36584
+#endif
3577336585
{ "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
3577436586
};
3577536587
int ii, v;
3577636588
open_db(p, 0);
3577736589
for(ii=0; ii<ArraySize(aDbConfig); ii++){
3577836590
if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
3577936591
if( nArg>=3 ){
3578036592
if( aDbConfig[ii].op==SQLITE_DBCONFIG_FP_DIGITS ){
35781
- sqlite3_db_config(p->db, aDbConfig[ii].op, atoi(azArg[2]), 0);
36593
+ sqlite3_db_config(p->db, aDbConfig[ii].op, atoi(azArg[2]), (int*)0);
3578236594
}else{
35783
- sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
36595
+ sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]),
36596
+ (int*)0);
3578436597
}
3578536598
}
3578636599
sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
3578736600
if( aDbConfig[ii].op==SQLITE_DBCONFIG_FP_DIGITS ){
3578836601
cli_printf(p->out, "%19s %d\n", aDbConfig[ii].zName, v);
@@ -35804,10 +36617,11 @@
3580436617
}else
3580536618
#endif /* SQLITE_SHELL_HAVE_RECOVER */
3580636619
3580736620
if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbtotxt", n)==0 ){
3580836621
open_db(p, 0);
36622
+ sqlite3_exec(p->db, "PRAGMA page_count", 0, 0, 0);
3580936623
rc = shell_dbtotxt_command(p, nArg, azArg);
3581036624
}else
3581136625
3581236626
if( c=='d' && n==8 && cli_strncmp(azArg[0], "diskused", n)==0 ){
3581336627
const char *zSchema = 0;
@@ -35980,34 +36794,11 @@
3598036794
if( c=='e' && n==5 && cli_strcmp(azArg[0],"endif")==0 ){
3598136795
rc = dotCmdEndif(p);
3598236796
}else
3598336797
3598436798
if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
35985
- if( nArg==2 ){
35986
- if( p->mode.autoEQPtrace ){
35987
- if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
35988
- p->mode.autoEQPtrace = 0;
35989
- }
35990
- if( cli_strcmp(azArg[1],"full")==0 ){
35991
- p->mode.autoEQP = AUTOEQP_full;
35992
- }else if( cli_strcmp(azArg[1],"trigger")==0 ){
35993
- p->mode.autoEQP = AUTOEQP_trigger;
35994
-#ifdef SQLITE_DEBUG
35995
- }else if( cli_strcmp(azArg[1],"trace")==0 ){
35996
- p->mode.autoEQP = AUTOEQP_full;
35997
- p->mode.autoEQPtrace = 1;
35998
- open_db(p, 0);
35999
- sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
36000
- sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
36001
-#endif
36002
- }else{
36003
- p->mode.autoEQP = (u8)booleanValue(azArg[1]);
36004
- }
36005
- }else{
36006
- eputz("Usage: .eqp off|on|trace|trigger|full\n");
36007
- rc = 1;
36008
- }
36799
+ rc = dotCmdEqp(p);
3600936800
}else
3601036801
3601136802
#ifndef SQLITE_SHELL_FIDDLE
3601236803
if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
3601336804
if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) cli_exit(rc);
@@ -36191,14 +36982,15 @@
3619136982
3619236983
if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
3619336984
ShellState data;
3619436985
int doStats = 0;
3619536986
int hasStat[5];
36196
- int flgs = 0;
36987
+ int bIndent = 0;
3619736988
char *zSql;
3619836989
if( nArg==2 && optionMatch(azArg[1], "indent") ){
3619936990
nArg = 1;
36991
+ bIndent = 1;
3620036992
}
3620136993
if( nArg!=1 ){
3620236994
eputz("Usage: .fullschema ?--indent?\n");
3620336995
rc = 1;
3620436996
goto meta_command_exit;
@@ -36209,11 +37001,11 @@
3620937001
" (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
3621037002
" FROM sqlite_schema UNION ALL"
3621137003
" SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
3621237004
"WHERE type!='meta' AND sql NOTNULL"
3621337005
" AND name NOT LIKE 'sqlite__%%' ESCAPE '_' "
36214
- "ORDER BY x", flgs);
37006
+ "ORDER BY x", bIndent);
3621537007
memcpy(&data, p, sizeof(data));
3621637008
data.mode.spec.bTitles = QRF_No;
3621737009
data.mode.eMode = MODE_List;
3621837010
data.mode.spec.eText = QRF_TEXT_Plain;
3621937011
data.mode.spec.nCharLimit = 0;
@@ -37149,10 +37941,14 @@
3714937941
rc = 1;
3715037942
}
3715137943
close_db(pSrc);
3715237944
}else
3715337945
#endif /* !defined(SQLITE_SHELL_FIDDLE) */
37946
+
37947
+ if( c=='s' && cli_strcmp(azArg[0], "safe")==0 ){
37948
+ rc = dotCmdSafe(p);
37949
+ }else
3715437950
3715537951
if( c=='s' &&
3715637952
(cli_strncmp(azArg[0], "scanstats", n)==0 ||
3715737953
cli_strncmp(azArg[0], "scanstatus", n)==0)
3715837954
){
@@ -38109,17 +38905,17 @@
3810938905
** -LABEL Disable the named optimization
3811038906
**
3811138907
** INTEGER Mask of optimizations to disable
3811238908
*/
3811338909
case SQLITE_TESTCTRL_OPTIMIZATIONS: {
38114
- unsigned int curOpt; /* Current opt-disabled mask */
38115
- unsigned int newOpt; /* New opt-disabled mask */
38116
- unsigned int m; /* A working mask value */
38117
- sqlite3_uint64 mm; /* 64-bit working mask value */
38910
+ u64 curOpt; /* Current opt-disabled mask */
38911
+ u64 newOpt; /* New opt-disabled mask */
38912
+ u64 m; /* A working mask value */
3811838913
int ii, jj; /* Loop counters */
3811938914
int nOff; /* Number of disabled optimizations */
3812038915
const char *zName; /* Name of an optimization */
38916
+ int bQuiet = 0; /* Suppress output echo */
3812138917
3812238918
sqlite3_test_control(SQLITE_TESTCTRL_GETOPT, p->db, &curOpt);
3812338919
newOpt = curOpt;
3812438920
for(ii=2; ii<nArg; ii++){
3812538921
const char *z = azArg[ii];
@@ -38133,11 +38929,16 @@
3813338929
zLabel = z;
3813438930
}else{
3813538931
newOpt = (unsigned int)strtol(z,0,0);
3813638932
}
3813738933
if( useLabel ){
38138
- if( sqlite3_optimization_mask(zLabel,&mm)==SQLITE_NOTFOUND ){
38934
+ if( sqlite3_optimization_mask(zLabel,&m)==SQLITE_NOTFOUND ){
38935
+ if( strcmp(zLabel,"q")==0 ){
38936
+ /* Special -q option suppresses output */
38937
+ bQuiet = 1;
38938
+ continue;
38939
+ }
3813938940
cli_printf(stderr,
3814038941
"Error: no such optimization: \"%s\"\n", zLabel);
3814138942
cli_puts("Should be one of: All", stderr);
3814238943
for(jj=0; jj<32; jj++){
3814338944
zName = sqlite3_optimization_name(1ull<<jj);
@@ -38145,11 +38946,10 @@
3814538946
}
3814638947
cli_puts("\n", stderr);
3814738948
rc = 1;
3814838949
goto meta_command_exit;
3814938950
}
38150
- m = (u32)mm;
3815138951
if( useLabel=='+' ){
3815238952
newOpt &= ~m;
3815338953
}else{
3815438954
newOpt |= m;
3815538955
}
@@ -38156,33 +38956,35 @@
3815638956
}
3815738957
}
3815838958
if( curOpt!=newOpt ){
3815938959
sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,p->db,newOpt);
3816038960
}
38161
- for(ii=nOff=0, m=1; ii<32; ii++, m <<= 1){
38162
- if( m & newOpt ) nOff++;
38163
- }
38164
- if( nOff<12 ){
38165
- cli_puts("+All", p->out);
38166
- for(ii=0, m=1; ii<32; ii++, m <<= 1){
38167
- if( (newOpt & m)!=0
38168
- && (zName = sqlite3_optimization_name(m))!=0
38169
- ){
38170
- cli_printf(p->out, " -%s", zName);
38171
- }
38172
- }
38173
- }else{
38174
- cli_puts("-All", p->out);
38175
- for(ii=0, m=1; ii<32; ii++, m <<= 1){
38176
- if( (newOpt & m)==0
38177
- && (zName = sqlite3_optimization_name(m))!=0
38178
- ){
38179
- cli_printf(p->out, " +%s", zName);
38180
- }
38181
- }
38182
- }
38183
- cli_puts("\n", p->out);
38961
+ if( !bQuiet ){
38962
+ for(ii=nOff=0, m=1; ii<64; ii++, m <<= 1){
38963
+ if( m & newOpt ) nOff++;
38964
+ }
38965
+ if( nOff<12 ){
38966
+ cli_puts("+All", p->out);
38967
+ for(ii=0, m=1; ii<64; ii++, m <<= 1){
38968
+ if( (newOpt & m)!=0
38969
+ && (zName = sqlite3_optimization_name(m))!=0
38970
+ ){
38971
+ cli_printf(p->out, " -%s", zName);
38972
+ }
38973
+ }
38974
+ }else{
38975
+ cli_puts("-All", p->out);
38976
+ for(ii=0, m=1; ii<64; ii++, m <<= 1){
38977
+ if( (newOpt & m)==0
38978
+ && (zName = sqlite3_optimization_name(m))!=0
38979
+ ){
38980
+ cli_printf(p->out, " +%s", zName);
38981
+ }
38982
+ }
38983
+ }
38984
+ cli_puts("\n", p->out);
38985
+ }
3818438986
rc2 = isOk = 3;
3818538987
break;
3818638988
}
3818738989
3818838990
/* sqlite3_test_control(int, db, int) */
@@ -38758,20 +39560,20 @@
3875839560
}else{
3875939561
p->eRestoreState = 7;
3876039562
}
3876139563
break;
3876239564
};
38763
-
39565
+
3876439566
case 1: {
3876539567
int bIsDump = 0;
3876639568
const char *zExpect = "BEGIN TRANSACTION;";
3876739569
assert( strlen(zExpect)==18 );
3876839570
if( memcmp(zSql, zExpect, 19)==0 ){
3876939571
/* Now check if the database is empty. */
3877039572
const char *zQuery = "SELECT 1 FROM sqlite_schema LIMIT 1";
3877139573
sqlite3_stmt *pStmt = 0;
38772
-
39574
+
3877339575
bIsDump = 1;
3877439576
shellPrepare(p->db, &rc, zQuery, &pStmt);
3877539577
if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
3877639578
bIsDump = 0;
3877739579
}
@@ -38780,26 +39582,26 @@
3878039582
if( bIsDump && rc==SQLITE_OK ){
3878139583
int bDefense = 0;
3878239584
int bDqsDdl = 0;
3878339585
sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense);
3878439586
sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl);
38785
- sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
38786
- sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, 0);
39587
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, (int*)0);
39588
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, (int*)0);
3878739589
p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0);
3878839590
}else{
3878939591
p->eRestoreState = 7;
3879039592
}
3879139593
break;
3879239594
}
38793
-
39595
+
3879439596
default: {
3879539597
if( sqlite3_get_autocommit(p->db) ){
3879639598
if( (p->eRestoreState & 2) ){
38797
- sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, 0);
39599
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, (int*)0);
3879839600
}
3879939601
if( (p->eRestoreState & 4) ){
38800
- sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, 0);
39602
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, (int*)0);
3880139603
}
3880239604
p->eRestoreState = 7;
3880339605
}
3880439606
break;
3880539607
}
@@ -39402,10 +40204,11 @@
3940240204
" -nullvalue TEXT set text string for NULL values. Default ''\n"
3940340205
" -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
3940440206
" -pcachetrace trace all page cache operations\n"
3940540207
" -quote set '.mode quote'\n"
3940640208
" -readonly open the database read-only\n"
40209
+ " -runtests SCRIPT... Run multiple *.sql test script in subprocesses\n"
3940740210
" -safe enable safe-mode\n"
3940840211
" -screenwidth N use N as the default screenwidth \n"
3940940212
" -separator SEP set output column separator. Default: '|'\n"
3941040213
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
3941140214
" -sorterref SIZE sorter references threshold size\n"
@@ -39442,10 +40245,131 @@
3944240245
sputz(stdout, "WARNING: attempt to configure SQLite after"
3944340246
" initialization.\n");
3944440247
}
3944540248
}
3944640249
40250
+/*
40251
+** Run a copy of this program as a subprocess
40252
+*/
40253
+static void runShellSubprocess(
40254
+ const char *zProg,
40255
+ const char *zScript,
40256
+ int *pNErr,
40257
+ int *pNTest
40258
+){
40259
+ FILE *in;
40260
+ char *zCmd;
40261
+ const char *zTail;
40262
+ char zIn[1000];
40263
+ zTail = strrchr(zScript, '/');
40264
+ if( zTail ){
40265
+ zTail++;
40266
+ }else{
40267
+ zTail = zScript;
40268
+ }
40269
+#ifdef _WIN32
40270
+ {
40271
+ const char *zBackslash = strrchr(zTail, '\\');
40272
+ if( zBackslash ) zTail = zBackslash+1;
40273
+ }
40274
+#endif
40275
+ sqlite3_fprintf(stdout, "%-24s ", zTail);
40276
+ fflush(stdout);
40277
+ if( !isScriptFile(zScript,0) ){
40278
+ sqlite3_fprintf(stdout, "not an SQL script\n");
40279
+ (*pNErr)++;
40280
+ return;
40281
+ }
40282
+#ifdef _WIN32
40283
+ /* The command runs as "cmd.exe /c COMMAND". If COMMAND starts with a
40284
+ ** double-quote and contains more than two of them, then cmd.exe removes
40285
+ ** the first and the last double-quote before doing anything else.
40286
+ ** The extra pair of quotes around the whole command is there to be
40287
+ ** removed, so that the quotes on the individual arguments survive. */
40288
+ zCmd = sqlite3_mprintf("\"\"%s\" \"%s\" 2>NUL\"", zProg, zScript);
40289
+#else
40290
+ zCmd = sqlite3_mprintf("\"%s\" \"%s\" 2>/dev/null", zProg, zScript);
40291
+#endif
40292
+ in = sqlite3_popen(zCmd, "r");
40293
+ if( in==0 ){
40294
+ sqlite3_fprintf(stdout, "cannot start subprocess\n");
40295
+ sqlite3_free(zCmd);
40296
+ (*pNErr)++;
40297
+ return;
40298
+ }
40299
+ while( sqlite3_fgets(zIn, sizeof(zIn), in) ){
40300
+ int n = 0;
40301
+ int m = 0;
40302
+ char *zRunWith;
40303
+ zRunWith = strstr(zIn, " run with ");
40304
+ if( zRunWith==0 ) continue;
40305
+ if( zIn[0]<'0' || zIn[0]>'9' ) continue;
40306
+ if( zRunWith[10]<'0' || zRunWith[10]>'9' ) continue;
40307
+ n = atoi(zIn);
40308
+ m = atoi(&zRunWith[10]);
40309
+ if( m==0 ){
40310
+ sqlite3_fprintf(stdout, "tests %5d\n", n);
40311
+ }else{
40312
+ sqlite3_fprintf(stdout, "tests %5d errors %5d\n", n, m);
40313
+ }
40314
+ (*pNErr) += m;
40315
+ (*pNTest) += n;
40316
+ pclose(in);
40317
+ sqlite3_free(zCmd);
40318
+ return;
40319
+ }
40320
+ pclose(in);
40321
+ sqlite3_free(zCmd);
40322
+ sqlite3_fprintf(stdout, "did not complete\n");
40323
+ fflush(stdout);
40324
+ (*pNErr)++;
40325
+}
40326
+
40327
+#ifdef _WIN32
40328
+/*
40329
+** Run a subprocess for each script file that matches the wildcard zPattern.
40330
+** CMD.EXE does not expand wildcards, so the application must do it.
40331
+** Only the final path component of zPattern may contain wildcards.
40332
+** Return the number of scripts run.
40333
+*/
40334
+static int runShellSubprocessGlob(
40335
+ const char *zProg,
40336
+ const char *zPattern,
40337
+ int *pNErr,
40338
+ int *pNTest
40339
+){
40340
+ WIN32_FIND_DATAW sFind;
40341
+ HANDLE hFind;
40342
+ LPWSTR zW = sqlite3_win32_utf8_to_unicode(zPattern);
40343
+ int nDir;
40344
+ int nRun = 0;
40345
+ shell_check_oom(zW);
40346
+ for(nDir=(int)strlen(zPattern); nDir>0; nDir--){
40347
+ char c = zPattern[nDir-1];
40348
+ if( c=='/' || c=='\\' || c==':' ) break;
40349
+ }
40350
+ hFind = FindFirstFileW(zW, &sFind);
40351
+ sqlite3_free(zW);
40352
+ if( hFind==INVALID_HANDLE_VALUE ) return 0;
40353
+ do{
40354
+ char *zName, *zPath;
40355
+ if( sFind.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) continue;
40356
+ zName = sqlite3_win32_unicode_to_utf8(sFind.cFileName);
40357
+ zPath = sqlite3_mprintf("%.*s%s", nDir, zPattern, zName);
40358
+ shell_check_oom(zPath);
40359
+ if( isScriptFile(zPath,0) ){ /* Also rejects 8.3-name false matches */
40360
+ runShellSubprocess(zProg, zPath, pNErr, pNTest);
40361
+ nRun++;
40362
+ }
40363
+ sqlite3_free(zPath);
40364
+ sqlite3_free(zName);
40365
+ }while( FindNextFileW(hFind, &sFind) );
40366
+ FindClose(hFind);
40367
+ return nRun;
40368
+}
40369
+#endif
40370
+
3944740371
#if HAVE_EDITLINE
3944840372
/*
3944940373
** https://sqlite.org/forum/forumpost/aad7a634916ff050:
3945040374
**
3945140375
** Calling setlocale(LC_...,"") is required to get libedit to accept
@@ -39462,11 +40386,11 @@
3946240386
*/
3946340387
static void main_init(ShellState *p) {
3946440388
memset(p, 0, sizeof(*p));
3946540389
p->pAuxDb = &p->aAuxDb[0];
3946640390
p->shellFlgs = SHFLG_Lookaside;
39467
- sqlite3_config(SQLITE_CONFIG_LOG, shellLog, p);
40391
+ sqlite3_config(SQLITE_CONFIG_LOG, shellLog, (void*)p);
3946840392
#if !defined(SQLITE_SHELL_FIDDLE)
3946940393
verify_uninitialized();
3947040394
#endif
3947140395
sqlite3_config(SQLITE_CONFIG_URI, 1);
3947240396
sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
@@ -39622,10 +40546,11 @@
3962240546
int readStdin = 1;
3962340547
int noInit = 0; /* Do not read ~/.sqliterc if true */
3962440548
int nCmd = 0;
3962540549
int nOptsEnd = argc;
3962640550
int bEnableVfstrace = 0;
40551
+ int bTestMode = 0; /* --runtests option */
3962740552
char **azCmd = 0;
3962840553
int *aiCmd = 0;
3962940554
const char *zVfs = 0; /* Value of -vfs command-line option */
3963040555
setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
3963140556
@@ -39716,11 +40641,15 @@
3971640641
#endif
3971740642
for(i=1; i<argc; i++){
3971840643
char *z;
3971940644
z = argv[i];
3972040645
if( z[0]!='-' || i>nOptsEnd ){
39721
- if( data.aAuxDb->zDbFilename==0 && !isScriptFile(z,1) ){
40646
+ if( data.aAuxDb->zDbFilename==0
40647
+ && !bTestMode
40648
+ && (z[0]!='.' || !(z[1]>='a' && z[1]<='z'))
40649
+ && !isScriptFile(z,1)
40650
+ ){
3972240651
data.aAuxDb->zDbFilename = z;
3972340652
}else{
3972440653
/* Excess arguments are interpreted as SQL (or dot-commands) and
3972540654
** mean that nothing is read from stdin */
3972640655
readStdin = 0;
@@ -39887,10 +40816,12 @@
3988740816
}else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
3988840817
/* skip over the argument */
3988940818
i++;
3989040819
}else if( cli_strcmp(z,"-cmdline-edit")==0 ){
3989140820
shellCmdLineEdit = booleanValue(cmdline_option_value(argc,argv,++i));
40821
+ }else if( cli_strcmp(z,"-runtests")==0 ){
40822
+ bTestMode = 1;
3989240823
}else if( cli_strcmp(z,"-test-argv")==0 ){
3989340824
/* Undocumented test option. Print the values in argv[] and exit.
3989440825
** Use this to verify that any translation of the argv[], for example
3989540826
** on Windows that receives wargv[] from the OS and must convert
3989640827
** to UTF8 prior to calling this routine. */
@@ -39901,19 +40832,48 @@
3990140832
return 0;
3990240833
}else if( cli_strcmp(z,"-test-parse")==0 ){
3990340834
/* Undocumented test option. Read input normally and process all
3990440835
** dot-commands. But do not process any SQL. Instead, whenever input
3990540836
** text would have been processed as SQL, print a one-line summary of
39906
- ** the input. This is used by test script to verify that the end-of-SQL
40837
+ ** the input. This is used by test scripts to verify that the end-of-SQL
3990740838
** parsing logic is working correctly. */
3990840839
data.bTestParse = 1;
3990940840
}
3991040841
}
3991140842
#ifndef SQLITE_SHELL_FIDDLE
3991240843
if( !bEnableVfstrace ) verify_uninitialized();
3991340844
#endif
3991440845
40846
+#ifndef SQLITE_SHELL_FIDDLE
40847
+ if( bTestMode ){
40848
+ int nErr = 0;
40849
+ int nTest = 0;
40850
+ int nScript = 0;
40851
+#ifdef _WIN32
40852
+ /* Child processes inherit this. Without it, a crash in a test script
40853
+ ** might raise a dialog box that stalls the run until it is dismissed. */
40854
+ SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
40855
+#endif
40856
+ for(i=0; i<nCmd; i++){
40857
+#ifdef _WIN32
40858
+ if( strpbrk(azCmd[i], "*?") ){
40859
+ int n = runShellSubprocessGlob(argv[0], azCmd[i], &nErr, &nTest);
40860
+ if( n>0 ){
40861
+ nScript += n;
40862
+ continue;
40863
+ }
40864
+ }
40865
+#endif
40866
+ runShellSubprocess(argv[0], azCmd[i], &nErr, &nTest);
40867
+ nScript++;
40868
+ }
40869
+ sqlite3_fprintf(stdout, "%-24s tests %5d errors %5d scripts %5d\n",
40870
+ "TOTAL", nTest, nErr, nScript);
40871
+ rc = nErr>0;
40872
+ goto shell_main_exit;
40873
+ }
40874
+#endif
3991540875
3991640876
#ifdef SQLITE_SHELL_INIT_PROC
3991740877
{
3991840878
/* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
3991940879
** of a C-function that will perform initialization actions on SQLite that
@@ -40202,10 +41162,12 @@
4020241162
#endif
4020341163
}else if( cli_strcmp(z,"-safe")==0 ){
4020441164
data.bSafeMode = data.bSafeModePersist = 1;
4020541165
}else if( cli_strcmp(z,"-unsafe-testing")==0
4020641166
|| cli_strcmp(z,"-unsafe")==0 ){
41167
+ /* Acted upon in first pass. */
41168
+ }else if( cli_strcmp(z,"-runtests")==0 ){
4020741169
/* Acted upon in first pass. */
4020841170
}else if( cli_strcmp(z,"-test-parse")==0 ){
4020941171
/* Acted upon in first pass. */
4021041172
}else{
4021141173
cli_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
@@ -40230,16 +41192,17 @@
4023041192
res = process_input(&data, azCmd[i]);
4023141193
fclose(data.in);
4023241194
}
4023341195
data.in = inSaved;
4023441196
data.lineno = savedLineno;
40235
- if( res ) i = nCmd;
41197
+ if( res && bail_on_error ) i = nCmd;
4023641198
}else if( azCmd[i][0]=='.' ){
4023741199
char *zErrCtx = malloc( 64 );
4023841200
shell_check_oom(zErrCtx);
4023941201
sqlite3_snprintf(64,zErrCtx,"argv[%i]:",aiCmd[i]);
4024041202
data.zInFile = "<cmdline>";
41203
+ free(data.zErrPrefix);
4024141204
data.zErrPrefix = zErrCtx;
4024241205
rc = do_meta_command(azCmd[i], &data);
4024341206
free(data.zErrPrefix);
4024441207
data.zErrPrefix = 0;
4024541208
if( rc ){
@@ -40350,10 +41313,11 @@
4035041313
modeFree(&data.aSavedModes[ii].mode);
4035141314
free(data.aSavedModes[ii].zTag);
4035241315
}
4035341316
free(data.aSavedModes);
4035441317
}
41318
+ free(data.zEqpFile);
4035541319
free(data.zErrPrefix);
4035641320
free(data.zNonce);
4035741321
free(data.dot.zCopy);
4035841322
free(data.dot.azArg);
4035941323
free(data.dot.aiOfst);
@@ -40456,13 +41420,15 @@
4045641420
** https://sqlite.org/forum/forumpost/0b41a25d65
4045741421
*/
4045841422
cli_puts("Rolling back in-progress transaction.\n", stdout);
4045941423
sqlite3_exec(globalDb,"ROLLBACK", 0, 0, 0);
4046041424
}
40461
- rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
41425
+ rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1,
41426
+ (int*)0);
4046241427
if( 0==rc ) sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
40463
- sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
41428
+ sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0,
41429
+ (int*)0);
4046441430
}
4046541431
}
4046641432
4046741433
/*
4046841434
** Uses the current database's VFS xRead to stream the db file's
4046941435
--- extsrc/shell.c
+++ extsrc/shell.c
@@ -25,10 +25,11 @@
25 ** ext/misc/sqlar.c
26 ** ext/misc/sqlite3_stdio.c
27 ** ext/misc/sqlite3_stdio.h
28 ** ext/misc/stmtrand.c
29 ** ext/misc/strdup.c
 
30 ** ext/misc/uint.c
31 ** ext/misc/vfstrace.c
32 ** ext/misc/windirent.h
33 ** ext/misc/zipfile.c
34 ** ext/qrf/qrf.c
@@ -1655,10 +1656,16 @@
1655 n = (n+8)&~7;
1656 }else if( z[0]=='\n' || z[0]=='\r' ){
1657 nNL++;
1658 if( n>mx ) mx = n;
1659 n = 0;
 
 
 
 
 
 
1660 }
1661 z++;
1662 }
1663 }else if( (0x80&z[0])==0 ){
1664 n++;
@@ -2009,10 +2016,11 @@
2009 */
2010 static int qrfTitleLimit(char *zIn, int N){
2011 unsigned char *z = (unsigned char*)zIn;
2012 int n = 0;
2013 unsigned char *zEllipsis = 0;
 
2014 while( 1 /*exit-by-break*/ ){
2015 if( z[0]<' ' ){
2016 int k;
2017 if( z[0]==0 ){
2018 zEllipsis = 0;
@@ -2025,24 +2033,28 @@
2025 z[0] = ' ';
2026 }else{
2027 z++;
2028 }
2029 }else if( (0x80&z[0])==0 ){
2030 if( n>=(N-3) && zEllipsis==0 ) zEllipsis = z;
2031 if( n==N ){ z[0] = 0; break; }
2032 n++;
2033 z++;
2034 }else{
2035 int u = 0;
2036 int len = sqlite3_qrf_decode_utf8(z, &u);
2037 if( n+len>(N-3) && zEllipsis==0 ) zEllipsis = z;
2038 if( n+len>N ){ z[0] = 0; break; }
 
2039 z += len;
2040 n += sqlite3_qrf_wcwidth(u);
2041 }
2042 }
2043 if( zEllipsis && N>=3 ) memcpy(zEllipsis,"...",4);
 
 
 
2044 return n;
2045 }
2046
2047
2048 /*
@@ -2178,11 +2190,16 @@
2178 }
2179 }
2180 break;
2181 }
2182 case SQLITE_NULL: {
2183 sqlite3_str_appendall(pOut, p->spec.zNull);
 
 
 
 
 
2184 break;
2185 }
2186 case SQLITE_TEXT: {
2187 const char *zTxt = (const char*)sqlite3_column_text(p->pStmt,iCol);
2188 qrfEncodeText(p, pOut, zTxt);
@@ -2240,11 +2257,12 @@
2240
2241 /*
2242 ** Store string zUtf to pOut as w characters. If w is negative,
2243 ** then right-justify the text. W is the width in display characters, not
2244 ** in bytes. Double-width unicode characters count as two characters.
2245 ** VT100 escape sequences count as zero. And so forth.
 
2246 */
2247 static void qrfWidthPrint(Qrf *p, sqlite3_str *pOut, int w, const char *zUtf){
2248 const unsigned char *a = (const unsigned char*)zUtf;
2249 static const int mxW = 10000000;
2250 unsigned char c;
@@ -2270,10 +2288,14 @@
2270 }
2271 i += len;
2272 n += x;
2273 }else if( c==0x1b && (k = qrfIsVt100(&a[i]))>0 ){
2274 i += k;
 
 
 
 
2275 }else if( n>=aw ){
2276 break;
2277 }else{
2278 n++;
2279 i++;
@@ -3865,11 +3887,11 @@
3865 if( p->spec.zFpFmt==0 ) p->spec.zFpFmt = "%!0.17g";
3866 break;
3867 }
3868 case QRF_STYLE_Html: {
3869 p->spec.eText = QRF_TEXT_Html;
3870 p->spec.zNull = "null";
3871 break;
3872 }
3873 case QRF_STYLE_Insert: {
3874 p->spec.eText = QRF_TEXT_Sql;
3875 p->spec.zNull = "NULL";
@@ -6314,14 +6336,15 @@
6314 z = sqlite3_malloc64( (sqlite3_int64)p->nDigit+8 );
6315 if( z==0 ){
6316 sqlite3_result_error_nomem(pCtx);
6317 return;
6318 }
 
 
 
 
6319 i = 0;
6320 if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
6321 p->sign = 0;
6322 }
6323 if( p->sign ){
6324 z[0] = '-';
6325 i = 1;
6326 }
6327 n = p->nDigit - p->nFrac;
@@ -7205,45 +7228,62 @@
7205 char c;
7206 while( nc-- > 0 && (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s;
7207 return s;
7208 }
7209
7210 /* Decode base64 text into a byte buffer. */
 
 
 
 
 
 
 
7211 static u8* fromBase64( char *pIn, int ncIn, u8 *pOut ){
7212 if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
7213 while( ncIn>0 && *pIn!=PAD_CHAR ){
7214 static signed char nboi[] = { 0, 0, 1, 2, 3 };
7215 char *pUse = skipNonB64(pIn, ncIn);
7216 unsigned long qv = 0L;
7217 int nti, nbo, nac;
7218 ncIn -= (pUse - pIn);
7219 pIn = pUse;
7220 nti = (ncIn>4)? 4 : ncIn;
7221 ncIn -= nti;
7222 nbo = nboi[nti];
7223 if( nbo==0 ) break;
7224 for( nac=0; nac<4; ++nac ){
7225 char c = (nac<nti)? *pIn++ : b64Numerals[0];
7226 u8 bdp = BX_DV_PROTO(c);
7227 switch( bdp ){
7228 case ND:
7229 /* Treat dark non-digits as pad, but they terminate decode too. */
7230 ncIn = 0;
7231 deliberate_fall_through; /* FALLTHRU */
7232 case WS:
7233 /* Treat whitespace as pad and terminate this group.*/
7234 nti = nac;
7235 deliberate_fall_through; /* FALLTHRU */
7236 case PC:
7237 bdp = 0;
7238 --nbo;
7239 deliberate_fall_through; /* FALLTHRU */
7240 default: /* bdp is the digit value. */
7241 qv = qv<<6 | bdp;
 
 
 
 
 
 
 
 
7242 break;
7243 }
 
 
7244 }
 
 
7245 switch( nbo ){
7246 case 3:
7247 pOut[2] = (qv) & 0xff;
7248 deliberate_fall_through; /* FALLTHRU */
7249 case 2:
@@ -7867,11 +7907,11 @@
7867 { OPT_MASK(16), "PropagateConst" },
7868 { OPT_MASK(17), "MinMaxOpt" },
7869 { OPT_MASK(18), "SeekScan" },
7870 { OPT_MASK(19), "OmitOrderBy" },
7871 { OPT_MASK(20), "BloomFilter" },
7872 /* 21 currently unused */
7873 { OPT_MASK(22), "BalancedMerge" },
7874 { OPT_MASK(23), "ReleaseReg" },
7875 { OPT_MASK(24), "FlttnUnionAll" },
7876 { OPT_MASK(25), "IndexedExpr" },
7877 { OPT_MASK(26), "Coroutines" },
@@ -7880,10 +7920,11 @@
7880 { OPT_MASK(29), "OrderBySubq" },
7881 { OPT_MASK(29), "OrderBySubquery" }, /* Alias for prior */
7882 { OPT_MASK(30), "StarQuery" },
7883 { OPT_MASK(31), "ExistsToJoin" },
7884 { OPT_MASK(32), "UnionLimit" },
 
7885 /* Special names */
7886 { 0xffffffffffffffffULL, "All" },
7887 { 0x0000000000000000ULL, "None" },
7888 };
7889
@@ -8284,970 +8325,10 @@
8284 }
8285 return rc;
8286 }
8287
8288 /************************* End ext/misc/ieee754.c ********************/
8289 /************************* Begin ext/misc/series.c ******************/
8290 /*
8291 ** 2015-08-18, 2023-04-28
8292 **
8293 ** The author disclaims copyright to this source code. In place of
8294 ** a legal notice, here is a blessing:
8295 **
8296 ** May you do good and not evil.
8297 ** May you find forgiveness for yourself and forgive others.
8298 ** May you share freely, never taking more than you give.
8299 **
8300 *************************************************************************
8301 **
8302 ** This file demonstrates how to create a table-valued-function using
8303 ** a virtual table. This demo implements the generate_series() function
8304 ** which gives the same results as the eponymous function in PostgreSQL,
8305 ** within the limitation that its arguments are signed 64-bit integers.
8306 **
8307 ** Considering its equivalents to generate_series(start,stop,step): A
8308 ** value V[n] sequence is produced for integer n ascending from 0 where
8309 ** ( V[n] == start + n * step && sgn(V[n] - stop) * sgn(step) >= 0 )
8310 ** for each produced value (independent of production time ordering.)
8311 **
8312 ** All parameters must be either integer or convertable to integer.
8313 ** The start parameter is required.
8314 ** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
8315 ** The step parameter defaults to 1 and 0 is treated as 1.
8316 **
8317 ** Examples:
8318 **
8319 ** SELECT * FROM generate_series(0,100,5);
8320 **
8321 ** The query above returns integers from 0 through 100 counting by steps
8322 ** of 5. In other words, 0, 5, 10, 15, ..., 90, 95, 100. There are a total
8323 ** of 21 rows.
8324 **
8325 ** SELECT * FROM generate_series(0,100);
8326 **
8327 ** Integers from 0 through 100 with a step size of 1. 101 rows.
8328 **
8329 ** SELECT * FROM generate_series(20) LIMIT 10;
8330 **
8331 ** Integers 20 through 29. 10 rows.
8332 **
8333 ** SELECT * FROM generate_series(0,-100,-5);
8334 **
8335 ** Integers 0 -5 -10 ... -100. 21 rows.
8336 **
8337 ** SELECT * FROM generate_series(0,-1);
8338 **
8339 ** Empty sequence.
8340 **
8341 ** HOW IT WORKS
8342 **
8343 ** The generate_series "function" is really a virtual table with the
8344 ** following schema:
8345 **
8346 ** CREATE TABLE generate_series(
8347 ** value,
8348 ** start HIDDEN,
8349 ** stop HIDDEN,
8350 ** step HIDDEN
8351 ** );
8352 **
8353 ** The virtual table also has a rowid which is an alias for the value.
8354 **
8355 ** Function arguments in queries against this virtual table are translated
8356 ** into equality constraints against successive hidden columns. In other
8357 ** words, the following pairs of queries are equivalent to each other:
8358 **
8359 ** SELECT * FROM generate_series(0,100,5);
8360 ** SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
8361 **
8362 ** SELECT * FROM generate_series(0,100);
8363 ** SELECT * FROM generate_series WHERE start=0 AND stop=100;
8364 **
8365 ** SELECT * FROM generate_series(20) LIMIT 10;
8366 ** SELECT * FROM generate_series WHERE start=20 LIMIT 10;
8367 **
8368 ** The generate_series virtual table implementation leaves the xCreate method
8369 ** set to NULL. This means that it is not possible to do a CREATE VIRTUAL
8370 ** TABLE command with "generate_series" as the USING argument. Instead, there
8371 ** is a single generate_series virtual table that is always available without
8372 ** having to be created first.
8373 **
8374 ** The xBestIndex method looks for equality constraints against the hidden
8375 ** start, stop, and step columns, and if present, it uses those constraints
8376 ** to bound the sequence of generated values. If the equality constraints
8377 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
8378 ** xBestIndex returns a small cost when both start and stop are available,
8379 ** and a very large cost if either start or stop are unavailable. This
8380 ** encourages the query planner to order joins such that the bounds of the
8381 ** series are well-defined.
8382 **
8383 ** Update on 2024-08-22:
8384 ** xBestIndex now also looks for equality and inequality constraints against
8385 ** the value column and uses those constraints as additional bounds against
8386 ** the sequence range. Thus, a query like this:
8387 **
8388 ** SELECT value FROM generate_series($SA,$EA)
8389 ** WHERE value BETWEEN $SB AND $EB;
8390 **
8391 ** Is logically the same as:
8392 **
8393 ** SELECT value FROM generate_series(max($SA,$SB),min($EA,$EB));
8394 **
8395 ** Constraints on the value column can server as substitutes for constraints
8396 ** on the hidden start and stop columns. So, the following two queries
8397 ** are equivalent:
8398 **
8399 ** SELECT value FROM generate_series($S,$E);
8400 ** SELECT value FROM generate_series WHERE value BETWEEN $S and $E;
8401 **
8402 */
8403 /* #include "sqlite3ext.h" */
8404 SQLITE_EXTENSION_INIT1
8405 #include <assert.h>
8406 #include <string.h>
8407 #include <limits.h>
8408 #include <math.h>
8409
8410 #ifndef SQLITE_OMIT_VIRTUALTABLE
8411
8412 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
8413 ** serve as the underlying representation of a cursor that scans
8414 ** over rows of the result.
8415 **
8416 ** iOBase, iOTerm, and iOStep are the original values of the
8417 ** start=, stop=, and step= constraints on the query. These are
8418 ** the values reported by the start, stop, and step columns of the
8419 ** virtual table.
8420 **
8421 ** iBase, iTerm, iStep, and bDescp are the actual values used to generate
8422 ** the sequence. These might be different from the iOxxxx values.
8423 ** For example in
8424 **
8425 ** SELECT value FROM generate_series(1,11,2)
8426 ** WHERE value BETWEEN 4 AND 8;
8427 **
8428 ** The iOBase is 1, but the iBase is 5. iOTerm is 11 but iTerm is 7.
8429 ** Another example:
8430 **
8431 ** SELECT value FROM generate_series(1,15,3) ORDER BY value DESC;
8432 **
8433 ** The cursor initialization for the above query is:
8434 **
8435 ** iOBase = 1 iBase = 13
8436 ** iOTerm = 15 iTerm = 1
8437 ** iOStep = 3 iStep = 3 bDesc = 1
8438 **
8439 ** The actual step size is unsigned so that can have a value of
8440 ** +9223372036854775808 which is needed for querys like this:
8441 **
8442 ** SELECT value
8443 ** FROM generate_series(9223372036854775807,
8444 ** -9223372036854775808,
8445 ** -9223372036854775808)
8446 ** ORDER BY value ASC;
8447 **
8448 ** The setup for the previous query will be:
8449 **
8450 ** iOBase = 9223372036854775807 iBase = -1
8451 ** iOTerm = -9223372036854775808 iTerm = 9223372036854775807
8452 ** iOStep = -9223372036854775808 iStep = 9223372036854775808 bDesc = 0
8453 */
8454 /* typedef unsigned char u8; */
8455 typedef struct series_cursor series_cursor;
8456 struct series_cursor {
8457 sqlite3_vtab_cursor base; /* Base class - must be first */
8458 sqlite3_int64 iOBase; /* Original starting value ("start") */
8459 sqlite3_int64 iOTerm; /* Original terminal value ("stop") */
8460 sqlite3_int64 iOStep; /* Original step value */
8461 sqlite3_int64 iBase; /* Starting value to actually use */
8462 sqlite3_int64 iTerm; /* Terminal value to actually use */
8463 sqlite3_uint64 iStep; /* The step size */
8464 sqlite3_int64 iValue; /* Current value */
8465 u8 bDesc; /* iStep is really negative */
8466 u8 bDone; /* True if stepped past last element */
8467 u8 bLimit; /* There exists a limit clause */
8468 };
8469
8470 /*
8471 ** Computed the difference between two 64-bit signed integers using a
8472 ** convoluted computation designed to work around the silly restriction
8473 ** against signed integer overflow in C.
8474 */
8475 static sqlite3_uint64 span64(sqlite3_int64 a, sqlite3_int64 b){
8476 assert( a>=b );
8477 return (*(sqlite3_uint64*)&a) - (*(sqlite3_uint64*)&b);
8478 }
8479
8480 /*
8481 ** Add or substract an unsigned 64-bit integer from a signed 64-bit integer
8482 ** and return the new signed 64-bit integer.
8483 */
8484 static sqlite3_int64 add64(sqlite3_int64 a, sqlite3_uint64 b){
8485 sqlite3_uint64 x = *(sqlite3_uint64*)&a;
8486 x += b;
8487 return *(sqlite3_int64*)&x;
8488 }
8489 static sqlite3_int64 sub64(sqlite3_int64 a, sqlite3_uint64 b){
8490 sqlite3_uint64 x = *(sqlite3_uint64*)&a;
8491 x -= b;
8492 return *(sqlite3_int64*)&x;
8493 }
8494
8495 /*
8496 ** The seriesConnect() method is invoked to create a new
8497 ** series_vtab that describes the generate_series virtual table.
8498 **
8499 ** Think of this routine as the constructor for series_vtab objects.
8500 **
8501 ** All this routine needs to do is:
8502 **
8503 ** (1) Allocate the series_vtab object and initialize all fields.
8504 **
8505 ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
8506 ** result set of queries against generate_series will look like.
8507 */
8508 static int seriesConnect(
8509 sqlite3 *db,
8510 void *pUnused,
8511 int argcUnused, const char *const*argvUnused,
8512 sqlite3_vtab **ppVtab,
8513 char **pzErrUnused
8514 ){
8515 sqlite3_vtab *pNew;
8516 int rc;
8517
8518 /* Column numbers */
8519 #define SERIES_COLUMN_ROWID (-1)
8520 #define SERIES_COLUMN_VALUE 0
8521 #define SERIES_COLUMN_START 1
8522 #define SERIES_COLUMN_STOP 2
8523 #define SERIES_COLUMN_STEP 3
8524
8525 (void)pUnused;
8526 (void)argcUnused;
8527 (void)argvUnused;
8528 (void)pzErrUnused;
8529 rc = sqlite3_declare_vtab(db,
8530 "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
8531 if( rc==SQLITE_OK ){
8532 pNew = *ppVtab = sqlite3_malloc64( sizeof(*pNew) );
8533 if( pNew==0 ) return SQLITE_NOMEM;
8534 memset(pNew, 0, sizeof(*pNew));
8535 sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
8536 }
8537 return rc;
8538 }
8539
8540 /*
8541 ** This method is the destructor for series_cursor objects.
8542 */
8543 static int seriesDisconnect(sqlite3_vtab *pVtab){
8544 sqlite3_free(pVtab);
8545 return SQLITE_OK;
8546 }
8547
8548 /*
8549 ** Constructor for a new series_cursor object.
8550 */
8551 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
8552 series_cursor *pCur;
8553 (void)pUnused;
8554 pCur = sqlite3_malloc64( sizeof(*pCur) );
8555 if( pCur==0 ) return SQLITE_NOMEM;
8556 memset(pCur, 0, sizeof(*pCur));
8557 *ppCursor = &pCur->base;
8558 return SQLITE_OK;
8559 }
8560
8561 /*
8562 ** Destructor for a series_cursor.
8563 */
8564 static int seriesClose(sqlite3_vtab_cursor *cur){
8565 sqlite3_free(cur);
8566 return SQLITE_OK;
8567 }
8568
8569
8570 /*
8571 ** Advance a series_cursor to its next row of output.
8572 */
8573 static int seriesNext(sqlite3_vtab_cursor *cur){
8574 series_cursor *pCur = (series_cursor*)cur;
8575 if( pCur->iValue==pCur->iTerm ){
8576 pCur->bDone = 1;
8577 }else if( pCur->bDesc ){
8578 pCur->iValue = sub64(pCur->iValue, pCur->iStep);
8579 assert( pCur->iValue>=pCur->iTerm || pCur->bLimit );
8580 }else{
8581 pCur->iValue = add64(pCur->iValue, pCur->iStep);
8582 assert( pCur->iValue<=pCur->iTerm || pCur->bLimit );
8583 }
8584 return SQLITE_OK;
8585 }
8586
8587 /*
8588 ** Return values of columns for the row at which the series_cursor
8589 ** is currently pointing.
8590 */
8591 static int seriesColumn(
8592 sqlite3_vtab_cursor *cur, /* The cursor */
8593 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
8594 int i /* Which column to return */
8595 ){
8596 series_cursor *pCur = (series_cursor*)cur;
8597 sqlite3_int64 x = 0;
8598 switch( i ){
8599 case SERIES_COLUMN_START: x = pCur->iOBase; break;
8600 case SERIES_COLUMN_STOP: x = pCur->iOTerm; break;
8601 case SERIES_COLUMN_STEP: x = pCur->iOStep; break;
8602 default: x = pCur->iValue; break;
8603 }
8604 sqlite3_result_int64(ctx, x);
8605 return SQLITE_OK;
8606 }
8607
8608 #ifndef LARGEST_UINT64
8609 #define LARGEST_INT64 ((sqlite3_int64)0x7fffffffffffffffLL)
8610 #define LARGEST_UINT64 ((sqlite3_uint64)0xffffffffffffffffULL)
8611 #define SMALLEST_INT64 ((sqlite3_int64)0x8000000000000000LL)
8612 #endif
8613
8614 /*
8615 ** The rowid is the same as the value.
8616 */
8617 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
8618 series_cursor *pCur = (series_cursor*)cur;
8619 *pRowid = pCur->iValue;
8620 return SQLITE_OK;
8621 }
8622
8623 /*
8624 ** Return TRUE if the cursor has been moved off of the last
8625 ** row of output.
8626 */
8627 static int seriesEof(sqlite3_vtab_cursor *cur){
8628 series_cursor *pCur = (series_cursor*)cur;
8629 return pCur->bDone;
8630 }
8631
8632 /* True to cause run-time checking of the start=, stop=, and/or step=
8633 ** parameters. The only reason to do this is for testing the
8634 ** constraint checking logic for virtual tables in the SQLite core.
8635 */
8636 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
8637 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
8638 #endif
8639
8640 /*
8641 ** Return the number of steps between pCur->iBase and pCur->iTerm if
8642 ** the step width is pCur->iStep.
8643 */
8644 static sqlite3_uint64 seriesSteps(series_cursor *pCur){
8645 if( pCur->bDesc ){
8646 assert( pCur->iBase >= pCur->iTerm );
8647 return span64(pCur->iBase, pCur->iTerm)/pCur->iStep;
8648 }else{
8649 assert( pCur->iBase <= pCur->iTerm );
8650 return span64(pCur->iTerm, pCur->iBase)/pCur->iStep;
8651 }
8652 }
8653
8654 #if defined(SQLITE_ENABLE_MATH_FUNCTIONS) || defined(_WIN32)
8655 /*
8656 ** Case 1 (the most common case):
8657 ** The standard math library is available so use ceil() and floor() from there.
8658 */
8659 static double seriesCeil(double r){ return ceil(r); }
8660 static double seriesFloor(double r){ return floor(r); }
8661 #elif defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
8662 /*
8663 ** Case 2 (2nd most common): Use GCC/Clang builtins
8664 */
8665 static double seriesCeil(double r){ return __builtin_ceil(r); }
8666 static double seriesFloor(double r){ return __builtin_floor(r); }
8667 #else
8668 /*
8669 ** Case 3 (rarely happens): Use home-grown ceil() and floor() routines.
8670 */
8671 static double seriesCeil(double r){
8672 sqlite3_int64 x;
8673 if( r!=r ) return r;
8674 if( r<=(-4503599627370496.0) ) return r;
8675 if( r>=(+4503599627370496.0) ) return r;
8676 x = (sqlite3_int64)r;
8677 if( r==(double)x ) return r;
8678 if( r>(double)x ) x++;
8679 return (double)x;
8680 }
8681 static double seriesFloor(double r){
8682 sqlite3_int64 x;
8683 if( r!=r ) return r;
8684 if( r<=(-4503599627370496.0) ) return r;
8685 if( r>=(+4503599627370496.0) ) return r;
8686 x = (sqlite3_int64)r;
8687 if( r==(double)x ) return r;
8688 if( r<(double)x ) x--;
8689 return (double)x;
8690 }
8691 #endif
8692
8693 /* Convert a floating point value to its closest integer. Do so in
8694 ** a way that avoids 'outside the range of representable values' warnings
8695 ** from UBSAN.
8696 */
8697 static sqlite3_int64 seriesRealToI64(double r){
8698 if( r<-9223372036854774784.0 ) return SMALLEST_INT64;
8699 if( r>+9223372036854774784.0 ) return LARGEST_INT64;
8700 return (sqlite3_int64)r;
8701 }
8702
8703 /*
8704 ** This method is called to "rewind" the series_cursor object back
8705 ** to the first row of output. This method is always called at least
8706 ** once prior to any call to seriesColumn() or seriesRowid() or
8707 ** seriesEof().
8708 **
8709 ** The query plan selected by seriesBestIndex is passed in the idxNum
8710 ** parameter. (idxStr is not used in this implementation.) idxNum
8711 ** is a bitmask showing which constraints are available:
8712 **
8713 ** 0x0001: start=VALUE
8714 ** 0x0002: stop=VALUE
8715 ** 0x0004: step=VALUE
8716 ** 0x0008: descending order
8717 ** 0x0010: ascending order
8718 ** 0x0020: LIMIT VALUE
8719 ** 0x0040: OFFSET VALUE
8720 ** 0x0080: value=VALUE
8721 ** 0x0100: value>=VALUE
8722 ** 0x0200: value>VALUE
8723 ** 0x1000: value<=VALUE
8724 ** 0x2000: value<VALUE
8725 **
8726 ** This routine should initialize the cursor and position it so that it
8727 ** is pointing at the first row, or pointing off the end of the table
8728 ** (so that seriesEof() will return true) if the table is empty.
8729 */
8730 static int seriesFilter(
8731 sqlite3_vtab_cursor *pVtabCursor,
8732 int idxNum, const char *idxStrUnused,
8733 int argc, sqlite3_value **argv
8734 ){
8735 series_cursor *pCur = (series_cursor *)pVtabCursor;
8736 int iArg = 0; /* Arguments used so far */
8737 int i; /* Loop counter */
8738 sqlite3_int64 iMin = SMALLEST_INT64; /* Smallest allowed output value */
8739 sqlite3_int64 iMax = LARGEST_INT64; /* Largest allowed output value */
8740 sqlite3_int64 iLimit = 0; /* if >0, the value of the LIMIT */
8741 sqlite3_int64 iOffset = 0; /* if >0, the value of the OFFSET */
8742
8743 (void)idxStrUnused;
8744
8745 /* If any constraints have a NULL value, then return no rows.
8746 ** See ticket https://sqlite.org/src/info/fac496b61722daf2
8747 */
8748 for(i=0; i<argc; i++){
8749 if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
8750 goto series_no_rows;
8751 }
8752 }
8753
8754 /* Capture the three HIDDEN parameters to the virtual table and insert
8755 ** default values for any parameters that are omitted.
8756 */
8757 if( idxNum & 0x01 ){
8758 pCur->iOBase = sqlite3_value_int64(argv[iArg++]);
8759 }else{
8760 pCur->iOBase = 0;
8761 }
8762 if( idxNum & 0x02 ){
8763 pCur->iOTerm = sqlite3_value_int64(argv[iArg++]);
8764 }else{
8765 pCur->iOTerm = 0xffffffff;
8766 }
8767 if( idxNum & 0x04 ){
8768 pCur->iOStep = sqlite3_value_int64(argv[iArg++]);
8769 if( pCur->iOStep==0 ) pCur->iOStep = 1;
8770 }else{
8771 pCur->iOStep = 1;
8772 }
8773
8774 /* If there are constraints on the value column but there are
8775 ** no constraints on the start, stop, and step columns, then
8776 ** initialize the default range to be the entire range of 64-bit signed
8777 ** integers. This range will contracted by the value column constraints
8778 ** further below.
8779 */
8780 if( (idxNum & 0x05)==0 && (idxNum & 0x0380)!=0 ){
8781 pCur->iOBase = SMALLEST_INT64;
8782 }
8783 if( (idxNum & 0x06)==0 && (idxNum & 0x3080)!=0 ){
8784 pCur->iOTerm = LARGEST_INT64;
8785 }
8786 pCur->iBase = pCur->iOBase;
8787 pCur->iTerm = pCur->iOTerm;
8788 if( pCur->iOStep>0 ){
8789 pCur->iStep = pCur->iOStep;
8790 }else if( pCur->iOStep>SMALLEST_INT64 ){
8791 pCur->iStep = -pCur->iOStep;
8792 }else{
8793 pCur->iStep = LARGEST_INT64;
8794 pCur->iStep++;
8795 }
8796 pCur->bDesc = pCur->iOStep<0;
8797 if( pCur->bDesc==0 && pCur->iBase>pCur->iTerm ){
8798 goto series_no_rows;
8799 }
8800 if( pCur->bDesc!=0 && pCur->iBase<pCur->iTerm ){
8801 goto series_no_rows;
8802 }
8803
8804 /* Extract the LIMIT and OFFSET values, but do not apply them yet.
8805 ** The range must first be constrained by the limits on value.
8806 */
8807 if( idxNum & 0x20 ){
8808 iLimit = sqlite3_value_int64(argv[iArg++]);
8809 if( idxNum & 0x40 ){
8810 iOffset = sqlite3_value_int64(argv[iArg++]);
8811 }
8812 if( iLimit>0 ) pCur->bLimit = 1;
8813 }
8814
8815 /* Narrow the range of iMin and iMax (the minimum and maximum outputs)
8816 ** based on equality and inequality constraints on the "value" column.
8817 */
8818 if( idxNum & 0x3380 ){
8819 if( idxNum & 0x0080 ){ /* value=X */
8820 if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
8821 double r = sqlite3_value_double(argv[iArg++]);
8822 if( r==seriesCeil(r)
8823 && r>=(double)SMALLEST_INT64
8824 && r<=(double)LARGEST_INT64
8825 ){
8826 iMin = iMax = seriesRealToI64(r);
8827 }else{
8828 goto series_no_rows;
8829 }
8830 }else{
8831 iMin = iMax = sqlite3_value_int64(argv[iArg++]);
8832 }
8833 }else{
8834 if( idxNum & 0x0300 ){ /* value>X (0x200) or value>=X (0x100) */
8835 if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
8836 double r = sqlite3_value_double(argv[iArg++]);
8837 if( r<=(double)SMALLEST_INT64 ){
8838 iMin = SMALLEST_INT64;
8839 }else if( r>(double)LARGEST_INT64 ){
8840 goto series_no_rows;
8841 }else{
8842 iMin = seriesRealToI64(seriesCeil(r));
8843 if( (idxNum & 0x0200)!=0 && r==seriesCeil(r) ){
8844 if( iMin==LARGEST_INT64 ) goto series_no_rows;
8845 iMin++;
8846 }
8847 }
8848 }else{
8849 iMin = sqlite3_value_int64(argv[iArg++]);
8850 if( (idxNum & 0x0200)!=0 ){
8851 if( iMin==LARGEST_INT64 ){
8852 goto series_no_rows;
8853 }else{
8854 iMin++;
8855 }
8856 }
8857 }
8858 }
8859 if( idxNum & 0x3000 ){ /* value<X (0x2000) or value<=X (0x1000) */
8860 if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
8861 double r = sqlite3_value_double(argv[iArg++]);
8862 if( r>=(double)LARGEST_INT64 ){
8863 iMax = LARGEST_INT64;
8864 }else if( r<=(double)SMALLEST_INT64 ){
8865 goto series_no_rows;
8866 }else{
8867 iMax = seriesRealToI64(seriesFloor(r));
8868 if( (idxNum & 0x2000)!=0 && r==seriesFloor(r) ){
8869 if( iMax==SMALLEST_INT64 ) goto series_no_rows;
8870 iMax--;
8871 }
8872 }
8873 }else{
8874 iMax = sqlite3_value_int64(argv[iArg++]);
8875 if( idxNum & 0x2000 ){
8876 if( iMax==SMALLEST_INT64 ){
8877 goto series_no_rows;
8878 }else{
8879 iMax--;
8880 }
8881 }
8882 }
8883 }
8884 if( iMin>iMax ){
8885 goto series_no_rows;
8886 }
8887 }
8888
8889 /* Try to reduce the range of values to be generated based on
8890 ** constraints on the "value" column.
8891 */
8892 if( pCur->bDesc==0 ){
8893 if( pCur->iBase<iMin ){
8894 sqlite3_uint64 span = span64(iMin,pCur->iBase);
8895 pCur->iBase = add64(pCur->iBase, (span/pCur->iStep)*pCur->iStep);
8896 if( pCur->iBase<iMin ){
8897 if( pCur->iBase > sub64(LARGEST_INT64, pCur->iStep) ){
8898 goto series_no_rows;
8899 }
8900 pCur->iBase = add64(pCur->iBase, pCur->iStep);
8901 }
8902 }
8903 if( pCur->iTerm>iMax ){
8904 pCur->iTerm = iMax;
8905 }
8906 }else{
8907 if( pCur->iBase>iMax ){
8908 sqlite3_uint64 span = span64(pCur->iBase,iMax);
8909 pCur->iBase = sub64(pCur->iBase, (span/pCur->iStep)*pCur->iStep);
8910 if( pCur->iBase>iMax ){
8911 if( pCur->iBase < add64(SMALLEST_INT64, pCur->iStep) ){
8912 goto series_no_rows;
8913 }
8914 pCur->iBase = sub64(pCur->iBase, pCur->iStep);
8915 }
8916 }
8917 if( pCur->iTerm<iMin ){
8918 pCur->iTerm = iMin;
8919 }
8920 }
8921 }
8922
8923 /* Adjust iTerm so that it is exactly the last value of the series.
8924 */
8925 if( pCur->bDesc==0 ){
8926 if( pCur->iBase>pCur->iTerm ){
8927 goto series_no_rows;
8928 }
8929 pCur->iTerm = sub64(pCur->iTerm,
8930 span64(pCur->iTerm,pCur->iBase) % pCur->iStep);
8931 }else{
8932 if( pCur->iBase<pCur->iTerm ){
8933 goto series_no_rows;
8934 }
8935 pCur->iTerm = add64(pCur->iTerm,
8936 span64(pCur->iBase,pCur->iTerm) % pCur->iStep);
8937 }
8938
8939 /* Transform the series generator to output values in the requested
8940 ** order.
8941 */
8942 if( ((idxNum & 0x0008)!=0 && pCur->bDesc==0)
8943 || ((idxNum & 0x0010)!=0 && pCur->bDesc!=0)
8944 ){
8945 sqlite3_int64 tmp = pCur->iBase;
8946 pCur->iBase = pCur->iTerm;
8947 pCur->iTerm = tmp;
8948 pCur->bDesc = !pCur->bDesc;
8949 }
8950
8951 /* Apply LIMIT and OFFSET constraints, if any */
8952 assert( pCur->iStep!=0 );
8953 if( idxNum & 0x20 ){
8954 if( iOffset>0 ){
8955 if( seriesSteps(pCur) < (sqlite3_uint64)iOffset ){
8956 goto series_no_rows;
8957 }else if( pCur->bDesc ){
8958 pCur->iBase = sub64(pCur->iBase, pCur->iStep*iOffset);
8959 }else{
8960 pCur->iBase = add64(pCur->iBase, pCur->iStep*iOffset);
8961 }
8962 }
8963 if( iLimit>=0 && seriesSteps(pCur) > (sqlite3_uint64)iLimit ){
8964 pCur->iTerm = add64(pCur->iBase, (iLimit - 1)*pCur->iStep);
8965 }
8966 }
8967 pCur->iValue = pCur->iBase;
8968 pCur->bDone = 0;
8969 return SQLITE_OK;
8970
8971 series_no_rows:
8972 pCur->iBase = 0;
8973 pCur->iTerm = 0;
8974 pCur->iStep = 1;
8975 pCur->bDesc = 0;
8976 pCur->bDone = 1;
8977 return SQLITE_OK;
8978 }
8979
8980 /*
8981 ** SQLite will invoke this method one or more times while planning a query
8982 ** that uses the generate_series virtual table. This routine needs to create
8983 ** a query plan for each invocation and compute an estimated cost for that
8984 ** plan.
8985 **
8986 ** In this implementation idxNum is used to represent the
8987 ** query plan. idxStr is unused.
8988 **
8989 ** The query plan is represented by bits in idxNum:
8990 **
8991 ** 0x0001 start = $num
8992 ** 0x0002 stop = $num
8993 ** 0x0004 step = $num
8994 ** 0x0008 output is in descending order
8995 ** 0x0010 output is in ascending order
8996 ** 0x0020 LIMIT $num
8997 ** 0x0040 OFFSET $num
8998 ** 0x0080 value = $num
8999 ** 0x0100 value >= $num
9000 ** 0x0200 value > $num
9001 ** 0x1000 value <= $num
9002 ** 0x2000 value < $num
9003 **
9004 ** Only one of 0x0100 or 0x0200 will be returned. Similarly, only
9005 ** one of 0x1000 or 0x2000 will be returned. If the 0x0080 is set, then
9006 ** none of the 0xff00 bits will be set.
9007 **
9008 ** The order of parameters passed to xFilter is as follows:
9009 **
9010 ** * The argument to start= if bit 0x0001 is in the idxNum mask
9011 ** * The argument to stop= if bit 0x0002 is in the idxNum mask
9012 ** * The argument to step= if bit 0x0004 is in the idxNum mask
9013 ** * The argument to LIMIT if bit 0x0020 is in the idxNum mask
9014 ** * The argument to OFFSET if bit 0x0040 is in the idxNum mask
9015 ** * The argument to value=, or value>= or value> if any of
9016 ** bits 0x0380 are in the idxNum mask
9017 ** * The argument to value<= or value< if either of bits 0x3000
9018 ** are in the mask
9019 **
9020 */
9021 static int seriesBestIndex(
9022 sqlite3_vtab *pVTab,
9023 sqlite3_index_info *pIdxInfo
9024 ){
9025 int i, j; /* Loop over constraints */
9026 int idxNum = 0; /* The query plan bitmask */
9027 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
9028 int bStartSeen = 0; /* EQ constraint seen on the START column */
9029 #endif
9030 int unusableMask = 0; /* Mask of unusable constraints */
9031 int nArg = 0; /* Number of arguments that seriesFilter() expects */
9032 int aIdx[7]; /* Constraints on start, stop, step, LIMIT, OFFSET,
9033 ** and value. aIdx[5] covers value=, value>=, and
9034 ** value>, aIdx[6] covers value<= and value< */
9035 const struct sqlite3_index_constraint *pConstraint;
9036
9037 /* This implementation assumes that the start, stop, and step columns
9038 ** are the last three columns in the virtual table. */
9039 assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
9040 assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
9041
9042 aIdx[0] = aIdx[1] = aIdx[2] = aIdx[3] = aIdx[4] = aIdx[5] = aIdx[6] = -1;
9043 pConstraint = pIdxInfo->aConstraint;
9044 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
9045 int iCol; /* 0 for start, 1 for stop, 2 for step */
9046 int iMask; /* bitmask for those column */
9047 int op = pConstraint->op;
9048 if( op>=SQLITE_INDEX_CONSTRAINT_LIMIT
9049 && op<=SQLITE_INDEX_CONSTRAINT_OFFSET
9050 ){
9051 if( pConstraint->usable==0 ){
9052 /* do nothing */
9053 }else if( op==SQLITE_INDEX_CONSTRAINT_LIMIT ){
9054 aIdx[3] = i;
9055 idxNum |= 0x20;
9056 }else{
9057 assert( op==SQLITE_INDEX_CONSTRAINT_OFFSET );
9058 aIdx[4] = i;
9059 idxNum |= 0x40;
9060 }
9061 continue;
9062 }
9063 if( pConstraint->iColumn<SERIES_COLUMN_START ){
9064 if( (pConstraint->iColumn==SERIES_COLUMN_VALUE ||
9065 pConstraint->iColumn==SERIES_COLUMN_ROWID)
9066 && pConstraint->usable
9067 ){
9068 switch( op ){
9069 case SQLITE_INDEX_CONSTRAINT_EQ:
9070 case SQLITE_INDEX_CONSTRAINT_IS: {
9071 idxNum |= 0x0080;
9072 idxNum &= ~0x3300;
9073 aIdx[5] = i;
9074 aIdx[6] = -1;
9075 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
9076 bStartSeen = 1;
9077 #endif
9078 break;
9079 }
9080 case SQLITE_INDEX_CONSTRAINT_GE: {
9081 if( idxNum & 0x0080 ) break;
9082 idxNum |= 0x0100;
9083 idxNum &= ~0x0200;
9084 aIdx[5] = i;
9085 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
9086 bStartSeen = 1;
9087 #endif
9088 break;
9089 }
9090 case SQLITE_INDEX_CONSTRAINT_GT: {
9091 if( idxNum & 0x0080 ) break;
9092 idxNum |= 0x0200;
9093 idxNum &= ~0x0100;
9094 aIdx[5] = i;
9095 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
9096 bStartSeen = 1;
9097 #endif
9098 break;
9099 }
9100 case SQLITE_INDEX_CONSTRAINT_LE: {
9101 if( idxNum & 0x0080 ) break;
9102 idxNum |= 0x1000;
9103 idxNum &= ~0x2000;
9104 aIdx[6] = i;
9105 break;
9106 }
9107 case SQLITE_INDEX_CONSTRAINT_LT: {
9108 if( idxNum & 0x0080 ) break;
9109 idxNum |= 0x2000;
9110 idxNum &= ~0x1000;
9111 aIdx[6] = i;
9112 break;
9113 }
9114 }
9115 }
9116 continue;
9117 }
9118 iCol = pConstraint->iColumn - SERIES_COLUMN_START;
9119 assert( iCol>=0 && iCol<=2 );
9120 iMask = 1 << iCol;
9121 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
9122 if( iCol==0 && op==SQLITE_INDEX_CONSTRAINT_EQ ){
9123 bStartSeen = 1;
9124 }
9125 #endif
9126 if( pConstraint->usable==0 ){
9127 unusableMask |= iMask;
9128 continue;
9129 }else if( op==SQLITE_INDEX_CONSTRAINT_EQ ){
9130 idxNum |= iMask;
9131 aIdx[iCol] = i;
9132 }
9133 }
9134 if( aIdx[3]==0 ){
9135 /* Ignore OFFSET if LIMIT is omitted */
9136 idxNum &= ~0x60;
9137 aIdx[4] = 0;
9138 }
9139 for(i=0; i<7; i++){
9140 if( (j = aIdx[i])>=0 ){
9141 pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
9142 pIdxInfo->aConstraintUsage[j].omit =
9143 !SQLITE_SERIES_CONSTRAINT_VERIFY || i>=3;
9144 }
9145 }
9146 /* The current generate_column() implementation requires at least one
9147 ** argument (the START value). Legacy versions assumed START=0 if the
9148 ** first argument was omitted. Compile with -DZERO_ARGUMENT_GENERATE_SERIES
9149 ** to obtain the legacy behavior */
9150 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
9151 if( !bStartSeen ){
9152 sqlite3_free(pVTab->zErrMsg);
9153 pVTab->zErrMsg = sqlite3_mprintf(
9154 "first argument to \"generate_series()\" missing or unusable");
9155 return SQLITE_ERROR;
9156 }
9157 #endif
9158 if( (unusableMask & ~idxNum)!=0 ){
9159 /* The start, stop, and step columns are inputs. Therefore if there
9160 ** are unusable constraints on any of start, stop, or step then
9161 ** this plan is unusable */
9162 return SQLITE_CONSTRAINT;
9163 }
9164 if( (idxNum & 0x03)==0x03 ){
9165 /* Both start= and stop= boundaries are available. This is the
9166 ** the preferred case */
9167 pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
9168 pIdxInfo->estimatedRows = 1000;
9169 if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
9170 if( pIdxInfo->aOrderBy[0].desc ){
9171 idxNum |= 0x08;
9172 }else{
9173 idxNum |= 0x10;
9174 }
9175 pIdxInfo->orderByConsumed = 1;
9176 }
9177 }else if( (idxNum & 0x21)==0x21 ){
9178 /* We have start= and LIMIT */
9179 pIdxInfo->estimatedRows = 2500;
9180 }else{
9181 /* If either boundary is missing, we have to generate a huge span
9182 ** of numbers. Make this case very expensive so that the query
9183 ** planner will work hard to avoid it. */
9184 pIdxInfo->estimatedRows = 2147483647;
9185 }
9186 pIdxInfo->idxNum = idxNum;
9187 #ifdef SQLITE_INDEX_SCAN_HEX
9188 pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_HEX;
9189 #endif
9190 return SQLITE_OK;
9191 }
9192
9193 /*
9194 ** This following structure defines all the methods for the
9195 ** generate_series virtual table.
9196 */
9197 static sqlite3_module seriesModule = {
9198 0, /* iVersion */
9199 0, /* xCreate */
9200 seriesConnect, /* xConnect */
9201 seriesBestIndex, /* xBestIndex */
9202 seriesDisconnect, /* xDisconnect */
9203 0, /* xDestroy */
9204 seriesOpen, /* xOpen - open a cursor */
9205 seriesClose, /* xClose - close a cursor */
9206 seriesFilter, /* xFilter - configure scan constraints */
9207 seriesNext, /* xNext - advance a cursor */
9208 seriesEof, /* xEof - check for end of scan */
9209 seriesColumn, /* xColumn - read data */
9210 seriesRowid, /* xRowid - read data */
9211 0, /* xUpdate */
9212 0, /* xBegin */
9213 0, /* xSync */
9214 0, /* xCommit */
9215 0, /* xRollback */
9216 0, /* xFindMethod */
9217 0, /* xRename */
9218 0, /* xSavepoint */
9219 0, /* xRelease */
9220 0, /* xRollbackTo */
9221 0, /* xShadowName */
9222 0 /* xIntegrity */
9223 };
9224
9225 #endif /* SQLITE_OMIT_VIRTUALTABLE */
9226
9227 #ifdef _WIN32
9228
9229 #endif
9230 int sqlite3_series_init(
9231 sqlite3 *db,
9232 char **pzErrMsg,
9233 const sqlite3_api_routines *pApi
9234 ){
9235 int rc = SQLITE_OK;
9236 SQLITE_EXTENSION_INIT2(pApi);
9237 #ifndef SQLITE_OMIT_VIRTUALTABLE
9238 if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
9239 *pzErrMsg = sqlite3_mprintf(
9240 "generate_series() requires SQLite 3.8.12 or later");
9241 return SQLITE_ERROR;
9242 }
9243 rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
9244 #endif
9245 return rc;
9246 }
9247
9248 /************************* End ext/misc/series.c ********************/
9249 /************************* Begin ext/misc/regexp.c ******************/
9250 /*
9251 ** 2012-11-13
9252 **
9253 ** The author disclaims copyright to this source code. In place of
@@ -9938,15 +9019,11 @@
9938 if( re_resize(pRe, 30) ){
9939 zErr = pRe->zErr;
9940 re_free(pRe);
9941 return zErr;
9942 }
9943 if( zIn[0]=='^' ){
9944 zIn++;
9945 }else{
9946 re_append(pRe, RE_OP_ANYSTAR, 0);
9947 }
9948 pRe->sIn.z = (unsigned char*)zIn;
9949 pRe->sIn.i = 0;
9950 pRe->sIn.mx = (int)strlen(zIn);
9951 zErr = re_subcompile_re(pRe);
9952 if( zErr ){
@@ -9958,10 +9035,23 @@
9958 *ppRe = pRe;
9959 }else{
9960 re_free(pRe);
9961 return "unrecognized character";
9962 }
 
 
 
 
 
 
 
 
 
 
 
 
 
9963
9964 /* The following is a performance optimization. If the regex begins with
9965 ** ".*" (if the input regex lacks an initial "^") and afterwards there are
9966 ** one or more matching characters, enter those matching characters into
9967 ** zInit[]. The re_match() routine can then search ahead in the input
@@ -10177,10 +9267,1133 @@
10177 }
10178 return rc;
10179 }
10180
10181 /************************* End ext/misc/regexp.c ********************/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10182 #ifndef SQLITE_SHELL_FIDDLE
10183 /************************* Begin ext/misc/fileio.c ******************/
10184 /*
10185 ** 2014-06-13
10186 **
@@ -10593,20 +10806,23 @@
10593 char *zCopy = sqlite3_mprintf("%s", zFile);
10594 int rc = SQLITE_OK;
10595
10596 if( zCopy==0 ){
10597 rc = SQLITE_NOMEM;
 
 
 
10598 }else{
10599 int nCopy = (int)strlen(zCopy);
10600 int i = 1;
10601
10602 while( rc==SQLITE_OK ){
10603 STRUCT_STAT sStat;
10604 int rc2;
10605
10606 for(; zCopy[i]!='/' && i<nCopy; i++);
10607 if( i==nCopy ) break;
10608 zCopy[i] = '\0';
10609
10610 rc2 = fileStat(zCopy, &sStat);
10611 if( rc2!=0 ){
10612 if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
@@ -10773,11 +10989,12 @@
10773 mtime = sqlite3_value_int64(argv[3]);
10774 }
10775
10776 res = writeFile(context, zFile, argv[1], mode, mtime);
10777 if( res==1 && errno==ENOENT ){
10778 if( makeDirectory(zFile)==SQLITE_OK ){
 
10779 res = writeFile(context, zFile, argv[1], mode, mtime);
10780 }
10781 }
10782
10783 if( argc>2 && res!=0 ){
@@ -11505,10 +11722,14 @@
11505 const sqlite3_api_routines *pApi
11506 ){
11507 int rc = SQLITE_OK;
11508 SQLITE_EXTENSION_INIT2(pApi);
11509 (void)pzErrMsg; /* Unused parameter */
 
 
 
 
11510 rc = sqlite3_create_function(db, "readfile", 1,
11511 SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
11512 readfileFunc, 0, 0);
11513 if( rc==SQLITE_OK ){
11514 rc = sqlite3_create_function(db, "writefile", -1,
@@ -13165,10 +13386,22 @@
13165 ** transaction.
13166 */
13167 static void zipfileCleanupTransaction(ZipfileTab *pTab){
13168 ZipfileEntry *pEntry;
13169 ZipfileEntry *pNext;
 
 
 
 
 
 
 
 
 
 
 
 
13170
13171 if( pTab->pWriteFd ){
13172 fclose(pTab->pWriteFd);
13173 pTab->pWriteFd = 0;
13174 }
@@ -13217,15 +13450,19 @@
13217 ZipfileEntry *p;
13218 ZipfileEntry *pNext;
13219
13220 pCsr->bEof = 0;
13221 if( pCsr->pFile ){
 
13222 fclose(pCsr->pFile);
13223 pCsr->pFile = 0;
13224 zipfileEntryFree(pCsr->pCurrent);
13225 pCsr->pCurrent = 0;
13226 }
 
 
 
 
13227
13228 for(p=pCsr->pFreeEntry; p; p=pNext){
13229 pNext = p->pNext;
13230 zipfileEntryFree(p);
13231 }
@@ -13521,10 +13758,19 @@
13521 i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
13522
13523 int A, B, C, D, E;
13524 int yr, mon, day;
13525 int hr, min, sec;
 
 
 
 
 
 
 
 
 
13526
13527 A = (int)((JD - 1867216.25)/36524.25);
13528 A = (int)(JD + 1 + A - (A/4));
13529 B = A + 1524;
13530 C = (int)((B - 122.1)/365.25);
@@ -13537,21 +13783,15 @@
13537
13538 hr = (mUnixTime % (24*60*60)) / (60*60);
13539 min = (mUnixTime % (60*60)) / 60;
13540 sec = (mUnixTime % 60);
13541
13542 if( yr>=1980 ){
13543 pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
13544 pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
13545 }else{
13546 pCds->mDate = pCds->mTime = 0;
13547 }
13548
13549 assert( mUnixTime<315507600
13550 || mUnixTime==zipfileMtime(pCds)
13551 || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
13552 /* || (mUnixTime % 2) */
13553 );
13554 }
13555
13556 /*
13557 ** Set (*pzErr) to point to a buffer from sqlite3_malloc() containing a
@@ -13712,11 +13952,11 @@
13712 pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
13713 }
13714 pCsr->pCurrent = p;
13715 }
13716 }else{
13717 if( !pCsr->bNoop ){
13718 pCsr->pCurrent = pCsr->pCurrent->pNext;
13719 }
13720 if( pCsr->pCurrent==0 ){
13721 pCsr->bEof = 1;
13722 }
@@ -13832,12 +14072,17 @@
13832 sqlite3_vtab_cursor *cur, /* The cursor */
13833 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
13834 int i /* Which column to return */
13835 ){
13836 ZipfileCsr *pCsr = (ZipfileCsr*)cur;
13837 ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
13838 int rc = SQLITE_OK;
 
 
 
 
 
13839 switch( i ){
13840 case 0: /* name */
13841 sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
13842 break;
13843 case 1: /* mode */
@@ -14678,11 +14923,11 @@
14678 ZipfileCsr *pCsr;
14679 ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
14680 assert( argc>0 );
14681
14682 pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
14683 if( pCsr ){
14684 ZipfileCDS *p = &pCsr->pCurrent->cds;
14685 char *zRes = sqlite3_mprintf("{"
14686 "\"version-made-by\" : %u, "
14687 "\"version-to-extract\" : %u, "
14688 "\"flags\" : %u, "
@@ -15025,10 +15270,13 @@
15025 0, /* xRollback */
15026 0, /* xShadowName */
15027 0 /* xIntegrity */
15028 };
15029
 
 
 
15030 int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0);
15031 if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
15032 if( rc==SQLITE_OK ){
15033 rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
15034 zipfileStep, zipfileFinal
@@ -15660,11 +15908,11 @@
15660 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
15661 IdxConstraint *pNew;
15662 int nColl = STRLEN(zColl);
15663
15664 assert( *pRc==SQLITE_OK );
15665 pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
15666 if( pNew ){
15667 pNew->zColl = (char*)&pNew[1];
15668 memcpy(pNew->zColl, zColl, nColl+1);
15669 }
15670 return pNew;
@@ -16184,10 +16432,12 @@
16184 */
16185 static int idxIdentifierRequiresQuotes(const char *zId){
16186 int i;
16187 int nId = STRLEN(zId);
16188
 
 
16189 if( sqlite3_keyword_check(zId, nId) ) return 1;
16190
16191 for(i=0; zId[i]; i++){
16192 if( !(zId[i]=='_')
16193 && !(zId[i]>='0' && zId[i]<='9')
@@ -16398,13 +16648,11 @@
16398 zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
16399 if( !zIdx ){
16400 rc = SQLITE_NOMEM;
16401 }else{
16402 rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
16403 if( rc!=SQLITE_OK ){
16404 rc = SQLITE_BUSY_TIMEOUT;
16405 }else{
16406 idxHashAdd(&rc, &p->hIdx, zName, zIdx);
16407 }
16408 }
16409 sqlite3_free(zIdx);
16410 }
@@ -17521,15 +17769,19 @@
17521 /* Do trigger processing to collect any extra IdxScan structures */
17522 rc = idxProcessTriggers(p, pzErr);
17523
17524 /* Create candidate indexes within the in-memory database file */
17525 if( rc==SQLITE_OK ){
 
17526 rc = idxCreateCandidates(p);
17527 }else if ( rc==SQLITE_BUSY_TIMEOUT ){
17528 if( pzErr )
17529 *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
17530 return rc;
 
 
 
17531 }
17532
17533 /* Generate the stat1 data */
17534 if( rc==SQLITE_OK ){
17535 rc = idxPopulateStat1(p, pzErr);
@@ -22443,10 +22695,16 @@
22443 ** index of the bind paramater to which the rowid value should be bound.
22444 ** Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
22445 ** KEY column, then the rowid value should be bound to the index associated
22446 ** with the column.
22447 **
 
 
 
 
 
 
22448 ** pNext:
22449 ** All RecoverTable objects used by the recovery operation are allocated
22450 ** and populated as part of creating the recovered database schema in
22451 ** the output database, before any non-schema data are recovered. They
22452 ** are then stored in a singly-linked list linked by this variable beginning
@@ -22458,10 +22716,11 @@
22458 int nCol; /* Number of columns in table */
22459 int nField; /* Number of fields in each record */
22460 RecoverColumn *aCol; /* Array of columns */
22461 int bIntkey; /* True for intkey, false for without rowid */
22462 int iRowidBind; /* If >0, bind rowid to INSERT here */
 
22463 RecoverTable *pNext;
22464 };
22465
22466 /*
22467 ** Each database column is represented by an instance of the following object
@@ -22908,15 +23167,15 @@
22908 ** SQL statements separated by ';', only the first is run.
22909 **
22910 ** Return the sqlite3_finalizer() or sqlite3_prepare() result code
22911 ** from running the zSql statement.
22912 */
22913 static int recoverOneStmt(sqlite3 *db, const char *zSql){
22914 sqlite3_stmt *pStmt = 0;
22915 int rc;
22916 if( zSql==0 ) return SQLITE_OK;
22917 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
22918 if( rc ){
22919 sqlite3_finalize(pStmt);
22920 return rc;
22921 }
22922 while( SQLITE_ROW==sqlite3_step(pStmt) ){}
@@ -22933,11 +23192,11 @@
22933 ** If successful, return SQLITE_OK. Or, if an error occurs, leave an error
22934 ** code and message in the recover handle and return a copy of the error code.
22935 */
22936 static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){
22937 if( p->errCode==SQLITE_OK ){
22938 int rc = recoverOneStmt(db, zSql);
22939 if( rc ){
22940 recoverDbError(p, db);
22941 }
22942 }
22943 return p->errCode;
@@ -23444,11 +23703,11 @@
23444 sqlite3_recover *p,
23445 const char *zName, /* Name of table created in output db */
23446 i64 iRoot /* Root page of same table in INPUT db */
23447 ){
23448 sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut,
23449 "PRAGMA table_xinfo(%Q)", zName
23450 );
23451
23452 if( pStmt ){
23453 int iPk = -1;
23454 int iBind = 1;
@@ -23511,11 +23770,12 @@
23511 /* If this is a WITHOUT ROWID table, the fields of each record are
23512 ** ordered as reported by PRAGMA index_xinfo on the table. A column may
23513 ** appear more than once if it is listed more than once in the PRIMARY
23514 ** KEY (with different collation sequences). In that case use the first
23515 ** field - the others are redundant copies. */
23516 pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName);
 
23517 while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
23518 int iField = sqlite3_column_int(pStmt, 0);
23519 int iCol = sqlite3_column_int(pStmt, 1);
23520
23521 assert( iCol>=0 && iCol<pNew->nCol );
@@ -23527,16 +23787,40 @@
23527 if( pNew->aCol[iCol].iField<0 ) pNew->aCol[iCol].iField = iField;
23528 pNew->nField = iField+1;
23529 iPk = -2;
23530 }
23531 recoverFinalize(p, pStmt);
 
 
 
 
 
 
 
 
 
 
 
 
23532
23533 if( p->errCode==SQLITE_OK ){
23534 if( iPk>=0 ){
23535 pNew->aCol[iPk].bIPK = 1;
23536 }else if( pNew->bIntkey ){
23537 pNew->iRowidBind = iBind++;
 
 
 
 
 
 
 
 
 
 
 
 
23538 }
23539 }
23540 }
23541 }
23542
@@ -23590,27 +23874,37 @@
23590 int bVirtual = sqlite3_column_int(pSelect, 2);
23591 const char *zName = (const char*)sqlite3_column_text(pSelect, 3);
23592 const char *zSql = (const char*)sqlite3_column_text(pSelect, 4);
23593 char *zFree = 0;
23594 int rc = SQLITE_OK;
 
23595
23596 if( bVirtual ){
23597 zSql = (const char*)(zFree = recoverMPrintf(p,
23598 "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
23599 zName, zName, zSql
23600 ));
23601 }
23602 rc = recoverOneStmt(p->dbOut, zSql);
23603 if( rc==SQLITE_OK ){
 
 
 
 
 
 
 
 
23604 recoverSqlCallback(p, zSql);
23605 if( bTable && !bVirtual ){
23606 if( SQLITE_ROW==sqlite3_step(pTblname) ){
23607 const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0);
23608 if( zTbl ) recoverAddTable(p, zTbl, iRoot);
23609 }
23610 recoverReset(p, pTblname);
23611 }
 
23612 }else if( rc!=SQLITE_ERROR ){
23613 recoverDbError(p, p->dbOut);
23614 }
23615 sqlite3_free(zFree);
23616 }
@@ -23649,13 +23943,23 @@
23649 );
23650
23651 if( pSelect ){
23652 while( sqlite3_step(pSelect)==SQLITE_ROW ){
23653 const char *zSql = (const char*)sqlite3_column_text(pSelect, 1);
23654 int rc = recoverOneStmt(p->dbOut, zSql);
 
23655 if( rc==SQLITE_OK ){
 
 
 
 
 
 
 
 
23656 recoverSqlCallback(p, zSql);
 
23657 }else if( rc!=SQLITE_ERROR ){
23658 recoverDbError(p, p->dbOut);
23659 }
23660 }
23661 }
@@ -23719,11 +24023,12 @@
23719
23720 zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab);
23721
23722 if( pTab->iRowidBind ){
23723 assert( pTab->bIntkey );
23724 zSql = recoverMPrintf(p, "%z_rowid_", zSql);
 
23725 if( bSql ){
23726 zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind);
23727 }else{
23728 zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind);
23729 }
@@ -25033,11 +25338,11 @@
25033 recoverCacheSchema(p);
25034
25035 if( bUseWrapper ) recoverUninstallWrapper(p);
25036 }while( p->errCode==SQLITE_NOTADB
25037 && (bUseWrapper--)
25038 && SQLITE_OK==recoverOneStmt(p->dbIn, "ROLLBACK")
25039 );
25040 }
25041
25042 recoverLeaveMutex();
25043 recoverExec(p, p->dbOut, "BEGIN");
@@ -25098,11 +25403,11 @@
25098
25099 /* If no error has occurred, commit the write transaction on the output
25100 ** database. Regardless of whether or not an error has occurred, make
25101 ** an attempt to end the read transaction on the input database. */
25102 recoverExec(p, p->dbOut, "COMMIT");
25103 rc = recoverOneStmt(p->dbIn, "END");
25104 if( p->errCode==SQLITE_OK ) p->errCode = rc;
25105
25106 recoverSqlCallback(p, "PRAGMA writable_schema = off");
25107 recoverSqlCallback(p, "COMMIT");
25108 p->eState = RECOVER_STATE_DONE;
@@ -25294,11 +25599,11 @@
25294 if( p==0 ){
25295 rc = SQLITE_NOMEM;
25296 }else{
25297 recoverFinalCleanup(p);
25298 if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){
25299 rc = recoverOneStmt(p->dbIn, "END");
25300 if( p->errCode==SQLITE_OK ) p->errCode = rc;
25301 }
25302 rc = p->errCode;
25303 sqlite3_free(p->zErrMsg);
25304 sqlite3_free(p->zStateDb);
@@ -25352,11 +25657,10 @@
25352 /* All the parameters that determine how to render query results.
25353 */
25354 typedef struct Mode {
25355 u8 autoExplain; /* Automatically turn on .explain mode */
25356 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
25357 u8 autoEQPtrace; /* autoEQP is in trace mode */
25358 u8 scanstatsOn; /* True to display scan stats before each finalize */
25359 u8 bAutoScreenWidth; /* Using the TTY to determine screen width */
25360 u8 mFlags; /* MFLG_ECHO, MFLG_CRLF, etc. */
25361 u8 eMode; /* One of the MODE_ values */
25362 char zIFmt[24]; /* Space to hold the --ifmt value */
@@ -25423,10 +25727,11 @@
25423 const char *zInFile; /* Name of the input file */
25424 int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
25425 FILE *in; /* Read commands from this stream */
25426 FILE *out; /* Write results here */
25427 FILE *traceOut; /* Output for sqlite3_trace() */
 
25428 int nErr; /* Number of errors seen */
25429 int writableSchema; /* True if PRAGMA writable_schema=ON */
25430 int nCheck; /* Number of ".check" commands run */
25431 unsigned nProgress; /* Number of progress callbacks encountered */
25432 unsigned mxProgress; /* Maximum progress callbacks before failing */
@@ -25583,13 +25888,14 @@
25583 #define MODE_Quote 17 /* Quote values as for SQL */
25584 #define MODE_Split 18 /* Split-column mode */
25585 #define MODE_Table 19 /* MySQL-style table formatting */
25586 #define MODE_Tabs 20 /* Tab-separated values */
25587 #define MODE_Tcl 21 /* Space-separated list of TCL strings */
25588 #define MODE_Www 22 /* Full web-page output */
 
25589
25590 #define MODE_BUILTIN 22 /* Maximum built-in mode */
25591 #define MODE_BATCH 50 /* Default mode for batch processing */
25592 #define MODE_TTY 51 /* Default mode for interactive processing */
25593 #define MODE_USER 75 /* First user-defined mode */
25594 #define MODE_N_USER 25 /* Maximum number of user-defined modes */
25595
@@ -25624,11 +25930,11 @@
25624 { "box", 0, 0, 9, 1, 1, 0, 3, 1, 2, 0 },
25625 { "c", 4, 1, 10, 5, 5, 4, 1, 12, 0, 0 },
25626 { "column", 0, 0, 9, 1, 1, 0, 3, 2, 2, 0 },
25627 { "count", 0, 0, 0, 0, 0, 0, 0, 3, 0, 0 },
25628 { "csv", 4, 5, 9, 3, 3, 0, 1, 12, 0, 0 },
25629 { "html", 0, 0, 9, 4, 4, 0, 3, 7, 0, 0 },
25630 { "insert", 0, 0, 10, 2, 2, 0, 1, 8, 0, 0 },
25631 { "jatom", 4, 1, 11, 6, 6, 0, 1, 12, 0, 0 },
25632 { "jobject", 0, 1, 11, 6, 6, 0, 0, 10, 0, 0 },
25633 { "json", 0, 0, 11, 6, 6, 0, 0, 9, 0, 0 },
25634 { "line", 13, 1, 9, 1, 1, 0, 0, 11, 1, 0 },
@@ -25640,11 +25946,11 @@
25640 { "quote", 4, 1, 10, 2, 2, 0, 1, 12, 0, 0 },
25641 { "split", 0, 0, 9, 1, 1, 0, 1, 2, 2, 2 },
25642 { "table", 0, 0, 9, 1, 1, 0, 3, 19, 2, 0 },
25643 { "tabs", 8, 1, 9, 3, 3, 0, 1, 12, 0, 0 },
25644 { "tcl", 3, 1, 12, 5, 5, 4, 1, 12, 0, 0 },
25645 { "www", 0, 0, 9, 4, 4, 0, 3, 7, 0, 0 }
25646 }; /* | / / | / / | | / \____
25647 ** | / / | / / | | / |
25648 ** Index into aModeStr[] | / / | | 2: columnar |
25649 ** | / / | | 1: line |
25650 ** | / / | | 0: other |
@@ -26828,10 +27134,41 @@
26828 /*
26829 ** SQL function: capable(X)
26830 **
26831 ** Return true if the current build has capability X. Return 0
26832 ** if X is not a capability or NULL if X is NULL.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26833 **
26834 ** This function is intended to be used with the ".if" command
26835 ** to bypass test cases that use features that are not part of
26836 ** the build. Examples:
26837 **
@@ -26861,33 +27198,54 @@
26861 "load_ext", "OMIT_LOAD_EXTENSION",
26862 };
26863 size_t i;
26864 int invert = 0;
26865 int res = 0;
 
26866
26867 UNUSED_PARAMETER(nVal);
26868 if( z==0 ) return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26869 for(i=0; i<sizeof(azInversions)/sizeof(azInversions[0])-1; i+=2){
26870 if( sqlite3_stricmp(z, azInversions[i])==0 ){
26871 z = azInversions[i+1];
26872 invert = 1;
26873 break;
26874 }
26875 }
 
 
26876 for(i=0; i<sizeof(azSql)/sizeof(azSql[0]); i++){
26877 sqlite3_stmt *pStmt = 0;
26878 sqlite3_prepare_v2(p->db, azSql[i], -1, &pStmt, 0);
26879 while( sqlite3_step(pStmt)==SQLITE_ROW ){
26880 const char *zRow = (const char*)sqlite3_column_text(pStmt, 0);
26881 if( sqlite3_stricmp(zRow, z)==0 ){
26882 res = 1;
26883 break;
26884 }
26885 }
26886 sqlite3_finalize(pStmt);
26887 if( res ) break;
26888 }
 
 
26889 if( invert ) res = !res;
26890 sqlite3_result_int(pCtx, res);
26891 }
26892
26893
@@ -27343,10 +27701,25 @@
27343 }
27344 }
27345
27346 /* Forward reference */
27347 static int pickStr(const char *zArg, char **pzErr, ...);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27348
27349 /*
27350 ** Change the limits on the display mode. Return 0 on
27351 ** success. Return non-zero if zArg is mis-formatted.
27352 **
@@ -27371,13 +27744,13 @@
27371 p->mode.spec.nTitleLimit = 0;
27372 }else{
27373 int L, C, T = 0;
27374 int nNum = sscanf(zArg, "%d,%d,%d", &L, &C, &T);
27375 if( nNum<2 || L<0 || C<0 || T<0) return 1;
27376 p->mode.spec.nLineLimit = L;
27377 p->mode.spec.nCharLimit = C;
27378 if( nNum==3 ) p->mode.spec.nTitleLimit = T;
27379 }
27380 return 0;
27381 }
27382
27383 /*
@@ -28324,10 +28697,34 @@
28324 }
28325 if( zName==0 ) return;
28326 p->zDestTable = sqlite3_mprintf("%s", zName);
28327 shell_check_oom(p->zDestTable);
28328 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28329
28330 /*
28331 ** Maybe construct two lines of text that point out the position of a
28332 ** syntax error. Return a pointer to the text, in memory obtained from
28333 ** sqlite3_malloc(). Or, if the most recent error does not involve a
@@ -28357,11 +28754,11 @@
28357 len = strlen(zSql);
28358 if( len>78 ){
28359 len = 78;
28360 while( len>0 && (zSql[len]&0xc0)==0x80 ) len--;
28361 }
28362 zCode = sqlite3_mprintf("%.*s", len, zSql);
28363 shell_check_oom(zCode);
28364 for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
28365 if( iOffset<25 ){
28366 zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode,iOffset,"");
28367 }else{
@@ -28391,12 +28788,14 @@
28391 int i;
28392 const char *z;
28393 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
28394 if( rc!=SQLITE_OK || !pSelect ){
28395 char *zContext = shell_error_context(zSelect, p->db);
 
28396 cli_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s",
28397 rc, sqlite3_errmsg(p->db), zContext);
 
28398 sqlite3_free(zContext);
28399 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
28400 return rc;
28401 }
28402 rc = sqlite3_step(pSelect);
@@ -28416,12 +28815,13 @@
28416 }
28417 rc = sqlite3_step(pSelect);
28418 }
28419 rc = sqlite3_finalize(pSelect);
28420 if( rc!=SQLITE_OK ){
28421 cli_printf(p->out, "/**** ERROR: (%d) %s *****/\n",
28422 rc, sqlite3_errmsg(p->db));
 
28423 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
28424 }
28425 return rc;
28426 }
28427
@@ -28705,21 +29105,21 @@
28705 /* Create the TEMP table used to store parameter bindings */
28706 static void bind_table_init(ShellState *p){
28707 int wrSchema = 0;
28708 int defensiveMode = 0;
28709 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
28710 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
28711 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
28712 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
28713 sqlite3_exec(p->db,
28714 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
28715 " key TEXT PRIMARY KEY,\n"
28716 " value\n"
28717 ") WITHOUT ROWID;",
28718 0, 0, 0);
28719 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
28720 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
28721 }
28722
28723 /*
28724 ** Bind parameters on a prepared statement.
28725 **
@@ -28735,13 +29135,16 @@
28735 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
28736 int nVar;
28737 int i;
28738 int rc;
28739 sqlite3_stmt *pQ = 0;
 
28740
28741 nVar = sqlite3_bind_parameter_count(pStmt);
28742 if( nVar==0 ) return; /* Nothing to do */
 
 
28743 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
28744 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
28745 rc = SQLITE_NOTFOUND;
28746 pQ = 0;
28747 }else{
@@ -28754,10 +29157,11 @@
28754 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
28755 if( zVar==0 ){
28756 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
28757 zVar = zNum;
28758 }
 
28759 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
28760 if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){
28761 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
28762 #ifdef NAN
28763 }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){
@@ -28805,17 +29209,18 @@
28805 && ShellHasFlag(pArg,SHFLG_TestingMode) ){
28806 sqlite3_bind_pointer(pStmt,i,aPrimes,"carray",0);
28807 }else{
28808 sqlite3_bind_null(pStmt, i);
28809 }
28810 #endif
28811 }else{
28812 sqlite3_bind_null(pStmt, i);
28813 }
28814 sqlite3_reset(pQ);
28815 }
28816 sqlite3_finalize(pQ);
 
28817 }
28818
28819 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION)
28820 /*
28821 ** This function is called to process SQL if the previous shell command
@@ -29034,42 +29439,55 @@
29034
29035 /* save off the prepared statement handle */
29036 if( pArg ){
29037 pArg->pStmt = pStmt;
29038 }
29039
29040 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
 
29041 isExplain = sqlite3_stmt_isexplain(pStmt);
29042 if( pArg && pArg->mode.autoEQP && isExplain==0 && pArg->dot.nArg==0 ){
29043 int triggerEQP = 0;
29044 u8 savedEnableTimer = pArg->enableTimer;
 
29045 pArg->enableTimer = 0;
29046 disable_debug_trace_modes();
29047 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
29048 if( pArg->mode.autoEQP>=AUTOEQP_trigger ){
29049 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
29050 }
29051 sqlite3_reset(pStmt);
29052 spec.eStyle = QRF_STYLE_Auto;
29053 sqlite3_stmt_explain(pStmt, 2);
 
 
 
 
 
 
 
 
29054 sqlite3_format_query_result(pStmt, &spec, 0);
29055 if( pArg->mode.autoEQP>=AUTOEQP_full ){
29056 sqlite3_reset(pStmt);
29057 sqlite3_stmt_explain(pStmt, 1);
29058 sqlite3_format_query_result(pStmt, &spec, 0);
29059 }
29060
29061 if( pArg->mode.autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
29062 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
29063 }
29064 sqlite3_reset(pStmt);
29065 sqlite3_stmt_explain(pStmt, 0);
 
 
 
 
29066 restore_debug_trace_modes();
29067 pArg->enableTimer = savedEnableTimer;
29068 }
29069
29070 bind_prepared_stmt(pArg, pStmt);
29071 if( isExplain && pArg->mode.autoExplain ){
29072 spec.eStyle = isExplain==1 ? QRF_STYLE_Explain : QRF_STYLE_Eqp;
29073 rc = sqlite3_format_query_result(pStmt, &spec, pzErrMsg);
29074 }else if( pArg->mode.eMode==MODE_Www ){
29075 cli_printf(pArg->out,
@@ -29422,20 +29840,24 @@
29422 if( rc==SQLITE_CORRUPT ){
29423 char *zQ2;
29424 int len = strlen30(zQuery);
29425 cli_puts("/****** CORRUPTION ERROR *******/\n", p->out);
29426 if( zErr ){
29427 cli_printf(p->out, "/****** %s ******/\n", zErr);
 
 
29428 sqlite3_free(zErr);
29429 zErr = 0;
29430 }
29431 zQ2 = malloc( len+100 );
29432 if( zQ2==0 ) return rc;
29433 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
29434 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
29435 if( rc ){
29436 cli_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
 
 
29437 }else{
29438 rc = SQLITE_CORRUPT;
29439 }
29440 free(zQ2);
29441 }
@@ -29632,13 +30054,17 @@
29632 ".recover Recover as much data as possible from corrupt db.",
29633 " --ignore-freelist Ignore pages that appear to be on db freelist",
29634 " --lost-and-found TABLE Alternative name for the lost-and-found table",
29635 " --no-rowids Do not attempt to recover rowid values",
29636 " that are not also INTEGER PRIMARY KEYs",
 
29637 #endif
29638 #ifndef SQLITE_SHELL_FIDDLE
29639 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
 
 
 
29640 ".save ?OPTIONS? FILE Write database to FILE (an alias for .backup ...)",
29641 #endif
29642 ".scanstats on|off|est Turn sqlite3_stmt_scanstatus() metrics on or off",
29643 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
29644 " Options:",
@@ -29726,21 +30152,10 @@
29726 ** "Usage" help text automatically generated from comments */
29727 static const struct {
29728 const char *zCmd; /* Name of the dot-command */
29729 const char *zUsage; /* Documentation */
29730 } aUsage[] = {
29731 { ".clone",
29732 "USAGE: .clone FILE\n"
29733 "\n"
29734 "The original purpose of the \".clone\" command (when it was first introduced\n"
29735 "in 2014) was to try to recover content for a corrupt database file and\n"
29736 "write the recovered content into a new database named FILE. However,\n"
29737 "the command has always been experimental and undocumented. Today, it\n"
29738 "does nothing more than make a copy of the main database into a new\n"
29739 "database named by its only argument, FILE. No repair attempts are\n"
29740 "made. The command is retained for legacy only.\n"
29741 },
29742 { ".import",
29743 "USAGE: .import [OPTIONS] FILE TABLE\n"
29744 "\n"
29745 "Import CSV or similar text from FILE into TABLE. If TABLE does\n"
29746 "not exist, it is created using the first row of FILE as the column\n"
@@ -29770,10 +30185,140 @@
29770 " --rowsep CHAR Use CHAR as the row separator.\n"
29771 " --schema S When creating TABLE, put it in schema S\n"
29772 " --skip N Ignore the first N rows of input\n"
29773 " -v Verbose mode\n"
29774 },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29775 { ".mode",
29776 "USAGE: .mode [MODE] [OPTIONS]\n"
29777 "\n"
29778 "Change the output mode to MODE and/or apply OPTIONS to the output mode.\n"
29779 "Arguments are processed from left to right. If no arguments, show the\n"
@@ -29844,10 +30389,81 @@
29844 " for the unspecified widths.\n"
29845 " --wordwrap BOOLEAN Enable/disable word wrapping\n"
29846 " --wrap N Wrap columns wider than N characters\n"
29847 " --ww Shorthand for \"--wordwrap on\"\n"
29848 },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29849 { ".output",
29850 "USAGE: .output [OPTIONS] [FILE]\n"
29851 "\n"
29852 "Begin redirecting output to FILE. Or if FILE is omitted, revert\n"
29853 "to sending output to the console. If FILE begins with \"|\" then\n"
@@ -29876,109 +30492,10 @@
29876 " the --plain is used too.\n"
29877 " -x Show the output in a spreadsheet. Output is\n"
29878 " written to a temp file as CSV then the spreadsheet\n"
29879 " is launched when\n"
29880 },
29881 { ".once",
29882 "USAGE: .once [OPTIONS] FILE ...\n"
29883 "\n"
29884 "Write the output for the next line of SQL or the next dot-command into\n"
29885 "FILE. If FILE begins with \"|\" then it is a program into which output\n"
29886 "is written. The FILE argument should be omitted if one of the -e, -w,\n"
29887 "or -x options is used.\n"
29888 "\n"
29889 "Options:\n"
29890 " -e Capture output into a temporary file then bring up\n"
29891 " a text editor on that temporary file.\n"
29892 " --plain Use plain text rather than HTML tables with -w\n"
29893 " -w Capture output into an HTML file then bring up that\n"
29894 " file in a web browser\n"
29895 " -x Show the output in a spreadsheet. Output is\n"
29896 " written to a temp file as CSV then the spreadsheet\n"
29897 " is launched when\n"
29898 },
29899 { ".check",
29900 "USAGE: .check [OPTIONS] PATTERN\n"
29901 "\n"
29902 "Verify results of commands since the most recent .testcase command.\n"
29903 "Restore output to the console, unless --keep is used.\n"
29904 "\n"
29905 "If PATTERN starts with \"<<ENDMARK\" then the actual pattern is taken from\n"
29906 "subsequent lines of text up to the first line that begins with ENDMARK.\n"
29907 "All pattern lines and the ENDMARK are discarded.\n"
29908 "\n"
29909 "Options:\n"
29910 " --exact Do an exact comparison including leading and\n"
29911 " trailing whitespace.\n"
29912 " --glob Treat PATTERN as a GLOB\n"
29913 " --keep Do not reset the testcase. More .check commands\n"
29914 " will follow.\n"
29915 " --notglob Output should not match PATTERN\n"
29916 " --show Write testcase output to the screen, for debugging.\n"
29917 },
29918 { ".stats",
29919 "USAGE: .stats [OPTIONS] ...\n"
29920 "\n"
29921 "Show status information about the database and database connection.\n"
29922 "The stats setting is persistent, unless the --once option is used.\n"
29923 "Options are cumulative and are processed from left to right.\n"
29924 "If no options are given, that is the same as \".stats all --once\".\n"
29925 "\n"
29926 "Options:\n"
29927 " all Show all available stats.\n"
29928 " io Show I/O stats (Linux only).\n"
29929 " mem Show basic memory usage.\n"
29930 " off Show nothing. Turn off stat display.\n"
29931 " on Shorthand for \"stmt xmem\".\n"
29932 " --once Show the stats once. Do not change the default stats display.\n"
29933 " reset Reset \"max\" values after next display of each that value.\n"
29934 " stmt Show information about the last SQL statement.\n"
29935 " vmstep Show the number of virtual machine steps taken.\n"
29936 " xmem Show detailed memory status information\n"
29937 " xstmt Show details about each SQL statement\n"
29938 },
29939 { ".testcase",
29940 "USAGE: .testcase [OPTIONS] NAME\n"
29941 "\n"
29942 "Start a new test case identified by NAME. All output\n"
29943 "through the next \".check\" command is captured for comparison. See the\n"
29944 "\".check\" command for additional informatioon.\n"
29945 "\n"
29946 "Options:\n"
29947 " --error-prefix TEXT Change error message prefix text to TEXT\n"
29948 },
29949 { ".if",
29950 "USAGE: .if SQL-EXPRESSION\n"
29951 "\n"
29952 "The argument can be any SQL expression, including a subquery in\n"
29953 "parentheses. If the expression evalutes to true (if it is non-zero\n"
29954 "when converted into an number) then subsequent statements are\n"
29955 "evaluated. If SQL-EXPRESSION evalutes to false or NULL or raises\n"
29956 "an error, then subsequent statements are skipped, up until the first\n"
29957 "matching .elseif, .else, or .endif.\n"
29958 "\n"
29959 "Maximum nested depth is limited. An error is raised if .if statements\n"
29960 "are nested to deep.\n"
29961 "\n"
29962 "Every .if must be followed by a matching .endif, or an error is raised.\n"
29963 },
29964 { ".elseif",
29965 "USAGE: .elseif SQL-EXPRESSION\n"
29966 "\n"
29967 "An \"else-if\". The prior .if is finished and a new condition is applied.\n"
29968 },
29969 { ".else",
29970 "USAGE: .else\n"
29971 "\n"
29972 "Invert the sense of the inner-most .if. Start processing if the prior\n"
29973 ".if was false. Stop processing if the prior .if was true.\n"
29974 },
29975 { ".endif",
29976 "USAGE: .endif\n"
29977 "\n"
29978 "Terminate an .if statement.\n"
29979 },
29980 };
29981
29982 /*
29983 ** Return a pointer to usage text for zCmd, or NULL if none exists.
29984 */
@@ -30119,11 +30636,11 @@
30119 **
30120 ** NULL is returned if any error is encountered. The final value of *pnByte
30121 ** is undefined in this case.
30122 */
30123 static char *readFile(const char *zName, int *pnByte){
30124 FILE *in = sqlite3_fopen(zName, "rb");
30125 long nIn;
30126 size_t nRead;
30127 char *pBuf;
30128 int rc;
30129 if( in==0 ) return 0;
@@ -30328,10 +30845,11 @@
30328 }
30329 if( rc ) return 0; /* Is a database */
30330 }
30331 if( sqlite3_strlike("%.sql",z,0)==0 ) return 1;
30332 if( sqlite3_strlike("%.txt",z,0)==0 ) return 1;
 
30333 return 0;
30334 }
30335
30336 #ifndef SQLITE_OMIT_DESERIALIZE
30337 /*
@@ -30438,10 +30956,29 @@
30438 int sleep = sqlite3_value_int(argv[0]);
30439 (void)argcUnused;
30440 sqlite3_sleep(sleep/1000);
30441 sqlite3_result_int(context, sleep);
30442 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30443
30444 /*
30445 ** SQL function: shell_module_schema(X)
30446 **
30447 ** For use internally and for debugging and testing only. This function
@@ -30580,16 +31117,18 @@
30580 sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
30581
30582 /* Reflect the use or absence of --unsafe-testing invocation. */
30583 {
30584 int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
30585 sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0);
30586 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0);
 
 
30587 }
30588
30589 #ifndef SQLITE_OMIT_LOAD_EXTENSION
30590 sqlite3_enable_load_extension(p->db, 1);
30591 #endif
30592 sqlite3_sha_init(p->db, 0, 0);
30593 sqlite3_shathree_init(p->db, 0, 0);
30594 sqlite3_uint_init(p->db, 0, 0);
30595 sqlite3_stmtrand_init(p->db, 0, 0);
@@ -30599,22 +31138,20 @@
30599 sqlite3_regexp_init(p->db, 0, 0);
30600 sqlite3_ieee_init(p->db, 0, 0);
30601 sqlite3_series_init(p->db, 0, 0);
30602 sqlite3_diskused_init(p->db, 0, 0);
30603 sqlite3_strdup_init(p->db, 0, 0);
30604 #ifndef SQLITE_SHELL_FIDDLE
30605 if( !p->bSafeMode ){
 
 
30606 sqlite3_fileio_init(p->db, 0, 0);
30607 }
30608 sqlite3_completion_init(p->db, 0, 0);
30609 #endif
30610 #ifdef SQLITE_HAVE_ZLIB
30611 if( !p->bSafeModePersist ){
30612 sqlite3_zipfile_init(p->db, 0, 0);
30613 sqlite3_sqlar_init(p->db, 0, 0);
 
30614 }
30615 #endif
30616 #ifdef SQLITE_SHELL_EXTFUNCS
30617 /* Create a preprocessing mechanism for extensions to make
30618 * their own provisions for being built into the shell.
30619 * This is a short-span macro. See further below for usage.
30620 */
@@ -30661,10 +31198,12 @@
30661 shell_complete_sql, 0, 0);
30662 sqlite3_create_function(p->db, "shell_complete_sql", 2, SQLITE_UTF8, p,
30663 shell_complete_sql, 0, 0);
30664 sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
30665 shellUSleepFunc, 0, 0);
 
 
30666 #ifndef SQLITE_NOHAVE_SYSTEM
30667 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
30668 editFunc, 0, 0);
30669 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
30670 editFunc, 0, 0);
@@ -31624,11 +32163,13 @@
31624 while( (c=(*(zGlob++))) == '*' || c=='?' ){
31625 if( c=='?' && (*(z++))==0 ) return 0;
31626 }
31627 if( c==0 ){
31628 return 1;
31629 }else if( c=='[' ){
 
 
31630 while( *z && testcase_glob(zGlob-1,z)==0 ){
31631 z++;
31632 }
31633 return (*z)!=0;
31634 }
@@ -32103,12 +32644,15 @@
32103 sqlite3_free(zPrev);
32104 zPrev = sqlite3_mprintf("%s", zParent);
32105 }
32106
32107 if( res==0 ){
 
32108 cli_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
32109 }else if( bVerbose ){
 
 
32110 cli_printf(out,
32111 "%s/* no extra indexes required for %s -> %s */\n",
32112 zIndent, zFrom, zTarget
32113 );
32114 }
@@ -33081,10 +33625,11 @@
33081 int rc = SQLITE_OK;
33082 const char *zRecoveryDb = ""; /* Name of "recovery" database. Debug only */
33083 const char *zLAF = "lost_and_found";
33084 int bFreelist = 1; /* 0 if --ignore-freelist is specified */
33085 int bRowids = 1; /* 0 if --no-rowids */
 
33086 sqlite3_recover *p = 0;
33087 int i = 0;
33088
33089 for(i=1; i<nArg; i++){
33090 char *z = azArg[i];
@@ -33107,10 +33652,13 @@
33107 i++;
33108 zLAF = azArg[i];
33109 }else
33110 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
33111 bRowids = 0;
 
 
 
33112 }
33113 else{
33114 cli_printf(stderr,"unexpected option: %s\n", azArg[i]);
33115 showHelp(pState->out, azArg[0]);
33116 return 1;
@@ -33127,10 +33675,11 @@
33127 sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
33128 sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
33129 sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
33130
33131 cli_printf(pState->out, ".dbconfig defensive off\n");
 
33132 sqlite3_recover_run(p);
33133 if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
33134 const char *zErr = sqlite3_recover_errmsg(p);
33135 int errCode = sqlite3_recover_errcode(p);
33136 cli_printf(stderr,"sql error: %s (%d)\n", zErr, errCode);
@@ -33910,11 +34459,11 @@
33910 import_cleanup(&sCtx);
33911 sqlite3_finalize(pStmt);
33912 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
33913 if( eVerbose>0 ){
33914 cli_printf(p->out,
33915 "Added %d rows with %d errors using %d lines of input\n",
33916 sCtx.nRow, sCtx.nErr, sCtx.nLine-1-iLineOffset);
33917 }
33918 return sCtx.nErr ? 1 : 0;
33919 }
33920
@@ -34144,21 +34693,21 @@
34144 p->mode.spec.bBorder = k & 0x3;
34145 }
34146 chng = 1;
34147 }else if( 0<=(k=pickStr(z,0,
34148 "-charlimit","-linelimit","-titlelimit","-multiinsert","")) ){
34149 int w; /* 0 1 2 3 */
34150 if( i+1>=nArg ){
34151 dotCmdError(p, i, "missing argument", 0);
34152 return 1;
34153 }
34154 w = integerValue(azArg[++i]);
34155 switch( k ){
34156 case 0: p->mode.spec.nCharLimit = w; break;
34157 case 1: p->mode.spec.nLineLimit = w; break;
34158 case 2: p->mode.spec.nTitleLimit = w; break;
34159 default: p->mode.spec.nMultiInsert = w; break;
34160 }
34161 chng = 1;
34162 }else if( 0<=(k=pickStr(z,0,"-tablename","-rowsep","-colsep","-null","")) ){
34163 /* 0 1 2 3 */
34164 if( i+1>=nArg ){
@@ -34305,13 +34854,15 @@
34305 memcpy(p->mode.zFpFmt, azArg[i], strlen(azArg[i])+1);
34306 p->mode.spec.zFpFmt = p->mode.zFpFmt;
34307 }
34308 chng = 1;
34309 }else if( optionMatch(z,"reset") ){
34310 int saved_eMode = p->mode.eMode;
34311 modeFree(&p->mode);
 
34312 modeChange(p, saved_eMode);
 
34313 }else if( optionMatch(z,"rowcount") ){
34314 if( i+1>=nArg ){
34315 dotCmdError(p, i, "missing argument", 0);
34316 return 1;
34317 }
@@ -34893,11 +35444,11 @@
34893
34894 /*
34895 ** Return true if the argument is <<MARK for some arbitrary mark
34896 */
34897 static int isHereDoc(const char *z){
34898 return z[0]=='<' && z[1]=='<' && z[2]!=0;
34899 }
34900
34901 /*
34902 ** Capture lines of input text up until a line that matches zTerminator.
34903 ** Return a memory buffer (allocated using sqlite3_malloc64()) that
@@ -34912,42 +35463,93 @@
34912 if( cli_strncmp(zTerminator,zLine,nTerminator)==0 ) break;
34913 sqlite3_str_appendall(pHeredoc, zLine);
34914 }
34915 return sqlite3_str_finish(pHeredoc);
34916 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34917
34918 /*
34919 ** DOT-COMMAND: .check
34920 ** USAGE: .check [OPTIONS] PATTERN
34921 **
34922 ** Verify results of commands since the most recent .testcase command.
34923 ** Restore output to the console, unless --keep is used.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34924 **
34925 ** If PATTERN starts with "<<ENDMARK" then the actual pattern is taken from
34926 ** subsequent lines of text up to the first line that begins with ENDMARK.
34927 ** All pattern lines and the ENDMARK are discarded.
 
34928 **
34929 ** Options:
34930 ** --exact Do an exact comparison including leading and
34931 ** trailing whitespace.
34932 ** --glob Treat PATTERN as a GLOB
34933 ** --keep Do not reset the testcase. More .check commands
34934 ** will follow.
34935 ** --notglob Output should not match PATTERN
34936 ** --show Write testcase output to the screen, for debugging.
 
 
 
 
 
 
 
 
34937 */
34938 static int dotCmdCheck(ShellState *p){
34939 int nArg = p->dot.nArg; /* Number of arguments */
34940 char **azArg = p->dot.azArg; /* Text of the arguments */
34941 int i; /* Loop counter */
34942 int k; /* Result of pickStr() */
34943 char *zTest; /* Textcase result */
34944 int bKeep = 0; /* --keep option */
34945 char *zCheck = 0; /* PATTERN argument */
34946 char *zPattern = 0; /* Actual test pattern */
34947 int eCheck = 0; /* 1: --glob, 2: --notglob, 3: --exact */
34948 int isOk; /* True if results are OK */
 
 
 
34949 sqlite3_int64 iStart = p->lineno; /* Line number of .check statement */
34950
34951 if( p->mIf!=0 ){
34952 /* Unlike most other dot-commands, the .check command runs even if
34953 ** inside the false branch of a .if. It needs to do this so that it
@@ -34959,10 +35561,11 @@
34959 }
34960 if( p->zTestcase[0]==0 ){
34961 dotCmdError(p, 0, "no .testcase is active", 0);
34962 return 1;
34963 }
 
34964 for(i=1; i<nArg; i++){
34965 char *z = azArg[i];
34966 if( z[0]=='-' && z[1]=='-' && z[2]!=0 ) z++;
34967 if( cli_strcmp(z,"-keep")==0 ){
34968 bKeep = 1;
@@ -34970,87 +35573,157 @@
34970 if( sqlite3_str_length(cli_output_capture)>0 ){
34971 sqlite3_fprintf(stdout, "%s", sqlite3_str_value(cli_output_capture));
34972 }
34973 bKeep = 1;
34974 }else if( z[0]=='-'
34975 && (k = pickStr(&z[1],0,"glob","notglob","exact",""))>=0
 
 
34976 ){
34977 if( eCheck && eCheck!=k+1 ){
 
 
 
 
 
 
34978 dotCmdError(p, i, "incompatible with prior options",0);
34979 return 1;
34980 }
34981 eCheck = k+1;
34982 }else if( zCheck ){
34983 dotCmdError(p, i, "unknown option", 0);
34984 return 1;
34985 }else{
34986 zCheck = azArg[i];
 
 
 
 
 
34987 }
34988 }
34989 if( zCheck==0 ){
34990 dotCmdError(p, 0, "no PATTERN specified", 0);
34991 return 1;
34992 }
34993 if( sqlite3_str_length(cli_output_capture) ){
34994 zTest = sqlite3_str_value(cli_output_capture);
34995 shell_check_oom(zTest);
34996 }else{
34997 zTest = "";
34998 }
34999 p->nTestRun++;
35000 if( isHereDoc(zCheck) ){
35001 zPattern = captureHereDoc(p, zCheck+2);
35002 if( zPattern==0 ){
35003 zPattern = sqlite3_mprintf("");
35004 }
35005 }else{
35006 zPattern = zCheck;
35007 }
35008 shell_check_oom(zPattern);
35009 switch( eCheck ){
35010 case 1: {
35011 char *zGlob = sqlite3_mprintf("*%s*", zPattern);
35012 isOk = testcase_glob(zGlob, zTest)!=0;
35013 sqlite3_free(zGlob);
35014 break;
35015 }
35016 case 2: {
35017 char *zGlob = sqlite3_mprintf("*%s*", zPattern);
35018 isOk = testcase_glob(zGlob, zTest)==0;
35019 sqlite3_free(zGlob);
35020 break;
35021 }
35022 case 3: {
35023 isOk = cli_strcmp(zTest,zPattern)==0;
35024 break;
35025 }
35026 default: {
35027 /* Skip leading and trailing \n and \r on both pattern and test output */
35028 const char *z1 = zPattern;
35029 const char *z2 = zTest;
35030 size_t n1, n2;
35031 while( z1[0]=='\n' || z1[0]=='\r' ) z1++;
35032 n1 = strlen(z1);
35033 while( n1>0 && (z1[n1-1]=='\n' || z1[n1-1]=='\r') ) n1--;
35034 while( z2[0]=='\n' || z2[0]=='\r' ) z2++;
35035 n2 = strlen(z2);
35036 while( n2>0 && (z2[n2-1]=='\n' || z2[n2-1]=='\r') ) n2--;
35037 isOk = n1==n2 && memcmp(z1,z2,n1)==0;
35038 break;
35039 }
35040 }
35041 if( !isOk ){
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35042 sqlite3_fprintf(stderr,
35043 "%s:%lld: .check failed for testcase %s\n",
35044 p->zInFile, iStart, p->zTestcase);
35045 p->nTestErr++;
35046 sqlite3_fprintf(stderr, "Expected: [%s]\n", zPattern);
35047 sqlite3_fprintf(stderr, "Got: [%s]\n", zTest);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35048 }
35049 if( zPattern!=zCheck ){
35050 sqlite3_free(zPattern);
35051 }
35052 if( !bKeep ){
35053 output_reset(p);
35054 p->zTestcase[0] = 0;
35055 }
35056 return 0;
@@ -35151,11 +35824,11 @@
35151 ** DOT-COMMAND: .testcase
35152 ** USAGE: .testcase [OPTIONS] NAME
35153 **
35154 ** Start a new test case identified by NAME. All output
35155 ** through the next ".check" command is captured for comparison. See the
35156 ** ".check" command for additional informatioon.
35157 **
35158 ** Options:
35159 ** --error-prefix TEXT Change error message prefix text to TEXT
35160 */
35161 static int dotCmdTestcase(ShellState *p){
@@ -35172,11 +35845,11 @@
35172 dotCmdError(p, i, "missing argument", 0);
35173 return 1;
35174 }
35175 free(p->zErrPrefix);
35176 i++;
35177 p->zErrPrefix = azArg[i][0]==0 ? 0 : strdup(azArg[i]);
35178 }else if( zName ){
35179 dotCmdError(p, i, "unknown option", 0);
35180 return 1;
35181 }else{
35182 zName = azArg[i];
@@ -35329,11 +36002,148 @@
35329 p->mElse &= ~(1<<p->nIfLevel);
35330 p->mIfHasBeenTrue &= ~(1<<p->nIfLevel);
35331 return 0;
35332 }
35333
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35335
35336 /*
35337 ** Enlarge the space allocated in p->dot so that it can hold more
35338 ** than nArg parsed command-line arguments.
35339 */
@@ -35344,11 +36154,10 @@
35344 p->dot.aiOfst = realloc(p->dot.aiOfst,p->dot.nAlloc*sizeof(int));
35345 shell_check_oom(p->dot.aiOfst);
35346 p->dot.abQuot = realloc(p->dot.abQuot,p->dot.nAlloc);
35347 shell_check_oom(p->dot.abQuot);
35348 }
35349
35350
35351 /*
35352 ** Parse input line zLine up into individual arguments. Retain the
35353 ** parse in the p->dot substructure.
35354 */
@@ -35768,21 +36577,25 @@
35768 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
35769 { "reverse_scanorder", SQLITE_DBCONFIG_REVERSE_SCANORDER },
35770 { "stmt_scanstatus", SQLITE_DBCONFIG_STMT_SCANSTATUS },
35771 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
35772 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA },
 
 
 
35773 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
35774 };
35775 int ii, v;
35776 open_db(p, 0);
35777 for(ii=0; ii<ArraySize(aDbConfig); ii++){
35778 if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
35779 if( nArg>=3 ){
35780 if( aDbConfig[ii].op==SQLITE_DBCONFIG_FP_DIGITS ){
35781 sqlite3_db_config(p->db, aDbConfig[ii].op, atoi(azArg[2]), 0);
35782 }else{
35783 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
 
35784 }
35785 }
35786 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
35787 if( aDbConfig[ii].op==SQLITE_DBCONFIG_FP_DIGITS ){
35788 cli_printf(p->out, "%19s %d\n", aDbConfig[ii].zName, v);
@@ -35804,10 +36617,11 @@
35804 }else
35805 #endif /* SQLITE_SHELL_HAVE_RECOVER */
35806
35807 if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbtotxt", n)==0 ){
35808 open_db(p, 0);
 
35809 rc = shell_dbtotxt_command(p, nArg, azArg);
35810 }else
35811
35812 if( c=='d' && n==8 && cli_strncmp(azArg[0], "diskused", n)==0 ){
35813 const char *zSchema = 0;
@@ -35980,34 +36794,11 @@
35980 if( c=='e' && n==5 && cli_strcmp(azArg[0],"endif")==0 ){
35981 rc = dotCmdEndif(p);
35982 }else
35983
35984 if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
35985 if( nArg==2 ){
35986 if( p->mode.autoEQPtrace ){
35987 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
35988 p->mode.autoEQPtrace = 0;
35989 }
35990 if( cli_strcmp(azArg[1],"full")==0 ){
35991 p->mode.autoEQP = AUTOEQP_full;
35992 }else if( cli_strcmp(azArg[1],"trigger")==0 ){
35993 p->mode.autoEQP = AUTOEQP_trigger;
35994 #ifdef SQLITE_DEBUG
35995 }else if( cli_strcmp(azArg[1],"trace")==0 ){
35996 p->mode.autoEQP = AUTOEQP_full;
35997 p->mode.autoEQPtrace = 1;
35998 open_db(p, 0);
35999 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
36000 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
36001 #endif
36002 }else{
36003 p->mode.autoEQP = (u8)booleanValue(azArg[1]);
36004 }
36005 }else{
36006 eputz("Usage: .eqp off|on|trace|trigger|full\n");
36007 rc = 1;
36008 }
36009 }else
36010
36011 #ifndef SQLITE_SHELL_FIDDLE
36012 if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
36013 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) cli_exit(rc);
@@ -36191,14 +36982,15 @@
36191
36192 if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
36193 ShellState data;
36194 int doStats = 0;
36195 int hasStat[5];
36196 int flgs = 0;
36197 char *zSql;
36198 if( nArg==2 && optionMatch(azArg[1], "indent") ){
36199 nArg = 1;
 
36200 }
36201 if( nArg!=1 ){
36202 eputz("Usage: .fullschema ?--indent?\n");
36203 rc = 1;
36204 goto meta_command_exit;
@@ -36209,11 +37001,11 @@
36209 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
36210 " FROM sqlite_schema UNION ALL"
36211 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
36212 "WHERE type!='meta' AND sql NOTNULL"
36213 " AND name NOT LIKE 'sqlite__%%' ESCAPE '_' "
36214 "ORDER BY x", flgs);
36215 memcpy(&data, p, sizeof(data));
36216 data.mode.spec.bTitles = QRF_No;
36217 data.mode.eMode = MODE_List;
36218 data.mode.spec.eText = QRF_TEXT_Plain;
36219 data.mode.spec.nCharLimit = 0;
@@ -37149,10 +37941,14 @@
37149 rc = 1;
37150 }
37151 close_db(pSrc);
37152 }else
37153 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
 
 
 
 
37154
37155 if( c=='s' &&
37156 (cli_strncmp(azArg[0], "scanstats", n)==0 ||
37157 cli_strncmp(azArg[0], "scanstatus", n)==0)
37158 ){
@@ -38109,17 +38905,17 @@
38109 ** -LABEL Disable the named optimization
38110 **
38111 ** INTEGER Mask of optimizations to disable
38112 */
38113 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
38114 unsigned int curOpt; /* Current opt-disabled mask */
38115 unsigned int newOpt; /* New opt-disabled mask */
38116 unsigned int m; /* A working mask value */
38117 sqlite3_uint64 mm; /* 64-bit working mask value */
38118 int ii, jj; /* Loop counters */
38119 int nOff; /* Number of disabled optimizations */
38120 const char *zName; /* Name of an optimization */
 
38121
38122 sqlite3_test_control(SQLITE_TESTCTRL_GETOPT, p->db, &curOpt);
38123 newOpt = curOpt;
38124 for(ii=2; ii<nArg; ii++){
38125 const char *z = azArg[ii];
@@ -38133,11 +38929,16 @@
38133 zLabel = z;
38134 }else{
38135 newOpt = (unsigned int)strtol(z,0,0);
38136 }
38137 if( useLabel ){
38138 if( sqlite3_optimization_mask(zLabel,&mm)==SQLITE_NOTFOUND ){
 
 
 
 
 
38139 cli_printf(stderr,
38140 "Error: no such optimization: \"%s\"\n", zLabel);
38141 cli_puts("Should be one of: All", stderr);
38142 for(jj=0; jj<32; jj++){
38143 zName = sqlite3_optimization_name(1ull<<jj);
@@ -38145,11 +38946,10 @@
38145 }
38146 cli_puts("\n", stderr);
38147 rc = 1;
38148 goto meta_command_exit;
38149 }
38150 m = (u32)mm;
38151 if( useLabel=='+' ){
38152 newOpt &= ~m;
38153 }else{
38154 newOpt |= m;
38155 }
@@ -38156,33 +38956,35 @@
38156 }
38157 }
38158 if( curOpt!=newOpt ){
38159 sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,p->db,newOpt);
38160 }
38161 for(ii=nOff=0, m=1; ii<32; ii++, m <<= 1){
38162 if( m & newOpt ) nOff++;
38163 }
38164 if( nOff<12 ){
38165 cli_puts("+All", p->out);
38166 for(ii=0, m=1; ii<32; ii++, m <<= 1){
38167 if( (newOpt & m)!=0
38168 && (zName = sqlite3_optimization_name(m))!=0
38169 ){
38170 cli_printf(p->out, " -%s", zName);
38171 }
38172 }
38173 }else{
38174 cli_puts("-All", p->out);
38175 for(ii=0, m=1; ii<32; ii++, m <<= 1){
38176 if( (newOpt & m)==0
38177 && (zName = sqlite3_optimization_name(m))!=0
38178 ){
38179 cli_printf(p->out, " +%s", zName);
38180 }
38181 }
38182 }
38183 cli_puts("\n", p->out);
 
 
38184 rc2 = isOk = 3;
38185 break;
38186 }
38187
38188 /* sqlite3_test_control(int, db, int) */
@@ -38758,20 +39560,20 @@
38758 }else{
38759 p->eRestoreState = 7;
38760 }
38761 break;
38762 };
38763
38764 case 1: {
38765 int bIsDump = 0;
38766 const char *zExpect = "BEGIN TRANSACTION;";
38767 assert( strlen(zExpect)==18 );
38768 if( memcmp(zSql, zExpect, 19)==0 ){
38769 /* Now check if the database is empty. */
38770 const char *zQuery = "SELECT 1 FROM sqlite_schema LIMIT 1";
38771 sqlite3_stmt *pStmt = 0;
38772
38773 bIsDump = 1;
38774 shellPrepare(p->db, &rc, zQuery, &pStmt);
38775 if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
38776 bIsDump = 0;
38777 }
@@ -38780,26 +39582,26 @@
38780 if( bIsDump && rc==SQLITE_OK ){
38781 int bDefense = 0;
38782 int bDqsDdl = 0;
38783 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense);
38784 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl);
38785 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
38786 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, 0);
38787 p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0);
38788 }else{
38789 p->eRestoreState = 7;
38790 }
38791 break;
38792 }
38793
38794 default: {
38795 if( sqlite3_get_autocommit(p->db) ){
38796 if( (p->eRestoreState & 2) ){
38797 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, 0);
38798 }
38799 if( (p->eRestoreState & 4) ){
38800 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, 0);
38801 }
38802 p->eRestoreState = 7;
38803 }
38804 break;
38805 }
@@ -39402,10 +40204,11 @@
39402 " -nullvalue TEXT set text string for NULL values. Default ''\n"
39403 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
39404 " -pcachetrace trace all page cache operations\n"
39405 " -quote set '.mode quote'\n"
39406 " -readonly open the database read-only\n"
 
39407 " -safe enable safe-mode\n"
39408 " -screenwidth N use N as the default screenwidth \n"
39409 " -separator SEP set output column separator. Default: '|'\n"
39410 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
39411 " -sorterref SIZE sorter references threshold size\n"
@@ -39442,10 +40245,131 @@
39442 sputz(stdout, "WARNING: attempt to configure SQLite after"
39443 " initialization.\n");
39444 }
39445 }
39446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39447 #if HAVE_EDITLINE
39448 /*
39449 ** https://sqlite.org/forum/forumpost/aad7a634916ff050:
39450 **
39451 ** Calling setlocale(LC_...,"") is required to get libedit to accept
@@ -39462,11 +40386,11 @@
39462 */
39463 static void main_init(ShellState *p) {
39464 memset(p, 0, sizeof(*p));
39465 p->pAuxDb = &p->aAuxDb[0];
39466 p->shellFlgs = SHFLG_Lookaside;
39467 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, p);
39468 #if !defined(SQLITE_SHELL_FIDDLE)
39469 verify_uninitialized();
39470 #endif
39471 sqlite3_config(SQLITE_CONFIG_URI, 1);
39472 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
@@ -39622,10 +40546,11 @@
39622 int readStdin = 1;
39623 int noInit = 0; /* Do not read ~/.sqliterc if true */
39624 int nCmd = 0;
39625 int nOptsEnd = argc;
39626 int bEnableVfstrace = 0;
 
39627 char **azCmd = 0;
39628 int *aiCmd = 0;
39629 const char *zVfs = 0; /* Value of -vfs command-line option */
39630 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
39631
@@ -39716,11 +40641,15 @@
39716 #endif
39717 for(i=1; i<argc; i++){
39718 char *z;
39719 z = argv[i];
39720 if( z[0]!='-' || i>nOptsEnd ){
39721 if( data.aAuxDb->zDbFilename==0 && !isScriptFile(z,1) ){
 
 
 
 
39722 data.aAuxDb->zDbFilename = z;
39723 }else{
39724 /* Excess arguments are interpreted as SQL (or dot-commands) and
39725 ** mean that nothing is read from stdin */
39726 readStdin = 0;
@@ -39887,10 +40816,12 @@
39887 }else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
39888 /* skip over the argument */
39889 i++;
39890 }else if( cli_strcmp(z,"-cmdline-edit")==0 ){
39891 shellCmdLineEdit = booleanValue(cmdline_option_value(argc,argv,++i));
 
 
39892 }else if( cli_strcmp(z,"-test-argv")==0 ){
39893 /* Undocumented test option. Print the values in argv[] and exit.
39894 ** Use this to verify that any translation of the argv[], for example
39895 ** on Windows that receives wargv[] from the OS and must convert
39896 ** to UTF8 prior to calling this routine. */
@@ -39901,19 +40832,48 @@
39901 return 0;
39902 }else if( cli_strcmp(z,"-test-parse")==0 ){
39903 /* Undocumented test option. Read input normally and process all
39904 ** dot-commands. But do not process any SQL. Instead, whenever input
39905 ** text would have been processed as SQL, print a one-line summary of
39906 ** the input. This is used by test script to verify that the end-of-SQL
39907 ** parsing logic is working correctly. */
39908 data.bTestParse = 1;
39909 }
39910 }
39911 #ifndef SQLITE_SHELL_FIDDLE
39912 if( !bEnableVfstrace ) verify_uninitialized();
39913 #endif
39914
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39915
39916 #ifdef SQLITE_SHELL_INIT_PROC
39917 {
39918 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
39919 ** of a C-function that will perform initialization actions on SQLite that
@@ -40202,10 +41162,12 @@
40202 #endif
40203 }else if( cli_strcmp(z,"-safe")==0 ){
40204 data.bSafeMode = data.bSafeModePersist = 1;
40205 }else if( cli_strcmp(z,"-unsafe-testing")==0
40206 || cli_strcmp(z,"-unsafe")==0 ){
 
 
40207 /* Acted upon in first pass. */
40208 }else if( cli_strcmp(z,"-test-parse")==0 ){
40209 /* Acted upon in first pass. */
40210 }else{
40211 cli_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
@@ -40230,16 +41192,17 @@
40230 res = process_input(&data, azCmd[i]);
40231 fclose(data.in);
40232 }
40233 data.in = inSaved;
40234 data.lineno = savedLineno;
40235 if( res ) i = nCmd;
40236 }else if( azCmd[i][0]=='.' ){
40237 char *zErrCtx = malloc( 64 );
40238 shell_check_oom(zErrCtx);
40239 sqlite3_snprintf(64,zErrCtx,"argv[%i]:",aiCmd[i]);
40240 data.zInFile = "<cmdline>";
 
40241 data.zErrPrefix = zErrCtx;
40242 rc = do_meta_command(azCmd[i], &data);
40243 free(data.zErrPrefix);
40244 data.zErrPrefix = 0;
40245 if( rc ){
@@ -40350,10 +41313,11 @@
40350 modeFree(&data.aSavedModes[ii].mode);
40351 free(data.aSavedModes[ii].zTag);
40352 }
40353 free(data.aSavedModes);
40354 }
 
40355 free(data.zErrPrefix);
40356 free(data.zNonce);
40357 free(data.dot.zCopy);
40358 free(data.dot.azArg);
40359 free(data.dot.aiOfst);
@@ -40456,13 +41420,15 @@
40456 ** https://sqlite.org/forum/forumpost/0b41a25d65
40457 */
40458 cli_puts("Rolling back in-progress transaction.\n", stdout);
40459 sqlite3_exec(globalDb,"ROLLBACK", 0, 0, 0);
40460 }
40461 rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
 
40462 if( 0==rc ) sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
40463 sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
 
40464 }
40465 }
40466
40467 /*
40468 ** Uses the current database's VFS xRead to stream the db file's
40469
--- extsrc/shell.c
+++ extsrc/shell.c
@@ -25,10 +25,11 @@
25 ** ext/misc/sqlar.c
26 ** ext/misc/sqlite3_stdio.c
27 ** ext/misc/sqlite3_stdio.h
28 ** ext/misc/stmtrand.c
29 ** ext/misc/strdup.c
30 ** ext/misc/tryeval.c
31 ** ext/misc/uint.c
32 ** ext/misc/vfstrace.c
33 ** ext/misc/windirent.h
34 ** ext/misc/zipfile.c
35 ** ext/qrf/qrf.c
@@ -1655,10 +1656,16 @@
1656 n = (n+8)&~7;
1657 }else if( z[0]=='\n' || z[0]=='\r' ){
1658 nNL++;
1659 if( n>mx ) mx = n;
1660 n = 0;
1661 }else{
1662 /* Any other control character is shown by qrfAppendWithTabs()
1663 ** as a one-column-wide Control Picture symbol, and is counted as
1664 ** one column by qrfWrapLine(). Count it as one column here too,
1665 ** so that columns are wide enough to hold it. */
1666 n++;
1667 }
1668 z++;
1669 }
1670 }else if( (0x80&z[0])==0 ){
1671 n++;
@@ -2009,10 +2016,11 @@
2016 */
2017 static int qrfTitleLimit(char *zIn, int N){
2018 unsigned char *z = (unsigned char*)zIn;
2019 int n = 0;
2020 unsigned char *zEllipsis = 0;
2021 int nEllipsis = 0; /* Display width of the text before zEllipsis */
2022 while( 1 /*exit-by-break*/ ){
2023 if( z[0]<' ' ){
2024 int k;
2025 if( z[0]==0 ){
2026 zEllipsis = 0;
@@ -2025,24 +2033,28 @@
2033 z[0] = ' ';
2034 }else{
2035 z++;
2036 }
2037 }else if( (0x80&z[0])==0 ){
2038 if( n>=(N-3) && zEllipsis==0 ){ zEllipsis = z; nEllipsis = n; }
2039 if( n==N ){ z[0] = 0; break; }
2040 n++;
2041 z++;
2042 }else{
2043 int u = 0;
2044 int len = sqlite3_qrf_decode_utf8(z, &u);
2045 int w = sqlite3_qrf_wcwidth(u); /* Display width, not byte count */
2046 if( n+w>(N-3) && zEllipsis==0 ){ zEllipsis = z; nEllipsis = n; }
2047 if( n+w>N ){ z[0] = 0; break; }
2048 z += len;
2049 n += w;
2050 }
2051 }
2052 if( zEllipsis && N>=3 ){
2053 memcpy(zEllipsis,"...",4);
2054 n = nEllipsis + 3; /* Width of the text kept plus the "..." */
2055 }
2056 return n;
2057 }
2058
2059
2060 /*
@@ -2178,11 +2190,16 @@
2190 }
2191 }
2192 break;
2193 }
2194 case SQLITE_NULL: {
2195 if( p->spec.eText==QRF_TEXT_Html ){
2196 /* The NULL text is user-supplied (--null) and must be escaped */
2197 qrfEncodeText(p, pOut, p->spec.zNull);
2198 }else{
2199 sqlite3_str_appendall(pOut, p->spec.zNull);
2200 }
2201 break;
2202 }
2203 case SQLITE_TEXT: {
2204 const char *zTxt = (const char*)sqlite3_column_text(p->pStmt,iCol);
2205 qrfEncodeText(p, pOut, zTxt);
@@ -2240,11 +2257,12 @@
2257
2258 /*
2259 ** Store string zUtf to pOut as w characters. If w is negative,
2260 ** then right-justify the text. W is the width in display characters, not
2261 ** in bytes. Double-width unicode characters count as two characters.
2262 ** VT100 escape sequences and other control characters count as zero.
2263 ** And so forth.
2264 */
2265 static void qrfWidthPrint(Qrf *p, sqlite3_str *pOut, int w, const char *zUtf){
2266 const unsigned char *a = (const unsigned char*)zUtf;
2267 static const int mxW = 10000000;
2268 unsigned char c;
@@ -2270,10 +2288,14 @@
2288 }
2289 i += len;
2290 n += x;
2291 }else if( c==0x1b && (k = qrfIsVt100(&a[i]))>0 ){
2292 i += k;
2293 }else if( c<0x20 ){
2294 /* Other control characters are zero-width, as in
2295 ** sqlite3_qrf_wcswidth() */
2296 i++;
2297 }else if( n>=aw ){
2298 break;
2299 }else{
2300 n++;
2301 i++;
@@ -3865,11 +3887,11 @@
3887 if( p->spec.zFpFmt==0 ) p->spec.zFpFmt = "%!0.17g";
3888 break;
3889 }
3890 case QRF_STYLE_Html: {
3891 p->spec.eText = QRF_TEXT_Html;
3892 if( pSpec->zNull==0 ) p->spec.zNull = "null";
3893 break;
3894 }
3895 case QRF_STYLE_Insert: {
3896 p->spec.eText = QRF_TEXT_Sql;
3897 p->spec.zNull = "NULL";
@@ -6314,14 +6336,15 @@
6336 z = sqlite3_malloc64( (sqlite3_int64)p->nDigit+8 );
6337 if( z==0 ){
6338 sqlite3_result_error_nomem(pCtx);
6339 return;
6340 }
6341 if( p->sign ){
6342 for(i=0; i<p->nDigit && p->a[i]==0; i++){}
6343 if( i==p->nDigit ) p->sign = 0;
6344 }
6345 i = 0;
 
 
 
6346 if( p->sign ){
6347 z[0] = '-';
6348 i = 1;
6349 }
6350 n = p->nDigit - p->nFrac;
@@ -7205,45 +7228,62 @@
7228 char c;
7229 while( nc-- > 0 && (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s;
7230 return s;
7231 }
7232
7233 /* Decode base64 text into a byte buffer.
7234 **
7235 ** Whitespace is ignored wherever it appears, including inside a group
7236 ** of four base64 digits. A pad character fills one position of its
7237 ** group with zero bits. Any other non-base64 character inside a group
7238 ** ends the decode. Each group yields only the whole bytes encoded by
7239 ** the base64 digits actually present in it.
7240 */
7241 static u8* fromBase64( char *pIn, int ncIn, u8 *pOut ){
7242 if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
7243 while( ncIn>0 && *pIn!=PAD_CHAR ){
7244 static signed char nboi[] = { 0, 0, 1, 2, 3 };
7245 char *pUse = skipNonB64(pIn, ncIn);
7246 unsigned long qv = 0L;
7247 int nbo, nac = 0, ndg = 0;
7248 ncIn -= (pUse - pIn);
7249 pIn = pUse;
7250 if( ncIn>=4 ){
7251 /* Fast path: a complete group of four base64 digits. */
7252 u8 d0 = BX_DV_PROTO(pIn[0]), d1 = BX_DV_PROTO(pIn[1]);
7253 u8 d2 = BX_DV_PROTO(pIn[2]), d3 = BX_DV_PROTO(pIn[3]);
7254 if( IS_BX_DIGIT(d0|d1|d2|d3) ){
7255 qv = (unsigned long)d0<<18 | (unsigned long)d1<<12 | d2<<6 | d3;
7256 pOut[0] = (qv>>16) & 0xff;
7257 pOut[1] = (qv>>8) & 0xff;
7258 pOut[2] = (qv) & 0xff;
7259 pOut += 3;
7260 pIn += 4;
7261 ncIn -= 4;
7262 continue;
7263 }
7264 }
7265 /* Gather up to four group positions: digits and pad characters. */
7266 while( nac<4 && ncIn>0 ){
7267 u8 bdp = BX_DV_PROTO(*pIn);
7268 if( IS_BX_DIGIT(bdp) ){
 
 
7269 qv = qv<<6 | bdp;
7270 ++nac;
7271 ++ndg;
7272 }else if( IS_BX_PAD(bdp) ){
7273 qv <<= 6;
7274 ++nac;
7275 }else if( !IS_BX_WS(bdp) ){
7276 /* Dark non-digits terminate the decode. */
7277 ncIn = 0;
7278 break;
7279 }
7280 ++pIn;
7281 --ncIn;
7282 }
7283 qv <<= 6*(4-nac);
7284 nbo = nboi[ndg];
7285 switch( nbo ){
7286 case 3:
7287 pOut[2] = (qv) & 0xff;
7288 deliberate_fall_through; /* FALLTHRU */
7289 case 2:
@@ -7867,11 +7907,11 @@
7907 { OPT_MASK(16), "PropagateConst" },
7908 { OPT_MASK(17), "MinMaxOpt" },
7909 { OPT_MASK(18), "SeekScan" },
7910 { OPT_MASK(19), "OmitOrderBy" },
7911 { OPT_MASK(20), "BloomFilter" },
7912 { OPT_MASK(21), "DevTest" },
7913 { OPT_MASK(22), "BalancedMerge" },
7914 { OPT_MASK(23), "ReleaseReg" },
7915 { OPT_MASK(24), "FlttnUnionAll" },
7916 { OPT_MASK(25), "IndexedExpr" },
7917 { OPT_MASK(26), "Coroutines" },
@@ -7880,10 +7920,11 @@
7920 { OPT_MASK(29), "OrderBySubq" },
7921 { OPT_MASK(29), "OrderBySubquery" }, /* Alias for prior */
7922 { OPT_MASK(30), "StarQuery" },
7923 { OPT_MASK(31), "ExistsToJoin" },
7924 { OPT_MASK(32), "UnionLimit" },
7925 { OPT_MASK(33), "HavingToWhere" },
7926 /* Special names */
7927 { 0xffffffffffffffffULL, "All" },
7928 { 0x0000000000000000ULL, "None" },
7929 };
7930
@@ -8284,970 +8325,10 @@
8325 }
8326 return rc;
8327 }
8328
8329 /************************* End ext/misc/ieee754.c ********************/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8330 /************************* Begin ext/misc/regexp.c ******************/
8331 /*
8332 ** 2012-11-13
8333 **
8334 ** The author disclaims copyright to this source code. In place of
@@ -9938,15 +9019,11 @@
9019 if( re_resize(pRe, 30) ){
9020 zErr = pRe->zErr;
9021 re_free(pRe);
9022 return zErr;
9023 }
9024 re_append(pRe, RE_OP_ANYSTAR, 0);
 
 
 
 
9025 pRe->sIn.z = (unsigned char*)zIn;
9026 pRe->sIn.i = 0;
9027 pRe->sIn.mx = (int)strlen(zIn);
9028 zErr = re_subcompile_re(pRe);
9029 if( zErr ){
@@ -9958,10 +9035,23 @@
9035 *ppRe = pRe;
9036 }else{
9037 re_free(pRe);
9038 return "unrecognized character";
9039 }
9040
9041 /* If the regex begins with "^" and has no "|" at the top level, then
9042 ** the whole regex is anchored at the start of the input and the
9043 ** initial ".*" is not needed. Convert it into a no-op so that
9044 ** re_match() can stop as soon as the start of the input fails to
9045 ** match. A "|" at the top level would have caused a FORK to be
9046 ** inserted at aOp[1], so aOp[1]==RE_OP_ATSTART is sufficient. Do
9047 ** not remove the initial "^" itself, as there might be jumps back
9048 ** to it, as in "^+". */
9049 if( pRe->aOp[1]==RE_OP_ATSTART ){
9050 pRe->aOp[0] = RE_OP_GOTO;
9051 pRe->aArg[0] = 1;
9052 }
9053
9054 /* The following is a performance optimization. If the regex begins with
9055 ** ".*" (if the input regex lacks an initial "^") and afterwards there are
9056 ** one or more matching characters, enter those matching characters into
9057 ** zInit[]. The re_match() routine can then search ahead in the input
@@ -10177,10 +9267,1133 @@
9267 }
9268 return rc;
9269 }
9270
9271 /************************* End ext/misc/regexp.c ********************/
9272 /************************* Begin ext/misc/series.c ******************/
9273 /*
9274 ** 2015-08-18, 2023-04-28
9275 **
9276 ** The author disclaims copyright to this source code. In place of
9277 ** a legal notice, here is a blessing:
9278 **
9279 ** May you do good and not evil.
9280 ** May you find forgiveness for yourself and forgive others.
9281 ** May you share freely, never taking more than you give.
9282 **
9283 *************************************************************************
9284 **
9285 ** This file demonstrates how to create a table-valued-function using
9286 ** a virtual table. This demo implements the generate_series() function
9287 ** which gives the same results as the eponymous function in PostgreSQL,
9288 ** within the limitation that its arguments are signed 64-bit integers.
9289 **
9290 ** Considering its equivalents to generate_series(start,stop,step): A
9291 ** value V[n] sequence is produced for integer n ascending from 0 where
9292 ** ( V[n] == start + n * step && sgn(V[n] - stop) * sgn(step) >= 0 )
9293 ** for each produced value (independent of production time ordering.)
9294 **
9295 ** All parameters must be either integer or convertable to integer.
9296 ** The start parameter is required.
9297 ** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
9298 ** The step parameter defaults to 1 and 0 is treated as 1.
9299 **
9300 ** Examples:
9301 **
9302 ** SELECT * FROM generate_series(0,100,5);
9303 **
9304 ** The query above returns integers from 0 through 100 counting by steps
9305 ** of 5. In other words, 0, 5, 10, 15, ..., 90, 95, 100. There are a total
9306 ** of 21 rows.
9307 **
9308 ** SELECT * FROM generate_series(0,100);
9309 **
9310 ** Integers from 0 through 100 with a step size of 1. 101 rows.
9311 **
9312 ** SELECT * FROM generate_series(20) LIMIT 10;
9313 **
9314 ** Integers 20 through 29. 10 rows.
9315 **
9316 ** SELECT * FROM generate_series(0,-100,-5);
9317 **
9318 ** Integers 0 -5 -10 ... -100. 21 rows.
9319 **
9320 ** SELECT * FROM generate_series(0,-1);
9321 **
9322 ** Empty sequence.
9323 **
9324 ** HOW IT WORKS
9325 **
9326 ** The generate_series "function" is really a virtual table with the
9327 ** following schema:
9328 **
9329 ** CREATE TABLE generate_series(
9330 ** value,
9331 ** start HIDDEN,
9332 ** stop HIDDEN,
9333 ** step HIDDEN
9334 ** );
9335 **
9336 ** The virtual table also has a rowid which is an alias for the value.
9337 **
9338 ** Function arguments in queries against this virtual table are translated
9339 ** into equality constraints against successive hidden columns. In other
9340 ** words, the following pairs of queries are equivalent to each other:
9341 **
9342 ** SELECT * FROM generate_series(0,100,5);
9343 ** SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
9344 **
9345 ** SELECT * FROM generate_series(0,100);
9346 ** SELECT * FROM generate_series WHERE start=0 AND stop=100;
9347 **
9348 ** SELECT * FROM generate_series(20) LIMIT 10;
9349 ** SELECT * FROM generate_series WHERE start=20 LIMIT 10;
9350 **
9351 ** The generate_series virtual table implementation leaves the xCreate method
9352 ** set to NULL. This means that it is not possible to do a CREATE VIRTUAL
9353 ** TABLE command with "generate_series" as the USING argument. Instead, there
9354 ** is a single generate_series virtual table that is always available without
9355 ** having to be created first.
9356 **
9357 ** The xBestIndex method looks for equality constraints against the hidden
9358 ** start, stop, and step columns, and if present, it uses those constraints
9359 ** to bound the sequence of generated values. If the equality constraints
9360 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
9361 ** xBestIndex returns a small cost when both start and stop are available,
9362 ** and a very large cost if either start or stop are unavailable. This
9363 ** encourages the query planner to order joins such that the bounds of the
9364 ** series are well-defined.
9365 **
9366 ** Update on 2024-08-22:
9367 ** xBestIndex now also looks for equality and inequality constraints against
9368 ** the value column and uses those constraints as additional bounds against
9369 ** the sequence range. Thus, a query like this:
9370 **
9371 ** SELECT value FROM generate_series($SA,$EA)
9372 ** WHERE value BETWEEN $SB AND $EB;
9373 **
9374 ** Is logically the same as:
9375 **
9376 ** SELECT value FROM generate_series(max($SA,$SB),min($EA,$EB));
9377 **
9378 ** Constraints on the value column can server as substitutes for constraints
9379 ** on the hidden start and stop columns. So, the following two queries
9380 ** are equivalent:
9381 **
9382 ** SELECT value FROM generate_series($S,$E);
9383 ** SELECT value FROM generate_series WHERE value BETWEEN $S and $E;
9384 **
9385 */
9386 /* #include "sqlite3ext.h" */
9387 SQLITE_EXTENSION_INIT1
9388 #include <assert.h>
9389 #include <string.h>
9390 #include <limits.h>
9391 #include <math.h>
9392
9393 #ifndef SQLITE_OMIT_VIRTUALTABLE
9394
9395 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
9396 ** serve as the underlying representation of a cursor that scans
9397 ** over rows of the result.
9398 **
9399 ** iOBase, iOTerm, and iOStep are the original values of the
9400 ** start=, stop=, and step= constraints on the query. These are
9401 ** the values reported by the start, stop, and step columns of the
9402 ** virtual table.
9403 **
9404 ** iBase, iTerm, iStep, and bDescp are the actual values used to generate
9405 ** the sequence. These might be different from the iOxxxx values.
9406 ** For example in
9407 **
9408 ** SELECT value FROM generate_series(1,11,2)
9409 ** WHERE value BETWEEN 4 AND 8;
9410 **
9411 ** The iOBase is 1, but the iBase is 5. iOTerm is 11 but iTerm is 7.
9412 ** Another example:
9413 **
9414 ** SELECT value FROM generate_series(1,15,3) ORDER BY value DESC;
9415 **
9416 ** The cursor initialization for the above query is:
9417 **
9418 ** iOBase = 1 iBase = 13
9419 ** iOTerm = 15 iTerm = 1
9420 ** iOStep = 3 iStep = 3 bDesc = 1
9421 **
9422 ** The actual step size is unsigned so that can have a value of
9423 ** +9223372036854775808 which is needed for querys like this:
9424 **
9425 ** SELECT value
9426 ** FROM generate_series(9223372036854775807,
9427 ** -9223372036854775808,
9428 ** -9223372036854775808)
9429 ** ORDER BY value ASC;
9430 **
9431 ** The setup for the previous query will be:
9432 **
9433 ** iOBase = 9223372036854775807 iBase = -1
9434 ** iOTerm = -9223372036854775808 iTerm = 9223372036854775807
9435 ** iOStep = -9223372036854775808 iStep = 9223372036854775808 bDesc = 0
9436 */
9437 /* typedef unsigned char u8; */
9438 typedef struct series_cursor series_cursor;
9439 struct series_cursor {
9440 sqlite3_vtab_cursor base; /* Base class - must be first */
9441 sqlite3_int64 iOBase; /* Original starting value ("start") */
9442 sqlite3_int64 iOTerm; /* Original terminal value ("stop") */
9443 sqlite3_int64 iOStep; /* Original step value */
9444 sqlite3_int64 iBase; /* Starting value to actually use */
9445 sqlite3_int64 iTerm; /* Terminal value to actually use */
9446 sqlite3_uint64 iStep; /* The step size */
9447 sqlite3_int64 iValue; /* Current value */
9448 u8 bDesc; /* iStep is really negative */
9449 u8 bDone; /* True if stepped past last element */
9450 u8 bLimit; /* There exists a limit clause */
9451 };
9452
9453 /*
9454 ** Computed the difference between two 64-bit signed integers using a
9455 ** convoluted computation designed to work around the silly restriction
9456 ** against signed integer overflow in C.
9457 */
9458 static sqlite3_uint64 span64(sqlite3_int64 a, sqlite3_int64 b){
9459 assert( a>=b );
9460 return (*(sqlite3_uint64*)&a) - (*(sqlite3_uint64*)&b);
9461 }
9462
9463 /*
9464 ** Add or substract an unsigned 64-bit integer from a signed 64-bit integer
9465 ** and return the new signed 64-bit integer.
9466 */
9467 static sqlite3_int64 add64(sqlite3_int64 a, sqlite3_uint64 b){
9468 sqlite3_uint64 x = *(sqlite3_uint64*)&a;
9469 x += b;
9470 return *(sqlite3_int64*)&x;
9471 }
9472 static sqlite3_int64 sub64(sqlite3_int64 a, sqlite3_uint64 b){
9473 sqlite3_uint64 x = *(sqlite3_uint64*)&a;
9474 x -= b;
9475 return *(sqlite3_int64*)&x;
9476 }
9477
9478 /*
9479 ** The seriesConnect() method is invoked to create a new
9480 ** series_vtab that describes the generate_series virtual table.
9481 **
9482 ** Think of this routine as the constructor for series_vtab objects.
9483 **
9484 ** All this routine needs to do is:
9485 **
9486 ** (1) Allocate the series_vtab object and initialize all fields.
9487 **
9488 ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
9489 ** result set of queries against generate_series will look like.
9490 */
9491 static int seriesConnect(
9492 sqlite3 *db,
9493 void *pUnused,
9494 int argcUnused, const char *const*argvUnused,
9495 sqlite3_vtab **ppVtab,
9496 char **pzErrUnused
9497 ){
9498 sqlite3_vtab *pNew;
9499 int rc;
9500
9501 /* Column numbers */
9502 #define SERIES_COLUMN_ROWID (-1)
9503 #define SERIES_COLUMN_VALUE 0
9504 #define SERIES_COLUMN_START 1
9505 #define SERIES_COLUMN_STOP 2
9506 #define SERIES_COLUMN_STEP 3
9507
9508 (void)pUnused;
9509 (void)argcUnused;
9510 (void)argvUnused;
9511 (void)pzErrUnused;
9512 rc = sqlite3_declare_vtab(db,
9513 "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
9514 if( rc==SQLITE_OK ){
9515 pNew = *ppVtab = sqlite3_malloc64( sizeof(*pNew) );
9516 if( pNew==0 ) return SQLITE_NOMEM;
9517 memset(pNew, 0, sizeof(*pNew));
9518 sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
9519 }
9520 return rc;
9521 }
9522
9523 /*
9524 ** This method is the destructor for series_cursor objects.
9525 */
9526 static int seriesDisconnect(sqlite3_vtab *pVtab){
9527 sqlite3_free(pVtab);
9528 return SQLITE_OK;
9529 }
9530
9531 /*
9532 ** Constructor for a new series_cursor object.
9533 */
9534 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
9535 series_cursor *pCur;
9536 (void)pUnused;
9537 pCur = sqlite3_malloc64( sizeof(*pCur) );
9538 if( pCur==0 ) return SQLITE_NOMEM;
9539 memset(pCur, 0, sizeof(*pCur));
9540 *ppCursor = &pCur->base;
9541 return SQLITE_OK;
9542 }
9543
9544 /*
9545 ** Destructor for a series_cursor.
9546 */
9547 static int seriesClose(sqlite3_vtab_cursor *cur){
9548 sqlite3_free(cur);
9549 return SQLITE_OK;
9550 }
9551
9552
9553 /*
9554 ** Advance a series_cursor to its next row of output.
9555 */
9556 static int seriesNext(sqlite3_vtab_cursor *cur){
9557 series_cursor *pCur = (series_cursor*)cur;
9558 if( pCur->iValue==pCur->iTerm ){
9559 pCur->bDone = 1;
9560 }else if( pCur->bDesc ){
9561 pCur->iValue = sub64(pCur->iValue, pCur->iStep);
9562 assert( pCur->iValue>=pCur->iTerm || pCur->bLimit );
9563 }else{
9564 pCur->iValue = add64(pCur->iValue, pCur->iStep);
9565 assert( pCur->iValue<=pCur->iTerm || pCur->bLimit );
9566 }
9567 return SQLITE_OK;
9568 }
9569
9570 /*
9571 ** Return values of columns for the row at which the series_cursor
9572 ** is currently pointing.
9573 */
9574 static int seriesColumn(
9575 sqlite3_vtab_cursor *cur, /* The cursor */
9576 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
9577 int i /* Which column to return */
9578 ){
9579 series_cursor *pCur = (series_cursor*)cur;
9580 sqlite3_int64 x = 0;
9581 switch( i ){
9582 case SERIES_COLUMN_START: x = pCur->iOBase; break;
9583 case SERIES_COLUMN_STOP: x = pCur->iOTerm; break;
9584 case SERIES_COLUMN_STEP: x = pCur->iOStep; break;
9585 default: x = pCur->iValue; break;
9586 }
9587 sqlite3_result_int64(ctx, x);
9588 return SQLITE_OK;
9589 }
9590
9591 #ifndef LARGEST_UINT64
9592 #define LARGEST_INT64 ((sqlite3_int64)0x7fffffffffffffffLL)
9593 #define LARGEST_UINT64 ((sqlite3_uint64)0xffffffffffffffffULL)
9594 #define SMALLEST_INT64 ((sqlite3_int64)0x8000000000000000LL)
9595 #endif
9596
9597 /*
9598 ** The rowid is the same as the value.
9599 */
9600 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
9601 series_cursor *pCur = (series_cursor*)cur;
9602 *pRowid = pCur->iValue;
9603 return SQLITE_OK;
9604 }
9605
9606 /*
9607 ** Return TRUE if the cursor has been moved off of the last
9608 ** row of output.
9609 */
9610 static int seriesEof(sqlite3_vtab_cursor *cur){
9611 series_cursor *pCur = (series_cursor*)cur;
9612 return pCur->bDone;
9613 }
9614
9615 /* True to cause run-time checking of the start=, stop=, and/or step=
9616 ** parameters. The only reason to do this is for testing the
9617 ** constraint checking logic for virtual tables in the SQLite core.
9618 */
9619 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
9620 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
9621 #endif
9622
9623 /*
9624 ** Return the number of steps between pCur->iBase and pCur->iTerm if
9625 ** the step width is pCur->iStep.
9626 */
9627 static sqlite3_uint64 seriesSteps(series_cursor *pCur){
9628 if( pCur->bDesc ){
9629 assert( pCur->iBase >= pCur->iTerm );
9630 return span64(pCur->iBase, pCur->iTerm)/pCur->iStep;
9631 }else{
9632 assert( pCur->iBase <= pCur->iTerm );
9633 return span64(pCur->iTerm, pCur->iBase)/pCur->iStep;
9634 }
9635 }
9636
9637 #if defined(SQLITE_ENABLE_MATH_FUNCTIONS) || defined(_WIN32)
9638 /*
9639 ** Case 1 (the most common case):
9640 ** The standard math library is available so use ceil() and floor() from there.
9641 */
9642 static double seriesCeil(double r){ return ceil(r); }
9643 static double seriesFloor(double r){ return floor(r); }
9644 #elif defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
9645 /*
9646 ** Case 2 (2nd most common): Use GCC/Clang builtins
9647 */
9648 static double seriesCeil(double r){ return __builtin_ceil(r); }
9649 static double seriesFloor(double r){ return __builtin_floor(r); }
9650 #else
9651 /*
9652 ** Case 3 (rarely happens): Use home-grown ceil() and floor() routines.
9653 */
9654 static double seriesCeil(double r){
9655 sqlite3_int64 x;
9656 if( r!=r ) return r;
9657 if( r<=(-4503599627370496.0) ) return r;
9658 if( r>=(+4503599627370496.0) ) return r;
9659 x = (sqlite3_int64)r;
9660 if( r==(double)x ) return r;
9661 if( r>(double)x ) x++;
9662 return (double)x;
9663 }
9664 static double seriesFloor(double r){
9665 sqlite3_int64 x;
9666 if( r!=r ) return r;
9667 if( r<=(-4503599627370496.0) ) return r;
9668 if( r>=(+4503599627370496.0) ) return r;
9669 x = (sqlite3_int64)r;
9670 if( r==(double)x ) return r;
9671 if( r<(double)x ) x--;
9672 return (double)x;
9673 }
9674 #endif
9675
9676 /* Convert a floating point value to its closest integer. Do so in
9677 ** a way that avoids 'outside the range of representable values' warnings
9678 ** from UBSAN.
9679 */
9680 static sqlite3_int64 seriesRealToI64(double r){
9681 if( r<-9223372036854774784.0 ) return SMALLEST_INT64;
9682 if( r>+9223372036854774784.0 ) return LARGEST_INT64;
9683 return (sqlite3_int64)r;
9684 }
9685
9686 /* Return true if the type of the value is TEXT or BLOB.
9687 */
9688 static int seriesIsTextOrBlob(sqlite3_value *pVal){
9689 int eType = sqlite3_value_type(pVal);
9690 return eType==SQLITE_TEXT || eType==SQLITE_BLOB;
9691 }
9692
9693 /*
9694 ** This method is called to "rewind" the series_cursor object back
9695 ** to the first row of output. This method is always called at least
9696 ** once prior to any call to seriesColumn() or seriesRowid() or
9697 ** seriesEof().
9698 **
9699 ** The query plan selected by seriesBestIndex is passed in the idxNum
9700 ** parameter. (idxStr is not used in this implementation.) idxNum
9701 ** is a bitmask showing which constraints are available:
9702 **
9703 ** 0x0001: start=VALUE
9704 ** 0x0002: stop=VALUE
9705 ** 0x0004: step=VALUE
9706 ** 0x0008: descending order
9707 ** 0x0010: ascending order
9708 ** 0x0020: LIMIT VALUE
9709 ** 0x0040: OFFSET VALUE
9710 ** 0x0080: value=VALUE
9711 ** 0x0100: value>=VALUE
9712 ** 0x0200: value>VALUE
9713 ** 0x1000: value<=VALUE
9714 ** 0x2000: value<VALUE
9715 **
9716 ** This routine should initialize the cursor and position it so that it
9717 ** is pointing at the first row, or pointing off the end of the table
9718 ** (so that seriesEof() will return true) if the table is empty.
9719 */
9720 static int seriesFilter(
9721 sqlite3_vtab_cursor *pVtabCursor,
9722 int idxNum, const char *idxStrUnused,
9723 int argc, sqlite3_value **argv
9724 ){
9725 series_cursor *pCur = (series_cursor *)pVtabCursor;
9726 int iArg = 0; /* Arguments used so far */
9727 int i; /* Loop counter */
9728 sqlite3_int64 iMin = SMALLEST_INT64; /* Smallest allowed output value */
9729 sqlite3_int64 iMax = LARGEST_INT64; /* Largest allowed output value */
9730 sqlite3_int64 iLimit = 0; /* if >0, the value of the LIMIT */
9731 sqlite3_int64 iOffset = 0; /* if >0, the value of the OFFSET */
9732
9733 (void)idxStrUnused;
9734
9735 /* If any constraints have a NULL value, then return no rows.
9736 ** See ticket https://sqlite.org/src/info/fac496b61722daf2
9737 */
9738 for(i=0; i<argc; i++){
9739 if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
9740 goto series_no_rows;
9741 }
9742 }
9743
9744 /* Capture the three HIDDEN parameters to the virtual table and insert
9745 ** default values for any parameters that are omitted.
9746 */
9747 if( idxNum & 0x01 ){
9748 pCur->iOBase = sqlite3_value_int64(argv[iArg++]);
9749 }else{
9750 pCur->iOBase = 0;
9751 }
9752 if( idxNum & 0x02 ){
9753 pCur->iOTerm = sqlite3_value_int64(argv[iArg++]);
9754 }else{
9755 pCur->iOTerm = 0xffffffff;
9756 }
9757 if( idxNum & 0x04 ){
9758 pCur->iOStep = sqlite3_value_int64(argv[iArg++]);
9759 if( pCur->iOStep==0 ) pCur->iOStep = 1;
9760 }else{
9761 pCur->iOStep = 1;
9762 }
9763
9764 /* If there are constraints on the value column but there are
9765 ** no constraints on the start, stop, and step columns, then
9766 ** initialize the default range to be the entire range of 64-bit signed
9767 ** integers. This range will contracted by the value column constraints
9768 ** further below.
9769 */
9770 if( (idxNum & 0x05)==0 && (idxNum & 0x0380)!=0 ){
9771 pCur->iOBase = SMALLEST_INT64;
9772 }
9773 if( (idxNum & 0x06)==0 && (idxNum & 0x3080)!=0 ){
9774 pCur->iOTerm = LARGEST_INT64;
9775 }
9776 pCur->iBase = pCur->iOBase;
9777 pCur->iTerm = pCur->iOTerm;
9778 if( pCur->iOStep>0 ){
9779 pCur->iStep = pCur->iOStep;
9780 }else if( pCur->iOStep>SMALLEST_INT64 ){
9781 pCur->iStep = -pCur->iOStep;
9782 }else{
9783 pCur->iStep = LARGEST_INT64;
9784 pCur->iStep++;
9785 }
9786 pCur->bDesc = pCur->iOStep<0;
9787 if( pCur->bDesc==0 && pCur->iBase>pCur->iTerm ){
9788 goto series_no_rows;
9789 }
9790 if( pCur->bDesc!=0 && pCur->iBase<pCur->iTerm ){
9791 goto series_no_rows;
9792 }
9793
9794 /* Extract the LIMIT and OFFSET values, but do not apply them yet.
9795 ** The range must first be constrained by the limits on value.
9796 */
9797 if( idxNum & 0x20 ){
9798 iLimit = sqlite3_value_int64(argv[iArg++]);
9799 if( idxNum & 0x40 ){
9800 iOffset = sqlite3_value_int64(argv[iArg++]);
9801 }
9802 if( iLimit>0 ) pCur->bLimit = 1;
9803 }
9804
9805 /* Narrow the range of iMin and iMax (the minimum and maximum outputs)
9806 ** based on equality and inequality constraints on the "value" column.
9807 **
9808 ** The "value" column has no affinity, so a TEXT or BLOB operand X is
9809 ** not converted into a number. Every INTEGER is less than any TEXT
9810 ** or BLOB, so "value=X", "value>X" and "value>=X" are never true and
9811 ** "value<X" and "value<=X" are always true. The type must be checked
9812 ** before sqlite3_value_numeric_type(), which would convert a TEXT
9813 ** value such as '3' into a number.
9814 */
9815 if( idxNum & 0x3380 ){
9816 if( idxNum & 0x0080 ){ /* value=X */
9817 if( seriesIsTextOrBlob(argv[iArg]) ){
9818 goto series_no_rows;
9819 }else if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
9820 double r = sqlite3_value_double(argv[iArg++]);
9821 if( r==seriesCeil(r)
9822 && r>=(double)SMALLEST_INT64
9823 && r<=(double)LARGEST_INT64
9824 ){
9825 iMin = iMax = seriesRealToI64(r);
9826 }else{
9827 goto series_no_rows;
9828 }
9829 }else{
9830 iMin = iMax = sqlite3_value_int64(argv[iArg++]);
9831 }
9832 }else{
9833 if( idxNum & 0x0300 ){ /* value>X (0x200) or value>=X (0x100) */
9834 if( seriesIsTextOrBlob(argv[iArg]) ){
9835 goto series_no_rows;
9836 }else if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
9837 double r = sqlite3_value_double(argv[iArg++]);
9838 if( r<=(double)SMALLEST_INT64 ){
9839 iMin = SMALLEST_INT64;
9840 }else if( r>(double)LARGEST_INT64 ){
9841 goto series_no_rows;
9842 }else{
9843 iMin = seriesRealToI64(seriesCeil(r));
9844 if( (idxNum & 0x0200)!=0 && r==seriesCeil(r) ){
9845 if( iMin==LARGEST_INT64 ) goto series_no_rows;
9846 iMin++;
9847 }
9848 }
9849 }else{
9850 iMin = sqlite3_value_int64(argv[iArg++]);
9851 if( (idxNum & 0x0200)!=0 ){
9852 if( iMin==LARGEST_INT64 ){
9853 goto series_no_rows;
9854 }else{
9855 iMin++;
9856 }
9857 }
9858 }
9859 }
9860 if( idxNum & 0x3000 ){ /* value<X (0x2000) or value<=X (0x1000) */
9861 if( seriesIsTextOrBlob(argv[iArg]) ){
9862 iArg++; /* No upper bound */
9863 }else if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
9864 double r = sqlite3_value_double(argv[iArg++]);
9865 if( r>=(double)LARGEST_INT64 ){
9866 iMax = LARGEST_INT64;
9867 }else if( r<=(double)SMALLEST_INT64 ){
9868 goto series_no_rows;
9869 }else{
9870 iMax = seriesRealToI64(seriesFloor(r));
9871 if( (idxNum & 0x2000)!=0 && r==seriesFloor(r) ){
9872 if( iMax==SMALLEST_INT64 ) goto series_no_rows;
9873 iMax--;
9874 }
9875 }
9876 }else{
9877 iMax = sqlite3_value_int64(argv[iArg++]);
9878 if( idxNum & 0x2000 ){
9879 if( iMax==SMALLEST_INT64 ){
9880 goto series_no_rows;
9881 }else{
9882 iMax--;
9883 }
9884 }
9885 }
9886 }
9887 if( iMin>iMax ){
9888 goto series_no_rows;
9889 }
9890 }
9891
9892 /* Try to reduce the range of values to be generated based on
9893 ** constraints on the "value" column.
9894 */
9895 if( pCur->bDesc==0 ){
9896 if( pCur->iBase<iMin ){
9897 sqlite3_uint64 span = span64(iMin,pCur->iBase);
9898 pCur->iBase = add64(pCur->iBase, (span/pCur->iStep)*pCur->iStep);
9899 if( pCur->iBase<iMin ){
9900 if( pCur->iBase > sub64(LARGEST_INT64, pCur->iStep) ){
9901 goto series_no_rows;
9902 }
9903 pCur->iBase = add64(pCur->iBase, pCur->iStep);
9904 }
9905 }
9906 if( pCur->iTerm>iMax ){
9907 pCur->iTerm = iMax;
9908 }
9909 }else{
9910 if( pCur->iBase>iMax ){
9911 sqlite3_uint64 span = span64(pCur->iBase,iMax);
9912 pCur->iBase = sub64(pCur->iBase, (span/pCur->iStep)*pCur->iStep);
9913 if( pCur->iBase>iMax ){
9914 if( pCur->iBase < add64(SMALLEST_INT64, pCur->iStep) ){
9915 goto series_no_rows;
9916 }
9917 pCur->iBase = sub64(pCur->iBase, pCur->iStep);
9918 }
9919 }
9920 if( pCur->iTerm<iMin ){
9921 pCur->iTerm = iMin;
9922 }
9923 }
9924 }
9925
9926 /* Adjust iTerm so that it is exactly the last value of the series.
9927 */
9928 if( pCur->bDesc==0 ){
9929 if( pCur->iBase>pCur->iTerm ){
9930 goto series_no_rows;
9931 }
9932 pCur->iTerm = sub64(pCur->iTerm,
9933 span64(pCur->iTerm,pCur->iBase) % pCur->iStep);
9934 }else{
9935 if( pCur->iBase<pCur->iTerm ){
9936 goto series_no_rows;
9937 }
9938 pCur->iTerm = add64(pCur->iTerm,
9939 span64(pCur->iBase,pCur->iTerm) % pCur->iStep);
9940 }
9941
9942 /* Transform the series generator to output values in the requested
9943 ** order.
9944 */
9945 if( ((idxNum & 0x0008)!=0 && pCur->bDesc==0)
9946 || ((idxNum & 0x0010)!=0 && pCur->bDesc!=0)
9947 ){
9948 sqlite3_int64 tmp = pCur->iBase;
9949 pCur->iBase = pCur->iTerm;
9950 pCur->iTerm = tmp;
9951 pCur->bDesc = !pCur->bDesc;
9952 }
9953
9954 /* Apply LIMIT and OFFSET constraints, if any */
9955 assert( pCur->iStep!=0 );
9956 if( idxNum & 0x20 ){
9957 if( iOffset>0 ){
9958 if( seriesSteps(pCur) < (sqlite3_uint64)iOffset ){
9959 goto series_no_rows;
9960 }else if( pCur->bDesc ){
9961 pCur->iBase = sub64(pCur->iBase, pCur->iStep*iOffset);
9962 }else{
9963 pCur->iBase = add64(pCur->iBase, pCur->iStep*iOffset);
9964 }
9965 }
9966 if( iLimit>=0 && seriesSteps(pCur) > (sqlite3_uint64)iLimit ){
9967 pCur->iTerm = add64(pCur->iBase, (iLimit - 1)*pCur->iStep);
9968 }
9969 }
9970 pCur->iValue = pCur->iBase;
9971 pCur->bDone = 0;
9972 return SQLITE_OK;
9973
9974 series_no_rows:
9975 pCur->iBase = 0;
9976 pCur->iTerm = 0;
9977 pCur->iStep = 1;
9978 pCur->bDesc = 0;
9979 pCur->bDone = 1;
9980 return SQLITE_OK;
9981 }
9982
9983 /*
9984 ** SQLite will invoke this method one or more times while planning a query
9985 ** that uses the generate_series virtual table. This routine needs to create
9986 ** a query plan for each invocation and compute an estimated cost for that
9987 ** plan.
9988 **
9989 ** In this implementation idxNum is used to represent the
9990 ** query plan. idxStr is unused.
9991 **
9992 ** The query plan is represented by bits in idxNum:
9993 **
9994 ** 0x0001 start = $num
9995 ** 0x0002 stop = $num
9996 ** 0x0004 step = $num
9997 ** 0x0008 output is in descending order
9998 ** 0x0010 output is in ascending order
9999 ** 0x0020 LIMIT $num
10000 ** 0x0040 OFFSET $num
10001 ** 0x0080 value = $num
10002 ** 0x0100 value >= $num
10003 ** 0x0200 value > $num
10004 ** 0x1000 value <= $num
10005 ** 0x2000 value < $num
10006 **
10007 ** Only one of 0x0100 or 0x0200 will be returned. Similarly, only
10008 ** one of 0x1000 or 0x2000 will be returned. If the 0x0080 is set, then
10009 ** none of the 0xff00 bits will be set.
10010 **
10011 ** The order of parameters passed to xFilter is as follows:
10012 **
10013 ** * The argument to start= if bit 0x0001 is in the idxNum mask
10014 ** * The argument to stop= if bit 0x0002 is in the idxNum mask
10015 ** * The argument to step= if bit 0x0004 is in the idxNum mask
10016 ** * The argument to LIMIT if bit 0x0020 is in the idxNum mask
10017 ** * The argument to OFFSET if bit 0x0040 is in the idxNum mask
10018 ** * The argument to value=, or value>= or value> if any of
10019 ** bits 0x0380 are in the idxNum mask
10020 ** * The argument to value<= or value< if either of bits 0x3000
10021 ** are in the mask
10022 **
10023 */
10024 static int seriesBestIndex(
10025 sqlite3_vtab *pVTab,
10026 sqlite3_index_info *pIdxInfo
10027 ){
10028 int i, j; /* Loop over constraints */
10029 int idxNum = 0; /* The query plan bitmask */
10030 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
10031 int bStartSeen = 0; /* EQ constraint seen on the START column */
10032 #endif
10033 int unusableMask = 0; /* Mask of unusable constraints */
10034 int nArg = 0; /* Number of arguments that seriesFilter() expects */
10035 int aIdx[7]; /* Constraints on start, stop, step, LIMIT, OFFSET,
10036 ** and value. aIdx[5] covers value=, value>=, and
10037 ** value>, aIdx[6] covers value<= and value< */
10038 const struct sqlite3_index_constraint *pConstraint;
10039
10040 /* This implementation assumes that the start, stop, and step columns
10041 ** are the last three columns in the virtual table. */
10042 assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
10043 assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
10044
10045 aIdx[0] = aIdx[1] = aIdx[2] = aIdx[3] = aIdx[4] = aIdx[5] = aIdx[6] = -1;
10046 pConstraint = pIdxInfo->aConstraint;
10047 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
10048 int iCol; /* 0 for start, 1 for stop, 2 for step */
10049 int iMask; /* bitmask for those column */
10050 int op = pConstraint->op;
10051 if( op>=SQLITE_INDEX_CONSTRAINT_LIMIT
10052 && op<=SQLITE_INDEX_CONSTRAINT_OFFSET
10053 ){
10054 if( pConstraint->usable==0 ){
10055 /* do nothing */
10056 }else if( op==SQLITE_INDEX_CONSTRAINT_LIMIT ){
10057 aIdx[3] = i;
10058 idxNum |= 0x20;
10059 }else{
10060 assert( op==SQLITE_INDEX_CONSTRAINT_OFFSET );
10061 aIdx[4] = i;
10062 idxNum |= 0x40;
10063 }
10064 continue;
10065 }
10066 if( pConstraint->iColumn<SERIES_COLUMN_START ){
10067 if( (pConstraint->iColumn==SERIES_COLUMN_VALUE ||
10068 pConstraint->iColumn==SERIES_COLUMN_ROWID)
10069 && pConstraint->usable
10070 ){
10071 switch( op ){
10072 case SQLITE_INDEX_CONSTRAINT_EQ:
10073 case SQLITE_INDEX_CONSTRAINT_IS: {
10074 idxNum |= 0x0080;
10075 idxNum &= ~0x3300;
10076 aIdx[5] = i;
10077 aIdx[6] = -1;
10078 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
10079 bStartSeen = 1;
10080 #endif
10081 break;
10082 }
10083 case SQLITE_INDEX_CONSTRAINT_GE: {
10084 if( idxNum & 0x0080 ) break;
10085 idxNum |= 0x0100;
10086 idxNum &= ~0x0200;
10087 aIdx[5] = i;
10088 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
10089 bStartSeen = 1;
10090 #endif
10091 break;
10092 }
10093 case SQLITE_INDEX_CONSTRAINT_GT: {
10094 if( idxNum & 0x0080 ) break;
10095 idxNum |= 0x0200;
10096 idxNum &= ~0x0100;
10097 aIdx[5] = i;
10098 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
10099 bStartSeen = 1;
10100 #endif
10101 break;
10102 }
10103 case SQLITE_INDEX_CONSTRAINT_LE: {
10104 if( idxNum & 0x0080 ) break;
10105 idxNum |= 0x1000;
10106 idxNum &= ~0x2000;
10107 aIdx[6] = i;
10108 break;
10109 }
10110 case SQLITE_INDEX_CONSTRAINT_LT: {
10111 if( idxNum & 0x0080 ) break;
10112 idxNum |= 0x2000;
10113 idxNum &= ~0x1000;
10114 aIdx[6] = i;
10115 break;
10116 }
10117 }
10118 }
10119 continue;
10120 }
10121 iCol = pConstraint->iColumn - SERIES_COLUMN_START;
10122 assert( iCol>=0 && iCol<=2 );
10123 iMask = 1 << iCol;
10124 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
10125 if( iCol==0 && op==SQLITE_INDEX_CONSTRAINT_EQ ){
10126 bStartSeen = 1;
10127 }
10128 #endif
10129 if( pConstraint->usable==0 ){
10130 unusableMask |= iMask;
10131 continue;
10132 }else if( op==SQLITE_INDEX_CONSTRAINT_EQ ){
10133 idxNum |= iMask;
10134 aIdx[iCol] = i;
10135 }
10136 }
10137 if( pIdxInfo->nOrderBy>=1 ){
10138 int iOB = pIdxInfo->aOrderBy[0].iColumn;
10139 if( iOB==SERIES_COLUMN_VALUE || iOB==SERIES_COLUMN_ROWID ){
10140 /* The rowid is an alias for value, and both are unique, so the
10141 ** series can be generated in the requested order regardless of any
10142 ** subsequent ORDER BY terms. */
10143 if( pIdxInfo->aOrderBy[0].desc ){
10144 idxNum |= 0x08;
10145 }else{
10146 idxNum |= 0x10;
10147 }
10148 pIdxInfo->orderByConsumed = 1;
10149 }else{
10150 /* The core will sort the output, so it needs to see every row.
10151 ** A LIMIT or OFFSET applied here would discard rows before the sort */
10152 idxNum &= ~0x60;
10153 aIdx[3] = aIdx[4] = -1;
10154 }
10155 }
10156 if( aIdx[3]==0 ){
10157 /* Ignore OFFSET if LIMIT is omitted */
10158 idxNum &= ~0x60;
10159 aIdx[4] = 0;
10160 }
10161 for(i=0; i<7; i++){
10162 if( (j = aIdx[i])>=0 ){
10163 pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
10164 pIdxInfo->aConstraintUsage[j].omit =
10165 !SQLITE_SERIES_CONSTRAINT_VERIFY || i>=3;
10166 }
10167 }
10168 /* The current generate_column() implementation requires at least one
10169 ** argument (the START value). Legacy versions assumed START=0 if the
10170 ** first argument was omitted. Compile with -DZERO_ARGUMENT_GENERATE_SERIES
10171 ** to obtain the legacy behavior */
10172 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
10173 if( !bStartSeen ){
10174 sqlite3_free(pVTab->zErrMsg);
10175 pVTab->zErrMsg = sqlite3_mprintf(
10176 "first argument to \"generate_series()\" missing or unusable");
10177 return SQLITE_ERROR;
10178 }
10179 #endif
10180 if( (unusableMask & ~idxNum)!=0 ){
10181 /* The start, stop, and step columns are inputs. Therefore if there
10182 ** are unusable constraints on any of start, stop, or step then
10183 ** this plan is unusable */
10184 return SQLITE_CONSTRAINT;
10185 }
10186 if( (idxNum & 0x03)==0x03 ){
10187 /* Both start= and stop= boundaries are available. This is the
10188 ** the preferred case */
10189 pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
10190 pIdxInfo->estimatedRows = 1000;
10191 }else if( (idxNum & 0x21)==0x21 ){
10192 /* We have start= and LIMIT */
10193 pIdxInfo->estimatedRows = 2500;
10194 }else{
10195 /* If either boundary is missing, we have to generate a huge span
10196 ** of numbers. Make this case very expensive so that the query
10197 ** planner will work hard to avoid it. */
10198 pIdxInfo->estimatedRows = 2147483647;
10199 }
10200 pIdxInfo->idxNum = idxNum;
10201 #ifdef SQLITE_INDEX_SCAN_HEX
10202 pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_HEX;
10203 #endif
10204 return SQLITE_OK;
10205 }
10206
10207 /*
10208 ** This following structure defines all the methods for the
10209 ** generate_series virtual table.
10210 */
10211 static sqlite3_module seriesModule = {
10212 0, /* iVersion */
10213 0, /* xCreate */
10214 seriesConnect, /* xConnect */
10215 seriesBestIndex, /* xBestIndex */
10216 seriesDisconnect, /* xDisconnect */
10217 0, /* xDestroy */
10218 seriesOpen, /* xOpen - open a cursor */
10219 seriesClose, /* xClose - close a cursor */
10220 seriesFilter, /* xFilter - configure scan constraints */
10221 seriesNext, /* xNext - advance a cursor */
10222 seriesEof, /* xEof - check for end of scan */
10223 seriesColumn, /* xColumn - read data */
10224 seriesRowid, /* xRowid - read data */
10225 0, /* xUpdate */
10226 0, /* xBegin */
10227 0, /* xSync */
10228 0, /* xCommit */
10229 0, /* xRollback */
10230 0, /* xFindMethod */
10231 0, /* xRename */
10232 0, /* xSavepoint */
10233 0, /* xRelease */
10234 0, /* xRollbackTo */
10235 0, /* xShadowName */
10236 0 /* xIntegrity */
10237 };
10238
10239 #endif /* SQLITE_OMIT_VIRTUALTABLE */
10240
10241 #ifdef _WIN32
10242
10243 #endif
10244 int sqlite3_series_init(
10245 sqlite3 *db,
10246 char **pzErrMsg,
10247 const sqlite3_api_routines *pApi
10248 ){
10249 int rc = SQLITE_OK;
10250 SQLITE_EXTENSION_INIT2(pApi);
10251 #ifndef SQLITE_OMIT_VIRTUALTABLE
10252 if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
10253 *pzErrMsg = sqlite3_mprintf(
10254 "generate_series() requires SQLite 3.8.12 or later");
10255 return SQLITE_ERROR;
10256 }
10257 rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
10258 #endif
10259 return rc;
10260 }
10261
10262 /************************* End ext/misc/series.c ********************/
10263 /************************* Begin ext/misc/tryeval.c ******************/
10264 /*
10265 ** 2026-10-26
10266 **
10267 ** The author disclaims copyright to this source code. In place of
10268 ** a legal notice, here is a blessing:
10269 **
10270 ** May you do good and not evil.
10271 ** May you find forgiveness for yourself and forgive others.
10272 ** May you share freely, never taking more than you give.
10273 **
10274 ******************************************************************************
10275 **
10276 ** This is an extension used for testing SQLite. It is not intended for
10277 ** production use. The interface might change. This file might go out
10278 ** of support and disappear at any moment. Do not depend on this extension.
10279 **
10280 ** Apparent from comments in the code, this extension is undocumented.
10281 **
10282 ** This SQLite extension implements the SQL function tryeval(). The tryeval()
10283 ** function takes zero or more arguments, each of which is an SQL statement.
10284 ** The tryeval() function returns the first column of the first row that
10285 ** has a non-NULL first column across each of the argument SQL statements.
10286 ** Evaluation stops as soon as the first row with a non-NULL first column
10287 ** is encountered. Errors in evaluation are silently ignored, moving on
10288 ** the next SQL statement argument. If none of the arguments successfully
10289 ** executes and returns a row with a non-NULL first column, then NULL is
10290 ** returned.
10291 **
10292 ** Update: Also the expire(V) and expire(V,N) functions. See comments
10293 ** below for details.
10294 **
10295 ** The purpose of this function is to help evaluate recursive
10296 ** behavior, and expecially the bug report at
10297 ** sqlite.org/bugs/info/3577bc69c52237a4 (2026-10-25T19:26:00Z)
10298 ** as well as other bugs.
10299 **
10300 ** To build (with SODIR being the directory that contains your
10301 ** sqlite3.h and sqlite3ext.h headers):
10302 **
10303 ** Linux: gcc -O2 -shared -I$SQDIR -fPIC -o tryeval.so tryeval.c
10304 ** Mac: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o tryeval.dylib tryeval.c
10305 ** Win32: cl /Os -I%SQDIR% tryeval.c -link -dll -out:tryeval.dll
10306 */
10307 /* #include "sqlite3ext.h" */
10308 SQLITE_EXTENSION_INIT1
10309 #include <string.h>
10310
10311 /*
10312 ** Implementation of the tryeval(...)
10313 */
10314 static void tryEvalFunc(
10315 sqlite3_context *context,
10316 int argc,
10317 sqlite3_value **argv
10318 ){
10319 const char *zSql; /* Next SQL statement to evaluate */
10320 sqlite3 *db; /* The database connection */
10321 sqlite3_stmt *pStmt; /* Compiled bytecode for zSql */
10322 int bDone = 0; /* True if a row with non-NULL first column seen */
10323 int rc; /* Result from sqlite3 API calls */
10324 int i; /* Loop counter */
10325
10326 db = sqlite3_context_db_handle(context);
10327 for(i=0; !bDone && i<argc; i++){
10328 zSql = (const char*)sqlite3_value_text(argv[i]);
10329 if( zSql==0 ) continue;
10330 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
10331 if( rc==SQLITE_OK ){
10332 while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){
10333 if( sqlite3_column_type(pStmt,0)==SQLITE_NULL ) continue;
10334 sqlite3_result_value(context, sqlite3_column_value(pStmt,0));
10335 bDone = 1;
10336 break;
10337 }
10338 }
10339 sqlite3_finalize(pStmt);
10340 }
10341 }
10342
10343 /* SQL function: expire(v,n)
10344 **
10345 ** Return the first argument. But before doing so, expire all prepared
10346 ** statements that use schema n (0,1,...) or if n==-1 expire all prepared
10347 ** statements. If the second argument is omitted, it is assumed to be -1.
10348 **
10349 ** This routine requires the (new) SQLITE_TESTCTRL_EXPIRE_STMTS test
10350 ** control. If your SQLite does not support that test control, or if
10351 ** you compile with test controls disabled (you ought not do that!) then
10352 ** this routine is just copies its first argument as its result.
10353 */
10354 static void expireFunc(
10355 sqlite3_context *context,
10356 int argc,
10357 sqlite3_value **argv
10358 ){
10359 sqlite3 *db = sqlite3_context_db_handle(context);
10360 int iDb = argc>=2 ? sqlite3_value_int(argv[1]) : -1;
10361 #ifdef SQLITE_TESTCTRL_EXPIRE_STMTS
10362 sqlite3_test_control(SQLITE_TESTCTRL_EXPIRE_STMTS, db, iDb);
10363 #endif
10364 sqlite3_result_value(context, argv[0]);
10365 }
10366
10367 #ifdef _WIN32
10368
10369 #endif
10370 int sqlite3_tryeval_init(
10371 sqlite3 *db,
10372 char **pzErrMsg,
10373 const sqlite3_api_routines *pApi
10374 ){
10375 int rc = SQLITE_OK;
10376 SQLITE_EXTENSION_INIT2(pApi);
10377 (void)pzErrMsg; /* Unused parameter */
10378 rc = sqlite3_create_function(db, "tryeval", -1,
10379 SQLITE_UTF8, 0,
10380 tryEvalFunc, 0, 0);
10381 if( rc==SQLITE_OK ){
10382 rc = sqlite3_create_function(db, "expire", 1,
10383 SQLITE_UTF8|SQLITE_DETERMINISTIC, 0,
10384 expireFunc, 0, 0);
10385 }
10386 if( rc==SQLITE_OK ){
10387 rc = sqlite3_create_function(db, "expire", 2,
10388 SQLITE_UTF8|SQLITE_DETERMINISTIC, 0,
10389 expireFunc, 0, 0);
10390 }
10391 return rc;
10392 }
10393
10394 /************************* End ext/misc/tryeval.c ********************/
10395 #ifndef SQLITE_SHELL_FIDDLE
10396 /************************* Begin ext/misc/fileio.c ******************/
10397 /*
10398 ** 2014-06-13
10399 **
@@ -10593,20 +10806,23 @@
10806 char *zCopy = sqlite3_mprintf("%s", zFile);
10807 int rc = SQLITE_OK;
10808
10809 if( zCopy==0 ){
10810 rc = SQLITE_NOMEM;
10811 }else if( zCopy[0]==0 ){
10812 rc = SQLITE_ERROR;
10813 sqlite3_free(zCopy);
10814 }else{
10815 int nCopy = (int)strlen(zCopy);
10816 int i = 1;
10817
10818 while( rc==SQLITE_OK ){
10819 STRUCT_STAT sStat;
10820 int rc2;
10821
10822 for(; i<nCopy && zCopy[i]!='/'; i++);
10823 if( i>=nCopy ) break;
10824 zCopy[i] = '\0';
10825
10826 rc2 = fileStat(zCopy, &sStat);
10827 if( rc2!=0 ){
10828 if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
@@ -10773,11 +10989,12 @@
10989 mtime = sqlite3_value_int64(argv[3]);
10990 }
10991
10992 res = writeFile(context, zFile, argv[1], mode, mtime);
10993 if( res==1 && errno==ENOENT ){
10994 res = makeDirectory(zFile);
10995 if( res==SQLITE_OK ){
10996 res = writeFile(context, zFile, argv[1], mode, mtime);
10997 }
10998 }
10999
11000 if( argc>2 && res!=0 ){
@@ -11505,10 +11722,14 @@
11722 const sqlite3_api_routines *pApi
11723 ){
11724 int rc = SQLITE_OK;
11725 SQLITE_EXTENSION_INIT2(pApi);
11726 (void)pzErrMsg; /* Unused parameter */
11727
11728 /* REMINDER: Changes here should be reflected in the ".safe" command
11729 ** of the CLI.
11730 */
11731 rc = sqlite3_create_function(db, "readfile", 1,
11732 SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
11733 readfileFunc, 0, 0);
11734 if( rc==SQLITE_OK ){
11735 rc = sqlite3_create_function(db, "writefile", -1,
@@ -13165,10 +13386,22 @@
13386 ** transaction.
13387 */
13388 static void zipfileCleanupTransaction(ZipfileTab *pTab){
13389 ZipfileEntry *pEntry;
13390 ZipfileEntry *pNext;
13391 ZipfileCsr *pCsr;
13392
13393 /* A cursor that is not reading from a file or from a blob steps through
13394 ** the pTab->pFirstEntry list, which is about to be deleted. Such a
13395 ** cursor has nothing left to return, so leave it at EOF rather than
13396 ** pointing at freed memory. */
13397 for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
13398 if( pCsr->pFile==0 && pCsr->pFreeEntry==0 ){
13399 pCsr->pCurrent = 0;
13400 pCsr->bEof = 1;
13401 }
13402 }
13403
13404 if( pTab->pWriteFd ){
13405 fclose(pTab->pWriteFd);
13406 pTab->pWriteFd = 0;
13407 }
@@ -13217,15 +13450,19 @@
13450 ZipfileEntry *p;
13451 ZipfileEntry *pNext;
13452
13453 pCsr->bEof = 0;
13454 if( pCsr->pFile ){
13455 /* File mode: pCurrent is a private copy owned by this cursor. */
13456 fclose(pCsr->pFile);
13457 pCsr->pFile = 0;
13458 zipfileEntryFree(pCsr->pCurrent);
 
13459 }
13460 /* In the other modes pCurrent belongs to pFreeEntry or to the table.
13461 ** It must not be left dangling, since a later xFilter() that switches
13462 ** this cursor to file mode would free it. */
13463 pCsr->pCurrent = 0;
13464
13465 for(p=pCsr->pFreeEntry; p; p=pNext){
13466 pNext = p->pNext;
13467 zipfileEntryFree(p);
13468 }
@@ -13521,10 +13758,19 @@
13758 i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
13759
13760 int A, B, C, D, E;
13761 int yr, mon, day;
13762 int hr, min, sec;
13763
13764 if( mUnixTime<=315532800 ){
13765 /* Experimentally, I find that Win11 will not report the modification
13766 ** time for any ZIP file entry with a date before 1980-01-01 00:00:01.
13767 ** So make that the minimum date-time value. */
13768 pCds->mDate = 0x0021;
13769 pCds->mTime = 0x0001;
13770 return;
13771 }
13772
13773 A = (int)((JD - 1867216.25)/36524.25);
13774 A = (int)(JD + 1 + A - (A/4));
13775 B = A + 1524;
13776 C = (int)((B - 122.1)/365.25);
@@ -13537,21 +13783,15 @@
13783
13784 hr = (mUnixTime % (24*60*60)) / (60*60);
13785 min = (mUnixTime % (60*60)) / 60;
13786 sec = (mUnixTime % 60);
13787
13788 pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
13789 pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
13790
13791 assert( mUnixTime==zipfileMtime(pCds)
13792 || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
 
 
 
 
 
 
13793 );
13794 }
13795
13796 /*
13797 ** Set (*pzErr) to point to a buffer from sqlite3_malloc() containing a
@@ -13712,11 +13952,11 @@
13952 pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
13953 }
13954 pCsr->pCurrent = p;
13955 }
13956 }else{
13957 if( !pCsr->bNoop && !pCsr->bEof ){
13958 pCsr->pCurrent = pCsr->pCurrent->pNext;
13959 }
13960 if( pCsr->pCurrent==0 ){
13961 pCsr->bEof = 1;
13962 }
@@ -13832,12 +14072,17 @@
14072 sqlite3_vtab_cursor *cur, /* The cursor */
14073 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
14074 int i /* Which column to return */
14075 ){
14076 ZipfileCsr *pCsr = (ZipfileCsr*)cur;
14077 ZipfileCDS *pCDS;
14078 int rc = SQLITE_OK;
14079 if( pCsr->pCurrent==0 ){
14080 /* The transaction ended while this row was being processed. */
14081 return SQLITE_OK;
14082 }
14083 pCDS = &pCsr->pCurrent->cds;
14084 switch( i ){
14085 case 0: /* name */
14086 sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
14087 break;
14088 case 1: /* mode */
@@ -14678,11 +14923,11 @@
14923 ZipfileCsr *pCsr;
14924 ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
14925 assert( argc>0 );
14926
14927 pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
14928 if( pCsr && pCsr->pCurrent ){
14929 ZipfileCDS *p = &pCsr->pCurrent->cds;
14930 char *zRes = sqlite3_mprintf("{"
14931 "\"version-made-by\" : %u, "
14932 "\"version-to-extract\" : %u, "
14933 "\"flags\" : %u, "
@@ -15025,10 +15270,13 @@
15270 0, /* xRollback */
15271 0, /* xShadowName */
15272 0 /* xIntegrity */
15273 };
15274
15275 /* REMINDER: Changes here should also be reflected in the ".safe"
15276 ** command of the CLI
15277 */
15278 int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0);
15279 if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
15280 if( rc==SQLITE_OK ){
15281 rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
15282 zipfileStep, zipfileFinal
@@ -15660,11 +15908,11 @@
15908 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
15909 IdxConstraint *pNew;
15910 int nColl = STRLEN(zColl);
15911
15912 assert( *pRc==SQLITE_OK );
15913 pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) + nColl + 1);
15914 if( pNew ){
15915 pNew->zColl = (char*)&pNew[1];
15916 memcpy(pNew->zColl, zColl, nColl+1);
15917 }
15918 return pNew;
@@ -16184,10 +16432,12 @@
16432 */
16433 static int idxIdentifierRequiresQuotes(const char *zId){
16434 int i;
16435 int nId = STRLEN(zId);
16436
16437 if( nId==0 ) return 1;
16438 if( zId[0]>='0' && zId[0]<='9' ) return 1;
16439 if( sqlite3_keyword_check(zId, nId) ) return 1;
16440
16441 for(i=0; zId[i]; i++){
16442 if( !(zId[i]=='_')
16443 && !(zId[i]>='0' && zId[i]<='9')
@@ -16398,13 +16648,11 @@
16648 zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
16649 if( !zIdx ){
16650 rc = SQLITE_NOMEM;
16651 }else{
16652 rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
16653 if( rc==SQLITE_OK ){
 
 
16654 idxHashAdd(&rc, &p->hIdx, zName, zIdx);
16655 }
16656 }
16657 sqlite3_free(zIdx);
16658 }
@@ -17521,15 +17769,19 @@
17769 /* Do trigger processing to collect any extra IdxScan structures */
17770 rc = idxProcessTriggers(p, pzErr);
17771
17772 /* Create candidate indexes within the in-memory database file */
17773 if( rc==SQLITE_OK ){
17774 p->pzErrmsg = pzErr;
17775 rc = idxCreateCandidates(p);
17776 p->pzErrmsg = 0;
17777 if( rc==SQLITE_BUSY_TIMEOUT ){
17778 if( pzErr ){
17779 *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
17780 }
17781 return rc;
17782 }
17783 }
17784
17785 /* Generate the stat1 data */
17786 if( rc==SQLITE_OK ){
17787 rc = idxPopulateStat1(p, pzErr);
@@ -22443,10 +22695,16 @@
22695 ** index of the bind paramater to which the rowid value should be bound.
22696 ** Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
22697 ** KEY column, then the rowid value should be bound to the index associated
22698 ** with the column.
22699 **
22700 ** zRowid:
22701 ** If iRowidBind>0, the name used to refer to the rowid in the INSERT
22702 ** statement. This is the first of "_rowid_", "rowid" and "oid" that is
22703 ** not also the name of a column. If all three are column names, the
22704 ** rowid cannot be written and iRowidBind is 0.
22705 **
22706 ** pNext:
22707 ** All RecoverTable objects used by the recovery operation are allocated
22708 ** and populated as part of creating the recovered database schema in
22709 ** the output database, before any non-schema data are recovered. They
22710 ** are then stored in a singly-linked list linked by this variable beginning
@@ -22458,10 +22716,11 @@
22716 int nCol; /* Number of columns in table */
22717 int nField; /* Number of fields in each record */
22718 RecoverColumn *aCol; /* Array of columns */
22719 int bIntkey; /* True for intkey, false for without rowid */
22720 int iRowidBind; /* If >0, bind rowid to INSERT here */
22721 const char *zRowid; /* Name to use for rowid in INSERT */
22722 RecoverTable *pNext;
22723 };
22724
22725 /*
22726 ** Each database column is represented by an instance of the following object
@@ -22908,15 +23167,15 @@
23167 ** SQL statements separated by ';', only the first is run.
23168 **
23169 ** Return the sqlite3_finalizer() or sqlite3_prepare() result code
23170 ** from running the zSql statement.
23171 */
23172 static int recoverOneStmt(sqlite3 *db, const char *zSql, const char **pzTail){
23173 sqlite3_stmt *pStmt = 0;
23174 int rc;
23175 if( zSql==0 ) return SQLITE_OK;
23176 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, pzTail);
23177 if( rc ){
23178 sqlite3_finalize(pStmt);
23179 return rc;
23180 }
23181 while( SQLITE_ROW==sqlite3_step(pStmt) ){}
@@ -22933,11 +23192,11 @@
23192 ** If successful, return SQLITE_OK. Or, if an error occurs, leave an error
23193 ** code and message in the recover handle and return a copy of the error code.
23194 */
23195 static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){
23196 if( p->errCode==SQLITE_OK ){
23197 int rc = recoverOneStmt(db, zSql, 0);
23198 if( rc ){
23199 recoverDbError(p, db);
23200 }
23201 }
23202 return p->errCode;
@@ -23444,11 +23703,11 @@
23703 sqlite3_recover *p,
23704 const char *zName, /* Name of table created in output db */
23705 i64 iRoot /* Root page of same table in INPUT db */
23706 ){
23707 sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut,
23708 "PRAGMA %Q.table_xinfo(%Q)", p->zDb, zName
23709 );
23710
23711 if( pStmt ){
23712 int iPk = -1;
23713 int iBind = 1;
@@ -23511,11 +23770,12 @@
23770 /* If this is a WITHOUT ROWID table, the fields of each record are
23771 ** ordered as reported by PRAGMA index_xinfo on the table. A column may
23772 ** appear more than once if it is listed more than once in the PRIMARY
23773 ** KEY (with different collation sequences). In that case use the first
23774 ** field - the others are redundant copies. */
23775 pStmt = recoverPreparePrintf(p, p->dbOut,
23776 "PRAGMA %Q.index_xinfo(%Q)", p->zDb, zName);
23777 while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
23778 int iField = sqlite3_column_int(pStmt, 0);
23779 int iCol = sqlite3_column_int(pStmt, 1);
23780
23781 assert( iCol>=0 && iCol<pNew->nCol );
@@ -23527,16 +23787,40 @@
23787 if( pNew->aCol[iCol].iField<0 ) pNew->aCol[iCol].iField = iField;
23788 pNew->nField = iField+1;
23789 iPk = -2;
23790 }
23791 recoverFinalize(p, pStmt);
23792
23793 /* A column declared as "INTEGER PRIMARY KEY DESC" is not an alias for
23794 ** the rowid. Such a table has an automatic index with origin 'pk',
23795 ** whereas a table with a true rowid alias does not. */
23796 if( iPk>=0 ){
23797 pStmt = recoverPreparePrintf(p, p->dbOut,
23798 "SELECT 1 FROM pragma_index_list(%Q, %Q) WHERE origin='pk'",
23799 zName, p->zDb
23800 );
23801 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ) iPk = -1;
23802 recoverFinalize(p, pStmt);
23803 }
23804
23805 if( p->errCode==SQLITE_OK ){
23806 if( iPk>=0 ){
23807 pNew->aCol[iPk].bIPK = 1;
23808 }else if( pNew->bIntkey ){
23809 /* Find a name for the rowid that is not also the name of a column */
23810 static const char *azRowid[] = { "_rowid_", "rowid", "oid" };
23811 int ii, jj;
23812 for(ii=0; ii<(int)(sizeof(azRowid)/sizeof(azRowid[0])); ii++){
23813 for(jj=0; jj<pNew->nCol; jj++){
23814 if( sqlite3_stricmp(azRowid[ii], pNew->aCol[jj].zCol)==0 ) break;
23815 }
23816 if( jj==pNew->nCol ){
23817 pNew->zRowid = azRowid[ii];
23818 pNew->iRowidBind = iBind++;
23819 break;
23820 }
23821 }
23822 }
23823 }
23824 }
23825 }
23826
@@ -23590,27 +23874,37 @@
23874 int bVirtual = sqlite3_column_int(pSelect, 2);
23875 const char *zName = (const char*)sqlite3_column_text(pSelect, 3);
23876 const char *zSql = (const char*)sqlite3_column_text(pSelect, 4);
23877 char *zFree = 0;
23878 int rc = SQLITE_OK;
23879 const char *zTail = 0;
23880
23881 if( bVirtual ){
23882 zSql = (const char*)(zFree = recoverMPrintf(p,
23883 "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
23884 zName, zName, zSql
23885 ));
23886 }
23887 rc = recoverOneStmt(p->dbOut, zSql, &zTail);
23888 if( rc==SQLITE_OK ){
23889 char *pToFree = 0;
23890 if( zTail && zTail[0] ){
23891 int n = (int)(zTail - zSql);
23892 while( n>0 && (zSql[n-1]==';' || zSql[n-1]<=' ') ){ n--; }
23893 pToFree = sqlite3_mprintf("%.*s", n, zSql);
23894 zSql = pToFree;
23895
23896 }
23897 recoverSqlCallback(p, zSql);
23898 if( bTable && !bVirtual ){
23899 if( SQLITE_ROW==sqlite3_step(pTblname) ){
23900 const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0);
23901 if( zTbl ) recoverAddTable(p, zTbl, iRoot);
23902 }
23903 recoverReset(p, pTblname);
23904 }
23905 sqlite3_free(pToFree);
23906 }else if( rc!=SQLITE_ERROR ){
23907 recoverDbError(p, p->dbOut);
23908 }
23909 sqlite3_free(zFree);
23910 }
@@ -23649,13 +23943,23 @@
23943 );
23944
23945 if( pSelect ){
23946 while( sqlite3_step(pSelect)==SQLITE_ROW ){
23947 const char *zSql = (const char*)sqlite3_column_text(pSelect, 1);
23948 const char *zTail = 0;
23949 int rc = recoverOneStmt(p->dbOut, zSql, &zTail);
23950 if( rc==SQLITE_OK ){
23951 char *pToFree = 0;
23952 if( zTail && zTail[0] ){
23953 /* Omit any extraneous text that follows the first SQL statement */
23954 int n = (int)(zTail - zSql);
23955 while( n>0 && (zSql[n-1]==';' || zSql[n-1]<=' ') ){ n--; }
23956 pToFree = sqlite3_mprintf("%.*s", n, zSql);
23957 zSql = pToFree;
23958 }
23959 recoverSqlCallback(p, zSql);
23960 sqlite3_free(pToFree);
23961 }else if( rc!=SQLITE_ERROR ){
23962 recoverDbError(p, p->dbOut);
23963 }
23964 }
23965 }
@@ -23719,11 +24023,12 @@
24023
24024 zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab);
24025
24026 if( pTab->iRowidBind ){
24027 assert( pTab->bIntkey );
24028 assert( pTab->zRowid );
24029 zSql = recoverMPrintf(p, "%z%s", zSql, pTab->zRowid);
24030 if( bSql ){
24031 zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind);
24032 }else{
24033 zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind);
24034 }
@@ -25033,11 +25338,11 @@
25338 recoverCacheSchema(p);
25339
25340 if( bUseWrapper ) recoverUninstallWrapper(p);
25341 }while( p->errCode==SQLITE_NOTADB
25342 && (bUseWrapper--)
25343 && SQLITE_OK==recoverOneStmt(p->dbIn, "ROLLBACK", 0)
25344 );
25345 }
25346
25347 recoverLeaveMutex();
25348 recoverExec(p, p->dbOut, "BEGIN");
@@ -25098,11 +25403,11 @@
25403
25404 /* If no error has occurred, commit the write transaction on the output
25405 ** database. Regardless of whether or not an error has occurred, make
25406 ** an attempt to end the read transaction on the input database. */
25407 recoverExec(p, p->dbOut, "COMMIT");
25408 rc = recoverOneStmt(p->dbIn, "END", 0);
25409 if( p->errCode==SQLITE_OK ) p->errCode = rc;
25410
25411 recoverSqlCallback(p, "PRAGMA writable_schema = off");
25412 recoverSqlCallback(p, "COMMIT");
25413 p->eState = RECOVER_STATE_DONE;
@@ -25294,11 +25599,11 @@
25599 if( p==0 ){
25600 rc = SQLITE_NOMEM;
25601 }else{
25602 recoverFinalCleanup(p);
25603 if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){
25604 rc = recoverOneStmt(p->dbIn, "END", 0);
25605 if( p->errCode==SQLITE_OK ) p->errCode = rc;
25606 }
25607 rc = p->errCode;
25608 sqlite3_free(p->zErrMsg);
25609 sqlite3_free(p->zStateDb);
@@ -25352,11 +25657,10 @@
25657 /* All the parameters that determine how to render query results.
25658 */
25659 typedef struct Mode {
25660 u8 autoExplain; /* Automatically turn on .explain mode */
25661 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
 
25662 u8 scanstatsOn; /* True to display scan stats before each finalize */
25663 u8 bAutoScreenWidth; /* Using the TTY to determine screen width */
25664 u8 mFlags; /* MFLG_ECHO, MFLG_CRLF, etc. */
25665 u8 eMode; /* One of the MODE_ values */
25666 char zIFmt[24]; /* Space to hold the --ifmt value */
@@ -25423,10 +25727,11 @@
25727 const char *zInFile; /* Name of the input file */
25728 int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
25729 FILE *in; /* Read commands from this stream */
25730 FILE *out; /* Write results here */
25731 FILE *traceOut; /* Output for sqlite3_trace() */
25732 char *zEqpFile; /* Append .eqp output to this file, if not NULL */
25733 int nErr; /* Number of errors seen */
25734 int writableSchema; /* True if PRAGMA writable_schema=ON */
25735 int nCheck; /* Number of ".check" commands run */
25736 unsigned nProgress; /* Number of progress callbacks encountered */
25737 unsigned mxProgress; /* Maximum progress callbacks before failing */
@@ -25583,13 +25888,14 @@
25888 #define MODE_Quote 17 /* Quote values as for SQL */
25889 #define MODE_Split 18 /* Split-column mode */
25890 #define MODE_Table 19 /* MySQL-style table formatting */
25891 #define MODE_Tabs 20 /* Tab-separated values */
25892 #define MODE_Tcl 21 /* Space-separated list of TCL strings */
25893 #define MODE_Test 22 /* list -colsep , -quote on <-- for testing */
25894 #define MODE_Www 23 /* Full web-page output */
25895
25896 #define MODE_BUILTIN 23 /* Maximum built-in mode */
25897 #define MODE_BATCH 50 /* Default mode for batch processing */
25898 #define MODE_TTY 51 /* Default mode for interactive processing */
25899 #define MODE_USER 75 /* First user-defined mode */
25900 #define MODE_N_USER 25 /* Maximum number of user-defined modes */
25901
@@ -25624,11 +25930,11 @@
25930 { "box", 0, 0, 9, 1, 1, 0, 3, 1, 2, 0 },
25931 { "c", 4, 1, 10, 5, 5, 4, 1, 12, 0, 0 },
25932 { "column", 0, 0, 9, 1, 1, 0, 3, 2, 2, 0 },
25933 { "count", 0, 0, 0, 0, 0, 0, 0, 3, 0, 0 },
25934 { "csv", 4, 5, 9, 3, 3, 0, 1, 12, 0, 0 },
25935 { "html", 0, 0, 11, 4, 4, 0, 3, 7, 0, 0 },
25936 { "insert", 0, 0, 10, 2, 2, 0, 1, 8, 0, 0 },
25937 { "jatom", 4, 1, 11, 6, 6, 0, 1, 12, 0, 0 },
25938 { "jobject", 0, 1, 11, 6, 6, 0, 0, 10, 0, 0 },
25939 { "json", 0, 0, 11, 6, 6, 0, 0, 9, 0, 0 },
25940 { "line", 13, 1, 9, 1, 1, 0, 0, 11, 1, 0 },
@@ -25640,11 +25946,11 @@
25946 { "quote", 4, 1, 10, 2, 2, 0, 1, 12, 0, 0 },
25947 { "split", 0, 0, 9, 1, 1, 0, 1, 2, 2, 2 },
25948 { "table", 0, 0, 9, 1, 1, 0, 3, 19, 2, 0 },
25949 { "tabs", 8, 1, 9, 3, 3, 0, 1, 12, 0, 0 },
25950 { "tcl", 3, 1, 12, 5, 5, 4, 1, 12, 0, 0 },
25951 { "www", 0, 0, 11, 4, 4, 0, 3, 7, 0, 0 }
25952 }; /* | / / | / / | | / \____
25953 ** | / / | / / | | / |
25954 ** Index into aModeStr[] | / / | | 2: columnar |
25955 ** | / / | | 1: line |
25956 ** | / / | | 0: other |
@@ -26828,10 +27134,41 @@
27134 /*
27135 ** SQL function: capable(X)
27136 **
27137 ** Return true if the current build has capability X. Return 0
27138 ** if X is not a capability or NULL if X is NULL.
27139 **
27140 ** A build has capability X if any of the following are true:
27141 **
27142 ** (1) A VFS named X exists.
27143 ** (2) A function named X exists.
27144 ** (3) A module named X exists.
27145 ** (4) A compile-time option X is used for the build.
27146 **
27147 ** Comparison between X and the various items above is done
27148 ** using sqlite_stricmp() so that upper/lower case does not matter.
27149 ** So capable('generate_series') and capable('GENERATE_SERIES')
27150 ** both work the same.
27151 **
27152 ** There are also special names "vtab", "fkey", and "load_ext"
27153 ** that return true as long as compile-time options
27154 ** SQLITE_OMIT_VIRTUALTABLE, SQLITE_OMIT_FOREIGN_KEY, and
27155 ** SQLITE_OMIT_LOAD_EXTENSION are omitted from the build,
27156 ** respectively. Thus capable('vtab') means that virtual table
27157 ** features of SQLite are available in the current build.
27158 **
27159 ** There is also the special name "unsafe" which is true as long
27160 ** as the CLI is not in safe mode. New special names may be added
27161 ** in the future.
27162 **
27163 ** For other "OMIT" options (besides the three special ones noted
27164 ** in the previous paragraph) you have to say something like
27165 ** "capable('OMIT_EXPLAIN')". And that function returns true
27166 ** if the EXPLAIN capability is omitted. It works like a
27167 ** double-negative. This is a bit confusing (hence the special
27168 ** names for the common cases mentioned above) but it servicable
27169 ** for the rare cases when it is needed.
27170 **
27171 ** This function is intended to be used with the ".if" command
27172 ** to bypass test cases that use features that are not part of
27173 ** the build. Examples:
27174 **
@@ -26861,33 +27198,54 @@
27198 "load_ext", "OMIT_LOAD_EXTENSION",
27199 };
27200 size_t i;
27201 int invert = 0;
27202 int res = 0;
27203 sqlite3_vfs *pVfs;
27204
27205 UNUSED_PARAMETER(nVal);
27206 if( z==0 ) return;
27207
27208 /* Check available VFS names */
27209 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
27210 if( sqlite3_stricmp(z,pVfs->zName)==0 ){
27211 res = 1;
27212 goto capable_finished;
27213 }
27214 }
27215
27216 /* Special case: capable('unsafe') is true if not in safe mode */
27217 if( sqlite3_stricmp(z, "unsafe")==0 && p->bSafeMode==0 ){
27218 res = 1;
27219 goto capable_finished;
27220 }
27221
27222 /* Check special cases likek "vtab" and "fkey" */
27223 for(i=0; i<sizeof(azInversions)/sizeof(azInversions[0])-1; i+=2){
27224 if( sqlite3_stricmp(z, azInversions[i])==0 ){
27225 z = azInversions[i+1];
27226 invert = 1;
27227 break;
27228 }
27229 }
27230
27231 /* Run pragmas listing compile-time options, virtual tables, and functions */
27232 for(i=0; i<sizeof(azSql)/sizeof(azSql[0]); i++){
27233 sqlite3_stmt *pStmt = 0;
27234 sqlite3_prepare_v2(p->db, azSql[i], -1, &pStmt, 0);
27235 while( sqlite3_step(pStmt)==SQLITE_ROW ){
27236 const char *zRow = (const char*)sqlite3_column_text(pStmt, 0);
27237 if( sqlite3_stricmp(z,zRow)==0 ){
27238 res = 1;
27239 break;
27240 }
27241 }
27242 sqlite3_finalize(pStmt);
27243 if( res ) break;
27244 }
27245
27246 capable_finished:
27247 if( invert ) res = !res;
27248 sqlite3_result_int(pCtx, res);
27249 }
27250
27251
@@ -27343,10 +27701,25 @@
27701 }
27702 }
27703
27704 /* Forward reference */
27705 static int pickStr(const char *zArg, char **pzErr, ...);
27706
27707 /*
27708 ** Clamp a user-supplied value into the range 0..32767 or
27709 ** 0..2147483647
27710 */
27711 static short int modeClamp16(i64 x){
27712 if( x<0 ) x = 0;
27713 if( x>0x7fff ) x = 0x7fff;
27714 return (short int)x;
27715 }
27716 static int modeClamp32(i64 x){
27717 if( x<0 ) x = 0;
27718 if( x>0x7fffffff ) x = 0x7fffffff;
27719 return (int)x;
27720 }
27721
27722 /*
27723 ** Change the limits on the display mode. Return 0 on
27724 ** success. Return non-zero if zArg is mis-formatted.
27725 **
@@ -27371,13 +27744,13 @@
27744 p->mode.spec.nTitleLimit = 0;
27745 }else{
27746 int L, C, T = 0;
27747 int nNum = sscanf(zArg, "%d,%d,%d", &L, &C, &T);
27748 if( nNum<2 || L<0 || C<0 || T<0) return 1;
27749 p->mode.spec.nLineLimit = modeClamp16(L);
27750 p->mode.spec.nCharLimit = C;
27751 if( nNum==3 ) p->mode.spec.nTitleLimit = modeClamp16(T);
27752 }
27753 return 0;
27754 }
27755
27756 /*
@@ -28324,10 +28697,34 @@
28697 }
28698 if( zName==0 ) return;
28699 p->zDestTable = sqlite3_mprintf("%s", zName);
28700 shell_check_oom(p->zDestTable);
28701 }
28702
28703 /*
28704 ** Return a copy of the text z, obtained from sqlite3_malloc(), that is safe
28705 ** to embed inside of a C-style comment in a script of SQL statements and
28706 ** dot-commands. Newlines and other control characters are changed to spaces,
28707 ** and any end-of-comment sequence is broken up. Otherwise, text taken from
28708 ** an untrusted database (for example, a table name in an error message)
28709 ** could terminate the comment and put arbitrary SQL, or a line that begins
28710 ** with "." and so is interpreted as a dot-command, into the output.
28711 */
28712 static char *shellSafeCommentText(const char *z){
28713 char *zOut = sqlite3_mprintf("%s", z ? z : "");
28714 int i;
28715 if( zOut==0 ) return 0;
28716 for(i=0; zOut[i]; i++){
28717 unsigned char c = (unsigned char)zOut[i];
28718 if( c<' ' || c==0x7f ){
28719 zOut[i] = ' ';
28720 }else if( c=='/' && i>0 && zOut[i-1]=='*' ){
28721 zOut[i] = ' ';
28722 }
28723 }
28724 return zOut;
28725 }
28726
28727 /*
28728 ** Maybe construct two lines of text that point out the position of a
28729 ** syntax error. Return a pointer to the text, in memory obtained from
28730 ** sqlite3_malloc(). Or, if the most recent error does not involve a
@@ -28357,11 +28754,11 @@
28754 len = strlen(zSql);
28755 if( len>78 ){
28756 len = 78;
28757 while( len>0 && (zSql[len]&0xc0)==0x80 ) len--;
28758 }
28759 zCode = sqlite3_mprintf("%.*s", (int)len, zSql);
28760 shell_check_oom(zCode);
28761 for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
28762 if( iOffset<25 ){
28763 zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode,iOffset,"");
28764 }else{
@@ -28391,12 +28788,14 @@
28788 int i;
28789 const char *z;
28790 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
28791 if( rc!=SQLITE_OK || !pSelect ){
28792 char *zContext = shell_error_context(zSelect, p->db);
28793 char *zMsg = shellSafeCommentText(sqlite3_errmsg(p->db));
28794 cli_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s",
28795 rc, zMsg, zContext);
28796 sqlite3_free(zMsg);
28797 sqlite3_free(zContext);
28798 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
28799 return rc;
28800 }
28801 rc = sqlite3_step(pSelect);
@@ -28416,12 +28815,13 @@
28815 }
28816 rc = sqlite3_step(pSelect);
28817 }
28818 rc = sqlite3_finalize(pSelect);
28819 if( rc!=SQLITE_OK ){
28820 char *zMsg = shellSafeCommentText(sqlite3_errmsg(p->db));
28821 cli_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, zMsg);
28822 sqlite3_free(zMsg);
28823 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
28824 }
28825 return rc;
28826 }
28827
@@ -28705,21 +29105,21 @@
29105 /* Create the TEMP table used to store parameter bindings */
29106 static void bind_table_init(ShellState *p){
29107 int wrSchema = 0;
29108 int defensiveMode = 0;
29109 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
29110 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, (int*)0);
29111 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
29112 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, (int*)0);
29113 sqlite3_exec(p->db,
29114 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
29115 " key TEXT PRIMARY KEY,\n"
29116 " value\n"
29117 ") WITHOUT ROWID;",
29118 0, 0, 0);
29119 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, (int*)0);
29120 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, (int*)0);
29121 }
29122
29123 /*
29124 ** Bind parameters on a prepared statement.
29125 **
@@ -28735,13 +29135,16 @@
29135 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
29136 int nVar;
29137 int i;
29138 int rc;
29139 sqlite3_stmt *pQ = 0;
29140 int inTrace = 0;
29141
29142 nVar = sqlite3_bind_parameter_count(pStmt);
29143 if( nVar==0 ) return; /* Nothing to do */
29144 sqlite3_db_config(pArg->db, SQLITE_DBCONFIG_VDBE_TRACE, -1, &inTrace);
29145 sqlite3_db_config(pArg->db, SQLITE_DBCONFIG_VDBE_TRACE, 0, (int*)0);
29146 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
29147 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
29148 rc = SQLITE_NOTFOUND;
29149 pQ = 0;
29150 }else{
@@ -28754,10 +29157,11 @@
29157 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
29158 if( zVar==0 ){
29159 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
29160 zVar = zNum;
29161 }
29162 if( inTrace ) cli_printf(pArg->out, "BIND: %s\n", zVar);
29163 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
29164 if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){
29165 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
29166 #ifdef NAN
29167 }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){
@@ -28805,17 +29209,18 @@
29209 && ShellHasFlag(pArg,SHFLG_TestingMode) ){
29210 sqlite3_bind_pointer(pStmt,i,aPrimes,"carray",0);
29211 }else{
29212 sqlite3_bind_null(pStmt, i);
29213 }
29214 #endif
29215 }else{
29216 sqlite3_bind_null(pStmt, i);
29217 }
29218 sqlite3_reset(pQ);
29219 }
29220 sqlite3_finalize(pQ);
29221 sqlite3_db_config(pArg->db, SQLITE_DBCONFIG_VDBE_TRACE, inTrace, (int*)0);
29222 }
29223
29224 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION)
29225 /*
29226 ** This function is called to process SQL if the previous shell command
@@ -29034,42 +29439,55 @@
29439
29440 /* save off the prepared statement handle */
29441 if( pArg ){
29442 pArg->pStmt = pStmt;
29443 }
29444
29445 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
29446 bind_prepared_stmt(pArg, pStmt);
29447 isExplain = sqlite3_stmt_isexplain(pStmt);
29448 if( pArg && pArg->mode.autoEQP && isExplain==0 && pArg->dot.nArg==0 ){
29449 int triggerEQP = 0;
29450 u8 savedEnableTimer = pArg->enableTimer;
29451 FILE *savedOut = pArg->out;
29452 pArg->enableTimer = 0;
29453 disable_debug_trace_modes();
29454 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
29455 if( pArg->mode.autoEQP>=AUTOEQP_trigger ){
29456 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
29457 }
29458 sqlite3_reset(pStmt);
29459 spec.eStyle = QRF_STYLE_Auto;
29460 sqlite3_stmt_explain(pStmt, 2);
29461 if( pArg->zEqpFile ){
29462 pArg->out = sqlite3_fopen(pArg->zEqpFile, "ab");
29463 if( pArg->out==0 ){
29464 cli_printf(savedOut, "cannot open .eqp output file \"%s\"\n",
29465 pArg->zEqpFile);
29466 pArg->out = savedOut;
29467 }
29468 }
29469 sqlite3_format_query_result(pStmt, &spec, 0);
29470 if( pArg->mode.autoEQP>=AUTOEQP_full ){
29471 sqlite3_reset(pStmt);
29472 sqlite3_stmt_explain(pStmt, 1);
29473 sqlite3_format_query_result(pStmt, &spec, 0);
29474 }
29475
29476 if( pArg->mode.autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
29477 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, (int*)0);
29478 }
29479 sqlite3_reset(pStmt);
29480 sqlite3_stmt_explain(pStmt, 0);
29481 if( pArg->out!=savedOut ){
29482 fclose(pArg->out);
29483 pArg->out = savedOut;
29484 }
29485 restore_debug_trace_modes();
29486 pArg->enableTimer = savedEnableTimer;
29487 }
29488
 
29489 if( isExplain && pArg->mode.autoExplain ){
29490 spec.eStyle = isExplain==1 ? QRF_STYLE_Explain : QRF_STYLE_Eqp;
29491 rc = sqlite3_format_query_result(pStmt, &spec, pzErrMsg);
29492 }else if( pArg->mode.eMode==MODE_Www ){
29493 cli_printf(pArg->out,
@@ -29422,20 +29840,24 @@
29840 if( rc==SQLITE_CORRUPT ){
29841 char *zQ2;
29842 int len = strlen30(zQuery);
29843 cli_puts("/****** CORRUPTION ERROR *******/\n", p->out);
29844 if( zErr ){
29845 char *zMsg = shellSafeCommentText(zErr);
29846 cli_printf(p->out, "/****** %s ******/\n", zMsg);
29847 sqlite3_free(zMsg);
29848 sqlite3_free(zErr);
29849 zErr = 0;
29850 }
29851 zQ2 = malloc( len+100 );
29852 if( zQ2==0 ) return rc;
29853 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
29854 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
29855 if( rc ){
29856 char *zMsg = shellSafeCommentText(zErr);
29857 cli_printf(p->out, "/****** ERROR: %s ******/\n", zMsg);
29858 sqlite3_free(zMsg);
29859 }else{
29860 rc = SQLITE_CORRUPT;
29861 }
29862 free(zQ2);
29863 }
@@ -29632,13 +30054,17 @@
30054 ".recover Recover as much data as possible from corrupt db.",
30055 " --ignore-freelist Ignore pages that appear to be on db freelist",
30056 " --lost-and-found TABLE Alternative name for the lost-and-found table",
30057 " --no-rowids Do not attempt to recover rowid values",
30058 " that are not also INTEGER PRIMARY KEYs",
30059 " --unsafe Do not issue the \".safe\" command in output",
30060 #endif
30061 #ifndef SQLITE_SHELL_FIDDLE
30062 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
30063 #endif
30064 ".safe Put the CLI into \"safe mode\"",
30065 #ifndef SQLITE_SHELL_FIDDLE
30066 ".save ?OPTIONS? FILE Write database to FILE (an alias for .backup ...)",
30067 #endif
30068 ".scanstats on|off|est Turn sqlite3_stmt_scanstatus() metrics on or off",
30069 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
30070 " Options:",
@@ -29726,21 +30152,10 @@
30152 ** "Usage" help text automatically generated from comments */
30153 static const struct {
30154 const char *zCmd; /* Name of the dot-command */
30155 const char *zUsage; /* Documentation */
30156 } aUsage[] = {
 
 
 
 
 
 
 
 
 
 
 
30157 { ".import",
30158 "USAGE: .import [OPTIONS] FILE TABLE\n"
30159 "\n"
30160 "Import CSV or similar text from FILE into TABLE. If TABLE does\n"
30161 "not exist, it is created using the first row of FILE as the column\n"
@@ -29770,10 +30185,140 @@
30185 " --rowsep CHAR Use CHAR as the row separator.\n"
30186 " --schema S When creating TABLE, put it in schema S\n"
30187 " --skip N Ignore the first N rows of input\n"
30188 " -v Verbose mode\n"
30189 },
30190 { ".testcase",
30191 "USAGE: .testcase [OPTIONS] NAME\n"
30192 "\n"
30193 "Start a new test case identified by NAME. All output\n"
30194 "through the next \".check\" command is captured for comparison. See the\n"
30195 "\".check\" command for additional information.\n"
30196 "\n"
30197 "Options:\n"
30198 " --error-prefix TEXT Change error message prefix text to TEXT\n"
30199 },
30200 { ".once",
30201 "USAGE: .once [OPTIONS] FILE ...\n"
30202 "\n"
30203 "Write the output for the next line of SQL or the next dot-command into\n"
30204 "FILE. If FILE begins with \"|\" then it is a program into which output\n"
30205 "is written. The FILE argument should be omitted if one of the -e, -w,\n"
30206 "or -x options is used.\n"
30207 "\n"
30208 "Options:\n"
30209 " -e Capture output into a temporary file then bring up\n"
30210 " a text editor on that temporary file.\n"
30211 " --plain Use plain text rather than HTML tables with -w\n"
30212 " -w Capture output into an HTML file then bring up that\n"
30213 " file in a web browser\n"
30214 " -x Show the output in a spreadsheet. Output is\n"
30215 " written to a temp file as CSV then the spreadsheet\n"
30216 " is launched when\n"
30217 },
30218 { ".check",
30219 "USAGE: .check [OPTIONS] PATTERN\n"
30220 "\n"
30221 "Verify the output of all commands since the most recent .testcase\n"
30222 "command. Both stdout and stderr are captured and compared, so error\n"
30223 "messages are part of the text being compared, however output from\n"
30224 "the \".echo on\" dot-command is not captured and is not part of the test\n"
30225 "result.\n"
30226 "\n"
30227 "After checking the result, all captured output is discarded and\n"
30228 "output starts going back to the console, unless --keep is used.\n"
30229 "\n"
30230 "The PATTERN is the concatenation (with a single space separator) of\n"
30231 "all arguments that are not part of OPTIONS.\n"
30232 "\n"
30233 "If PATTERN is \"<<ENDMARK\" (for any ENDMARK) then the actual pattern is\n"
30234 "taken from subsequent lines of text up to the first line that begins\n"
30235 "with ENDMARK.\n"
30236 "\n"
30237 "The default comparison algorithm is to ignore all leading and trailing\n"
30238 "whitespace and compare the pattern against the result byte-for-byte except\n"
30239 "that whitespace characters are equal to other whitespace characters.\n"
30240 "Thus if the pattern contains a space character and the result contains\n"
30241 "a tab in the same spot, they would still compare equal. The number of\n"
30242 "whitespace characters must be the same in the pattern and the result.\n"
30243 "\n"
30244 "The --glob, --notglob, and --allglob comparisons are extended so that\n"
30245 "\"#\" in the pattern matches a sequence of one or more digits with an\n"
30246 "optional leading \"+\" or \"-\", and a space in the pattern matches a run\n"
30247 "of one or more whitespace characters.\n"
30248 "\n"
30249 "Options:\n"
30250 " --allglob PATTERN is a GLOB matching the entire test output except\n"
30251 " leading and trailing whitespace.\n"
30252 " --any PATTERN is any substring within the test output.\n"
30253 " --exact PATTERN matches the entire test output, byte for byte.\n"
30254 " --glob PATTERN is a GLOB matching any substring of the test\n"
30255 " output. Leading and trailing whitespace on the PATTERN\n"
30256 " is ignored.\n"
30257 " --keep Do not reset the test output. One or more .check commands\n"
30258 " will follow and do additional tests.\n"
30259 " --not Pass if the test output does *not* match PATTERN.\n"
30260 " --notglob Shorthand for \"--not --glob\".\n"
30261 " --nowhere Shorthand for \"--not --any\".\n"
30262 " --regexp PATTERN is a regular expression matching any substring\n"
30263 " of the test output.\n"
30264 " --show Write test output to the screen, for debugging.\n"
30265 },
30266 { ".safe",
30267 "USAGE: .safe\n"
30268 "\n"
30269 "This command puts the CLI into \"safe mode\". This command cannot be\n"
30270 "undone. The only way to restore full capabilities is to exit and\n"
30271 "restart the CLI.\n"
30272 "\n"
30273 "Safe mode restricts SQL statements and dot-commands so that no\n"
30274 "changes may be made to the filesystem other than writing to database\n"
30275 "files that are already open.\n"
30276 "\n"
30277 " * The .open command is blocked unless the database is \":memory:\"\n"
30278 " or the --hexdb option is used.\n"
30279 " * The ATTACH command of SQL may not be used\n"
30280 " * SQL functions with side effects (ex: writefile()) are blocked.\n"
30281 " * The \".shell\" and \".system\" dot-commands are blocked.\n"
30282 " * Dot-command like \".archive\", \".backup\", \".load\", \".log\", \".save\"\n"
30283 " are blocked.\n"
30284 " * Other commands with deleterious side effects are blocked.\n"
30285 "\n"
30286 "Unsafe actions might be simply blocked, or the CLI might issue an error\n"
30287 "and exit immediately.\n"
30288 "\n"
30289 "Safe mode does not prevent harm to database files that are already open.\n"
30290 "An attacker can still delete content and even use commands like\n"
30291 "\"PRAGMA writable_schema=ON\" to corrupt a database file that is already\n"
30292 "open. Safe mode only blocks access to other previously unopened files.\n"
30293 "\n"
30294 "CAUTION: If third-party extensions with system side effects have been\n"
30295 "loaded prior to the .safe command, the CLI has no knowledge of those\n"
30296 "extensions and does not know to block them. Unsafe actions might still\n"
30297 "be possible using those third-party extension.\n"
30298 },
30299 { ".if",
30300 "USAGE: .if SQL-EXPRESSION\n"
30301 "\n"
30302 "The argument can be any SQL expression, including a subquery in\n"
30303 "parentheses. If the expression evalutes to true (if it is non-zero\n"
30304 "when converted into an number) then subsequent statements are\n"
30305 "evaluated. If SQL-EXPRESSION evalutes to false or NULL or raises\n"
30306 "an error, then subsequent statements are skipped, up until the first\n"
30307 "matching .elseif, .else, or .endif.\n"
30308 "\n"
30309 "Maximum nested depth is limited. An error is raised if .if statements\n"
30310 "are nested to deep.\n"
30311 "\n"
30312 "Every .if must be followed by a matching .endif, or an error is raised.\n"
30313 },
30314 { ".else",
30315 "USAGE: .else\n"
30316 "\n"
30317 "Invert the sense of the inner-most .if. Start processing if the prior\n"
30318 ".if was false. Stop processing if the prior .if was true.\n"
30319 },
30320 { ".mode",
30321 "USAGE: .mode [MODE] [OPTIONS]\n"
30322 "\n"
30323 "Change the output mode to MODE and/or apply OPTIONS to the output mode.\n"
30324 "Arguments are processed from left to right. If no arguments, show the\n"
@@ -29844,10 +30389,81 @@
30389 " for the unspecified widths.\n"
30390 " --wordwrap BOOLEAN Enable/disable word wrapping\n"
30391 " --wrap N Wrap columns wider than N characters\n"
30392 " --ww Shorthand for \"--wordwrap on\"\n"
30393 },
30394 { ".eqp",
30395 "USAGE: .eqp EQPMODE [>OUTPUTFILE]\n"
30396 "\n"
30397 "The .eqp command enables or disables the automatic display of EXPLAIN\n"
30398 "output for each SQL statement evaluated. The required EQPMODE argument\n"
30399 "may be one of the following:\n"
30400 "\n"
30401 " full Show both EXPLAIN QUERY PLAN and EXPLAIN output.\n"
30402 "\n"
30403 " off Disable all explain output.\n"
30404 "\n"
30405 " on Show EXPLAIN QUERY PLAN output only.\n"
30406 "\n"
30407 " trace Like \"full\" but also enable VDBE tracing using\n"
30408 " PRAGMA vdbe_trace=ON. This option only works if the\n"
30409 " CLI is compiled with -DSQLITE_DEBUG. The trace output\n"
30410 " always appears on stdout and is not redirected to a file.\n"
30411 "\n"
30412 " trigger Like \"full\" but also show EXPLAIN output for trigger\n"
30413 " subprograms.\n"
30414 "\n"
30415 "The EQPMODE maybe be optionally followed by a filename. If a file is\n"
30416 "specified, with or without a single leading \">\", then the file is\n"
30417 "deleted and all subsequent explain output is appended to that file.\n"
30418 "If the filename begins with \">>\" then the content of the file is retained\n"
30419 "and all output is appended. If not redirection argument is provided,\n"
30420 "output redirection is cancelled. The ability to redirect is not available\n"
30421 "for --safe mode.\n"
30422 },
30423 { ".endif",
30424 "USAGE: .endif\n"
30425 "\n"
30426 "Terminate an .if statement.\n"
30427 },
30428 { ".stats",
30429 "USAGE: .stats [OPTIONS] ...\n"
30430 "\n"
30431 "Show status information about the database and database connection.\n"
30432 "The stats setting is persistent, unless the --once option is used.\n"
30433 "Options are cumulative and are processed from left to right.\n"
30434 "If no options are given, that is the same as \".stats all --once\".\n"
30435 "\n"
30436 "Options:\n"
30437 " all Show all available stats.\n"
30438 " io Show I/O stats (Linux only).\n"
30439 " mem Show basic memory usage.\n"
30440 " off Show nothing. Turn off stat display.\n"
30441 " on Shorthand for \"stmt xmem\".\n"
30442 " --once Show the stats once. Do not change the default stats display.\n"
30443 " reset Reset \"max\" values after next display of each that value.\n"
30444 " stmt Show information about the last SQL statement.\n"
30445 " vmstep Show the number of virtual machine steps taken.\n"
30446 " xmem Show detailed memory status information\n"
30447 " xstmt Show details about each SQL statement\n"
30448 },
30449 { ".elseif",
30450 "USAGE: .elseif SQL-EXPRESSION\n"
30451 "\n"
30452 "An \"else-if\". The prior .if is finished and a new condition is applied.\n"
30453 },
30454 { ".clone",
30455 "USAGE: .clone FILE\n"
30456 "\n"
30457 "The original purpose of the \".clone\" command (when it was first introduced\n"
30458 "in 2014) was to try to recover content for a corrupt database file and\n"
30459 "write the recovered content into a new database named FILE. However,\n"
30460 "the command has always been experimental and undocumented. Today, it\n"
30461 "does nothing more than make a copy of the main database into a new\n"
30462 "database named by its only argument, FILE. No repair attempts are\n"
30463 "made. The command is retained for legacy only.\n"
30464 },
30465 { ".output",
30466 "USAGE: .output [OPTIONS] [FILE]\n"
30467 "\n"
30468 "Begin redirecting output to FILE. Or if FILE is omitted, revert\n"
30469 "to sending output to the console. If FILE begins with \"|\" then\n"
@@ -29876,109 +30492,10 @@
30492 " the --plain is used too.\n"
30493 " -x Show the output in a spreadsheet. Output is\n"
30494 " written to a temp file as CSV then the spreadsheet\n"
30495 " is launched when\n"
30496 },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30497 };
30498
30499 /*
30500 ** Return a pointer to usage text for zCmd, or NULL if none exists.
30501 */
@@ -30119,11 +30636,11 @@
30636 **
30637 ** NULL is returned if any error is encountered. The final value of *pnByte
30638 ** is undefined in this case.
30639 */
30640 static char *readFile(const char *zName, int *pnByte){
30641 FILE *in = (zName && zName[0]) ? sqlite3_fopen(zName, "rb") : 0;
30642 long nIn;
30643 size_t nRead;
30644 char *pBuf;
30645 int rc;
30646 if( in==0 ) return 0;
@@ -30328,10 +30845,11 @@
30845 }
30846 if( rc ) return 0; /* Is a database */
30847 }
30848 if( sqlite3_strlike("%.sql",z,0)==0 ) return 1;
30849 if( sqlite3_strlike("%.txt",z,0)==0 ) return 1;
30850 if( sqlite3_strlike("%.clitest",z,0)==0 ) return 1;
30851 return 0;
30852 }
30853
30854 #ifndef SQLITE_OMIT_DESERIALIZE
30855 /*
@@ -30438,10 +30956,29 @@
30956 int sleep = sqlite3_value_int(argv[0]);
30957 (void)argcUnused;
30958 sqlite3_sleep(sleep/1000);
30959 sqlite3_result_int(context, sleep);
30960 }
30961
30962 /*
30963 ** SQL function: dualrep(X)
30964 **
30965 ** Return the value X. But if X is in a numeric representation (an
30966 ** integer or a float) then return a dual-representation where the
30967 ** result is both numeric and text at the same time. This has no
30968 ** known practical application, but is useful in testing SQLite
30969 ** internals.
30970 */
30971 static void shellDualRepFunc(
30972 sqlite3_context *context,
30973 int argcUnused,
30974 sqlite3_value **argv
30975 ){
30976 (void)argcUnused;
30977 sqlite3_value_text(argv[0]);
30978 sqlite3_result_value(context, argv[0]);
30979 }
30980
30981 /*
30982 ** SQL function: shell_module_schema(X)
30983 **
30984 ** For use internally and for debugging and testing only. This function
@@ -30580,16 +31117,18 @@
31117 sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
31118
31119 /* Reflect the use or absence of --unsafe-testing invocation. */
31120 {
31121 int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
31122 sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,
31123 (int*)0);
31124 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,
31125 (int*)0);
31126 }
31127
31128 #ifndef SQLITE_OMIT_LOAD_EXTENSION
31129 sqlite3_enable_load_extension(p->db, !p->bSafeMode);
31130 #endif
31131 sqlite3_sha_init(p->db, 0, 0);
31132 sqlite3_shathree_init(p->db, 0, 0);
31133 sqlite3_uint_init(p->db, 0, 0);
31134 sqlite3_stmtrand_init(p->db, 0, 0);
@@ -30599,22 +31138,20 @@
31138 sqlite3_regexp_init(p->db, 0, 0);
31139 sqlite3_ieee_init(p->db, 0, 0);
31140 sqlite3_series_init(p->db, 0, 0);
31141 sqlite3_diskused_init(p->db, 0, 0);
31142 sqlite3_strdup_init(p->db, 0, 0);
 
31143 if( !p->bSafeMode ){
31144 sqlite3_tryeval_init(p->db, 0, 0);
31145 #ifndef SQLITE_SHELL_FIDDLE
31146 sqlite3_fileio_init(p->db, 0, 0);
 
 
31147 #endif
31148 #ifdef SQLITE_HAVE_ZLIB
 
31149 sqlite3_zipfile_init(p->db, 0, 0);
31150 sqlite3_sqlar_init(p->db, 0, 0);
31151 #endif
31152 }
 
31153 #ifdef SQLITE_SHELL_EXTFUNCS
31154 /* Create a preprocessing mechanism for extensions to make
31155 * their own provisions for being built into the shell.
31156 * This is a short-span macro. See further below for usage.
31157 */
@@ -30661,10 +31198,12 @@
31198 shell_complete_sql, 0, 0);
31199 sqlite3_create_function(p->db, "shell_complete_sql", 2, SQLITE_UTF8, p,
31200 shell_complete_sql, 0, 0);
31201 sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
31202 shellUSleepFunc, 0, 0);
31203 sqlite3_create_function(p->db, "dualrep",1,SQLITE_UTF8,0,
31204 shellDualRepFunc, 0, 0);
31205 #ifndef SQLITE_NOHAVE_SYSTEM
31206 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
31207 editFunc, 0, 0);
31208 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
31209 editFunc, 0, 0);
@@ -31624,11 +32163,13 @@
32163 while( (c=(*(zGlob++))) == '*' || c=='?' ){
32164 if( c=='?' && (*(z++))==0 ) return 0;
32165 }
32166 if( c==0 ){
32167 return 1;
32168 }else if( c=='[' || c=='#' || IsSpace(c) ){
32169 /* The next pattern element is not a literal character. Try to
32170 ** match it at each position in the remaining text. */
32171 while( *z && testcase_glob(zGlob-1,z)==0 ){
32172 z++;
32173 }
32174 return (*z)!=0;
32175 }
@@ -32103,12 +32644,15 @@
32644 sqlite3_free(zPrev);
32645 zPrev = sqlite3_mprintf("%s", zParent);
32646 }
32647
32648 if( res==0 ){
32649 if( strchr(zTarget,'\n') ) zTarget = "(REDACTED)";
32650 cli_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
32651 }else if( bVerbose ){
32652 if( strstr(zFrom,"*/") ) zFrom = "(REDACTED)";
32653 if( strstr(zTarget,"*/") ) zTarget = "(REDACTED)";
32654 cli_printf(out,
32655 "%s/* no extra indexes required for %s -> %s */\n",
32656 zIndent, zFrom, zTarget
32657 );
32658 }
@@ -33081,10 +33625,11 @@
33625 int rc = SQLITE_OK;
33626 const char *zRecoveryDb = ""; /* Name of "recovery" database. Debug only */
33627 const char *zLAF = "lost_and_found";
33628 int bFreelist = 1; /* 0 if --ignore-freelist is specified */
33629 int bRowids = 1; /* 0 if --no-rowids */
33630 int bUnsafe = 0; /* 1 if --unsafe */
33631 sqlite3_recover *p = 0;
33632 int i = 0;
33633
33634 for(i=1; i<nArg; i++){
33635 char *z = azArg[i];
@@ -33107,10 +33652,13 @@
33652 i++;
33653 zLAF = azArg[i];
33654 }else
33655 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
33656 bRowids = 0;
33657 }else
33658 if( n<=7 && memcmp("-unsafe", z, n)==0 ){
33659 bUnsafe = 1;
33660 }
33661 else{
33662 cli_printf(stderr,"unexpected option: %s\n", azArg[i]);
33663 showHelp(pState->out, azArg[0]);
33664 return 1;
@@ -33127,10 +33675,11 @@
33675 sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
33676 sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
33677 sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
33678
33679 cli_printf(pState->out, ".dbconfig defensive off\n");
33680 if( !bUnsafe ) cli_printf(pState->out, ".safe\n");
33681 sqlite3_recover_run(p);
33682 if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
33683 const char *zErr = sqlite3_recover_errmsg(p);
33684 int errCode = sqlite3_recover_errcode(p);
33685 cli_printf(stderr,"sql error: %s (%d)\n", zErr, errCode);
@@ -33910,11 +34459,11 @@
34459 import_cleanup(&sCtx);
34460 sqlite3_finalize(pStmt);
34461 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
34462 if( eVerbose>0 ){
34463 cli_printf(p->out,
34464 "Added %d rows with %d errors using %lld lines of input\n",
34465 sCtx.nRow, sCtx.nErr, sCtx.nLine-1-iLineOffset);
34466 }
34467 return sCtx.nErr ? 1 : 0;
34468 }
34469
@@ -34144,21 +34693,21 @@
34693 p->mode.spec.bBorder = k & 0x3;
34694 }
34695 chng = 1;
34696 }else if( 0<=(k=pickStr(z,0,
34697 "-charlimit","-linelimit","-titlelimit","-multiinsert","")) ){
34698 i64 w; /* 0 1 2 3 */
34699 if( i+1>=nArg ){
34700 dotCmdError(p, i, "missing argument", 0);
34701 return 1;
34702 }
34703 w = integerValue(azArg[++i]);
34704 switch( k ){
34705 case 0: p->mode.spec.nCharLimit = modeClamp32(w); break;
34706 case 1: p->mode.spec.nLineLimit = modeClamp16(w); break;
34707 case 2: p->mode.spec.nTitleLimit = modeClamp16(w); break;
34708 default: p->mode.spec.nMultiInsert = modeClamp32(w); break;
34709 }
34710 chng = 1;
34711 }else if( 0<=(k=pickStr(z,0,"-tablename","-rowsep","-colsep","-null","")) ){
34712 /* 0 1 2 3 */
34713 if( i+1>=nArg ){
@@ -34305,13 +34854,15 @@
34854 memcpy(p->mode.zFpFmt, azArg[i], strlen(azArg[i])+1);
34855 p->mode.spec.zFpFmt = p->mode.zFpFmt;
34856 }
34857 chng = 1;
34858 }else if( optionMatch(z,"reset") ){
34859 int saved_eMode = p->mode.eMode; /* Don't change the mode */
34860 u8 saved_echo = p->mode.mFlags & MFLG_ECHO; /* Don't reset --echo */
34861 modeFree(&p->mode); /* Reset everything else */
34862 modeChange(p, saved_eMode);
34863 p->mode.mFlags = saved_echo;
34864 }else if( optionMatch(z,"rowcount") ){
34865 if( i+1>=nArg ){
34866 dotCmdError(p, i, "missing argument", 0);
34867 return 1;
34868 }
@@ -34893,11 +35444,11 @@
35444
35445 /*
35446 ** Return true if the argument is <<MARK for some arbitrary mark
35447 */
35448 static int isHereDoc(const char *z){
35449 return z && z[0]=='<' && z[1]=='<' && z[2]!=0;
35450 }
35451
35452 /*
35453 ** Capture lines of input text up until a line that matches zTerminator.
35454 ** Return a memory buffer (allocated using sqlite3_malloc64()) that
@@ -34912,42 +35463,93 @@
35463 if( cli_strncmp(zTerminator,zLine,nTerminator)==0 ) break;
35464 sqlite3_str_appendall(pHeredoc, zLine);
35465 }
35466 return sqlite3_str_finish(pHeredoc);
35467 }
35468
35469 /*
35470 ** Return a pointer to the first non-whitespace character in the input
35471 ** string, or a pointer to the string terminator if the input contains
35472 ** no non-whitespace characters.
35473 **
35474 ** The number of bytes that follow, excluding trailing whitespace, is
35475 ** written into *pN if pN!=0.
35476 */
35477 static char *trimSpace(char *zIn, int *pN){
35478 while( IsSpace(zIn[0]) ){ zIn++; }
35479 if( pN ){
35480 size_t n = strlen(zIn);
35481 assert( n<=0x7fffffff );
35482 while( n>0 && IsSpace(zIn[n-1]) ){ n--; }
35483 *pN = (int)n;
35484 }
35485 return zIn;
35486 }
35487
35488 /*
35489 ** DOT-COMMAND: .check
35490 ** USAGE: .check [OPTIONS] PATTERN
35491 **
35492 ** Verify the output of all commands since the most recent .testcase
35493 ** command. Both stdout and stderr are captured and compared, so error
35494 ** messages are part of the text being compared, however output from
35495 ** the ".echo on" dot-command is not captured and is not part of the test
35496 ** result.
35497 **
35498 ** After checking the result, all captured output is discarded and
35499 ** output starts going back to the console, unless --keep is used.
35500 **
35501 ** The PATTERN is the concatenation (with a single space separator) of
35502 ** all arguments that are not part of OPTIONS.
35503 **
35504 ** If PATTERN is "<<ENDMARK" (for any ENDMARK) then the actual pattern is
35505 ** taken from subsequent lines of text up to the first line that begins
35506 ** with ENDMARK.
35507 **
35508 ** The default comparison algorithm is to ignore all leading and trailing
35509 ** whitespace and compare the pattern against the result byte-for-byte except
35510 ** that whitespace characters are equal to other whitespace characters.
35511 ** Thus if the pattern contains a space character and the result contains
35512 ** a tab in the same spot, they would still compare equal. The number of
35513 ** whitespace characters must be the same in the pattern and the result.
35514 **
35515 ** The --glob, --notglob, and --allglob comparisons are extended so that
35516 ** "#" in the pattern matches a sequence of one or more digits with an
35517 ** optional leading "+" or "-", and a space in the pattern matches a run
35518 ** of one or more whitespace characters.
35519 **
35520 ** Options:
35521 ** --allglob PATTERN is a GLOB matching the entire test output except
35522 ** leading and trailing whitespace.
35523 ** --any PATTERN is any substring within the test output.
35524 ** --exact PATTERN matches the entire test output, byte for byte.
35525 ** --glob PATTERN is a GLOB matching any substring of the test
35526 ** output. Leading and trailing whitespace on the PATTERN
35527 ** is ignored.
35528 ** --keep Do not reset the test output. One or more .check commands
35529 ** will follow and do additional tests.
35530 ** --not Pass if the test output does *not* match PATTERN.
35531 ** --notglob Shorthand for "--not --glob".
35532 ** --nowhere Shorthand for "--not --any".
35533 ** --regexp PATTERN is a regular expression matching any substring
35534 ** of the test output.
35535 ** --show Write test output to the screen, for debugging.
35536 */
35537 static int dotCmdCheck(ShellState *p){
35538 int nArg = p->dot.nArg; /* Number of arguments */
35539 char **azArg = p->dot.azArg; /* Text of the arguments */
35540 int i; /* Loop counter */
35541 int k; /* Result of pickStr() */
35542 char *zTest; /* Textcase result */
35543 int bKeep = 0; /* --keep option */
35544 sqlite3_str *pPattern; /* PATTERN argument */
35545 char *zPattern = 0; /* Test pattern */
35546 char *zToFree = 0; /* Start of test pattern */
35547 int eCheck = 0; /* 0: default. Else 1+index of option */
35548 int isOk = 0; /* True if results are OK */
35549 int bNot = 0; /* Invert the sense of the test */
35550 int iPat = -1; /* Location of the pattern */
35551 sqlite3_int64 iStart = p->lineno; /* Line number of .check statement */
35552
35553 if( p->mIf!=0 ){
35554 /* Unlike most other dot-commands, the .check command runs even if
35555 ** inside the false branch of a .if. It needs to do this so that it
@@ -34959,10 +35561,11 @@
35561 }
35562 if( p->zTestcase[0]==0 ){
35563 dotCmdError(p, 0, "no .testcase is active", 0);
35564 return 1;
35565 }
35566 pPattern = sqlite3_str_new(p->db);
35567 for(i=1; i<nArg; i++){
35568 char *z = azArg[i];
35569 if( z[0]=='-' && z[1]=='-' && z[2]!=0 ) z++;
35570 if( cli_strcmp(z,"-keep")==0 ){
35571 bKeep = 1;
@@ -34970,87 +35573,157 @@
35573 if( sqlite3_str_length(cli_output_capture)>0 ){
35574 sqlite3_fprintf(stdout, "%s", sqlite3_str_value(cli_output_capture));
35575 }
35576 bKeep = 1;
35577 }else if( z[0]=='-'
35578 && (k = pickStr(&z[1],0,
35579 /* 0 1 2 3 4 5 6 7 */
35580 "glob","exact","regexp","any","nowhere","allglob","notglob","not",""))>=0
35581 ){
35582 if( k==7 ){
35583 bNot = !bNot;
35584 }else if( eCheck==0 || eCheck==k+1 ){
35585 eCheck = k+1;
35586 }else{
35587 output_reset(p);
35588 sqlite3_str_free(pPattern);
35589 dotCmdError(p, i, "incompatible with prior options",0);
35590 return 1;
35591 }
 
 
 
 
35592 }else{
35593 if( sqlite3_str_length(pPattern)>0 ){
35594 sqlite3_str_appendchar(pPattern, 1, ' ');
35595 }else{
35596 iPat = i;
35597 }
35598 sqlite3_str_appendall(pPattern, azArg[i]);
35599 }
35600 }
 
 
 
 
35601 if( sqlite3_str_length(cli_output_capture) ){
35602 zTest = sqlite3_str_value(cli_output_capture);
35603 shell_check_oom(zTest);
35604 }else{
35605 zTest = "";
35606 }
35607 p->nTestRun++;
35608 zToFree = zPattern = sqlite3_str_finish(pPattern);
35609 if( isHereDoc(zPattern) ){
35610 zPattern = captureHereDoc(p, zPattern+2);
35611 sqlite3_free(zToFree);
35612 zToFree = zPattern;
35613 }
35614 if( zPattern==0 ){
35615 zToFree = zPattern = sqlite3_mprintf("");
35616 }
35617 shell_check_oom(zPattern);
35618 switch( eCheck ){
35619 case 6: /* --allglob */
35620 case 7: /* --notglob */
35621 case 1: { /* --glob */
35622 int nPat = 0;
35623 char *zGlob;
35624 zPattern = trimSpace(zPattern, &nPat);
35625 zTest = trimSpace(zTest, 0);
35626 if( eCheck==6 ){
35627 zGlob = sqlite3_mprintf("%.*s", nPat, zPattern);
35628 }else{
35629 zGlob = sqlite3_mprintf("*%.*s*", nPat, zPattern);
35630 }
35631 shell_check_oom(zGlob);
35632 isOk = testcase_glob(zGlob, zTest)!=0;
35633 if( eCheck==7 ) isOk = !isOk;
35634 sqlite3_free(zGlob);
35635 break;
35636 }
35637 case 2: { /* --exact */
35638 isOk = cli_strcmp(zTest,zPattern)==0;
35639 break;
35640 }
35641 case 3: { /* --regexp */
35642 ReCompiled *pRe = 0;
35643 const char *zErr = re_compile(&pRe, zPattern, 1000, 0);
35644 if( zErr ){
35645 re_free(pRe);
35646 sqlite3_free(zToFree);
35647 output_reset(p);
35648 p->nTestErr++;
35649 dotCmdError(p, iPat, "bad regexp", "bad regular expression: %s", zErr);
35650 return 1;
35651 }
35652 shell_check_oom(pRe);
35653 isOk = re_match(pRe, (const unsigned char*)zTest, -1);
35654 re_free(pRe);
35655 break;
35656 }
35657 case 4: { /* --any */
35658 isOk = strstr(zTest,zPattern)!=0;
35659 break;
35660 }
35661 case 5: { /* --nowhere */
35662 isOk = strstr(zTest,zPattern)==0;
35663 break;
35664 }
35665 default: { /* default matching rule */
35666 /* Ignore leading and trailing whitespace on both the pattern and the
35667 ** test output. Each interior whitespace character will compare equal
35668 ** to exactly one other whitespace character. */
35669 int nPat = 0;
35670 int nTest = 0;
35671 zPattern = trimSpace(zPattern, &nPat);
35672 zTest = trimSpace(zTest, &nTest);
35673 if( nPat!=nTest ){
35674 isOk = 0;
35675 }else if( memcmp(zPattern, zTest, nPat)==0 ){
35676 isOk = 1;
35677 }else{
35678 int ii;
35679 isOk = 1;
35680 for(ii=0; ii<nPat; ii++){
35681 if( zPattern[ii]!=zTest[ii]
35682 && !(IsSpace(zPattern[ii]) && IsSpace(zTest[ii]))
35683 ){
35684 isOk = 0;
35685 break;
35686 }
35687 }
35688 }
35689 break;
35690 }
35691 }
35692 if( bNot ) isOk = !isOk;
35693 if( !isOk ){
35694 static const char zDL[] = "\342\225\255\342\224\200";
35695 static const char zDR[] = "\342\224\200\342\225\256";
35696 static const char zUL[] = "\342\225\260\342\224\200";
35697 static const char zUR[] = "\342\224\200\342\225\257";
35698 static const char zLine[] = "\342\224\200\342\224\200\342\224\200"
35699 "\342\224\200\342\224\200\342\224\200"
35700 "\342\224\200\342\224\200\342\224\200"
35701 "\342\224\200\342\224\200\342\224\200"
35702 "\342\224\200\342\224\200";
35703 sqlite3_fprintf(stderr,
35704 "%s:%lld: .check failed for testcase %s\n",
35705 p->zInFile, iStart, p->zTestcase);
35706 p->nTestErr++;
35707 if( sqlite3_strglob("*\n", zPattern)==0 ){
35708 sqlite3_fprintf(stderr, "%s%s Expected %s%s\n%s%s%s Expected %s%s\n",
35709 zDL, zLine+9, zLine+9, zDR,
35710 zPattern,
35711 zUL, zLine+9, zLine+9, zUR);
35712 }else{
35713 sqlite3_fprintf(stderr, "Expected: [%s]\n", zPattern);
35714 }
35715 if( sqlite3_strglob("*\n", zTest)==0 ){
35716 sqlite3_fprintf(stderr, "%s%s Got %s%s\n%s%s%s Got %s%s\n",
35717 zDL, zLine+3, zLine, zDR,
35718 zTest,
35719 zUL, zLine+3, zLine, zUR);
35720 }else{
35721 sqlite3_fprintf(stderr, "Got: [%s]\n", zTest);
35722 }
35723 }
35724 sqlite3_free(zToFree);
 
 
35725 if( !bKeep ){
35726 output_reset(p);
35727 p->zTestcase[0] = 0;
35728 }
35729 return 0;
@@ -35151,11 +35824,11 @@
35824 ** DOT-COMMAND: .testcase
35825 ** USAGE: .testcase [OPTIONS] NAME
35826 **
35827 ** Start a new test case identified by NAME. All output
35828 ** through the next ".check" command is captured for comparison. See the
35829 ** ".check" command for additional information.
35830 **
35831 ** Options:
35832 ** --error-prefix TEXT Change error message prefix text to TEXT
35833 */
35834 static int dotCmdTestcase(ShellState *p){
@@ -35172,11 +35845,11 @@
35845 dotCmdError(p, i, "missing argument", 0);
35846 return 1;
35847 }
35848 free(p->zErrPrefix);
35849 i++;
35850 p->zErrPrefix = (azArg[i] && azArg[i][0]) ? strdup(azArg[i]) : 0;
35851 }else if( zName ){
35852 dotCmdError(p, i, "unknown option", 0);
35853 return 1;
35854 }else{
35855 zName = azArg[i];
@@ -35329,11 +36002,148 @@
36002 p->mElse &= ~(1<<p->nIfLevel);
36003 p->mIfHasBeenTrue &= ~(1<<p->nIfLevel);
36004 return 0;
36005 }
36006
36007 /*
36008 ** DOT-COMMAND: .eqp
36009 ** USAGE: .eqp EQPMODE [>OUTPUTFILE]
36010 **
36011 ** The .eqp command enables or disables the automatic display of EXPLAIN
36012 ** output for each SQL statement evaluated. The required EQPMODE argument
36013 ** may be one of the following:
36014 **
36015 ** full Show both EXPLAIN QUERY PLAN and EXPLAIN output.
36016 **
36017 ** off Disable all explain output.
36018 **
36019 ** on Show EXPLAIN QUERY PLAN output only.
36020 **
36021 ** trace Like "full" but also enable VDBE tracing using
36022 ** PRAGMA vdbe_trace=ON. This option only works if the
36023 ** CLI is compiled with -DSQLITE_DEBUG. The trace output
36024 ** always appears on stdout and is not redirected to a file.
36025 **
36026 ** trigger Like "full" but also show EXPLAIN output for trigger
36027 ** subprograms.
36028 **
36029 ** The EQPMODE maybe be optionally followed by a filename. If a file is
36030 ** specified, with or without a single leading ">", then the file is
36031 ** deleted and all subsequent explain output is appended to that file.
36032 ** If the filename begins with ">>" then the content of the file is retained
36033 ** and all output is appended. If not redirection argument is provided,
36034 ** output redirection is cancelled. The ability to redirect is not available
36035 ** for --safe mode.
36036 */
36037 static int dotCmdEqp(ShellState *p){
36038 int nArg = p->dot.nArg; /* Number of arguments */
36039 char **azArg = p->dot.azArg; /* Argument list */
36040 if( nArg==2 || nArg==3 ){
36041 int isTrace = 0;
36042 if( p->db ) sqlite3_db_config(p->db, SQLITE_DBCONFIG_VDBE_TRACE, 0,
36043 (int*)0);
36044 if( cli_strcmp(azArg[1],"full")==0 ){
36045 p->mode.autoEQP = AUTOEQP_full;
36046 }else if( cli_strcmp(azArg[1],"trigger")==0 ){
36047 p->mode.autoEQP = AUTOEQP_trigger;
36048 }else if( cli_strcmp(azArg[1],"trace")==0 ){
36049 #ifdef SQLITE_DEBUG
36050 p->mode.autoEQP = AUTOEQP_full;
36051 if( p->db==0 ){
36052 open_db(p, 0);
36053 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1",0,0,0);
36054 }
36055 sqlite3_db_config(p->db, SQLITE_DBCONFIG_VDBE_TRACE, 1, (int*)0);
36056 isTrace = 1;
36057 #else
36058 eputz("\".eqp trace\" is only available in debug builds\n");
36059 return 1;
36060 #endif
36061 }else{
36062 p->mode.autoEQP = (u8)booleanValue(azArg[1]);
36063 }
36064 free(p->zEqpFile);
36065 if( nArg==3 ){
36066 const char *zOut = azArg[2];
36067 int bAppend = 0;
36068 failIfSafeMode(p, "cannot redirect .eqp output in safe mode");
36069 if( zOut[0]=='>' ) zOut++;
36070 if( zOut[0]=='>' ){ bAppend = 1; zOut++; }
36071 p->zEqpFile = strdup(zOut);
36072 if( !bAppend ){
36073 (void)shellDeleteFile(p->zEqpFile, 0);
36074 }
36075 if( isTrace ){
36076 cli_printf(p->out, "WARNING: trace output will not be redirected\n");
36077 }
36078 }else{
36079 p->zEqpFile = 0;
36080 }
36081 }else{
36082 eputz("Usage: .eqp off|on|trace|trigger|full [OUTPUTFILE]\n");
36083 return 1;
36084 }
36085 return 0;
36086 }
36087
36088
36089 /*
36090 ** DOT-COMMAND: .safe
36091 ** USAGE: .safe
36092 **
36093 ** This command puts the CLI into "safe mode". This command cannot be
36094 ** undone. The only way to restore full capabilities is to exit and
36095 ** restart the CLI.
36096 **
36097 ** Safe mode restricts SQL statements and dot-commands so that no
36098 ** changes may be made to the filesystem other than writing to database
36099 ** files that are already open.
36100 **
36101 ** * The .open command is blocked unless the database is ":memory:"
36102 ** or the --hexdb option is used.
36103 ** * The ATTACH command of SQL may not be used
36104 ** * SQL functions with side effects (ex: writefile()) are blocked.
36105 ** * The ".shell" and ".system" dot-commands are blocked.
36106 ** * Dot-command like ".archive", ".backup", ".load", ".log", ".save"
36107 ** are blocked.
36108 ** * Other commands with deleterious side effects are blocked.
36109 **
36110 ** Unsafe actions might be simply blocked, or the CLI might issue an error
36111 ** and exit immediately.
36112 **
36113 ** Safe mode does not prevent harm to database files that are already open.
36114 ** An attacker can still delete content and even use commands like
36115 ** "PRAGMA writable_schema=ON" to corrupt a database file that is already
36116 ** open. Safe mode only blocks access to other previously unopened files.
36117 **
36118 ** CAUTION: If third-party extensions with system side effects have been
36119 ** loaded prior to the .safe command, the CLI has no knowledge of those
36120 ** extensions and does not know to block them. Unsafe actions might still
36121 ** be possible using those third-party extension.
36122 */
36123 static int dotCmdSafe(ShellState *p){
36124 int i;
36125 p->bSafeMode = 1;
36126 p->bSafeModePersist = 1;
36127 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
36128 if( p->db ) sqlite3_enable_load_extension(p->db, 0);
36129 #endif
36130 for(i=0; i<ArraySize(p->aAuxDb); i++){
36131 sqlite3 *db = p->aAuxDb[i].db;
36132 if( db==0 ) continue;
36133 #ifndef SQLITE_OMIT_VIRTUALTABLE
36134 sqlite3_create_module(db, "fsdir", 0, 0);
36135 sqlite3_create_module(db, "zipfile", 0, 0);
36136 #endif
36137 sqlite3_create_function(db, "writefile", -1, 0, 0, 0, 0, 0);
36138 sqlite3_create_function(db, "zipfile", -1, 0, 0, 0, 0, 0);
36139 sqlite3_create_function(db, "tryeval", -1, 0, 0, 0, 0, 0);
36140 sqlite3_create_function(db, "expire", 1, 0, 0, 0, 0, 0);
36141 sqlite3_create_function(db, "expire", 2, 0, 0, 0, 0, 0);
36142 }
36143 return 0;
36144 }
36145
36146 /*
36147 ** Enlarge the space allocated in p->dot so that it can hold more
36148 ** than nArg parsed command-line arguments.
36149 */
@@ -35344,11 +36154,10 @@
36154 p->dot.aiOfst = realloc(p->dot.aiOfst,p->dot.nAlloc*sizeof(int));
36155 shell_check_oom(p->dot.aiOfst);
36156 p->dot.abQuot = realloc(p->dot.abQuot,p->dot.nAlloc);
36157 shell_check_oom(p->dot.abQuot);
36158 }
 
36159
36160 /*
36161 ** Parse input line zLine up into individual arguments. Retain the
36162 ** parse in the p->dot substructure.
36163 */
@@ -35768,21 +36577,25 @@
36577 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
36578 { "reverse_scanorder", SQLITE_DBCONFIG_REVERSE_SCANORDER },
36579 { "stmt_scanstatus", SQLITE_DBCONFIG_STMT_SCANSTATUS },
36580 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
36581 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA },
36582 #ifdef SQLITE_DEBUG
36583 { "vdbe_trace", SQLITE_DBCONFIG_VDBE_TRACE },
36584 #endif
36585 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
36586 };
36587 int ii, v;
36588 open_db(p, 0);
36589 for(ii=0; ii<ArraySize(aDbConfig); ii++){
36590 if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
36591 if( nArg>=3 ){
36592 if( aDbConfig[ii].op==SQLITE_DBCONFIG_FP_DIGITS ){
36593 sqlite3_db_config(p->db, aDbConfig[ii].op, atoi(azArg[2]), (int*)0);
36594 }else{
36595 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]),
36596 (int*)0);
36597 }
36598 }
36599 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
36600 if( aDbConfig[ii].op==SQLITE_DBCONFIG_FP_DIGITS ){
36601 cli_printf(p->out, "%19s %d\n", aDbConfig[ii].zName, v);
@@ -35804,10 +36617,11 @@
36617 }else
36618 #endif /* SQLITE_SHELL_HAVE_RECOVER */
36619
36620 if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbtotxt", n)==0 ){
36621 open_db(p, 0);
36622 sqlite3_exec(p->db, "PRAGMA page_count", 0, 0, 0);
36623 rc = shell_dbtotxt_command(p, nArg, azArg);
36624 }else
36625
36626 if( c=='d' && n==8 && cli_strncmp(azArg[0], "diskused", n)==0 ){
36627 const char *zSchema = 0;
@@ -35980,34 +36794,11 @@
36794 if( c=='e' && n==5 && cli_strcmp(azArg[0],"endif")==0 ){
36795 rc = dotCmdEndif(p);
36796 }else
36797
36798 if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
36799 rc = dotCmdEqp(p);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36800 }else
36801
36802 #ifndef SQLITE_SHELL_FIDDLE
36803 if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
36804 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) cli_exit(rc);
@@ -36191,14 +36982,15 @@
36982
36983 if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
36984 ShellState data;
36985 int doStats = 0;
36986 int hasStat[5];
36987 int bIndent = 0;
36988 char *zSql;
36989 if( nArg==2 && optionMatch(azArg[1], "indent") ){
36990 nArg = 1;
36991 bIndent = 1;
36992 }
36993 if( nArg!=1 ){
36994 eputz("Usage: .fullschema ?--indent?\n");
36995 rc = 1;
36996 goto meta_command_exit;
@@ -36209,11 +37001,11 @@
37001 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
37002 " FROM sqlite_schema UNION ALL"
37003 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
37004 "WHERE type!='meta' AND sql NOTNULL"
37005 " AND name NOT LIKE 'sqlite__%%' ESCAPE '_' "
37006 "ORDER BY x", bIndent);
37007 memcpy(&data, p, sizeof(data));
37008 data.mode.spec.bTitles = QRF_No;
37009 data.mode.eMode = MODE_List;
37010 data.mode.spec.eText = QRF_TEXT_Plain;
37011 data.mode.spec.nCharLimit = 0;
@@ -37149,10 +37941,14 @@
37941 rc = 1;
37942 }
37943 close_db(pSrc);
37944 }else
37945 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
37946
37947 if( c=='s' && cli_strcmp(azArg[0], "safe")==0 ){
37948 rc = dotCmdSafe(p);
37949 }else
37950
37951 if( c=='s' &&
37952 (cli_strncmp(azArg[0], "scanstats", n)==0 ||
37953 cli_strncmp(azArg[0], "scanstatus", n)==0)
37954 ){
@@ -38109,17 +38905,17 @@
38905 ** -LABEL Disable the named optimization
38906 **
38907 ** INTEGER Mask of optimizations to disable
38908 */
38909 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
38910 u64 curOpt; /* Current opt-disabled mask */
38911 u64 newOpt; /* New opt-disabled mask */
38912 u64 m; /* A working mask value */
 
38913 int ii, jj; /* Loop counters */
38914 int nOff; /* Number of disabled optimizations */
38915 const char *zName; /* Name of an optimization */
38916 int bQuiet = 0; /* Suppress output echo */
38917
38918 sqlite3_test_control(SQLITE_TESTCTRL_GETOPT, p->db, &curOpt);
38919 newOpt = curOpt;
38920 for(ii=2; ii<nArg; ii++){
38921 const char *z = azArg[ii];
@@ -38133,11 +38929,16 @@
38929 zLabel = z;
38930 }else{
38931 newOpt = (unsigned int)strtol(z,0,0);
38932 }
38933 if( useLabel ){
38934 if( sqlite3_optimization_mask(zLabel,&m)==SQLITE_NOTFOUND ){
38935 if( strcmp(zLabel,"q")==0 ){
38936 /* Special -q option suppresses output */
38937 bQuiet = 1;
38938 continue;
38939 }
38940 cli_printf(stderr,
38941 "Error: no such optimization: \"%s\"\n", zLabel);
38942 cli_puts("Should be one of: All", stderr);
38943 for(jj=0; jj<32; jj++){
38944 zName = sqlite3_optimization_name(1ull<<jj);
@@ -38145,11 +38946,10 @@
38946 }
38947 cli_puts("\n", stderr);
38948 rc = 1;
38949 goto meta_command_exit;
38950 }
 
38951 if( useLabel=='+' ){
38952 newOpt &= ~m;
38953 }else{
38954 newOpt |= m;
38955 }
@@ -38156,33 +38956,35 @@
38956 }
38957 }
38958 if( curOpt!=newOpt ){
38959 sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,p->db,newOpt);
38960 }
38961 if( !bQuiet ){
38962 for(ii=nOff=0, m=1; ii<64; ii++, m <<= 1){
38963 if( m & newOpt ) nOff++;
38964 }
38965 if( nOff<12 ){
38966 cli_puts("+All", p->out);
38967 for(ii=0, m=1; ii<64; ii++, m <<= 1){
38968 if( (newOpt & m)!=0
38969 && (zName = sqlite3_optimization_name(m))!=0
38970 ){
38971 cli_printf(p->out, " -%s", zName);
38972 }
38973 }
38974 }else{
38975 cli_puts("-All", p->out);
38976 for(ii=0, m=1; ii<64; ii++, m <<= 1){
38977 if( (newOpt & m)==0
38978 && (zName = sqlite3_optimization_name(m))!=0
38979 ){
38980 cli_printf(p->out, " +%s", zName);
38981 }
38982 }
38983 }
38984 cli_puts("\n", p->out);
38985 }
38986 rc2 = isOk = 3;
38987 break;
38988 }
38989
38990 /* sqlite3_test_control(int, db, int) */
@@ -38758,20 +39560,20 @@
39560 }else{
39561 p->eRestoreState = 7;
39562 }
39563 break;
39564 };
39565
39566 case 1: {
39567 int bIsDump = 0;
39568 const char *zExpect = "BEGIN TRANSACTION;";
39569 assert( strlen(zExpect)==18 );
39570 if( memcmp(zSql, zExpect, 19)==0 ){
39571 /* Now check if the database is empty. */
39572 const char *zQuery = "SELECT 1 FROM sqlite_schema LIMIT 1";
39573 sqlite3_stmt *pStmt = 0;
39574
39575 bIsDump = 1;
39576 shellPrepare(p->db, &rc, zQuery, &pStmt);
39577 if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
39578 bIsDump = 0;
39579 }
@@ -38780,26 +39582,26 @@
39582 if( bIsDump && rc==SQLITE_OK ){
39583 int bDefense = 0;
39584 int bDqsDdl = 0;
39585 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense);
39586 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl);
39587 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, (int*)0);
39588 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, (int*)0);
39589 p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0);
39590 }else{
39591 p->eRestoreState = 7;
39592 }
39593 break;
39594 }
39595
39596 default: {
39597 if( sqlite3_get_autocommit(p->db) ){
39598 if( (p->eRestoreState & 2) ){
39599 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, (int*)0);
39600 }
39601 if( (p->eRestoreState & 4) ){
39602 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, (int*)0);
39603 }
39604 p->eRestoreState = 7;
39605 }
39606 break;
39607 }
@@ -39402,10 +40204,11 @@
40204 " -nullvalue TEXT set text string for NULL values. Default ''\n"
40205 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
40206 " -pcachetrace trace all page cache operations\n"
40207 " -quote set '.mode quote'\n"
40208 " -readonly open the database read-only\n"
40209 " -runtests SCRIPT... Run multiple *.sql test script in subprocesses\n"
40210 " -safe enable safe-mode\n"
40211 " -screenwidth N use N as the default screenwidth \n"
40212 " -separator SEP set output column separator. Default: '|'\n"
40213 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
40214 " -sorterref SIZE sorter references threshold size\n"
@@ -39442,10 +40245,131 @@
40245 sputz(stdout, "WARNING: attempt to configure SQLite after"
40246 " initialization.\n");
40247 }
40248 }
40249
40250 /*
40251 ** Run a copy of this program as a subprocess
40252 */
40253 static void runShellSubprocess(
40254 const char *zProg,
40255 const char *zScript,
40256 int *pNErr,
40257 int *pNTest
40258 ){
40259 FILE *in;
40260 char *zCmd;
40261 const char *zTail;
40262 char zIn[1000];
40263 zTail = strrchr(zScript, '/');
40264 if( zTail ){
40265 zTail++;
40266 }else{
40267 zTail = zScript;
40268 }
40269 #ifdef _WIN32
40270 {
40271 const char *zBackslash = strrchr(zTail, '\\');
40272 if( zBackslash ) zTail = zBackslash+1;
40273 }
40274 #endif
40275 sqlite3_fprintf(stdout, "%-24s ", zTail);
40276 fflush(stdout);
40277 if( !isScriptFile(zScript,0) ){
40278 sqlite3_fprintf(stdout, "not an SQL script\n");
40279 (*pNErr)++;
40280 return;
40281 }
40282 #ifdef _WIN32
40283 /* The command runs as "cmd.exe /c COMMAND". If COMMAND starts with a
40284 ** double-quote and contains more than two of them, then cmd.exe removes
40285 ** the first and the last double-quote before doing anything else.
40286 ** The extra pair of quotes around the whole command is there to be
40287 ** removed, so that the quotes on the individual arguments survive. */
40288 zCmd = sqlite3_mprintf("\"\"%s\" \"%s\" 2>NUL\"", zProg, zScript);
40289 #else
40290 zCmd = sqlite3_mprintf("\"%s\" \"%s\" 2>/dev/null", zProg, zScript);
40291 #endif
40292 in = sqlite3_popen(zCmd, "r");
40293 if( in==0 ){
40294 sqlite3_fprintf(stdout, "cannot start subprocess\n");
40295 sqlite3_free(zCmd);
40296 (*pNErr)++;
40297 return;
40298 }
40299 while( sqlite3_fgets(zIn, sizeof(zIn), in) ){
40300 int n = 0;
40301 int m = 0;
40302 char *zRunWith;
40303 zRunWith = strstr(zIn, " run with ");
40304 if( zRunWith==0 ) continue;
40305 if( zIn[0]<'0' || zIn[0]>'9' ) continue;
40306 if( zRunWith[10]<'0' || zRunWith[10]>'9' ) continue;
40307 n = atoi(zIn);
40308 m = atoi(&zRunWith[10]);
40309 if( m==0 ){
40310 sqlite3_fprintf(stdout, "tests %5d\n", n);
40311 }else{
40312 sqlite3_fprintf(stdout, "tests %5d errors %5d\n", n, m);
40313 }
40314 (*pNErr) += m;
40315 (*pNTest) += n;
40316 pclose(in);
40317 sqlite3_free(zCmd);
40318 return;
40319 }
40320 pclose(in);
40321 sqlite3_free(zCmd);
40322 sqlite3_fprintf(stdout, "did not complete\n");
40323 fflush(stdout);
40324 (*pNErr)++;
40325 }
40326
40327 #ifdef _WIN32
40328 /*
40329 ** Run a subprocess for each script file that matches the wildcard zPattern.
40330 ** CMD.EXE does not expand wildcards, so the application must do it.
40331 ** Only the final path component of zPattern may contain wildcards.
40332 ** Return the number of scripts run.
40333 */
40334 static int runShellSubprocessGlob(
40335 const char *zProg,
40336 const char *zPattern,
40337 int *pNErr,
40338 int *pNTest
40339 ){
40340 WIN32_FIND_DATAW sFind;
40341 HANDLE hFind;
40342 LPWSTR zW = sqlite3_win32_utf8_to_unicode(zPattern);
40343 int nDir;
40344 int nRun = 0;
40345 shell_check_oom(zW);
40346 for(nDir=(int)strlen(zPattern); nDir>0; nDir--){
40347 char c = zPattern[nDir-1];
40348 if( c=='/' || c=='\\' || c==':' ) break;
40349 }
40350 hFind = FindFirstFileW(zW, &sFind);
40351 sqlite3_free(zW);
40352 if( hFind==INVALID_HANDLE_VALUE ) return 0;
40353 do{
40354 char *zName, *zPath;
40355 if( sFind.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) continue;
40356 zName = sqlite3_win32_unicode_to_utf8(sFind.cFileName);
40357 zPath = sqlite3_mprintf("%.*s%s", nDir, zPattern, zName);
40358 shell_check_oom(zPath);
40359 if( isScriptFile(zPath,0) ){ /* Also rejects 8.3-name false matches */
40360 runShellSubprocess(zProg, zPath, pNErr, pNTest);
40361 nRun++;
40362 }
40363 sqlite3_free(zPath);
40364 sqlite3_free(zName);
40365 }while( FindNextFileW(hFind, &sFind) );
40366 FindClose(hFind);
40367 return nRun;
40368 }
40369 #endif
40370
40371 #if HAVE_EDITLINE
40372 /*
40373 ** https://sqlite.org/forum/forumpost/aad7a634916ff050:
40374 **
40375 ** Calling setlocale(LC_...,"") is required to get libedit to accept
@@ -39462,11 +40386,11 @@
40386 */
40387 static void main_init(ShellState *p) {
40388 memset(p, 0, sizeof(*p));
40389 p->pAuxDb = &p->aAuxDb[0];
40390 p->shellFlgs = SHFLG_Lookaside;
40391 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, (void*)p);
40392 #if !defined(SQLITE_SHELL_FIDDLE)
40393 verify_uninitialized();
40394 #endif
40395 sqlite3_config(SQLITE_CONFIG_URI, 1);
40396 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
@@ -39622,10 +40546,11 @@
40546 int readStdin = 1;
40547 int noInit = 0; /* Do not read ~/.sqliterc if true */
40548 int nCmd = 0;
40549 int nOptsEnd = argc;
40550 int bEnableVfstrace = 0;
40551 int bTestMode = 0; /* --runtests option */
40552 char **azCmd = 0;
40553 int *aiCmd = 0;
40554 const char *zVfs = 0; /* Value of -vfs command-line option */
40555 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
40556
@@ -39716,11 +40641,15 @@
40641 #endif
40642 for(i=1; i<argc; i++){
40643 char *z;
40644 z = argv[i];
40645 if( z[0]!='-' || i>nOptsEnd ){
40646 if( data.aAuxDb->zDbFilename==0
40647 && !bTestMode
40648 && (z[0]!='.' || !(z[1]>='a' && z[1]<='z'))
40649 && !isScriptFile(z,1)
40650 ){
40651 data.aAuxDb->zDbFilename = z;
40652 }else{
40653 /* Excess arguments are interpreted as SQL (or dot-commands) and
40654 ** mean that nothing is read from stdin */
40655 readStdin = 0;
@@ -39887,10 +40816,12 @@
40816 }else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
40817 /* skip over the argument */
40818 i++;
40819 }else if( cli_strcmp(z,"-cmdline-edit")==0 ){
40820 shellCmdLineEdit = booleanValue(cmdline_option_value(argc,argv,++i));
40821 }else if( cli_strcmp(z,"-runtests")==0 ){
40822 bTestMode = 1;
40823 }else if( cli_strcmp(z,"-test-argv")==0 ){
40824 /* Undocumented test option. Print the values in argv[] and exit.
40825 ** Use this to verify that any translation of the argv[], for example
40826 ** on Windows that receives wargv[] from the OS and must convert
40827 ** to UTF8 prior to calling this routine. */
@@ -39901,19 +40832,48 @@
40832 return 0;
40833 }else if( cli_strcmp(z,"-test-parse")==0 ){
40834 /* Undocumented test option. Read input normally and process all
40835 ** dot-commands. But do not process any SQL. Instead, whenever input
40836 ** text would have been processed as SQL, print a one-line summary of
40837 ** the input. This is used by test scripts to verify that the end-of-SQL
40838 ** parsing logic is working correctly. */
40839 data.bTestParse = 1;
40840 }
40841 }
40842 #ifndef SQLITE_SHELL_FIDDLE
40843 if( !bEnableVfstrace ) verify_uninitialized();
40844 #endif
40845
40846 #ifndef SQLITE_SHELL_FIDDLE
40847 if( bTestMode ){
40848 int nErr = 0;
40849 int nTest = 0;
40850 int nScript = 0;
40851 #ifdef _WIN32
40852 /* Child processes inherit this. Without it, a crash in a test script
40853 ** might raise a dialog box that stalls the run until it is dismissed. */
40854 SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
40855 #endif
40856 for(i=0; i<nCmd; i++){
40857 #ifdef _WIN32
40858 if( strpbrk(azCmd[i], "*?") ){
40859 int n = runShellSubprocessGlob(argv[0], azCmd[i], &nErr, &nTest);
40860 if( n>0 ){
40861 nScript += n;
40862 continue;
40863 }
40864 }
40865 #endif
40866 runShellSubprocess(argv[0], azCmd[i], &nErr, &nTest);
40867 nScript++;
40868 }
40869 sqlite3_fprintf(stdout, "%-24s tests %5d errors %5d scripts %5d\n",
40870 "TOTAL", nTest, nErr, nScript);
40871 rc = nErr>0;
40872 goto shell_main_exit;
40873 }
40874 #endif
40875
40876 #ifdef SQLITE_SHELL_INIT_PROC
40877 {
40878 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
40879 ** of a C-function that will perform initialization actions on SQLite that
@@ -40202,10 +41162,12 @@
41162 #endif
41163 }else if( cli_strcmp(z,"-safe")==0 ){
41164 data.bSafeMode = data.bSafeModePersist = 1;
41165 }else if( cli_strcmp(z,"-unsafe-testing")==0
41166 || cli_strcmp(z,"-unsafe")==0 ){
41167 /* Acted upon in first pass. */
41168 }else if( cli_strcmp(z,"-runtests")==0 ){
41169 /* Acted upon in first pass. */
41170 }else if( cli_strcmp(z,"-test-parse")==0 ){
41171 /* Acted upon in first pass. */
41172 }else{
41173 cli_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
@@ -40230,16 +41192,17 @@
41192 res = process_input(&data, azCmd[i]);
41193 fclose(data.in);
41194 }
41195 data.in = inSaved;
41196 data.lineno = savedLineno;
41197 if( res && bail_on_error ) i = nCmd;
41198 }else if( azCmd[i][0]=='.' ){
41199 char *zErrCtx = malloc( 64 );
41200 shell_check_oom(zErrCtx);
41201 sqlite3_snprintf(64,zErrCtx,"argv[%i]:",aiCmd[i]);
41202 data.zInFile = "<cmdline>";
41203 free(data.zErrPrefix);
41204 data.zErrPrefix = zErrCtx;
41205 rc = do_meta_command(azCmd[i], &data);
41206 free(data.zErrPrefix);
41207 data.zErrPrefix = 0;
41208 if( rc ){
@@ -40350,10 +41313,11 @@
41313 modeFree(&data.aSavedModes[ii].mode);
41314 free(data.aSavedModes[ii].zTag);
41315 }
41316 free(data.aSavedModes);
41317 }
41318 free(data.zEqpFile);
41319 free(data.zErrPrefix);
41320 free(data.zNonce);
41321 free(data.dot.zCopy);
41322 free(data.dot.azArg);
41323 free(data.dot.aiOfst);
@@ -40456,13 +41420,15 @@
41420 ** https://sqlite.org/forum/forumpost/0b41a25d65
41421 */
41422 cli_puts("Rolling back in-progress transaction.\n", stdout);
41423 sqlite3_exec(globalDb,"ROLLBACK", 0, 0, 0);
41424 }
41425 rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1,
41426 (int*)0);
41427 if( 0==rc ) sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
41428 sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0,
41429 (int*)0);
41430 }
41431 }
41432
41433 /*
41434 ** Uses the current database's VFS xRead to stream the db file's
41435
+2422 -953
--- 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
-** d08cabd778f7844d04f3852d93197e80c0d0 with changes in files:
21
+** ad4ee20509dc4e2803f35093b03df55cb3e3 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.55.0"
471471
#define SQLITE_VERSION_NUMBER 3055000
472
-#define SQLITE_SOURCE_ID "2026-10-24 22:25:07 d08cabd778f7844d04f3852d93197e80c0d0f4f30a589f7fd0d28577fa3fa68b"
472
+#define SQLITE_SOURCE_ID "2026-11-15 00:55:04 ad4ee20509dc4e2803f35093b03df55cb3e39c8083b0d4ad231e1432516c7841"
473473
#define SQLITE_SCM_BRANCH "trunk"
474474
#define SQLITE_SCM_TAGS ""
475
-#define SQLITE_SCM_DATETIME "2026-10-24T22:25:07.764Z"
475
+#define SQLITE_SCM_DATETIME "2026-11-15T00:55:04.503Z"
476476
477477
/*
478478
** CAPI3REF: Run-Time Library Version Numbers
479479
** KEYWORDS: sqlite3_version sqlite3_sourceid
480480
**
@@ -795,10 +795,11 @@
795795
#define SQLITE_FORMAT 24 /* Not used */
796796
#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
797797
#define SQLITE_NOTADB 26 /* File opened that is not a database file */
798798
#define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
799799
#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
800
+#define SQLITE_MOVED 29 /* Internal use only: Cursor moved */
800801
#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
801802
#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
802803
/* end-of-error-codes */
803804
804805
/*
@@ -2983,16 +2984,23 @@
29832984
** the number of significant digits that SQLite will attempt to preserve when
29842985
** converting floating point numbers (IEEE 754 "doubles") into text. The
29852986
** default value 17, as of SQLite version 3.52.0. The value was 15 in all
29862987
** prior versions.<p>
29872988
** This option takes two arguments which are an integer and a pointer
2988
-** to an integer. The first argument is a small integer, between 3 and 23, or
2989
+** to an integer. The first argument is a small integer, between 4 and 23, or
29892990
** zero. The FP_DIGITS setting is changed to that small integer, or left
29902991
** unaltered if the first argument is zero or out of range. The second argument
29912992
** is a pointer to an integer. If the pointer is not NULL, then the value of
29922993
** the FP_DIGITS setting, after possibly being modified by the first
29932994
** arguments, is written into the integer to which the second argument points.
2995
+**
2996
+** [[SQLITE_DBCONFIG_VDBE_TRACE]]
2997
+** <dt>SQLITE_DBCONFIG_VDBE_TRACE</dt>
2998
+** <dd>The SQLITE_DBCONFIG_VDBE_TRACE setting enables or disables tracing
2999
+** of the [bytecode engine]. This setting is only available when SQLite has
3000
+** be compiled with -DSQLITE_DEBUG. It is the equivalent of using
3001
+** [PRAGMA vdbe_trace].
29943002
** </dd>
29953003
**
29963004
** </dl>
29973005
**
29983006
** [[DBCONFIG arguments]] <h3>Arguments To SQLITE_DBCONFIG Options</h3>
@@ -3039,11 +3047,12 @@
30393047
#define SQLITE_DBCONFIG_REVERSE_SCANORDER 1019 /* int int* */
30403048
#define SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE 1020 /* int int* */
30413049
#define SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE 1021 /* int int* */
30423050
#define SQLITE_DBCONFIG_ENABLE_COMMENTS 1022 /* int int* */
30433051
#define SQLITE_DBCONFIG_FP_DIGITS 1023 /* int int* */
3044
-#define SQLITE_DBCONFIG_MAX 1023 /* Largest DBCONFIG */
3052
+#define SQLITE_DBCONFIG_VDBE_TRACE 1024 /* int int* */
3053
+#define SQLITE_DBCONFIG_MAX 1024 /* Largest DBCONFIG */
30453054
30463055
/*
30473056
** CAPI3REF: Enable Or Disable Extended Result Codes
30483057
** METHOD: sqlite3
30493058
**
@@ -5320,11 +5329,11 @@
53205329
** or indicates the lifetime of the object referenced by the third parameter.
53215330
** These three options exist:
53225331
** ^ (1) A destructor to dispose of the BLOB or string after SQLite has finished
53235332
** with it may be passed. ^It is called to dispose of the BLOB or string even
53245333
** if the call to the bind API fails, except the destructor is not called if
5325
-** the third parameter is a NULL pointer or the fourth parameter is negative.
5334
+** the third parameter is a NULL pointer or the fifth parameter is negative.
53265335
** ^ (2) The special constant, [SQLITE_STATIC], may be passed to indicate that
53275336
** the application remains responsible for disposing of the object. ^In this
53285337
** case, the object and the provided pointer to it must remain valid until
53295338
** either the prepared statement is finalized or the same SQL parameter is
53305339
** bound to something else, whichever occurs sooner.
@@ -9112,11 +9121,12 @@
91129121
#define SQLITE_TESTCTRL_TRACEFLAGS 31
91139122
#define SQLITE_TESTCTRL_TUNE 32
91149123
#define SQLITE_TESTCTRL_LOGEST 33
91159124
#define SQLITE_TESTCTRL_USELONGDOUBLE 34 /* NOT USED */
91169125
#define SQLITE_TESTCTRL_ATOF 34
9117
-#define SQLITE_TESTCTRL_LAST 34 /* Largest TESTCTRL */
9126
+#define SQLITE_TESTCTRL_EXPIRE_STMTS 35
9127
+#define SQLITE_TESTCTRL_LAST 35 /* Largest TESTCTRL */
91189128
91199129
/*
91209130
** CAPI3REF: SQL Keyword Checking
91219131
**
91229132
** These routines provide access to the set of SQL language keywords
@@ -18041,64 +18051,66 @@
1804118051
#define OP_ResetCount 132
1804218052
#define OP_SorterCompare 133 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
1804318053
#define OP_SorterData 134 /* synopsis: r[P2]=data */
1804418054
#define OP_RowData 135 /* synopsis: r[P2]=data */
1804518055
#define OP_Rowid 136 /* synopsis: r[P2]=PX rowid of P1 */
18046
-#define OP_NullRow 137
18047
-#define OP_SeekEnd 138
18048
-#define OP_IdxInsert 139 /* synopsis: key=r[P2] */
18049
-#define OP_SorterInsert 140 /* synopsis: key=r[P2] */
18050
-#define OP_IdxDelete 141 /* synopsis: key=r[P2@P5] */
18051
-#define OP_DeferredSeek 142 /* synopsis: Move P3 to P1.rowid if needed */
18052
-#define OP_IdxRowid 143 /* synopsis: r[P2]=rowid */
18053
-#define OP_FinishSeek 144
18054
-#define OP_Destroy 145
18055
-#define OP_Clear 146
18056
-#define OP_ResetSorter 147
18057
-#define OP_CreateBtree 148 /* synopsis: r[P2]=root iDb=P1 flags=P3 */
18058
-#define OP_SqlExec 149
18059
-#define OP_ParseSchema 150
18060
-#define OP_LoadAnalysis 151
18061
-#define OP_DropTable 152
18062
-#define OP_DropIndex 153
18056
+#define OP_Stale 137
18057
+#define OP_NullRow 138
18058
+#define OP_SeekEnd 139
18059
+#define OP_IdxInsert 140 /* synopsis: key=r[P2] */
18060
+#define OP_SorterInsert 141 /* synopsis: key=r[P2] */
18061
+#define OP_IdxDelete 142 /* synopsis: key=r[P2@P5] */
18062
+#define OP_DeferredSeek 143 /* synopsis: Move P3 to P1.rowid if needed */
18063
+#define OP_IdxRowid 144 /* synopsis: r[P2]=rowid */
18064
+#define OP_FinishSeek 145
18065
+#define OP_Destroy 146
18066
+#define OP_DbLock 147
18067
+#define OP_Clear 148
18068
+#define OP_ResetSorter 149
18069
+#define OP_CreateBtree 150 /* synopsis: r[P2]=root iDb=P1 flags=P3 */
18070
+#define OP_SqlExec 151
18071
+#define OP_ParseSchema 152
18072
+#define OP_LoadAnalysis 153
1806318073
#define OP_Real 154 /* same as TK_FLOAT, synopsis: r[P2]=PDBL13 */
18064
-#define OP_DropTrigger 155
18065
-#define OP_IntegrityCk 156
18066
-#define OP_RowSetAdd 157 /* synopsis: rowset(P1)=r[P2] */
18067
-#define OP_Param 158
18068
-#define OP_FkCounter 159 /* synopsis: fkctr[P1]+=P2 */
18069
-#define OP_MemMax 160 /* synopsis: r[P1]=max(r[P1],r[P2]) */
18070
-#define OP_OffsetLimit 161 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
18071
-#define OP_AggInverse 162 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */
18072
-#define OP_AggStep 163 /* synopsis: accum=r[P3] step(r[P2@P5]) */
18073
-#define OP_AggStep1 164 /* synopsis: accum=r[P3] step(r[P2@P5]) */
18074
-#define OP_AggValue 165 /* synopsis: r[P3]=value N=P2 */
18075
-#define OP_AggFinal 166 /* synopsis: accum=r[P1] N=P2 */
18076
-#define OP_Expire 167
18077
-#define OP_CursorLock 168
18078
-#define OP_CursorUnlock 169
18079
-#define OP_TableLock 170 /* synopsis: iDb=P1 root=P2 write=P3 */
18080
-#define OP_VBegin 171
18081
-#define OP_VCreate 172
18082
-#define OP_VDestroy 173
18083
-#define OP_VOpen 174
18084
-#define OP_VCheck 175
18085
-#define OP_VInitIn 176 /* synopsis: r[P2]=ValueList(P1,P3) */
18086
-#define OP_VColumn 177 /* synopsis: r[P3]=vcolumn(P2) */
18087
-#define OP_VRename 178
18088
-#define OP_Pagecount 179
18089
-#define OP_MaxPgcnt 180
18090
-#define OP_ClrSubtype 181 /* synopsis: r[P1].subtype = 0 */
18091
-#define OP_GetSubtype 182 /* synopsis: r[P2] = r[P1].subtype */
18092
-#define OP_SetSubtype 183 /* synopsis: r[P2].subtype = r[P1] */
18093
-#define OP_FilterAdd 184 /* synopsis: filter(P1) += key(P3@P4) */
18094
-#define OP_Trace 185
18095
-#define OP_CursorHint 186
18096
-#define OP_ReleaseReg 187 /* synopsis: release r[P1@P2] mask P3 */
18097
-#define OP_Noop 188
18098
-#define OP_Explain 189
18099
-#define OP_Abortable 190
18074
+#define OP_DropTable 155
18075
+#define OP_DropIndex 156
18076
+#define OP_DropTrigger 157
18077
+#define OP_IntegrityCk 158
18078
+#define OP_RowSetAdd 159 /* synopsis: rowset(P1)=r[P2] */
18079
+#define OP_Param 160
18080
+#define OP_FkCounter 161 /* synopsis: fkctr[P1]+=P2 */
18081
+#define OP_MemMax 162 /* synopsis: r[P1]=max(r[P1],r[P2]) */
18082
+#define OP_OffsetLimit 163 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
18083
+#define OP_AggInverse 164 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */
18084
+#define OP_AggStep 165 /* synopsis: accum=r[P3] step(r[P2@P5]) */
18085
+#define OP_AggStep1 166 /* synopsis: accum=r[P3] step(r[P2@P5]) */
18086
+#define OP_AggValue 167 /* synopsis: r[P3]=value N=P2 */
18087
+#define OP_AggFinal 168 /* synopsis: accum=r[P1] N=P2 */
18088
+#define OP_Expire 169
18089
+#define OP_CursorLock 170
18090
+#define OP_CursorUnlock 171
18091
+#define OP_TableLock 172 /* synopsis: iDb=P1 root=P2 write=P3 */
18092
+#define OP_VBegin 173
18093
+#define OP_VCreate 174
18094
+#define OP_VDestroy 175
18095
+#define OP_VOpen 176
18096
+#define OP_VCheck 177
18097
+#define OP_VInitIn 178 /* synopsis: r[P2]=ValueList(P1,P3) */
18098
+#define OP_VColumn 179 /* synopsis: r[P3]=vcolumn(P2) */
18099
+#define OP_VRename 180
18100
+#define OP_Pagecount 181
18101
+#define OP_MaxPgcnt 182
18102
+#define OP_ClrSubtype 183 /* synopsis: r[P1].subtype = 0 */
18103
+#define OP_GetSubtype 184 /* synopsis: r[P2] = r[P1].subtype */
18104
+#define OP_SetSubtype 185 /* synopsis: r[P2].subtype = r[P1] */
18105
+#define OP_FilterAdd 186 /* synopsis: filter(P1) += key(P3@P4) */
18106
+#define OP_Trace 187
18107
+#define OP_CursorHint 188
18108
+#define OP_ReleaseReg 189 /* synopsis: release r[P1@P2] mask P3 */
18109
+#define OP_Noop 190
18110
+#define OP_Explain 191
18111
+#define OP_Abortable 192
1810018112
1810118113
/* Properties such as "out2" or "jump" that are specified in
1810218114
** comments following the "case" for each opcode in the vdbe.c
1810318115
** are encoded into bitvectors as follows:
1810418116
*/
@@ -18126,17 +18138,18 @@
1812618138
/* 96 */ 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x26,\
1812718139
/* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,\
1812818140
/* 112 */ 0x26, 0x40, 0x00, 0x12, 0x40, 0x40, 0x10, 0x40,\
1812918141
/* 120 */ 0x00, 0x00, 0x00, 0x40, 0x00, 0x40, 0x40, 0x10,\
1813018142
/* 128 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00,\
18131
-/* 136 */ 0x50, 0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50,\
18132
-/* 144 */ 0x40, 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,\
18133
-/* 152 */ 0x00, 0x00, 0x10, 0x00, 0x00, 0x06, 0x10, 0x00,\
18134
-/* 160 */ 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
18135
-/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10,\
18136
-/* 176 */ 0x50, 0x40, 0x00, 0x10, 0x10, 0x02, 0x12, 0x12,\
18137
-/* 184 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}
18143
+/* 136 */ 0x50, 0x00, 0x00, 0x40, 0x04, 0x04, 0x00, 0x40,\
18144
+/* 144 */ 0x50, 0x40, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00,\
18145
+/* 152 */ 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x06,\
18146
+/* 160 */ 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00,\
18147
+/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
18148
+/* 176 */ 0x40, 0x10, 0x50, 0x40, 0x00, 0x10, 0x10, 0x02,\
18149
+/* 184 */ 0x12, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
18150
+/* 192 */ 0x00,}
1813818151
1813918152
/* The resolve3P2Values() routine is able to run faster if it knows
1814018153
** the value of the largest JUMP opcode. The smaller the maximum
1814118154
** JUMP opcode the better, so the mkopcodeh.tcl script that
1814218155
** generated this include file strives to group all JUMP opcodes
@@ -18930,14 +18943,15 @@
1893018943
u8 mTrace; /* zero or more SQLITE_TRACE flags */
1893118944
u8 noSharedCache; /* True if no shared-cache backends */
1893218945
u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
1893318946
u8 eOpenState; /* Current condition of the connection */
1893418947
u8 nFpDigit; /* Significant digits to keep on double->text */
18948
+ u8 bPendingSchemaReset; /* 1 or more schema resets pending */
1893518949
int nextPagesize; /* Pagesize after VACUUM if >0 */
1893618950
i64 nChange; /* Value returned by sqlite3_changes() */
1893718951
i64 nTotalChange; /* Value returned by sqlite3_total_changes() */
18938
- u32 dbOptFlags; /* Flags to enable/disable optimizations */
18952
+ u64 dbOptFlags; /* Flags to enable/disable optimizations */
1893918953
int aLimit[SQLITE_N_LIMIT]; /* Limits */
1894018954
int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
1894118955
struct sqlite3InitInfo { /* Information used during initialization */
1894218956
Pgno newTnum; /* Rootpage of table being initialized */
1894318957
u8 iDb; /* Which db file is being initialized */
@@ -19161,11 +19175,11 @@
1916119175
#define SQLITE_PropagateConst 16 /* The constant propagation opt */
1916219176
#define SQLITE_MinMaxOpt 17 /* The min/max optimization */
1916319177
#define SQLITE_SeekScan 18 /* The OP_SeekScan optimization */
1916419178
#define SQLITE_OmitOrderBy 19 /* Omit pointless ORDER BY */
1916519179
#define SQLITE_BloomFilter 20 /* Use a Bloom filters */
19166
- /* 21 -- Available for reuse */
19180
+#define SQLITE_DevTest 21 /* Temporary development testing use */
1916719181
#define SQLITE_BalancedMerge 22 /* Balance multi-way merges */
1916819182
#define SQLITE_ReleaseReg 23 /* Use OP_ReleaseReg for testing */
1916919183
#define SQLITE_FlttnUnionAll 24 /* Disable the UNION ALL flattener */
1917019184
#define SQLITE_IndexedExpr 25 /* Pull exprs from index when able */
1917119185
#define SQLITE_Coroutines 26 /* Co-routines for subqueries */
@@ -19173,16 +19187,17 @@
1917319187
#define SQLITE_OnePass 28 /* Single-pass DELETE and UPDATE */
1917419188
#define SQLITE_OrderBySubq 29 /* ORDER BY in subquery helps outer */
1917519189
#define SQLITE_StarQuery 30 /* Heurists for star queries */
1917619190
#define SQLITE_ExistsToJoin 31 /* The EXISTS-to-JOIN optimization */
1917719191
#define SQLITE_UnionLimit 32 /* Optimizations for UNION + LIMIT */
19192
+#define SQLITE_HavingToWhere 33 /* HAVING-to-WHERE optimization */
1917819193
1917919194
/*
1918019195
** Macros for testing whether or not optimizations are enabled or disabled.
1918119196
*/
19182
-#define OptimizationDisabled(D,M) (((D)->dbOptFlags&(1ul<<((M)-1)))!=0)
19183
-#define OptimizationEnabled(D,M) (((D)->dbOptFlags&(1ul<<((M)-1)))==0)
19197
+#define OptimizationDisabled(D,M) (((D)->dbOptFlags&(1ull<<((M)-1)))!=0)
19198
+#define OptimizationEnabled(D,M) (((D)->dbOptFlags&(1ull<<((M)-1)))==0)
1918419199
1918519200
/*
1918619201
** Return true if it OK to factor constant expressions into the initialization
1918719202
** code. The argument is a Parse object for the code generator.
1918819203
*/
@@ -20486,10 +20501,11 @@
2048620501
unsigned reusable :1; /* Constant expression is reusable */
2048720502
unsigned bSorterRef :1; /* Defer evaluation until after sorting */
2048820503
unsigned bNulls :1; /* True if explicit "NULLS FIRST/LAST" */
2048920504
unsigned bUsed :1; /* This column used in a SF_NestedFrom subquery */
2049020505
unsigned bUsingTerm:1; /* Term from the USING clause of a NestedFrom */
20506
+ unsigned bStarName:1; /* RENAME only: zEName from expanding a "*" */
2049120507
unsigned bNoExpand: 1; /* Term is an auxiliary in NestedFrom and should
2049220508
** not be expanded by "*" in parent queries */
2049320509
} fg;
2049420510
union {
2049520511
struct { /* Used by any ExprList other than Parse.pConsExpr */
@@ -21053,20 +21069,26 @@
2105321069
#if SQLITE_MAX_ATTACHED>30
2105421070
typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
2105521071
# define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
2105621072
# define DbMaskZero(M) memset((M),0,sizeof(M))
2105721073
# define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
21074
+# define DbMaskUnion(M,X) sqlite3DbMaskUnion(M,X)
2105821075
# define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
2105921076
# define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
2106021077
#else
2106121078
typedef unsigned int yDbMask;
2106221079
# define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
2106321080
# define DbMaskZero(M) ((M)=0)
2106421081
# define DbMaskSet(M,I) ((M)|=(((yDbMask)1)<<(I)))
21082
+# define DbMaskUnion(M,X) ((M)|=(X))
2106521083
# define DbMaskAllZero(M) ((M)==0)
2106621084
# define DbMaskNonZero(M) ((M)!=0)
2106721085
#endif
21086
+
21087
+/* Should be in vdbe.h, but we needed yDbMask definition first */
21088
+SQLITE_PRIVATE void sqlite3VdbeSchemaInUse(sqlite3*,Vdbe*,yDbMask*);
21089
+
2106821090
2106921091
/*
2107021092
** For each index X that has as one of its arguments either an expression
2107121093
** or the name of a virtual generated column, and if X is in scope such that
2107221094
** the value of the expression can simply be read from the index, then
@@ -21194,11 +21216,10 @@
2119421216
** determined by offsetof(Parse,aTempReg).
2119521217
**************************************************************************/
2119621218
2119721219
int aTempReg[8]; /* Holding area for temporary registers */
2119821220
Parse *pOuterParse; /* Outer Parse object when nested */
21199
- Token sNameToken; /* Token with unqualified schema object name */
2120021221
u32 oldmask; /* Mask of old.* columns referenced */
2120121222
u32 newmask; /* Mask of new.* columns referenced */
2120221223
union {
2120321224
struct { /* These fields available when isCreate is true */
2120421225
int addrCrTab; /* Address of OP_CreateBtree on CREATE TABLE */
@@ -21223,11 +21244,12 @@
2122321244
** each recursion. The boundary between these two regions is determined
2122421245
** using offsetof(Parse,sLastToken) so the sLastToken field must be the
2122521246
** first field in the recursive region.
2122621247
************************************************************************/
2122721248
21228
- Token sLastToken; /* The last token parsed */
21249
+ Token sLastToken; /* The last token parsed */
21250
+ Token sNameToken; /* Token with unqualified schema object name */
2122921251
ynVar nVar; /* Number of '?' variables seen in the SQL so far */
2123021252
u64 aVnbmc[SQLITE_VNBMC]; /* Varible Number Bitmap Cache */
2123121253
u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
2123221254
u8 explain; /* True if the EXPLAIN flag is found on the query */
2123321255
u8 eParseMode; /* PARSE_MODE_XXX constant */
@@ -21347,17 +21369,25 @@
2134721369
** linked list is stored as the "pTrigger" member of the associated
2134821370
** struct Table.
2134921371
**
2135021372
** The "step_list" member points to the first element of a linked list
2135121373
** containing the SQL statements specified as the trigger program.
21374
+**
21375
+** Trigger.nSelect is a copy of the Parse.nSelect value from when the
21376
+** trigger and its steps were parsed. There are no Select.selId values
21377
+** equal to or greater than this anywhere in the trigger program.
21378
+** Initializing the Parse.nSelect field to this value before coding
21379
+** the trigger program based on these structures ensures that no duplicate
21380
+** selId values are assigned.
2135221381
*/
2135321382
struct Trigger {
2135421383
char *zName; /* The name of the trigger */
2135521384
char *table; /* The table or view to which the trigger applies */
2135621385
u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
2135721386
u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
2135821387
u8 bReturning; /* This trigger implements a RETURNING clause */
21388
+ int nSelect; /* Upper bound on Select.selId in this trigger */
2135921389
Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
2136021390
IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
2136121391
the <column-list> is stored here */
2136221392
Schema *pSchema; /* Schema containing the trigger */
2136321393
Schema *pTabSchema; /* Schema containing the table */
@@ -22276,11 +22306,11 @@
2227622306
SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
2227722307
#ifndef SQLITE_OMIT_VIRTUALTABLE
2227822308
SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
2227922309
#endif
2228022310
SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
22281
-SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
22311
+SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int,Vdbe*);
2228222312
SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
2228322313
SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
2228422314
SQLITE_PRIVATE void sqlite3ColumnSetExpr(Parse*,Table*,Column*,Expr*);
2228522315
SQLITE_PRIVATE Expr *sqlite3ColumnExpr(Table*,Column*);
2228622316
SQLITE_PRIVATE Expr *sqlite3ColumnExprAuth(Table*,Column*,Parse*);
@@ -22353,10 +22383,11 @@
2235322383
# define sqlite3ViewGetColumnNames(A,B) 0
2235422384
#endif
2235522385
2235622386
#if SQLITE_MAX_ATTACHED>30
2235722387
SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
22388
+SQLITE_PRIVATE void sqlite3DbMaskUnion(yDbMask,yDbMask);
2235822389
#endif
2235922390
SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
2236022391
SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
2236122392
SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
2236222393
SQLITE_PRIVATE void sqlite3DeleteTableGeneric(sqlite3*, void*);
@@ -22718,11 +22749,11 @@
2271822749
SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
2271922750
SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
2272022751
SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr*);
2272122752
SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
2272222753
SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*);
22723
-SQLITE_PRIVATE int sqlite3CheckObjectName(Parse*, const char*,const char*,const char*);
22754
+SQLITE_PRIVATE int sqlite3CheckObjectName(Parse*,const char*,const char*,const char*,const char*);
2272422755
SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, i64);
2272522756
SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
2272622757
SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
2272722758
SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
2272822759
SQLITE_PRIVATE int sqlite3AbsInt32(int);
@@ -22787,10 +22818,11 @@
2278722818
);
2278822819
SQLITE_PRIVATE void sqlite3AlterSetNotNull(Parse*, SrcList*, Token*, Token*);
2278922820
SQLITE_PRIVATE i64 sqlite3GetToken(const unsigned char *, int *);
2279022821
SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
2279122822
SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int);
22823
+SQLITE_PRIVATE void sqlite3ExpireStmtsUsingSchema(sqlite3*, int, Vdbe*);
2279222824
SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int, int);
2279322825
SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr*);
2279422826
SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
2279522827
SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, SrcItem*);
2279622828
SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
@@ -22952,16 +22984,16 @@
2295222984
);
2295322985
# define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
2295422986
#endif
2295522987
SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db);
2295622988
#ifndef SQLITE_OMIT_VIRTUALTABLE
22957
-SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName);
22989
+SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName, const char *zDb);
2295822990
SQLITE_PRIVATE int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*);
2295922991
SQLITE_PRIVATE void sqlite3MarkAllShadowTablesOf(sqlite3*, Table*);
2296022992
SQLITE_PRIVATE void sqlite3VtabEponymousTableClearAll(sqlite3*);
2296122993
#else
22962
-# define sqlite3ShadowTableName(A,B) 0
22994
+# define sqlite3ShadowTableName(A,B,C) 0
2296322995
# define sqlite3IsShadowTableOf(A,B,C) 0
2296422996
# define sqlite3MarkAllShadowTablesOf(A,B)
2296522997
# define sqlite3VtabEponymousTableClearAll(X)
2296622998
#endif
2296722999
SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
@@ -25999,11 +26031,11 @@
2599926031
** The HH, MM, and SS must each be exactly 2 digits. The
2600026032
** fractional seconds FFFF can be one or more digits.
2600126033
**
2600226034
** Return 1 if there is a parsing error and 0 on success.
2600326035
*/
26004
-static int parseHhMmSs(const char *zDate, DateTime *p){
26036
+static int parseHhMmSs(const char *zDate, DateTime *p, int bAllowTZ){
2600526037
int h, m, s;
2600626038
double ms = 0.0;
2600726039
if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
2600826040
return 1;
2600926041
}
@@ -26035,10 +26067,11 @@
2603526067
p->rawS = 0;
2603626068
p->validHMS = 1;
2603726069
p->h = h;
2603826070
p->m = m;
2603926071
p->s = s + ms;
26072
+ if( !bAllowTZ && zDate[0] ) return 1;
2604026073
if( parseTimezone(zDate, p) ) return 1;
2604126074
return 0;
2604226075
}
2604326076
2604426077
/*
@@ -26154,11 +26187,11 @@
2615426187
return 1;
2615526188
}
2615626189
if( neg ) Y = -Y;
2615726190
zDate += 10;
2615826191
while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
26159
- if( parseHhMmSs(zDate, p)==0 ){
26192
+ if( parseHhMmSs(zDate, p, 1)==0 ){
2616026193
if( p->h==24 ){
2616126194
int mxD = daysOfMonth(Y,M);
2616226195
p->h = 0;
2616326196
D++;
2616426197
if( D>mxD ){
@@ -26245,11 +26278,11 @@
2624526278
DateTime *p
2624626279
){
2624726280
double r;
2624826281
if( parseYyyyMmDd(zDate,p)==0 ){
2624926282
return 0;
26250
- }else if( parseHhMmSs(zDate, p)==0 ){
26283
+ }else if( parseHhMmSs(zDate, p, 1)==0 ){
2625126284
return 0;
2625226285
}else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
2625326286
return setDateTimeToCurrent(context, p);
2625426287
}else if( sqlite3AtoF(zDate, &r)>0 ){
2625526288
setRawDateNumber(p, r);
@@ -26624,10 +26657,11 @@
2662426657
clearYMD_HMS_TZ(p);
2662526658
rc = 0;
2662626659
}else if( sqlite3_stricmp(z,"year")==0 ){
2662726660
p->M = 12;
2662826661
p->D = 31;
26662
+ p->nFloor = 0;
2662926663
rc = 0;
2663026664
}else if( sqlite3_stricmp(z,"day")==0 ){
2663126665
rc = 0;
2663226666
}
2663326667
break;
@@ -26640,10 +26674,11 @@
2664026674
** previous month.
2664126675
*/
2664226676
if( sqlite3_stricmp(z, "floor")==0 ){
2664326677
computeJD(p);
2664426678
p->iJD -= p->nFloor*86400000;
26679
+ p->nFloor = 0;
2664526680
clearYMD_HMS_TZ(p);
2664626681
rc = 0;
2664726682
}
2664826683
break;
2664926684
}
@@ -26703,11 +26738,13 @@
2670326738
if( p->isUtc==0 ){
2670426739
i64 iOrigJD; /* Original localtime */
2670526740
i64 iGuess; /* Guess at the corresponding utc time */
2670626741
int cnt = 0; /* Safety to prevent infinite loop */
2670726742
i64 iErr; /* Guess is off by this much */
26743
+ int useSubsec; /* Saved subseconds flag */
2670826744
26745
+ useSubsec = p->useSubsec;
2670926746
computeJD(p);
2671026747
iGuess = iOrigJD = p->iJD;
2671126748
iErr = 0;
2671226749
do{
2671326750
DateTime new;
@@ -26723,10 +26760,11 @@
2672326760
memset(p, 0, sizeof(*p));
2672426761
p->iJD = iGuess;
2672526762
p->validJD = 1;
2672626763
p->isUtc = 1;
2672726764
p->isLocal = 0;
26765
+ p->useSubsec = useSubsec;
2672826766
}
2672926767
rc = SQLITE_OK;
2673026768
}
2673126769
#endif
2673226770
break;
@@ -26757,10 +26795,11 @@
2675726795
if( Z>n ) Z -= 7;
2675826796
p->iJD += (n - Z)*86400000;
2675926797
if( strchr(z+8,'-')!=0 ) p->iJD -= 7*86400000;
2676026798
}
2676126799
clearYMD_HMS_TZ(p);
26800
+ p->nFloor = 0;
2676226801
rc = 0;
2676326802
}
2676426803
break;
2676526804
}
2676626805
case 's': {
@@ -26796,14 +26835,16 @@
2679626835
p->rawS = 0;
2679726836
p->tz = 0;
2679826837
p->validJD = 0;
2679926838
if( sqlite3_stricmp(z,"month")==0 ){
2680026839
p->D = 1;
26840
+ p->nFloor = 0;
2680126841
rc = 0;
2680226842
}else if( sqlite3_stricmp(z,"year")==0 ){
2680326843
p->M = 1;
2680426844
p->D = 1;
26845
+ p->nFloor = 0;
2680526846
rc = 0;
2680626847
}else if( sqlite3_stricmp(z,"day")==0 ){
2680726848
rc = 0;
2680826849
}
2680926850
break;
@@ -26896,21 +26937,30 @@
2689626937
** omitted.
2689726938
*/
2689826939
2689926940
DateTime tx;
2690026941
sqlite3_int64 day;
26942
+ int is24hr; /* 1 for a shift of exactly 24:00 */
26943
+ int bTimeOnly = z2==z; /* This is not the HH:MM tail of a
26944
+ ** +/-YYYY-MM-DD HH:MM shift, whose own
26945
+ ** nFloor must survive (e0fe679e7c) */
2690126946
if( !sqlite3Isdigit(*z2) ) z2++;
2690226947
memset(&tx, 0, sizeof(tx));
26903
- if( parseHhMmSs(z2, &tx) ) break;
26948
+ if( parseHhMmSs(z2, &tx, 0) ){
26949
+ break; /* HH:MM:SS.FFF failed to parse */
26950
+ }
26951
+ is24hr = tx.h==24;
2690426952
computeJD(&tx);
2690526953
tx.iJD -= 43200000;
2690626954
day = tx.iJD/86400000;
2690726955
tx.iJD -= day*86400000;
26956
+ if( is24hr ) tx.iJD += (sqlite3_int64)86400000;
2690826957
if( z0=='-' ) tx.iJD = -tx.iJD;
2690926958
computeJD(p);
2691026959
clearYMD_HMS_TZ(p);
2691126960
p->iJD += tx.iJD;
26961
+ if( bTimeOnly ) p->nFloor = 0;
2691226962
rc = 0;
2691326963
break;
2691426964
}
2691526965
2691626966
/* If control reaches this point, it means the transformation is
@@ -27007,13 +27057,14 @@
2700727057
n = sqlite3_value_bytes(argv[i]);
2700827058
if( z==0 || parseModifier(context, (char*)z, n, p, i) ) return 1;
2700927059
}
2701027060
computeJD(p);
2701127061
if( p->isError || !validJulianDay(p->iJD) ) return 1;
27012
- if( argc==1 && p->validYMD && p->D>28 ){
27062
+ if( p->validYMD && p->D>28 ){
2701327063
/* Make sure a YYYY-MM-DD is normalized.
27014
- ** Example: 2023-02-31 -> 2023-03-03 */
27064
+ ** Example: 2023-02-31 -> 2023-03-03
27065
+ */
2701527066
assert( p->validJD );
2701627067
p->validYMD = 0;
2701727068
}
2701827069
return 0;
2701927070
}
@@ -33722,11 +33773,11 @@
3372233773
if( (zz[i]&0xc0)==0x80 ) len--;
3372333774
}
3372433775
}
3372533776
if( width>len ){
3372633777
sqlite3_int64 sp = width-len;
33727
- assert( sp>0 && sp<0x7fffffff );
33778
+ assert( sp>0 && sp<=0x7fffffff );
3372833779
sqlite3StrAppendchar64(pAccum, (int)sp, ' ');
3372933780
if( !flag_leftjustify
3373033781
&& n>0
3373133782
&& sqlite3_str_errcode(pAccum)==0
3373233783
){
@@ -37664,11 +37715,11 @@
3766437715
** Return an IEEE754 floating point value that approximates d*pow(10,p).
3766537716
**
3766637717
** The (current) algorithm is adapted from the work of Ross Cox at
3766737718
** https://github.com/rsc/fpfmt
3766837719
*/
37669
-static double sqlite3Fp10Convert2(u64 d, int p){
37720
+static double sqlite3Fp10Convert2(u64 d, i64 p){
3767037721
int b, lp, e, adj, s;
3767137722
u32 pwr10l, mid1;
3767237723
u64 pwr10h, x, hi, lo, sticky, u, m;
3767337724
double r;
3767437725
if( p<POWERSOF10_FIRST ) return 0.0;
@@ -37723,15 +37774,17 @@
3772337774
**
3772437775
** bit 0 => Set if any prefix of the input is valid. Clear if
3772537776
** there is no prefix of the input that can be seen as
3772637777
** a valid floating point number.
3772737778
** bit 1 => Set if the input contains a decimal point or eNNN
37728
-** clause. Zero if the input is an integer.
37779
+** clause or other text that disqualifies it as an
37780
+** integer value. Zero if the input is an integer.
3772937781
** bit 2 => The input is exactly 0.0, not an underflow from
3773037782
** some value near zero.
3773137783
** bit 3 => Set if there are more than about 19 significant
3773237784
** digits in the input.
37785
+** bit 4 => The input is a special value like "Inf" or "NaN"
3773337786
**
3773437787
** If the input contains a syntax error but begins with text that might
3773537788
** be a valid number of some kind, then the result is negative. The
3773637789
** result is only zero if no prefix of the input could be interpreted as
3773737790
** a number.
@@ -37760,11 +37813,11 @@
3776037813
SQLITE_PRIVATE int sqlite3AtoF(const char *zIn, double *pResult){
3776137814
#ifndef SQLITE_OMIT_FLOATING_POINT
3776237815
const unsigned char *z = (const unsigned char*)zIn;
3776337816
int neg = 0; /* True for a negative value */
3776437817
u64 s = 0; /* mantissa */
37765
- int d = 0; /* Value is s * pow(10,d) */
37818
+ i64 d = 0; /* Value is s * pow(10,d) */
3776637819
int mState = 0; /* 1: digit seen 2: fp 4: hard-zero */
3776737820
unsigned v; /* Value of a single digit */
3776837821
3776937822
start_of_text:
3777037823
if( (v = (unsigned)z[0] - '0')<10 ){
@@ -37812,12 +37865,17 @@
3781237865
*pResult = 0.0;
3781337866
return 0;
3781437867
}
3781537868
mState |= 2;
3781637869
}else if( mState==0 ){
37817
- *pResult = 0.0;
37818
- return 0;
37870
+ if( sqlite3StrICmp((const char*)z,"Inf")==0 ){
37871
+ *pResult = neg ? -INFINITY : INFINITY;
37872
+ return 0x13;
37873
+ }else{
37874
+ *pResult = 0.0;
37875
+ return 0;
37876
+ }
3781937877
}
3782037878
3782137879
/* if exponent is present */
3782237880
if( *z=='e' || *z=='E' ){
3782337881
int esign;
@@ -37833,18 +37891,18 @@
3783337891
z++;
3783437892
}
3783537893
}
3783637894
/* copy digits to exponent */
3783737895
if( (v = (unsigned)z[0] - '0')<10 ){
37838
- int exp = v;
37896
+ u64 exp = v;
3783937897
z++;
3784037898
mState |= 2;
3784137899
while( (v = (unsigned)z[0] - '0')<10 ){
37842
- exp = exp<10000 ? (exp*10 + v) : 10000;
37900
+ exp = exp*10 + v + (exp & (0xffULL<<32));
3784337901
z++;
3784437902
}
37845
- d += esign*exp;
37903
+ d += esign*(exp & ((1ULL<<48)-1));
3784637904
}else{
3784737905
z--; /* Leave z[0] at 'e' or '+' or '-',
3784837906
** so that the return is 0 or -1 */
3784937907
}
3785037908
}
@@ -39387,11 +39445,10 @@
3938739445
}
3938839446
insertElement(pH, pH->ht ? &pH->ht[new_elem->h % pH->htsize] : 0, new_elem);
3938939447
return 0;
3939039448
}
3939139449
39392
-
3939339450
/************** End of hash.c ************************************************/
3939439451
/************** Begin file opcodes.c *****************************************/
3939539452
/* Automatically generated. Do not edit */
3939639453
/* See the tool/mkopcodec.tcl script for details. */
3939739454
#if !defined(SQLITE_OMIT_EXPLAIN) \
@@ -39539,64 +39596,66 @@
3953939596
/* 132 */ "ResetCount" OpHelp(""),
3954039597
/* 133 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
3954139598
/* 134 */ "SorterData" OpHelp("r[P2]=data"),
3954239599
/* 135 */ "RowData" OpHelp("r[P2]=data"),
3954339600
/* 136 */ "Rowid" OpHelp("r[P2]=PX rowid of P1"),
39544
- /* 137 */ "NullRow" OpHelp(""),
39545
- /* 138 */ "SeekEnd" OpHelp(""),
39546
- /* 139 */ "IdxInsert" OpHelp("key=r[P2]"),
39547
- /* 140 */ "SorterInsert" OpHelp("key=r[P2]"),
39548
- /* 141 */ "IdxDelete" OpHelp("key=r[P2@P5]"),
39549
- /* 142 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),
39550
- /* 143 */ "IdxRowid" OpHelp("r[P2]=rowid"),
39551
- /* 144 */ "FinishSeek" OpHelp(""),
39552
- /* 145 */ "Destroy" OpHelp(""),
39553
- /* 146 */ "Clear" OpHelp(""),
39554
- /* 147 */ "ResetSorter" OpHelp(""),
39555
- /* 148 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),
39556
- /* 149 */ "SqlExec" OpHelp(""),
39557
- /* 150 */ "ParseSchema" OpHelp(""),
39558
- /* 151 */ "LoadAnalysis" OpHelp(""),
39559
- /* 152 */ "DropTable" OpHelp(""),
39560
- /* 153 */ "DropIndex" OpHelp(""),
39601
+ /* 137 */ "Stale" OpHelp(""),
39602
+ /* 138 */ "NullRow" OpHelp(""),
39603
+ /* 139 */ "SeekEnd" OpHelp(""),
39604
+ /* 140 */ "IdxInsert" OpHelp("key=r[P2]"),
39605
+ /* 141 */ "SorterInsert" OpHelp("key=r[P2]"),
39606
+ /* 142 */ "IdxDelete" OpHelp("key=r[P2@P5]"),
39607
+ /* 143 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),
39608
+ /* 144 */ "IdxRowid" OpHelp("r[P2]=rowid"),
39609
+ /* 145 */ "FinishSeek" OpHelp(""),
39610
+ /* 146 */ "Destroy" OpHelp(""),
39611
+ /* 147 */ "DbLock" OpHelp(""),
39612
+ /* 148 */ "Clear" OpHelp(""),
39613
+ /* 149 */ "ResetSorter" OpHelp(""),
39614
+ /* 150 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),
39615
+ /* 151 */ "SqlExec" OpHelp(""),
39616
+ /* 152 */ "ParseSchema" OpHelp(""),
39617
+ /* 153 */ "LoadAnalysis" OpHelp(""),
3956139618
/* 154 */ "Real" OpHelp("r[P2]=PDBL13"),
39562
- /* 155 */ "DropTrigger" OpHelp(""),
39563
- /* 156 */ "IntegrityCk" OpHelp(""),
39564
- /* 157 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
39565
- /* 158 */ "Param" OpHelp(""),
39566
- /* 159 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
39567
- /* 160 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
39568
- /* 161 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
39569
- /* 162 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"),
39570
- /* 163 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
39571
- /* 164 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"),
39572
- /* 165 */ "AggValue" OpHelp("r[P3]=value N=P2"),
39573
- /* 166 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
39574
- /* 167 */ "Expire" OpHelp(""),
39575
- /* 168 */ "CursorLock" OpHelp(""),
39576
- /* 169 */ "CursorUnlock" OpHelp(""),
39577
- /* 170 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
39578
- /* 171 */ "VBegin" OpHelp(""),
39579
- /* 172 */ "VCreate" OpHelp(""),
39580
- /* 173 */ "VDestroy" OpHelp(""),
39581
- /* 174 */ "VOpen" OpHelp(""),
39582
- /* 175 */ "VCheck" OpHelp(""),
39583
- /* 176 */ "VInitIn" OpHelp("r[P2]=ValueList(P1,P3)"),
39584
- /* 177 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
39585
- /* 178 */ "VRename" OpHelp(""),
39586
- /* 179 */ "Pagecount" OpHelp(""),
39587
- /* 180 */ "MaxPgcnt" OpHelp(""),
39588
- /* 181 */ "ClrSubtype" OpHelp("r[P1].subtype = 0"),
39589
- /* 182 */ "GetSubtype" OpHelp("r[P2] = r[P1].subtype"),
39590
- /* 183 */ "SetSubtype" OpHelp("r[P2].subtype = r[P1]"),
39591
- /* 184 */ "FilterAdd" OpHelp("filter(P1) += key(P3@P4)"),
39592
- /* 185 */ "Trace" OpHelp(""),
39593
- /* 186 */ "CursorHint" OpHelp(""),
39594
- /* 187 */ "ReleaseReg" OpHelp("release r[P1@P2] mask P3"),
39595
- /* 188 */ "Noop" OpHelp(""),
39596
- /* 189 */ "Explain" OpHelp(""),
39597
- /* 190 */ "Abortable" OpHelp(""),
39619
+ /* 155 */ "DropTable" OpHelp(""),
39620
+ /* 156 */ "DropIndex" OpHelp(""),
39621
+ /* 157 */ "DropTrigger" OpHelp(""),
39622
+ /* 158 */ "IntegrityCk" OpHelp(""),
39623
+ /* 159 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
39624
+ /* 160 */ "Param" OpHelp(""),
39625
+ /* 161 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
39626
+ /* 162 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
39627
+ /* 163 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
39628
+ /* 164 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"),
39629
+ /* 165 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
39630
+ /* 166 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"),
39631
+ /* 167 */ "AggValue" OpHelp("r[P3]=value N=P2"),
39632
+ /* 168 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
39633
+ /* 169 */ "Expire" OpHelp(""),
39634
+ /* 170 */ "CursorLock" OpHelp(""),
39635
+ /* 171 */ "CursorUnlock" OpHelp(""),
39636
+ /* 172 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
39637
+ /* 173 */ "VBegin" OpHelp(""),
39638
+ /* 174 */ "VCreate" OpHelp(""),
39639
+ /* 175 */ "VDestroy" OpHelp(""),
39640
+ /* 176 */ "VOpen" OpHelp(""),
39641
+ /* 177 */ "VCheck" OpHelp(""),
39642
+ /* 178 */ "VInitIn" OpHelp("r[P2]=ValueList(P1,P3)"),
39643
+ /* 179 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
39644
+ /* 180 */ "VRename" OpHelp(""),
39645
+ /* 181 */ "Pagecount" OpHelp(""),
39646
+ /* 182 */ "MaxPgcnt" OpHelp(""),
39647
+ /* 183 */ "ClrSubtype" OpHelp("r[P1].subtype = 0"),
39648
+ /* 184 */ "GetSubtype" OpHelp("r[P2] = r[P1].subtype"),
39649
+ /* 185 */ "SetSubtype" OpHelp("r[P2].subtype = r[P1]"),
39650
+ /* 186 */ "FilterAdd" OpHelp("filter(P1) += key(P3@P4)"),
39651
+ /* 187 */ "Trace" OpHelp(""),
39652
+ /* 188 */ "CursorHint" OpHelp(""),
39653
+ /* 189 */ "ReleaseReg" OpHelp("release r[P1@P2] mask P3"),
39654
+ /* 190 */ "Noop" OpHelp(""),
39655
+ /* 191 */ "Explain" OpHelp(""),
39656
+ /* 192 */ "Abortable" OpHelp(""),
3959839657
};
3959939658
return azName[i];
3960039659
}
3960139660
#endif
3960239661
@@ -41832,11 +41891,11 @@
4183241891
static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
4183341892
struct vxworksFileId *pNew; /* search key and new file ID */
4183441893
struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
4183541894
int n; /* Length of zAbsoluteName string */
4183641895
41837
- assert( zAbsoluteName[0]=='/' );
41896
+ if( zAbsoluteName==0 || zAbsoluteName[0]=='/' );
4183841897
n = (int)strlen(zAbsoluteName);
4183941898
pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
4184041899
if( pNew==0 ) return 0;
4184141900
pNew->zCanonicalName = (char*)&pNew[1];
4184241901
memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
@@ -45261,23 +45320,23 @@
4526145320
unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
4526245321
sqlite3_mutex *pShmMutex; /* Mutex to access this object */
4526345322
char *zFilename; /* Name of the mmapped file */
4526445323
int hShm; /* Open file descriptor */
4526545324
int szRegion; /* Size of shared-memory regions */
45266
- u16 nRegion; /* Size of array apRegion */
45325
+ int nRegion; /* Size of array apRegion */
45326
+ int nRef; /* Number of unixShm objects pointing to this */
4526745327
u8 isReadonly; /* True if read-only */
4526845328
u8 isUnlocked; /* True if no DMS lock held */
45329
+#ifdef SQLITE_DEBUG
45330
+ u8 nextShmId; /* Next available unixShm.id value */
45331
+#endif
4526945332
char **apRegion; /* Array of mapped shared-memory regions */
45270
- int nRef; /* Number of unixShm objects pointing to this */
4527145333
unixShm *pFirst; /* All unixShm objects pointing to this */
4527245334
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4527345335
sqlite3_mutex *aMutex[SQLITE_SHM_NLOCK];
4527445336
#endif
4527545337
int aLock[SQLITE_SHM_NLOCK]; /* # shared locks on slot, -1==excl lock */
45276
-#ifdef SQLITE_DEBUG
45277
- u8 nextShmId; /* Next available unixShm.id value */
45278
-#endif
4527945338
};
4528045339
4528145340
/*
4528245341
** Structure used internally by this VFS to record the state of an
4528345342
** open shared memory connection.
@@ -46809,14 +46868,18 @@
4680946868
if( strcmp(pVfs->zName,"unix-excl")==0 ){
4681046869
pNew->ctrlFlags |= UNIXFILE_EXCL;
4681146870
}
4681246871
4681346872
#if OS_VXWORKS
46814
- pNew->pId = vxworksFindFileId(zFilename);
46815
- if( pNew->pId==0 ){
46816
- ctrlFlags |= UNIXFILE_NOLOCK;
46817
- rc = SQLITE_NOMEM_BKPT;
46873
+ if( zFilename ){
46874
+ pNew->pId = vxworksFindFileId(zFilename);
46875
+ if( pNew->pId==0 ){
46876
+ ctrlFlags |= UNIXFILE_NOLOCK;
46877
+ rc = SQLITE_NOMEM_BKPT;
46878
+ }
46879
+ }else{
46880
+ pNew->pId = 0;
4681846881
}
4681946882
#endif
4682046883
4682146884
if( ctrlFlags & UNIXFILE_NOLOCK ){
4682246885
pLockingStyle = &nolockIoMethods;
@@ -46917,16 +46980,19 @@
4691746980
if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4691846981
char *zSemName = pNew->pInode->aSemName;
4691946982
int n;
4692046983
sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
4692146984
pNew->pId->zCanonicalName);
46922
- for( n=1; zSemName[n]; n++ )
46923
- if( zSemName[n]=='/' ) zSemName[n] = '_';
46985
+ for(n=1; zSemName[n]; n++){
46986
+ if( zSemName[n]=='/' && !sqlite3FaultSim(801) ) zSemName[n] = '_';
46987
+ }
4692446988
pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4692546989
if( pNew->pInode->pSem == SEM_FAILED ){
4692646990
rc = SQLITE_NOMEM_BKPT;
4692746991
pNew->pInode->aSemName[0] = '\0';
46992
+ releaseInodeInfo(pNew);
46993
+ pNew->pInode = 0;
4692846994
}
4692946995
}
4693046996
unixLeaveMutex();
4693146997
}
4693246998
#endif
@@ -61074,15 +61140,22 @@
6107461140
**
6107561141
** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
6107661142
** file has been created already (via a spill on pagerStress()) and
6107761143
** when the number of dirty pages in memory exceeds 25% of the total
6107861144
** cache size.
61145
+**
61146
+** * Never sync a TEMP database if the current transaction has not
61147
+** modified the database (eState<PAGER_WRITER_CACHEMOD). In this case
61148
+** sqlite3PagerCommitPhaseOne() returns early without flushing any
61149
+** dirty pages left over from earlier transactions, so they must not
61150
+** be marked as clean by pager_end_transaction().
6107961151
*/
6108061152
static int pagerFlushOnCommit(Pager *pPager, int bCommit){
6108161153
if( pPager->tempFile==0 ) return 1;
6108261154
if( !bCommit ) return 0;
6108361155
if( !isOpen(pPager->fd) ) return 0;
61156
+ if( pPager->eState<PAGER_WRITER_CACHEMOD ) return 0;
6108461157
return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
6108561158
}
6108661159
6108761160
/*
6108861161
** This routine ends a transaction. A transaction is usually ended by
@@ -65750,10 +65823,15 @@
6575065823
if( rc!=SQLITE_OK ){
6575165824
sqlite3OsClose(pPager->jfd);
6575265825
goto commit_phase_one_exit;
6575365826
}
6575465827
bBatch = 0;
65828
+
65829
+ /* The journal file was just created on disk. Sync it now before
65830
+ ** any pages are written to the database file. */
65831
+ rc = syncJournal(pPager, 0);
65832
+ if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
6575565833
}else{
6575665834
sqlite3OsClose(pPager->jfd);
6575765835
}
6575865836
}
6575965837
#endif /* SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
@@ -78225,32 +78303,38 @@
7822578303
7822678304
/*
7822778305
** This variant of sqlite3BtreePayload() works even if the cursor has not
7822878306
** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
7822978307
** interface.
78308
+**
78309
+** If the cursor has to be restored to its saved position, then SQLITE_MOVED
78310
+** is returned and no data is read. The content of the row might have changed
78311
+** while the cursor position was saved, so the caller needs to recompute the
78312
+** size and offset of the data it is reading before it tries again. If the
78313
+** row no longer exists, SQLITE_ABORT is returned.
7823078314
*/
7823178315
#ifndef SQLITE_OMIT_INCRBLOB
78232
-static SQLITE_NOINLINE int accessPayloadChecked(
78233
- BtCursor *pCur,
78234
- u32 offset,
78235
- u32 amt,
78236
- void *pBuf
78237
-){
78316
+static SQLITE_NOINLINE int accessPayloadChecked(BtCursor *pCur){
7823878317
int rc;
7823978318
if ( pCur->eState==CURSOR_INVALID ){
7824078319
return SQLITE_ABORT;
7824178320
}
7824278321
assert( cursorOwnsBtShared(pCur) );
7824378322
rc = btreeRestoreCursorPosition(pCur);
78244
- return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
78323
+ if( rc ) return rc;
78324
+ if( pCur->eState!=CURSOR_VALID ){
78325
+ /* The row is gone, and the cursor was restored onto a neighbor. */
78326
+ return SQLITE_ABORT;
78327
+ }
78328
+ return SQLITE_MOVED;
7824578329
}
7824678330
SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
7824778331
if( pCur->eState==CURSOR_VALID ){
7824878332
assert( cursorOwnsBtShared(pCur) );
7824978333
return accessPayload(pCur, offset, amt, pBuf, 0);
7825078334
}else{
78251
- return accessPayloadChecked(pCur, offset, amt, pBuf);
78335
+ return accessPayloadChecked(pCur);
7825278336
}
7825378337
}
7825478338
#endif /* SQLITE_OMIT_INCRBLOB */
7825578339
7825678340
/*
@@ -79871,14 +79955,12 @@
7987179955
}
7987279956
ovflPgno = get4byte(pCell + pInfo->nSize - 4);
7987379957
pBt = pPage->pBt;
7987479958
assert( pBt->usableSize > 4 );
7987579959
ovflPageSize = pBt->usableSize - 4;
79876
- nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
79877
- assert( nOvfl>0 ||
79878
- (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
79879
- );
79960
+ nOvfl = (pInfo->nPayload - pInfo->nLocal + (u64)ovflPageSize-1)/ovflPageSize;
79961
+ assert( nOvfl>0 );
7988079962
while( nOvfl-- ){
7988179963
Pgno iNext = 0;
7988279964
MemPage *pOvfl = 0;
7988379965
if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
7988479966
/* 0 is not a legal page number and page 1 cannot be an
@@ -82331,10 +82413,11 @@
8233182413
if( pCur->eState>=CURSOR_REQUIRESEEK ){
8233282414
testcase( pCur->eState==CURSOR_REQUIRESEEK );
8233382415
testcase( pCur->eState==CURSOR_FAULT );
8233482416
rc = moveToRoot(pCur);
8233582417
if( rc && rc!=SQLITE_EMPTY ) return rc;
82418
+ loc = 0; /* Indicate the the cursor is not in a known position */
8233682419
}
8233782420
8233882421
assert( cursorOwnsBtShared(pCur) );
8233982422
assert( (pCur->curFlags & BTCF_WriteFlag)!=0
8234082423
&& p->pBt->inTransaction==TRANS_WRITE
@@ -82354,15 +82437,17 @@
8235482437
** cursors open on the row being replaced */
8235582438
if( p->hasIncrblobCur ){
8235682439
invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
8235782440
}
8235882441
82359
- /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
82360
- ** to a row with the same key as the new entry being inserted.
82442
+ /* If BTREE_SAVEPOSITION is set and seekResult is non-zero and
82443
+ ** if we didn't have to reposition the cursor initially, then
82444
+ ** the cursor must already be pointing to a row with the same
82445
+ ** key as the new entry being inserted. Verify that this is so.
8236182446
*/
8236282447
#ifdef SQLITE_DEBUG
82363
- if( flags & BTREE_SAVEPOSITION ){
82448
+ if( (flags & BTREE_SAVEPOSITION)!=0 && loc!=0 ){
8236482449
assert( pCur->curFlags & BTCF_ValidNKey );
8236582450
assert( pX->nKey==pCur->info.nKey );
8236682451
assert( loc==0 );
8236782452
}
8236882453
#endif
@@ -86019,11 +86104,15 @@
8601986104
}
8602086105
}
8602186106
assert( j<=n/2 );
8602286107
zCopy[j] = 0;
8602386108
rc = sqlite3AtoF(zCopy, pValue);
86024
- if( i<n ) rc = -100;
86109
+ if( i<n && rc>0 ){
86110
+ /* Only a prefix was converted. Adjust rc to match would
86111
+ ** sqlite3AtoF() would have done. */
86112
+ rc |= -16;
86113
+ }
8602586114
sqlite3DbFree(pMem->db, zCopy);
8602686115
}
8602786116
return rc;
8602886117
}
8602986118
}
@@ -87162,11 +87251,11 @@
8716287251
8716387252
if( op==TK_CAST ){
8716487253
u8 aff;
8716587254
assert( !ExprHasProperty(pExpr, EP_IntValue) );
8716687255
aff = sqlite3AffinityType(pExpr->u.zToken,0);
87167
- rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
87256
+ rc = valueFromExpr(db, pExpr->pLeft, enc, SQLITE_AFF_BLOB, ppVal, pCtx);
8716887257
testcase( rc!=SQLITE_OK );
8716987258
if( *ppVal ){
8717087259
#ifdef SQLITE_ENABLE_STAT4
8717187260
rc = ExpandBlob(*ppVal);
8717287261
#else
@@ -88420,10 +88509,13 @@
8842088509
if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
8842188510
|| opcode==OP_VDestroy
8842288511
|| opcode==OP_VCreate
8842388512
|| opcode==OP_ParseSchema
8842488513
|| opcode==OP_Function || opcode==OP_PureFunc
88514
+ || opcode==OP_AggStep || opcode==OP_AggInverse
88515
+ || opcode==OP_AggFinal || opcode==OP_AggValue
88516
+ || opcode==OP_VFilter || opcode==OP_VColumn
8842588517
|| ((opcode==OP_Halt || opcode==OP_HaltIfNull)
8842688518
&& ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
8842788519
|| (opcode==OP_MustBeInt && pOp->p2==0)
8842888520
){
8842988521
hasAbort = 1;
@@ -89992,10 +90084,12 @@
8999290084
if( eMode==2 ){
8999390085
Op *pOp = aOp + i;
8999490086
if( pOp->opcode==OP_OpenRead ) break;
8999590087
if( pOp->opcode==OP_OpenWrite && (pOp->p5 & OPFLAG_P2ISREG)==0 ) break;
8999690088
if( pOp->opcode==OP_ReopenIdx ) break;
90089
+ if( pOp->opcode==OP_Clear ) break;
90090
+ if( pOp->opcode==OP_Destroy ) break;
8999790091
}else
8999890092
#endif
8999990093
{
9000090094
assert( eMode==1 );
9000190095
if( aOp[i].opcode==OP_Explain ) break;
@@ -90846,10 +90940,26 @@
9084690940
assert( nRead==db->nVdbeRead );
9084790941
}
9084890942
#else
9084990943
#define checkActiveVdbeCnt(x)
9085090944
#endif
90945
+
90946
+/*
90947
+** Return a bitmask of all schemas referenced by active VDBEs, other
90948
+** than pExcept.
90949
+*/
90950
+SQLITE_PRIVATE void sqlite3VdbeSchemaInUse(sqlite3 *db, Vdbe *pExcept, yDbMask *pM){
90951
+ Vdbe *p;
90952
+ yDbMask m;
90953
+ DbMaskZero(m);
90954
+ for(p=db->pVdbe; p; p=p->pVNext){
90955
+ if( p==pExcept ) continue;
90956
+ if( p->eVdbeState!=VDBE_RUN_STATE ) continue;
90957
+ DbMaskUnion(m,p->btreeMask);
90958
+ }
90959
+ memcpy(pM, &m, sizeof(m));
90960
+}
9085190961
9085290962
/*
9085390963
** If the Vdbe passed as the first argument opened a statement-transaction,
9085490964
** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
9085590965
** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
@@ -91152,10 +91262,17 @@
9115291262
** to invoke any required unlock-notify callbacks.
9115391263
*/
9115491264
if( db->autoCommit ){
9115591265
sqlite3ConnectionUnlocked(db);
9115691266
}
91267
+
91268
+ /* Do any pending schema resets that were deferred because multiple
91269
+ ** VDBEs where active at the same time.
91270
+ */
91271
+ if( db->bPendingSchemaReset && db->nVdbeActive==0 ){
91272
+ sqlite3ResetOneSchema(db, -1, 0);
91273
+ }
9115791274
9115891275
assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
9115991276
return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
9116091277
}
9116191278
@@ -92919,10 +93036,27 @@
9291993036
Vdbe *p;
9292093037
for(p = db->pVdbe; p; p=p->pVNext){
9292193038
p->expired = iCode+1;
9292293039
}
9292393040
}
93041
+
93042
+/*
93043
+** Expire (urgently, with iCode 0) every prepared statement that is using
93044
+** a particular schema (iDb).
93045
+*/
93046
+SQLITE_PRIVATE void sqlite3ExpireStmtsUsingSchema(
93047
+ sqlite3 *db, /* The database connection statements belong to */
93048
+ int iDb, /* Index of the schema they are using */
93049
+ Vdbe *pExcept /* Except, don't expire this one */
93050
+){
93051
+ Vdbe *p;
93052
+ for(p = db->pVdbe; p; p=p->pVNext){
93053
+ if( p==pExcept ) continue;
93054
+ if( !DbMaskTest(p->btreeMask, iDb) ) continue;
93055
+ p->expired = 1;
93056
+ }
93057
+}
9292493058
9292593059
/*
9292693060
** Return the database associated with the Vdbe.
9292793061
*/
9292893062
SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
@@ -93512,10 +93646,13 @@
9351293646
rc = SQLITE_OK;
9351393647
}else{
9351493648
Vdbe *v = (Vdbe*)pStmt;
9351593649
sqlite3 *db = v->db;
9351693650
if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
93651
+#if defined(SQLITE_DISPOSAL_NOTIFIER)
93652
+ SQLITE_DISPOSAL_NOTIFIER(2,pStmt);
93653
+#endif
9351793654
sqlite3_mutex_enter(db->mutex);
9351893655
checkProfileCallback(db, v);
9351993656
assert( v->eVdbeState>=VDBE_READY_STATE );
9352093657
rc = sqlite3VdbeReset(v);
9352193658
sqlite3VdbeDelete(v);
@@ -99426,11 +99563,11 @@
9942699563
case OP_IfNullRow: { /* jump */
9942799564
VdbeCursor *pC;
9942899565
assert( pOp->p1>=0 && pOp->p1<p->nCursor );
9942999566
pC = p->apCsr[pOp->p1];
9943099567
if( pC && pC->nullRow ){
99431
- sqlite3VdbeMemSetNull(aMem + pOp->p3);
99568
+ if( pOp->p3>0 ) sqlite3VdbeMemSetNull(aMem + pOp->p3);
9943299569
goto jump_to_p2;
9943399570
}
9943499571
break;
9943599572
}
9943699573
@@ -99890,10 +100027,11 @@
99890100027
Column *aCol;
99891100028
int i;
99892100029
int nCol;
99893100030
99894100031
assert( pOp->p4type==P4_TABLE );
100032
+ if( p->expired==1 ) goto abort_due_to_expired;
99895100033
pTab = pOp->p4.pTab;
99896100034
assert( pTab->tabFlags & TF_Strict );
99897100035
assert( pOp->p3>=0 && pOp->p3<pTab->nCol+2 );
99898100036
aCol = pTab->aCol;
99899100037
pIn1 = &aMem[pOp->p1];
@@ -99942,15 +100080,15 @@
99942100080
testcase( pIn1->u.i==140737488355327LL );
99943100081
testcase( pIn1->u.i==-140737488355328LL );
99944100082
testcase( pIn1->u.i==-140737488355329LL );
99945100083
if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL){
99946100084
pIn1->flags |= MEM_IntReal;
99947
- pIn1->flags &= ~MEM_Int;
100085
+ pIn1->flags &= ~(MEM_Int|MEM_Str);
99948100086
}else{
99949100087
pIn1->u.r = (double)pIn1->u.i;
99950100088
pIn1->flags |= MEM_Real;
99951
- pIn1->flags &= ~MEM_Int;
100089
+ pIn1->flags &= ~(MEM_Int|MEM_Str);
99952100090
}
99953100091
}else if( (pIn1->flags & (MEM_Real|MEM_IntReal))==0 ){
99954100092
goto vdbe_type_error;
99955100093
}
99956100094
break;
@@ -100089,11 +100227,11 @@
100089100227
pRec = pData0;
100090100228
do{
100091100229
applyAffinity(pRec, zAffinity[0], encoding);
100092100230
if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){
100093100231
pRec->flags |= MEM_IntReal;
100094
- pRec->flags &= ~(MEM_Int);
100232
+ pRec->flags &= ~(MEM_Int|MEM_Str);
100095100233
}
100096100234
REGISTER_TRACE((int)(pRec-aMem), pRec);
100097100235
zAffinity++;
100098100236
pRec++;
100099100237
assert( zAffinity[0]==0 || pRec<=pLast );
@@ -100217,17 +100355,17 @@
100217100355
assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) );
100218100356
assert( pRec->n>=0 );
100219100357
len = (u32)pRec->n;
100220100358
serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);
100221100359
if( pRec->flags & MEM_Zero ){
100222
- serial_type += (u32)pRec->u.nZero*2;
100223100360
if( nData ){
100224100361
if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
100225100362
len += pRec->u.nZero;
100226100363
}else{
100227100364
nZero += pRec->u.nZero;
100228100365
}
100366
+ serial_type += 2*(u32)pRec->u.nZero;
100229100367
}
100230100368
nData += len;
100231100369
nHdr += sqlite3VarintLen(serial_type);
100232100370
pRec->uTemp = serial_type;
100233100371
}
@@ -100789,11 +100927,11 @@
100789100927
** v-table would have to be ready for the sqlite3_vtab structure itself
100790100928
** to be invalidated whenever sqlite3_step() is called from within
100791100929
** a v-table method.
100792100930
*/
100793100931
if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
100794
- sqlite3ResetOneSchema(db, pOp->p1);
100932
+ sqlite3ResetOneSchema(db, pOp->p1, p);
100795100933
}
100796100934
p->expired = 1;
100797100935
rc = SQLITE_SCHEMA;
100798100936
100799100937
/* Set changeCntOn to 0 to prevent the value returned by sqlite3_changes()
@@ -100936,11 +101074,14 @@
100936101074
/* Opcode: OpenWrite P1 P2 P3 P4 P5
100937101075
** Synopsis: root=P2 iDb=P3
100938101076
**
100939101077
** Open a read/write cursor named P1 on the table or index whose root
100940101078
** page is P2 (or whose root page is held in register P2 if the
100941
-** OPFLAG_P2ISREG bit is set in P5 - see below).
101079
+** OPFLAG_P2ISREG bit is set in P5 - see below). The database file is
101080
+** determined by P3. P3==0 means the main database, P3==1 means the
101081
+** database used for temporary tables, and P3>1 means used the
101082
+** corresponding attached database.
100942101083
**
100943101084
** The P4 value may be either an integer (P4_INT32) or a pointer to
100944101085
** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
100945101086
** object, then table being opened must be an [index b-tree] where the
100946101087
** KeyInfo object defines the content and collating
@@ -102122,11 +102263,11 @@
102122102263
** integer value of pIn3. Jump to P2 if pIn3 cannot be converted
102123102264
** into an integer without loss of information. Take care to avoid
102124102265
** changing the datatype of pIn3, however, as it is used by other
102125102266
** parts of the prepared statement. */
102126102267
Mem x = pIn3[0];
102127
- if( x.flags & MEM_Str ){
102268
+ if( (x.flags & (MEM_Str|MEM_Int|MEM_Real|MEM_IntReal))==MEM_Str ){
102128102269
applyNumericAffinity(&x, 1);
102129102270
}
102130102271
if( x.flags & MEM_Int ){
102131102272
iKey = x.u.i;
102132102273
}else
@@ -102399,10 +102540,11 @@
102399102540
REGISTER_TRACE(pOp->p3, pKey);
102400102541
x.nKey = pKey->u.i;
102401102542
102402102543
if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
102403102544
assert( pC->iDb>=0 );
102545
+ if( p->expired==1 ) goto abort_due_to_expired;
102404102546
zDb = db->aDb[pC->iDb].zDbSName;
102405102547
pTab = pOp->p4.pTab;
102406102548
assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
102407102549
}else{
102408102550
pTab = 0;
@@ -102541,10 +102683,11 @@
102541102683
assert( pC->deferredMoveto==0 );
102542102684
sqlite3VdbeIncrWriteCounter(p, pC);
102543102685
102544102686
#ifdef SQLITE_DEBUG
102545102687
if( pOp->p4type==P4_TABLE
102688
+ && !p->expired
102546102689
&& HasRowid(pOp->p4.pTab)
102547102690
&& pOp->p5==0
102548102691
&& sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
102549102692
){
102550102693
/* If p5 is zero, the seek operation that positioned the cursor prior to
@@ -102559,10 +102702,11 @@
102559102702
** the name of the db to pass as to it. Also set local pTab to a copy
102560102703
** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
102561102704
** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
102562102705
** VdbeCursor.movetoTarget to the current rowid. */
102563102706
if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
102707
+ if( p->expired==1 ) goto abort_due_to_expired;
102564102708
assert( pC->iDb>=0 );
102565102709
assert( pOp->p4.pTab!=0 );
102566102710
zDb = db->aDb[pC->iDb].zDbSName;
102567102711
pTab = pOp->p4.pTab;
102568102712
if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
@@ -102815,10 +102959,26 @@
102815102959
v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
102816102960
}
102817102961
pOut->u.i = v;
102818102962
break;
102819102963
}
102964
+
102965
+/* Opcode: Stale P1 * * * *
102966
+**
102967
+** Mark the row cache for cursor P1 as stale. This opcode is used
102968
+** on pseudo-cursors right before the content of the register that
102969
+** holds their record is modified.
102970
+*/
102971
+case OP_Stale: {
102972
+ VdbeCursor *pC;
102973
+
102974
+ pC = p->apCsr[pOp->p1];
102975
+ assert( pC!=0 );
102976
+ assert( pC->eCurType==CURTYPE_PSEUDO );
102977
+ pC->cacheStatus = CACHE_STALE;
102978
+ break;
102979
+}
102820102980
102821102981
/* Opcode: NullRow P1 P2 * * *
102822102982
**
102823102983
** Move the cursor P1 to a null row if P2 is 0. Any OP_Column operations
102824102984
** that occur while the cursor is on the null row will always
@@ -102830,10 +102990,11 @@
102830102990
** If P2 is not 0, then the nullRow flag on the pseudo-cursor is
102831102991
** turned off.
102832102992
*/
102833102993
case OP_NullRow: {
102834102994
VdbeCursor *pC;
102995
+ Mem *pMem;
102835102996
102836102997
assert( pOp->p1>=0 && pOp->p1<p->nCursor );
102837102998
pC = p->apCsr[pOp->p1];
102838102999
if( pC==0 ){
102839103000
/* If the cursor is not already open, create a special kind of
@@ -102848,10 +103009,18 @@
102848103009
pC->nullRow = (pOp->p2==0);
102849103010
pC->cacheStatus = CACHE_STALE;
102850103011
if( pC->eCurType==CURTYPE_BTREE ){
102851103012
assert( pC->uc.pCursor!=0 );
102852103013
sqlite3BtreeClearCursor(pC->uc.pCursor);
103014
+ }else if( pC->eCurType==CURTYPE_PSEUDO && pC->seekResult>0 ){
103015
+ static char nullRecord[] = { 0x02, 0x00 };
103016
+ pMem = &aMem[pC->seekResult];
103017
+ assert( !VdbeMemDynamic(pMem) );
103018
+ pC->nullRow = 1;
103019
+ pMem->z = nullRecord;
103020
+ pMem->n = 2;
103021
+ pMem->flags = MEM_Blob|MEM_Ephem;
102853103022
}
102854103023
#ifdef SQLITE_DEBUG
102855103024
if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
102856103025
#endif
102857103026
break;
@@ -103288,10 +103457,11 @@
103288103457
r.default_rc = 0;
103289103458
r.aMem = &aMem[pOp->p2];
103290103459
rc = sqlite3BtreeIndexMoveto(pCrsr, &r, &res);
103291103460
if( rc ) goto abort_due_to_error;
103292103461
if( res!=0 ){
103462
+ if( p->expired==1 ) goto abort_due_to_expired;
103293103463
rc = sqlite3VdbeFindIndexKey(pCrsr, pOp->p4.pIdx, &r, &res, 0);
103294103464
if( rc!=SQLITE_OK ) goto abort_due_to_error;
103295103465
if( res!=0 ){
103296103466
if( !sqlite3WritableSchema(db) ){
103297103467
rc = sqlite3ReportError(
@@ -103601,10 +103771,25 @@
103601103771
}
103602103772
#endif
103603103773
}
103604103774
break;
103605103775
}
103776
+
103777
+/*
103778
+** Opcode: DbLock
103779
+**
103780
+** Raise an SQLITE_LOCKED error if there are any other reader statements
103781
+** currently active.
103782
+*/
103783
+case OP_DbLock: {
103784
+ if( db->nVdbeRead>1 ){
103785
+ rc = SQLITE_LOCKED;
103786
+ p->errorAction = OE_Abort;
103787
+ goto abort_due_to_error;
103788
+ }
103789
+ break;
103790
+};
103606103791
103607103792
/* Opcode: Clear P1 P2 P3
103608103793
**
103609103794
** Delete all contents of the database table or index whose root page
103610103795
** in the database file is given by P1. But, unlike Destroy, do not
@@ -103784,13 +103969,17 @@
103784103969
assert( iDb>=0 && iDb<db->nDb );
103785103970
assert( DbHasProperty(db, iDb, DB_SchemaLoaded)
103786103971
|| db->mallocFailed
103787103972
|| (CORRUPT_DB && (db->flags & SQLITE_NoSchemaError)!=0) );
103788103973
103974
+ /* ParseSchema is never invoked on a read-only database */
103975
+ assert( db->aDb[iDb].pBt==0 || sqlite3BtreeIsReadonly(db->aDb[iDb].pBt)==0 );
103976
+
103789103977
#ifndef SQLITE_OMIT_ALTERTABLE
103790103978
if( pOp->p4.z==0 ){
103791103979
assert( pOp->p5!=0 );
103980
+ sqlite3ExpireStmtsUsingSchema(db, iDb, p);
103792103981
sqlite3SchemaClear(db->aDb[iDb].pSchema);
103793103982
db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
103794103983
rc = sqlite3InitOne(db, iDb, &p->zErrMsg, pOp->p5);
103795103984
db->mDbFlags |= DBFLAG_SchemaChange;
103796103985
p->expired = 0;
@@ -103827,10 +104016,11 @@
103827104016
db->init.busy = 0;
103828104017
}
103829104018
}
103830104019
if( rc ){
103831104020
sqlite3ResetAllSchemasOfConnection(db);
104021
+ sqlite3ExpirePreparedStatements(db, 0);
103832104022
if( rc==SQLITE_NOMEM ){
103833104023
goto no_mem;
103834104024
}
103835104025
goto abort_due_to_error;
103836104026
}
@@ -103985,10 +104175,11 @@
103985104175
assert( pOp[-1].opcode==OP_Found );
103986104176
assert( pOp[-1].p1==pOp->p1 );
103987104177
assert( pOp[-1].p3==pOp->p3 );
103988104178
pC = p->apCsr[pOp->p1];
103989104179
assert( pOp->p4type==P4_INDEX );
104180
+ if( p->expired==1 ) goto abort_due_to_expired;
103990104181
assert( pC->eCurType==CURTYPE_BTREE );
103991104182
assert( pC->uc.pCursor!=0 );
103992104183
assert( pC->isTable==0 );
103993104184
103994104185
memset(&r, 0, sizeof(r));
@@ -105984,11 +106175,11 @@
105984106175
if( rc==SQLITE_CORRUPT && db->autoCommit==0 ){
105985106176
db->flags |= SQLITE_CorruptRdOnly;
105986106177
}
105987106178
rc = SQLITE_ERROR;
105988106179
if( resetSchemaOnFault>0 ){
105989
- sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
106180
+ sqlite3ResetOneSchema(db, resetSchemaOnFault-1, p);
105990106181
}
105991106182
105992106183
/* This is the only way out of this procedure. We have to
105993106184
** release the mutexes on btrees that were acquired at the
105994106185
** top. */
@@ -106045,10 +106236,14 @@
106045106236
*/
106046106237
abort_due_to_interrupt:
106047106238
assert( AtomicLoad(&db->u1.isInterrupted) );
106048106239
rc = SQLITE_INTERRUPT;
106049106240
goto abort_due_to_error;
106241
+
106242
+abort_due_to_expired:
106243
+ rc = SQLITE_SCHEMA;
106244
+ goto abort_due_to_error;
106050106245
}
106051106246
106052106247
106053106248
/************** End of vdbe.c ************************************************/
106054106249
/************** Begin file vdbeblob.c ****************************************/
@@ -106078,10 +106273,11 @@
106078106273
typedef struct Incrblob Incrblob;
106079106274
struct Incrblob {
106080106275
int nByte; /* Size of open blob, in bytes */
106081106276
int iOffset; /* Byte offset of blob in cursor data */
106082106277
u16 iCol; /* Table column this handle is open on */
106278
+ u8 bRetry; /* Doing a blobReadWrite() retry */
106083106279
BtCursor *pCsr; /* Cursor pointing at blob row */
106084106280
sqlite3_stmt *pStmt; /* Statement holding cursor open */
106085106281
sqlite3 *db; /* The associated database */
106086106282
char *zDb; /* Database name */
106087106283
Table *pTab; /* Table object */
@@ -106426,10 +106622,71 @@
106426106622
}else{
106427106623
rc = SQLITE_OK;
106428106624
}
106429106625
return rc;
106430106626
}
106627
+
106628
+/* Forward reference */
106629
+static int blobReadWrite(
106630
+ sqlite3_blob *pBlob,
106631
+ void *z,
106632
+ int n,
106633
+ int iOffset,
106634
+ int (*xCall)(BtCursor*, u32, u32, void*)
106635
+);
106636
+
106637
+/*
106638
+** The b-tree cursor for blob handle p was restored to its saved position by
106639
+** sqlite3BtreePayloadChecked(), which then returned SQLITE_MOVED. The
106640
+** position is saved, for example, by a ROLLBACK, and that might have changed
106641
+** the content of the row. So the iOffset and nByte values computed when the
106642
+** handle was opened or last moved cannot be trusted. A ROLLBACK can change
106643
+** the size of a column that precedes the blob, which moves the blob within
106644
+** the row.
106645
+**
106646
+** Recompute iOffset and nByte in the same way that sqlite3_blob_reopen()
106647
+** does. Then retry the blobReadWrite().
106648
+*/
106649
+static SQLITE_NOINLINE int blobReadWriteRetry(
106650
+ Incrblob *p,
106651
+ void *z,
106652
+ int n,
106653
+ int iOffset,
106654
+ int (*xCall)(BtCursor*, u32, u32, void*)
106655
+){
106656
+ int rc;
106657
+ sqlite3_int64 iRow;
106658
+ char *zErr = 0;
106659
+ sqlite3 *db = p->db;
106660
+
106661
+ sqlite3BtreeEnterCursor(p->pCsr);
106662
+ iRow = sqlite3BtreeIntegerKey(p->pCsr);
106663
+ sqlite3BtreeLeaveCursor(p->pCsr);
106664
+ ((Vdbe*)p->pStmt)->rc = SQLITE_OK;
106665
+ if( NEVER(p->bRetry) || sqlite3FaultSim(210) ){
106666
+ /* It should not be possible for blobReadWrite() and blobReadWriteRetry()
106667
+ ** to get into a loop, but we check anyway, for safety. */
106668
+ rc = SQLITE_ABORT;
106669
+ sqlite3VdbeFinalize((Vdbe*)p->pStmt);
106670
+ p->pStmt = 0;
106671
+ }else{
106672
+ rc = blobSeekToRow(p, iRow, &zErr);
106673
+ }
106674
+ assert( rc==SQLITE_OK || p->pStmt==0 );
106675
+ if( rc==SQLITE_OK ){
106676
+ sqlite3DbFree(db, zErr);
106677
+ p->bRetry = 1;
106678
+ rc = blobReadWrite((sqlite3_blob*)p,z,n,iOffset,xCall);
106679
+ p->bRetry = 0;
106680
+ }else{
106681
+ sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : (char*)0), zErr);
106682
+ sqlite3DbFree(db, zErr);
106683
+ rc = sqlite3ApiExit(db, rc);
106684
+ }
106685
+ sqlite3_mutex_leave(db->mutex);
106686
+ return rc;
106687
+}
106431106688
106432106689
/*
106433106690
** Perform a read or write operation on a blob
106434106691
*/
106435106692
static int blobReadWrite(
@@ -106504,15 +106761,25 @@
106504106761
#else
106505106762
rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
106506106763
#endif
106507106764
106508106765
sqlite3BtreeLeaveCursor(p->pCsr);
106509
- if( rc==SQLITE_ABORT ){
106510
- sqlite3VdbeFinalize(v);
106511
- p->pStmt = 0;
106766
+ if( rc==SQLITE_OK ){
106767
+ v->rc = SQLITE_OK;
106512106768
}else{
106513
- v->rc = rc;
106769
+ if( rc==SQLITE_MOVED ){
106770
+ /* The cursor was restored and no data was read. Refresh the
106771
+ ** handle and try the read again. */
106772
+ return blobReadWriteRetry(p,z,n,iOffset,xCall);
106773
+ }
106774
+ if( rc==SQLITE_ABORT ){
106775
+ assert( p->pStmt );
106776
+ sqlite3VdbeFinalize(v);
106777
+ p->pStmt = 0;
106778
+ }else{
106779
+ v->rc = rc;
106780
+ }
106514106781
}
106515106782
}
106516106783
sqlite3Error(db, rc);
106517106784
rc = sqlite3ApiExit(db, rc);
106518106785
sqlite3_mutex_leave(db->mutex);
@@ -109749,12 +110016,28 @@
109749110016
i = 8;
109750110017
}else{
109751110018
if( i<=2 && pCur->zType==0 ){
109752110019
Schema *pSchema;
109753110020
HashElem *k;
109754
- int iDb = pOp->p3;
109755
- Pgno iRoot = (Pgno)pOp->p2;
110021
+ int iDb;
110022
+ Pgno iRoot;
110023
+ switch( pOp->opcode ){
110024
+ case OP_Clear: {
110025
+ iRoot = (Pgno)pOp->p1;
110026
+ iDb = pOp->p2;
110027
+ break;
110028
+ }
110029
+ case OP_Destroy: {
110030
+ iRoot = (Pgno)pOp->p1;
110031
+ iDb = pOp->p3;
110032
+ break;
110033
+ }
110034
+ default: {
110035
+ iRoot = (Pgno)pOp->p2;
110036
+ iDb = pOp->p3;
110037
+ }
110038
+ }
109756110039
sqlite3 *db = pVTab->db;
109757110040
pSchema = db->aDb[iDb].pSchema;
109758110041
pCur->zSchema = db->aDb[iDb].zDbSName;
109759110042
for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
109760110043
Table *pTab = (Table*)sqliteHashData(k);
@@ -109847,11 +110130,14 @@
109847110130
break;
109848110131
case 22: /* tables_used.name */
109849110132
sqlite3_result_text(ctx, pCur->zName, -1, SQLITE_STATIC);
109850110133
break;
109851110134
case 23: /* tables_used.wr */
109852
- sqlite3_result_int(ctx, pOp->opcode==OP_OpenWrite);
110135
+ sqlite3_result_int(ctx,
110136
+ pOp->opcode==OP_OpenWrite ||
110137
+ pOp->opcode==OP_Clear ||
110138
+ pOp->opcode==OP_Destroy);
109853110139
break;
109854110140
}
109855110141
return SQLITE_OK;
109856110142
}
109857110143
@@ -110690,10 +110976,23 @@
110690110976
*/
110691110977
SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
110692110978
UNUSED_PARAMETER2(NotUsed, NotUsed2);
110693110979
return WRC_Continue;
110694110980
}
110981
+
110982
+/*
110983
+** This is a SELECT-node callback for the expression walker that
110984
+** always "fails". By "fail" in this case, we mean set
110985
+** pWalker->eCode to zero and abort.
110986
+**
110987
+** This callback is used by multiple expression walkers.
110988
+*/
110989
+SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
110990
+ UNUSED_PARAMETER(NotUsed);
110991
+ pWalker->eCode = 0;
110992
+ return WRC_Abort;
110993
+}
110695110994
110696110995
/************** End of walker.c **********************************************/
110697110996
/************** Begin file resolve.c *****************************************/
110698110997
/*
110699110998
** 2008 August 18
@@ -111157,12 +111456,19 @@
111157111456
extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
111158111457
}
111159111458
}
111160111459
cnt++;
111161111460
pMatch = pItem;
111162
- /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
111163
- pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
111461
+ /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY.
111462
+ ** Except when parsing for ALTER TABLE. In that case leave
111463
+ ** Expr.iColumn set to iCol so that it can be distinguished from
111464
+ ** literal "rowid" references. */
111465
+ if( j==pTab->iPKey && !IN_RENAME_OBJECT ){
111466
+ pExpr->iColumn = -1;
111467
+ }else{
111468
+ pExpr->iColumn = (i16)j;
111469
+ }
111164111470
if( pItem->fg.isNestedFrom ){
111165111471
sqlite3SrcItemColumnUsed(pItem, j);
111166111472
}
111167111473
}
111168111474
if( 0==cnt && VisibleRowid(pTab) ){
@@ -111257,11 +111563,11 @@
111257111563
int iCol;
111258111564
pSchema = pTab->pSchema;
111259111565
cntTab++;
111260111566
iCol = sqlite3ColumnIndex(pTab, zCol);
111261111567
if( iCol>=0 ){
111262
- if( pTab->iPKey==iCol ) iCol = -1;
111568
+ if( pTab->iPKey==iCol && !IN_RENAME_OBJECT ) iCol = -1;
111263111569
}else{
111264111570
if( sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
111265111571
iCol = -1;
111266111572
}else{
111267111573
iCol = pTab->nCol;
@@ -111672,10 +111978,14 @@
111672111978
break;
111673111979
}
111674111980
if( pExpr->op==TK_UPLUS ){
111675111981
pExpr = pExpr->pLeft;
111676111982
assert( pExpr!=0 );
111983
+ }else if( pExpr->op==TK_CASE ){
111984
+ assert( ExprUseXList(pExpr) );
111985
+ resolveSetExprSubtypeArg(pExpr->x.pList);
111986
+ break;
111677111987
}else{
111678111988
break;
111679111989
}
111680111990
}
111681111991
}
@@ -112300,10 +112610,33 @@
112300112610
}
112301112611
112302112612
/* If no match, return 0. */
112303112613
return 0;
112304112614
}
112615
+
112616
+/*
112617
+** ORDER BY term pE, a simple identifier, has been matched by resolveAsName()
112618
+** against the iCol-th (1-based) entry of result-set pEList. If this is an
112619
+** ALTER TABLE rename, and the name of that entry was generated by expanding
112620
+** "*" or "tbl.*", then modify pE to refer to the table column directly.
112621
+*/
112622
+static void resolveRenameStarTerm(
112623
+ Parse *pParse, /* Parsing context */
112624
+ ExprList *pEList, /* Result-set that pE was matched against */
112625
+ int iCol, /* 1-based index of the matching pEList entry */
112626
+ Expr *pE /* ORDER BY term to convert */
112627
+){
112628
+ if( IN_RENAME_OBJECT && pEList->a[iCol-1].fg.bStarName ){
112629
+ Expr *pX = pEList->a[iCol-1].pExpr;
112630
+ if( ALWAYS(pX->op==TK_COLUMN) && ALWAYS(pE->op==TK_ID) ){
112631
+ pE->op = TK_COLUMN;
112632
+ pE->iTable = pX->iTable;
112633
+ pE->iColumn = pX->iColumn;
112634
+ pE->y.pTab = pX->y.pTab;
112635
+ }
112636
+ }
112637
+}
112305112638
112306112639
/*
112307112640
** Generate an ORDER BY or GROUP BY term out-of-range error.
112308112641
*/
112309112642
static void resolveOutOfRangeError(
@@ -112375,11 +112708,13 @@
112375112708
resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE);
112376112709
return 1;
112377112710
}
112378112711
}else{
112379112712
iCol = resolveAsName(pParse, pEList, pE);
112380
- if( iCol==0 ){
112713
+ if( iCol>0 ){
112714
+ resolveRenameStarTerm(pParse, pEList, iCol, pE);
112715
+ }else{
112381112716
/* Now test if expression pE matches one of the values returned
112382112717
** by pSelect. In the usual case this is done by duplicating the
112383112718
** expression, resolving any symbols in it, and then comparing
112384112719
** it against each expression returned by the SELECT statement.
112385112720
** Once the comparisons are finished, the duplicate expression
@@ -112543,10 +112878,11 @@
112543112878
Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);
112544112879
if( NEVER(pE2==0) ) continue;
112545112880
if( zType[0]!='G' ){
112546112881
iCol = resolveAsName(pParse, pSelect->pEList, pE2);
112547112882
if( iCol>0 ){
112883
+ resolveRenameStarTerm(pParse, pSelect->pEList, iCol, pE2);
112548112884
/* If an AS-name match is found, mark this ORDER BY column as being
112549112885
** a copy of the iCol-th result-set column. The subsequent call to
112550112886
** sqlite3ResolveOrderGroupBy() will convert the expression to a
112551112887
** copy of the iCol-th result-set expression. */
112552112888
pItem->u.x.iOrderByCol = (u16)iCol;
@@ -113141,15 +113477,20 @@
113141113477
assert( pExpr->iTable==pExpr->pLeft->x.pSelect->pEList->nExpr );
113142113478
return sqlite3ExprAffinity(
113143113479
pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
113144113480
);
113145113481
}
113146
- if( op==TK_VECTOR
113147
- || (op==TK_FUNCTION && pExpr->affExpr==SQLITE_AFF_DEFER)
113148
- ){
113482
+ if( op==TK_VECTOR ){
113149113483
assert( ExprUseXList(pExpr) );
113150113484
return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
113485
+ }
113486
+ if( op==TK_FUNCTION && pExpr->affExpr==SQLITE_AFF_DEFER ){
113487
+ /* The USING column of a FULL JOIN: coalesce(L.x, R.x). Use the
113488
+ ** affinity of L.x, except that REAL becomes NUMERIC, since the
113489
+ ** value may come from R.x and so need not be REAL. */
113490
+ char aff = sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
113491
+ return aff==SQLITE_AFF_REAL ? SQLITE_AFF_NUMERIC : aff;
113151113492
}
113152113493
if( ExprHasProperty(pExpr, EP_Skip|EP_IfNullRow) ){
113153113494
assert( pExpr->op==TK_COLLATE
113154113495
|| pExpr->op==TK_IF_NULL_ROW
113155113496
|| (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) );
@@ -114665,12 +115006,12 @@
114665115006
**
114666115007
** The return value includes space to duplicate all Expr nodes in the
114667115008
** tree formed by Expr.pLeft and Expr.pRight, but not any other
114668115009
** substructure such as Expr.x.pList, Expr.x.pSelect, and Expr.y.pWin.
114669115010
*/
114670
-static int dupedExprSize(const Expr *p){
114671
- int nByte;
115011
+static u64 dupedExprSize(const Expr *p){
115012
+ u64 nByte;
114672115013
assert( p!=0 );
114673115014
nByte = dupedExprNodeSize(p, EXPRDUP_REDUCE);
114674115015
if( p->pLeft ) nByte += dupedExprSize(p->pLeft);
114675115016
if( p->pRight ) nByte += dupedExprSize(p->pRight);
114676115017
assert( nByte==ROUND8(nByte) );
@@ -114723,11 +115064,11 @@
114723115064
#endif
114724115065
staticFlag = EP_Static;
114725115066
assert( sEdupBuf.zAlloc!=0 );
114726115067
assert( dupFlags==EXPRDUP_REDUCE );
114727115068
}else{
114728
- int nAlloc;
115069
+ u64 nAlloc;
114729115070
if( dupFlags ){
114730115071
nAlloc = dupedExprSize(p);
114731115072
}else if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
114732115073
nToken = sqlite3Strlen30NN(p->u.zToken)+1;
114733115074
nAlloc = ROUND8(EXPR_FULLSIZE + nToken);
@@ -115392,23 +115733,10 @@
115392115733
m |= pExpr->flags;
115393115734
}
115394115735
return m;
115395115736
}
115396115737
115397
-/*
115398
-** This is a SELECT-node callback for the expression walker that
115399
-** always "fails". By "fail" in this case, we mean set
115400
-** pWalker->eCode to zero and abort.
115401
-**
115402
-** This callback is used by multiple expression walkers.
115403
-*/
115404
-SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
115405
- UNUSED_PARAMETER(NotUsed);
115406
- pWalker->eCode = 0;
115407
- return WRC_Abort;
115408
-}
115409
-
115410115738
/*
115411115739
** Check the input string to see if it is "true" or "false" (in any case).
115412115740
**
115413115741
** If the string is.... Return
115414115742
** "true" EP_IsTrue
@@ -115702,10 +116030,22 @@
115702116030
case TK_IS:
115703116031
case TK_ISNOT:
115704116032
if( pWalker->eCode==6 ){
115705116033
pWalker->eCode = 0;
115706116034
return WRC_Abort;
116035
+ }
116036
+ if( pWalker->eCode==4 || pWalker->eCode==5 ){
116037
+ /* This is a DEFAULT expression. As it will never be name resolved,
116038
+ ** attempt the the TK_IS -> TK_TRUTH transform here. */
116039
+ Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);
116040
+ if( ALWAYS(pRight) ){
116041
+ if( pRight->op==TK_ID ) sqlite3ExprIdToTrueFalse(pRight);
116042
+ if( pRight->op==TK_TRUEFALSE ){
116043
+ pExpr->op2 = pExpr->op;
116044
+ pExpr->op = TK_TRUTH;
116045
+ }
116046
+ }
115707116047
}
115708116048
return WRC_Continue;
115709116049
case TK_VARIABLE:
115710116050
if( pWalker->eCode==5 ){
115711116051
/* Silently convert bound parameters that appear inside of CREATE
@@ -115907,35 +116247,157 @@
115907116247
}
115908116248
/* Rules (1), (2a), and (2b) handled by the following: */
115909116249
return sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor, bAllowSubq);
115910116250
}
115911116251
116252
+
116253
+/*
116254
+** Return true if pExpr is a copy of a term of pGroupBy that sorts using
116255
+** the BINARY collating sequence.
116256
+*/
116257
+static int exprIsBinaryGroupByTerm(
116258
+ Parse *pParse,
116259
+ Expr *pExpr,
116260
+ ExprList *pGroupBy
116261
+){
116262
+ int i;
116263
+ for(i=0; i<pGroupBy->nExpr; i++){
116264
+ Expr *p = pGroupBy->a[i].pExpr;
116265
+ if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
116266
+ CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, p);
116267
+ if( sqlite3IsBinary(pColl) ) return 1;
116268
+ }
116269
+ }
116270
+ return 0;
116271
+}
116272
+
116273
+/*
116274
+** Bits returned by exprScanOperand().
116275
+*/
116276
+#define GBOP_GROUPBY 0x01 /* The operand is a GROUP BY term */
116277
+#define GBOP_INEXACT 0x02 /* That GROUP BY term might be a number */
116278
+#define GBOP_NOAFF 0x04 /* That GROUP BY term has no affinity */
116279
+#define GBOP_TEXT 0x08 /* The operand has TEXT affinity */
116280
+
116281
+/*
116282
+** Inspect operand pOp of an operator and return a mask of GBOP_* bits that
116283
+** describe it. GBOP_GROUPBY is set if pOp is a GROUP BY term. Then
116284
+** GBOP_INEXACT is also set if that term might be a number, and GBOP_NOAFF
116285
+** if it has no affinity. GBOP_TEXT is set if pOp has TEXT affinity.
116286
+*/
116287
+static int exprScanOperand(Walker *pWalker, Expr *pOp){
116288
+ int m = 0;
116289
+ if( pOp ){
116290
+ char aff = sqlite3ExprAffinity(pOp);
116291
+ if( exprIsBinaryGroupByTerm(pWalker->pParse, pOp, pWalker->u.pGroupBy) ){
116292
+ m |= GBOP_GROUPBY;
116293
+ if( aff<=SQLITE_AFF_NONE ) m |= GBOP_NOAFF;
116294
+ if( aff!=SQLITE_AFF_TEXT && pOp->op!=TK_CONCAT ) m |= GBOP_INEXACT;
116295
+ }
116296
+ if( aff==SQLITE_AFF_TEXT ) m |= GBOP_TEXT;
116297
+ }
116298
+ return m;
116299
+}
116300
+
116301
+/*
116302
+** pExpr is not itself a GROUP BY term. Return true if it has an operand
116303
+** that is a GROUP BY term, and the value of pExpr might depend on which
116304
+** member of a group that operand was taken from.
116305
+**
116306
+** The rows of a group are equal in the GROUP BY sense but are not always
116307
+** identical. With the BINARY collating sequence, two values in the same
116308
+** group can still differ in type: 1 and 1.0 (also -0.0 and 0.0) are in the
116309
+** same group. So typeof(x), length(x), x||'', x/2, x+1 and so forth can
116310
+** have a different value for different rows of one group. A GROUP BY
116311
+** term that might be a number may therefore only be an operand of a
116312
+** comparison, because comparisons treat values that are equal as
116313
+** interchangeable, or of a logical operator. A GROUP BY term that is
116314
+** always TEXT or BLOB (the result of the || operator, or a column or CAST
116315
+** with TEXT affinity) can be an operand of anything, since equal text
116316
+** values are identical.
116317
+**
116318
+** The exception for comparisons is a comparison of a GROUP BY term that
116319
+** has no affinity (an expression, not a column) against a TEXT operand.
116320
+** TEXT affinity is applied to the term and converts 1 to '1' but 1.0 to
116321
+** '1.0'.
116322
+*/
116323
+static int exprGroupByOperandUnsafe(Walker *pWalker, Expr *pExpr){
116324
+ int bCmp = 0; /* True for a comparison operator */
116325
+ int bOther = 0; /* True for any operator or function that is not a
116326
+ ** comparison or a logical operator */
116327
+ int m = 0; /* Union of the GBOP_* bits for all operands */
116328
+ int i;
116329
+
116330
+ switch( pExpr->op ){
116331
+ case TK_EQ: case TK_NE: case TK_LT: case TK_LE:
116332
+ case TK_GT: case TK_GE: case TK_IS: case TK_ISNOT:
116333
+ case TK_IN: case TK_BETWEEN: {
116334
+ testcase( pExpr->op==TK_EQ ); testcase( pExpr->op==TK_NE );
116335
+ testcase( pExpr->op==TK_LT ); testcase( pExpr->op==TK_LE );
116336
+ testcase( pExpr->op==TK_GT ); testcase( pExpr->op==TK_GE );
116337
+ testcase( pExpr->op==TK_IS ); testcase( pExpr->op==TK_ISNOT );
116338
+ testcase( pExpr->op==TK_IN ); testcase( pExpr->op==TK_BETWEEN );
116339
+ bCmp = 1;
116340
+ break;
116341
+ }
116342
+ case TK_ISNULL: case TK_NOTNULL: case TK_AND: case TK_OR: case TK_NOT: {
116343
+ testcase( pExpr->op==TK_ISNULL ); testcase( pExpr->op==TK_NOTNULL );
116344
+ testcase( pExpr->op==TK_AND ); testcase( pExpr->op==TK_OR );
116345
+ testcase( pExpr->op==TK_NOT );
116346
+ break;
116347
+ }
116348
+ default: {
116349
+ bOther = 1;
116350
+ break;
116351
+ }
116352
+ }
116353
+ m |= exprScanOperand(pWalker, pExpr->pLeft);
116354
+ m |= exprScanOperand(pWalker, pExpr->pRight);
116355
+ assert( ExprUseXList(pExpr) ); /* Sub-selects were handled by the caller */
116356
+ if( pExpr->x.pList ){
116357
+ for(i=0; i<pExpr->x.pList->nExpr; i++){
116358
+ m |= exprScanOperand(pWalker, pExpr->x.pList->a[i].pExpr);
116359
+ }
116360
+ }
116361
+ if( (m & GBOP_GROUPBY)==0 ) return 0;
116362
+
116363
+ /* Any other operator or function is unsafe if it has an operand that
116364
+ ** is a GROUP BY term that might be a number. */
116365
+ if( bOther ) return (m & GBOP_INEXACT)!=0;
116366
+
116367
+ /* A comparison is unsafe if a GROUP BY operand without affinity is
116368
+ ** compared against an operand with TEXT affinity. */
116369
+ testcase( (m & (GBOP_NOAFF|GBOP_TEXT))==0 );
116370
+ testcase( (m & (GBOP_NOAFF|GBOP_TEXT))==GBOP_NOAFF );
116371
+ testcase( (m & (GBOP_NOAFF|GBOP_TEXT))==GBOP_TEXT );
116372
+ return bCmp && (m & (GBOP_NOAFF|GBOP_TEXT))==(GBOP_NOAFF|GBOP_TEXT);
116373
+}
115912116374
115913116375
/*
115914116376
** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
115915116377
*/
115916116378
static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
115917116379
ExprList *pGroupBy = pWalker->u.pGroupBy;
115918
- int i;
115919116380
115920116381
/* Check if pExpr is identical to any GROUP BY term. If so, consider
115921116382
** it constant. */
115922
- for(i=0; i<pGroupBy->nExpr; i++){
115923
- Expr *p = pGroupBy->a[i].pExpr;
115924
- if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
115925
- CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
115926
- if( sqlite3IsBinary(pColl) ){
115927
- return WRC_Prune;
115928
- }
115929
- }
116383
+ if( exprIsBinaryGroupByTerm(pWalker->pParse, pExpr, pGroupBy) ){
116384
+ return WRC_Prune;
115930116385
}
115931116386
115932116387
/* Check if pExpr is a sub-select. If so, consider it variable. */
115933116388
if( ExprUseXSelect(pExpr) ){
115934116389
pWalker->eCode = 0;
115935116390
return WRC_Abort;
115936116391
}
116392
+
116393
+ /* An operator applied to a GROUP BY term is constant only if its value
116394
+ ** is the same for every member of a group. */
116395
+ if( exprGroupByOperandUnsafe(pWalker, pExpr) ){
116396
+ pWalker->eCode = 0;
116397
+ return WRC_Abort;
116398
+ }
115937116399
115938116400
return exprNodeIsConstant(pWalker, pExpr);
115939116401
}
115940116402
115941116403
/*
@@ -115944,20 +116406,29 @@
115944116406
** in pGroupBy that sort with the BINARY collation sequence.
115945116407
**
115946116408
** This routine is used to determine if a term of the HAVING clause can
115947116409
** be promoted into the WHERE clause. In order for such a promotion to work,
115948116410
** the value of the HAVING clause term must be the same for all members of
115949
-** a "group". The requirement that the GROUP BY term must be BINARY
115950
-** assumes that no other collating sequence will have a finer-grained
115951
-** grouping than binary. In other words (A=B COLLATE binary) implies
115952
-** A=B in every other collating sequence. The requirement that the
115953
-** GROUP BY be BINARY is stricter than necessary. It would also work
115954
-** to promote HAVING clauses that use the same alternative collating
115955
-** sequence as the GROUP BY term, but that is much harder to check,
115956
-** alternative collating sequences are uncommon, and this is only an
115957
-** optimization, so we take the easy way out and simply require the
115958
-** GROUP BY to use the BINARY collating sequence.
116411
+** a "group". There are two requirements for this.
116412
+**
116413
+** (1) Members of a group are equal in the sense of the GROUP BY collating
116414
+** sequence, but need not be identical. The requirement that the
116415
+** GROUP BY term be BINARY assumes that no other collating sequence
116416
+** will have a finer-grained grouping than binary. In other words
116417
+** (A=B COLLATE binary) implies A=B in every other collating sequence.
116418
+** The requirement that the GROUP BY be BINARY is stricter than
116419
+** necessary. It would also work to promote HAVING clauses that use the
116420
+** same alternative collating sequence as the GROUP BY term, but that
116421
+** is much harder to check, alternative collating sequences are
116422
+** uncommon, and this is only an optimization, so we take the easy way
116423
+** out and simply require the GROUP BY to use the BINARY collating
116424
+** sequence.
116425
+**
116426
+** (2) Even with BINARY, equal values can be distinguishable, as in the
116427
+** case of 1 and 1.0. A GROUP BY term may therefore only be used as
116428
+** an operand of a comparison or logical operator. See
116429
+** exprGroupByOperandUnsafe() for details.
115959116430
*/
115960116431
SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
115961116432
Walker w;
115962116433
w.eCode = 1;
115963116434
w.xExprCallback = exprNodeIsConstantOrGroupBy;
@@ -116617,10 +117088,15 @@
116617117088
#ifndef SQLITE_OMIT_SUBQUERY
116618117089
/*
116619117090
** Argument pExpr is an (?, ?...) IN(...) expression. This
116620117091
** function allocates and returns a nul-terminated string containing
116621117092
** the affinities to be used for each column of the comparison.
117093
+**
117094
+** NUMERIC affinity is used in place of REAL. Within a comparison the
117095
+** two are the same, except that REAL affinity (as applied by OP_Affinity
117096
+** and OP_MakeRecord) converts integers into floating point, and that
117097
+** might change the value of a large integer.
116622117098
**
116623117099
** It is the responsibility of the caller to ensure that the returned
116624117100
** string is eventually freed using sqlite3DbFree().
116625117101
*/
116626117102
static char *exprINAffinity(Parse *pParse, const Expr *pExpr){
@@ -116639,10 +117115,11 @@
116639117115
if( pSelect ){
116640117116
zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
116641117117
}else{
116642117118
zRet[i] = a;
116643117119
}
117120
+ if( zRet[i]==SQLITE_AFF_REAL ) zRet[i] = SQLITE_AFF_NUMERIC;
116644117121
}
116645117122
zRet[nVal] = '\0';
116646117123
}
116647117124
return zRet;
116648117125
}
@@ -117115,11 +117592,11 @@
117115117592
}
117116117593
sqlite3ExprDeferredDelete(pParse, pLeft);
117117117594
pSel->pLimit->pLeft = pLimit;
117118117595
}
117119117596
}else{
117120
- /* If there is no pre-existing limit add a limit of 1 */
117597
+ /* If there is no limit add a limit of 1. (tag-202611101908) */
117121117598
pLimit = sqlite3ExprInt32(pParse->db, 1);
117122117599
pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
117123117600
}
117124117601
pSel->iLimit = 0;
117125117602
if( sqlite3Select(pParse, pSel, &dest) ){
@@ -117435,13 +117912,14 @@
117435117912
**
117436117913
** For a scalar LHS, it is sufficient to check just the first row
117437117914
** of the RHS.
117438117915
*/
117439117916
if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
117440
- if( eType==IN_INDEX_INDEX_DESC ){
117917
+ if( eType==IN_INDEX_INDEX_DESC && nVector==1 ){
117441117918
addrTop = sqlite3VdbeAddOp2(v, OP_Last, iTab, destIfFalse);
117442117919
}else{
117920
+ testcase( eType==IN_INDEX_INDEX_DESC );
117443117921
testcase( eType==IN_INDEX_EPH );
117444117922
testcase( eType==IN_INDEX_ROWID );
117445117923
addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
117446117924
}
117447117925
VdbeCoverage(v);
@@ -117953,10 +118431,34 @@
117953118431
w.xExprCallback = exprNodeCanReturnSubtype;
117954118432
sqlite3WalkExpr(&w, pExpr);
117955118433
return w.eCode;
117956118434
}
117957118435
118436
+/*
118437
+** Return 0 iff the expression in IndexedExpr object p is identical to
118438
+** expression pExpr, and the affinity is such that an entry read from
118439
+** the index may be substituted for pExpr in any context. Otherwise
118440
+** return non-zero.
118441
+*/
118442
+static int indexedExprCompare(
118443
+ IndexedExpr *p, /* Indexed expression */
118444
+ Expr *pExpr, /* Expression to compare to p */
118445
+ int iDataCur /* iTab argument for ExprCompare() */
118446
+){
118447
+ u8 exprAff;
118448
+ if( sqlite3ExprCompare(0, pExpr, p->pExpr, iDataCur)!=0 ) return 1;
118449
+ assert( p->aff>=SQLITE_AFF_BLOB && p->aff<=SQLITE_AFF_NUMERIC );
118450
+ exprAff = sqlite3ExprAffinity(pExpr);
118451
+ if( (exprAff<=SQLITE_AFF_BLOB && p->aff!=SQLITE_AFF_BLOB)
118452
+ || (exprAff==SQLITE_AFF_TEXT && p->aff!=SQLITE_AFF_TEXT)
118453
+ || (exprAff>=SQLITE_AFF_NUMERIC && p->aff!=SQLITE_AFF_NUMERIC)
118454
+ ){
118455
+ /* Affinity mismatch on a generated column */
118456
+ return 1;
118457
+ }
118458
+ return 0;
118459
+}
117958118460
117959118461
/*
117960118462
** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr.
117961118463
** If it is, then resolve the expression by reading from the index and
117962118464
** return the register into which the value has been read. If pExpr is
@@ -117967,29 +118469,19 @@
117967118469
Expr *pExpr, /* The expression to potentially bypass */
117968118470
int target /* Where to store the result of the expression */
117969118471
){
117970118472
IndexedExpr *p;
117971118473
Vdbe *v;
118474
+
117972118475
for(p=pParse->pIdxEpr; p; p=p->pIENext){
117973
- u8 exprAff;
117974118476
int iDataCur = p->iDataCur;
117975118477
if( iDataCur<0 ) continue;
117976118478
if( pParse->iSelfTab ){
117977118479
if( p->iDataCur!=pParse->iSelfTab-1 ) continue;
117978118480
iDataCur = -1;
117979118481
}
117980
- if( sqlite3ExprCompare(0, pExpr, p->pExpr, iDataCur)!=0 ) continue;
117981
- assert( p->aff>=SQLITE_AFF_BLOB && p->aff<=SQLITE_AFF_NUMERIC );
117982
- exprAff = sqlite3ExprAffinity(pExpr);
117983
- if( (exprAff<=SQLITE_AFF_BLOB && p->aff!=SQLITE_AFF_BLOB)
117984
- || (exprAff==SQLITE_AFF_TEXT && p->aff!=SQLITE_AFF_TEXT)
117985
- || (exprAff>=SQLITE_AFF_NUMERIC && p->aff!=SQLITE_AFF_NUMERIC)
117986
- ){
117987
- /* Affinity mismatch on a generated column */
117988
- continue;
117989
- }
117990
-
118482
+ if( indexedExprCompare(p, pExpr, iDataCur)!=0 ) continue;
117991118483
117992118484
/* Functions that might set a subtype should not be replaced by the
117993118485
** value taken from an expression index if they are themselves an
117994118486
** argument to another scalar function or aggregate.
117995118487
** https://sqlite.org/forum/forumpost/68d284c86b082c3e */
@@ -117996,23 +118488,24 @@
117996118488
if( ExprHasProperty(pExpr, EP_SubtArg)
117997118489
&& sqlite3ExprCanReturnSubtype(pParse, pExpr)
117998118490
){
117999118491
continue;
118000118492
}
118493
+
118494
+ /* Do not read the value from an index if the expression is a constant.
118495
+ ** This prevents an attempt to use an index value outside of the loop that
118496
+ ** uses the index. (Bugs 2026-10-11T19:26:40Z and 2026-11-03T02:12:43Z). */
118497
+ if( sqlite3ExprIsConstant(pParse, pExpr) ){
118498
+ return -1;
118499
+ }
118001118500
118002118501
v = pParse->pVdbe;
118003118502
assert( v!=0 );
118004
- if( p->bMaybeNullRow || sqlite3ExprIsConstant(pParse, pExpr) ){
118503
+ if( p->bMaybeNullRow ){
118005118504
/* The value of pExpr should be computed from the original expression,
118006
- ** not from the index, if either:
118007
- **
118008
- ** 1. The index might be on a NULL row due to an outer join.
118009
- **
118010
- ** 2. The expression is a constant. This prevents an attempt to
118011
- ** use an index value outside of the loop that positions the
118012
- ** index. (Bug 2026-10-11T19:26:40Z).
118013
- */
118505
+ ** not from the index, if the index might be on a NULL row due to an
118506
+ ** outer join. */
118014118507
int addr = sqlite3VdbeCurrentAddr(v);
118015118508
sqlite3VdbeAddOp3(v, OP_IfNullRow, p->iIdxCur, addr+3, target);
118016118509
VdbeCoverage(v);
118017118510
sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
118018118511
VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
@@ -118047,13 +118540,17 @@
118047118540
for(p=pParse->pIdxPartExpr; p; p=p->pIENext){
118048118541
if( pExpr->iColumn==p->iIdxCol && pExpr->iTable==p->iDataCur ){
118049118542
Vdbe *v = pParse->pVdbe;
118050118543
int addr = 0;
118051118544
int ret;
118545
+ u8 okConstFactor = pParse->okConstFactor;
118052118546
118053118547
if( p->bMaybeNullRow ){
118548
+ /* OP_IfNullRow can overwrite the result register with NULL, so the
118549
+ ** value must be recomputed each time, not factored out. */
118054118550
addr = sqlite3VdbeAddOp1(v, OP_IfNullRow, p->iIdxCur);
118551
+ pParse->okConstFactor = 0;
118055118552
}
118056118553
ret = sqlite3ExprCodeTarget(pParse, p->pExpr, iTarget);
118057118554
sqlite3VdbeAddOp4(pParse->pVdbe, OP_Affinity, ret, 1, 0,
118058118555
(const char*)&p->aff, 1);
118059118556
if( sqlite3ExprCanReturnSubtype(pParse, p->pExpr) ){
@@ -118060,10 +118557,11 @@
118060118557
/* If the expression value may have a sub-type, clear it. Values
118061118558
** read from columns do not have subtypes. */
118062118559
sqlite3VdbeAddOp1(pParse->pVdbe, OP_ClrSubtype, ret);
118063118560
}
118064118561
if( addr ){
118562
+ pParse->okConstFactor = okConstFactor;
118065118563
sqlite3VdbeJumpHere(v, addr);
118066118564
sqlite3VdbeChangeP3(v, addr, ret);
118067118565
}
118068118566
return ret;
118069118567
}
@@ -118187,11 +118685,11 @@
118187118685
case TK_AGG_COLUMN: {
118188118686
AggInfo *pAggInfo = pExpr->pAggInfo;
118189118687
struct AggInfo_col *pCol;
118190118688
assert( pAggInfo!=0 );
118191118689
assert( pExpr->iAgg>=0 );
118192
- if( pExpr->iAgg>=pAggInfo->nColumn ){
118690
+ if( NEVER(pExpr->iAgg>=pAggInfo->nColumn) ){
118193118691
/* Happens when the left table of a RIGHT JOIN is null and
118194118692
** is using an expression index */
118195118693
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
118196118694
#ifdef SQLITE_VDBE_COVERAGE
118197118695
/* Verify that the OP_Null above is exercised by tests
@@ -118963,11 +119461,11 @@
118963119461
assert( pExpr->affExpr==OE_Rollback
118964119462
|| pExpr->affExpr==OE_Abort
118965119463
|| pExpr->affExpr==OE_Fail
118966119464
|| pExpr->affExpr==OE_Ignore
118967119465
);
118968
- if( !pParse->pTriggerTab && !pParse->nested ){
119466
+ if( !pParse->pTriggerTab ){
118969119467
sqlite3ErrorMsg(pParse,
118970119468
"RAISE() may only be used within a trigger-program");
118971119469
return 0;
118972119470
}
118973119471
if( pExpr->affExpr==OE_Abort ){
@@ -118977,12 +119475,11 @@
118977119475
if( pExpr->affExpr==OE_Ignore ){
118978119476
sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, OE_Ignore);
118979119477
VdbeCoverage(v);
118980119478
}else{
118981119479
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
118982
- sqlite3VdbeAddOp3(v, OP_Halt,
118983
- pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
119480
+ sqlite3VdbeAddOp3(v, OP_Halt, SQLITE_CONSTRAINT_TRIGGER,
118984119481
pExpr->affExpr, r1);
118985119482
}
118986119483
break;
118987119484
}
118988119485
#endif
@@ -119736,14 +120233,22 @@
119736120233
if( pR ){
119737120234
iVar = pVar->iColumn;
119738120235
sqlite3VdbeReprepareOnBind(pParse->pVdbe, iVar, 0);
119739120236
pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
119740120237
if( pL ){
120238
+ int eType;
119741120239
if( sqlite3_value_type(pL)==SQLITE_TEXT ){
119742120240
sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
119743120241
}
119744
- res = sqlite3MemCompare(pL, pR, 0) ? 2 : 0;
120242
+ /* The bound value and the literal must be interchangeable, not
120243
+ ** just compare equal. For example, integer 1 and real 1.0 are equal
120244
+ ** according to MemCompare(), but are different if TEXT affinity
120245
+ ** is applied to them. */
120246
+ eType = sqlite3_value_type(pL);
120247
+ if( eType==sqlite3_value_type(pR) && sqlite3MemCompare(pL, pR, 0)==0 ){
120248
+ res = 0;
120249
+ }
119745120250
}
119746120251
sqlite3ValueFree(pR);
119747120252
sqlite3ValueFree(pL);
119748120253
}
119749120254
return res;
@@ -120629,14 +121134,24 @@
120629121134
IndexedExpr *pIEpr;
120630121135
Expr tmp;
120631121136
assert( pParse->iSelfTab==0 );
120632121137
if( (pNC->ncFlags & NC_InAggFunc)==0 ) break;
120633121138
if( pParse->pIdxEpr==0 ) break;
121139
+ if( pWalker->walkerDepth>0 ){
121140
+ break; /* See bug report 2026-11-07T18:33:11Z */
121141
+ }
120634121142
for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
120635121143
int iDataCur = pIEpr->iDataCur;
120636121144
if( iDataCur<0 ) continue;
120637
- if( sqlite3ExprCompare(0, pExpr, pIEpr->pExpr, iDataCur)==0 ) break;
121145
+ /* If the index might be on the NULL row of an outer join, then the
121146
+ ** expression must not be replaced by a plain read of the index
121147
+ ** column, as the value of the expression on the NULL row is not
121148
+ ** necessarily NULL. In many cases (when the GROUP BY is not
121149
+ ** using temp b-tree to sort), sqlite3IndexedExprLookup() will make
121150
+ ** the same substitution later on anyway. */
121151
+ if( pIEpr->bMaybeNullRow ) continue;
121152
+ if( indexedExprCompare(pIEpr, pExpr, iDataCur)==0 ) break;
120638121153
}
120639121154
if( pIEpr==0 ) break;
120640121155
if( NEVER(!ExprUseYTab(pExpr)) ) break;
120641121156
for(i=0; i<pSrcList->nSrc; i++){
120642121157
if( pSrcList->a[i].iCursor==pIEpr->iDataCur ){
@@ -120644,10 +121159,15 @@
120644121159
break;
120645121160
}
120646121161
}
120647121162
if( i>=pSrcList->nSrc ) break;
120648121163
if( NEVER(pExpr->pAggInfo!=0) ) break; /* Resolved by outer context */
121164
+ if( ExprHasProperty(pExpr, EP_SubtArg)
121165
+ && sqlite3ExprCanReturnSubtype(pParse, pExpr)
121166
+ ){
121167
+ break;
121168
+ }
120649121169
if( pParse->nErr ){ return WRC_Abort; }
120650121170
120651121171
/* If we reach this point, it means that expression pExpr can be
120652121172
** translated into a reference to an index column as described by
120653121173
** pIEpr.
@@ -121112,11 +121632,11 @@
121112121632
** that the table is being renamed to.
121113121633
*/
121114121634
if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
121115121635
goto exit_rename_table;
121116121636
}
121117
- if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){
121637
+ if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName,zDb) ){
121118121638
goto exit_rename_table;
121119121639
}
121120121640
121121121641
#ifndef SQLITE_OMIT_VIEW
121122121642
if( IsView(pTab) ){
@@ -121157,35 +121677,35 @@
121157121677
/* figure out how many UTF-8 characters are in zName */
121158121678
zTabName = pTab->zName;
121159121679
nTabName = sqlite3Utf8CharLen(zTabName, -1);
121160121680
121161121681
/* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
121162
- ** the schema to use the new table name. */
121682
+ ** the schema to use the new table name, and update the tbl_name and
121683
+ ** name columns as required. */
121163121684
sqlite3NestedParse(pParse,
121164121685
"UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
121165
- "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
121166
- "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
121167
- "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
121168
- , zDb, zDb, zTabName, zName, (iDb==1), zTabName
121169
- );
121170
-
121171
- /* Update the tbl_name and name columns of the sqlite_schema table
121172
- ** as required. */
121173
- sqlite3NestedParse(pParse,
121174
- "UPDATE %Q." LEGACY_SCHEMA_TABLE " SET "
121175
- "tbl_name = %Q, "
121176
- "name = CASE "
121177
- "WHEN type='table' THEN %Q "
121178
- "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
121179
- " AND type='index' THEN "
121180
- "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
121181
- "ELSE name END "
121182
- "WHERE tbl_name=%Q COLLATE nocase AND "
121183
- "(type='table' OR type='index' OR type='trigger');",
121184
- zDb,
121185
- zName, zName, zName,
121186
- nTabName, zTabName
121686
+ "sql = CASE WHEN type='index' AND "
121687
+ "name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' THEN sql "
121688
+ "ELSE sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) END, "
121689
+ "tbl_name = CASE "
121690
+ "WHEN tbl_name=%Q COLLATE nocase AND (type!='trigger' OR %d=0 OR "
121691
+ " sqlite_rename_test(%Q, sql, type, name, 1, 'after rename', 0)) "
121692
+ "THEN %Q ELSE tbl_name END, "
121693
+ "name = CASE "
121694
+ "WHEN type='table' AND tbl_name=%Q COLLATE nocase THEN %Q "
121695
+ "WHEN type='index' AND name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
121696
+ "THEN 'sqlite_autoindex_' || %Q || substr(name,%d+18) "
121697
+ "ELSE name END "
121698
+ "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase) "
121699
+ "AND (name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
121700
+ "OR (type='index' AND name LIKE 'sqliteX_autoindex%%' ESCAPE 'X'))"
121701
+ , zDb,
121702
+ zDb, zTabName, zName, (iDb==1),
121703
+ zTabName, (iDb==1), zDb, zName,
121704
+ zTabName, zName,
121705
+ zName, nTabName,
121706
+ zTabName
121187121707
);
121188121708
121189121709
#ifndef SQLITE_OMIT_AUTOINCREMENT
121190121710
/* If the sqlite_sequence table exists in this database, then update
121191121711
** it with the new table name.
@@ -121242,11 +121762,11 @@
121242121762
const char *zDb, /* Schema holding the table */
121243121763
const char *zTab, /* Table to check for empty */
121244121764
const char *zErr /* Error message text */
121245121765
){
121246121766
sqlite3NestedParse(pParse,
121247
- "SELECT raise(ABORT,%Q) FROM \"%w\".\"%w\"",
121767
+ "SELECT sqlite_fail(%Q, 1) FROM \"%w\".\"%w\"",
121248121768
zErr, zDb, zTab
121249121769
);
121250121770
}
121251121771
121252121772
/*
@@ -121270,10 +121790,55 @@
121270121790
}
121271121791
return SQLITE_OK;
121272121792
}
121273121793
121274121794
121795
+
121796
+/*
121797
+** Buffer pFrag, which is nFrag bytes in size, contains a fragment of
121798
+** SQL that will be inserted into a CREATE TABLE statement. If successful, this
121799
+** function returns the size of the buffer in bytes not including any trailing
121800
+** whitespace, semicolons, "--" style comments or unterminated C-style
121801
+** comments. Or, if an OOM occurs, it returns 0 and sets db->mallocFailed to
121802
+** true.
121803
+**
121804
+** Terminated C-style comments at the end are preserved. "--" style
121805
+** comments and unterminated C-style comments are removed because otherwise
121806
+** inserting pFrag[] into the middle of a larger SQL statement without a
121807
+** comment terminator will mess up its syntax.
121808
+*/
121809
+static int alterRtrimFragment(
121810
+ sqlite3 *db, /* used to record OOM error */
121811
+ const char *pFrag, /* Buffer containing SQL fragment */
121812
+ int nFrag /* Size of pFrag in bytes */
121813
+){
121814
+ u8 *zTmp = (u8*)sqlite3MPrintf(db, "%.*s", nFrag, pFrag);
121815
+ int iOff = 0;
121816
+ int iEnd = 0;
121817
+
121818
+ if( zTmp==0 ) return 0;
121819
+
121820
+ while( 1 ){
121821
+ int t = 0;
121822
+ int nToken = sqlite3GetToken(&zTmp[iOff], &t);
121823
+ if( t==TK_ILLEGAL ) break;
121824
+ if( t==TK_COMMENT ){
121825
+ /* Ignore all but properly terminated C-style comments */
121826
+ if( zTmp[iOff]=='/' && nToken>=4
121827
+ && zTmp[iOff+nToken-2]=='*' && zTmp[iOff+nToken-1]=='/'
121828
+ ){
121829
+ iEnd = iOff+nToken;
121830
+ }
121831
+ }else if( t!=TK_SPACE && t!=TK_SEMI ){
121832
+ iEnd = iOff+nToken;
121833
+ }
121834
+ iOff += nToken;
121835
+ }
121836
+
121837
+ sqlite3DbFree(db, zTmp);
121838
+ return iEnd;
121839
+}
121275121840
121276121841
/*
121277121842
** This function is called after an "ALTER TABLE ... ADD" statement
121278121843
** has been parsed. Argument pColDef contains the text of the new
121279121844
** column definition.
@@ -121286,10 +121851,11 @@
121286121851
Table *pTab; /* Table being altered */
121287121852
int iDb; /* Database number */
121288121853
const char *zDb; /* Database name */
121289121854
const char *zTab; /* Table name */
121290121855
char *zCol; /* Null-terminated column definition */
121856
+ int nCol; /* Size of zCol in bytes */
121291121857
Column *pCol; /* The new column */
121292121858
Expr *pDflt; /* Default value for the new column */
121293121859
sqlite3 *db; /* The database connection; */
121294121860
Vdbe *v; /* The prepared statement under construction */
121295121861
int r1; /* Temporary registers */
@@ -121331,32 +121897,16 @@
121331121897
"Cannot add a UNIQUE column");
121332121898
return;
121333121899
}
121334121900
if( isRowidAlias(pParse, pTab, pCol->zCnName, "add") ) return;
121335121901
if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
121336
- /* If the default value for the new column was specified with a
121337
- ** literal NULL, then set pDflt to 0. This simplifies checking
121338
- ** for an SQL NULL default below.
121339
- */
121340121902
assert( pDflt==0 || pDflt->op==TK_SPAN );
121341
- if( pDflt && pDflt->pLeft->op==TK_NULL ){
121342
- pDflt = 0;
121343
- }
121344
- assert( IsOrdinaryTable(pNew) );
121345
- if( (db->flags&SQLITE_ForeignKeys) && pNew->u.tab.pFKey && pDflt ){
121346
- sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
121347
- "Cannot add a REFERENCES column with non-NULL default value");
121348
- }
121349
- if( pCol->notNull && !pDflt ){
121350
- sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
121351
- "Cannot add a NOT NULL column with default value NULL");
121352
- }
121353
-
121354
-
121355
- /* Ensure the default expression is something that sqlite3ValueFromExpr()
121356
- ** can handle (i.e. not CURRENT_TIME etc.)
121357
- */
121903
+
121904
+ /* Ensure the default expression, if any, is something that
121905
+ ** sqlite3ValueFromExpr() can handle (i.e. not CURRENT_TIME etc.).
121906
+ ** If the default expression evaluates to NULL, then set pDflt to
121907
+ ** 0. This simplifies the checks below. */
121358121908
if( pDflt ){
121359121909
sqlite3_value *pVal = 0;
121360121910
int rc;
121361121911
rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
121362121912
assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
@@ -121365,25 +121915,35 @@
121365121915
return;
121366121916
}
121367121917
if( !pVal ){
121368121918
sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
121369121919
"Cannot add a column with non-constant default");
121920
+ }else if( sqlite3_value_type(pVal)==SQLITE_NULL ){
121921
+ pDflt = 0;
121370121922
}
121371121923
sqlite3ValueFree(pVal);
121372121924
}
121925
+
121926
+ assert( IsOrdinaryTable(pNew) );
121927
+ if( (db->flags&SQLITE_ForeignKeys) && pNew->u.tab.pFKey && pDflt ){
121928
+ sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
121929
+ "Cannot add a REFERENCES column with non-NULL default value");
121930
+ }
121931
+ if( pCol->notNull && !pDflt ){
121932
+ sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
121933
+ "Cannot add a NOT NULL column with default value NULL");
121934
+ }
121935
+
121373121936
}else if( pCol->colFlags & COLFLAG_STORED ){
121374121937
sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column");
121375121938
}
121376121939
121377121940
121378121941
/* Modify the CREATE TABLE statement. */
121379
- zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
121942
+ nCol = alterRtrimFragment(db, (char*)pColDef->z, pColDef->n);
121943
+ zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, nCol);
121380121944
if( zCol ){
121381
- char *zEnd = &zCol[pColDef->n-1];
121382
- while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
121383
- *zEnd-- = '\0';
121384
- }
121385121945
/* substr() operations on characters, but addColOffset is in bytes. So we
121386121946
** have to use printf() to translate between these units: */
121387121947
assert( IsOrdinaryTable(pTab) );
121388121948
assert( IsOrdinaryTable(pNew) );
121389121949
sqlite3NestedParse(pParse,
@@ -121397,10 +121957,13 @@
121397121957
sqlite3DbFree(db, zCol);
121398121958
}
121399121959
121400121960
v = sqlite3GetVdbe(pParse);
121401121961
if( v ){
121962
+ int isStrict = pTab->tabFlags & TF_Strict;
121963
+ int isGen = (pCol->colFlags & COLFLAG_GENERATED)!=0;
121964
+
121402121965
/* Make sure the schema version is at least 3. But do not upgrade
121403121966
** from less than 3 to 4, as that will corrupt any preexisting DESC
121404121967
** index.
121405121968
*/
121406121969
r1 = sqlite3GetTempReg(pParse);
@@ -121413,28 +121976,46 @@
121413121976
sqlite3ReleaseTempReg(pParse, r1);
121414121977
121415121978
/* Reload the table definition */
121416121979
renameReloadSchema(pParse, iDb, INITFLAG_AlterAdd);
121417121980
121418
- /* Verify that constraints are still satisfied */
121981
+ /* Verify that constraints are still satisfied. This requires a scan
121982
+ ** of the entire table if:
121983
+ **
121984
+ ** 1) the new column has a CHECK constraint, or
121985
+ ** 2) the new column is a NOT NULL generated column, or
121986
+ ** 3) the table is STRICT and the new column is a generated column
121987
+ ** with a type other than ANY.
121988
+ */
121419121989
if( pNew->pCheck!=0
121420
- || (pCol->notNull && (pCol->colFlags & COLFLAG_GENERATED)!=0)
121421
- || (pTab->tabFlags & TF_Strict)!=0
121990
+ || (pCol->notNull && isGen)
121991
+ || (isStrict && isGen && pCol->eCType!=COLTYPE_ANY)
121422121992
){
121423121993
pParse->colNamesSet = 1;
121424121994
sqlite3NestedParse(pParse,
121425121995
"SELECT CASE WHEN quick_check GLOB 'CHECK*'"
121426
- " THEN raise(ABORT,'CHECK constraint failed')"
121996
+ " THEN sqlite_fail('CHECK constraint failed', 1)"
121427121997
" WHEN quick_check GLOB 'non-* value in*'"
121428
- " THEN raise(ABORT,'type mismatch on DEFAULT')"
121429
- " ELSE raise(ABORT,'NOT NULL constraint failed')"
121998
+ " THEN sqlite_fail('type mismatch on DEFAULT', 1)"
121999
+ " ELSE sqlite_fail('NOT NULL constraint failed', 1)"
121430122000
" END"
121431122001
" FROM pragma_quick_check(%Q,%Q)"
121432122002
" WHERE quick_check GLOB 'CHECK*'"
121433122003
" OR quick_check GLOB 'NULL*'"
121434122004
" OR quick_check GLOB 'non-* value in*'",
121435122005
zTab, zDb
122006
+ );
122007
+ }else if( pDflt && isStrict && pCol->eCType>COLTYPE_ANY ){
122008
+ static const char *azTypeof[] = {
122009
+ "any", "blob", "integer", "integer", "real", "text"
122010
+ };
122011
+ assert( pCol->eCType<=ArraySize(azTypeof) );
122012
+ pParse->colNamesSet = 1;
122013
+ sqlite3NestedParse(pParse,
122014
+ "SELECT sqlite_fail('type mismatch on DEFAULT', 1)"
122015
+ " WHERE sqlite_check_type(%Q, %Q, %Q, %Q)",
122016
+ zDb, zTab, pCol->zCnName, azTypeof[pCol->eCType-1]
121436122017
);
121437122018
}
121438122019
}
121439122020
}
121440122021
@@ -122348,10 +122929,11 @@
122348122929
SrcList *pSrc = sqlite3SrcListDup(db, pStep->pSrc, 0);
122349122930
if( pSrc ){
122350122931
Select *pSel = sqlite3SelectNew(
122351122932
pParse, pStep->pExprList, pSrc, 0, 0, 0, 0, 0, 0
122352122933
);
122934
+ Upsert *pUpsert = 0;
122353122935
if( pSel==0 ){
122354122936
pStep->pExprList = 0;
122355122937
pSrc = 0;
122356122938
rc = SQLITE_NOMEM;
122357122939
}else{
@@ -122371,34 +122953,39 @@
122371122953
assert( pSrc==pSel->pSrc );
122372122954
if( pStep->pExprList ) pSel->pEList = 0;
122373122955
pSel->pSrc = 0;
122374122956
sqlite3SelectDelete(db, pSel);
122375122957
}
122958
+
122959
+ sNC.pSrcList = pSrc;
122376122960
if( ALWAYS(pStep->pSrc) ){
122377122961
int i;
122378122962
for(i=0; i<pStep->pSrc->nSrc && rc==SQLITE_OK; i++){
122379122963
SrcItem *p = &pStep->pSrc->a[i];
122380122964
if( p->fg.isSubquery ){
122381122965
assert( p->u4.pSubq!=0 );
122382122966
sqlite3SelectPrep(pParse, p->u4.pSubq->pSelect, 0);
122383122967
}
122968
+ if( p->fg.isUsing==0 ){
122969
+ rc = sqlite3ResolveExprNames(&sNC, p->u3.pOn);
122970
+ }
122384122971
}
122385122972
}
122386
-
122387
- if( db->mallocFailed ){
122973
+ if( db->mallocFailed ){
122388122974
rc = SQLITE_NOMEM;
122389122975
}
122390
- sNC.pSrcList = pSrc;
122391122976
if( rc==SQLITE_OK && pStep->pWhere ){
122392122977
rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
122393122978
}
122394122979
if( rc==SQLITE_OK ){
122395122980
rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
122396122981
}
122397122982
assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
122398
- if( pStep->pUpsert && rc==SQLITE_OK ){
122399
- Upsert *pUpsert = pStep->pUpsert;
122983
+ for(pUpsert=pStep->pUpsert;
122984
+ pUpsert && rc==SQLITE_OK;
122985
+ pUpsert=pUpsert->pNextUpsert
122986
+ ){
122400122987
pUpsert->pUpsertSrc = pSrc;
122401122988
sNC.uNC.pUpsert = pUpsert;
122402122989
sNC.ncFlags = NC_UUpsert;
122403122990
rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
122404122991
if( rc==SQLITE_OK ){
@@ -122433,27 +123020,31 @@
122433123020
/* Find tokens to edit in WHEN clause */
122434123021
sqlite3WalkExpr(pWalker, pTrigger->pWhen);
122435123022
122436123023
/* Find tokens to edit in trigger steps */
122437123024
for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
123025
+ Upsert *pUpsert = 0;
122438123026
sqlite3WalkSelect(pWalker, pStep->pSelect);
122439123027
sqlite3WalkExpr(pWalker, pStep->pWhere);
122440123028
sqlite3WalkExprList(pWalker, pStep->pExprList);
122441
- if( pStep->pUpsert ){
122442
- Upsert *pUpsert = pStep->pUpsert;
123029
+ for(pUpsert=pStep->pUpsert; pUpsert; pUpsert=pUpsert->pNextUpsert){
122443123030
sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
122444123031
sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
122445123032
sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
122446123033
sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
122447123034
}
122448123035
if( pStep->pSrc ){
122449123036
int i;
122450123037
SrcList *pSrc = pStep->pSrc;
122451123038
for(i=0; i<pSrc->nSrc; i++){
122452
- if( pSrc->a[i].fg.isSubquery ){
122453
- assert( pSrc->a[i].u4.pSubq!=0 );
122454
- sqlite3WalkSelect(pWalker, pSrc->a[i].u4.pSubq->pSelect);
123039
+ SrcItem *p = &pSrc->a[i];
123040
+ if( p->fg.isSubquery ){
123041
+ assert( p->u4.pSubq!=0 );
123042
+ sqlite3WalkSelect(pWalker, p->u4.pSubq->pSelect);
123043
+ }
123044
+ if( p->fg.isUsing==0 ){
123045
+ sqlite3WalkExpr(pWalker, p->u3.pOn);
122455123046
}
122456123047
}
122457123048
}
122458123049
}
122459123050
}
@@ -122539,11 +123130,11 @@
122539123130
sqlite3BtreeLeaveAll(db);
122540123131
return;
122541123132
}
122542123133
zOld = pTab->aCol[iCol].zCnName;
122543123134
memset(&sCtx, 0, sizeof(sCtx));
122544
- sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
123135
+ sCtx.iCol = iCol;
122545123136
122546123137
#ifndef SQLITE_OMIT_AUTHORIZATION
122547123138
db->xAuth = 0;
122548123139
#endif
122549123140
rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
@@ -122577,11 +123168,11 @@
122577123168
if( iCol<sParse.pNewTable->nCol ){
122578123169
renameTokenFind(
122579123170
&sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zCnName
122580123171
);
122581123172
}
122582
- if( sCtx.iCol<0 ){
123173
+ if( iCol==sParse.pNewTable->iPKey ){
122583123174
renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
122584123175
}
122585123176
sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
122586123177
for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
122587123178
sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
@@ -122623,13 +123214,13 @@
122623123214
122624123215
for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
122625123216
if( pStep->pSrc ){
122626123217
Table *pTarget = sqlite3LocateTableItem(&sParse, 0, &pStep->pSrc->a[0]);
122627123218
if( pTarget==pTab ){
122628
- if( pStep->pUpsert ){
122629
- ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
122630
- renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
123219
+ Upsert *pUpsert = 0;
123220
+ for(pUpsert=pStep->pUpsert; pUpsert; pUpsert=pUpsert->pNextUpsert){
123221
+ renameColumnElistNames(&sParse,&sCtx,pUpsert->pUpsertSet,zOld);
122631123222
}
122632123223
renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
122633123224
renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
122634123225
}
122635123226
}
@@ -122705,10 +123296,30 @@
122705123296
renameWalkWith(pWalker, pSelect);
122706123297
122707123298
return WRC_Continue;
122708123299
}
122709123300
123301
+
123302
+#ifndef SQLITE_OMIT_TRIGGER
123303
+/*
123304
+** Return the table that SrcItem pItem, which is part of the pSrc list of
123305
+** an INSERT, UPDATE or DELETE trigger step (the target table, or a table
123306
+** from the FROM clause of an UPDATE ... FROM), refers to. Or NULL if it
123307
+** does not refer to any existing table.
123308
+*/
123309
+static Table *renameTriggerSrcTab(sqlite3 *db, SrcItem *pItem){
123310
+ const char *zDb;
123311
+ assert( pItem->fg.isSubquery==0 );
123312
+ if( pItem->fg.fixedSchema ){
123313
+ int iDb = sqlite3SchemaToIndex(db, pItem->u4.pSchema);
123314
+ zDb = db->aDb[iDb].zDbSName;
123315
+ }else{
123316
+ zDb = pItem->u4.zDatabase;
123317
+ }
123318
+ return sqlite3FindTable(db, pItem->zName, zDb);
123319
+}
123320
+#endif
122710123321
122711123322
/*
122712123323
** This C function implements an SQL user function that is used by SQL code
122713123324
** generated by the ALTER TABLE ... RENAME command to modify the definition
122714123325
** of any foreign key constraints that use the table being renamed as the
@@ -122824,12 +123435,12 @@
122824123435
#ifndef SQLITE_OMIT_TRIGGER
122825123436
else{
122826123437
Trigger *pTrigger = sParse.pNewTrigger;
122827123438
TriggerStep *pStep;
122828123439
if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
122829
- && sCtx.pTab->pSchema==pTrigger->pTabSchema
122830
- ){
123440
+ && sCtx.pTab->pSchema==pTrigger->pTabSchema
123441
+ ){
122831123442
renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
122832123443
}
122833123444
122834123445
if( isLegacy==0 ){
122835123446
rc = renameResolveTrigger(&sParse);
@@ -122837,13 +123448,13 @@
122837123448
renameWalkTrigger(&sWalker, pTrigger);
122838123449
for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
122839123450
if( pStep->pSrc ){
122840123451
int i;
122841123452
for(i=0; i<pStep->pSrc->nSrc; i++){
122842
- SrcItem *pItem = &pStep->pSrc->a[i];
122843
- if( 0==sqlite3_stricmp(pItem->zName, zOld) ){
122844
- renameTokenFind(&sParse, &sCtx, pItem->zName);
123453
+ SrcItem *p = &pStep->pSrc->a[i];
123454
+ if( p->zName && renameTriggerSrcTab(db, p)==sCtx.pTab ){
123455
+ renameTokenFind(&sParse, &sCtx, p->zName);
122845123456
}
122846123457
}
122847123458
}
122848123459
}
122849123460
}
@@ -123294,75 +123905,78 @@
123294123905
/* Drop and reload the database schema. */
123295123906
renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
123296123907
renameTestSchema(pParse, zDb, iDb==1, "after drop column", 1);
123297123908
123298123909
/* Edit rows of table on disk */
123299
- if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
123300
- int i;
123301
- int addr;
123302
- int reg;
123303
- int regRec;
123304
- Index *pPk = 0;
123305
- int nField = 0; /* Number of non-virtual columns after drop */
123306
- int iCur;
123910
+ if( pParse->nErr==0 ){
123307123911
Vdbe *v = sqlite3GetVdbe(pParse);
123308
- iCur = pParse->nTab++;
123309
- sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
123310
- addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
123311
- reg = ++pParse->nMem;
123312
- if( HasRowid(pTab) ){
123313
- sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
123314
- pParse->nMem += pTab->nCol;
123315
- }else{
123316
- pPk = sqlite3PrimaryKeyIndex(pTab);
123317
- pParse->nMem += pPk->nColumn;
123318
- for(i=0; i<pPk->nKeyCol; i++){
123319
- sqlite3VdbeAddOp3(v, OP_Column, iCur, i, reg+i+1);
123320
- }
123321
- nField = pPk->nKeyCol;
123322
- }
123323
- regRec = ++pParse->nMem;
123324
- for(i=0; i<pTab->nCol; i++){
123325
- if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
123326
- int regOut;
123327
- if( pPk ){
123328
- int iPos = sqlite3TableColumnToIndex(pPk, i);
123329
- int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
123330
- if( iPos<pPk->nKeyCol ) continue;
123331
- regOut = reg+1+iPos-(iPos>iColPos);
123332
- }else{
123333
- regOut = reg+1+nField;
123334
- }
123335
- if( i==pTab->iPKey ){
123336
- sqlite3VdbeAddOp2(v, OP_Null, 0, regOut);
123337
- }else{
123338
- sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
123339
- assert( pParse->nErr
123340
- || sqlite3VdbeGetOp(v,sqlite3VdbeCurrentAddr(v)-1)->opcode
123341
- != OP_RealAffinity
123342
- || pTab->aCol[i].affinity==SQLITE_AFF_REAL );
123343
- sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
123344
- }
123345
- nField++;
123346
- }
123347
- }
123348
- if( nField==0 ){
123349
- /* dbsqlfuzz 5f09e7bcc78b4954d06bf9f2400d7715f48d1fef */
123350
- pParse->nMem++;
123351
- sqlite3VdbeAddOp2(v, OP_Null, 0, reg+1);
123352
- nField = 1;
123353
- }
123354
- sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
123355
- if( pPk ){
123356
- sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
123357
- }else{
123358
- sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
123359
- }
123360
- sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
123361
-
123362
- sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
123363
- sqlite3VdbeJumpHere(v, addr);
123912
+ sqlite3VdbeAddOp0(v, OP_DbLock);
123913
+ if( (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
123914
+ int i;
123915
+ int addr;
123916
+ int reg;
123917
+ int regRec;
123918
+ Index *pPk = 0;
123919
+ int nField = 0; /* Number of non-virtual columns after drop */
123920
+ int iCur;
123921
+ iCur = pParse->nTab++;
123922
+ sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
123923
+ addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
123924
+ reg = ++pParse->nMem;
123925
+ if( HasRowid(pTab) ){
123926
+ sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
123927
+ pParse->nMem += pTab->nCol;
123928
+ }else{
123929
+ pPk = sqlite3PrimaryKeyIndex(pTab);
123930
+ pParse->nMem += pPk->nColumn;
123931
+ for(i=0; i<pPk->nKeyCol; i++){
123932
+ sqlite3VdbeAddOp3(v, OP_Column, iCur, i, reg+i+1);
123933
+ }
123934
+ nField = pPk->nKeyCol;
123935
+ }
123936
+ regRec = ++pParse->nMem;
123937
+ for(i=0; i<pTab->nCol; i++){
123938
+ if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
123939
+ int regOut;
123940
+ if( pPk ){
123941
+ int iPos = sqlite3TableColumnToIndex(pPk, i);
123942
+ int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
123943
+ if( iPos<pPk->nKeyCol ) continue;
123944
+ regOut = reg+1+iPos-(iPos>iColPos);
123945
+ }else{
123946
+ regOut = reg+1+nField;
123947
+ }
123948
+ if( i==pTab->iPKey ){
123949
+ sqlite3VdbeAddOp2(v, OP_Null, 0, regOut);
123950
+ }else{
123951
+ sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
123952
+ assert( pParse->nErr
123953
+ || sqlite3VdbeGetOp(v,sqlite3VdbeCurrentAddr(v)-1)->opcode
123954
+ != OP_RealAffinity
123955
+ || pTab->aCol[i].affinity==SQLITE_AFF_REAL );
123956
+ sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
123957
+ }
123958
+ nField++;
123959
+ }
123960
+ }
123961
+ if( nField==0 ){
123962
+ /* dbsqlfuzz 5f09e7bcc78b4954d06bf9f2400d7715f48d1fef */
123963
+ pParse->nMem++;
123964
+ sqlite3VdbeAddOp2(v, OP_Null, 0, reg+1);
123965
+ nField = 1;
123966
+ }
123967
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
123968
+ if( pPk ){
123969
+ sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1,pPk->nKeyCol);
123970
+ }else{
123971
+ sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
123972
+ }
123973
+ sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
123974
+
123975
+ sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
123976
+ sqlite3VdbeJumpHere(v, addr);
123977
+ }
123364123978
}
123365123979
123366123980
exit_drop_column:
123367123981
sqlite3DbFree(db, zCol);
123368123982
sqlite3SrcListDelete(db, pSrc);
@@ -123864,48 +124478,10 @@
123864124478
(void)NotUsed;
123865124479
sqlite3_result_error(ctx, zText, -1);
123866124480
sqlite3_result_error_code(ctx, err);
123867124481
}
123868124482
123869
-/*
123870
-** Buffer pCons, which is nCons bytes in size, contains the text of a
123871
-** NOT NULL or CHECK constraint that will be inserted into a CREATE TABLE
123872
-** statement. If successful, this function returns the size of the buffer in
123873
-** bytes not including any trailing whitespace or "--" style comments. Or,
123874
-** if an OOM occurs, it returns 0 and sets db->mallocFailed to true.
123875
-**
123876
-** C-style comments at the end are preserved. "--" style comments are
123877
-** removed because the comment terminator might be \000, and we are about
123878
-** to insert the pCons[] text into the middle of a larger string, and that
123879
-** will have the effect of removing the comment terminator and messing up
123880
-** the syntax.
123881
-*/
123882
-static int alterRtrimConstraint(
123883
- sqlite3 *db, /* used to record OOM error */
123884
- const char *pCons, /* Buffer containing constraint */
123885
- int nCons /* Size of pCons in bytes */
123886
-){
123887
- u8 *zTmp = (u8*)sqlite3MPrintf(db, "%.*s", nCons, pCons);
123888
- int iOff = 0;
123889
- int iEnd = 0;
123890
-
123891
- if( zTmp==0 ) return 0;
123892
-
123893
- while( 1 ){
123894
- int t = 0;
123895
- int nToken = sqlite3GetToken(&zTmp[iOff], &t);
123896
- if( t==TK_ILLEGAL ) break;
123897
- if( t!=TK_SPACE && (t!=TK_COMMENT || zTmp[iOff]!='-') ){
123898
- iEnd = iOff+nToken;
123899
- }
123900
- iOff += nToken;
123901
- }
123902
-
123903
- sqlite3DbFree(db, zTmp);
123904
- return iEnd;
123905
-}
123906
-
123907124483
/*
123908124484
** Prepare a statement of the form:
123909124485
**
123910124486
** ALTER TABLE pSrc ALTER pCol SET NOT NULL
123911124487
*/
@@ -123932,11 +124508,11 @@
123932124508
return;
123933124509
}
123934124510
123935124511
/* Find the length in bytes of the constraint definition */
123936124512
pCons = pFirst->z;
123937
- nCons = alterRtrimConstraint(pParse->db, pCons, pParse->sLastToken.z - pCons);
124513
+ nCons = alterRtrimFragment(pParse->db, pCons, pParse->sLastToken.z - pCons);
123938124514
123939124515
/* Search for a constraint violation. Throw an exception if one is found. */
123940124516
sqlite3NestedParse(pParse,
123941124517
"SELECT sqlite_fail('constraint failed', %d) "
123942124518
"FROM %Q.%Q AS x WHERE x.%.*s IS NULL",
@@ -124064,11 +124640,11 @@
124064124640
SQLITE_CONSTRAINT, zDb, pTab->zName, nExpr, zExpr
124065124641
);
124066124642
124067124643
/* Edit the SQL for the named table. */
124068124644
pCons = pFirst->z;
124069
- nCons = alterRtrimConstraint(pParse->db, pCons, pParse->sLastToken.z - pCons);
124645
+ nCons = alterRtrimFragment(pParse->db, pCons, pParse->sLastToken.z - pCons);
124070124646
124071124647
sqlite3NestedParse(pParse,
124072124648
"UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
124073124649
"sql = sqlite_add_constraint(sql, %.*Q, -1) "
124074124650
"WHERE type='table' AND tbl_name=%Q COLLATE nocase"
@@ -124076,25 +124652,83 @@
124076124652
);
124077124653
124078124654
/* Finally, reload the database schema. */
124079124655
renameReloadSchema(pParse, iDb, INITFLAG_AlterDropCons);
124080124656
}
124657
+
124658
+/*
124659
+** The implementation of internal SQL function:
124660
+**
124661
+** sqlite_check_type(DB, TAB, COL, TYPE)
124662
+**
124663
+** Read the value of column COL from the first row of table DB.TAB. Return
124664
+** 1 if the table contains at least one row and typeof() of the value read
124665
+** is not TYPE. Otherwise, return NULL.
124666
+*/
124667
+static void checkTypeFunc(
124668
+ sqlite3_context *ctx,
124669
+ int NotUsed,
124670
+ sqlite3_value **argv
124671
+){
124672
+ sqlite3 *db = sqlite3_context_db_handle(ctx);
124673
+ const char *zDb = (const char*)sqlite3_value_text(argv[0]);
124674
+ const char *zTab = (const char*)sqlite3_value_text(argv[1]);
124675
+ const char *zCol = (const char*)sqlite3_value_text(argv[2]);
124676
+ const char *zType = (const char*)sqlite3_value_text(argv[3]);
124677
+ sqlite3_stmt *pStmt = 0;
124678
+ char *zSql;
124679
+ int rc;
124680
+
124681
+#ifndef SQLITE_OMIT_AUTHORIZATION
124682
+ sqlite3_xauth xAuth = db->xAuth;
124683
+ db->xAuth = 0;
124684
+#endif
124685
+
124686
+ (void)NotUsed;
124687
+ if( zDb==0 || zTab==0 || zCol==0 || zType==0 ) return;
124688
+ zSql = sqlite3MPrintf(db,
124689
+ "SELECT typeof(\"%w\") FROM \"%w\".\"%w\" LIMIT 1", zCol, zDb, zTab
124690
+ );
124691
+ if( zSql==0 ){
124692
+ sqlite3_result_error_nomem(ctx);
124693
+ return;
124694
+ }
124695
+ rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
124696
+ sqlite3DbFree(db, zSql);
124697
+ if( rc==SQLITE_OK ){
124698
+ if( sqlite3_step(pStmt)==SQLITE_ROW ){
124699
+ const char *zVal = (const char*)sqlite3_column_text(pStmt, 0);
124700
+ if( sqlite3_stricmp(zVal, zType)!=0 ){
124701
+ sqlite3_result_int(ctx, 1);
124702
+ }
124703
+ }
124704
+ rc = sqlite3_finalize(pStmt);
124705
+ }
124706
+ if( rc!=SQLITE_OK ){
124707
+ sqlite3_result_error(ctx, sqlite3_errmsg(db), -1);
124708
+ sqlite3_result_error_code(ctx, rc);
124709
+ }
124710
+#ifndef SQLITE_OMIT_AUTHORIZATION
124711
+ db->xAuth = xAuth;
124712
+#endif
124713
+}
124081124714
124082124715
/*
124083124716
** Register built-in functions used to help implement ALTER TABLE
124084124717
*/
124085124718
SQLITE_PRIVATE void sqlite3AlterFunctions(void){
124086124719
static FuncDef aAlterTableFuncs[] = {
124720
+ INTERNAL_FUNCTION(sqlite_check_type, 4, checkTypeFunc),
124087124721
INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
124088124722
INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
124089124723
INTERNAL_FUNCTION(sqlite_rename_test, 7, renameTableTest),
124090124724
INTERNAL_FUNCTION(sqlite_drop_column, 3, dropColumnFunc),
124091124725
INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc),
124092124726
INTERNAL_FUNCTION(sqlite_drop_constraint,2, dropConstraintFunc),
124093124727
INTERNAL_FUNCTION(sqlite_fail, 2, failConstraintFunc),
124094124728
INTERNAL_FUNCTION(sqlite_add_constraint, 3, addConstraintFunc),
124095
- INTERNAL_FUNCTION(sqlite_find_constraint,2, findConstraintFunc),
124729
+ INTERNAL_FUNCTION(sqlite_find_constraint,2, findConstraintFunc)
124096124730
};
124097124731
sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
124098124732
}
124099124733
#endif /* SQLITE_ALTER_TABLE */
124100124734
@@ -127172,10 +127806,20 @@
127172127806
for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
127173127807
return 1;
127174127808
}
127175127809
#endif
127176127810
127811
+/*
127812
+** Do the union all two yDbMask objects into the first.
127813
+*/
127814
+#if SQLITE_MAX_ATTACHED>30
127815
+SQLITE_PRIVATE void sqlite3DbMaskUnion(yDbMask m, yDbMask x){
127816
+ int i;
127817
+ for(i=0; i<sizeof(yDbMask); i++){ m[i] |= x[i]; }
127818
+}
127819
+#endif
127820
+
127177127821
/*
127178127822
** This routine is called after a single SQL statement has been
127179127823
** parsed and a VDBE program to execute that statement has been
127180127824
** prepared. This routine puts the finishing touches on the
127181127825
** VDBE program and resets the pParse structure for the next
@@ -127664,27 +128308,37 @@
127664128308
}
127665128309
}
127666128310
127667128311
/*
127668128312
** Reset the schema for the database at index iDb. Also reset the
127669
-** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
127670
-** Deferred resets may be run by calling with iDb<0.
128313
+** TEMP schema. The reset is deferred if db->nSchemaLock is not zero
128314
+** or if an active VDBE other than pSafe is using iDb
128315
+**
128316
+** Deferred schema resets may be retried by calling with iDb<0.
127671128317
*/
127672
-SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
128318
+SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb, Vdbe *pSafe){
127673128319
int i;
127674128320
assert( iDb<db->nDb );
127675128321
127676128322
if( iDb>=0 ){
127677128323
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
127678128324
DbSetProperty(db, iDb, DB_ResetWanted);
127679128325
DbSetProperty(db, 1, DB_ResetWanted);
127680128326
db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
128327
+ db->bPendingSchemaReset = 1;
127681128328
}
127682128329
127683128330
if( db->nSchemaLock==0 ){
128331
+ yDbMask m;
128332
+ sqlite3VdbeSchemaInUse(db, pSafe, &m);
128333
+ db->bPendingSchemaReset = 0;
127684128334
for(i=0; i<db->nDb; i++){
127685
- if( DbHasProperty(db, i, DB_ResetWanted) ){
128335
+ if( !DbHasProperty(db, i, DB_ResetWanted) ){
128336
+ /* no-op */
128337
+ }else if( DbMaskTest(m,i) ){
128338
+ db->bPendingSchemaReset = 1;
128339
+ }else{
127686128340
sqlite3SchemaClear(db->aDb[i].pSchema);
127687128341
db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
127688128342
}
127689128343
}
127690128344
}
@@ -127705,10 +128359,11 @@
127705128359
}else{
127706128360
DbSetProperty(db, i, DB_ResetWanted);
127707128361
}
127708128362
}
127709128363
}
128364
+ sqlite3ExpirePreparedStatements(db, 0);
127710128365
db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
127711128366
sqlite3VtabUnlockList(db);
127712128367
sqlite3BtreeLeaveAll(db);
127713128368
if( db->nSchemaLock==0 ){
127714128369
sqlite3CollapseDatabaseArray(db);
@@ -128130,16 +128785,20 @@
128130128785
** is reserved for internal use.
128131128786
**
128132128787
** When parsing the sqlite_schema table, this routine also checks to
128133128788
** make sure the "type", "name", and "tbl_name" columns are consistent
128134128789
** with the SQL.
128790
+**
128791
+** If shadow tables are read-only, names that are shadow table names
128792
+** of a virtual table in schema zDb are also reserved.
128135128793
*/
128136128794
SQLITE_PRIVATE int sqlite3CheckObjectName(
128137128795
Parse *pParse, /* Parsing context */
128138128796
const char *zName, /* Name of the object to check */
128139128797
const char *zType, /* Type of this object */
128140
- const char *zTblName /* Parent table name for triggers and indexes */
128798
+ const char *zTblName, /* Parent table name for triggers and indexes */
128799
+ const char *zDb /* Schema in which the object will be created */
128141128800
){
128142128801
sqlite3 *db = pParse->db;
128143128802
if( sqlite3WritableSchema(db)
128144128803
|| db->init.imposterTable
128145128804
|| !sqlite3Config.bExtraSchemaChecks
@@ -128155,11 +128814,12 @@
128155128814
sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
128156128815
return SQLITE_ERROR;
128157128816
}
128158128817
}else{
128159128818
if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
128160
- || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))
128819
+ || (sqlite3ReadOnlyShadowTables(db)
128820
+ && sqlite3ShadowTableName(db, zName, zDb))
128161128821
){
128162128822
sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
128163128823
zName);
128164128824
return SQLITE_ERROR;
128165128825
}
@@ -128342,14 +129002,18 @@
128342129002
if( !OMIT_TEMPDB && isTemp ) iDb = 1;
128343129003
zName = sqlite3NameFromToken(db, pName);
128344129004
if( IN_RENAME_OBJECT ){
128345129005
sqlite3RenameTokenMap(pParse, (void*)zName, pName);
128346129006
}
129007
+ if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
129008
+ goto begin_table_error;
129009
+ }
128347129010
}
128348129011
pParse->sNameToken = *pName;
128349129012
if( zName==0 ) return;
128350
- if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){
129013
+ if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName,
129014
+ db->aDb[iDb].zDbSName) ){
128351129015
goto begin_table_error;
128352129016
}
128353129017
if( db->init.iDb==1 ) isTemp = 1;
128354129018
#ifndef SQLITE_OMIT_AUTHORIZATION
128355129019
assert( isTemp==0 || isTemp==1 );
@@ -128379,13 +129043,10 @@
128379129043
** and types will be used, so there is no need to test for namespace
128380129044
** collisions.
128381129045
*/
128382129046
if( !IN_SPECIAL_PARSE ){
128383129047
char *zDb = db->aDb[iDb].zDbSName;
128384
- if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
128385
- goto begin_table_error;
128386
- }
128387129048
pTable = sqlite3FindTable(db, zName, zDb);
128388129049
if( pTable ){
128389129050
if( !noErr ){
128390129051
sqlite3ErrorMsg(pParse, "%s %T already exists",
128391129052
(IsView(pTable)? "view" : "table"), pName);
@@ -128613,19 +129274,18 @@
128613129274
128614129275
/* Because keywords GENERATE ALWAYS can be converted into identifiers
128615129276
** by the parser, we can sometimes end up with a typename that ends
128616129277
** with "generated always". Check for this case and omit the surplus
128617129278
** text. */
128618
- if( sType.n>=16
128619
- && sqlite3_strnicmp(sType.z+(sType.n-6),"always",6)==0
128620
- ){
128621
- sType.n -= 6;
128622
- while( ALWAYS(sType.n>0) && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
128623
- if( sType.n>=9
128624
- && sqlite3_strnicmp(sType.z+(sType.n-9),"generated",9)==0
128625
- ){
128626
- sType.n -= 9;
129279
+ if( sType.n>=16 && sqlite3_strnicmp(sType.z+(sType.n-6),"always",6)==0 ){
129280
+ u32 nType = sType.n - 6;
129281
+ while( ALWAYS(nType>0) && sqlite3Isspace(sType.z[nType-1]) ) nType--;
129282
+ if( nType>=9 && nType<(sType.n - 6)
129283
+ && sqlite3_strnicmp(sType.z+(nType-9),"generated",9)==0
129284
+ && (nType==9 || sqlite3Isspace(sType.z[nType-10]))
129285
+ ){
129286
+ sType.n = nType - 9;
128627129287
while( sType.n>0 && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
128628129288
}
128629129289
}
128630129290
128631129291
/* Check for standard typenames. For standard typenames we will
@@ -129692,25 +130352,38 @@
129692130352
}
129693130353
#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
129694130354
129695130355
#ifndef SQLITE_OMIT_VIRTUALTABLE
129696130356
/*
129697
-** Return true if zName is a shadow table name in the current database
129698
-** connection.
130357
+** Return true if zName is the name of a shadow table of a virtual table
130358
+** in schema zDb. If zDb is NULL, return true if zName is a shadow table
130359
+** name of a virtual table in any schema of the database connection.
130360
+**
130361
+** Each schema is checked separately. An ordinary table in one schema
130362
+** (for example, a TEMP table) must not hide a same-named virtual table
130363
+** in another schema.
129699130364
*/
129700
-SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
130365
+SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName, const char *zDb){
129701130366
const char *zTail; /* Pointer to the last "_" in zName */
129702130367
Table *pTab; /* Table that zName is a shadow of */
129703130368
char *zCopy; /* Transient copy of zName after last "_" */
130369
+ int i; /* Loop counter over schemas */
130370
+ int bRet = 0; /* Return value */
129704130371
zTail = strrchr(zName, '_');
129705130372
if( zTail==0 ) return 0;
129706130373
zCopy = sqlite3DbStrNDup(db, zName, (int)(zTail-zName));
129707
- pTab = zCopy ? sqlite3FindTable(db, zCopy, 0) : 0;
130374
+ if( zCopy==0 ) return 0;
130375
+ for(i=0; i<db->nDb && bRet==0; i++){
130376
+ const char *zSchema = db->aDb[i].zDbSName;
130377
+ if( zDb && sqlite3DbIsNamed(db, i, zDb)==0 ) continue;
130378
+ pTab = sqlite3FindTable(db, zCopy, zSchema);
130379
+ if( pTab && IsVirtual(pTab) ){
130380
+ bRet = sqlite3IsShadowTableOf(db, pTab, zName);
130381
+ }
130382
+ }
129708130383
sqlite3DbFree(db, zCopy);
129709
- if( pTab==0 ) return 0;
129710
- if( !IsVirtual(pTab) ) return 0;
129711
- return sqlite3IsShadowTableOf(db, pTab, zName);
130384
+ return bRet;
129712130385
}
129713130386
#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
129714130387
129715130388
129716130389
#ifdef SQLITE_DEBUG
@@ -129775,11 +130448,14 @@
129775130448
return;
129776130449
}
129777130450
p = pParse->pNewTable;
129778130451
if( p==0 ) return;
129779130452
129780
- if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
130453
+ if( pSelect==0
130454
+ && sqlite3ShadowTableName(db, p->zName,
130455
+ db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].zDbSName)
130456
+ ){
129781130457
p->tabFlags |= TF_Shadow;
129782130458
}
129783130459
129784130460
/* If the db->init.busy is 1 it means we are reading the SQL off the
129785130461
** "sqlite_schema" or "sqlite_temp_schema" table on the disk.
@@ -131123,13 +131799,17 @@
131123131799
assert( pName && pName->z );
131124131800
131125131801
#ifndef SQLITE_OMIT_TEMPDB
131126131802
/* If the index name was unqualified, check if the table
131127131803
** is a temp table. If so, set the database to 1. Do not do this
131128
- ** if initializing a database schema.
131129
- */
131130
- if( !db->init.busy ){
131804
+ ** if initializing a database schema, if ALTER TABLE is reparsing an
131805
+ ** existing index, or if VACUUM is recreating the indexes of a
131806
+ ** database. */
131807
+ if( !db->init.busy
131808
+ && !IN_RENAME_OBJECT
131809
+ && (db->mDbFlags & DBFLAG_Vacuum)==0
131810
+ ){
131131131811
pTab = sqlite3SrcListLookup(pParse, pTblName);
131132131812
if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
131133131813
iDb = 1;
131134131814
}
131135131815
}
@@ -131196,11 +131876,13 @@
131196131876
*/
131197131877
if( pName ){
131198131878
zName = sqlite3NameFromToken(db, pName);
131199131879
if( zName==0 ) goto exit_create_index;
131200131880
assert( pName->z!=0 );
131201
- if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
131881
+ if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName, "index",
131882
+ pTab->zName, db->aDb[iDb].zDbSName)
131883
+ ){
131202131884
goto exit_create_index;
131203131885
}
131204131886
if( !IN_RENAME_OBJECT ){
131205131887
if( !db->init.busy ){
131206131888
if( sqlite3FindTable(db, zName, pDb->zDbSName)!=0 ){
@@ -131775,12 +132457,12 @@
131775132457
sqlite3NestedParse(pParse,
131776132458
"DELETE FROM %Q." LEGACY_SCHEMA_TABLE " WHERE name=%Q AND type='index'",
131777132459
db->aDb[iDb].zDbSName, pIndex->zName
131778132460
);
131779132461
sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
131780
- sqlite3ChangeCookie(pParse, iDb);
131781132462
destroyRootPage(pParse, pIndex->tnum, iDb);
132463
+ sqlite3ChangeCookie(pParse, iDb);
131782132464
sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
131783132465
}
131784132466
131785132467
exit_drop_index:
131786132468
sqlite3SrcListDelete(db, pName);
@@ -134754,11 +135436,11 @@
134754135436
** something that can be converted into a number, we have:
134755135437
** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
134756135438
** that cannot be converted to a numeric value.
134757135439
*/
134758135440
double rVal = sqlite3_value_double(argv[0]);
134759
- if( rVal<0 ) rVal = -rVal;
135441
+ if( signbit(rVal) ) rVal = -rVal;
134760135442
sqlite3_result_double(context, rVal);
134761135443
break;
134762135444
}
134763135445
}
134764135446
}
@@ -134897,12 +135579,19 @@
134897135579
assert( argc==3 || argc==2 );
134898135580
p0type = sqlite3_value_type(argv[0]);
134899135581
p1 = sqlite3_value_int64(argv[1]);
134900135582
if( p0type==SQLITE_BLOB ){
134901135583
len = sqlite3_value_bytes(argv[0]);
134902
- z = sqlite3_value_blob(argv[0]);
134903
- if( z==0 ) return;
135584
+ if( len==0){
135585
+ /* sqlite3_value_blob() returns a NULL pointer for a zero-length blob.
135586
+ ** But the call to sqlite3_result_blob() below interprets a NULL pointer
135587
+ ** as an SQL NULL. So set z to point to some non-NULL location here. */
135588
+ z = (const unsigned char*)"";
135589
+ }else{
135590
+ z = sqlite3_value_blob(argv[0]);
135591
+ if( z==0 ) return;
135592
+ }
134904135593
assert( len==sqlite3_value_bytes(argv[0]) );
134905135594
}else{
134906135595
z = sqlite3_value_text(argv[0]);
134907135596
if( z==0 ) return;
134908135597
len = 0;
@@ -134932,11 +135621,11 @@
134932135621
if( p1<0 ){
134933135622
p1 += len;
134934135623
if( p1<0 ){
134935135624
if( p2<0 ){
134936135625
p2 = 0;
134937
- }else{
135626
+ }else if( argc==3 ){
134938135627
p2 += p1;
134939135628
}
134940135629
p1 = 0;
134941135630
}
134942135631
}else if( p1>0 ){
@@ -135022,14 +135711,12 @@
135022135711
** handle the rounding directly,
135023135712
** otherwise use printf.
135024135713
*/
135025135714
if( r<-4503599627370496.0 || r>+4503599627370496.0 ){
135026135715
/* The value has no fractional part so there is nothing to round */
135027
- }else if( n==0 ){
135028
- r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5)));
135029135716
}else{
135030
- zBuf = sqlite3_mprintf("%!.*f",(int)n,r);
135717
+ zBuf = sqlite3_mprintf("%#!.*f",(int)n,r);
135031135718
if( zBuf==0 ){
135032135719
sqlite3_result_error_nomem(context);
135033135720
return;
135034135721
}
135035135722
sqlite3AtoF(zBuf, &r);
@@ -137109,11 +137796,11 @@
137109137796
if( argc==2 ){
137110137797
switch( sqlite3_value_numeric_type(argv[1]) ){
137111137798
case SQLITE_INTEGER:
137112137799
case SQLITE_FLOAT:
137113137800
b = log(x);
137114
- if( b<=0.0 ) return;
137801
+ if( b==0.0 ) return;
137115137802
x = sqlite3_value_double(argv[1]);
137116137803
if( x<=0.0 ) return;
137117137804
break;
137118137805
default:
137119137806
return;
@@ -138544,10 +139231,12 @@
138544139231
for(i=0; i<nCol; i++){
138545139232
sqlite3VdbeAddOp2(v, OP_Copy,
138546139233
sqlite3TableColumnToStorage(pFKey->pFrom, aiCol[i])+1+regData,
138547139234
regTemp+i);
138548139235
}
139236
+ sqlite3VdbeAddOp4(v, OP_Affinity, regTemp, nCol, 0,
139237
+ sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
138549139238
138550139239
/* If the parent table is the same as the child table, and we are about
138551139240
** to increment the constraint-counter (i.e. this is an INSERT operation),
138552139241
** then check if the row being inserted matches itself. If so, do not
138553139242
** increment the constraint-counter.
@@ -138558,29 +139247,29 @@
138558139247
** none of the child key values are).
138559139248
*/
138560139249
if( pTab==pFKey->pFrom && nIncr==1 ){
138561139250
int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
138562139251
for(i=0; i<nCol; i++){
138563
- int iChild = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i])
138564
- +1+regData;
139252
+ CollSeq *pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
139253
+ int iChild = regTemp+i;
138565139254
int iParent = 1+regData;
138566139255
iParent += sqlite3TableColumnToStorage(pIdx->pTable,
138567139256
pIdx->aiColumn[i]);
138568139257
assert( pIdx->aiColumn[i]>=0 );
138569139258
assert( aiCol[i]!=pTab->iPKey );
138570139259
if( pIdx->aiColumn[i]==pTab->iPKey ){
138571139260
/* The parent key is a composite key that includes the IPK column */
138572139261
iParent = regData;
138573139262
}
138574
- sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
139263
+ sqlite3VdbeAddOp4(v, OP_Ne, iChild, iJump, iParent,
139264
+ (char*)pColl, P4_COLLSEQ);
139265
+ VdbeCoverage(v);
138575139266
sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
138576139267
}
138577139268
sqlite3VdbeGoto(v, iOk);
138578139269
}
138579139270
138580
- sqlite3VdbeAddOp4(v, OP_Affinity, regTemp, nCol, 0,
138581
- sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
138582139271
sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regTemp, nCol);
138583139272
VdbeCoverage(v);
138584139273
sqlite3ReleaseTempRange(pParse, regTemp, nCol);
138585139274
}
138586139275
}
@@ -139150,10 +139839,27 @@
139150139839
return 1;
139151139840
}
139152139841
}
139153139842
return 0;
139154139843
}
139844
+
139845
+/*
139846
+** Return true if the child table of FK constraint pFKey has one or
139847
+** more BEFORE triggers that could interfere with the action (either
139848
+** a CASCADE or SET NULL) caused by either a DELETE (if bUpdate==0)
139849
+** or UPDATE (if bUpdate==1) of the parent table. Or false otherwise.
139850
+*/
139851
+static int fkBeforeTriggersExist(
139852
+ Parse *pParse, /* Parse context */
139853
+ FKey *pFKey, /* Foreign key constraint */
139854
+ int bUpdate /* True for ON UPDATE, false ON DELETE */
139855
+){
139856
+ int mask = 0;
139857
+ int op = (!bUpdate && pFKey->aAction[0]==OE_Cascade) ? TK_DELETE : TK_UPDATE;
139858
+ sqlite3TriggersExist(pParse, pFKey->pFrom, op, 0, &mask);
139859
+ return (mask & TRIGGER_BEFORE)!=0;
139860
+}
139155139861
139156139862
/*
139157139863
** This function is called when inserting, deleting or updating a row of
139158139864
** table pTab to generate VDBE code to perform foreign key constraint
139159139865
** processing for the operation.
@@ -139184,10 +139890,11 @@
139184139890
sqlite3 *db = pParse->db; /* Database handle */
139185139891
FKey *pFKey; /* Used to iterate through FKs */
139186139892
int iDb; /* Index of database containing pTab */
139187139893
const char *zDb; /* Name of database containing pTab */
139188139894
int isIgnoreErrors = pParse->disableTriggers;
139895
+ int iPass; /* 0: immediate FKs, 1: deferred FKs */
139189139896
139190139897
/* Exactly one of regOld and regNew should be non-zero. */
139191139898
assert( (regOld==0)!=(regNew==0) );
139192139899
139193139900
/* If foreign-keys are disabled, this function is a no-op. */
@@ -139197,110 +139904,120 @@
139197139904
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
139198139905
assert( iDb>=00 && iDb<db->nDb );
139199139906
zDb = db->aDb[iDb].zDbSName;
139200139907
139201139908
/* Loop through all the foreign key constraints for which pTab is the
139202
- ** child table (the table that the foreign key definition is part of). */
139203
- for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
139204
- Table *pTo; /* Parent table of foreign key pFKey */
139205
- Index *pIdx = 0; /* Index on key columns in pTo */
139206
- int *aiFree = 0;
139207
- int *aiCol;
139208
- int iCol;
139209
- int i;
139210
- int bIgnore = 0;
139211
-
139212
- if( aChange
139213
- && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
139214
- && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
139215
- ){
139216
- continue;
139217
- }
139218
-
139219
- /* Find the parent table of this foreign key. Also find a unique index
139220
- ** on the parent key columns in the parent table. If either of these
139221
- ** schema items cannot be located, set an error in pParse and return
139222
- ** early. */
139223
- if( pParse->disableTriggers ){
139224
- pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
139225
- }else{
139226
- pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
139227
- }
139228
- if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
139229
- assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
139230
- if( !isIgnoreErrors || db->mallocFailed ) return;
139231
- if( pTo==0 ){
139232
- /* If isIgnoreErrors is true, then a table is being dropped. In this
139233
- ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
139234
- ** before actually dropping it in order to check FK constraints.
139235
- ** If the parent table of an FK constraint on the current table is
139236
- ** missing, behave as if it is empty. i.e. decrement the relevant
139237
- ** FK counter for each row of the current table with non-NULL keys.
139238
- */
139239
- Vdbe *v = sqlite3GetVdbe(pParse);
139240
- int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
139241
- for(i=0; i<pFKey->nCol; i++){
139242
- int iFromCol, iReg;
139243
- iFromCol = pFKey->aCol[i].iFrom;
139244
- iReg = sqlite3TableColumnToStorage(pFKey->pFrom,iFromCol) + regOld+1;
139245
- sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
139246
- }
139247
- sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
139248
- }
139249
- continue;
139250
- }
139251
- assert( pFKey->nCol==1 || (aiFree && pIdx) );
139252
-
139253
- if( aiFree ){
139254
- aiCol = aiFree;
139255
- }else{
139256
- iCol = pFKey->aCol[0].iFrom;
139257
- aiCol = &iCol;
139258
- }
139259
- for(i=0; i<pFKey->nCol; i++){
139260
- if( aiCol[i]==pTab->iPKey ){
139261
- aiCol[i] = -1;
139262
- }
139263
- assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
139264
-#ifndef SQLITE_OMIT_AUTHORIZATION
139265
- /* Request permission to read the parent key columns. If the
139266
- ** authorization callback returns SQLITE_IGNORE, behave as if any
139267
- ** values read from the parent table are NULL. */
139268
- if( db->xAuth ){
139269
- int rcauth;
139270
- char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zCnName;
139271
- rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
139272
- bIgnore = (rcauth==SQLITE_IGNORE);
139273
- }
139274
-#endif
139275
- }
139276
-
139277
- /* Take a shared-cache advisory read-lock on the parent table. Allocate
139278
- ** a cursor to use to search the unique index on the parent key columns
139279
- ** in the parent table. */
139280
- sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
139281
- pParse->nTab++;
139282
-
139283
- if( regOld!=0 ){
139284
- /* A row is being removed from the child table. Search for the parent.
139285
- ** If the parent does not exist, removing the child row resolves an
139286
- ** outstanding foreign key constraint violation. */
139287
- fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
139288
- }
139289
- if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
139290
- /* A row is being added to the child table. If a parent row cannot
139291
- ** be found, adding the child row has violated the FK constraint.
139292
- **
139293
- ** If this operation is being performed as part of a trigger program
139294
- ** that is actually a "SET NULL" action belonging to this very
139295
- ** foreign key, then omit this scan altogether. As all child key
139296
- ** values are guaranteed to be NULL, it is not possible for adding
139297
- ** this row to cause an FK violation. */
139298
- fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
139299
- }
139300
-
139301
- sqlite3DbFree(db, aiFree);
139909
+ ** child table (the table that the foreign key definition is part of).
139910
+ **
139911
+ ** Immediate constraints are processed first, then deferred constraints
139912
+ ** in a second pass. This is because immediate FK processing may halt
139913
+ ** the VM, and in cases where there is no statement journal this needs
139914
+ ** to happen before any deferred FKs are processed. */
139915
+ for(iPass=0; iPass<2; iPass++){
139916
+ for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
139917
+ Table *pTo; /* Parent table of foreign key pFKey */
139918
+ Index *pIdx = 0; /* Index on key columns in pTo */
139919
+ int *aiFree = 0;
139920
+ int *aiCol;
139921
+ int iCol;
139922
+ int i;
139923
+ int bIgnore = 0;
139924
+
139925
+ assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
139926
+ if( pFKey->isDeferred!=iPass ) continue;
139927
+
139928
+ if( aChange
139929
+ && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
139930
+ && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
139931
+ ){
139932
+ continue;
139933
+ }
139934
+
139935
+ /* Find the parent table of this foreign key. Also find a unique index
139936
+ ** on the parent key columns in the parent table. If either of these
139937
+ ** schema items cannot be located, set an error in pParse and return
139938
+ ** early. */
139939
+ if( pParse->disableTriggers ){
139940
+ pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
139941
+ }else{
139942
+ pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
139943
+ }
139944
+ if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
139945
+ assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
139946
+ if( !isIgnoreErrors || db->mallocFailed ) return;
139947
+ if( pTo==0 ){
139948
+ /* If isIgnoreErrors is true, then a table is being dropped. In this
139949
+ ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
139950
+ ** before actually dropping it in order to check FK constraints.
139951
+ ** If the parent table of an FK constraint on the current table is
139952
+ ** missing, behave as if it is empty. i.e. decrement the relevant
139953
+ ** FK counter for each row of the current table with non-NULL keys.
139954
+ */
139955
+ Vdbe *v = sqlite3GetVdbe(pParse);
139956
+ int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
139957
+ for(i=0; i<pFKey->nCol; i++){
139958
+ int iFromCol, iReg;
139959
+ iFromCol = pFKey->aCol[i].iFrom;
139960
+ iReg = sqlite3TableColumnToStorage(pFKey->pFrom,iFromCol)+regOld+1;
139961
+ sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
139962
+ }
139963
+ sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
139964
+ }
139965
+ continue;
139966
+ }
139967
+ assert( pFKey->nCol==1 || (aiFree && pIdx) );
139968
+
139969
+ if( aiFree ){
139970
+ aiCol = aiFree;
139971
+ }else{
139972
+ iCol = pFKey->aCol[0].iFrom;
139973
+ aiCol = &iCol;
139974
+ }
139975
+ for(i=0; i<pFKey->nCol; i++){
139976
+ if( aiCol[i]==pTab->iPKey ){
139977
+ aiCol[i] = -1;
139978
+ }
139979
+ assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
139980
+ #ifndef SQLITE_OMIT_AUTHORIZATION
139981
+ /* Request permission to read the parent key columns. If the
139982
+ ** authorization callback returns SQLITE_IGNORE, behave as if any
139983
+ ** values read from the parent table are NULL. */
139984
+ if( db->xAuth ){
139985
+ int rcauth;
139986
+ char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zCnName;
139987
+ rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
139988
+ bIgnore = (rcauth==SQLITE_IGNORE);
139989
+ }
139990
+ #endif
139991
+ }
139992
+
139993
+ /* Take a shared-cache advisory read-lock on the parent table. Allocate
139994
+ ** a cursor to use to search the unique index on the parent key columns
139995
+ ** in the parent table. */
139996
+ sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
139997
+ pParse->nTab++;
139998
+
139999
+ if( regOld!=0 ){
140000
+ /* A row is being removed from the child table. Search for the parent.
140001
+ ** If the parent does not exist, removing the child row resolves an
140002
+ ** outstanding foreign key constraint violation. */
140003
+ fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld,-1,bIgnore);
140004
+ }
140005
+ if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
140006
+ /* A row is being added to the child table. If a parent row cannot
140007
+ ** be found, adding the child row has violated the FK constraint.
140008
+ **
140009
+ ** If this operation is being performed as part of a trigger program
140010
+ ** that is actually a "SET NULL" action belonging to this very
140011
+ ** foreign key, then omit this scan altogether. As all child key
140012
+ ** values are guaranteed to be NULL, it is not possible for adding
140013
+ ** this row to cause an FK violation. */
140014
+ fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew,+1,bIgnore);
140015
+ }
140016
+
140017
+ sqlite3DbFree(db, aiFree);
140018
+ }
139302140019
}
139303140020
139304140021
/* Loop through all the foreign key constraints that refer to this table.
139305140022
** (the "child" constraints) */
139306140023
for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
@@ -139343,14 +140060,20 @@
139343140060
if( regOld!=0 ){
139344140061
int eAction = pFKey->aAction[aChange!=0];
139345140062
if( (db->flags & SQLITE_FkNoAction) ) eAction = OE_None;
139346140063
139347140064
fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
139348
- /* If this is a deferred FK constraint, or a CASCADE or SET NULL
139349
- ** action applies, then any foreign key violations caused by
139350
- ** removing the parent key will be rectified by the action trigger.
139351
- ** So do not set the "may-abort" flag in this case.
140065
+ /* If this is an immediate FK constraint, then foreign key violations
140066
+ ** caused by removing the parent key may cause an abort.
140067
+ **
140068
+ ** Except - if a CASCADE or SET NULL action applies, then any such
140069
+ ** foreign key violations will be rectified by the action trigger. So
140070
+ ** do not set the "may-abort" flag in this case.
140071
+ **
140072
+ ** Except - if there are BEFORE triggers on the child table, then
140073
+ ** one of them may use RAISE(IGNORE) to prevent the SET NULL or
140074
+ ** CASCADE action from taking place. Do set the "may-abort" flag then.
139352140075
**
139353140076
** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
139354140077
** may-abort flag will eventually be set on this statement anyway
139355140078
** (when this function is called as part of processing the UPDATE
139356140079
** within the action trigger).
@@ -139360,11 +140083,14 @@
139360140083
** applies. The trouble starts if the CASCADE or SET NULL action
139361140084
** trigger causes other triggers or action rules attached to the
139362140085
** child table to fire. In these cases the fk constraint counters
139363140086
** might be set incorrectly if any OP_FkCounter related scans are
139364140087
** omitted. */
139365
- if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
140088
+ if( !pFKey->isDeferred && (
140089
+ (eAction!=OE_Cascade && eAction!=OE_SetNull)
140090
+ || fkBeforeTriggersExist(pParse, pFKey, aChange!=0)
140091
+ )){
139366140092
sqlite3MayAbort(pParse);
139367140093
}
139368140094
}
139369140095
pItem->zName = 0;
139370140096
sqlite3SrcListDelete(db, pSrc);
@@ -139423,11 +140149,16 @@
139423140149
**
139424140150
** * There are any FKs for which pTab is the child and the parent table
139425140151
** and any FK processing at all is required (even of a different FK), or
139426140152
**
139427140153
** * the UPDATE modifies one or more parent keys for which the action is
139428
-** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
140154
+** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL), or
140155
+**
140156
+** * the UPDATE modifies one or more parent keys of an FK for which pTab
140157
+** is also the child table. The old version of the row must be removed
140158
+** from the table before the FK checks run, as otherwise the scan for
140159
+** rows that refer to the new parent key may find it.
139429140160
**
139430140161
** Or, assuming some other foreign key processing is required, 1.
139431140162
*/
139432140163
SQLITE_PRIVATE int sqlite3FkRequired(
139433140164
Parse *pParse, /* Parse context */
@@ -139462,10 +140193,11 @@
139462140193
if( (pParse->db->flags & SQLITE_FkNoAction)==0
139463140194
&& p->aAction[1]!=OE_None
139464140195
){
139465140196
return 2;
139466140197
}
140198
+ if( p->pFrom==pTab ) eRet = 2;
139467140199
bHaveFK = 1;
139468140200
}
139469140201
}
139470140202
}
139471140203
}
@@ -140403,10 +141135,22 @@
140403141135
if( 0!=sqlite3ExprAffinity(pExpr) ) return 0;
140404141136
}
140405141137
return 1;
140406141138
140407141139
}
141140
+
141141
+/*
141142
+** Return true if any expression in the expression-list passed as the
141143
+** only argument contains a COLLATE operator.
141144
+*/
141145
+static int exprListHasCollate(ExprList *pRow){
141146
+ int ii;
141147
+ for(ii=0; ii<pRow->nExpr; ii++){
141148
+ if( ExprHasProperty(pRow->a[ii].pExpr, EP_Collate) ) return 1;
141149
+ }
141150
+ return 0;
141151
+}
140408141152
140409141153
/*
140410141154
** This function is called by the parser for the second and subsequent
140411141155
** rows of a multi-row VALUES clause. Argument pLeft is the part of
140412141156
** the VALUES clause already parsed, argument pRow is the vector of values
@@ -140454,18 +141198,28 @@
140454141198
** has an affinity (i.e. is a CAST expression). This causes problems
140455141199
** because the complex rules SQLite uses (see function
140456141200
** sqlite3SubqueryColumnTypes() in select.c) to determine the effective
140457141201
** affinity of such a column for all rows require access to all values in
140458141202
** the column simultaneously.
141203
+**
141204
+** e) The new row, or the row that would become the first row of the
141205
+** co-routine, contains a COLLATE operator. This ensures that the
141206
+** columns of a co-routine never have a collation sequence (see
141207
+** multiSelectCollSeq() in select.c). Each explicit COLLATE in a VALUES
141208
+** clause is instead part of an ordinary SELECT in a UNION ALL
141209
+** compound, where it is available when the collation sequence for a
141210
+** compound SELECT column is determined.
140459141211
*/
140460141212
SQLITE_PRIVATE Select *sqlite3MultiValues(Parse *pParse, Select *pLeft, ExprList *pRow){
140461141213
140462141214
if( pParse->bHasWith /* condition (a) above */
140463141215
|| pParse->db->init.busy /* condition (b) above */
140464141216
|| sqlite3ExprListIsConstant(pParse, pRow, 1)==0 /* condition (c) above */
140465141217
|| (pLeft->pSrc->nSrc==0 &&
140466141218
exprListIsNoAffinity(pParse,pLeft->pEList)==0) /* condition (d) above */
141219
+ || exprListHasCollate(pRow) /* condition (e) above */
141220
+ || (pLeft->pSrc->nSrc==0 && exprListHasCollate(pLeft->pEList))
140467141221
|| IN_SPECIAL_PARSE
140468141222
){
140469141223
/* The co-routine method cannot be used. Fall back to UNION ALL. */
140470141224
Select *pSelect = 0;
140471141225
int f = SF_Values | SF_MultiValue;
@@ -140503,11 +141257,11 @@
140503141257
SelectDest dest;
140504141258
Subquery *pSubq;
140505141259
pRet->pSrc->nSrc = 1;
140506141260
pRet->pPrior = pLeft->pPrior;
140507141261
pRet->op = pLeft->op;
140508
- if( pRet->pPrior ) pRet->selFlags |= SF_Values;
141262
+ pRet->selFlags |= SF_Values;
140509141263
pLeft->pPrior = 0;
140510141264
pLeft->op = TK_SELECT;
140511141265
assert( pLeft->pNext==0 );
140512141266
assert( pRet->pNext==0 );
140513141267
p = &pRet->pSrc->a[0];
@@ -140729,11 +141483,15 @@
140729141483
140730141484
/* If the Select object is really just a simple VALUES() list with a
140731141485
** single row (the common case) then keep that one row of values
140732141486
** and discard the other (unused) parts of the pSelect object
140733141487
*/
140734
- if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
141488
+ if( pSelect
141489
+ && (pSelect->selFlags & SF_Values)!=0
141490
+ && pSelect->pPrior==0
141491
+ && pSelect->pSrc->nSrc==0
141492
+ ){
140735141493
pList = pSelect->pEList;
140736141494
pSelect->pEList = 0;
140737141495
sqlite3SelectDelete(db, pSelect);
140738141496
pSelect = 0;
140739141497
}
@@ -142054,10 +142812,16 @@
142054142812
if( pUpsertClause!=0 ){
142055142813
if( pUpsertClause->isDoUpdate==0 ){
142056142814
onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
142057142815
}else{
142058142816
onError = OE_Update; /* DO UPDATE */
142817
+ /* The excluded.* values used by the DO UPDATE must have
142818
+ ** column affinity applied before the rowid conflict check. */
142819
+ if( bAffinityDone==0 ){
142820
+ sqlite3TableAffinity(v, pTab, regNewData+1);
142821
+ bAffinityDone = 1;
142822
+ }
142059142823
}
142060142824
}
142061142825
if( pUpsertClause!=pUpsert ){
142062142826
/* The first ON CONFLICT clause has a conflict target other than
142063142827
** the IPK. We have to jump ahead to that first ON CONFLICT clause
@@ -142213,10 +142977,18 @@
142213142977
bAffinityDone = 1;
142214142978
}
142215142979
VdbeNoopComment((v, "prep index %s", pIdx->zName));
142216142980
iThisCur = iIdxCur+ix;
142217142981
142982
+ /* If an OE_Replace resolution earlier in the constraint checks may
142983
+ ** have already deleted a conflicting row, and evaluating the partial
142984
+ ** index WHERE clause or an indexed expression for this index might
142985
+ ** raise an error, then a statement journal may be required to undo
142986
+ ** the deletion. */
142987
+ if( seenReplace && (pIdx->pPartIdxWhere || pIdx->aColExpr) ){
142988
+ sqlite3MultiWrite(pParse);
142989
+ }
142218142990
142219142991
/* Skip partial indices for which the WHERE clause is not true */
142220142992
if( pIdx->pPartIdxWhere ){
142221142993
sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
142222142994
pParse->iSelfTab = -(regNewData+1);
@@ -142897,10 +143669,13 @@
142897143669
return 0; /* FROM clause must have exactly one term */
142898143670
}
142899143671
if( pSelect->pSrc->a[0].fg.isSubquery ){
142900143672
return 0; /* FROM clause cannot contain a subquery */
142901143673
}
143674
+ if( pSelect->pSrc->a[0].fg.isIndexedBy ){
143675
+ return 0; /* FROM clause cannot have an INDEXED BY clause */
143676
+ }
142902143677
if( pSelect->pWhere ){
142903143678
return 0; /* SELECT may not have a WHERE clause */
142904143679
}
142905143680
if( pSelect->pOrderBy ){
142906143681
return 0; /* SELECT may not have an ORDER BY clause */
@@ -143064,19 +143839,21 @@
143064143839
){
143065143840
return 0; /* Tables have different CHECK constraints. Ticket #2252 */
143066143841
}
143067143842
#endif
143068143843
#ifndef SQLITE_OMIT_FOREIGN_KEY
143069
- /* Disallow the transfer optimization if the destination table contains
143070
- ** any foreign key constraints. This is more restrictive than necessary.
143071
- ** But the main beneficiary of the transfer optimization is the VACUUM
143072
- ** command, and the VACUUM command disables foreign key constraints. So
143073
- ** the extra complication to make this rule less restrictive is probably
143074
- ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
143075
- */
143844
+ /* Disallow the transfer optimization if foreign key processing is
143845
+ ** enabled and the destination table is either the child or the parent
143846
+ ** of any foreign key constraint. This is more restrictive than
143847
+ ** necessary. But the main beneficiary of the transfer optimization is
143848
+ ** the VACUUM command, and the VACUUM command disables foreign key
143849
+ ** constraints. So the extra complication to make this rule less
143850
+ ** restrictive is probably not worth the effort. Ticket
143851
+ ** [6284df89debdfa61db8073e062908af0c9b6118e] and bugs forum post
143852
+ ** [2026-11-04T20:24:15Z]. */
143076143853
assert( IsOrdinaryTable(pDest) );
143077
- if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->u.tab.pFKey!=0 ){
143854
+ if( sqlite3FkRequired(pParse, pDest, 0, 0) ){
143078143855
return 0;
143079143856
}
143080143857
#endif
143081143858
if( (db->flags & SQLITE_CountRows)!=0 ){
143082143859
return 0; /* xfer opt does not play well with PRAGMA count_changes */
@@ -146157,17 +146934,26 @@
146157146934
** Helper subroutine for PRAGMA integrity_check:
146158146935
**
146159146936
** Generate code to output a single-column result row with a value of the
146160146937
** string held in register 3. Decrement the result count in register 1
146161146938
** and halt if the maximum number of result rows have been issued.
146939
+**
146940
+** If iCol is not negative, then after the result row has been output,
146941
+** also load column iCol of cursor iCur into register 3. This is to ensure
146942
+** the cursor's column cache is valid after it is invalidated by the
146943
+** OP_ResultRow.
146162146944
*/
146163
-static int integrityCheckResultRow(Vdbe *v){
146945
+static int integrityCheckResultRow(Vdbe *v, int iCur, int iCol){
146164146946
int addr;
146165146947
sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
146166146948
addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
146167146949
VdbeCoverage(v);
146168146950
sqlite3VdbeAddOp0(v, OP_Halt);
146951
+ if( iCol>=0 ){
146952
+ sqlite3VdbeAddOp3(v, OP_Column, iCur, iCol, 3);
146953
+ sqlite3VdbeTypeofColumn(v, 3);
146954
+ }
146169146955
return addr;
146170146956
}
146171146957
146172146958
/*
146173146959
** Should table pTab be skipped when doing an integrity_check?
@@ -147567,11 +148353,11 @@
147567148353
addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
147568148354
sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
147569148355
sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
147570148356
P4_DYNAMIC);
147571148357
sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
147572
- integrityCheckResultRow(v);
148358
+ integrityCheckResultRow(v, 0, -1);
147573148359
sqlite3VdbeJumpHere(v, addr);
147574148360
147575148361
/* Check that the indexes all have the right number of rows */
147576148362
cnt = pObjTab ? 1 : 0;
147577148363
sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
@@ -147593,11 +148379,11 @@
147593148379
if( pIdx->pPartIdxWhere==0 ){
147594148380
addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+cnt, 0, 8+iTab);
147595148381
VdbeCoverageNeverNull(v);
147596148382
sqlite3VdbeLoadString(v, 4, pIdx->zName);
147597148383
sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
147598
- integrityCheckResultRow(v);
148384
+ integrityCheckResultRow(v, 0, -1);
147599148385
sqlite3VdbeJumpHere(v, addr);
147600148386
}
147601148387
cnt++;
147602148388
}
147603148389
}
@@ -147639,25 +148425,20 @@
147639148425
** will also prepopulate the cursor column cache that is used
147640148426
** by the OP_IsType code, so it is a required step.
147641148427
*/
147642148428
assert( !IsVirtual(pTab) );
147643148429
if( HasRowid(pTab) ){
147644
- mxCol = -1;
147645
- for(j=0; j<pTab->nCol; j++){
147646
- if( (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)==0 ) mxCol++;
147647
- }
147648
- if( mxCol==pTab->iPKey ) mxCol--;
148430
+ mxCol = pTab->nNVCol-1;
147649148431
}else{
147650148432
/* COLFLAG_VIRTUAL columns are not included in the WITHOUT ROWID
147651148433
** PK index column-count, so there is no need to account for them
147652148434
** in this case. */
147653148435
mxCol = sqlite3PrimaryKeyIndex(pTab)->nColumn-1;
147654148436
}
147655
- if( mxCol>=0 ){
147656
- sqlite3VdbeAddOp3(v, OP_Column, iDataCur, mxCol, 3);
147657
- sqlite3VdbeTypeofColumn(v, 3);
147658
- }
148437
+ assert( mxCol>=0 );
148438
+ sqlite3VdbeAddOp3(v, OP_Column, iDataCur, mxCol, 3);
148439
+ sqlite3VdbeTypeofColumn(v, 3);
147659148440
147660148441
if( !isQuick ){
147661148442
if( pPk ){
147662148443
/* Verify WITHOUT ROWID keys are in ascending order */
147663148444
int a1;
@@ -147667,11 +148448,11 @@
147667148448
sqlite3VdbeAddOp1(v, OP_IsNull, r2); VdbeCoverage(v);
147668148449
zErr = sqlite3MPrintf(db,
147669148450
"row not in PRIMARY KEY order for %s",
147670148451
pTab->zName);
147671148452
sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
147672
- integrityCheckResultRow(v);
148453
+ integrityCheckResultRow(v, iDataCur, mxCol);
147673148454
sqlite3VdbeJumpHere(v, a1);
147674148455
sqlite3VdbeJumpHere(v, a1+1);
147675148456
for(j=0; j<pPk->nKeyCol; j++){
147676148457
sqlite3ExprCodeLoadIndexColumn(pParse, pPk, iDataCur, j, r2+j);
147677148458
}
@@ -147804,11 +148585,11 @@
147804148585
zErr = sqlite3MPrintf(db, "TEXT value in %s.%s",
147805148586
pTab->zName, pTab->aCol[j].zCnName);
147806148587
sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
147807148588
}
147808148589
sqlite3VdbeResolveLabel(v, labelError);
147809
- integrityCheckResultRow(v);
148590
+ integrityCheckResultRow(v, iDataCur, mxCol);
147810148591
sqlite3VdbeResolveLabel(v, labelOk);
147811148592
}
147812148593
/* Verify CHECK constraints */
147813148594
if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
147814148595
ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
@@ -147826,11 +148607,11 @@
147826148607
sqlite3VdbeResolveLabel(v, addrCkFault);
147827148608
pParse->iSelfTab = 0;
147828148609
zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
147829148610
pTab->zName);
147830148611
sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
147831
- integrityCheckResultRow(v);
148612
+ integrityCheckResultRow(v, 0, -1);
147832148613
sqlite3VdbeResolveLabel(v, addrCkOk);
147833148614
}
147834148615
sqlite3ExprListDelete(db, pCheck);
147835148616
}
147836148617
if( !isQuick ){ /* Omit the remaining tests for quick_check */
@@ -147852,21 +148633,21 @@
147852148633
sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
147853148634
sqlite3MPrintf(db, "index %s stores an imprecise floating-point "
147854148635
"value for row ", pIdx->zName),
147855148636
P4_DYNAMIC);
147856148637
sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
147857
- integrityCheckResultRow(v);
148638
+ integrityCheckResultRow(v, 0, -1);
147858148639
sqlite3VdbeAddOp2(v, OP_Goto, 0, ckUniq);
147859148640
147860148641
sqlite3VdbeJumpHere(v, jmp2);
147861148642
sqlite3VdbeLoadString(v, 3, "row ");
147862148643
sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
147863148644
sqlite3VdbeLoadString(v, 4, " missing from index ");
147864148645
sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
147865148646
jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
147866148647
sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
147867
- jmp4 = integrityCheckResultRow(v);
148648
+ jmp4 = integrityCheckResultRow(v, 0, -1);
147868148649
sqlite3VdbeResolveLabel(v, ckUniq);
147869148650
147870148651
/* The OP_IdxRowid opcode is an optimized version of OP_Column
147871148652
** that extracts the rowid off the end of the index record.
147872148653
** But it only works correctly if index record does not have
@@ -147961,11 +148742,11 @@
147961148742
if( pVTab->pModule->xIntegrity==0 ) continue;
147962148743
sqlite3VdbeAddOp3(v, OP_VCheck, i, 3, isQuick);
147963148744
pTab->nTabRef++;
147964148745
sqlite3VdbeAppendP4(v, pTab, P4_TABLEREF);
147965148746
a1 = sqlite3VdbeAddOp1(v, OP_IsNull, 3); VdbeCoverage(v);
147966
- integrityCheckResultRow(v);
148747
+ integrityCheckResultRow(v, 0, -1);
147967148748
sqlite3VdbeJumpHere(v, a1);
147968148749
continue;
147969148750
}
147970148751
#endif
147971148752
}
@@ -148761,15 +149542,17 @@
148761149542
PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
148762149543
int rc;
148763149544
int i, j;
148764149545
StrAccum acc;
148765149546
char *zSql;
149547
+ int type0 = SQLITE_NULL;
148766149548
148767149549
UNUSED_PARAMETER(idxNum);
148768149550
UNUSED_PARAMETER(idxStr);
148769149551
pragmaVtabCursorClear(pCsr);
148770149552
j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
149553
+ if( argc>0 ) type0 = sqlite3_value_type(argv[0]);
148771149554
for(i=0; i<argc; i++, j++){
148772149555
const char *zText = (const char*)sqlite3_value_text(argv[i]);
148773149556
assert( j<ArraySize(pCsr->azArg) );
148774149557
assert( pCsr->azArg[j]==0 );
148775149558
if( zText ){
@@ -148784,11 +149567,15 @@
148784149567
if( pCsr->azArg[1] ){
148785149568
sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
148786149569
}
148787149570
sqlite3_str_appendall(&acc, pTab->pName->zName);
148788149571
if( pCsr->azArg[0] ){
148789
- sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
149572
+ if( type0<=SQLITE_FLOAT ){
149573
+ sqlite3_str_appendf(&acc, "=%s", pCsr->azArg[0]);
149574
+ }else{
149575
+ sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
149576
+ }
148790149577
}
148791149578
zSql = sqlite3StrAccumFinish(&acc);
148792149579
if( zSql==0 ) return SQLITE_NOMEM;
148793149580
rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
148794149581
sqlite3_free(zSql);
@@ -149018,10 +149805,17 @@
149018149805
const char *zEnd;
149019149806
TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
149020149807
149021149808
assert( db->init.busy );
149022149809
db->init.iDb = iDb;
149810
+
149811
+ /* We never try to parse a trigger on a read-only database */
149812
+ assert( db->aDb[iDb].pBt==0
149813
+ || sqlite3BtreeIsReadonly(db->aDb[iDb].pBt)==0
149814
+ || sqlite3_stricmp(argv[0],"trigger")!=0
149815
+ || CORRUPT_DB );
149816
+
149023149817
if( sqlite3GetUInt32(argv[3], &db->init.newTnum)==0
149024149818
|| (db->init.newTnum>pData->mxPage && pData->mxPage>0)
149025149819
){
149026149820
if( sqlite3Config.bExtraSchemaChecks ){
149027149821
corruptSchema(pData, argv, "invalid rootpage");
@@ -149267,12 +150061,13 @@
149267150061
assert( db->init.busy );
149268150062
initData.mxPage = sqlite3BtreeLastPage(pDb->pBt);
149269150063
{
149270150064
char *zSql;
149271150065
zSql = sqlite3MPrintf(db,
149272
- "SELECT*FROM\"%w\".%s ORDER BY rowid",
149273
- db->aDb[iDb].zDbSName, zSchemaTabName);
150066
+ "SELECT*FROM\"%w\".%s %sORDER BY rowid",
150067
+ db->aDb[iDb].zDbSName, zSchemaTabName,
150068
+ sqlite3BtreeIsReadonly(db->aDb[iDb].pBt)?"WHERE type<>'trigger'":"");
149274150069
#ifndef SQLITE_OMIT_AUTHORIZATION
149275150070
{
149276150071
sqlite3_xauth xAuth;
149277150072
xAuth = db->xAuth;
149278150073
db->xAuth = 0;
@@ -149289,10 +150084,16 @@
149289150084
sqlite3AnalysisLoad(db, iDb);
149290150085
}
149291150086
#endif
149292150087
}
149293150088
assert( pDb == &(db->aDb[iDb]) );
150089
+
150090
+ /* Confirm that TRIGGERs are not parsed on a read-only database */
150091
+ assert( sqlite3BtreeIsReadonly(pDb->pBt)==0
150092
+ || sqliteHashCount(&pDb->pSchema->trigHash)==0
150093
+ || CORRUPT_DB );
150094
+
149294150095
if( db->mallocFailed ){
149295150096
rc = SQLITE_NOMEM_BKPT;
149296150097
sqlite3ResetAllSchemasOfConnection(db);
149297150098
pDb = &db->aDb[iDb];
149298150099
}else
@@ -149324,11 +150125,11 @@
149324150125
error_out:
149325150126
if( rc ){
149326150127
if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
149327150128
sqlite3OomFault(db);
149328150129
}
149329
- sqlite3ResetOneSchema(db, iDb);
150130
+ sqlite3ResetOneSchema(db, iDb, 0);
149330150131
}
149331150132
db->init.busy = 0;
149332150133
return rc;
149333150134
}
149334150135
@@ -149426,11 +150227,11 @@
149426150227
** set Parse.rc to SQLITE_SCHEMA. */
149427150228
sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
149428150229
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
149429150230
if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
149430150231
if( DbHasProperty(db, iDb, DB_SchemaLoaded) ) pParse->rc = SQLITE_SCHEMA;
149431
- sqlite3ResetOneSchema(db, iDb);
150232
+ sqlite3ResetOneSchema(db, iDb, 0);
149432150233
}
149433150234
149434150235
/* Close the transaction, if one was opened. */
149435150236
if( openedTransaction ){
149436150237
sqlite3BtreeCommit(pBt);
@@ -149768,11 +150569,11 @@
149768150569
rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
149769150570
assert( rc==SQLITE_OK || *ppStmt==0 );
149770150571
if( rc==SQLITE_OK || db->mallocFailed ) break;
149771150572
cnt++;
149772150573
}while( (rc==SQLITE_ERROR_RETRY && ALWAYS(cnt<=SQLITE_MAX_PREPARE_RETRY))
149773
- || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt)==1) );
150574
+ || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1,0), cnt)==1) );
149774150575
sqlite3BtreeLeaveAll(db);
149775150576
assert( rc!=SQLITE_ERROR_RETRY );
149776150577
rc = sqlite3ApiExit(db, rc);
149777150578
assert( (rc&db->errMask)==rc );
149778150579
db->busyHandler.nBusy = 0;
@@ -150492,10 +151293,41 @@
150492151293
}
150493151294
unsetJoinExpr(p->pLeft, iTable, nullable);
150494151295
p = p->pRight;
150495151296
}
150496151297
}
151298
+
151299
+/*
151300
+** Tree walker expression callback for clearOuterOnExpr().
151301
+**
151302
+** If the Expr node is marked as coming from an outer join for
151303
+** table pWalker->u.iCur, then clear its join markers completely.
151304
+*/
151305
+static int clearOuterOnExprCb(Walker *pWalker, Expr *p){
151306
+ if( ExprHasProperty(p, EP_OuterON) && p->w.iJoin==pWalker->u.iCur ){
151307
+ ExprClearProperty(p, EP_OuterON|EP_InnerON);
151308
+ }
151309
+ return WRC_Continue;
151310
+}
151311
+
151312
+/*
151313
+** Remove the EP_OuterON mark, without substituting EP_InnerON, from every
151314
+** term of the expression tree p that is marked EP_OuterON with w.iJoin==iTable.
151315
+** The resulting terms are ordinary WHERE-clause terms.
151316
+**
151317
+** This is used when table iTable was marked as an outer-join table only
151318
+** because it was the left operand of a RIGHT JOIN (JT_LTORJ) and that
151319
+** status has been removed by OUTER JOIN strength reduction.
151320
+*/
151321
+static void clearOuterOnExpr(Expr *p, int iTable){
151322
+ Walker w;
151323
+ memset(&w, 0, sizeof(w));
151324
+ w.u.iCur = iTable;
151325
+ w.xExprCallback = clearOuterOnExprCb;
151326
+ w.xSelectCallback = 0;
151327
+ sqlite3WalkExpr(&w,p);
151328
+}
150497151329
150498151330
/*
150499151331
** This routine processes the join information for a SELECT statement.
150500151332
**
150501151333
** * A NATURAL join is converted into a USING join. After that, we
@@ -150522,10 +151354,11 @@
150522151354
SrcItem *pLeft; /* Left table being joined */
150523151355
SrcItem *pRight; /* Right table being joined */
150524151356
int bSeenTFunc = 0; /* True if have seen table-valued function */
150525151357
150526151358
pSrc = p->pSrc;
151359
+ if( pSrc->nSrc<=1 ) return 0;
150527151360
pLeft = &pSrc->a[0];
150528151361
pRight = &pLeft[1];
150529151362
for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
150530151363
Table *pRightTab = pRight->pSTab;
150531151364
u32 joinType;
@@ -151254,17 +152087,17 @@
151254152087
if( srcTab>=0 ){
151255152088
for(i=0; i<nResultCol; i++){
151256152089
sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
151257152090
VdbeComment((v, "%s", p->pEList->a[i].zEName));
151258152091
}
151259
- }else if( eDest!=SRT_Exists ){
152092
+ }else if( eDest!=SRT_Exists || hasDistinct ){
152093
+ /* If the destination is an EXISTS(...) expression, the actual
152094
+ ** values returned by the SELECT are only required if the query is
152095
+ ** DISTINCT. */
151260152096
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
151261152097
ExprList *pExtra = 0;
151262152098
#endif
151263
- /* If the destination is an EXISTS(...) expression, the actual
151264
- ** values returned by the SELECT are not required.
151265
- */
151266152099
u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
151267152100
ExprList *pEList;
151268152101
if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
151269152102
ecelFlags = SQLITE_ECEL_DUP;
151270152103
}else{
@@ -152647,16 +153480,20 @@
152647153480
pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
152648153481
}else{
152649153482
pRet = 0;
152650153483
}
152651153484
assert( iCol>=0 );
152652
- /* iCol must be less than p->pEList->nExpr. Otherwise an error would
153485
+ /* iCol must be less than p->pEList->nExpr. Otherwise an error would
152653153486
** have been thrown during name resolution and we would not have gotten
152654
- ** this far */
152655
- if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
153487
+ ** this far. If p is really a multi-row VALUES statement, it is guaranteed
153488
+ ** not to have any collation sequences. So leave pRet set to 0 in this case */
153489
+ if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr)
153490
+ && ((p->selFlags & SF_Values)==0 || p->pSrc->nSrc==0) /* multi-row VALUES */
153491
+ ){
152656153492
pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
152657153493
}
153494
+
152658153495
return pRet;
152659153496
}
152660153497
152661153498
/*
152662153499
** The select statement passed as the second parameter is a compound SELECT
@@ -152864,11 +153701,11 @@
152864153701
152865153702
/* Find the next row in the Queue and output that row */
152866153703
addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
152867153704
152868153705
/* Transfer the next row in Queue over to Current */
152869
- sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
153706
+ sqlite3VdbeAddOp1(v, OP_Stale, iCurrent); /* To reset column cache */
152870153707
if( pOrderBy ){
152871153708
sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
152872153709
}else{
152873153710
sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
152874153711
}
@@ -152968,10 +153805,21 @@
152968153805
*/
152969153806
static int hasAnchor(Select *p){
152970153807
while( p && (p->selFlags & SF_Recursive)!=0 ){ p = p->pPrior; }
152971153808
return p!=0;
152972153809
}
153810
+
153811
+/*
153812
+** Return TRUE if every compound operator in the compound SELECT that
153813
+** ends with p is UNION ALL.
153814
+*/
153815
+static int selectIsUnionAll(Select *p){
153816
+ for(; p->pPrior; p=p->pPrior){
153817
+ if( p->op!=TK_ALL ) return 0;
153818
+ }
153819
+ return 1;
153820
+}
152973153821
152974153822
/*
152975153823
** Return TRUE if p is a UNION with a LIMIT of exactly 1 and no OFFSET
152976153824
** clause. This is a precondition for a couple of related optimizations.
152977153825
**
@@ -153080,11 +153928,11 @@
153080153928
#endif
153081153929
if( p->pOrderBy ){
153082153930
/* If the compound has an ORDER BY clause, then always use the merge
153083153931
** algorithm. */
153084153932
return multiSelectByMerge(pParse, p, pDest);
153085
- }else if( p->op!=TK_ALL && !unionWithLimitOne(db,p) ){
153933
+ }else if( !selectIsUnionAll(p) && !unionWithLimitOne(db,p) ){
153086153934
/* If the compound is EXCEPT, INTERSECT, or UNION (anything other than
153087153935
** UNION ALL) then also always use the merge algorithm. However, the
153088153936
** multiSelectByMerge() routine requires that the compound have an
153089153937
** ORDER BY clause, and it doesn't right now. So invent one first. */
153090153938
Expr *pOne = sqlite3ExprInt32(db, 1);
@@ -153236,30 +154084,34 @@
153236154084
switch( pDest->eDest ){
153237154085
/* Store the result as data using a unique key.
153238154086
*/
153239154087
case SRT_Fifo:
153240154088
case SRT_DistFifo:
154089
+#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
153241154090
case SRT_Table:
154091
+#endif
153242154092
case SRT_EphemTab: {
153243154093
int r1 = sqlite3GetTempReg(pParse);
153244154094
int r2 = sqlite3GetTempReg(pParse);
153245154095
int iParm = pDest->iSDParm;
153246
- testcase( pDest->eDest==SRT_Table );
153247154096
testcase( pDest->eDest==SRT_EphemTab );
153248154097
testcase( pDest->eDest==SRT_Fifo );
153249154098
testcase( pDest->eDest==SRT_DistFifo );
153250154099
sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
154100
+#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
154101
+ testcase( pDest->eDest==SRT_Table );
153251154102
#if !defined(SQLITE_ENABLE_NULL_TRIM) && defined(SQLITE_DEBUG)
153252154103
/* A destination of SRT_Table and a non-zero iSDParm2 parameter means
153253154104
** that this is an "UPDATE ... FROM" on a virtual table or view. In this
153254154105
** case set the p5 parameter of the OP_MakeRecord to OPFLAG_NOCHNG_MAGIC.
153255154106
** This does not affect operation in any way - it just allows MakeRecord
153256154107
** to process OPFLAG_NOCHANGE values without an assert() failing. */
153257154108
if( pDest->eDest==SRT_Table && pDest->iSDParm2 ){
153258154109
sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
153259154110
}
153260
-#endif
154111
+#endif /* !ENABLE_NULL_TRIM && DEBUG */
154112
+#endif /* UPDATE_DELETE_LIMIT */
153261154113
#ifndef SQLITE_OMIT_CTE
153262154114
if( pDest->eDest==SRT_DistFifo ){
153263154115
/* If the destination is DistFifo, then cursor (iParm+1) is open
153264154116
** on an ephemeral index that is used to enforce uniqueness on the
153265154117
** total result. At this point, we are processing the setup portion
@@ -153863,10 +154715,19 @@
153863154715
**
153864154716
** When the subquery on the right side of the LEFT JOIN is flattened, we
153865154717
** have to add OP_IfNullRow in front of the OP_Integer that implements the
153866154718
** "m" value of the subquery so that a NULL will be loaded instead of 59
153867154719
** when processing a non-matched row of the left.
154720
+**
154721
+** ## Unwrap mode:
154722
+**
154723
+** If pEList is NULL, then the SubstContext is being used by
154724
+** unwrapIfNullRow() to remove TK_IF_NULL_ROW wrappers instead of to
154725
+** substitute column references. In that mode, only the TK_IF_NULL_ROW
154726
+** nodes with iTable==iTable are touched, each one being replaced by its
154727
+** operand. Column references are left alone and iNewTable must equal
154728
+** iTable.
153868154729
*/
153869154730
typedef struct SubstContext {
153870154731
Parse *pParse; /* The parsing context */
153871154732
int iTable; /* Replace references to this table */
153872154733
int iNewTable; /* New table number */
@@ -153904,10 +154765,11 @@
153904154765
testcase( ExprHasProperty(pExpr, EP_InnerON) );
153905154766
pExpr->w.iJoin = pSubst->iNewTable;
153906154767
}
153907154768
if( pExpr->op==TK_COLUMN
153908154769
&& pExpr->iTable==pSubst->iTable
154770
+ && pSubst->pEList!=0
153909154771
&& !ExprHasProperty(pExpr, EP_FixedCol)
153910154772
){
153911154773
#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
153912154774
if( pExpr->iColumn<0 ){
153913154775
pExpr->op = TK_NULL;
@@ -153975,13 +154837,23 @@
153975154837
pExpr = pNew;
153976154838
}
153977154839
}
153978154840
}else{
153979154841
if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
154842
+ if( pSubst->pEList==0 ){
154843
+ /* Unwrap mode. See unwrapIfNullRow(). */
154844
+ Expr *pInner = pExpr->pLeft;
154845
+ pExpr->pLeft = 0;
154846
+ sqlite3ExprDelete(pSubst->pParse->db, pExpr);
154847
+ return substExpr(pSubst, pInner);
154848
+ }
153980154849
pExpr->iTable = pSubst->iNewTable;
153981154850
}
153982
- if( pExpr->op==TK_AGG_FUNCTION && pExpr->op2>=pSubst->nSelDepth ){
154851
+ if( pExpr->op==TK_AGG_FUNCTION
154852
+ && pSubst->pEList!=0
154853
+ && pExpr->op2>=pSubst->nSelDepth
154854
+ ){
153983154855
pExpr->op2--;
153984154856
}
153985154857
pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
153986154858
pExpr->pRight = substExpr(pSubst, pExpr->pRight);
153987154859
if( ExprUseXSelect(pExpr) ){
@@ -154037,10 +154909,38 @@
154037154909
}
154038154910
}
154039154911
}while( doPrior && (p = p->pPrior)!=0 );
154040154912
pSubst->nSelDepth--;
154041154913
}
154914
+
154915
+/*
154916
+** The flattener wraps each substituted expression in a TK_IF_NULL_ROW
154917
+** operator when the subquery being flattened is on the NULL-able side of
154918
+** an outer join. The wrapper is keyed to the cursor iCur of the
154919
+** (single-table) subquery.
154920
+**
154921
+** If OUTER JOIN strength reduction later determines that the table with
154922
+** cursor iCur can no longer be a NULL row, then those wrappers are
154923
+** unnecessary. Worse, they are harmful if the FROM-clause term for iCur
154924
+** is itself a subquery that is flattened later. The flattener would
154925
+** then renumber the wrappers to refer to the first table of that
154926
+** subquery, and that table might legitimately be a NULL row (for example,
154927
+** if it is the left operand of a FULL JOIN inside the subquery). The
154928
+** substituted expressions would then be incorrectly forced to NULL.
154929
+**
154930
+** So when strength reduction removes the NULL-able status from the
154931
+** table at iCur, remove all of the TK_IF_NULL_ROW wrappers for iCur from
154932
+** the entire SELECT statement p.
154933
+*/
154934
+static void unwrapIfNullRow(Parse *pParse, Select *p, int iCur){
154935
+ SubstContext x;
154936
+ memset(&x, 0, sizeof(x));
154937
+ x.pParse = pParse;
154938
+ x.iTable = iCur;
154939
+ x.iNewTable = iCur;
154940
+ substSelect(&x, p, 0);
154941
+}
154042154942
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
154043154943
154044154944
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
154045154945
/*
154046154946
** pSelect is a SELECT statement and pSrcItem is one item in the FROM
@@ -154213,10 +155113,34 @@
154213155113
}
154214155114
return 0;
154215155115
}
154216155116
154217155117
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
155118
+/*
155119
+** Return true if the FROM clause pSrc, other than item iExcept, contains
155120
+** a subquery implemented using a co-routine. Such co-routines may have
155121
+** been coded while the SQL text was being parsed, before query planning.
155122
+*/
155123
+static int srcListHasCoroutine(const SrcList *pSrc, int iExcept){
155124
+ int i;
155125
+ for(i=0; i<pSrc->nSrc; i++){
155126
+ const SrcItem *pItem = &pSrc->a[i];
155127
+ if( i==iExcept ) continue;
155128
+ if( pItem->fg.viaCoroutine ) return 1;
155129
+ if( pItem->fg.isSubquery ){
155130
+ Select *pSelect;
155131
+ for(pSelect=pItem->u4.pSubq->pSelect;
155132
+ pSelect;
155133
+ pSelect=pSelect->pPrior
155134
+ ){
155135
+ if( srcListHasCoroutine(pSelect->pSrc, -1) ) return 1;
155136
+ }
155137
+ }
155138
+ }
155139
+ return 0;
155140
+}
155141
+
154218155142
/*
154219155143
** This routine attempts to flatten subqueries as a performance optimization.
154220155144
** This routine returns 1 if it makes changes and 0 if no flattening occurs.
154221155145
**
154222155146
** To understand the concept of flattening, consider the following
@@ -154541,10 +155465,11 @@
154541155465
if( compoundHasDifferentAffinities(pSub) ) return 0;
154542155466
154543155467
if( pSrc->nSrc>1 ){
154544155468
if( pParse->nSelect>500 ) return 0;
154545155469
if( OptimizationDisabled(db, SQLITE_FlttnUnionAll) ) return 0;
155470
+ if( p->pOrderBy && srcListHasCoroutine(pSrc, iFrom) ) return 0;
154546155471
aCsrMap = sqlite3DbMallocZero(db, ((i64)pParse->nTab+1)*sizeof(int));
154547155472
if( aCsrMap ) aCsrMap[0] = pParse->nTab;
154548155473
}
154549155474
}
154550155475
@@ -154829,11 +155754,11 @@
154829155754
struct WhereConst {
154830155755
Parse *pParse; /* Parsing context */
154831155756
u8 *pOomFault; /* Pointer to pParse->db->mallocFailed */
154832155757
int nConst; /* Number for COLUMN=CONSTANT terms */
154833155758
int nChng; /* Number of times a constant is propagated */
154834
- int bHasAffBlob; /* At least one column in apExpr[] as affinity BLOB */
155759
+ int bHasAffBlob; /* A column in apExpr[] has affinity NONE or BLOB */
154835155760
u32 mExcludeOn; /* Which ON expressions to exclude from considertion.
154836155761
** Either EP_OuterON or EP_InnerON|EP_OuterON */
154837155762
Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */
154838155763
};
154839155764
@@ -154997,12 +155922,13 @@
154997155922
assert( TK_GE==TK_EQ+4 );
154998155923
if( pConst->bHasAffBlob ){
154999155924
if( (pExpr->op>=TK_EQ && pExpr->op<=TK_GE)
155000155925
|| pExpr->op==TK_IS
155001155926
){
155002
- propagateConstantExprRewriteOne(pConst, pExpr->pLeft, 0);
155003
- if( pConst->pOomFault[0] ) return WRC_Prune;
155927
+ if( sqlite3ExprAffinity(pExpr->pRight)!=SQLITE_AFF_TEXT ){
155928
+ propagateConstantExprRewriteOne(pConst, pExpr->pLeft, 0);
155929
+ }
155004155930
if( sqlite3ExprAffinity(pExpr->pLeft)!=SQLITE_AFF_TEXT ){
155005155931
propagateConstantExprRewriteOne(pConst, pExpr->pRight, 0);
155006155932
}
155007155933
}
155008155934
}
@@ -155466,14 +156392,19 @@
155466156392
for(pX=pSub; pX; pX=pX->pPrior) {
155467156393
Expr *pY = pX->pEList->a[j].pExpr;
155468156394
if( pY->op==TK_NULL ) continue;
155469156395
pY->op = TK_NULL;
155470156396
ExprClearProperty(pY, EP_Skip|EP_Unlikely);
155471
- pX->selFlags |= SF_PushDown;
155472156397
nChng++;
155473156398
}
155474156399
}
156400
+ if( nChng ){
156401
+ /* If there were any changes, mark the SELECT as modified. This is
156402
+ ** to let isSelfJoinView() know not to allow another reference to this
156403
+ ** view to use the existing materialization. */
156404
+ pSub->selFlags |= SF_PushDown;
156405
+ }
155475156406
return nChng;
155476156407
}
155477156408
155478156409
155479156410
/*
@@ -156447,10 +157378,11 @@
156447157378
pX->zEName = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
156448157379
pX->fg.eEName = ENAME_NAME;
156449157380
}else{
156450157381
pX->zEName = sqlite3DbStrDup(db, zName);
156451157382
pX->fg.eEName = ENAME_NAME;
157383
+ if( IN_RENAME_OBJECT ) pX->fg.bStarName = 1;
156452157384
}
156453157385
}
156454157386
}
156455157387
if( !tableSeen ){
156456157388
if( zTName ){
@@ -156816,10 +157748,13 @@
156816157748
assert( pAggInfo->iFirstReg>0 );
156817157749
assert( pParse->db->pParse==pParse );
156818157750
assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
156819157751
if( nReg==0 ) return;
156820157752
if( pParse->nErr ) return;
157753
+ if( pAggInfo->nFunc ){
157754
+ sqlite3MayAbort(pParse);
157755
+ }
156821157756
sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->iFirstReg,
156822157757
pAggInfo->iFirstReg+nReg-1);
156823157758
for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
156824157759
if( pFunc->iDistinct>=0 ){
156825157760
Expr *pE = pFunc->pFExpr;
@@ -157826,11 +158761,19 @@
157826158761
sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric,
157827158762
p->pOrderBy);
157828158763
testcase( pParse->earlyCleanup );
157829158764
p->pOrderBy = 0;
157830158765
}
157831
- p->selFlags &= ~(u32)SF_Distinct;
158766
+ /* Do not ignore DISTINCT for an EXISTS subquery with an OFFSET clause.
158767
+ ** In this case the OFFSET must be applied after duplicates are discarded,
158768
+ ** so the DISTINCT is required. */
158769
+ if( pDest->eDest!=SRT_Exists
158770
+ || (ALWAYS(p->pLimit!=0) && p->pLimit->pRight==0)
158771
+ /* ^^^^^^-- because tag-202611101908 and SRT_Exists set nowhere else */
158772
+ ){
158773
+ p->selFlags &= ~(u32)SF_Distinct;
158774
+ }
157832158775
}
157833158776
sqlite3SelectPrep(pParse, p, 0);
157834158777
if( pParse->nErr ){
157835158778
goto select_end;
157836158779
}
@@ -157949,12 +158892,17 @@
157949158892
unsetJoinExpr(p->pWhere, pI2->iCursor, 1);
157950158893
}
157951158894
}
157952158895
}
157953158896
for(j=pTabList->nSrc-1; j>=0; j--){
157954
- pTabList->a[j].fg.jointype &= ~JT_LTORJ;
157955
- if( pTabList->a[j].fg.jointype & JT_RIGHT ) break;
158897
+ SrcItem *pI2 = &pTabList->a[j];
158898
+ pI2->fg.jointype &= ~JT_LTORJ;
158899
+ if( (pI2->fg.jointype & (JT_LEFT|JT_RIGHT))==0 ){
158900
+ clearOuterOnExpr(p->pWhere, pI2->iCursor);
158901
+ unwrapIfNullRow(pParse, p, pI2->iCursor);
158902
+ }
158903
+ if( pI2->fg.jointype & JT_RIGHT ) break;
157956158904
}
157957158905
}
157958158906
}
157959158907
157960158908
/* No further action if this term of the FROM clause is not a subquery */
@@ -158618,11 +159566,11 @@
158618159566
pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
158619159567
pAggInfo->pGroupBy = pGroupBy;
158620159568
sqlite3ExprAnalyzeAggList(&sNC, pEList);
158621159569
sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
158622159570
if( pHaving ){
158623
- if( pGroupBy ){
159571
+ if( pGroupBy && OptimizationEnabled(db, SQLITE_HavingToWhere) ){
158624159572
assert( pWhere==p->pWhere );
158625159573
assert( pHaving==p->pHaving );
158626159574
assert( pGroupBy==p->pGroupBy );
158627159575
havingToWhere(pParse, p);
158628159576
pWhere = p->pWhere;
@@ -159529,15 +160477,19 @@
159529160477
159530160478
/* If the trigger name was unqualified, and the table is a temp table,
159531160479
** then set iDb to 1 to create the trigger in the temporary database.
159532160480
** If sqlite3SrcListLookup() returns 0, indicating the table does not
159533160481
** exist, the error is caught by the block below.
159534
- */
159535
- pTab = sqlite3SrcListLookup(pParse, pTableName);
159536
- if( db->init.busy==0 && pName2->n==0 && pTab
159537
- && pTab->pSchema==db->aDb[1].pSchema ){
159538
- iDb = 1;
160482
+ **
160483
+ ** Do not do this if ALTER TABLE is reparsing an existing trigger. In
160484
+ ** that case iDb is already set correctly. */
160485
+ if( !IN_RENAME_OBJECT ){
160486
+ pTab = sqlite3SrcListLookup(pParse, pTableName);
160487
+ if( db->init.busy==0 && pName2->n==0 && pTab
160488
+ && pTab->pSchema==db->aDb[1].pSchema ){
160489
+ iDb = 1;
160490
+ }
159539160491
}
159540160492
159541160493
/* Ensure the table name matches database name and that the table exists */
159542160494
if( db->mallocFailed ) goto trigger_cleanup;
159543160495
assert( pTableName->nSrc==1 );
@@ -159564,11 +160516,12 @@
159564160516
zName = sqlite3NameFromToken(db, pName);
159565160517
if( zName==0 ){
159566160518
assert( db->mallocFailed );
159567160519
goto trigger_cleanup;
159568160520
}
159569
- if( sqlite3CheckObjectName(pParse, zName, "trigger", pTab->zName) ){
160521
+ if( sqlite3CheckObjectName(pParse, zName, "trigger", pTab->zName,
160522
+ db->aDb[iDb].zDbSName) ){
159570160523
goto trigger_cleanup;
159571160524
}
159572160525
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
159573160526
if( !IN_RENAME_OBJECT ){
159574160527
if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
@@ -159706,10 +160659,11 @@
159706160659
if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
159707160660
zName = pTrig->zName;
159708160661
iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
159709160662
assert( iDb>=00 && iDb<db->nDb );
159710160663
pTrig->step_list = pStepList;
160664
+ pTrig->nSelect = pParse->nSelect;
159711160665
for(n=0; pStepList; n++){
159712160666
pStepList->pTrig = pTrig;
159713160667
pStepList = pStepList->pNext;
159714160668
}
159715160669
if( n>pParse->db->aLimit[SQLITE_LIMIT_TRIGGER_STEPS] ){
@@ -159739,16 +160693,19 @@
159739160693
Vdbe *v;
159740160694
char *z;
159741160695
159742160696
/* If this is a new CREATE TABLE statement, and if shadow tables
159743160697
** are read-only, and the trigger makes a change to a shadow table,
159744
- ** then raise an error - do not allow the trigger to be created. */
160698
+ ** then raise an error - do not allow the trigger to be created.
160699
+ ** The targets of a TEMP trigger may be in any schema, so check all
160700
+ ** of them in that case. */
159745160701
if( sqlite3ReadOnlyShadowTables(db) ){
159746160702
TriggerStep *pStep;
160703
+ const char *zDb = iDb==1 ? 0 : db->aDb[iDb].zDbSName;
159747160704
for(pStep=pTrig->step_list; pStep; pStep=pStep->pNext){
159748160705
if( pStep->pSrc!=0
159749
- && sqlite3ShadowTableName(db, pStep->pSrc->a[0].zName)
160706
+ && sqlite3ShadowTableName(db, pStep->pSrc->a[0].zName, zDb)
159750160707
){
159751160708
sqlite3ErrorMsg(pParse,
159752160709
"trigger \"%s\" may not write to shadow table \"%s\"",
159753160710
pTrig->zName, pStep->pSrc->a[0].zName);
159754160711
goto triggerfinish_cleanup;
@@ -160656,10 +161613,11 @@
160656161613
memset(&sNC, 0, sizeof(sNC));
160657161614
sNC.pParse = &sSubParse;
160658161615
sSubParse.pTriggerTab = pTab;
160659161616
sSubParse.pToplevel = pTop;
160660161617
sSubParse.pTrigCoded = pTrigger;
161618
+ sSubParse.nSelect = pTrigger->nSelect;
160661161619
sSubParse.zAuthContext = pTrigger->zName;
160662161620
sSubParse.eTriggerOp = pTrigger->op;
160663161621
sSubParse.nQueryLoop = pParse->nQueryLoop;
160664161622
sSubParse.prepFlags = pParse->prepFlags;
160665161623
sSubParse.oldmask = 0;
@@ -164628,10 +165586,11 @@
164628165586
struct InLoop {
164629165587
int iCur; /* The VDBE cursor used by this IN operator */
164630165588
int addrInTop; /* Top of the IN loop */
164631165589
int iBase; /* Base register of multi-key index record */
164632165590
int nPrefix; /* Number of prior entries in the key */
165591
+ int lblNull; /* Jump here if RHS value is NULL */
164633165592
u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
164634165593
} *aInLoop; /* Information about each nested IN operator */
164635165594
} in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
164636165595
Index *pCoveringIdx; /* Possible covering index for WHERE_MULTI_OR */
164637165596
} u;
@@ -165937,10 +166896,11 @@
165937166896
sqlite3WhereRealloc(pTerm->pWC->pWInfo,
165938166897
pLevel->u.in.aInLoop,
165939166898
sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
165940166899
pIn = pLevel->u.in.aInLoop;
165941166900
if( pIn ){
166901
+ int lblNull = sqlite3VdbeMakeLabel(pParse);
165942166902
int iMap = 0; /* Index in aiMap[] */
165943166903
pIn += i;
165944166904
for(i=iEq; i<pLoop->nLTerm; i++){
165945166905
if( pLoop->aLTerm[i]->pExpr==pX ){
165946166906
int iOut = iTarget + i - iEq;
@@ -165948,13 +166908,14 @@
165948166908
pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
165949166909
}else{
165950166910
int iCol = aiMap ? aiMap[iMap++] : 0;
165951166911
pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
165952166912
}
165953
- sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
166913
+ sqlite3VdbeAddOp2(v, OP_IsNull, iOut, lblNull); VdbeCoverage(v);
165954166914
if( i==iEq ){
165955166915
pIn->iCur = iTab;
166916
+ pIn->lblNull = lblNull;
165956166917
pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
165957166918
if( iEq>0 ){
165958166919
pIn->iBase = iTarget - i;
165959166920
pIn->nPrefix = i;
165960166921
}else{
@@ -166924,10 +167885,11 @@
166924167885
*/
166925167886
int iReg; /* P3 Value for OP_VFilter */
166926167887
int addrNotFound;
166927167888
int nConstraint = pLoop->nLTerm;
166928167889
167890
+ sqlite3MayAbort(pParse);
166929167891
iReg = sqlite3GetTempRange(pParse, nConstraint+2);
166930167892
addrNotFound = pLevel->addrBrk;
166931167893
for(j=0; j<nConstraint; j++){
166932167894
int iTarget = iReg+j+2;
166933167895
pTerm = pLoop->aLTerm[j];
@@ -167297,10 +168259,11 @@
167297168259
** index entries for which the column is null and for those for which
167298168260
** it is not. For an ASC sort, the non-NULL entries are scanned first.
167299168261
** For DESC, NULL entries are scanned first.
167300168262
*/
167301168263
if( (pLoop->wsFlags & (WHERE_TOP_LIMIT|WHERE_BTM_LIMIT))==0
168264
+ && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
167302168265
&& (pLoop->wsFlags & WHERE_BIGNULL_SORT)!=0
167303168266
){
167304168267
assert( bSeekPastNull==0 && nExtraReg==0 && nBtm==0 && nTop==0 );
167305168268
assert( pRangeEnd==0 && pRangeStart==0 );
167306168269
testcase( pLoop->nSkip>0 );
@@ -168512,10 +169475,47 @@
168512169475
assert( op!=TK_GE || c==WO_GE );
168513169476
assert( op!=TK_IS || c==WO_IS );
168514169477
return c;
168515169478
}
168516169479
169480
+#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
169481
+/*
169482
+** The input is an N-byte GLOB or LIKE pattern prefix
169483
+** with the following guarantees:
169484
+**
169485
+** (1) It contains no wildcards.
169486
+** (2) z[N]==0
169487
+** (3) N>0
169488
+** (4) bHasSpace is true if and only if the original complete LIKE/GLOB
169489
+** pattern contained wildcards and/or escapes. (It is usually true,
169490
+** therefore). bHasSpace also means that there is at least one byte
169491
+** of overrun space at z[N+1] that this routine may use.
169492
+**
169493
+** This routine checks to see if the input will be a prefix to
169494
+** any number (integer or floating-point) that SQLite might generate
169495
+** from a MEM_Int or MEM_Real, including "Inf" and "-Inf".
169496
+**
169497
+** Return true if the input is a possible numeric prefix and
169498
+** false if the input cannot possibly be a numeric prefix.
169499
+*/
169500
+static SQLITE_NOINLINE int isNumericPrefix(char *z, int N, int bHasSpace){
169501
+ int x;
169502
+ double rDummy;
169503
+ assert( N>0 );
169504
+ if( sqlite3AtoF(z, &rDummy)>0 ) return 1; /* Boundary is itself a number */
169505
+ if( bHasSpace ){
169506
+ z[N] = '0';
169507
+ z[N+1] = 0;
169508
+ x = sqlite3AtoF(z, &rDummy); /* Prefix like "1.0e" or "-" */
169509
+ z[N] = 0;
169510
+ if( x>0 ) return 1;
169511
+ }
169512
+ if( z[0]=='-' ){ z++; N--; }
169513
+ if( N>0 && N<=3 && sqlite3StrNICmp(z,"inf",N)==0 ) return 1;
169514
+ return 0;
169515
+}
169516
+#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
168517169517
168518169518
#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
168519169519
/*
168520169520
** Check to see if the given expression is a LIKE or GLOB operator that
168521169521
** can be optimized using inequality constraints. Return TRUE if it is
@@ -168567,11 +169567,11 @@
168567169567
}
168568169568
sqlite3VdbeReprepareOnBind(pParse->pVdbe, iCol, 0);
168569169569
assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
168570169570
}else if( op==TK_STRING ){
168571169571
assert( !ExprHasProperty(pRight, EP_IntValue) );
168572
- z = (u8*)pRight->u.zToken;
169572
+ z = (u8*)pRight->u.zToken;
168573169573
}
168574169574
if( z ){
168575169575
/* Count the number of prefix bytes prior to the first wildcard,
168576169576
** U+fffd character, or malformed utf-8. If the underlying database
168577169577
** has a UTF16LE encoding, then only consider ASCII characters. Note that
@@ -168583,27 +169583,40 @@
168583169583
cnt++;
168584169584
if( c==wc[3] && z[cnt]>0 && z[cnt]<0x80 ){
168585169585
cnt++;
168586169586
}else if( c>=0x80 ){
168587169587
const u8 *z2 = z+cnt-1;
168588
- if( c==0xff || sqlite3Utf8Read(&z2)==0xfffd /* bad utf-8 */
168589
- || ENC(db)==SQLITE_UTF16LE
169588
+ u32 u;
169589
+ if( c==0xff /* (1) */
169590
+ || (u = sqlite3Utf8Read(&z2))>=0xfffd /* (2) */
169591
+ || u==0x7ff /* (3) */
169592
+ || ENC(db)==SQLITE_UTF16LE /* (4) */
168590169593
){
169594
+ /* Do not accept this character as part of the prefix because
169595
+ ** (1) 0xff is not part of any valid UTF-8 character and the
169596
+ ** 0xff causes difficult when incrementing to the upper bound
169597
+ ** (2) 0xfffd is not a valid UTF-8 character and values greater
169598
+ ** start getting into the surrogate pairs in UTF16BE.
169599
+ ** (3) When incrementing this code point to the upper bound,
169600
+ ** that would require adding an extra byte to the UTF-8
169601
+ ** (4) UTF16LE does not compare in sorted order. Only
169602
+ ** UTF16BE and UTF8 have that property.
169603
+ */
168591169604
cnt--;
168592169605
break;
168593169606
}else{
168594169607
cnt = (int)(z2-z);
168595169608
}
168596169609
}
168597169610
}
168598169611
168599
- /* The optimization is possible only if (1) the pattern does not begin
168600
- ** with a wildcard and if (2) the non-wildcard prefix does not end with
168601
- ** an (illegal 0xff) character, or (3) the pattern does not consist of
168602
- ** a single escape character. The second condition is necessary so
169612
+ /* The optimization is possible only if either (1a) the pattern does not
169613
+ ** begin with a wildcard and if (1b) the non-wildcard prefix does not end
169614
+ ** with an (illegal) 0xff character, or (2) the pattern does not consist of
169615
+ ** a single escape character. The (1b) condition is necessary so
168603169616
** that we can increment the prefix key to find an upper bound for the
168604
- ** range search. The third is because the caller assumes that the pattern
169617
+ ** range search. The (2) is because the caller assumes that the pattern
168605169618
** consists of at least one character after all escapes have been
168606169619
** removed. */
168607169620
if( (cnt>1 || (cnt>0 && z[0]!=wc[3])) && ALWAYS(255!=(u8)z[cnt-1]) ){
168608169621
Expr *pPrefix;
168609169622
@@ -168625,41 +169638,41 @@
168625169638
zNew[iTo] = 0;
168626169639
assert( iTo>0 );
168627169640
168628169641
/* If the LHS is not an ordinary column with TEXT affinity, then the
168629169642
** pattern prefix boundaries (both the start and end boundaries) must
168630
- ** not look like a number. Otherwise the pattern might be treated as
168631
- ** a number, which will invalidate the LIKE optimization.
169643
+ ** not look like a number or the prefix of a number. Otherwise the
169644
+ ** pattern might might match against a number, which means this
169645
+ ** optimization will not work. If either the start or end boundary
169646
+ ** strings has any possibility of matching against a text rendering
169647
+ ** of a MEM_Int or MEM_Real, then we must return 0.
168632169648
**
168633169649
** Getting this right has been a persistent source of bugs in the
168634169650
** LIKE optimization. See, for example:
168635169651
** 2018-09-10 https://sqlite.org/src/info/c94369cae9b561b1
168636169652
** 2019-05-02 https://sqlite.org/src/info/b043a54c3de54b28
168637169653
** 2019-06-10 https://sqlite.org/src/info/fd76310a5e843e07
168638169654
** 2019-06-14 https://sqlite.org/src/info/ce8717f0885af975
168639169655
** 2019-09-03 https://sqlite.org/src/info/0f0428096f17252a
169656
+ ** 2026-10-28 https://sqlite.org/bugs/info/e85ab73aa1483325
168640169657
*/
168641169658
if( pLeft->op!=TK_COLUMN
168642169659
|| sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
168643169660
|| (ALWAYS( ExprUseYTab(pLeft) )
168644169661
&& ALWAYS(pLeft->y.pTab)
168645169662
&& IsVirtual(pLeft->y.pTab)) /* Might be numeric */
168646169663
){
168647
- int isNum;
168648
- double rDummy;
169664
+ int bHasSpace = iTo < (int)strlen((const char*)z);
169665
+ int x;
168649169666
assert( zNew[iTo]==0 );
168650
- isNum = sqlite3AtoF(zNew, &rDummy);
168651
- if( isNum<=0 ){
168652
- if( iTo==1 && zNew[0]=='-' ){
168653
- isNum = +1;
168654
- }else{
168655
- zNew[iTo-1]++;
168656
- isNum = sqlite3AtoF(zNew, &rDummy);
168657
- zNew[iTo-1]--;
168658
- }
168659
- }
168660
- if( isNum>0 ){
169667
+ x = isNumericPrefix(zNew, iTo, bHasSpace); /* start boundary */
169668
+ if( x==0 ){
169669
+ zNew[iTo-1]++;
169670
+ x = isNumericPrefix(zNew, iTo, bHasSpace); /* end boundary */
169671
+ zNew[iTo-1]--;
169672
+ }
169673
+ if( x!=0 ){
168661169674
sqlite3ExprDelete(db, pPrefix);
168662169675
sqlite3ValueFree(pVal);
168663169676
return 0;
168664169677
}
168665169678
}
@@ -168920,11 +169933,17 @@
168920169933
Expr *pNew; /* New virtual expression */
168921169934
int op; /* Operator for the combined expression */
168922169935
int idxNew; /* Index in pWC of the next virtual term */
168923169936
Expr *pA, *pB; /* Expressions associated with pOne and pTwo */
168924169937
168925
- if( (pOne->wtFlags | pTwo->wtFlags) & TERM_VNULL ) return;
169938
+ if( (pOne->wtFlags | pTwo->wtFlags) & (TERM_VNULL|TERM_LIKEOPT) ){
169939
+ testcase( pOne->wtFlags & TERM_VNULL );
169940
+ testcase( pOne->wtFlags & TERM_LIKEOPT );
169941
+ testcase( pTwo->wtFlags & TERM_VNULL );
169942
+ testcase( pTwo->wtFlags & TERM_LIKEOPT );
169943
+ return;
169944
+ }
168926169945
if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
168927169946
if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
168928169947
if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
168929169948
&& (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
168930169949
pA = pOne->pExpr;
@@ -169881,11 +170900,11 @@
169881170900
** used by each such virtual term is pExpr (the full vector IN(...)
169882170901
** expression). The WhereTerm.u.x.iField variable identifies the index within
169883170902
** the vector on the LHS that the virtual term represents.
169884170903
**
169885170904
** This only works if the RHS is a simple SELECT (not a compound) that does
169886
- ** not use window functions.
170905
+ ** not use window functions or a LIMIT clause.
169887170906
*/
169888170907
else if( pExpr->op==TK_IN
169889170908
&& pTerm->u.x.iField==0
169890170909
&& pExpr->pLeft->op==TK_VECTOR
169891170910
&& ALWAYS( ExprUseXSelect(pExpr) )
@@ -169892,10 +170911,12 @@
169892170911
&& (pExpr->x.pSelect->pPrior==0 || (pExpr->x.pSelect->selFlags & SF_Values))
169893170912
#ifndef SQLITE_OMIT_WINDOWFUNC
169894170913
&& pExpr->x.pSelect->pWin==0
169895170914
#endif
169896170915
&& (pExpr->x.pSelect->selFlags & SF_MinMaxAgg)==0
170916
+ && pExpr->x.pSelect->pLimit==0
170917
+ /* ^-- See bug 2026-11-04T00:59:22Z */
169897170918
&& pWC->op==TK_AND
169898170919
&& pExpr->x.pSelect->pEList->nExpr <= UMXV(pTerm->nChild)
169899170920
/* ^-- See bug 2026-06-04T10:00:49Z */
169900170921
){
169901170922
int i;
@@ -170574,18 +171595,20 @@
170574171595
return 0;
170575171596
}
170576171597
}
170577171598
if( pSet->n<N_OR_COST ){
170578171599
p = &pSet->a[pSet->n++];
170579
- p->nOut = nOut;
170580171600
}else{
171601
+ /* The set is full. Replace the most expensive entry, but only if the
171602
+ ** new entry is less expensive than it. */
170581171603
p = pSet->a;
170582171604
for(i=1; i<pSet->n; i++){
170583
- if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
171605
+ if( p->rRun<pSet->a[i].rRun ) p = pSet->a + i;
170584171606
}
170585171607
if( p->rRun<=rRun ) return 0;
170586171608
}
171609
+ p->nOut = nOut;
170587171610
whereOrInsert_done:
170588171611
p->prereq = prereq;
170589171612
p->rRun = rRun;
170590171613
if( p->nOut>nOut ) p->nOut = nOut;
170591171614
return 1;
@@ -170697,10 +171720,33 @@
170697171720
CollSeq *pRet = sqlite3ExprCompareCollSeq(pParse, pX);
170698171721
return pRet ? pRet->zName : sqlite3StrBINARY;
170699171722
}
170700171723
return 0;
170701171724
}
171725
+
171726
+/*
171727
+** pTerm is a WO_EQUIV term "X=Y" that whereScanNext() might use to add
171728
+** Y to the equivalence class of X. Return true if any of the following
171729
+** are true:
171730
+**
171731
+** * Parameter zCollName is NULL,
171732
+** * The collation sequence of pTerm is BINARY, or
171733
+** * The collation sequence of pTerm is zCollName.
171734
+**
171735
+** Otherwise return false.
171736
+*/
171737
+static int whereScanEquivCollOk(
171738
+ Parse *pParse,
171739
+ WhereTerm *pTerm,
171740
+ const char *zCollName
171741
+){
171742
+ CollSeq *pColl;
171743
+ if( zCollName==0 ) return 1;
171744
+ pColl = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr);
171745
+ if( sqlite3IsBinary(pColl) ) return 1;
171746
+ return sqlite3StrICmp(pColl->zName, zCollName)==0;
171747
+}
170702171748
170703171749
/*
170704171750
** Advance to the next WhereTerm that matches according to the criteria
170705171751
** established when the pScan object was initialized by whereScanInit().
170706171752
** Return NULL if there are no more matching WhereTerms.
@@ -170731,10 +171777,11 @@
170731171777
&& (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_OuterON))
170732171778
){
170733171779
if( (pTerm->eOperator & WO_EQUIV)!=0
170734171780
&& pScan->nEquiv<ArraySize(pScan->aiCur)
170735171781
&& (pX = whereRightSubexprIsColumn(pTerm->pExpr))!=0
171782
+ && whereScanEquivCollOk(pWC->pWInfo->pParse, pTerm, pScan->zCollName)
170736171783
){
170737171784
int j;
170738171785
for(j=0; j<pScan->nEquiv; j++){
170739171786
if( pScan->aiCur[j]==pX->iTable
170740171787
&& pScan->aiColumn[j]==pX->iColumn ){
@@ -170761,11 +171808,23 @@
170761171808
CollSeq *pColl;
170762171809
if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
170763171810
continue;
170764171811
}
170765171812
assert(pX->pLeft);
170766
- pColl = sqlite3ExprCompareCollSeq(pParse, pX);
171813
+ if( pX->pLeft->op==TK_VECTOR ){
171814
+ /* A vector inequality such as (a,b)>(?,?). This term
171815
+ ** constrains only the first field, so the collation is
171816
+ ** that of the first pair of fields only. */
171817
+ Expr *pL = sqlite3VectorFieldSubexpr(pX->pLeft, 0);
171818
+ Expr *pR = sqlite3VectorFieldSubexpr(pX->pRight, 0);
171819
+ assert( pTerm->u.x.iField==0 );
171820
+ assert( pX->op>=TK_GT && pX->op<=TK_GE );
171821
+ if( ExprHasProperty(pX, EP_Commuted) ) SWAP(Expr*, pL, pR);
171822
+ pColl = sqlite3BinaryCompareCollSeq(pParse, pL, pR);
171823
+ }else{
171824
+ pColl = sqlite3ExprCompareCollSeq(pParse, pX);
171825
+ }
170767171826
zCollName = pColl ? pColl->zName : sqlite3StrBINARY;
170768171827
}
170769171828
170770171829
if( sqlite3StrICmp(zCollName, pScan->zCollName) ){
170771171830
continue;
@@ -171360,11 +172419,13 @@
171360172419
int mxBitCol; /* Maximum column in pSrc->colUsed */
171361172420
CollSeq *pColl; /* Collating sequence to on a column */
171362172421
WhereLoop *pLoop; /* The Loop object */
171363172422
char *zNotUsed; /* Extra space on the end of pIdx */
171364172423
Bitmask idxCols; /* Bitmap of columns used for indexing */
172424
+ Bitmask pkCols; /* PK cols whose key collation keeps them unique */
171365172425
Bitmask extraCols; /* Bitmap of additional columns */
172426
+ int bHighCols; /* True to add all columns >= BMS-1 */
171366172427
u8 sentWarning = 0; /* True if a warning has been issued */
171367172428
u8 useBloomFilter = 1; /* True to also add a Bloom filter */
171368172429
Expr *pPartial = 0; /* Partial Index Expression */
171369172430
int iContinue = 0; /* Jump here to skip excluded rows */
171370172431
SrcList *pTabList; /* The complete FROM clause */
@@ -171388,10 +172449,11 @@
171388172449
pSrc = &pTabList->a[pLevel->iFrom];
171389172450
pTable = pSrc->pSTab;
171390172451
pWCEnd = &pWC->a[pWC->nTerm];
171391172452
pLoop = pLevel->pWLoop;
171392172453
idxCols = 0;
172454
+ pkCols = 0;
171393172455
for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
171394172456
Expr *pExpr = pTerm->pExpr;
171395172457
/* Make the automatic index a partial index if there are terms in the
171396172458
** WHERE clause (or the ON clause of a LEFT join) that constrain which
171397172459
** rows of the target table (pSrc) that can be used. */
@@ -171419,10 +172481,29 @@
171419172481
if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
171420172482
goto end_auto_index_create;
171421172483
}
171422172484
pLoop->aLTerm[nKeyCol++] = pTerm;
171423172485
idxCols |= cMask;
172486
+
172487
+ /* For a WITHOUT ROWID table, all PRIMARY KEY columns must be
172488
+ ** present in the automatic index, sorted with either BINARY or
172489
+ ** the same collation used by the PK index itself, to guarantee each
172490
+ ** entry is unique. If the current field matches that criteria,
172491
+ ** set the corresponding bit in pkCols. */
172492
+ if( !HasRowid(pTable) && iCol<BMS-1
172493
+ && (pTable->aCol[iCol].colFlags & COLFLAG_PRIMKEY)
172494
+ ){
172495
+ Index *pPk = sqlite3PrimaryKeyIndex(pTable);
172496
+ CollSeq *pX = sqlite3ExprCompareCollSeq(pParse, pExpr);
172497
+ int iPk = sqlite3TableColumnToIndex(pPk, iCol);
172498
+ assert( iPk>=0 && iPk<pPk->nKeyCol );
172499
+ if( sqlite3IsBinary(pX)
172500
+ || sqlite3StrICmp(pPk->azColl[iPk], pX->zName)==0
172501
+ ){
172502
+ pkCols |= cMask;
172503
+ }
172504
+ }
171424172505
}
171425172506
}
171426172507
}
171427172508
assert( nKeyCol>0 || pParse->db->mallocFailed );
171428172509
pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
@@ -171440,35 +172521,38 @@
171440172521
if( IsView(pTable) ){
171441172522
extraCols = ALLBITS & ~idxCols;
171442172523
}else{
171443172524
extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
171444172525
}
172526
+ bHighCols = (pSrc->colUsed & MASKBIT(BMS-1))!=0;
171445172527
if( !HasRowid(pTable) ){
171446172528
/* For WITHOUT ROWID tables, ensure that all PRIMARY KEY columns are
171447
- ** either in the idxCols mask or in the extraCols mask */
172529
+ ** either in the pkCols mask or in the extraCols mask. A column that
172530
+ ** is already an index key but is not in pkCols is added a second
172531
+ ** time, using the BINARY collating sequence. */
171448172532
for(i=0; i<pTable->nCol; i++){
171449172533
if( (pTable->aCol[i].colFlags & COLFLAG_PRIMKEY)==0 ) continue;
171450172534
if( i>=BMS-1 ){
171451
- extraCols |= MASKBIT(BMS-1);
172535
+ bHighCols = 1;
171452172536
break;
171453172537
}
171454
- if( idxCols & MASKBIT(i) ) continue;
172538
+ if( pkCols & MASKBIT(i) ) continue;
171455172539
extraCols |= MASKBIT(i);
171456172540
}
171457172541
}
171458172542
mxBitCol = MIN(BMS-1,pTable->nCol);
171459172543
testcase( pTable->nCol==BMS-1 );
171460172544
testcase( pTable->nCol==BMS-2 );
171461172545
for(i=0; i<mxBitCol; i++){
171462172546
if( extraCols & MASKBIT(i) ) nKeyCol++;
171463172547
}
171464
- if( pSrc->colUsed & MASKBIT(BMS-1) ){
172548
+ if( bHighCols ){
171465172549
nKeyCol += pTable->nCol - BMS + 1;
171466172550
}
171467172551
171468172552
/* Construct the Index object to describe this index */
171469
- assert( nKeyCol <= pTable->nCol + MAX(0, pTable->nCol - BMS + 1) );
172553
+ assert( nKeyCol <= pTable->nCol + MIN(pTable->nCol, BMS) );
171470172554
/* ^-- This guarantees that the number of index columns will fit in the u16 */
171471172555
pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+HasRowid(pTable),
171472172556
0, &zNotUsed);
171473172557
if( pIdx==0 ) goto end_auto_index_create;
171474172558
pLoop->u.btree.pIndex = pIdx;
@@ -171488,11 +172572,11 @@
171488172572
if( (idxCols & cMask)==0 ){
171489172573
Expr *pX = pTerm->pExpr;
171490172574
idxCols |= cMask;
171491172575
pIdx->aiColumn[n] = pTerm->u.x.leftColumn;
171492172576
pColl = sqlite3ExprCompareCollSeq(pParse, pX);
171493
- assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */
172577
+ testcase( pColl==0 && pParse->nErr==0 ); /* TH3 collate01.810 */
171494172578
if( !sqlite3IsBinary(pColl) ){
171495172579
/* Disallow the use of a Bloom filter if any non-BINARY collating
171496172580
** sequence is involved. tag-202607231411 */
171497172581
useBloomFilter = 0;
171498172582
}
@@ -171510,11 +172594,11 @@
171510172594
pIdx->aiColumn[n] = i;
171511172595
pIdx->azColl[n] = sqlite3StrBINARY;
171512172596
n++;
171513172597
}
171514172598
}
171515
- if( pSrc->colUsed & MASKBIT(BMS-1) ){
172599
+ if( bHighCols ){
171516172600
for(i=BMS-1; i<pTable->nCol; i++){
171517172601
pIdx->aiColumn[n] = i;
171518172602
pIdx->azColl[n] = sqlite3StrBINARY;
171519172603
n++;
171520172604
}
@@ -174113,13 +175197,43 @@
174113175197
*/
174114175198
typedef struct CoveringIndexCheck CoveringIndexCheck;
174115175199
struct CoveringIndexCheck {
174116175200
Index *pIdx; /* The index */
174117175201
int iTabCur; /* Cursor number for the corresponding table */
175202
+ WhereClause *pWC; /* Ignore terms of this WHERE implied by pIdx, or NULL */
174118175203
u8 bExpr; /* Uses an indexed expression */
174119175204
u8 bUnidx; /* Uses an unindexed column not within an indexed expr */
174120175205
};
175206
+
175207
+/*
175208
+** Return true if pExpr is a term of the WHERE clause pCk->pWC (not merely
175209
+** a copy of such a term) and is identical to one of the AND-connected
175210
+** terms of the WHERE clause of partial index pCk->pIdx. Such a term is
175211
+** never evaluated when pCk->pIdx drives the loop, because the
175212
+** whereApplyPartialIndexConstraints() routine marks it as already coded.
175213
+** Hence any columns used by the term do not need to be in the index.
175214
+*/
175215
+static int whereTermImpliedByPartialIndex(
175216
+ CoveringIndexCheck *pCk,
175217
+ const Expr *pExpr
175218
+){
175219
+ WhereClause *pWC = pCk->pWC;
175220
+ Expr *pPart;
175221
+ int i;
175222
+ for(i=0; i<pWC->nTerm; i++){
175223
+ if( pWC->a[i].pExpr==pExpr ) break;
175224
+ }
175225
+ if( i>=pWC->nTerm ) return 0;
175226
+ pPart = pCk->pIdx->pPartIdxWhere;
175227
+ while( pPart->op==TK_AND ){
175228
+ if( sqlite3ExprCompare(0, pExpr, pPart->pRight, pCk->iTabCur)==0 ){
175229
+ return 1;
175230
+ }
175231
+ pPart = pPart->pLeft;
175232
+ }
175233
+ return sqlite3ExprCompare(0, pExpr, pPart, pCk->iTabCur)==0;
175234
+}
174121175235
174122175236
/*
174123175237
** Information passed in is pWalk->u.pCovIdxCk. Call it pCk.
174124175238
**
174125175239
** If the Expr node references the table with cursor pCk->iTabCur, then
@@ -174143,10 +175257,13 @@
174143175257
u16 nColumn; /* Number of columns in the index */
174144175258
CoveringIndexCheck *pCk; /* Info about this search */
174145175259
174146175260
pCk = pWalk->u.pCovIdxCk;
174147175261
pIdx = pCk->pIdx;
175262
+ if( pCk->pWC && whereTermImpliedByPartialIndex(pCk, pExpr) ){
175263
+ return WRC_Prune;
175264
+ }
174148175265
if( (pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN) ){
174149175266
/* if( pExpr->iColumn<(BMS-1) && pIdx->bHasExpr==0 ) return WRC_Continue;*/
174150175267
if( pExpr->iTable!=pCk->iTabCur ) return WRC_Continue;
174151175268
pIdx = pWalk->u.pCovIdxCk->pIdx;
174152175269
aiColumn = pIdx->aiColumn;
@@ -174169,10 +175286,16 @@
174169175286
** pIdx is an index that covers all of the low-number columns used by
174170175287
** pWInfo->pSelect (columns from 0 through 62) or an index that has
174171175288
** expressions terms. Hence, we cannot determine whether or not it is
174172175289
** a covering index by using the colUsed bitmasks. We have to do a search
174173175290
** to see if the index is covering. This routine does that search.
175291
+**
175292
+** If pWC is not NULL, then pIdx is a partial index and terms of the
175293
+** WHERE clause pWC that are implied by the WHERE clause of pIdx are
175294
+** ignored, as they will never be evaluated when pIdx drives the loop.
175295
+** In this case pIdx might not cover all low-numbered columns used by
175296
+** pWInfo->pSelect.
174174175297
**
174175175298
** The return value is one of these:
174176175299
**
174177175300
** 0 The index is definitely not a covering index
174178175301
**
@@ -174189,21 +175312,22 @@
174189175312
** returned can lead to incorrect bytecode and assertion faults.
174190175313
*/
174191175314
static SQLITE_NOINLINE u32 whereIsCoveringIndex(
174192175315
WhereInfo *pWInfo, /* The WHERE clause context */
174193175316
Index *pIdx, /* Index that is being tested */
174194
- int iTabCur /* Cursor for the table being indexed */
175317
+ int iTabCur, /* Cursor for the table being indexed */
175318
+ WhereClause *pWC /* Ignore terms implied by pIdx, or NULL */
174195175319
){
174196175320
int i, rc;
174197175321
struct CoveringIndexCheck ck;
174198175322
Walker w;
174199175323
if( pWInfo->pSelect==0 ){
174200175324
/* We don't have access to the full query, so we cannot check to see
174201175325
** if pIdx is covering. Assume it is not. */
174202175326
return 0;
174203175327
}
174204
- if( pIdx->bHasExpr==0 ){
175328
+ if( pIdx->bHasExpr==0 && pWC==0 ){
174205175329
for(i=0; i<pIdx->nColumn; i++){
174206175330
if( pIdx->aiColumn[i]>=BMS-1 ) break;
174207175331
}
174208175332
if( i>=pIdx->nColumn ){
174209175333
/* pIdx does not index any columns greater than 62, but we know from
@@ -174212,10 +175336,11 @@
174212175336
return 0;
174213175337
}
174214175338
}
174215175339
ck.pIdx = pIdx;
174216175340
ck.iTabCur = iTabCur;
175341
+ ck.pWC = pWC;
174217175342
ck.bExpr = 0;
174218175343
ck.bUnidx = 0;
174219175344
memset(&w, 0, sizeof(w));
174220175345
w.xExprCallback = whereIsCoveringIndexWalkCallback;
174221175346
w.xSelectCallback = sqlite3SelectWalkNoop;
@@ -174563,10 +175688,11 @@
174563175688
rc = whereLoopInsert(pBuilder, pNew);
174564175689
pNew->nOut = rSize;
174565175690
if( rc ) break;
174566175691
}else{
174567175692
Bitmask m;
175693
+ WhereClause *pPartWC = 0; /* WHERE terms that pProbe might imply */
174568175694
if( pProbe->isCovering ){
174569175695
m = 0;
174570175696
pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
174571175697
}else{
174572175698
m = pSrc->colUsed & pProbe->colNotIdxed;
@@ -174574,14 +175700,34 @@
174574175700
&& (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
174575175701
){
174576175702
wherePartIdxExpr(
174577175703
pWInfo->pParse, pProbe, pProbe->pPartIdxWhere, &m, 0, 0
174578175704
);
175705
+ /* WHERE clause terms implied by the partial index WHERE clause
175706
+ ** are not evaluated, so the columns they use need not be in the
175707
+ ** index. But this does not apply to outer joins. See the
175708
+ ** call to whereApplyPartialIndexConstraints() in wherecode.c. */
175709
+ if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==0
175710
+ && pWC==&pWInfo->sWC
175711
+ ){
175712
+ pPartWC = pWC;
175713
+ }
174579175714
}
174580175715
pNew->wsFlags = WHERE_INDEXED;
174581
- if( m==TOPBIT || (pProbe->bHasExpr && !pProbe->bHasVCol && m!=0) ){
174582
- u32 isCov = whereIsCoveringIndex(pWInfo, pProbe, pSrc->iCursor);
175716
+ if( m==0 ){
175717
+ if( HasRowid(pTab) || pWInfo->pSelect!=0 || sqlite3FaultSim(700) ){
175718
+ WHERETRACE(0x200,
175719
+ ("-> %s is a covering index according to bitmasks\n",
175720
+ pProbe->zName, m==0 ? "is" : "is not"));
175721
+ pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
175722
+ }
175723
+ }else if( m==TOPBIT
175724
+ || (pProbe->bHasExpr && !pProbe->bHasVCol)
175725
+ || pPartWC
175726
+ ){
175727
+ u32 isCov = whereIsCoveringIndex(pWInfo, pProbe, pSrc->iCursor,
175728
+ pPartWC);
174583175729
if( isCov==0 ){
174584175730
WHERETRACE(0x200,
174585175731
("-> %s is not a covering index"
174586175732
" according to whereIsCoveringIndex()\n", pProbe->zName));
174587175733
assert( m!=0 );
@@ -174597,17 +175743,10 @@
174597175743
WHERETRACE(0x200,
174598175744
("-> %s might be a covering expression index"
174599175745
" according to whereIsCoveringIndex()\n", pProbe->zName));
174600175746
}
174601175747
}
174602
- }else if( m==0
174603
- && (HasRowid(pTab) || pWInfo->pSelect!=0 || sqlite3FaultSim(700))
174604
- ){
174605
- WHERETRACE(0x200,
174606
- ("-> %s is a covering index according to bitmasks\n",
174607
- pProbe->zName, m==0 ? "is" : "is not"));
174608
- pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
174609175748
}
174610175749
}
174611175750
174612175751
/* Full scan via index */
174613175752
if( b
@@ -175445,21 +176584,19 @@
175445176584
** long as the subquery ORDER BY does the same. But if the
175446176585
** outer ORDER BY uses COLLATE, even a redundant COLLATE, the
175447176586
** optimization is bypassed.
175448176587
**
175449176588
** (2) The subquery ORDER BY terms must exactly match subquery result
175450
-** columns, including any COLLATE annotations. This routine relies
175451
-** on iOrderByCol to do matching between order by terms and result
175452
-** columns, and iOrderByCol will not be set if the result column
175453
-** and ORDER BY collations differ.
176589
+** columns, and the collations used must match as well.
175454176590
**
175455176591
** (3) The subquery and outer ORDER BY can be in opposite directions as
175456176592
** long as the subquery is materialized. If the subquery is
175457176593
** implemented as a co-routine, the sort orders must be in the same
175458176594
** direction because there is no way to run a co-routine backwards.
175459176595
*/
175460176596
static SQLITE_NOINLINE int wherePathMatchSubqueryOB(
176597
+ Parse *pParse, /* The parsing context */
175461176598
WhereLoop *pLoop, /* The nested loop term that is a subquery */
175462176599
int iLoop, /* Which level of the nested loop. 0==outermost */
175463176600
int iCur, /* Cursor used by the this loop */
175464176601
ExprList *pOrderBy, /* The ORDER BY clause on the whole query */
175465176602
Bitmask *pRevMask, /* When loops need to go in reverse order */
@@ -175475,18 +176612,20 @@
175475176612
175476176613
pSubOB = pLoop->u.btree.pOrderBy;
175477176614
assert( pSubOB!=0 );
175478176615
for(iOB=0; (MASKBIT(iOB) & *pOBSat)!=0; iOB++){}
175479176616
for(jSub=0; jSub<pSubOB->nExpr && iOB<pOrderBy->nExpr; jSub++, iOB++){
175480
- if( pSubOB->a[jSub].u.x.iOrderByCol==0 ) break;
176617
+ struct ExprList_item *pItem = &pSubOB->a[jSub];
176618
+ if( pItem->u.x.iOrderByCol==0 ) break;
175481176619
pOBExpr = pOrderBy->a[iOB].pExpr;
175482176620
if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) break;
175483176621
if( pOBExpr->iTable!=iCur ) break;
175484
- if( pOBExpr->iColumn!=pSubOB->a[jSub].u.x.iOrderByCol-1 ) break;
176622
+ if( pOBExpr->iColumn!=pItem->u.x.iOrderByCol-1 ) break;
176623
+ if( 0==sqlite3ExprCollSeqMatch(pParse, pOBExpr, pItem->pExpr) ) break;
175485176624
if( (wctrlFlags & WHERE_GROUPBY)==0 ){
175486176625
u8 sfOB = pOrderBy->a[iOB].fg.sortFlags; /* sortFlags for iOB */
175487
- u8 sfSub = pSubOB->a[jSub].fg.sortFlags; /* sortFlags for jSub */
176626
+ u8 sfSub = pItem->fg.sortFlags; /* sortFlags for jSub */
175488176627
if( (sfSub & KEYINFO_ORDER_BIGNULL) != (sfOB & KEYINFO_ORDER_BIGNULL) ){
175489176628
break;
175490176629
}
175491176630
revIdx = sfSub & KEYINFO_ORDER_DESC;
175492176631
if( jSub>0 ){
@@ -175662,11 +176801,11 @@
175662176801
175663176802
if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
175664176803
if( pLoop->wsFlags & WHERE_IPK ){
175665176804
if( pLoop->u.btree.pOrderBy
175666176805
&& OptimizationEnabled(db, SQLITE_OrderBySubq)
175667
- && wherePathMatchSubqueryOB(pLoop,iLoop,iCur,
176806
+ && wherePathMatchSubqueryOB(pWInfo->pParse, pLoop,iLoop,iCur,
175668176807
pOrderBy,pRevMask, &obSat, wctrlFlags)
175669176808
){
175670176809
nColumn = 0;
175671176810
isOrderDistinct = 0;
175672176811
}else{
@@ -176158,11 +177297,11 @@
176158177297
for(pWLoop=pStart; pWLoop; pWLoop=pWLoop->pNextLoop){
176159177298
if( pWLoop->iTab<iFromIdx ) continue;
176160177299
if( pWLoop->iTab>iFromIdx ) break;
176161177300
if( pWLoop->rRun>mxRun ) mxRun = pWLoop->rRun;
176162177301
}
176163
- if( ALWAYS(mxRun<LOGEST_MAX) ) mxRun++;
177302
+ if( mxRun<LOGEST_MAX ) mxRun++;
176164177303
176165177304
/* Increase the cost of table scans for dimension tables to be
176166177305
** slightly more than the maximum cost of the fact table */
176167177306
for(pWLoop=pStart; pWLoop; pWLoop=pWLoop->pNextLoop){
176168177307
if( (pWLoop->maskSelf & mSeen)==0 ) continue;
@@ -178053,46 +179192,46 @@
178053179192
#endif
178054179193
if( (pLoop->wsFlags & WHERE_IN_ABLE)!=0 && pLevel->u.in.nIn>0 ){
178055179194
struct InLoop *pIn;
178056179195
int j;
178057179196
for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
178058
- assert( sqlite3VdbeGetOp(v, pIn->addrInTop+1)->opcode==OP_IsNull
178059
- || pParse->db->mallocFailed );
178060
- sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
178061
- if( pIn->eEndLoopOp!=OP_Noop ){
178062
- if( pIn->nPrefix ){
178063
- int bEarlyOut =
178064
- (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
178065
- && (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0;
178066
- if( pLevel->iLeftJoin ){
178067
- /* For LEFT JOIN queries, cursor pIn->iCur might have been
178068
- ** disabled by OP_NullRow. This occurs for WHERE clauses such
178069
- ** as "a = ? AND b IN (...)", where the index is on (a, b).
178070
- ** When the OP_IfNullRow jump is taken, the pIn->iBase register
178071
- ** is NULLed out as a side effect. But as that register is not
178072
- ** used when the jump is taken, the side-effect is harmless. */
178073
- sqlite3VdbeAddOp3(v, OP_IfNullRow, pIn->iCur,
178074
- sqlite3VdbeCurrentAddr(v) + 2 + bEarlyOut, pIn->iBase);
178075
- VdbeCoverage(v);
178076
- }
178077
- if( bEarlyOut ){
178078
- sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
178079
- sqlite3VdbeCurrentAddr(v)+2,
178080
- pIn->iBase, pIn->nPrefix);
178081
- VdbeCoverage(v);
178082
- /* Retarget the OP_IsNull against the left operand of IN so
178083
- ** it jumps past the OP_IfNoHope. This is because the
178084
- ** OP_IsNull also bypasses the OP_Affinity opcode that is
178085
- ** required by OP_IfNoHope. */
178086
- sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
178087
- }
178088
- }
178089
- sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
178090
- VdbeCoverage(v);
178091
- VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
178092
- VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
178093
- }
179197
+ /* The second and subsequent components of a row-value IN operator
179198
+ ** have eEndLoopOp==OP_Noop. Nothing to do for them. */
179199
+ if( pIn->eEndLoopOp==OP_Noop ) continue;
179200
+
179201
+ if( pIn->nPrefix ){
179202
+ int bEarlyOut = (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
179203
+ && (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0;
179204
+ if( pLevel->iLeftJoin ){
179205
+ /* For LEFT JOIN queries, cursor pIn->iCur might have been
179206
+ ** disabled by OP_NullRow. This occurs for WHERE clauses such
179207
+ ** as "a = ? AND b IN (...)", where the index is on (a, b).
179208
+ ** When the OP_IfNullRow jump is taken, the pIn->iBase register
179209
+ ** is NULLed out as a side effect. But as that register is not
179210
+ ** used when the jump is taken, the side-effect is harmless. */
179211
+ sqlite3VdbeAddOp3(v, OP_IfNullRow, pIn->iCur,
179212
+ sqlite3VdbeCurrentAddr(v) + 2 + bEarlyOut, pIn->iBase);
179213
+ VdbeCoverage(v);
179214
+ }
179215
+ if( bEarlyOut ){
179216
+ sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
179217
+ sqlite3VdbeCurrentAddr(v)+2,
179218
+ pIn->iBase, pIn->nPrefix);
179219
+ VdbeCoverage(v);
179220
+ }
179221
+ }
179222
+
179223
+ /* The OP_IsNull opcodes that test the components of the RHS of the
179224
+ ** IN operator jump directly here to the end-of-loop opcode. They
179225
+ ** must jump past the OP_IfNoHope above, because they may also jump
179226
+ ** past the OP_Affinity codes that prepare the key used by IfNoHope. */
179227
+ sqlite3VdbeResolveLabel(v, pIn->lblNull);
179228
+
179229
+ sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
179230
+ VdbeCoverage(v);
179231
+ VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
179232
+ VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
178094179233
sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
178095179234
}
178096179235
}
178097179236
sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
178098179237
if( pLevel->pRJ ){
@@ -178140,10 +179279,20 @@
178140179279
if( pIn->eEndLoopOp!=OP_Noop ){
178141179280
sqlite3VdbeAddOp1(v, OP_NullRow, pIn->iCur);
178142179281
}
178143179282
}
178144179283
}
179284
+#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
179285
+ if( pLevel->addrLikeRep ){
179286
+ /* The LIKE loop counter is initialized after the == and IN terms
179287
+ ** are coded, so a NULL == term or an empty IN list can reach this
179288
+ ** point without ever setting it. Set it to 0 so that the
179289
+ ** OP_DecrJumpZero at the bottom of the loop falls through after
179290
+ ** the NULL row instead of reading an undefined register. */
179291
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, (int)(pLevel->iLikeRepCntr>>1));
179292
+ }
179293
+#endif
178145179294
if( pLevel->op==OP_Return ){
178146179295
sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
178147179296
}else{
178148179297
sqlite3VdbeGoto(v, pLevel->addrFirst);
178149179298
}
@@ -179744,10 +180893,11 @@
179744180893
assert( pSelect->pSrc->a[0].fg.isSubquery );
179745180894
nEphExpr = pSelect->pSrc->a[0].u4.pSubq->pSelect->pEList->nExpr;
179746180895
pMWin = pSelect->pWin;
179747180896
v = sqlite3GetVdbe(pParse);
179748180897
180898
+ sqlite3MayAbort(pParse);
179749180899
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr);
179750180900
sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
179751180901
sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
179752180902
sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
179753180903
@@ -180438,17 +181588,21 @@
180438181588
**
180439181589
** If the sort-order for the ORDER BY term in the window is DESC, then the
180440181590
** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is
180441181591
** subtracted. And the comparison operator is inverted to - ">=" becomes "<=",
180442181592
** ">" becomes "<", and so on. So, with DESC sort order, if the argument op
180443
-** is OP_Ge, the generated code is equivalent to:
181593
+** is OP_Ge, the test is logically:
180444181594
**
180445181595
** if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;
180446181596
**
180447
-** A special type of arithmetic is used such that if csr1.peerVal is not
180448
-** a numeric type (real or integer), then the result of the addition
180449
-** or subtraction is a a copy of csr1.peerVal.
181597
+** But in the DESC case, to avoid integer overflow in some cases, in practice:
181598
+**
181599
+** if( csr1.peerVal <= csr2.peerVal + regVal ) goto lbl;
181600
+**
181601
+** A special type of arithmetic is used such that if the peer-value that
181602
+** regVal is added to is not a numeric type (real or integer), then the
181603
+** result of the addition is a copy of that peer-value.
180450181604
*/
180451181605
static void windowCodeRangeTest(
180452181606
WindowCodeArg *p,
180453181607
int op, /* OP_Ge, OP_Gt, or OP_Le */
180454181608
int csr1, /* Cursor number for cursor 1 */
@@ -180460,11 +181614,12 @@
180460181614
Vdbe *v = sqlite3GetVdbe(pParse);
180461181615
ExprList *pOrderBy = p->pMWin->pOrderBy; /* ORDER BY clause for window */
180462181616
int reg1 = sqlite3GetTempReg(pParse); /* Reg. for csr1.peerVal+regVal */
180463181617
int reg2 = sqlite3GetTempReg(pParse); /* Reg. for csr2.peerVal */
180464181618
int regString = ++pParse->nMem; /* Reg. for constant value '' */
180465
- int arith = OP_Add; /* OP_Add or OP_Subtract */
181619
+ int regArith = reg1; /* Register to add regVal to */
181620
+ int bDesc = 0; /* True for DESC ORDER BY */
180466181621
int addrGe; /* Jump destination */
180467181622
int addrDone = sqlite3VdbeMakeLabel(pParse); /* Address past OP_Ge */
180468181623
CollSeq *pColl;
180469181624
180470181625
/* Read the peer-value from each cursor into a register */
@@ -180477,16 +181632,18 @@
180477181632
switch( op ){
180478181633
case OP_Ge: op = OP_Le; break;
180479181634
case OP_Gt: op = OP_Lt; break;
180480181635
default: assert( op==OP_Le ); op = OP_Ge; break;
180481181636
}
180482
- arith = OP_Subtract;
181637
+ bDesc = 1;
181638
+ regArith = reg2;
180483181639
}
180484181640
180485
- VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl",
180486
- reg1, (arith==OP_Add ? "+" : "-"), regVal,
180487
- ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2
181641
+ VdbeModuleComment((v, "CodeRangeTest: if( R%d%s%s %s R%d%s%s ) goto lbl",
181642
+ reg1, (bDesc ? "" : " + R"), (bDesc ? "" : "regVal"),
181643
+ ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2,
181644
+ (bDesc ? " + R" : ""), (bDesc ? "regVal" : "")
180488181645
));
180489181646
180490181647
/* If the BIGNULL flag is set for the ORDER BY, then it is required to
180491181648
** consider NULL values to be larger than all other values, instead of
180492181649
** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this
@@ -180530,30 +181687,31 @@
180530181687
sqlite3VdbeAddOp2(v, OP_IsNull, reg2,
180531181688
(op==OP_Gt || op==OP_Ge) ? addrDone : lbl);
180532181689
VdbeCoverage(v);
180533181690
}
180534181691
180535
- /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).
180536
- ** This block adds (or subtracts for DESC) the numeric value in regVal
180537
- ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob),
180538
- ** then leave reg1 as it is. In pseudo-code, this is implemented as:
181692
+ /* Register regArith currently contains a peer-value - csr1.peerVal for
181693
+ ** ASC, or csr2.peerVal for DESC. This block adds the numeric value in
181694
+ ** regVal to it. Or, if regArith is not numeric (it is a NULL, a text value
181695
+ ** or a blob), then leave it as it is. In pseudo-code, this is implemented
181696
+ ** as:
180539181697
**
180540
- ** if( reg1>='' ) goto addrGe;
180541
- ** reg1 = reg1 +/- regVal
181698
+ ** if( regArith>='' ) goto addrGe;
181699
+ ** regArith = regArith + regVal
180542181700
** addrGe:
180543181701
**
180544181702
** Since all strings and blobs are greater-than-or-equal-to an empty string,
180545
- ** the add/subtract is skipped for these, as required. If reg1 is a NULL,
180546
- ** then the arithmetic is performed, but since adding or subtracting from
180547
- ** NULL is always NULL anyway, this case is handled as required too. */
181703
+ ** the addition is skipped for these, as required. If regArith is a NULL,
181704
+ ** then the arithmetic is performed, but since adding to NULL is always
181705
+ ** NULL anyway, this case is handled as required too. */
180548181706
sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
180549
- addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
181707
+ addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, regArith);
180550181708
VdbeCoverage(v);
180551
- if( (op==OP_Ge && arith==OP_Add) || (op==OP_Le && arith==OP_Subtract) ){
181709
+ if( (op==OP_Ge && !bDesc) || (op==OP_Le && bDesc) ){
180552181710
sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
180553181711
}
180554
- sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
181712
+ sqlite3VdbeAddOp3(v, OP_Add, regVal, regArith, regArith);
180555181713
sqlite3VdbeJumpHere(v, addrGe);
180556181714
180557181715
/* Compare registers reg2 and reg1, taking the jump if required. Note that
180558181716
** control skips over this test if the BIGNULL flag is set and either
180559181717
** reg1 or reg2 contain a NULL value. */
@@ -185801,13 +186959,12 @@
185801186959
{
185802186960
yylhsminor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0);
185803186961
if( yylhsminor.yy203 ){
185804186962
if( IN_RENAME_OBJECT ){
185805186963
sqlite3RenameTokenMap(pParse, yylhsminor.yy203->a[0].zName, &yymsp[-2].minor.yy0);
185806
- }else{
185807
- yylhsminor.yy203->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
185808186964
}
186965
+ yylhsminor.yy203->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
185809186966
}
185810186967
}
185811186968
yymsp[-2].minor.yy203 = yylhsminor.yy203;
185812186969
break;
185813186970
case 123: /* xfullname ::= nm DOT nm AS nm */
@@ -185814,13 +186971,12 @@
185814186971
{
185815186972
yylhsminor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0);
185816186973
if( yylhsminor.yy203 ){
185817186974
if( IN_RENAME_OBJECT ){
185818186975
sqlite3RenameTokenMap(pParse, yylhsminor.yy203->a[0].zName, &yymsp[-2].minor.yy0);
185819
- }else{
185820
- yylhsminor.yy203->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
185821186976
}
186977
+ yylhsminor.yy203->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
185822186978
}
185823186979
}
185824186980
yymsp[-4].minor.yy203 = yylhsminor.yy203;
185825186981
break;
185826186982
case 124: /* joinop ::= COMMA|JOIN */
@@ -186267,23 +187423,23 @@
186267187423
** Except, do not apply this optimization if expr1 contains a function
186268187424
** because that function might be an aggregate (we don't know yet whether
186269187425
** it is or not) and if it is an aggregate, that could change the meaning
186270187426
** of the whole query.
186271187427
*/
186272
- Expr *pB = sqlite3Expr(pParse->db, TK_STRING, yymsp[-3].minor.yy144 ? "true" : "false");
186273
- if( pB ) sqlite3ExprIdToTrueFalse(pB);
187428
+ Expr *pB = sqlite3ExprInt32(pParse->db, yymsp[-3].minor.yy144!=0);
186274187429
if( !ExprHasProperty(yymsp[-4].minor.yy454, EP_HasFunc) ){
187430
+ if( pB ) pB->op2 = 1;
186275187431
sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy454);
186276187432
yymsp[-4].minor.yy454 = pB;
186277187433
}else{
186278187434
yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, yymsp[-3].minor.yy144 ? TK_OR : TK_AND, pB, yymsp[-4].minor.yy454);
186279187435
}
186280187436
}else{
186281187437
Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
186282187438
if( yymsp[-1].minor.yy14->nExpr==1
186283187439
&& sqlite3ExprIsConstant(pParse,pRHS)
186284
- && pRHS->op!=TK_COLLATE
187440
+ && ExprHasProperty(pRHS, EP_Collate)==0
186285187441
&& yymsp[-4].minor.yy454->op!=TK_VECTOR
186286187442
){
186287187443
yymsp[-1].minor.yy14->a[0].pExpr = 0;
186288187444
sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
186289187445
pRHS = sqlite3PExpr(pParse, TK_UPLUS, pRHS, 0);
@@ -186328,10 +187484,13 @@
186328187484
break;
186329187485
case 226: /* expr ::= expr in_op nm dbnm paren_exprlist */
186330187486
{
186331187487
SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
186332187488
Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
187489
+ if( pSelect && IN_RENAME_OBJECT ){
187490
+ sqlite3RenameTokenMap(pParse, pSrc->a[0].zName, yymsp[-1].minor.yy0.z ? &yymsp[-1].minor.yy0 : &yymsp[-2].minor.yy0);
187491
+ }
186333187492
if( yymsp[0].minor.yy14 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy14);
186334187493
yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy454, 0);
186335187494
sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy454, pSelect);
186336187495
if( yymsp[-3].minor.yy144 ) yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy454, 0);
186337187496
}
@@ -190096,10 +191255,13 @@
190096191255
{ SQLITE_DBCONFIG_STMT_SCANSTATUS, SQLITE_StmtScanStatus },
190097191256
{ SQLITE_DBCONFIG_REVERSE_SCANORDER, SQLITE_ReverseOrder },
190098191257
{ SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE, SQLITE_AttachCreate },
190099191258
{ SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE, SQLITE_AttachWrite },
190100191259
{ SQLITE_DBCONFIG_ENABLE_COMMENTS, SQLITE_Comments },
191260
+#ifdef SQLITE_DEBUG
191261
+ { SQLITE_DBCONFIG_VDBE_TRACE, SQLITE_VdbeTrace },
191262
+#endif
190101191263
};
190102191264
unsigned int i;
190103191265
rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
190104191266
for(i=0; i<ArraySize(aFlagOp); i++){
190105191267
if( aFlagOp[i].op==op ){
@@ -190366,10 +191528,13 @@
190366191528
return SQLITE_OK;
190367191529
}
190368191530
if( !sqlite3SafetyCheckSickOrOk(db) ){
190369191531
return SQLITE_MISUSE_BKPT;
190370191532
}
191533
+#if defined(SQLITE_DISPOSAL_NOTIFIER)
191534
+ SQLITE_DISPOSAL_NOTIFIER(1,db);
191535
+#endif
190371191536
sqlite3_mutex_enter(db->mutex);
190372191537
if( db->mTrace & SQLITE_TRACE_CLOSE ){
190373191538
db->trace.xV2(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
190374191539
}
190375191540
@@ -193607,11 +194772,11 @@
193607194772
case SQLITE_TESTCTRL_BYTEORDER: {
193608194773
rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
193609194774
break;
193610194775
}
193611194776
193612
- /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
194777
+ /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, u64 N)
193613194778
**
193614194779
** Enable or disable various optimizations for testing purposes. The
193615194780
** argument N is a bitmask of optimizations to be disabled. For normal
193616194781
** operation N should be 0. The idea is that a test program (like the
193617194782
** SQL Logic Test or SLT test module) can run the same SQL multiple times
@@ -193618,22 +194783,22 @@
193618194783
** with various optimizations disabled to verify that the same answer
193619194784
** is obtained in every case.
193620194785
*/
193621194786
case SQLITE_TESTCTRL_OPTIMIZATIONS: {
193622194787
sqlite3 *db = va_arg(ap, sqlite3*);
193623
- db->dbOptFlags = va_arg(ap, u32);
194788
+ db->dbOptFlags = va_arg(ap, u64);
193624194789
break;
193625194790
}
193626194791
193627
- /* sqlite3_test_control(SQLITE_TESTCTRL_GETOPT, sqlite3 *db, int *N)
194792
+ /* sqlite3_test_control(SQLITE_TESTCTRL_GETOPT, sqlite3 *db, u64 *N)
193628194793
**
193629194794
** Write the current optimization settings into *N. A zero bit means that
193630194795
** the optimization is on, and a 1 bit means that the optimization is off.
193631194796
*/
193632194797
case SQLITE_TESTCTRL_GETOPT: {
193633194798
sqlite3 *db = va_arg(ap, sqlite3*);
193634
- int *pN = va_arg(ap, int*);
194799
+ u64 *pN = va_arg(ap, u64*);
193635194800
*pN = db->dbOptFlags;
193636194801
break;
193637194802
}
193638194803
193639194804
/* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, onoff, xAlt);
@@ -193877,10 +195042,32 @@
193877195042
const char *z = va_arg(ap,const char*);
193878195043
double *pR = va_arg(ap,double*);
193879195044
rc = sqlite3AtoF(z,pR);
193880195045
break;
193881195046
}
195047
+
195048
+ /* sqlite3_test_control(SQLITE_TESTCTRL_ATOF, sqlite3 *db, int iDb)
195049
+ **
195050
+ ** Test access to the sqlite3ExpireStmtsUsingSchema() routine. All
195051
+ ** prepared statements associated with database connection db and that
195052
+ ** use schema iDb (0==main, 1==temp, etc.) are marked as expired.
195053
+ ** Or if iDb is exactly -1, then expire all prepared statements.
195054
+ **
195055
+ ** If iDb is out of range, this test-control is a harmless no-op.
195056
+ */
195057
+ case SQLITE_TESTCTRL_EXPIRE_STMTS: {
195058
+ sqlite3 *db = va_arg(ap,sqlite3*);
195059
+ int iDb = va_arg(ap,int);
195060
+ assert( db!=0 );
195061
+ if( iDb>=0 && iDb<db->nDb ){
195062
+ sqlite3ExpireStmtsUsingSchema(db, iDb, 0);
195063
+ }else if( iDb==(-1) ){
195064
+ sqlite3ExpirePreparedStatements(db, 0);
195065
+ }
195066
+ rc = SQLITE_OK;
195067
+ break;
195068
+ }
193882195069
193883195070
#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
193884195071
/* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
193885195072
**
193886195073
** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
@@ -195581,12 +196768,12 @@
195581196768
int nIndex; /* Size of aIndex[] */
195582196769
struct Fts3Index {
195583196770
int nPrefix; /* Prefix length (0 for main terms index) */
195584196771
Fts3Hash hPending; /* Pending terms table for this index */
195585196772
} *aIndex;
195586
- int nMaxPendingData; /* Max pending data before flush to disk */
195587
- int nPendingData; /* Current bytes of pending data */
196773
+ sqlite_int64 nMaxPendingData; /* Max pending data before flush to disk */
196774
+ sqlite_int64 nPendingData; /* Current bytes of pending data */
195588196775
sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
195589196776
int iPrevLangid; /* Langid of recently inserted document */
195590196777
int bPrevDelete; /* True if last operation was a delete */
195591196778
195592196779
#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
@@ -195901,10 +197088,13 @@
195901197088
SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
195902197089
SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
195903197090
SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
195904197091
SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
195905197092
SQLITE_PRIVATE int sqlite3Fts3ReadInt(const char *z, int *pnOut);
197093
+SQLITE_PRIVATE int sqlite3Fts3CreateHashFunction(sqlite3*, const char*, int, int, Fts3Hash*,
197094
+ void (*)(sqlite3_context*,int,sqlite3_value**)
197095
+);
195906197096
195907197097
/* fts3_tokenizer.c */
195908197098
SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
195909197099
SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
195910197100
SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
@@ -196573,10 +197763,11 @@
196573197763
if( p->zContentTbl==0 ){
196574197764
if( !zFunc ){
196575197765
zFunction = "";
196576197766
}else{
196577197767
zFree = zFunction = fts3QuoteId(zFunc);
197768
+ if( zFunction==0 ) *pRc = SQLITE_NOMEM;
196578197769
}
196579197770
fts3Appendf(pRc, &zRet, "docid");
196580197771
for(i=0; i<p->nColumn; i++){
196581197772
fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
196582197773
}
@@ -196629,10 +197820,11 @@
196629197820
196630197821
if( !zFunc ){
196631197822
zFunction = "";
196632197823
}else{
196633197824
zFree = zFunction = fts3QuoteId(zFunc);
197825
+ if( zFunction==0 ) *pRc = SQLITE_NOMEM;
196634197826
}
196635197827
fts3Appendf(pRc, &zRet, "?");
196636197828
for(i=0; i<p->nColumn; i++){
196637197829
fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
196638197830
}
@@ -199774,10 +200966,35 @@
199774200966
if( pHash->nRef<=0 ){
199775200967
sqlite3Fts3HashClear(&pHash->hash);
199776200968
sqlite3_free(pHash);
199777200969
}
199778200970
}
200971
+
200972
+/*
200973
+** Register an SQL function that uses the tokenizer hash table pHash as its
200974
+** user-data pointer. The new function holds a reference to the hash table,
200975
+** which is released by hashDestroy() when the function is deleted or if
200976
+** this call fails.
200977
+**
200978
+** The Fts3Hash object passed as the fifth argument must be the "hash" member
200979
+** of an Fts3HashWrapper object. Since it is the first member of that
200980
+** structure, the pointer may be cast to (Fts3HashWrapper*).
200981
+*/
200982
+SQLITE_PRIVATE int sqlite3Fts3CreateHashFunction(
200983
+ sqlite3 *db, /* Database connection */
200984
+ const char *zName, /* Name of SQL function */
200985
+ int nArg, /* Number of arguments */
200986
+ int eTextRep, /* Text encoding and function flags */
200987
+ Fts3Hash *pHash, /* Tokenizer hash table */
200988
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**) /* Implementation */
200989
+){
200990
+ Fts3HashWrapper *pWrapper = (Fts3HashWrapper*)pHash;
200991
+ pWrapper->nRef++;
200992
+ return sqlite3_create_function_v2(
200993
+ db, zName, nArg, eTextRep, (void*)pWrapper, xFunc, 0, 0, hashDestroy
200994
+ );
200995
+}
199779200996
199780200997
/*
199781200998
** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
199782200999
** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
199783201000
** respectively. The following three forward declarations are for functions
@@ -199829,17 +201046,18 @@
199829201046
if( rc!=SQLITE_OK ) return rc;
199830201047
199831201048
sqlite3Fts3SimpleTokenizerModule(&pSimple);
199832201049
sqlite3Fts3PorterTokenizerModule(&pPorter);
199833201050
199834
- /* Allocate and initialize the hash-table used to store tokenizers. */
201051
+ /* Allocate and initialize the hash-table used to store tokenizers. The
201052
+ ** reference held by this function is released before it returns. */
199835201053
pHash = sqlite3_malloc(sizeof(Fts3HashWrapper));
199836201054
if( !pHash ){
199837201055
rc = SQLITE_NOMEM;
199838201056
}else{
199839201057
sqlite3Fts3HashInit(&pHash->hash, FTS3_HASH_STRING, 1);
199840
- pHash->nRef = 0;
201058
+ pHash->nRef = 1;
199841201059
}
199842201060
199843201061
/* Load the built-in tokenizers into the hash table */
199844201062
if( rc==SQLITE_OK ){
199845201063
if( sqlite3Fts3HashInsert(&pHash->hash, "simple", 7, (void *)pSimple)
@@ -199886,20 +201104,27 @@
199886201104
}
199887201105
if( rc==SQLITE_OK ){
199888201106
pHash->nRef++;
199889201107
rc = sqlite3Fts3InitTok(db, (void *)pHash, hashDestroy);
199890201108
}
199891
- return rc;
199892201109
}
199893201110
201111
+ /* If an error has occurred, remove any modules and functions registered
201112
+ ** above. If this is a loadable extension, the shared library may be unloaded
201113
+ ** as soon as this function returns, so they must not be left in place. */
201114
+ if( rc!=SQLITE_OK ){
201115
+ sqlite3_create_module(db, "fts3", 0, 0);
201116
+ sqlite3_create_module(db, "fts4", 0, 0);
201117
+ sqlite3_create_module(db, "fts3tokenize", 0, 0);
201118
+ sqlite3_create_module(db, "fts4aux", 0, 0);
201119
+ sqlite3_create_function(db, "fts3_tokenizer", 1, SQLITE_UTF8, 0, 0, 0, 0);
201120
+ sqlite3_create_function(db, "fts3_tokenizer", 2, SQLITE_UTF8, 0, 0, 0, 0);
201121
+ }
199894201122
199895
- /* An error has occurred. Delete the hash table and return the error code. */
199896
- assert( rc!=SQLITE_OK );
199897
- if( pHash ){
199898
- sqlite3Fts3HashClear(&pHash->hash);
199899
- sqlite3_free(pHash);
199900
- }
201123
+ /* Release the reference held by this function. If nothing else still holds
201124
+ ** a reference, this deletes the hash table. */
201125
+ if( pHash ) hashDestroy(pHash);
199901201126
return rc;
199902201127
}
199903201128
199904201129
/*
199905201130
** Allocate an Fts3MultiSegReader for each token in the expression headed
@@ -201955,11 +203180,12 @@
201955203180
201956203181
/*
201957203182
** Schema of the terms table.
201958203183
*/
201959203184
#define FTS3_AUX_SCHEMA \
201960
- "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
203185
+ "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN, " \
203186
+ "PRIMARY KEY(term, col, languageid)) WITHOUT ROWID"
201961203187
201962203188
/*
201963203189
** This function does all the work for both the xConnect and xCreate methods.
201964203190
** These tables have no persistent representation of their own, so xConnect
201965203191
** and xCreate are identical operations.
@@ -202342,11 +203568,11 @@
202342203568
if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
202343203569
pCsr->filter.nTerm = (int)strlen(pCsr->filter.zTerm);
202344203570
}
202345203571
}
202346203572
202347
- if( iLe>=0 && sqlite3_value_type(apVal[0])==SQLITE_TEXT ){
203573
+ if( iLe>=0 && sqlite3_value_type(apVal[iLe])==SQLITE_TEXT ){
202348203574
pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
202349203575
if( pCsr->zStop==0 ) return SQLITE_NOMEM;
202350203576
pCsr->nStop = (int)strlen(pCsr->zStop);
202351203577
}
202352203578
@@ -203780,16 +205006,17 @@
203780205006
/*
203781205007
** Register the query expression parser test function fts3_exprtest()
203782205008
** with database connection db.
203783205009
*/
203784205010
SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash *pHash){
203785
- int rc = sqlite3_create_function(
203786
- db, "fts3_exprtest", -1, SQLITE_UTF8, (void*)pHash, fts3ExprTest, 0, 0
205011
+ int rc = sqlite3Fts3CreateHashFunction(
205012
+ db, "fts3_exprtest", -1, SQLITE_UTF8, pHash, fts3ExprTest
203787205013
);
203788205014
if( rc==SQLITE_OK ){
203789
- rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
203790
- -1, SQLITE_UTF8, (void*)pHash, fts3ExprTestRebalance, 0, 0
205015
+ rc = sqlite3Fts3CreateHashFunction(
205016
+ db, "fts3_exprtest_rebalance", -1, SQLITE_UTF8, pHash,
205017
+ fts3ExprTestRebalance
203791205018
);
203792205019
}
203793205020
return rc;
203794205021
}
203795205022
@@ -205326,11 +206553,10 @@
205326206553
sqlite3 *db,
205327206554
Fts3Hash *pHash,
205328206555
const char *zName
205329206556
){
205330206557
int rc = SQLITE_OK;
205331
- void *p = (void *)pHash;
205332206558
const int any = SQLITE_UTF8|SQLITE_DIRECTONLY;
205333206559
205334206560
#ifdef SQLITE_TEST
205335206561
char *zTest = 0;
205336206562
char *zTest2 = 0;
@@ -205341,18 +206567,22 @@
205341206567
rc = SQLITE_NOMEM;
205342206568
}
205343206569
#endif
205344206570
205345206571
if( SQLITE_OK==rc ){
205346
- rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
206572
+ rc = sqlite3Fts3CreateHashFunction(
206573
+ db, zName, 1, any, pHash, fts3TokenizerFunc
206574
+ );
205347206575
}
205348206576
if( SQLITE_OK==rc ){
205349
- rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
206577
+ rc = sqlite3Fts3CreateHashFunction(
206578
+ db, zName, 2, any, pHash, fts3TokenizerFunc
206579
+ );
205350206580
}
205351206581
#ifdef SQLITE_TEST
205352206582
if( SQLITE_OK==rc ){
205353
- rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
206583
+ rc = sqlite3Fts3CreateHashFunction(db, zTest, -1, any, pHash, testFunc);
205354206584
}
205355206585
if( SQLITE_OK==rc ){
205356206586
rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
205357206587
}
205358206588
#endif
@@ -206847,12 +208077,12 @@
206847208077
int rc = SQLITE_OK;
206848208078
206849208079
pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
206850208080
if( pList ){
206851208081
assert( (i64)pList->nData+(i64)nToken+(i64)sizeof(Fts3HashElem)
206852
- <= (i64)p->nPendingData );
206853
- p->nPendingData -= (int)(pList->nData + nToken + sizeof(Fts3HashElem));
208082
+ <= p->nPendingData );
208083
+ p->nPendingData -= pList->nData + nToken + sizeof(Fts3HashElem);
206854208084
}
206855208085
if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
206856208086
if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
206857208087
/* Malloc failed while inserting the new entry. This can only
206858208088
** happen if there was no previous entry for this token.
@@ -206861,13 +208091,13 @@
206861208091
sqlite3_free(pList);
206862208092
rc = SQLITE_NOMEM;
206863208093
}
206864208094
}
206865208095
if( rc==SQLITE_OK ){
206866
- assert( (i64)p->nPendingData + pList->nData + nToken
208096
+ assert( p->nPendingData + pList->nData + nToken
206867208097
+ sizeof(Fts3HashElem) <= 0x3fffffff );
206868
- p->nPendingData += (int)(pList->nData + nToken + sizeof(Fts3HashElem));
208098
+ p->nPendingData += pList->nData + nToken + sizeof(Fts3HashElem);
206869208099
}
206870208100
return rc;
206871208101
}
206872208102
206873208103
/*
@@ -209848,13 +211078,13 @@
209848211078
**
209849211079
** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
209850211080
** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
209851211081
** to reflect the new size of the pBlob->a[] buffer.
209852211082
*/
209853
-static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
211083
+static void blobGrowBuffer(Blob *pBlob, i64 nMin, int *pRc){
209854211084
if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
209855
- int nAlloc = nMin;
211085
+ i64 nAlloc = nMin;
209856211086
char *a = (char *)sqlite3_realloc64(pBlob->a, nAlloc);
209857211087
if( a ){
209858211088
pBlob->nAlloc = nAlloc;
209859211089
pBlob->a = a;
209860211090
}else{
@@ -210118,23 +211348,23 @@
210118211348
const char *zTerm = pCsr->zTerm;
210119211349
int nTerm = pCsr->nTerm;
210120211350
const char *aDoclist = pCsr->aDoclist;
210121211351
int nDoclist = pCsr->nDoclist;
210122211352
int rc = SQLITE_OK; /* Return code */
210123
- int nSpace; /* Total space in bytes required on leaf */
211353
+ i64 nSpace; /* Total space in bytes required on leaf */
210124211354
int nPrefix; /* Size of prefix shared with previous term */
210125211355
int nSuffix; /* Size of suffix (nTerm - nPrefix) */
210126211356
NodeWriter *pLeaf; /* Object used to write leaf nodes */
210127211357
210128211358
pLeaf = &pWriter->aNodeWriter[0];
210129211359
nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
210130211360
nSuffix = nTerm - nPrefix;
210131211361
if(nSuffix<=0 ) return FTS_CORRUPT_VTAB;
210132211362
210133
- nSpace = sqlite3Fts3VarintLen(nPrefix);
210134
- nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
210135
- nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
211363
+ nSpace = (i64)sqlite3Fts3VarintLen(nPrefix);
211364
+ nSpace += (i64)sqlite3Fts3VarintLen(nSuffix) + nSuffix;
211365
+ nSpace += (i64)sqlite3Fts3VarintLen(nDoclist) + nDoclist;
210136211366
210137211367
/* If the current block is not empty, and if adding this term/doclist
210138211368
** to the current block would make it larger than Fts3Table.nNodeSize bytes,
210139211369
** and if there is still room for another leaf page, write this block out to
210140211370
** the database. */
@@ -211110,11 +212340,11 @@
211110212340
pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
211111212341
211112212342
if( rc==SQLITE_OK ){
211113212343
rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
211114212344
assert( bUseHint==1 || bUseHint==0 );
211115
- if( iIdx==0 || (bUseHint && iIdx==1) ){
212345
+ if( rc==SQLITE_OK && (iIdx==0 || (bUseHint && iIdx==1)) ){
211116212346
int bIgnore = 0;
211117212347
rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
211118212348
if( bIgnore ){
211119212349
pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
211120212350
}
@@ -214882,11 +216112,15 @@
214882216112
#define JEDIT_INS 3 /* Insert if not exists */
214883216113
#define JEDIT_SET 4 /* Insert or overwrite */
214884216114
#define JEDIT_AINS 5 /* array_insert() */
214885216115
214886216116
/*
214887
-** Maximum nesting depth of JSON for this implementation.
216117
+** The approximate maximum nesting depth of JSON for this implementation.
216118
+**
216119
+** Applications should say well clear of this maximum. Depending on
216120
+** implementation quirks, the limit might not reached one or two before
216121
+** or one or two after the published limit.
214888216122
**
214889216123
** This limit is needed to avoid a stack overflow in the recursive
214890216124
** descent parser. A depth of 1000 is far deeper than any sane JSON
214891216125
** should go. Historical note: This limit was 2000 prior to version 3.42.0
214892216126
*/
@@ -215901,10 +217135,11 @@
215901217135
if( z[j]=='-' ){
215902217136
j++;
215903217137
if( sz<2 ) return i+1;
215904217138
}
215905217139
k = i+n+sz;
217140
+ if( z[j]=='0' && j<k-1 ) return j+1;
215906217141
while( j<k ){
215907217142
if( sqlite3Isdigit(z[j]) ){
215908217143
j++;
215909217144
}else{
215910217145
return j+1;
@@ -215961,11 +217196,11 @@
215961217196
}
215962217197
seen = 1;
215963217198
continue;
215964217199
}
215965217200
if( z[j]=='e' || z[j]=='E' ){
215966
- if( seen==2 ) return j+1;
217201
+ if( seen==2 || j==i+n ) return j+1;
215967217202
if( j==k-1 ) return j+1;
215968217203
if( z[j+1]=='+' || z[j+1]=='-' ){
215969217204
j++;
215970217205
if( j==k-1 ) return j+1;
215971217206
}
@@ -216375,10 +217610,11 @@
216375217610
pParse->iErr = i+1;
216376217611
return -1;
216377217612
}
216378217613
}else{
216379217614
if( !sqlite3Isdigit(z[i+1]) ){
217615
+ assert( z[i]=='-' || z[i]=='+' );
216380217616
/* JSON5 allows for "+Infinity" and "-Infinity" using exactly
216381217617
** that case. SQLite also allows these in any case and it allows
216382217618
** "+inf" and "-inf". */
216383217619
if( (z[i+1]=='I' || z[i+1]=='i')
216384217620
&& sqlite3StrNICmp(&z[i+1], "inf",3)==0
@@ -216394,10 +217630,22 @@
216394217630
if( z[i+1]=='.' ){
216395217631
pParse->hasNonstd = 1;
216396217632
t |= 0x01;
216397217633
goto parse_number_2;
216398217634
}
217635
+#if 0
217636
+ /* Full JSON5 compliance requires support for +NaN and -NaN, even
217637
+ ** though the extra prefix is not used for anything. Enable this
217638
+ ** block of code to get SQLite to do the same thing. It never
217639
+ ** has in an official release, and the only accomplishment of
217640
+ ** enabling it would be to take up a few bytes more code space. */
217641
+ if( sqlite3StrNICmp(&z[i+1],"NaN",3)==0 ){
217642
+ pParse->hasNonstd = 1;
217643
+ jsonBlobAppendOneByte(pParse, JSONB_NULL);
217644
+ return i+4;
217645
+ }
217646
+#endif
216399217647
pParse->iErr = i;
216400217648
return -1;
216401217649
}
216402217650
if( z[i+1]=='0' ){
216403217651
if( sqlite3Isdigit(z[i+2]) ){
@@ -216573,10 +217821,11 @@
216573217821
#endif
216574217822
while( jsonIsspace(zJson[i]) ) i++;
216575217823
if( zJson[i] ){
216576217824
i += json5Whitespace(&zJson[i]);
216577217825
if( zJson[i] ){
217826
+ pParse->iErr = i;
216578217827
if( pCtx ) sqlite3_result_error(pCtx, "malformed JSON", -1);
216579217828
jsonParseReset(pParse);
216580217829
return 1;
216581217830
}
216582217831
pParse->hasNonstd = 1;
@@ -216845,10 +218094,98 @@
216845218094
#else /* if !SQLITE_USES_INLINE */
216846218095
/* On compilers that do not support in-lining, just call the original
216847218096
** jsonbPayloadSize(). It's slower, but it gets the right answer. */
216848218097
# define jsonbPayloadSizeSemiInline(a,b,c) jsonbPayloadSize(a,b,c)
216849218098
#endif
218099
+
218100
+/*
218101
+** Convert a JSONB integer literal into either an integer (if it is small
218102
+** enough) or into a double. Include the sign. Return:
218103
+**
218104
+** 0 Value is an integer, results written into *pI.
218105
+** 1 Value is a double, results written into *pR.
218106
+** 2 Syntax error
218107
+*/
218108
+static int jsonConvertInteger(const char *zIn, u32 sz, i64 *pI, double *pR){
218109
+ u32 k = 0;
218110
+ int bNeg = 0;
218111
+ sqlite3_uint64 u = 0;
218112
+ double rOverflow = 1.0;
218113
+ if( sz==0 ) return 2;
218114
+ if( zIn[0]=='-' ){
218115
+ bNeg = 1;
218116
+ k = 1;
218117
+ }else if( zIn[0]=='+' ){
218118
+ k = 1;
218119
+ }
218120
+ if( k+2<sz && zIn[k]=='0' && (zIn[k+1]=='x' || zIn[k+1]=='X') ){
218121
+ k += 2;
218122
+ do{
218123
+ if( !sqlite3Isxdigit(zIn[k]) ){
218124
+ return 2;
218125
+ }else if( (u>>60)!=0 ){
218126
+ rOverflow *= 16.0;
218127
+ }else{
218128
+ u = u*16 + sqlite3HexToInt(zIn[k]);
218129
+ }
218130
+ k++;
218131
+ }while( k<sz );
218132
+ }else if( k>=sz ){
218133
+ return 2;
218134
+ }else{
218135
+ do{
218136
+ if( zIn[k]<'0' || zIn[k]>'9' ){
218137
+ return 2;
218138
+ }else if( (u>>60)!=0 ){
218139
+ rOverflow *= 10.0;
218140
+ }else{
218141
+ u = u*10 + zIn[k] - '0';
218142
+ }
218143
+ k++;
218144
+ }while( k<sz );
218145
+ }
218146
+ if( rOverflow>1.0
218147
+ || (u>0x7fffffffffffffffULL && (!bNeg || u>0x8000000000000000ULL))
218148
+ ){
218149
+ *pR = rOverflow * (double)u;
218150
+ if( bNeg ) *pR = -*pR;
218151
+ return 1;
218152
+ }else{
218153
+ memcpy(pI, &u, sizeof(u));
218154
+ if( bNeg && u!=0x8000000000000000ULL ) *pI = -*pI;
218155
+ return 0;
218156
+ }
218157
+}
218158
+
218159
+/*
218160
+** Tail recursive code to implement the JSON_INT5 case of of
218161
+** jsonTranslateBlobInt5ToText(). This is split out because
218162
+** the resulting reduction in the stack frame size helps the
218163
+** caller to run faster.
218164
+*/
218165
+static SQLITE_NOINLINE u32 jsonTranslateBlobInt5ToText(
218166
+ JsonParse *pParse, /* the complete parse of the JSON */
218167
+ u32 i, /* Start rendering at this index */
218168
+ JsonString *pOut, /* Write JSON here */
218169
+ u32 sz, /* Payload size */
218170
+ u32 n /* Header size */
218171
+){
218172
+ int k;
218173
+ const char *zIn = (const char*)&pParse->aBlob[i+n];
218174
+ i64 ival;
218175
+ double rval;
218176
+ k = jsonConvertInteger(zIn, sz, &ival, &rval);
218177
+ if( k==0 ){
218178
+ jsonPrintf(100, pOut, "%lld", ival);
218179
+ }else if( k==1 ){
218180
+ jsonPrintf(100, pOut, "%!0.17g", rval);
218181
+ }else{
218182
+ pOut->eErr |= JSTRING_MALFORMED;
218183
+ }
218184
+ return i+n+sz;
218185
+}
218186
+
216850218187
216851218188
/*
216852218189
** Translate the binary JSONB representation of JSON beginning at
216853218190
** pParse->aBlob[i] into a JSON text string. Append the JSON
216854218191
** text onto the end of pOut. Return the index in pParse->aBlob[]
@@ -216891,33 +218228,11 @@
216891218228
if( sz==0 ) goto malformed_jsonb;
216892218229
jsonAppendRaw(pOut, (const char*)&pParse->aBlob[i+n], sz);
216893218230
break;
216894218231
}
216895218232
case JSONB_INT5: { /* Integer literal in hexadecimal notation */
216896
- u32 k = 2;
216897
- sqlite3_uint64 u = 0;
216898
- const char *zIn = (const char*)&pParse->aBlob[i+n];
216899
- int bOverflow = 0;
216900
- if( sz==0 ) goto malformed_jsonb;
216901
- if( zIn[0]=='-' ){
216902
- jsonAppendChar(pOut, '-');
216903
- k++;
216904
- }else if( zIn[0]=='+' ){
216905
- k++;
216906
- }
216907
- for(; k<sz; k++){
216908
- if( !sqlite3Isxdigit(zIn[k]) ){
216909
- pOut->eErr |= JSTRING_MALFORMED;
216910
- break;
216911
- }else if( (u>>60)!=0 ){
216912
- bOverflow = 1;
216913
- }else{
216914
- u = u*16 + sqlite3HexToInt(zIn[k]);
216915
- }
216916
- }
216917
- jsonPrintf(100,pOut,bOverflow?"9.0e999":"%llu", u);
216918
- break;
218233
+ return jsonTranslateBlobInt5ToText(pParse, i, pOut, sz, n);
216919218234
}
216920218235
case JSONB_FLOAT5: { /* Float literal missing digits beside "." */
216921218236
u32 k = 0;
216922218237
const char *zIn = (const char*)&pParse->aBlob[i+n];
216923218238
if( sz==0 ) goto malformed_jsonb;
@@ -217170,11 +218485,10 @@
217170218485
jsonAppendChar(pOut, '\n');
217171218486
pPretty->nIndent++;
217172218487
if( pPretty->nIndent >= JSON_MAX_DEPTH ){
217173218488
jsonStringTooDeep(pOut);
217174218489
}
217175
- pParse->iDepth = pPretty->nIndent;
217176218490
while( pOut->eErr==0 ){
217177218491
jsonPrettyIndent(pPretty);
217178218492
j = jsonTranslateBlobToText(pParse, j, pOut);
217179218493
if( j>iEnd ){
217180218494
pOut->eErr |= JSTRING_MALFORMED;
@@ -217672,11 +218986,11 @@
217672218986
jsonBlobEdit(pParse, iRoot, sz, 0, 0);
217673218987
}else if( pParse->eEdit==JEDIT_INS ){
217674218988
/* Already exists, so json_insert() is a no-op */
217675218989
}else if( pParse->eEdit==JEDIT_AINS ){
217676218990
/* json_array_insert() */
217677
- if( zPath[-1]!=']' ){
218991
+ if( zPath[-1]!=']' || iLabel ){
217678218992
return JSON_LOOKUP_NOTARRAY;
217679218993
}else{
217680218994
jsonBlobEdit(pParse, iRoot, 0, pParse->aIns, pParse->nIns);
217681218995
}
217682218996
}else{
@@ -217929,56 +219243,28 @@
217929219243
sqlite3_result_int(pCtx, 0);
217930219244
break;
217931219245
}
217932219246
case JSONB_INT5:
217933219247
case JSONB_INT: {
217934
- sqlite3_int64 iRes = 0;
217935
- char *z;
217936
- int bNeg = 0;
217937
- char x;
217938
- if( sz==0 ) goto returnfromblob_malformed;
217939
- x = (char)pParse->aBlob[i+n];
217940
- if( x=='-' ){
217941
- if( sz<2 ) goto returnfromblob_malformed;
217942
- n++;
217943
- sz--;
217944
- bNeg = 1;
217945
- }
217946
- z = sqlite3DbStrNDup(db, (const char*)&pParse->aBlob[i+n], (int)sz);
217947
- if( z==0 ) goto returnfromblob_oom;
217948
- rc = sqlite3DecOrHexToI64(z, &iRes);
217949
- sqlite3DbFree(db, z);
217950
- if( rc==0 ){
217951
- if( iRes<0 ){
217952
- /* A hexadecimal literal with 16 significant digits and with the
217953
- ** high-order bit set is a negative integer in SQLite (and hence
217954
- ** iRes comes back as negative) but should be interpreted as a
217955
- ** positive value if it occurs within JSON. The value is too
217956
- ** large to appear as an SQLite integer so it must be converted
217957
- ** into floating point. */
217958
- double r;
217959
- r = (double)*(sqlite3_uint64*)&iRes;
217960
- sqlite3_result_double(pCtx, bNeg ? -r : r);
217961
- }else{
217962
- sqlite3_result_int64(pCtx, bNeg ? -iRes : iRes);
217963
- }
217964
- }else if( rc==3 && bNeg ){
217965
- sqlite3_result_int64(pCtx, SMALLEST_INT64);
217966
- }else if( rc==1 ){
219248
+ sqlite3_int64 ival;
219249
+ double rval;
219250
+ int k;
219251
+ k = jsonConvertInteger((const char*)&pParse->aBlob[i+n], sz,&ival,&rval);
219252
+ if( k==0 ){
219253
+ sqlite3_result_int64(pCtx, ival);
219254
+ }else if( k==1 ){
219255
+ sqlite3_result_double(pCtx, rval);
219256
+ }else{
217967219257
goto returnfromblob_malformed;
217968
- }else{
217969
- if( bNeg ){ n--; sz++; }
217970
- goto to_double;
217971219258
}
217972219259
break;
217973219260
}
217974219261
case JSONB_FLOAT5:
217975219262
case JSONB_FLOAT: {
217976219263
double r;
217977219264
char *z;
217978219265
if( sz==0 ) goto returnfromblob_malformed;
217979
- to_double:
217980219266
z = sqlite3DbStrNDup(db, (const char*)&pParse->aBlob[i+n], (int)sz);
217981219267
if( z==0 ) goto returnfromblob_oom;
217982219268
rc = sqlite3AtoF(z, &r);
217983219269
sqlite3DbFree(db, z);
217984219270
if( rc<=0 ) goto returnfromblob_malformed;
@@ -218242,12 +219528,15 @@
218242219528
return;
218243219529
}
218244219530
if( zPath[1]==0 ){
218245219531
if( eEdit==JEDIT_REPL || eEdit==JEDIT_SET ){
218246219532
jsonBlobEdit(p, 0, p->nBlob, ax.aBlob, ax.nBlob);
219533
+ }else if( eEdit==JEDIT_AINS ){
219534
+ rc = JSON_LOOKUP_NOTARRAY;
219535
+ }else{
219536
+ rc = 0;
218247219537
}
218248
- rc = 0;
218249219538
}else{
218250219539
p->eEdit = eEdit;
218251219540
p->nIns = ax.nBlob;
218252219541
p->aIns = ax.aBlob;
218253219542
p->delta = 0;
@@ -220063,13 +221352,14 @@
220063221352
}
220064221353
break;
220065221354
}
220066221355
if( p->eType==JSONB_OBJECT ){
220067221356
jsonReturnFromBlob(&p->sParse, p->i, ctx, 1);
220068
- }else{
220069
- assert( p->eType==JSONB_ARRAY );
221357
+ }else if( p->eType==JSONB_ARRAY ){
220070221358
sqlite3_result_int64(ctx, p->aParent[p->nParent-1].iKey);
221359
+ }else{
221360
+ sqlite3_result_error(ctx, "malformed JSON", -1);
220071221361
}
220072221362
break;
220073221363
}
220074221364
case JEACH_VALUE: {
220075221365
u32 i = jsonSkipLabel(p);
@@ -221333,11 +222623,13 @@
221333222623
if( pNode->iNode ){
221334222624
sqlite3_bind_int64(p, 1, pNode->iNode);
221335222625
}else{
221336222626
sqlite3_bind_null(p, 1);
221337222627
}
221338
- sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
222628
+ rc = sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize,
222629
+ SQLITE_STATIC);
222630
+ if( rc!=SQLITE_OK ) return rc;
221339222631
sqlite3_step(p);
221340222632
pNode->isDirty = 0;
221341222633
rc = sqlite3_reset(p);
221342222634
sqlite3_bind_null(p, 2);
221343222635
if( pNode->iNode==0 && rc==SQLITE_OK ){
@@ -225214,11 +226506,11 @@
225214226506
sqlite3_str_append(x, "[", 1);
225215226507
for(i=0; i<p->nVertex; i++){
225216226508
sqlite3_str_appendf(x, "[%!g,%!g],", GeoX(p,i), GeoY(p,i));
225217226509
}
225218226510
sqlite3_str_appendf(x, "[%!g,%!g]]", GeoX(p,0), GeoY(p,0));
225219
- sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
226511
+ sqlite3_result_str(context, x, SQLITE_FINISH);
225220226512
sqlite3_free(p);
225221226513
}
225222226514
}
225223226515
225224226516
/*
@@ -225251,11 +226543,11 @@
225251226543
if( z && z[0] ){
225252226544
sqlite3_str_appendf(x, " %s", z);
225253226545
}
225254226546
}
225255226547
sqlite3_str_appendf(x, "></polyline>");
225256
- sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
226548
+ sqlite3_result_str(context, x, SQLITE_FINISH);
225257226549
sqlite3_free(p);
225258226550
}
225259226551
}
225260226552
225261226553
/*
@@ -226570,11 +227862,12 @@
226570227862
GeoPoly *p = 0;
226571227863
if( sqlite3_value_type(pShape)==SQLITE_TEXT
226572227864
&& (p = geopolyFuncParam(0, pShape, &rc))!=0
226573227865
&& rc==SQLITE_OK
226574227866
){
226575
- sqlite3_bind_blob(pUp, 2, p->hdr, 4+8*p->nVertex, SQLITE_TRANSIENT);
227867
+ rc = sqlite3_bind_blob(pUp, 2, p->hdr, 4+8*p->nVertex,
227868
+ SQLITE_TRANSIENT);
226576227869
}else{
226577227870
sqlite3_bind_value(pUp, 2, pShape);
226578227871
}
226579227872
sqlite3_free(p);
226580227873
nChange = 1;
@@ -226581,11 +227874,11 @@
226581227874
}
226582227875
for(jj=1; jj<nData-2; jj++){
226583227876
nChange++;
226584227877
sqlite3_bind_value(pUp, jj+2, aData[jj+2]);
226585227878
}
226586
- if( nChange ){
227879
+ if( rc==SQLITE_OK && nChange ){
226587227880
sqlite3_step(pUp);
226588227881
rc = sqlite3_reset(pUp);
226589227882
}
226590227883
}
226591227884
@@ -228654,10 +229947,11 @@
228654229947
sqlite3_stmt *pTblIter; /* Iterate through tables */
228655229948
sqlite3_stmt *pIdxIter; /* Index iterator */
228656229949
int nTblCol; /* Size of azTblCol[] array */
228657229950
char **azTblCol; /* Array of unquoted target column names */
228658229951
char **azTblType; /* Array of target column types */
229952
+ char **azTblDflt; /* Array of target column DEFAULT exprs */
228659229953
int *aiSrcOrder; /* src table col -> target table col */
228660229954
u8 *abTblPk; /* Array of flags, set on target PK columns */
228661229955
u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
228662229956
u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
228663229957
int eType; /* Table type - an RBU_PK_XXX value */
@@ -229219,14 +230513,16 @@
229219230513
static void rbuObjIterFreeCols(RbuObjIter *pIter){
229220230514
int i;
229221230515
for(i=0; i<pIter->nTblCol; i++){
229222230516
sqlite3_free(pIter->azTblCol[i]);
229223230517
sqlite3_free(pIter->azTblType[i]);
230518
+ sqlite3_free(pIter->azTblDflt[i]);
229224230519
}
229225230520
sqlite3_free(pIter->azTblCol);
229226230521
pIter->azTblCol = 0;
229227230522
pIter->azTblType = 0;
230523
+ pIter->azTblDflt = 0;
229228230524
pIter->aiSrcOrder = 0;
229229230525
pIter->abTblPk = 0;
229230230526
pIter->abNotNull = 0;
229231230527
pIter->nTblCol = 0;
229232230528
pIter->eType = 0; /* Invalid value */
@@ -229475,10 +230771,47 @@
229475230771
}
229476230772
sqlite3_free(zSql);
229477230773
va_end(ap);
229478230774
return p->rc;
229479230775
}
230776
+
230777
+/*
230778
+** Like rbuMPrintfExec() except that it is guaranteed to only run a
230779
+** single statement. If the generated SQL text includes two or more
230780
+** statements, all but the first is ignored.
230781
+**
230782
+** If an error occurs, an error code and error message is stored in the
230783
+** RBU handle. If an error has already occurred when this function is
230784
+** called, it is a no-op.
230785
+*/
230786
+static int rbuMPrintfOneStmt(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
230787
+ va_list ap;
230788
+ char *zSql;
230789
+ va_start(ap, zFmt);
230790
+ zSql = sqlite3_vmprintf(zFmt, ap);
230791
+ if( p->rc==SQLITE_OK ){
230792
+ if( zSql==0 ){
230793
+ p->rc = SQLITE_NOMEM;
230794
+ }else{
230795
+ sqlite3_stmt *pStmt;
230796
+ p->rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
230797
+ if( pStmt ){
230798
+ if( p->rc==SQLITE_OK ){
230799
+ while( sqlite3_step(pStmt)==SQLITE_ROW ){}
230800
+ }
230801
+ p->rc = sqlite3_finalize(pStmt);
230802
+ }
230803
+ if( p->rc!=SQLITE_OK ){
230804
+ sqlite3_free(p->zErrmsg);
230805
+ p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
230806
+ }
230807
+ }
230808
+ }
230809
+ sqlite3_free(zSql);
230810
+ va_end(ap);
230811
+ return p->rc;
230812
+}
229480230813
229481230814
/*
229482230815
** Attempt to allocate and return a pointer to a zeroed block of nByte
229483230816
** bytes.
229484230817
**
@@ -229507,18 +230840,19 @@
229507230840
** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
229508230841
** there is room for at least nCol elements. If an OOM occurs, store an
229509230842
** error code in the RBU handle passed as the first argument.
229510230843
*/
229511230844
static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
229512
- sqlite3_int64 nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
230845
+ sqlite3_int64 nByte = (3*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
229513230846
char **azNew;
229514230847
229515230848
azNew = (char**)rbuMalloc(p, nByte);
229516230849
if( azNew ){
229517230850
pIter->azTblCol = azNew;
229518230851
pIter->azTblType = &azNew[nCol];
229519
- pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
230852
+ pIter->azTblDflt = &azNew[nCol*2];
230853
+ pIter->aiSrcOrder = (int*)&pIter->azTblDflt[nCol];
229520230854
pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
229521230855
pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
229522230856
pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
229523230857
}
229524230858
}
@@ -229548,10 +230882,35 @@
229548230882
}
229549230883
}
229550230884
229551230885
return zRet;
229552230886
}
230887
+
230888
+/*
230889
+** Return a copy of the declared column type zType that is safe to paste
230890
+** into a CREATE TABLE statement.
230891
+**
230892
+** zType comes from the schema of a database that RBU does not control.
230893
+** A type name may legally be a quoted string, so after the quotes are
230894
+** removed (as PRAGMA table_xinfo does) it can contain any text at all,
230895
+** including ")", ";" and CHECK or other column constraints. So it is
230896
+** returned as a single double-quoted token, which the parser turns back
230897
+** into the identical type name. An empty type is returned as an empty
230898
+** string. The result must be freed using sqlite3_free().
230899
+*/
230900
+static char *rbuQuoteType(const char *zType, int *pRc){
230901
+ char *zRet = 0;
230902
+ if( *pRc==SQLITE_OK ){
230903
+ if( zType==0 || zType[0]==0 ){
230904
+ zRet = rbuStrndup("", pRc);
230905
+ }else{
230906
+ zRet = sqlite3_mprintf("\"%w\"", zType);
230907
+ if( zRet==0 ) *pRc = SQLITE_NOMEM;
230908
+ }
230909
+ }
230910
+ return zRet;
230911
+}
229553230912
229554230913
/*
229555230914
** Finalize the statement passed as the second argument.
229556230915
**
229557230916
** If the sqlite3_finalize() call indicates that an error occurs, and the
@@ -229734,10 +231093,29 @@
229734231093
229735231094
rbuFinalize(p, pList);
229736231095
if( bIndex==0 ) pIter->abIndexed = 0;
229737231096
}
229738231097
231098
+/*
231099
+** Return true if table zTbl in the main database of the target is a
231100
+** STRICT table, or false otherwise. If an error occurs, an error code
231101
+** and message are left in the RBU handle and zero is returned.
231102
+*/
231103
+static int rbuTableIsStrict(sqlite3rbu *p, const char *zTbl){
231104
+ int bStrict = 0;
231105
+ sqlite3_stmt *pStmt = 0;
231106
+ if( p->rc==SQLITE_OK ){
231107
+ p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
231108
+ sqlite3_mprintf("PRAGMA main.table_list(%Q)", zTbl)
231109
+ );
231110
+ if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
231111
+ bStrict = sqlite3_column_int(pStmt, 5);
231112
+ }
231113
+ rbuFinalize(p, pStmt);
231114
+ }
231115
+ return bStrict;
231116
+}
229739231117
229740231118
/*
229741231119
** If they are not already populated, populate the pIter->azTblCol[],
229742231120
** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
229743231121
** the table (not index) that the iterator currently points to.
@@ -229752,10 +231130,11 @@
229752231130
int nCol = 0;
229753231131
int i; /* for() loop iterator variable */
229754231132
int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
229755231133
int iOrder = 0;
229756231134
int iTnum = 0;
231135
+ int bStrict = 0; /* True if target is a STRICT table */
229757231136
229758231137
/* Figure out the type of table this step will deal with. */
229759231138
assert( pIter->eType==0 );
229760231139
rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
229761231140
if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
@@ -229802,14 +231181,16 @@
229802231181
p->zErrmsg = sqlite3_mprintf(
229803231182
"table %q %s rbu_rowid column", pIter->zDataTbl,
229804231183
(bRbuRowid ? "may not have" : "requires")
229805231184
);
229806231185
}
231186
+
231187
+ bStrict = rbuTableIsStrict(p, pIter->zTbl);
229807231188
229808231189
/* Check that all non-HIDDEN columns in the destination table are also
229809
- ** present in the input table. Populate the abTblPk[], azTblType[] and
229810
- ** aiTblOrder[] arrays at the same time.
231190
+ ** present in the input table. Populate the abTblPk[], azTblType[],
231191
+ ** azTblDflt[] and aiTblOrder[] arrays at the same time.
229811231192
**
229812231193
** RBU does not support tables with GENERATED columns. If the target
229813231194
** table has any, return an error. */
229814231195
if( p->rc==SQLITE_OK ){
229815231196
p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
@@ -229838,17 +231219,22 @@
229838231219
);
229839231220
}else{
229840231221
int iPk = sqlite3_column_int(pStmt, 5);
229841231222
int bNotNull = sqlite3_column_int(pStmt, 3);
229842231223
const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
231224
+ const char *zDflt = (const char*)sqlite3_column_text(pStmt, 4);
229843231225
229844231226
if( i!=iOrder ){
229845231227
SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
229846231228
SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
229847231229
}
229848231230
229849
- pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
231231
+ /* In a STRICT table, ANY means no affinity. In the non-STRICT
231232
+ ** imposter it would mean NUMERIC, so declare it without a type. */
231233
+ if( bStrict && sqlite3_stricmp(zType, "ANY")==0 ) zType = "";
231234
+ pIter->azTblType[iOrder] = rbuQuoteType(zType, &p->rc);
231235
+ pIter->azTblDflt[iOrder] = rbuStrndup(zDflt, &p->rc);
229850231236
assert( iPk>=0 );
229851231237
pIter->abTblPk[iOrder] = (u8)iPk;
229852231238
pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
229853231239
iOrder++;
229854231240
}
@@ -230517,11 +231903,11 @@
230517231903
}
230518231904
zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
230519231905
rbuFinalize(p, pXInfo);
230520231906
230521231907
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
230522
- rbuMPrintfExec(p, p->dbMain,
231908
+ rbuMPrintfOneStmt(p, p->dbMain,
230523231909
"CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
230524231910
zCols, zPk
230525231911
);
230526231912
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
230527231913
}
@@ -230567,13 +231953,15 @@
230567231953
if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
230568231954
/* If the target table column is an "INTEGER PRIMARY KEY", add
230569231955
** "PRIMARY KEY" to the imposter table column declaration. */
230570231956
zPk = "PRIMARY KEY ";
230571231957
}
230572
- zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s",
231958
+ zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s%s%s",
230573231959
zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
230574
- (pIter->abNotNull[iCol] ? " NOT NULL" : "")
231960
+ (pIter->abNotNull[iCol] ? " NOT NULL" : ""),
231961
+ (pIter->azTblDflt[iCol] ? " DEFAULT " : ""),
231962
+ (pIter->azTblDflt[iCol] ? pIter->azTblDflt[iCol] : "")
230575231963
);
230576231964
zComma = ", ";
230577231965
}
230578231966
230579231967
if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
@@ -230582,11 +231970,11 @@
230582231970
zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
230583231971
}
230584231972
}
230585231973
230586231974
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
230587
- rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
231975
+ rbuMPrintfOneStmt(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
230588231976
pIter->zTbl, zSql,
230589231977
(pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
230590231978
);
230591231979
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
230592231980
}
@@ -230786,11 +232174,11 @@
230786232174
zBind = rbuObjIterGetBindlist(p, nBind);
230787232175
230788232176
/* Create the imposter table used to write to this index. */
230789232177
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
230790232178
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
230791
- rbuMPrintfExec(p, p->dbMain,
232179
+ rbuMPrintfOneStmt(p, p->dbMain,
230792232180
"CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
230793232181
zTbl, zImposterCols, zImposterPK
230794232182
);
230795232183
sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
230796232184
@@ -230913,11 +232301,11 @@
230913232301
if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
230914232302
zRbuRowid = ", rbu_rowid";
230915232303
}
230916232304
230917232305
/* Create the rbu_tmp_xxx table and the triggers to populate it. */
230918
- rbuMPrintfExec(p, p->dbRbu,
232306
+ rbuMPrintfOneStmt(p, p->dbRbu,
230919232307
"CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
230920232308
"SELECT *%s FROM '%q' WHERE 0;"
230921232309
, p->zStateDb, pIter->zDataTbl
230922232310
, (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
230923232311
, pIter->zDataTbl
@@ -230942,11 +232330,11 @@
230942232330
zWrite, zTbl, zOldlist,
230943232331
zWrite, zTbl, zNewlist
230944232332
);
230945232333
230946232334
if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
230947
- rbuMPrintfExec(p, p->dbMain,
232335
+ rbuMPrintfOneStmt(p, p->dbMain,
230948232336
"CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
230949232337
"BEGIN "
230950232338
" SELECT rbu_tmp_insert(0, %s);"
230951232339
"END;",
230952232340
zWrite, zTbl, zNewlist
@@ -231227,11 +232615,11 @@
231227232615
}
231228232616
231229232617
/* If using separate RBU and state databases, attach the state database to
231230232618
** the RBU db handle now. */
231231232619
if( p->zState ){
231232
- rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
232620
+ rbuMPrintfOneStmt(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
231233232621
memcpy(p->zStateDb, "stat", 4);
231234232622
}else{
231235232623
memcpy(p->zStateDb, "main", 4);
231236232624
}
231237232625
@@ -231353,11 +232741,11 @@
231353232741
}
231354232742
231355232743
if( p->rc==SQLITE_OK ){
231356232744
p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
231357232745
}
231358
- rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_schema");
232746
+ rbuMPrintfOneStmt(p, p->dbMain, "SELECT * FROM sqlite_schema");
231359232747
231360232748
/* Mark the database file just opened as an RBU target database. If
231361232749
** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
231362232750
** This is an error. */
231363232751
if( p->rc==SQLITE_OK ){
@@ -231961,11 +233349,11 @@
231961233349
iCookie = sqlite3_column_int(pStmt, 0);
231962233350
}
231963233351
rbuFinalize(p, pStmt);
231964233352
}
231965233353
if( p->rc==SQLITE_OK ){
231966
- rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
233354
+ rbuMPrintfOneStmt(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
231967233355
}
231968233356
}
231969233357
}
231970233358
231971233359
/*
@@ -232039,11 +233427,11 @@
232039233427
sqlite3_stmt *pPragma = 0;
232040233428
p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
232041233429
sqlite3_mprintf("PRAGMA main.%s", zPragma)
232042233430
);
232043233431
if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
232044
- p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
233432
+ p->rc = rbuMPrintfOneStmt(p, p->dbMain, "PRAGMA main.%s = %d",
232045233433
zPragma, sqlite3_column_int(pPragma, 0)
232046233434
);
232047233435
}
232048233436
rbuFinalize(p, pPragma);
232049233437
}
@@ -232130,11 +233518,11 @@
232130233518
if( pIter->bCleanup ){
232131233519
/* Clean up the rbu_tmp_xxx table for the previous table. It
232132233520
** cannot be dropped as there are currently active SQL statements.
232133233521
** But the contents can be deleted. */
232134233522
if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
232135
- rbuMPrintfExec(p, p->dbRbu,
233523
+ rbuMPrintfOneStmt(p, p->dbRbu,
232136233524
"DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
232137233525
);
232138233526
}
232139233527
}else{
232140233528
rbuObjIterPrepareAll(p, pIter, 0);
@@ -234286,11 +235674,13 @@
234286235674
if( p->iPgno==1 ) nHdr += 100;
234287235675
p->nCell = get2byte(&aHdr[3]);
234288235676
p->nMxPayload = 0;
234289235677
szPage = sqlite3BtreeGetPageSize(pBt);
234290235678
234291
- nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
235679
+ nUnused = get2byte(&aHdr[5]);
235680
+ if( nUnused==0 ) nUnused = 65536;
235681
+ nUnused -= nHdr + 2*p->nCell;
234292235682
nUnused += (int)aHdr[7];
234293235683
iOff = get2byte(&aHdr[1]);
234294235684
while( iOff ){
234295235685
int iNext;
234296235686
if( iOff>=szPage ) goto statPageIsCorrupt;
@@ -235036,11 +236426,16 @@
235036236426
if( NEVER(pBt==0) ) return SQLITE_OK;
235037236427
pCsr->pPager = sqlite3BtreePager(pBt);
235038236428
pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
235039236429
pCsr->mxPgno = sqlite3BtreeLastPage(pBt);
235040236430
if( idxNum & 1 ){
235041
- i64 iPg = sqlite3_value_int64(argv[idxNum>>1]);
236431
+ i64 iPg;
236432
+ if( sqlite3_value_numeric_type(argv[idxNum>>1])==SQLITE_INTEGER ){
236433
+ iPg = sqlite3_value_int64(argv[idxNum>>1]);
236434
+ }else{
236435
+ iPg = 0;
236436
+ }
235042236437
assert( argc>(idxNum>>1) );
235043236438
if( iPg<1 || iPg>pCsr->mxPgno ){
235044236439
pCsr->pgno = 1;
235045236440
pCsr->mxPgno = 0;
235046236441
}else{
@@ -235798,14 +237193,17 @@
235798237193
}else if( mFlags==CARRAY_BLOB ){
235799237194
struct iovec *p = (struct iovec*)pNew->aData;
235800237195
unsigned char *z = (unsigned char*)&p[nData];
235801237196
for(i=0; i<nData; i++){
235802237197
size_t n = ((struct iovec*)aData)[i].iov_len;
237198
+ void *a = ((struct iovec*)aData)[i].iov_base;
235803237199
p[i].iov_len = n;
235804
- p[i].iov_base = z;
235805
- z += n;
235806
- memcpy(p[i].iov_base, ((struct iovec*)aData)[i].iov_base, n);
237200
+ p[i].iov_base = a ? z : 0;
237201
+ if( n ){
237202
+ z += n;
237203
+ memcpy(p[i].iov_base, a, n);
237204
+ }
235807237205
}
235808237206
}else if( sz>0 ){
235809237207
memcpy(pNew->aData, aData, sz);
235810237208
}
235811237209
pNew->xDel = sqlite3_free;
@@ -236494,11 +237892,12 @@
236494237892
int n;
236495237893
assert( a!=0 );
236496237894
e = *a;
236497237895
if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
236498237896
if( e==SQLITE_TEXT || e==SQLITE_BLOB ){
236499
- return sessionVarintGet(&a[1], &n) + 1 + n;
237897
+ const int v = sessionVarintGet(&a[1], &n);
237898
+ return v + 1 + n;
236500237899
}
236501237900
return 1;
236502237901
}
236503237902
236504237903
/*
@@ -239796,13 +241195,19 @@
239796241195
** there are no fields in the old.* record that are not (a) PK fields,
239797241196
** or (b) also present in the new.* record.
239798241197
**
239799241198
** Such records are technically corrupt, but the rebaser was at one
239800241199
** point generating them. Under most circumstances this is benign, but
239801
- ** can cause spurious SQLITE_RANGE errors when applying the changeset. */
241200
+ ** can cause spurious SQLITE_RANGE errors when applying the changeset.
241201
+ **
241202
+ ** Also check that all PK fields are present in the old.* record. If
241203
+ ** they are not, the changeset is corrupt. */
239802241204
if( p->bPatchset==0 && p->op==SQLITE_UPDATE){
239803241205
for(i=0; i<p->nCol; i++){
241206
+ if( p->abPK[i] && p->apValue[i]==0 ){
241207
+ return (p->rc = SQLITE_CORRUPT_BKPT);
241208
+ }
239804241209
if( p->abPK[i]==0 && p->apValue[i+p->nCol]==0 ){
239805241210
sqlite3ValueFree(p->apValue[i]);
239806241211
p->apValue[i] = 0;
239807241212
}
239808241213
}
@@ -241050,23 +242455,26 @@
241050242455
** before reattempting the INSERT. */
241051242456
else if( bReplace ){
241052242457
assert( pIter->op==SQLITE_INSERT );
241053242458
rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
241054242459
if( rc==SQLITE_OK ){
242460
+ int rc2;
241055242461
rc = sessionBindRow(pIter,
241056242462
sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
241057242463
sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
241058
- }
241059
- if( rc==SQLITE_OK ){
241060
- sqlite3_step(pApply->pDelete);
241061
- rc = sqlite3_reset(pApply->pDelete);
241062
- }
241063
- if( rc==SQLITE_OK ){
241064
- rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
241065
- }
241066
- if( rc==SQLITE_OK ){
241067
- rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
242464
+ if( rc==SQLITE_OK ){
242465
+ sqlite3_step(pApply->pDelete);
242466
+ rc = sqlite3_reset(pApply->pDelete);
242467
+ }
242468
+ if( rc==SQLITE_OK ){
242469
+ rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
242470
+ }
242471
+ if( rc!=SQLITE_OK ){
242472
+ sqlite3_exec(db, "ROLLBACK TO replace_op", 0, 0, 0);
242473
+ }
242474
+ rc2 = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
242475
+ if( rc==SQLITE_OK ) rc = rc2;
241068242476
}
241069242477
}
241070242478
}
241071242479
241072242480
return rc;
@@ -243213,13 +244621,10 @@
243213244621
*pzErr = sqlite3_mprintf("no such table: %s", zTab);
243214244622
}
243215244623
}
243216244624
if( rc==SQLITE_OK ){
243217244625
int nReq = pTab->nCol * (eOp==SQLITE_UPDATE ? 2 : 1);
243218
- pGrp->cd.pTab = pTab;
243219
- pGrp->cd.eOp = eOp;
243220
- pGrp->cd.bIndirect = bIndirect;
243221244626
243222244627
if( pGrp->cd.nBufAlloc<nReq ){
243223244628
SessionBuffer *aBuf = (SessionBuffer*)sqlite3_realloc(
243224244629
pGrp->cd.aBuf, nReq * sizeof(SessionBuffer)
243225244630
);
@@ -243231,10 +244636,18 @@
243231244636
);
243232244637
pGrp->cd.aBuf = aBuf;
243233244638
pGrp->cd.nBufAlloc = nReq;
243234244639
}
243235244640
}
244641
+
244642
+ /* Only mark a change as under construction once the column buffers
244643
+ ** have been allocated. */
244644
+ if( rc==SQLITE_OK ){
244645
+ pGrp->cd.pTab = pTab;
244646
+ pGrp->cd.eOp = eOp;
244647
+ pGrp->cd.bIndirect = bIndirect;
244648
+ }
243236244649
243237244650
#ifdef SQLITE_DEBUG
243238244651
{
243239244652
/* Assert that all column values are currently undefined */
243240244653
int ii;
@@ -243273,12 +244686,13 @@
243273244686
SessionBuffer *pBuf = &pGrp->cd.aBuf[iCol];
243274244687
if( pGrp->cd.eOp==SQLITE_UPDATE && bNew ){
243275244688
pBuf += pGrp->cd.pTab->nCol;
243276244689
}
243277244690
pBuf->nBuf = 0;
243278
- sessionBufferGrow(pBuf, nReq, &rc);
243279
- pBuf->nBuf = nReq;
244691
+ if( sessionBufferGrow(pBuf, nReq, &rc)==0 ){
244692
+ pBuf->nBuf = (int)nReq;
244693
+ }
243280244694
*ppBuf = pBuf;
243281244695
}
243282244696
return rc;
243283244697
}
243284244698
@@ -248832,11 +250246,11 @@
248832250246
zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
248833250247
for(i=0; zSql && i<pConfig->nCol; i++){
248834250248
const char *zSep = (i==0?"":", ");
248835250249
zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
248836250250
}
248837
- zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
250251
+ zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q BLOB HIDDEN, %s HIDDEN)",
248838250252
zSql, pConfig->zName, FTS5_RANK_NAME
248839250253
);
248840250254
248841250255
assert( zSql || rc==SQLITE_NOMEM );
248842250256
if( zSql ){
@@ -249135,11 +250549,13 @@
249135250549
pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
249136250550
pConfig->nDeleteMerge = FTS5_DEFAULT_DELETE_AUTOMERGE;
249137250551
249138250552
zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
249139250553
if( zSql ){
249140
- rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
250554
+ rc = sqlite3_prepare_v3(
250555
+ pConfig->db, zSql, -1, SQLITE_PREPARE_FROM_DDL, &p, 0
250556
+ );
249141250557
sqlite3_free(zSql);
249142250558
}
249143250559
249144250560
assert( rc==SQLITE_OK || p==0 );
249145250561
if( rc==SQLITE_OK ){
@@ -249185,11 +250601,11 @@
249185250601
char *zMsg = 0;
249186250602
249187250603
va_start(ap, zFmt);
249188250604
zMsg = sqlite3_vmprintf(zFmt, ap);
249189250605
if( pConfig->pzErrmsg ){
249190
- assert( *pConfig->pzErrmsg==0 );
250606
+ sqlite3_free(*pConfig->pzErrmsg);
249191250607
*pConfig->pzErrmsg = zMsg;
249192250608
}else{
249193250609
sqlite3_free(zMsg);
249194250610
}
249195250611
@@ -253657,10 +255073,13 @@
253657255073
/* Variables populated based on current entry. */
253658255074
Fts5Buffer term; /* Current term */
253659255075
i64 iRowid; /* Current rowid */
253660255076
int nPos; /* Number of bytes in current position list */
253661255077
u8 bDel; /* True if the delete flag is set */
255078
+
255079
+ /* True if the current entry shadows an entry that has the delete flag set */
255080
+ u8 bDelDup;
253662255081
};
253663255082
253664255083
static int fts5IndexCorruptRowid(Fts5Index *pIdx, i64 iRowid){
253665255084
pIdx->rc = FTS5_CORRUPT;
253666255085
sqlite3Fts5ConfigErrmsg(pIdx->pConfig,
@@ -254050,11 +255469,12 @@
254050255469
char *zSql
254051255470
){
254052255471
if( p->rc==SQLITE_OK ){
254053255472
if( zSql ){
254054255473
int rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
254055
- SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB,
255474
+ SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB
255475
+ |SQLITE_PREPARE_FROM_DDL,
254056255476
ppStmt, 0);
254057255477
/* If this prepare() call fails with SQLITE_ERROR, then one of the
254058255478
** %_idx or %_data tables has been removed or modified. Call this
254059255479
** corruption. */
254060255480
p->rc = (rc==SQLITE_ERROR ? SQLITE_CORRUPT : rc);
@@ -254064,10 +255484,21 @@
254064255484
}
254065255485
sqlite3_free(zSql);
254066255486
return p->rc;
254067255487
}
254068255488
255489
+/*
255490
+** If *pRc is other than SQLITE_OK when this function is called, it is a
255491
+** no-op. Otherwise, call sqlite3_step() and then sqlite3_reset() on the
255492
+** supplied statement pointer. Set (*pRc) to the result of sqlite3_reset().
255493
+*/
255494
+static void fts5StepAndReset(int *pRc, sqlite3_stmt *pStmt){
255495
+ if( *pRc==SQLITE_OK ){
255496
+ sqlite3_step(pStmt);
255497
+ *pRc = sqlite3_reset(pStmt);
255498
+ }
255499
+}
254069255500
254070255501
/*
254071255502
** INSERT OR REPLACE a record into the %_data table.
254072255503
*/
254073255504
static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
@@ -254081,13 +255512,12 @@
254081255512
));
254082255513
if( p->rc ) return;
254083255514
}
254084255515
254085255516
sqlite3_bind_int64(p->pWriter, 1, iRowid);
254086
- sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
254087
- sqlite3_step(p->pWriter);
254088
- p->rc = sqlite3_reset(p->pWriter);
255517
+ p->rc = sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
255518
+ fts5StepAndReset(&p->rc, p->pWriter);
254089255519
sqlite3_bind_null(p->pWriter, 2);
254090255520
}
254091255521
254092255522
/*
254093255523
** Execute the following SQL:
@@ -254690,10 +256120,21 @@
254690256120
}
254691256121
fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
254692256122
}
254693256123
}
254694256124
256125
+/*
256126
+** Return the page number iPgno+nDelta. If this is larger than FTS5_MAX_PGNO,
256127
+** which can only happen if the doclist-index record is corrupt, return
256128
+** FTS5_MAX_PGNO+1 instead. No leaf page with that number may exist, so
256129
+** this causes the corruption to be detected when the caller attempts to
256130
+** use the page number.
256131
+*/
256132
+static int fts5AddPgno(int iPgno, int nDelta){
256133
+ i64 iRet = (i64)iPgno + nDelta;
256134
+ return (int)(iRet>FTS5_MAX_PGNO ? FTS5_MAX_PGNO+1 : iRet);
256135
+}
254695256136
254696256137
/*
254697256138
** Advance the iterator passed as the only argument. If the end of the
254698256139
** doclist-index page is reached, return non-zero.
254699256140
*/
@@ -254712,11 +256153,11 @@
254712256153
if( pData->p[iOff] ) break;
254713256154
}
254714256155
254715256156
if( iOff<pData->nn ){
254716256157
u64 iVal;
254717
- pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
256158
+ pLvl->iLeafPgno = fts5AddPgno(pLvl->iLeafPgno, iOff-pLvl->iOff+1);
254718256159
iOff += fts5GetVarint(&pData->p[iOff], &iVal);
254719256160
pLvl->iRowid += iVal;
254720256161
pLvl->iOff = iOff;
254721256162
}else{
254722256163
pLvl->bEof = 1;
@@ -254822,11 +256263,11 @@
254822256263
ii++;
254823256264
}
254824256265
ii += sqlite3Fts5GetVarint(&a[ii], &delta);
254825256266
254826256267
if( ii>=iOff ) break;
254827
- pLvl->iLeafPgno += nZero+1;
256268
+ pLvl->iLeafPgno = fts5AddPgno(pLvl->iLeafPgno, nZero+1);
254828256269
pLvl->iRowid += delta;
254829256270
pLvl->iOff = ii;
254830256271
}
254831256272
}
254832256273
@@ -255828,11 +257269,12 @@
255828257269
/* This block sets stack variable iPg to the leaf page number that may
255829257270
** contain term (pTerm/nTerm), if it is present in the segment. */
255830257271
pIdxSelect = fts5IdxSelectStmt(p);
255831257272
if( p->rc ) return;
255832257273
sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
255833
- sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
257274
+ p->rc = sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
257275
+ if( p->rc ) return;
255834257276
if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
255835257277
i64 val = sqlite3_column_int(pIdxSelect, 0);
255836257278
iPg = (int)(val>>1);
255837257279
bDlidx = (val & 0x0001);
255838257280
}
@@ -255920,12 +257362,12 @@
255920257362
255921257363
pSel = fts5IdxNextStmt(p);
255922257364
if( pSel ){
255923257365
assert( p->rc==SQLITE_OK );
255924257366
sqlite3_bind_int(pSel, 1, pSeg->iSegid);
255925
- sqlite3_bind_blob(pSel, 2, pTerm, nTerm, SQLITE_STATIC);
255926
-
257367
+ p->rc = sqlite3_bind_blob(pSel, 2, pTerm, nTerm, SQLITE_STATIC);
257368
+ if( p->rc ) return;
255927257369
if( sqlite3_step(pSel)==SQLITE_ROW ){
255928257370
i64 val = sqlite3_column_int64(pSel, 0);
255929257371
iPg = (int)(val>>1);
255930257372
bDlidx = (val & 0x0001);
255931257373
}
@@ -256204,10 +257646,14 @@
256204257646
if( res==0 ){
256205257647
assert_nc( i2>i1 );
256206257648
assert_nc( i2!=0 );
256207257649
pRes->bTermEq = 1;
256208257650
if( p1->iRowid==p2->iRowid ){
257651
+ /* p2 is about to be advanced past this entry. If it, or an entry
257652
+ ** it shadowed, has the delete flag set, record this on p1. */
257653
+ p1->bDelDup |= (p2->bDel | p2->bDelDup);
257654
+ p2->bDelDup = 0;
256209257655
return i2;
256210257656
}
256211257657
res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
256212257658
}
256213257659
assert( res!=0 );
@@ -256721,10 +258167,15 @@
256721258167
int pgno = pSeg->iLeafPgno;
256722258168
int pgnoSave = 0;
256723258169
256724258170
/* This function does not work with detail=none databases. */
256725258171
assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
258172
+
258173
+ if( nChunk<0 ){
258174
+ FTS5_CORRUPT_IDX(p);
258175
+ return;
258176
+ }
256726258177
256727258178
if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
256728258179
pgnoSave = pgno+1;
256729258180
}
256730258181
@@ -257416,14 +258867,15 @@
257416258867
257417258868
if( p->rc==SQLITE_OK ){
257418258869
const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
257419258870
/* The following was already done in fts5WriteInit(): */
257420258871
/* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
257421
- sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
258872
+ p->rc = sqlite3_bind_blob(
258873
+ p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC
258874
+ );
257422258875
sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
257423
- sqlite3_step(p->pIdxWriter);
257424
- p->rc = sqlite3_reset(p->pIdxWriter);
258876
+ fts5StepAndReset(&p->rc, p->pIdxWriter);
257425258877
sqlite3_bind_null(p->pIdxWriter, 2);
257426258878
}
257427258879
pWriter->iBtPage = 0;
257428258880
}
257429258881
@@ -257966,10 +259418,18 @@
257966259418
){
257967259419
Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
257968259420
int nPos; /* position-list size field value */
257969259421
int nTerm;
257970259422
const u8 *pTerm;
259423
+ int bDel; /* True to set delete flag on output */
259424
+
259425
+ /* If this entry has the delete flag set, or shadows an entry with the
259426
+ ** delete flag set, set the delete flag on the output. Unless the output
259427
+ ** will be the oldest segment in the table - in that case the delete flag
259428
+ ** may be discarded. */
259429
+ bDel = bOldest ? 0 : (pSegIter->bDel || pSegIter->bDelDup);
259430
+ pSegIter->bDelDup = 0;
257971259431
257972259432
pTerm = fts5MultiIterTerm(pIter, &nTerm);
257973259433
if( nTerm!=term.n || fts5Memcmp(pTerm, term.p, nTerm) ){
257974259434
if( pnRem && writer.nLeafWritten>nRem ){
257975259435
break;
@@ -257977,11 +259437,11 @@
257977259437
fts5BufferSet(&p->rc, &term, nTerm, pTerm);
257978259438
bTermWritten =0;
257979259439
}
257980259440
257981259441
/* Check for key annihilation. */
257982
- if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
259442
+ if( pSegIter->nPos==0 && (bOldest || bDel==0) ) continue;
257983259443
257984259444
if( p->rc==SQLITE_OK && bTermWritten==0 ){
257985259445
/* This is a new term. Append a term to the output segment. */
257986259446
fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
257987259447
bTermWritten = 1;
@@ -257990,19 +259450,19 @@
257990259450
/* Append the rowid to the output */
257991259451
/* WRITEPOSLISTSIZE */
257992259452
fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
257993259453
257994259454
if( eDetail==FTS5_DETAIL_NONE ){
257995
- if( pSegIter->bDel ){
259455
+ if( bDel ){
257996259456
fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
257997259457
if( pSegIter->nPos>0 ){
257998259458
fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
257999259459
}
258000259460
}
258001259461
}else{
258002259462
/* Append the position-list data to the output */
258003
- nPos = pSegIter->nPos*2 + pSegIter->bDel;
259463
+ nPos = pSegIter->nPos*2 + bDel;
258004259464
fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
258005259465
fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
258006259466
}
258007259467
}
258008259468
@@ -258437,11 +259897,12 @@
258437259897
258438259898
iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
258439259899
assert_nc( iSOP<=pSeg->iLeafOffset );
258440259900
258441259901
if( bDetailNone ){
258442
- while( iSOP<pSeg->iLeafOffset ){
259902
+ int iEnd = pSeg->iLeafOffset - (pSeg->bDel ? 1 + pSeg->nPos : 0);
259903
+ while( iSOP<iEnd ){
258443259904
if( aPg[iSOP]==0x00 ) iSOP++;
258444259905
if( aPg[iSOP]==0x00 ) iSOP++;
258445259906
iStart = iSOP;
258446259907
iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
258447259908
}
@@ -258502,11 +259963,11 @@
258502259963
}
258503259964
}
258504259965
258505259966
if( pSeg->bDel ){
258506259967
iOff += sqlite3Fts5PutVarint(&aPg[iOff], iDelta);
258507
- aPg[iOff++] = 0x01;
259968
+ aPg[iOff++] = bDetailNone ? 0x00 : 0x01;
258508259969
}else if( bLastInDoclist==0 ){
258509259970
if( iNextOff!=iPgIdx ){
258510259971
u64 iNextDelta = 0;
258511259972
iNextOff += fts5GetVarint(&aPg[iNextOff], &iNextDelta);
258512259973
iOff += sqlite3Fts5PutVarint(&aPg[iOff], iDelta + iNextDelta);
@@ -261715,11 +263176,13 @@
261715263176
fts5DlidxIterEof(p, pDlidx)==0;
261716263177
fts5DlidxIterNext(p, pDlidx)
261717263178
){
261718263179
261719263180
/* Check any rowid-less pages that occur before the current leaf. */
261720
- for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
263181
+ for(iPg=iPrevLeaf+1; p->rc==SQLITE_OK && iPg<fts5DlidxIterPgno(pDlidx);
263182
+ iPg++
263183
+ ){
261721263184
iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
261722263185
pLeaf = fts5LeafRead(p, iKey);
261723263186
if( pLeaf ){
261724263187
if( fts5LeafFirstRowidOff(pLeaf)!=0 ) FTS5_CORRUPT_ROWID(p, iKey);
261725263188
fts5DataRelease(pLeaf);
@@ -263917,11 +265380,12 @@
263917265380
if( zRankArgs ){
263918265381
char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
263919265382
if( zSql ){
263920265383
sqlite3_stmt *pStmt = 0;
263921265384
rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
263922
- SQLITE_PREPARE_PERSISTENT, &pStmt, 0);
265385
+ SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_FROM_DDL, &pStmt, 0
265386
+ );
263923265387
sqlite3_free(zSql);
263924265388
assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
263925265389
if( rc==SQLITE_OK ){
263926265390
if( SQLITE_ROW==sqlite3_step(pStmt) ){
263927265391
sqlite3_int64 nByte;
@@ -264859,10 +266323,11 @@
264859266323
*/
264860266324
static int fts5RollbackMethod(sqlite3_vtab *pVtab){
264861266325
int rc;
264862266326
Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
264863266327
fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
266328
+ fts5TripCursors(pTab);
264864266329
rc = sqlite3Fts5StorageRollback(pTab->pStorage);
264865266330
pTab->p.pConfig->pgsz = 0;
264866266331
return rc;
264867266332
}
264868266333
@@ -266335,11 +267800,11 @@
266335267800
int nArg, /* Number of args */
266336267801
sqlite3_value **apUnused /* Function arguments */
266337267802
){
266338267803
assert( nArg==0 );
266339267804
UNUSED_PARAM2(nArg, apUnused);
266340
- sqlite3_result_text(pCtx, "fts5: 2026-10-24 22:25:07 d08cabd778f7844d04f3852d93197e80c0d0f4f30a589f7fd0d28577fa3fa68b", -1, SQLITE_TRANSIENT);
267805
+ sqlite3_result_text(pCtx, "fts5: 2026-11-15 00:55:04 ad4ee20509dc4e2803f35093b03df55cb3e39c8083b0d4ad231e1432516c7841", -1, SQLITE_TRANSIENT);
266341267806
}
266342267807
266343267808
/*
266344267809
** Implementation of fts5_locale(LOCALE, TEXT) function.
266345267810
**
@@ -266810,11 +268275,11 @@
266810268275
}
266811268276
266812268277
if( zSql==0 ){
266813268278
rc = SQLITE_NOMEM;
266814268279
}else{
266815
- int f = SQLITE_PREPARE_PERSISTENT;
268280
+ int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_FROM_DDL;
266816268281
if( eStmt>FTS5_STMT_LOOKUP2 ) f |= SQLITE_PREPARE_NO_VTAB;
266817268282
p->pConfig->bLock++;
266818268283
rc = sqlite3_prepare_v3(pC->db, zSql, -1, f, &p->aStmt[eStmt], 0);
266819268284
p->pConfig->bLock--;
266820268285
sqlite3_free(zSql);
@@ -267376,14 +268841,16 @@
267376268841
rc = sqlite3Fts5IndexGetOrigin(p->pIndex, &iOrigin);
267377268842
sqlite3_bind_int64(pReplace, 3, iOrigin);
267378268843
}
267379268844
}
267380268845
if( rc==SQLITE_OK ){
267381
- sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
267382
- sqlite3_step(pReplace);
267383
- rc = sqlite3_reset(pReplace);
267384
- sqlite3_bind_null(pReplace, 2);
268846
+ rc = sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
268847
+ if( rc==SQLITE_OK ){
268848
+ sqlite3_step(pReplace);
268849
+ rc = sqlite3_reset(pReplace);
268850
+ sqlite3_bind_null(pReplace, 2);
268851
+ }
267385268852
}
267386268853
}
267387268854
return rc;
267388268855
}
267389268856
@@ -267765,11 +269232,13 @@
267765269232
);
267766269233
if( zSql==0 ){
267767269234
rc = SQLITE_NOMEM;
267768269235
}else{
267769269236
sqlite3_stmt *pCnt = 0;
267770
- rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
269237
+ rc = sqlite3_prepare_v3(
269238
+ pConfig->db, zSql, -1, SQLITE_PREPARE_FROM_DDL, &pCnt, 0
269239
+ );
267771269240
if( rc==SQLITE_OK ){
267772269241
if( SQLITE_ROW==sqlite3_step(pCnt) ){
267773269242
*pnRow = sqlite3_column_int64(pCnt, 0);
267774269243
}
267775269244
rc = sqlite3_finalize(pCnt);
267776269245
--- extsrc/sqlite3.c
+++ extsrc/sqlite3.c
@@ -16,11 +16,11 @@
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
19 **
20 ** The content in this amalgamation comes from Fossil check-in
21 ** d08cabd778f7844d04f3852d93197e80c0d0 with changes in files:
22 **
23 **
24 */
25 #ifndef SQLITE_AMALGAMATION
26 #define SQLITE_CORE 1
@@ -467,14 +467,14 @@
467 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
468 ** [sqlite_version()] and [sqlite_source_id()].
469 */
470 #define SQLITE_VERSION "3.55.0"
471 #define SQLITE_VERSION_NUMBER 3055000
472 #define SQLITE_SOURCE_ID "2026-10-24 22:25:07 d08cabd778f7844d04f3852d93197e80c0d0f4f30a589f7fd0d28577fa3fa68b"
473 #define SQLITE_SCM_BRANCH "trunk"
474 #define SQLITE_SCM_TAGS ""
475 #define SQLITE_SCM_DATETIME "2026-10-24T22:25:07.764Z"
476
477 /*
478 ** CAPI3REF: Run-Time Library Version Numbers
479 ** KEYWORDS: sqlite3_version sqlite3_sourceid
480 **
@@ -795,10 +795,11 @@
795 #define SQLITE_FORMAT 24 /* Not used */
796 #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
797 #define SQLITE_NOTADB 26 /* File opened that is not a database file */
798 #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
799 #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
 
800 #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
801 #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
802 /* end-of-error-codes */
803
804 /*
@@ -2983,16 +2984,23 @@
2983 ** the number of significant digits that SQLite will attempt to preserve when
2984 ** converting floating point numbers (IEEE 754 "doubles") into text. The
2985 ** default value 17, as of SQLite version 3.52.0. The value was 15 in all
2986 ** prior versions.<p>
2987 ** This option takes two arguments which are an integer and a pointer
2988 ** to an integer. The first argument is a small integer, between 3 and 23, or
2989 ** zero. The FP_DIGITS setting is changed to that small integer, or left
2990 ** unaltered if the first argument is zero or out of range. The second argument
2991 ** is a pointer to an integer. If the pointer is not NULL, then the value of
2992 ** the FP_DIGITS setting, after possibly being modified by the first
2993 ** arguments, is written into the integer to which the second argument points.
 
 
 
 
 
 
 
2994 ** </dd>
2995 **
2996 ** </dl>
2997 **
2998 ** [[DBCONFIG arguments]] <h3>Arguments To SQLITE_DBCONFIG Options</h3>
@@ -3039,11 +3047,12 @@
3039 #define SQLITE_DBCONFIG_REVERSE_SCANORDER 1019 /* int int* */
3040 #define SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE 1020 /* int int* */
3041 #define SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE 1021 /* int int* */
3042 #define SQLITE_DBCONFIG_ENABLE_COMMENTS 1022 /* int int* */
3043 #define SQLITE_DBCONFIG_FP_DIGITS 1023 /* int int* */
3044 #define SQLITE_DBCONFIG_MAX 1023 /* Largest DBCONFIG */
 
3045
3046 /*
3047 ** CAPI3REF: Enable Or Disable Extended Result Codes
3048 ** METHOD: sqlite3
3049 **
@@ -5320,11 +5329,11 @@
5320 ** or indicates the lifetime of the object referenced by the third parameter.
5321 ** These three options exist:
5322 ** ^ (1) A destructor to dispose of the BLOB or string after SQLite has finished
5323 ** with it may be passed. ^It is called to dispose of the BLOB or string even
5324 ** if the call to the bind API fails, except the destructor is not called if
5325 ** the third parameter is a NULL pointer or the fourth parameter is negative.
5326 ** ^ (2) The special constant, [SQLITE_STATIC], may be passed to indicate that
5327 ** the application remains responsible for disposing of the object. ^In this
5328 ** case, the object and the provided pointer to it must remain valid until
5329 ** either the prepared statement is finalized or the same SQL parameter is
5330 ** bound to something else, whichever occurs sooner.
@@ -9112,11 +9121,12 @@
9112 #define SQLITE_TESTCTRL_TRACEFLAGS 31
9113 #define SQLITE_TESTCTRL_TUNE 32
9114 #define SQLITE_TESTCTRL_LOGEST 33
9115 #define SQLITE_TESTCTRL_USELONGDOUBLE 34 /* NOT USED */
9116 #define SQLITE_TESTCTRL_ATOF 34
9117 #define SQLITE_TESTCTRL_LAST 34 /* Largest TESTCTRL */
 
9118
9119 /*
9120 ** CAPI3REF: SQL Keyword Checking
9121 **
9122 ** These routines provide access to the set of SQL language keywords
@@ -18041,64 +18051,66 @@
18041 #define OP_ResetCount 132
18042 #define OP_SorterCompare 133 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
18043 #define OP_SorterData 134 /* synopsis: r[P2]=data */
18044 #define OP_RowData 135 /* synopsis: r[P2]=data */
18045 #define OP_Rowid 136 /* synopsis: r[P2]=PX rowid of P1 */
18046 #define OP_NullRow 137
18047 #define OP_SeekEnd 138
18048 #define OP_IdxInsert 139 /* synopsis: key=r[P2] */
18049 #define OP_SorterInsert 140 /* synopsis: key=r[P2] */
18050 #define OP_IdxDelete 141 /* synopsis: key=r[P2@P5] */
18051 #define OP_DeferredSeek 142 /* synopsis: Move P3 to P1.rowid if needed */
18052 #define OP_IdxRowid 143 /* synopsis: r[P2]=rowid */
18053 #define OP_FinishSeek 144
18054 #define OP_Destroy 145
18055 #define OP_Clear 146
18056 #define OP_ResetSorter 147
18057 #define OP_CreateBtree 148 /* synopsis: r[P2]=root iDb=P1 flags=P3 */
18058 #define OP_SqlExec 149
18059 #define OP_ParseSchema 150
18060 #define OP_LoadAnalysis 151
18061 #define OP_DropTable 152
18062 #define OP_DropIndex 153
18063 #define OP_Real 154 /* same as TK_FLOAT, synopsis: r[P2]=PDBL13 */
18064 #define OP_DropTrigger 155
18065 #define OP_IntegrityCk 156
18066 #define OP_RowSetAdd 157 /* synopsis: rowset(P1)=r[P2] */
18067 #define OP_Param 158
18068 #define OP_FkCounter 159 /* synopsis: fkctr[P1]+=P2 */
18069 #define OP_MemMax 160 /* synopsis: r[P1]=max(r[P1],r[P2]) */
18070 #define OP_OffsetLimit 161 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
18071 #define OP_AggInverse 162 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */
18072 #define OP_AggStep 163 /* synopsis: accum=r[P3] step(r[P2@P5]) */
18073 #define OP_AggStep1 164 /* synopsis: accum=r[P3] step(r[P2@P5]) */
18074 #define OP_AggValue 165 /* synopsis: r[P3]=value N=P2 */
18075 #define OP_AggFinal 166 /* synopsis: accum=r[P1] N=P2 */
18076 #define OP_Expire 167
18077 #define OP_CursorLock 168
18078 #define OP_CursorUnlock 169
18079 #define OP_TableLock 170 /* synopsis: iDb=P1 root=P2 write=P3 */
18080 #define OP_VBegin 171
18081 #define OP_VCreate 172
18082 #define OP_VDestroy 173
18083 #define OP_VOpen 174
18084 #define OP_VCheck 175
18085 #define OP_VInitIn 176 /* synopsis: r[P2]=ValueList(P1,P3) */
18086 #define OP_VColumn 177 /* synopsis: r[P3]=vcolumn(P2) */
18087 #define OP_VRename 178
18088 #define OP_Pagecount 179
18089 #define OP_MaxPgcnt 180
18090 #define OP_ClrSubtype 181 /* synopsis: r[P1].subtype = 0 */
18091 #define OP_GetSubtype 182 /* synopsis: r[P2] = r[P1].subtype */
18092 #define OP_SetSubtype 183 /* synopsis: r[P2].subtype = r[P1] */
18093 #define OP_FilterAdd 184 /* synopsis: filter(P1) += key(P3@P4) */
18094 #define OP_Trace 185
18095 #define OP_CursorHint 186
18096 #define OP_ReleaseReg 187 /* synopsis: release r[P1@P2] mask P3 */
18097 #define OP_Noop 188
18098 #define OP_Explain 189
18099 #define OP_Abortable 190
 
 
18100
18101 /* Properties such as "out2" or "jump" that are specified in
18102 ** comments following the "case" for each opcode in the vdbe.c
18103 ** are encoded into bitvectors as follows:
18104 */
@@ -18126,17 +18138,18 @@
18126 /* 96 */ 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x26,\
18127 /* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,\
18128 /* 112 */ 0x26, 0x40, 0x00, 0x12, 0x40, 0x40, 0x10, 0x40,\
18129 /* 120 */ 0x00, 0x00, 0x00, 0x40, 0x00, 0x40, 0x40, 0x10,\
18130 /* 128 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00,\
18131 /* 136 */ 0x50, 0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50,\
18132 /* 144 */ 0x40, 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,\
18133 /* 152 */ 0x00, 0x00, 0x10, 0x00, 0x00, 0x06, 0x10, 0x00,\
18134 /* 160 */ 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
18135 /* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10,\
18136 /* 176 */ 0x50, 0x40, 0x00, 0x10, 0x10, 0x02, 0x12, 0x12,\
18137 /* 184 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}
 
18138
18139 /* The resolve3P2Values() routine is able to run faster if it knows
18140 ** the value of the largest JUMP opcode. The smaller the maximum
18141 ** JUMP opcode the better, so the mkopcodeh.tcl script that
18142 ** generated this include file strives to group all JUMP opcodes
@@ -18930,14 +18943,15 @@
18930 u8 mTrace; /* zero or more SQLITE_TRACE flags */
18931 u8 noSharedCache; /* True if no shared-cache backends */
18932 u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
18933 u8 eOpenState; /* Current condition of the connection */
18934 u8 nFpDigit; /* Significant digits to keep on double->text */
 
18935 int nextPagesize; /* Pagesize after VACUUM if >0 */
18936 i64 nChange; /* Value returned by sqlite3_changes() */
18937 i64 nTotalChange; /* Value returned by sqlite3_total_changes() */
18938 u32 dbOptFlags; /* Flags to enable/disable optimizations */
18939 int aLimit[SQLITE_N_LIMIT]; /* Limits */
18940 int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
18941 struct sqlite3InitInfo { /* Information used during initialization */
18942 Pgno newTnum; /* Rootpage of table being initialized */
18943 u8 iDb; /* Which db file is being initialized */
@@ -19161,11 +19175,11 @@
19161 #define SQLITE_PropagateConst 16 /* The constant propagation opt */
19162 #define SQLITE_MinMaxOpt 17 /* The min/max optimization */
19163 #define SQLITE_SeekScan 18 /* The OP_SeekScan optimization */
19164 #define SQLITE_OmitOrderBy 19 /* Omit pointless ORDER BY */
19165 #define SQLITE_BloomFilter 20 /* Use a Bloom filters */
19166 /* 21 -- Available for reuse */
19167 #define SQLITE_BalancedMerge 22 /* Balance multi-way merges */
19168 #define SQLITE_ReleaseReg 23 /* Use OP_ReleaseReg for testing */
19169 #define SQLITE_FlttnUnionAll 24 /* Disable the UNION ALL flattener */
19170 #define SQLITE_IndexedExpr 25 /* Pull exprs from index when able */
19171 #define SQLITE_Coroutines 26 /* Co-routines for subqueries */
@@ -19173,16 +19187,17 @@
19173 #define SQLITE_OnePass 28 /* Single-pass DELETE and UPDATE */
19174 #define SQLITE_OrderBySubq 29 /* ORDER BY in subquery helps outer */
19175 #define SQLITE_StarQuery 30 /* Heurists for star queries */
19176 #define SQLITE_ExistsToJoin 31 /* The EXISTS-to-JOIN optimization */
19177 #define SQLITE_UnionLimit 32 /* Optimizations for UNION + LIMIT */
 
19178
19179 /*
19180 ** Macros for testing whether or not optimizations are enabled or disabled.
19181 */
19182 #define OptimizationDisabled(D,M) (((D)->dbOptFlags&(1ul<<((M)-1)))!=0)
19183 #define OptimizationEnabled(D,M) (((D)->dbOptFlags&(1ul<<((M)-1)))==0)
19184
19185 /*
19186 ** Return true if it OK to factor constant expressions into the initialization
19187 ** code. The argument is a Parse object for the code generator.
19188 */
@@ -20486,10 +20501,11 @@
20486 unsigned reusable :1; /* Constant expression is reusable */
20487 unsigned bSorterRef :1; /* Defer evaluation until after sorting */
20488 unsigned bNulls :1; /* True if explicit "NULLS FIRST/LAST" */
20489 unsigned bUsed :1; /* This column used in a SF_NestedFrom subquery */
20490 unsigned bUsingTerm:1; /* Term from the USING clause of a NestedFrom */
 
20491 unsigned bNoExpand: 1; /* Term is an auxiliary in NestedFrom and should
20492 ** not be expanded by "*" in parent queries */
20493 } fg;
20494 union {
20495 struct { /* Used by any ExprList other than Parse.pConsExpr */
@@ -21053,20 +21069,26 @@
21053 #if SQLITE_MAX_ATTACHED>30
21054 typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
21055 # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
21056 # define DbMaskZero(M) memset((M),0,sizeof(M))
21057 # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
 
21058 # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
21059 # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
21060 #else
21061 typedef unsigned int yDbMask;
21062 # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
21063 # define DbMaskZero(M) ((M)=0)
21064 # define DbMaskSet(M,I) ((M)|=(((yDbMask)1)<<(I)))
 
21065 # define DbMaskAllZero(M) ((M)==0)
21066 # define DbMaskNonZero(M) ((M)!=0)
21067 #endif
 
 
 
 
21068
21069 /*
21070 ** For each index X that has as one of its arguments either an expression
21071 ** or the name of a virtual generated column, and if X is in scope such that
21072 ** the value of the expression can simply be read from the index, then
@@ -21194,11 +21216,10 @@
21194 ** determined by offsetof(Parse,aTempReg).
21195 **************************************************************************/
21196
21197 int aTempReg[8]; /* Holding area for temporary registers */
21198 Parse *pOuterParse; /* Outer Parse object when nested */
21199 Token sNameToken; /* Token with unqualified schema object name */
21200 u32 oldmask; /* Mask of old.* columns referenced */
21201 u32 newmask; /* Mask of new.* columns referenced */
21202 union {
21203 struct { /* These fields available when isCreate is true */
21204 int addrCrTab; /* Address of OP_CreateBtree on CREATE TABLE */
@@ -21223,11 +21244,12 @@
21223 ** each recursion. The boundary between these two regions is determined
21224 ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
21225 ** first field in the recursive region.
21226 ************************************************************************/
21227
21228 Token sLastToken; /* The last token parsed */
 
21229 ynVar nVar; /* Number of '?' variables seen in the SQL so far */
21230 u64 aVnbmc[SQLITE_VNBMC]; /* Varible Number Bitmap Cache */
21231 u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
21232 u8 explain; /* True if the EXPLAIN flag is found on the query */
21233 u8 eParseMode; /* PARSE_MODE_XXX constant */
@@ -21347,17 +21369,25 @@
21347 ** linked list is stored as the "pTrigger" member of the associated
21348 ** struct Table.
21349 **
21350 ** The "step_list" member points to the first element of a linked list
21351 ** containing the SQL statements specified as the trigger program.
 
 
 
 
 
 
 
21352 */
21353 struct Trigger {
21354 char *zName; /* The name of the trigger */
21355 char *table; /* The table or view to which the trigger applies */
21356 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
21357 u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
21358 u8 bReturning; /* This trigger implements a RETURNING clause */
 
21359 Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
21360 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
21361 the <column-list> is stored here */
21362 Schema *pSchema; /* Schema containing the trigger */
21363 Schema *pTabSchema; /* Schema containing the table */
@@ -22276,11 +22306,11 @@
22276 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
22277 #ifndef SQLITE_OMIT_VIRTUALTABLE
22278 SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
22279 #endif
22280 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
22281 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
22282 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
22283 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
22284 SQLITE_PRIVATE void sqlite3ColumnSetExpr(Parse*,Table*,Column*,Expr*);
22285 SQLITE_PRIVATE Expr *sqlite3ColumnExpr(Table*,Column*);
22286 SQLITE_PRIVATE Expr *sqlite3ColumnExprAuth(Table*,Column*,Parse*);
@@ -22353,10 +22383,11 @@
22353 # define sqlite3ViewGetColumnNames(A,B) 0
22354 #endif
22355
22356 #if SQLITE_MAX_ATTACHED>30
22357 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
 
22358 #endif
22359 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
22360 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
22361 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
22362 SQLITE_PRIVATE void sqlite3DeleteTableGeneric(sqlite3*, void*);
@@ -22718,11 +22749,11 @@
22718 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
22719 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
22720 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr*);
22721 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
22722 SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*);
22723 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse*, const char*,const char*,const char*);
22724 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, i64);
22725 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
22726 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
22727 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
22728 SQLITE_PRIVATE int sqlite3AbsInt32(int);
@@ -22787,10 +22818,11 @@
22787 );
22788 SQLITE_PRIVATE void sqlite3AlterSetNotNull(Parse*, SrcList*, Token*, Token*);
22789 SQLITE_PRIVATE i64 sqlite3GetToken(const unsigned char *, int *);
22790 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
22791 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int);
 
22792 SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int, int);
22793 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr*);
22794 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
22795 SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, SrcItem*);
22796 SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
@@ -22952,16 +22984,16 @@
22952 );
22953 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
22954 #endif
22955 SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db);
22956 #ifndef SQLITE_OMIT_VIRTUALTABLE
22957 SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName);
22958 SQLITE_PRIVATE int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*);
22959 SQLITE_PRIVATE void sqlite3MarkAllShadowTablesOf(sqlite3*, Table*);
22960 SQLITE_PRIVATE void sqlite3VtabEponymousTableClearAll(sqlite3*);
22961 #else
22962 # define sqlite3ShadowTableName(A,B) 0
22963 # define sqlite3IsShadowTableOf(A,B,C) 0
22964 # define sqlite3MarkAllShadowTablesOf(A,B)
22965 # define sqlite3VtabEponymousTableClearAll(X)
22966 #endif
22967 SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
@@ -25999,11 +26031,11 @@
25999 ** The HH, MM, and SS must each be exactly 2 digits. The
26000 ** fractional seconds FFFF can be one or more digits.
26001 **
26002 ** Return 1 if there is a parsing error and 0 on success.
26003 */
26004 static int parseHhMmSs(const char *zDate, DateTime *p){
26005 int h, m, s;
26006 double ms = 0.0;
26007 if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
26008 return 1;
26009 }
@@ -26035,10 +26067,11 @@
26035 p->rawS = 0;
26036 p->validHMS = 1;
26037 p->h = h;
26038 p->m = m;
26039 p->s = s + ms;
 
26040 if( parseTimezone(zDate, p) ) return 1;
26041 return 0;
26042 }
26043
26044 /*
@@ -26154,11 +26187,11 @@
26154 return 1;
26155 }
26156 if( neg ) Y = -Y;
26157 zDate += 10;
26158 while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
26159 if( parseHhMmSs(zDate, p)==0 ){
26160 if( p->h==24 ){
26161 int mxD = daysOfMonth(Y,M);
26162 p->h = 0;
26163 D++;
26164 if( D>mxD ){
@@ -26245,11 +26278,11 @@
26245 DateTime *p
26246 ){
26247 double r;
26248 if( parseYyyyMmDd(zDate,p)==0 ){
26249 return 0;
26250 }else if( parseHhMmSs(zDate, p)==0 ){
26251 return 0;
26252 }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
26253 return setDateTimeToCurrent(context, p);
26254 }else if( sqlite3AtoF(zDate, &r)>0 ){
26255 setRawDateNumber(p, r);
@@ -26624,10 +26657,11 @@
26624 clearYMD_HMS_TZ(p);
26625 rc = 0;
26626 }else if( sqlite3_stricmp(z,"year")==0 ){
26627 p->M = 12;
26628 p->D = 31;
 
26629 rc = 0;
26630 }else if( sqlite3_stricmp(z,"day")==0 ){
26631 rc = 0;
26632 }
26633 break;
@@ -26640,10 +26674,11 @@
26640 ** previous month.
26641 */
26642 if( sqlite3_stricmp(z, "floor")==0 ){
26643 computeJD(p);
26644 p->iJD -= p->nFloor*86400000;
 
26645 clearYMD_HMS_TZ(p);
26646 rc = 0;
26647 }
26648 break;
26649 }
@@ -26703,11 +26738,13 @@
26703 if( p->isUtc==0 ){
26704 i64 iOrigJD; /* Original localtime */
26705 i64 iGuess; /* Guess at the corresponding utc time */
26706 int cnt = 0; /* Safety to prevent infinite loop */
26707 i64 iErr; /* Guess is off by this much */
 
26708
 
26709 computeJD(p);
26710 iGuess = iOrigJD = p->iJD;
26711 iErr = 0;
26712 do{
26713 DateTime new;
@@ -26723,10 +26760,11 @@
26723 memset(p, 0, sizeof(*p));
26724 p->iJD = iGuess;
26725 p->validJD = 1;
26726 p->isUtc = 1;
26727 p->isLocal = 0;
 
26728 }
26729 rc = SQLITE_OK;
26730 }
26731 #endif
26732 break;
@@ -26757,10 +26795,11 @@
26757 if( Z>n ) Z -= 7;
26758 p->iJD += (n - Z)*86400000;
26759 if( strchr(z+8,'-')!=0 ) p->iJD -= 7*86400000;
26760 }
26761 clearYMD_HMS_TZ(p);
 
26762 rc = 0;
26763 }
26764 break;
26765 }
26766 case 's': {
@@ -26796,14 +26835,16 @@
26796 p->rawS = 0;
26797 p->tz = 0;
26798 p->validJD = 0;
26799 if( sqlite3_stricmp(z,"month")==0 ){
26800 p->D = 1;
 
26801 rc = 0;
26802 }else if( sqlite3_stricmp(z,"year")==0 ){
26803 p->M = 1;
26804 p->D = 1;
 
26805 rc = 0;
26806 }else if( sqlite3_stricmp(z,"day")==0 ){
26807 rc = 0;
26808 }
26809 break;
@@ -26896,21 +26937,30 @@
26896 ** omitted.
26897 */
26898
26899 DateTime tx;
26900 sqlite3_int64 day;
 
 
 
 
26901 if( !sqlite3Isdigit(*z2) ) z2++;
26902 memset(&tx, 0, sizeof(tx));
26903 if( parseHhMmSs(z2, &tx) ) break;
 
 
 
26904 computeJD(&tx);
26905 tx.iJD -= 43200000;
26906 day = tx.iJD/86400000;
26907 tx.iJD -= day*86400000;
 
26908 if( z0=='-' ) tx.iJD = -tx.iJD;
26909 computeJD(p);
26910 clearYMD_HMS_TZ(p);
26911 p->iJD += tx.iJD;
 
26912 rc = 0;
26913 break;
26914 }
26915
26916 /* If control reaches this point, it means the transformation is
@@ -27007,13 +27057,14 @@
27007 n = sqlite3_value_bytes(argv[i]);
27008 if( z==0 || parseModifier(context, (char*)z, n, p, i) ) return 1;
27009 }
27010 computeJD(p);
27011 if( p->isError || !validJulianDay(p->iJD) ) return 1;
27012 if( argc==1 && p->validYMD && p->D>28 ){
27013 /* Make sure a YYYY-MM-DD is normalized.
27014 ** Example: 2023-02-31 -> 2023-03-03 */
 
27015 assert( p->validJD );
27016 p->validYMD = 0;
27017 }
27018 return 0;
27019 }
@@ -33722,11 +33773,11 @@
33722 if( (zz[i]&0xc0)==0x80 ) len--;
33723 }
33724 }
33725 if( width>len ){
33726 sqlite3_int64 sp = width-len;
33727 assert( sp>0 && sp<0x7fffffff );
33728 sqlite3StrAppendchar64(pAccum, (int)sp, ' ');
33729 if( !flag_leftjustify
33730 && n>0
33731 && sqlite3_str_errcode(pAccum)==0
33732 ){
@@ -37664,11 +37715,11 @@
37664 ** Return an IEEE754 floating point value that approximates d*pow(10,p).
37665 **
37666 ** The (current) algorithm is adapted from the work of Ross Cox at
37667 ** https://github.com/rsc/fpfmt
37668 */
37669 static double sqlite3Fp10Convert2(u64 d, int p){
37670 int b, lp, e, adj, s;
37671 u32 pwr10l, mid1;
37672 u64 pwr10h, x, hi, lo, sticky, u, m;
37673 double r;
37674 if( p<POWERSOF10_FIRST ) return 0.0;
@@ -37723,15 +37774,17 @@
37723 **
37724 ** bit 0 => Set if any prefix of the input is valid. Clear if
37725 ** there is no prefix of the input that can be seen as
37726 ** a valid floating point number.
37727 ** bit 1 => Set if the input contains a decimal point or eNNN
37728 ** clause. Zero if the input is an integer.
 
37729 ** bit 2 => The input is exactly 0.0, not an underflow from
37730 ** some value near zero.
37731 ** bit 3 => Set if there are more than about 19 significant
37732 ** digits in the input.
 
37733 **
37734 ** If the input contains a syntax error but begins with text that might
37735 ** be a valid number of some kind, then the result is negative. The
37736 ** result is only zero if no prefix of the input could be interpreted as
37737 ** a number.
@@ -37760,11 +37813,11 @@
37760 SQLITE_PRIVATE int sqlite3AtoF(const char *zIn, double *pResult){
37761 #ifndef SQLITE_OMIT_FLOATING_POINT
37762 const unsigned char *z = (const unsigned char*)zIn;
37763 int neg = 0; /* True for a negative value */
37764 u64 s = 0; /* mantissa */
37765 int d = 0; /* Value is s * pow(10,d) */
37766 int mState = 0; /* 1: digit seen 2: fp 4: hard-zero */
37767 unsigned v; /* Value of a single digit */
37768
37769 start_of_text:
37770 if( (v = (unsigned)z[0] - '0')<10 ){
@@ -37812,12 +37865,17 @@
37812 *pResult = 0.0;
37813 return 0;
37814 }
37815 mState |= 2;
37816 }else if( mState==0 ){
37817 *pResult = 0.0;
37818 return 0;
 
 
 
 
 
37819 }
37820
37821 /* if exponent is present */
37822 if( *z=='e' || *z=='E' ){
37823 int esign;
@@ -37833,18 +37891,18 @@
37833 z++;
37834 }
37835 }
37836 /* copy digits to exponent */
37837 if( (v = (unsigned)z[0] - '0')<10 ){
37838 int exp = v;
37839 z++;
37840 mState |= 2;
37841 while( (v = (unsigned)z[0] - '0')<10 ){
37842 exp = exp<10000 ? (exp*10 + v) : 10000;
37843 z++;
37844 }
37845 d += esign*exp;
37846 }else{
37847 z--; /* Leave z[0] at 'e' or '+' or '-',
37848 ** so that the return is 0 or -1 */
37849 }
37850 }
@@ -39387,11 +39445,10 @@
39387 }
39388 insertElement(pH, pH->ht ? &pH->ht[new_elem->h % pH->htsize] : 0, new_elem);
39389 return 0;
39390 }
39391
39392
39393 /************** End of hash.c ************************************************/
39394 /************** Begin file opcodes.c *****************************************/
39395 /* Automatically generated. Do not edit */
39396 /* See the tool/mkopcodec.tcl script for details. */
39397 #if !defined(SQLITE_OMIT_EXPLAIN) \
@@ -39539,64 +39596,66 @@
39539 /* 132 */ "ResetCount" OpHelp(""),
39540 /* 133 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
39541 /* 134 */ "SorterData" OpHelp("r[P2]=data"),
39542 /* 135 */ "RowData" OpHelp("r[P2]=data"),
39543 /* 136 */ "Rowid" OpHelp("r[P2]=PX rowid of P1"),
39544 /* 137 */ "NullRow" OpHelp(""),
39545 /* 138 */ "SeekEnd" OpHelp(""),
39546 /* 139 */ "IdxInsert" OpHelp("key=r[P2]"),
39547 /* 140 */ "SorterInsert" OpHelp("key=r[P2]"),
39548 /* 141 */ "IdxDelete" OpHelp("key=r[P2@P5]"),
39549 /* 142 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),
39550 /* 143 */ "IdxRowid" OpHelp("r[P2]=rowid"),
39551 /* 144 */ "FinishSeek" OpHelp(""),
39552 /* 145 */ "Destroy" OpHelp(""),
39553 /* 146 */ "Clear" OpHelp(""),
39554 /* 147 */ "ResetSorter" OpHelp(""),
39555 /* 148 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),
39556 /* 149 */ "SqlExec" OpHelp(""),
39557 /* 150 */ "ParseSchema" OpHelp(""),
39558 /* 151 */ "LoadAnalysis" OpHelp(""),
39559 /* 152 */ "DropTable" OpHelp(""),
39560 /* 153 */ "DropIndex" OpHelp(""),
39561 /* 154 */ "Real" OpHelp("r[P2]=PDBL13"),
39562 /* 155 */ "DropTrigger" OpHelp(""),
39563 /* 156 */ "IntegrityCk" OpHelp(""),
39564 /* 157 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
39565 /* 158 */ "Param" OpHelp(""),
39566 /* 159 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
39567 /* 160 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
39568 /* 161 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
39569 /* 162 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"),
39570 /* 163 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
39571 /* 164 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"),
39572 /* 165 */ "AggValue" OpHelp("r[P3]=value N=P2"),
39573 /* 166 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
39574 /* 167 */ "Expire" OpHelp(""),
39575 /* 168 */ "CursorLock" OpHelp(""),
39576 /* 169 */ "CursorUnlock" OpHelp(""),
39577 /* 170 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
39578 /* 171 */ "VBegin" OpHelp(""),
39579 /* 172 */ "VCreate" OpHelp(""),
39580 /* 173 */ "VDestroy" OpHelp(""),
39581 /* 174 */ "VOpen" OpHelp(""),
39582 /* 175 */ "VCheck" OpHelp(""),
39583 /* 176 */ "VInitIn" OpHelp("r[P2]=ValueList(P1,P3)"),
39584 /* 177 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
39585 /* 178 */ "VRename" OpHelp(""),
39586 /* 179 */ "Pagecount" OpHelp(""),
39587 /* 180 */ "MaxPgcnt" OpHelp(""),
39588 /* 181 */ "ClrSubtype" OpHelp("r[P1].subtype = 0"),
39589 /* 182 */ "GetSubtype" OpHelp("r[P2] = r[P1].subtype"),
39590 /* 183 */ "SetSubtype" OpHelp("r[P2].subtype = r[P1]"),
39591 /* 184 */ "FilterAdd" OpHelp("filter(P1) += key(P3@P4)"),
39592 /* 185 */ "Trace" OpHelp(""),
39593 /* 186 */ "CursorHint" OpHelp(""),
39594 /* 187 */ "ReleaseReg" OpHelp("release r[P1@P2] mask P3"),
39595 /* 188 */ "Noop" OpHelp(""),
39596 /* 189 */ "Explain" OpHelp(""),
39597 /* 190 */ "Abortable" OpHelp(""),
 
 
39598 };
39599 return azName[i];
39600 }
39601 #endif
39602
@@ -41832,11 +41891,11 @@
41832 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
41833 struct vxworksFileId *pNew; /* search key and new file ID */
41834 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
41835 int n; /* Length of zAbsoluteName string */
41836
41837 assert( zAbsoluteName[0]=='/' );
41838 n = (int)strlen(zAbsoluteName);
41839 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
41840 if( pNew==0 ) return 0;
41841 pNew->zCanonicalName = (char*)&pNew[1];
41842 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
@@ -45261,23 +45320,23 @@
45261 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
45262 sqlite3_mutex *pShmMutex; /* Mutex to access this object */
45263 char *zFilename; /* Name of the mmapped file */
45264 int hShm; /* Open file descriptor */
45265 int szRegion; /* Size of shared-memory regions */
45266 u16 nRegion; /* Size of array apRegion */
 
45267 u8 isReadonly; /* True if read-only */
45268 u8 isUnlocked; /* True if no DMS lock held */
 
 
 
45269 char **apRegion; /* Array of mapped shared-memory regions */
45270 int nRef; /* Number of unixShm objects pointing to this */
45271 unixShm *pFirst; /* All unixShm objects pointing to this */
45272 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
45273 sqlite3_mutex *aMutex[SQLITE_SHM_NLOCK];
45274 #endif
45275 int aLock[SQLITE_SHM_NLOCK]; /* # shared locks on slot, -1==excl lock */
45276 #ifdef SQLITE_DEBUG
45277 u8 nextShmId; /* Next available unixShm.id value */
45278 #endif
45279 };
45280
45281 /*
45282 ** Structure used internally by this VFS to record the state of an
45283 ** open shared memory connection.
@@ -46809,14 +46868,18 @@
46809 if( strcmp(pVfs->zName,"unix-excl")==0 ){
46810 pNew->ctrlFlags |= UNIXFILE_EXCL;
46811 }
46812
46813 #if OS_VXWORKS
46814 pNew->pId = vxworksFindFileId(zFilename);
46815 if( pNew->pId==0 ){
46816 ctrlFlags |= UNIXFILE_NOLOCK;
46817 rc = SQLITE_NOMEM_BKPT;
 
 
 
 
46818 }
46819 #endif
46820
46821 if( ctrlFlags & UNIXFILE_NOLOCK ){
46822 pLockingStyle = &nolockIoMethods;
@@ -46917,16 +46980,19 @@
46917 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
46918 char *zSemName = pNew->pInode->aSemName;
46919 int n;
46920 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
46921 pNew->pId->zCanonicalName);
46922 for( n=1; zSemName[n]; n++ )
46923 if( zSemName[n]=='/' ) zSemName[n] = '_';
 
46924 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
46925 if( pNew->pInode->pSem == SEM_FAILED ){
46926 rc = SQLITE_NOMEM_BKPT;
46927 pNew->pInode->aSemName[0] = '\0';
 
 
46928 }
46929 }
46930 unixLeaveMutex();
46931 }
46932 #endif
@@ -61074,15 +61140,22 @@
61074 **
61075 ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
61076 ** file has been created already (via a spill on pagerStress()) and
61077 ** when the number of dirty pages in memory exceeds 25% of the total
61078 ** cache size.
 
 
 
 
 
 
61079 */
61080 static int pagerFlushOnCommit(Pager *pPager, int bCommit){
61081 if( pPager->tempFile==0 ) return 1;
61082 if( !bCommit ) return 0;
61083 if( !isOpen(pPager->fd) ) return 0;
 
61084 return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
61085 }
61086
61087 /*
61088 ** This routine ends a transaction. A transaction is usually ended by
@@ -65750,10 +65823,15 @@
65750 if( rc!=SQLITE_OK ){
65751 sqlite3OsClose(pPager->jfd);
65752 goto commit_phase_one_exit;
65753 }
65754 bBatch = 0;
 
 
 
 
 
65755 }else{
65756 sqlite3OsClose(pPager->jfd);
65757 }
65758 }
65759 #endif /* SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
@@ -78225,32 +78303,38 @@
78225
78226 /*
78227 ** This variant of sqlite3BtreePayload() works even if the cursor has not
78228 ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
78229 ** interface.
 
 
 
 
 
 
78230 */
78231 #ifndef SQLITE_OMIT_INCRBLOB
78232 static SQLITE_NOINLINE int accessPayloadChecked(
78233 BtCursor *pCur,
78234 u32 offset,
78235 u32 amt,
78236 void *pBuf
78237 ){
78238 int rc;
78239 if ( pCur->eState==CURSOR_INVALID ){
78240 return SQLITE_ABORT;
78241 }
78242 assert( cursorOwnsBtShared(pCur) );
78243 rc = btreeRestoreCursorPosition(pCur);
78244 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
 
 
 
 
 
78245 }
78246 SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
78247 if( pCur->eState==CURSOR_VALID ){
78248 assert( cursorOwnsBtShared(pCur) );
78249 return accessPayload(pCur, offset, amt, pBuf, 0);
78250 }else{
78251 return accessPayloadChecked(pCur, offset, amt, pBuf);
78252 }
78253 }
78254 #endif /* SQLITE_OMIT_INCRBLOB */
78255
78256 /*
@@ -79871,14 +79955,12 @@
79871 }
79872 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
79873 pBt = pPage->pBt;
79874 assert( pBt->usableSize > 4 );
79875 ovflPageSize = pBt->usableSize - 4;
79876 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
79877 assert( nOvfl>0 ||
79878 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
79879 );
79880 while( nOvfl-- ){
79881 Pgno iNext = 0;
79882 MemPage *pOvfl = 0;
79883 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
79884 /* 0 is not a legal page number and page 1 cannot be an
@@ -82331,10 +82413,11 @@
82331 if( pCur->eState>=CURSOR_REQUIRESEEK ){
82332 testcase( pCur->eState==CURSOR_REQUIRESEEK );
82333 testcase( pCur->eState==CURSOR_FAULT );
82334 rc = moveToRoot(pCur);
82335 if( rc && rc!=SQLITE_EMPTY ) return rc;
 
82336 }
82337
82338 assert( cursorOwnsBtShared(pCur) );
82339 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
82340 && p->pBt->inTransaction==TRANS_WRITE
@@ -82354,15 +82437,17 @@
82354 ** cursors open on the row being replaced */
82355 if( p->hasIncrblobCur ){
82356 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
82357 }
82358
82359 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
82360 ** to a row with the same key as the new entry being inserted.
 
 
82361 */
82362 #ifdef SQLITE_DEBUG
82363 if( flags & BTREE_SAVEPOSITION ){
82364 assert( pCur->curFlags & BTCF_ValidNKey );
82365 assert( pX->nKey==pCur->info.nKey );
82366 assert( loc==0 );
82367 }
82368 #endif
@@ -86019,11 +86104,15 @@
86019 }
86020 }
86021 assert( j<=n/2 );
86022 zCopy[j] = 0;
86023 rc = sqlite3AtoF(zCopy, pValue);
86024 if( i<n ) rc = -100;
 
 
 
 
86025 sqlite3DbFree(pMem->db, zCopy);
86026 }
86027 return rc;
86028 }
86029 }
@@ -87162,11 +87251,11 @@
87162
87163 if( op==TK_CAST ){
87164 u8 aff;
87165 assert( !ExprHasProperty(pExpr, EP_IntValue) );
87166 aff = sqlite3AffinityType(pExpr->u.zToken,0);
87167 rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
87168 testcase( rc!=SQLITE_OK );
87169 if( *ppVal ){
87170 #ifdef SQLITE_ENABLE_STAT4
87171 rc = ExpandBlob(*ppVal);
87172 #else
@@ -88420,10 +88509,13 @@
88420 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
88421 || opcode==OP_VDestroy
88422 || opcode==OP_VCreate
88423 || opcode==OP_ParseSchema
88424 || opcode==OP_Function || opcode==OP_PureFunc
 
 
 
88425 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
88426 && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
88427 || (opcode==OP_MustBeInt && pOp->p2==0)
88428 ){
88429 hasAbort = 1;
@@ -89992,10 +90084,12 @@
89992 if( eMode==2 ){
89993 Op *pOp = aOp + i;
89994 if( pOp->opcode==OP_OpenRead ) break;
89995 if( pOp->opcode==OP_OpenWrite && (pOp->p5 & OPFLAG_P2ISREG)==0 ) break;
89996 if( pOp->opcode==OP_ReopenIdx ) break;
 
 
89997 }else
89998 #endif
89999 {
90000 assert( eMode==1 );
90001 if( aOp[i].opcode==OP_Explain ) break;
@@ -90846,10 +90940,26 @@
90846 assert( nRead==db->nVdbeRead );
90847 }
90848 #else
90849 #define checkActiveVdbeCnt(x)
90850 #endif
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90851
90852 /*
90853 ** If the Vdbe passed as the first argument opened a statement-transaction,
90854 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
90855 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
@@ -91152,10 +91262,17 @@
91152 ** to invoke any required unlock-notify callbacks.
91153 */
91154 if( db->autoCommit ){
91155 sqlite3ConnectionUnlocked(db);
91156 }
 
 
 
 
 
 
 
91157
91158 assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
91159 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
91160 }
91161
@@ -92919,10 +93036,27 @@
92919 Vdbe *p;
92920 for(p = db->pVdbe; p; p=p->pVNext){
92921 p->expired = iCode+1;
92922 }
92923 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92924
92925 /*
92926 ** Return the database associated with the Vdbe.
92927 */
92928 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
@@ -93512,10 +93646,13 @@
93512 rc = SQLITE_OK;
93513 }else{
93514 Vdbe *v = (Vdbe*)pStmt;
93515 sqlite3 *db = v->db;
93516 if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
 
 
 
93517 sqlite3_mutex_enter(db->mutex);
93518 checkProfileCallback(db, v);
93519 assert( v->eVdbeState>=VDBE_READY_STATE );
93520 rc = sqlite3VdbeReset(v);
93521 sqlite3VdbeDelete(v);
@@ -99426,11 +99563,11 @@
99426 case OP_IfNullRow: { /* jump */
99427 VdbeCursor *pC;
99428 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99429 pC = p->apCsr[pOp->p1];
99430 if( pC && pC->nullRow ){
99431 sqlite3VdbeMemSetNull(aMem + pOp->p3);
99432 goto jump_to_p2;
99433 }
99434 break;
99435 }
99436
@@ -99890,10 +100027,11 @@
99890 Column *aCol;
99891 int i;
99892 int nCol;
99893
99894 assert( pOp->p4type==P4_TABLE );
 
99895 pTab = pOp->p4.pTab;
99896 assert( pTab->tabFlags & TF_Strict );
99897 assert( pOp->p3>=0 && pOp->p3<pTab->nCol+2 );
99898 aCol = pTab->aCol;
99899 pIn1 = &aMem[pOp->p1];
@@ -99942,15 +100080,15 @@
99942 testcase( pIn1->u.i==140737488355327LL );
99943 testcase( pIn1->u.i==-140737488355328LL );
99944 testcase( pIn1->u.i==-140737488355329LL );
99945 if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL){
99946 pIn1->flags |= MEM_IntReal;
99947 pIn1->flags &= ~MEM_Int;
99948 }else{
99949 pIn1->u.r = (double)pIn1->u.i;
99950 pIn1->flags |= MEM_Real;
99951 pIn1->flags &= ~MEM_Int;
99952 }
99953 }else if( (pIn1->flags & (MEM_Real|MEM_IntReal))==0 ){
99954 goto vdbe_type_error;
99955 }
99956 break;
@@ -100089,11 +100227,11 @@
100089 pRec = pData0;
100090 do{
100091 applyAffinity(pRec, zAffinity[0], encoding);
100092 if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){
100093 pRec->flags |= MEM_IntReal;
100094 pRec->flags &= ~(MEM_Int);
100095 }
100096 REGISTER_TRACE((int)(pRec-aMem), pRec);
100097 zAffinity++;
100098 pRec++;
100099 assert( zAffinity[0]==0 || pRec<=pLast );
@@ -100217,17 +100355,17 @@
100217 assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) );
100218 assert( pRec->n>=0 );
100219 len = (u32)pRec->n;
100220 serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);
100221 if( pRec->flags & MEM_Zero ){
100222 serial_type += (u32)pRec->u.nZero*2;
100223 if( nData ){
100224 if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
100225 len += pRec->u.nZero;
100226 }else{
100227 nZero += pRec->u.nZero;
100228 }
 
100229 }
100230 nData += len;
100231 nHdr += sqlite3VarintLen(serial_type);
100232 pRec->uTemp = serial_type;
100233 }
@@ -100789,11 +100927,11 @@
100789 ** v-table would have to be ready for the sqlite3_vtab structure itself
100790 ** to be invalidated whenever sqlite3_step() is called from within
100791 ** a v-table method.
100792 */
100793 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
100794 sqlite3ResetOneSchema(db, pOp->p1);
100795 }
100796 p->expired = 1;
100797 rc = SQLITE_SCHEMA;
100798
100799 /* Set changeCntOn to 0 to prevent the value returned by sqlite3_changes()
@@ -100936,11 +101074,14 @@
100936 /* Opcode: OpenWrite P1 P2 P3 P4 P5
100937 ** Synopsis: root=P2 iDb=P3
100938 **
100939 ** Open a read/write cursor named P1 on the table or index whose root
100940 ** page is P2 (or whose root page is held in register P2 if the
100941 ** OPFLAG_P2ISREG bit is set in P5 - see below).
 
 
 
100942 **
100943 ** The P4 value may be either an integer (P4_INT32) or a pointer to
100944 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
100945 ** object, then table being opened must be an [index b-tree] where the
100946 ** KeyInfo object defines the content and collating
@@ -102122,11 +102263,11 @@
102122 ** integer value of pIn3. Jump to P2 if pIn3 cannot be converted
102123 ** into an integer without loss of information. Take care to avoid
102124 ** changing the datatype of pIn3, however, as it is used by other
102125 ** parts of the prepared statement. */
102126 Mem x = pIn3[0];
102127 if( x.flags & MEM_Str ){
102128 applyNumericAffinity(&x, 1);
102129 }
102130 if( x.flags & MEM_Int ){
102131 iKey = x.u.i;
102132 }else
@@ -102399,10 +102540,11 @@
102399 REGISTER_TRACE(pOp->p3, pKey);
102400 x.nKey = pKey->u.i;
102401
102402 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
102403 assert( pC->iDb>=0 );
 
102404 zDb = db->aDb[pC->iDb].zDbSName;
102405 pTab = pOp->p4.pTab;
102406 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
102407 }else{
102408 pTab = 0;
@@ -102541,10 +102683,11 @@
102541 assert( pC->deferredMoveto==0 );
102542 sqlite3VdbeIncrWriteCounter(p, pC);
102543
102544 #ifdef SQLITE_DEBUG
102545 if( pOp->p4type==P4_TABLE
 
102546 && HasRowid(pOp->p4.pTab)
102547 && pOp->p5==0
102548 && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
102549 ){
102550 /* If p5 is zero, the seek operation that positioned the cursor prior to
@@ -102559,10 +102702,11 @@
102559 ** the name of the db to pass as to it. Also set local pTab to a copy
102560 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
102561 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
102562 ** VdbeCursor.movetoTarget to the current rowid. */
102563 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
 
102564 assert( pC->iDb>=0 );
102565 assert( pOp->p4.pTab!=0 );
102566 zDb = db->aDb[pC->iDb].zDbSName;
102567 pTab = pOp->p4.pTab;
102568 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
@@ -102815,10 +102959,26 @@
102815 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
102816 }
102817 pOut->u.i = v;
102818 break;
102819 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102820
102821 /* Opcode: NullRow P1 P2 * * *
102822 **
102823 ** Move the cursor P1 to a null row if P2 is 0. Any OP_Column operations
102824 ** that occur while the cursor is on the null row will always
@@ -102830,10 +102990,11 @@
102830 ** If P2 is not 0, then the nullRow flag on the pseudo-cursor is
102831 ** turned off.
102832 */
102833 case OP_NullRow: {
102834 VdbeCursor *pC;
 
102835
102836 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
102837 pC = p->apCsr[pOp->p1];
102838 if( pC==0 ){
102839 /* If the cursor is not already open, create a special kind of
@@ -102848,10 +103009,18 @@
102848 pC->nullRow = (pOp->p2==0);
102849 pC->cacheStatus = CACHE_STALE;
102850 if( pC->eCurType==CURTYPE_BTREE ){
102851 assert( pC->uc.pCursor!=0 );
102852 sqlite3BtreeClearCursor(pC->uc.pCursor);
 
 
 
 
 
 
 
 
102853 }
102854 #ifdef SQLITE_DEBUG
102855 if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
102856 #endif
102857 break;
@@ -103288,10 +103457,11 @@
103288 r.default_rc = 0;
103289 r.aMem = &aMem[pOp->p2];
103290 rc = sqlite3BtreeIndexMoveto(pCrsr, &r, &res);
103291 if( rc ) goto abort_due_to_error;
103292 if( res!=0 ){
 
103293 rc = sqlite3VdbeFindIndexKey(pCrsr, pOp->p4.pIdx, &r, &res, 0);
103294 if( rc!=SQLITE_OK ) goto abort_due_to_error;
103295 if( res!=0 ){
103296 if( !sqlite3WritableSchema(db) ){
103297 rc = sqlite3ReportError(
@@ -103601,10 +103771,25 @@
103601 }
103602 #endif
103603 }
103604 break;
103605 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103606
103607 /* Opcode: Clear P1 P2 P3
103608 **
103609 ** Delete all contents of the database table or index whose root page
103610 ** in the database file is given by P1. But, unlike Destroy, do not
@@ -103784,13 +103969,17 @@
103784 assert( iDb>=0 && iDb<db->nDb );
103785 assert( DbHasProperty(db, iDb, DB_SchemaLoaded)
103786 || db->mallocFailed
103787 || (CORRUPT_DB && (db->flags & SQLITE_NoSchemaError)!=0) );
103788
 
 
 
103789 #ifndef SQLITE_OMIT_ALTERTABLE
103790 if( pOp->p4.z==0 ){
103791 assert( pOp->p5!=0 );
 
103792 sqlite3SchemaClear(db->aDb[iDb].pSchema);
103793 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
103794 rc = sqlite3InitOne(db, iDb, &p->zErrMsg, pOp->p5);
103795 db->mDbFlags |= DBFLAG_SchemaChange;
103796 p->expired = 0;
@@ -103827,10 +104016,11 @@
103827 db->init.busy = 0;
103828 }
103829 }
103830 if( rc ){
103831 sqlite3ResetAllSchemasOfConnection(db);
 
103832 if( rc==SQLITE_NOMEM ){
103833 goto no_mem;
103834 }
103835 goto abort_due_to_error;
103836 }
@@ -103985,10 +104175,11 @@
103985 assert( pOp[-1].opcode==OP_Found );
103986 assert( pOp[-1].p1==pOp->p1 );
103987 assert( pOp[-1].p3==pOp->p3 );
103988 pC = p->apCsr[pOp->p1];
103989 assert( pOp->p4type==P4_INDEX );
 
103990 assert( pC->eCurType==CURTYPE_BTREE );
103991 assert( pC->uc.pCursor!=0 );
103992 assert( pC->isTable==0 );
103993
103994 memset(&r, 0, sizeof(r));
@@ -105984,11 +106175,11 @@
105984 if( rc==SQLITE_CORRUPT && db->autoCommit==0 ){
105985 db->flags |= SQLITE_CorruptRdOnly;
105986 }
105987 rc = SQLITE_ERROR;
105988 if( resetSchemaOnFault>0 ){
105989 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
105990 }
105991
105992 /* This is the only way out of this procedure. We have to
105993 ** release the mutexes on btrees that were acquired at the
105994 ** top. */
@@ -106045,10 +106236,14 @@
106045 */
106046 abort_due_to_interrupt:
106047 assert( AtomicLoad(&db->u1.isInterrupted) );
106048 rc = SQLITE_INTERRUPT;
106049 goto abort_due_to_error;
 
 
 
 
106050 }
106051
106052
106053 /************** End of vdbe.c ************************************************/
106054 /************** Begin file vdbeblob.c ****************************************/
@@ -106078,10 +106273,11 @@
106078 typedef struct Incrblob Incrblob;
106079 struct Incrblob {
106080 int nByte; /* Size of open blob, in bytes */
106081 int iOffset; /* Byte offset of blob in cursor data */
106082 u16 iCol; /* Table column this handle is open on */
 
106083 BtCursor *pCsr; /* Cursor pointing at blob row */
106084 sqlite3_stmt *pStmt; /* Statement holding cursor open */
106085 sqlite3 *db; /* The associated database */
106086 char *zDb; /* Database name */
106087 Table *pTab; /* Table object */
@@ -106426,10 +106622,71 @@
106426 }else{
106427 rc = SQLITE_OK;
106428 }
106429 return rc;
106430 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106431
106432 /*
106433 ** Perform a read or write operation on a blob
106434 */
106435 static int blobReadWrite(
@@ -106504,15 +106761,25 @@
106504 #else
106505 rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
106506 #endif
106507
106508 sqlite3BtreeLeaveCursor(p->pCsr);
106509 if( rc==SQLITE_ABORT ){
106510 sqlite3VdbeFinalize(v);
106511 p->pStmt = 0;
106512 }else{
106513 v->rc = rc;
 
 
 
 
 
 
 
 
 
 
 
106514 }
106515 }
106516 sqlite3Error(db, rc);
106517 rc = sqlite3ApiExit(db, rc);
106518 sqlite3_mutex_leave(db->mutex);
@@ -109749,12 +110016,28 @@
109749 i = 8;
109750 }else{
109751 if( i<=2 && pCur->zType==0 ){
109752 Schema *pSchema;
109753 HashElem *k;
109754 int iDb = pOp->p3;
109755 Pgno iRoot = (Pgno)pOp->p2;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109756 sqlite3 *db = pVTab->db;
109757 pSchema = db->aDb[iDb].pSchema;
109758 pCur->zSchema = db->aDb[iDb].zDbSName;
109759 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
109760 Table *pTab = (Table*)sqliteHashData(k);
@@ -109847,11 +110130,14 @@
109847 break;
109848 case 22: /* tables_used.name */
109849 sqlite3_result_text(ctx, pCur->zName, -1, SQLITE_STATIC);
109850 break;
109851 case 23: /* tables_used.wr */
109852 sqlite3_result_int(ctx, pOp->opcode==OP_OpenWrite);
 
 
 
109853 break;
109854 }
109855 return SQLITE_OK;
109856 }
109857
@@ -110690,10 +110976,23 @@
110690 */
110691 SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
110692 UNUSED_PARAMETER2(NotUsed, NotUsed2);
110693 return WRC_Continue;
110694 }
 
 
 
 
 
 
 
 
 
 
 
 
 
110695
110696 /************** End of walker.c **********************************************/
110697 /************** Begin file resolve.c *****************************************/
110698 /*
110699 ** 2008 August 18
@@ -111157,12 +111456,19 @@
111157 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
111158 }
111159 }
111160 cnt++;
111161 pMatch = pItem;
111162 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
111163 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
 
 
 
 
 
 
 
111164 if( pItem->fg.isNestedFrom ){
111165 sqlite3SrcItemColumnUsed(pItem, j);
111166 }
111167 }
111168 if( 0==cnt && VisibleRowid(pTab) ){
@@ -111257,11 +111563,11 @@
111257 int iCol;
111258 pSchema = pTab->pSchema;
111259 cntTab++;
111260 iCol = sqlite3ColumnIndex(pTab, zCol);
111261 if( iCol>=0 ){
111262 if( pTab->iPKey==iCol ) iCol = -1;
111263 }else{
111264 if( sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
111265 iCol = -1;
111266 }else{
111267 iCol = pTab->nCol;
@@ -111672,10 +111978,14 @@
111672 break;
111673 }
111674 if( pExpr->op==TK_UPLUS ){
111675 pExpr = pExpr->pLeft;
111676 assert( pExpr!=0 );
 
 
 
 
111677 }else{
111678 break;
111679 }
111680 }
111681 }
@@ -112300,10 +112610,33 @@
112300 }
112301
112302 /* If no match, return 0. */
112303 return 0;
112304 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112305
112306 /*
112307 ** Generate an ORDER BY or GROUP BY term out-of-range error.
112308 */
112309 static void resolveOutOfRangeError(
@@ -112375,11 +112708,13 @@
112375 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE);
112376 return 1;
112377 }
112378 }else{
112379 iCol = resolveAsName(pParse, pEList, pE);
112380 if( iCol==0 ){
 
 
112381 /* Now test if expression pE matches one of the values returned
112382 ** by pSelect. In the usual case this is done by duplicating the
112383 ** expression, resolving any symbols in it, and then comparing
112384 ** it against each expression returned by the SELECT statement.
112385 ** Once the comparisons are finished, the duplicate expression
@@ -112543,10 +112878,11 @@
112543 Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);
112544 if( NEVER(pE2==0) ) continue;
112545 if( zType[0]!='G' ){
112546 iCol = resolveAsName(pParse, pSelect->pEList, pE2);
112547 if( iCol>0 ){
 
112548 /* If an AS-name match is found, mark this ORDER BY column as being
112549 ** a copy of the iCol-th result-set column. The subsequent call to
112550 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
112551 ** copy of the iCol-th result-set expression. */
112552 pItem->u.x.iOrderByCol = (u16)iCol;
@@ -113141,15 +113477,20 @@
113141 assert( pExpr->iTable==pExpr->pLeft->x.pSelect->pEList->nExpr );
113142 return sqlite3ExprAffinity(
113143 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
113144 );
113145 }
113146 if( op==TK_VECTOR
113147 || (op==TK_FUNCTION && pExpr->affExpr==SQLITE_AFF_DEFER)
113148 ){
113149 assert( ExprUseXList(pExpr) );
113150 return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
 
 
 
 
 
 
 
113151 }
113152 if( ExprHasProperty(pExpr, EP_Skip|EP_IfNullRow) ){
113153 assert( pExpr->op==TK_COLLATE
113154 || pExpr->op==TK_IF_NULL_ROW
113155 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) );
@@ -114665,12 +115006,12 @@
114665 **
114666 ** The return value includes space to duplicate all Expr nodes in the
114667 ** tree formed by Expr.pLeft and Expr.pRight, but not any other
114668 ** substructure such as Expr.x.pList, Expr.x.pSelect, and Expr.y.pWin.
114669 */
114670 static int dupedExprSize(const Expr *p){
114671 int nByte;
114672 assert( p!=0 );
114673 nByte = dupedExprNodeSize(p, EXPRDUP_REDUCE);
114674 if( p->pLeft ) nByte += dupedExprSize(p->pLeft);
114675 if( p->pRight ) nByte += dupedExprSize(p->pRight);
114676 assert( nByte==ROUND8(nByte) );
@@ -114723,11 +115064,11 @@
114723 #endif
114724 staticFlag = EP_Static;
114725 assert( sEdupBuf.zAlloc!=0 );
114726 assert( dupFlags==EXPRDUP_REDUCE );
114727 }else{
114728 int nAlloc;
114729 if( dupFlags ){
114730 nAlloc = dupedExprSize(p);
114731 }else if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
114732 nToken = sqlite3Strlen30NN(p->u.zToken)+1;
114733 nAlloc = ROUND8(EXPR_FULLSIZE + nToken);
@@ -115392,23 +115733,10 @@
115392 m |= pExpr->flags;
115393 }
115394 return m;
115395 }
115396
115397 /*
115398 ** This is a SELECT-node callback for the expression walker that
115399 ** always "fails". By "fail" in this case, we mean set
115400 ** pWalker->eCode to zero and abort.
115401 **
115402 ** This callback is used by multiple expression walkers.
115403 */
115404 SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
115405 UNUSED_PARAMETER(NotUsed);
115406 pWalker->eCode = 0;
115407 return WRC_Abort;
115408 }
115409
115410 /*
115411 ** Check the input string to see if it is "true" or "false" (in any case).
115412 **
115413 ** If the string is.... Return
115414 ** "true" EP_IsTrue
@@ -115702,10 +116030,22 @@
115702 case TK_IS:
115703 case TK_ISNOT:
115704 if( pWalker->eCode==6 ){
115705 pWalker->eCode = 0;
115706 return WRC_Abort;
 
 
 
 
 
 
 
 
 
 
 
 
115707 }
115708 return WRC_Continue;
115709 case TK_VARIABLE:
115710 if( pWalker->eCode==5 ){
115711 /* Silently convert bound parameters that appear inside of CREATE
@@ -115907,35 +116247,157 @@
115907 }
115908 /* Rules (1), (2a), and (2b) handled by the following: */
115909 return sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor, bAllowSubq);
115910 }
115911
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115912
115913 /*
115914 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
115915 */
115916 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
115917 ExprList *pGroupBy = pWalker->u.pGroupBy;
115918 int i;
115919
115920 /* Check if pExpr is identical to any GROUP BY term. If so, consider
115921 ** it constant. */
115922 for(i=0; i<pGroupBy->nExpr; i++){
115923 Expr *p = pGroupBy->a[i].pExpr;
115924 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
115925 CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
115926 if( sqlite3IsBinary(pColl) ){
115927 return WRC_Prune;
115928 }
115929 }
115930 }
115931
115932 /* Check if pExpr is a sub-select. If so, consider it variable. */
115933 if( ExprUseXSelect(pExpr) ){
115934 pWalker->eCode = 0;
115935 return WRC_Abort;
115936 }
 
 
 
 
 
 
 
115937
115938 return exprNodeIsConstant(pWalker, pExpr);
115939 }
115940
115941 /*
@@ -115944,20 +116406,29 @@
115944 ** in pGroupBy that sort with the BINARY collation sequence.
115945 **
115946 ** This routine is used to determine if a term of the HAVING clause can
115947 ** be promoted into the WHERE clause. In order for such a promotion to work,
115948 ** the value of the HAVING clause term must be the same for all members of
115949 ** a "group". The requirement that the GROUP BY term must be BINARY
115950 ** assumes that no other collating sequence will have a finer-grained
115951 ** grouping than binary. In other words (A=B COLLATE binary) implies
115952 ** A=B in every other collating sequence. The requirement that the
115953 ** GROUP BY be BINARY is stricter than necessary. It would also work
115954 ** to promote HAVING clauses that use the same alternative collating
115955 ** sequence as the GROUP BY term, but that is much harder to check,
115956 ** alternative collating sequences are uncommon, and this is only an
115957 ** optimization, so we take the easy way out and simply require the
115958 ** GROUP BY to use the BINARY collating sequence.
 
 
 
 
 
 
 
 
 
115959 */
115960 SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
115961 Walker w;
115962 w.eCode = 1;
115963 w.xExprCallback = exprNodeIsConstantOrGroupBy;
@@ -116617,10 +117088,15 @@
116617 #ifndef SQLITE_OMIT_SUBQUERY
116618 /*
116619 ** Argument pExpr is an (?, ?...) IN(...) expression. This
116620 ** function allocates and returns a nul-terminated string containing
116621 ** the affinities to be used for each column of the comparison.
 
 
 
 
 
116622 **
116623 ** It is the responsibility of the caller to ensure that the returned
116624 ** string is eventually freed using sqlite3DbFree().
116625 */
116626 static char *exprINAffinity(Parse *pParse, const Expr *pExpr){
@@ -116639,10 +117115,11 @@
116639 if( pSelect ){
116640 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
116641 }else{
116642 zRet[i] = a;
116643 }
 
116644 }
116645 zRet[nVal] = '\0';
116646 }
116647 return zRet;
116648 }
@@ -117115,11 +117592,11 @@
117115 }
117116 sqlite3ExprDeferredDelete(pParse, pLeft);
117117 pSel->pLimit->pLeft = pLimit;
117118 }
117119 }else{
117120 /* If there is no pre-existing limit add a limit of 1 */
117121 pLimit = sqlite3ExprInt32(pParse->db, 1);
117122 pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
117123 }
117124 pSel->iLimit = 0;
117125 if( sqlite3Select(pParse, pSel, &dest) ){
@@ -117435,13 +117912,14 @@
117435 **
117436 ** For a scalar LHS, it is sufficient to check just the first row
117437 ** of the RHS.
117438 */
117439 if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
117440 if( eType==IN_INDEX_INDEX_DESC ){
117441 addrTop = sqlite3VdbeAddOp2(v, OP_Last, iTab, destIfFalse);
117442 }else{
 
117443 testcase( eType==IN_INDEX_EPH );
117444 testcase( eType==IN_INDEX_ROWID );
117445 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
117446 }
117447 VdbeCoverage(v);
@@ -117953,10 +118431,34 @@
117953 w.xExprCallback = exprNodeCanReturnSubtype;
117954 sqlite3WalkExpr(&w, pExpr);
117955 return w.eCode;
117956 }
117957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117958
117959 /*
117960 ** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr.
117961 ** If it is, then resolve the expression by reading from the index and
117962 ** return the register into which the value has been read. If pExpr is
@@ -117967,29 +118469,19 @@
117967 Expr *pExpr, /* The expression to potentially bypass */
117968 int target /* Where to store the result of the expression */
117969 ){
117970 IndexedExpr *p;
117971 Vdbe *v;
 
117972 for(p=pParse->pIdxEpr; p; p=p->pIENext){
117973 u8 exprAff;
117974 int iDataCur = p->iDataCur;
117975 if( iDataCur<0 ) continue;
117976 if( pParse->iSelfTab ){
117977 if( p->iDataCur!=pParse->iSelfTab-1 ) continue;
117978 iDataCur = -1;
117979 }
117980 if( sqlite3ExprCompare(0, pExpr, p->pExpr, iDataCur)!=0 ) continue;
117981 assert( p->aff>=SQLITE_AFF_BLOB && p->aff<=SQLITE_AFF_NUMERIC );
117982 exprAff = sqlite3ExprAffinity(pExpr);
117983 if( (exprAff<=SQLITE_AFF_BLOB && p->aff!=SQLITE_AFF_BLOB)
117984 || (exprAff==SQLITE_AFF_TEXT && p->aff!=SQLITE_AFF_TEXT)
117985 || (exprAff>=SQLITE_AFF_NUMERIC && p->aff!=SQLITE_AFF_NUMERIC)
117986 ){
117987 /* Affinity mismatch on a generated column */
117988 continue;
117989 }
117990
117991
117992 /* Functions that might set a subtype should not be replaced by the
117993 ** value taken from an expression index if they are themselves an
117994 ** argument to another scalar function or aggregate.
117995 ** https://sqlite.org/forum/forumpost/68d284c86b082c3e */
@@ -117996,23 +118488,24 @@
117996 if( ExprHasProperty(pExpr, EP_SubtArg)
117997 && sqlite3ExprCanReturnSubtype(pParse, pExpr)
117998 ){
117999 continue;
118000 }
 
 
 
 
 
 
 
118001
118002 v = pParse->pVdbe;
118003 assert( v!=0 );
118004 if( p->bMaybeNullRow || sqlite3ExprIsConstant(pParse, pExpr) ){
118005 /* The value of pExpr should be computed from the original expression,
118006 ** not from the index, if either:
118007 **
118008 ** 1. The index might be on a NULL row due to an outer join.
118009 **
118010 ** 2. The expression is a constant. This prevents an attempt to
118011 ** use an index value outside of the loop that positions the
118012 ** index. (Bug 2026-10-11T19:26:40Z).
118013 */
118014 int addr = sqlite3VdbeCurrentAddr(v);
118015 sqlite3VdbeAddOp3(v, OP_IfNullRow, p->iIdxCur, addr+3, target);
118016 VdbeCoverage(v);
118017 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
118018 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
@@ -118047,13 +118540,17 @@
118047 for(p=pParse->pIdxPartExpr; p; p=p->pIENext){
118048 if( pExpr->iColumn==p->iIdxCol && pExpr->iTable==p->iDataCur ){
118049 Vdbe *v = pParse->pVdbe;
118050 int addr = 0;
118051 int ret;
 
118052
118053 if( p->bMaybeNullRow ){
 
 
118054 addr = sqlite3VdbeAddOp1(v, OP_IfNullRow, p->iIdxCur);
 
118055 }
118056 ret = sqlite3ExprCodeTarget(pParse, p->pExpr, iTarget);
118057 sqlite3VdbeAddOp4(pParse->pVdbe, OP_Affinity, ret, 1, 0,
118058 (const char*)&p->aff, 1);
118059 if( sqlite3ExprCanReturnSubtype(pParse, p->pExpr) ){
@@ -118060,10 +118557,11 @@
118060 /* If the expression value may have a sub-type, clear it. Values
118061 ** read from columns do not have subtypes. */
118062 sqlite3VdbeAddOp1(pParse->pVdbe, OP_ClrSubtype, ret);
118063 }
118064 if( addr ){
 
118065 sqlite3VdbeJumpHere(v, addr);
118066 sqlite3VdbeChangeP3(v, addr, ret);
118067 }
118068 return ret;
118069 }
@@ -118187,11 +118685,11 @@
118187 case TK_AGG_COLUMN: {
118188 AggInfo *pAggInfo = pExpr->pAggInfo;
118189 struct AggInfo_col *pCol;
118190 assert( pAggInfo!=0 );
118191 assert( pExpr->iAgg>=0 );
118192 if( pExpr->iAgg>=pAggInfo->nColumn ){
118193 /* Happens when the left table of a RIGHT JOIN is null and
118194 ** is using an expression index */
118195 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
118196 #ifdef SQLITE_VDBE_COVERAGE
118197 /* Verify that the OP_Null above is exercised by tests
@@ -118963,11 +119461,11 @@
118963 assert( pExpr->affExpr==OE_Rollback
118964 || pExpr->affExpr==OE_Abort
118965 || pExpr->affExpr==OE_Fail
118966 || pExpr->affExpr==OE_Ignore
118967 );
118968 if( !pParse->pTriggerTab && !pParse->nested ){
118969 sqlite3ErrorMsg(pParse,
118970 "RAISE() may only be used within a trigger-program");
118971 return 0;
118972 }
118973 if( pExpr->affExpr==OE_Abort ){
@@ -118977,12 +119475,11 @@
118977 if( pExpr->affExpr==OE_Ignore ){
118978 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, OE_Ignore);
118979 VdbeCoverage(v);
118980 }else{
118981 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
118982 sqlite3VdbeAddOp3(v, OP_Halt,
118983 pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
118984 pExpr->affExpr, r1);
118985 }
118986 break;
118987 }
118988 #endif
@@ -119736,14 +120233,22 @@
119736 if( pR ){
119737 iVar = pVar->iColumn;
119738 sqlite3VdbeReprepareOnBind(pParse->pVdbe, iVar, 0);
119739 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
119740 if( pL ){
 
119741 if( sqlite3_value_type(pL)==SQLITE_TEXT ){
119742 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
119743 }
119744 res = sqlite3MemCompare(pL, pR, 0) ? 2 : 0;
 
 
 
 
 
 
 
119745 }
119746 sqlite3ValueFree(pR);
119747 sqlite3ValueFree(pL);
119748 }
119749 return res;
@@ -120629,14 +121134,24 @@
120629 IndexedExpr *pIEpr;
120630 Expr tmp;
120631 assert( pParse->iSelfTab==0 );
120632 if( (pNC->ncFlags & NC_InAggFunc)==0 ) break;
120633 if( pParse->pIdxEpr==0 ) break;
 
 
 
120634 for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
120635 int iDataCur = pIEpr->iDataCur;
120636 if( iDataCur<0 ) continue;
120637 if( sqlite3ExprCompare(0, pExpr, pIEpr->pExpr, iDataCur)==0 ) break;
 
 
 
 
 
 
 
120638 }
120639 if( pIEpr==0 ) break;
120640 if( NEVER(!ExprUseYTab(pExpr)) ) break;
120641 for(i=0; i<pSrcList->nSrc; i++){
120642 if( pSrcList->a[i].iCursor==pIEpr->iDataCur ){
@@ -120644,10 +121159,15 @@
120644 break;
120645 }
120646 }
120647 if( i>=pSrcList->nSrc ) break;
120648 if( NEVER(pExpr->pAggInfo!=0) ) break; /* Resolved by outer context */
 
 
 
 
 
120649 if( pParse->nErr ){ return WRC_Abort; }
120650
120651 /* If we reach this point, it means that expression pExpr can be
120652 ** translated into a reference to an index column as described by
120653 ** pIEpr.
@@ -121112,11 +121632,11 @@
121112 ** that the table is being renamed to.
121113 */
121114 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
121115 goto exit_rename_table;
121116 }
121117 if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){
121118 goto exit_rename_table;
121119 }
121120
121121 #ifndef SQLITE_OMIT_VIEW
121122 if( IsView(pTab) ){
@@ -121157,35 +121677,35 @@
121157 /* figure out how many UTF-8 characters are in zName */
121158 zTabName = pTab->zName;
121159 nTabName = sqlite3Utf8CharLen(zTabName, -1);
121160
121161 /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
121162 ** the schema to use the new table name. */
 
121163 sqlite3NestedParse(pParse,
121164 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
121165 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
121166 "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
121167 "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
121168 , zDb, zDb, zTabName, zName, (iDb==1), zTabName
121169 );
121170
121171 /* Update the tbl_name and name columns of the sqlite_schema table
121172 ** as required. */
121173 sqlite3NestedParse(pParse,
121174 "UPDATE %Q." LEGACY_SCHEMA_TABLE " SET "
121175 "tbl_name = %Q, "
121176 "name = CASE "
121177 "WHEN type='table' THEN %Q "
121178 "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
121179 " AND type='index' THEN "
121180 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
121181 "ELSE name END "
121182 "WHERE tbl_name=%Q COLLATE nocase AND "
121183 "(type='table' OR type='index' OR type='trigger');",
121184 zDb,
121185 zName, zName, zName,
121186 nTabName, zTabName
121187 );
121188
121189 #ifndef SQLITE_OMIT_AUTOINCREMENT
121190 /* If the sqlite_sequence table exists in this database, then update
121191 ** it with the new table name.
@@ -121242,11 +121762,11 @@
121242 const char *zDb, /* Schema holding the table */
121243 const char *zTab, /* Table to check for empty */
121244 const char *zErr /* Error message text */
121245 ){
121246 sqlite3NestedParse(pParse,
121247 "SELECT raise(ABORT,%Q) FROM \"%w\".\"%w\"",
121248 zErr, zDb, zTab
121249 );
121250 }
121251
121252 /*
@@ -121270,10 +121790,55 @@
121270 }
121271 return SQLITE_OK;
121272 }
121273
121274
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121275
121276 /*
121277 ** This function is called after an "ALTER TABLE ... ADD" statement
121278 ** has been parsed. Argument pColDef contains the text of the new
121279 ** column definition.
@@ -121286,10 +121851,11 @@
121286 Table *pTab; /* Table being altered */
121287 int iDb; /* Database number */
121288 const char *zDb; /* Database name */
121289 const char *zTab; /* Table name */
121290 char *zCol; /* Null-terminated column definition */
 
121291 Column *pCol; /* The new column */
121292 Expr *pDflt; /* Default value for the new column */
121293 sqlite3 *db; /* The database connection; */
121294 Vdbe *v; /* The prepared statement under construction */
121295 int r1; /* Temporary registers */
@@ -121331,32 +121897,16 @@
121331 "Cannot add a UNIQUE column");
121332 return;
121333 }
121334 if( isRowidAlias(pParse, pTab, pCol->zCnName, "add") ) return;
121335 if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
121336 /* If the default value for the new column was specified with a
121337 ** literal NULL, then set pDflt to 0. This simplifies checking
121338 ** for an SQL NULL default below.
121339 */
121340 assert( pDflt==0 || pDflt->op==TK_SPAN );
121341 if( pDflt && pDflt->pLeft->op==TK_NULL ){
121342 pDflt = 0;
121343 }
121344 assert( IsOrdinaryTable(pNew) );
121345 if( (db->flags&SQLITE_ForeignKeys) && pNew->u.tab.pFKey && pDflt ){
121346 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
121347 "Cannot add a REFERENCES column with non-NULL default value");
121348 }
121349 if( pCol->notNull && !pDflt ){
121350 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
121351 "Cannot add a NOT NULL column with default value NULL");
121352 }
121353
121354
121355 /* Ensure the default expression is something that sqlite3ValueFromExpr()
121356 ** can handle (i.e. not CURRENT_TIME etc.)
121357 */
121358 if( pDflt ){
121359 sqlite3_value *pVal = 0;
121360 int rc;
121361 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
121362 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
@@ -121365,25 +121915,35 @@
121365 return;
121366 }
121367 if( !pVal ){
121368 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
121369 "Cannot add a column with non-constant default");
 
 
121370 }
121371 sqlite3ValueFree(pVal);
121372 }
 
 
 
 
 
 
 
 
 
 
 
121373 }else if( pCol->colFlags & COLFLAG_STORED ){
121374 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column");
121375 }
121376
121377
121378 /* Modify the CREATE TABLE statement. */
121379 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
 
121380 if( zCol ){
121381 char *zEnd = &zCol[pColDef->n-1];
121382 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
121383 *zEnd-- = '\0';
121384 }
121385 /* substr() operations on characters, but addColOffset is in bytes. So we
121386 ** have to use printf() to translate between these units: */
121387 assert( IsOrdinaryTable(pTab) );
121388 assert( IsOrdinaryTable(pNew) );
121389 sqlite3NestedParse(pParse,
@@ -121397,10 +121957,13 @@
121397 sqlite3DbFree(db, zCol);
121398 }
121399
121400 v = sqlite3GetVdbe(pParse);
121401 if( v ){
 
 
 
121402 /* Make sure the schema version is at least 3. But do not upgrade
121403 ** from less than 3 to 4, as that will corrupt any preexisting DESC
121404 ** index.
121405 */
121406 r1 = sqlite3GetTempReg(pParse);
@@ -121413,28 +121976,46 @@
121413 sqlite3ReleaseTempReg(pParse, r1);
121414
121415 /* Reload the table definition */
121416 renameReloadSchema(pParse, iDb, INITFLAG_AlterAdd);
121417
121418 /* Verify that constraints are still satisfied */
 
 
 
 
 
 
 
121419 if( pNew->pCheck!=0
121420 || (pCol->notNull && (pCol->colFlags & COLFLAG_GENERATED)!=0)
121421 || (pTab->tabFlags & TF_Strict)!=0
121422 ){
121423 pParse->colNamesSet = 1;
121424 sqlite3NestedParse(pParse,
121425 "SELECT CASE WHEN quick_check GLOB 'CHECK*'"
121426 " THEN raise(ABORT,'CHECK constraint failed')"
121427 " WHEN quick_check GLOB 'non-* value in*'"
121428 " THEN raise(ABORT,'type mismatch on DEFAULT')"
121429 " ELSE raise(ABORT,'NOT NULL constraint failed')"
121430 " END"
121431 " FROM pragma_quick_check(%Q,%Q)"
121432 " WHERE quick_check GLOB 'CHECK*'"
121433 " OR quick_check GLOB 'NULL*'"
121434 " OR quick_check GLOB 'non-* value in*'",
121435 zTab, zDb
 
 
 
 
 
 
 
 
 
 
 
121436 );
121437 }
121438 }
121439 }
121440
@@ -122348,10 +122929,11 @@
122348 SrcList *pSrc = sqlite3SrcListDup(db, pStep->pSrc, 0);
122349 if( pSrc ){
122350 Select *pSel = sqlite3SelectNew(
122351 pParse, pStep->pExprList, pSrc, 0, 0, 0, 0, 0, 0
122352 );
 
122353 if( pSel==0 ){
122354 pStep->pExprList = 0;
122355 pSrc = 0;
122356 rc = SQLITE_NOMEM;
122357 }else{
@@ -122371,34 +122953,39 @@
122371 assert( pSrc==pSel->pSrc );
122372 if( pStep->pExprList ) pSel->pEList = 0;
122373 pSel->pSrc = 0;
122374 sqlite3SelectDelete(db, pSel);
122375 }
 
 
122376 if( ALWAYS(pStep->pSrc) ){
122377 int i;
122378 for(i=0; i<pStep->pSrc->nSrc && rc==SQLITE_OK; i++){
122379 SrcItem *p = &pStep->pSrc->a[i];
122380 if( p->fg.isSubquery ){
122381 assert( p->u4.pSubq!=0 );
122382 sqlite3SelectPrep(pParse, p->u4.pSubq->pSelect, 0);
122383 }
 
 
 
122384 }
122385 }
122386
122387 if( db->mallocFailed ){
122388 rc = SQLITE_NOMEM;
122389 }
122390 sNC.pSrcList = pSrc;
122391 if( rc==SQLITE_OK && pStep->pWhere ){
122392 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
122393 }
122394 if( rc==SQLITE_OK ){
122395 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
122396 }
122397 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
122398 if( pStep->pUpsert && rc==SQLITE_OK ){
122399 Upsert *pUpsert = pStep->pUpsert;
 
 
122400 pUpsert->pUpsertSrc = pSrc;
122401 sNC.uNC.pUpsert = pUpsert;
122402 sNC.ncFlags = NC_UUpsert;
122403 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
122404 if( rc==SQLITE_OK ){
@@ -122433,27 +123020,31 @@
122433 /* Find tokens to edit in WHEN clause */
122434 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
122435
122436 /* Find tokens to edit in trigger steps */
122437 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
 
122438 sqlite3WalkSelect(pWalker, pStep->pSelect);
122439 sqlite3WalkExpr(pWalker, pStep->pWhere);
122440 sqlite3WalkExprList(pWalker, pStep->pExprList);
122441 if( pStep->pUpsert ){
122442 Upsert *pUpsert = pStep->pUpsert;
122443 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
122444 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
122445 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
122446 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
122447 }
122448 if( pStep->pSrc ){
122449 int i;
122450 SrcList *pSrc = pStep->pSrc;
122451 for(i=0; i<pSrc->nSrc; i++){
122452 if( pSrc->a[i].fg.isSubquery ){
122453 assert( pSrc->a[i].u4.pSubq!=0 );
122454 sqlite3WalkSelect(pWalker, pSrc->a[i].u4.pSubq->pSelect);
 
 
 
 
122455 }
122456 }
122457 }
122458 }
122459 }
@@ -122539,11 +123130,11 @@
122539 sqlite3BtreeLeaveAll(db);
122540 return;
122541 }
122542 zOld = pTab->aCol[iCol].zCnName;
122543 memset(&sCtx, 0, sizeof(sCtx));
122544 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
122545
122546 #ifndef SQLITE_OMIT_AUTHORIZATION
122547 db->xAuth = 0;
122548 #endif
122549 rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
@@ -122577,11 +123168,11 @@
122577 if( iCol<sParse.pNewTable->nCol ){
122578 renameTokenFind(
122579 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zCnName
122580 );
122581 }
122582 if( sCtx.iCol<0 ){
122583 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
122584 }
122585 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
122586 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
122587 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
@@ -122623,13 +123214,13 @@
122623
122624 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
122625 if( pStep->pSrc ){
122626 Table *pTarget = sqlite3LocateTableItem(&sParse, 0, &pStep->pSrc->a[0]);
122627 if( pTarget==pTab ){
122628 if( pStep->pUpsert ){
122629 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
122630 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
122631 }
122632 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
122633 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
122634 }
122635 }
@@ -122705,10 +123296,30 @@
122705 renameWalkWith(pWalker, pSelect);
122706
122707 return WRC_Continue;
122708 }
122709
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122710
122711 /*
122712 ** This C function implements an SQL user function that is used by SQL code
122713 ** generated by the ALTER TABLE ... RENAME command to modify the definition
122714 ** of any foreign key constraints that use the table being renamed as the
@@ -122824,12 +123435,12 @@
122824 #ifndef SQLITE_OMIT_TRIGGER
122825 else{
122826 Trigger *pTrigger = sParse.pNewTrigger;
122827 TriggerStep *pStep;
122828 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
122829 && sCtx.pTab->pSchema==pTrigger->pTabSchema
122830 ){
122831 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
122832 }
122833
122834 if( isLegacy==0 ){
122835 rc = renameResolveTrigger(&sParse);
@@ -122837,13 +123448,13 @@
122837 renameWalkTrigger(&sWalker, pTrigger);
122838 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
122839 if( pStep->pSrc ){
122840 int i;
122841 for(i=0; i<pStep->pSrc->nSrc; i++){
122842 SrcItem *pItem = &pStep->pSrc->a[i];
122843 if( 0==sqlite3_stricmp(pItem->zName, zOld) ){
122844 renameTokenFind(&sParse, &sCtx, pItem->zName);
122845 }
122846 }
122847 }
122848 }
122849 }
@@ -123294,75 +123905,78 @@
123294 /* Drop and reload the database schema. */
123295 renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
123296 renameTestSchema(pParse, zDb, iDb==1, "after drop column", 1);
123297
123298 /* Edit rows of table on disk */
123299 if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
123300 int i;
123301 int addr;
123302 int reg;
123303 int regRec;
123304 Index *pPk = 0;
123305 int nField = 0; /* Number of non-virtual columns after drop */
123306 int iCur;
123307 Vdbe *v = sqlite3GetVdbe(pParse);
123308 iCur = pParse->nTab++;
123309 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
123310 addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
123311 reg = ++pParse->nMem;
123312 if( HasRowid(pTab) ){
123313 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
123314 pParse->nMem += pTab->nCol;
123315 }else{
123316 pPk = sqlite3PrimaryKeyIndex(pTab);
123317 pParse->nMem += pPk->nColumn;
123318 for(i=0; i<pPk->nKeyCol; i++){
123319 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, reg+i+1);
123320 }
123321 nField = pPk->nKeyCol;
123322 }
123323 regRec = ++pParse->nMem;
123324 for(i=0; i<pTab->nCol; i++){
123325 if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
123326 int regOut;
123327 if( pPk ){
123328 int iPos = sqlite3TableColumnToIndex(pPk, i);
123329 int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
123330 if( iPos<pPk->nKeyCol ) continue;
123331 regOut = reg+1+iPos-(iPos>iColPos);
123332 }else{
123333 regOut = reg+1+nField;
123334 }
123335 if( i==pTab->iPKey ){
123336 sqlite3VdbeAddOp2(v, OP_Null, 0, regOut);
123337 }else{
123338 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
123339 assert( pParse->nErr
123340 || sqlite3VdbeGetOp(v,sqlite3VdbeCurrentAddr(v)-1)->opcode
123341 != OP_RealAffinity
123342 || pTab->aCol[i].affinity==SQLITE_AFF_REAL );
123343 sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
123344 }
123345 nField++;
123346 }
123347 }
123348 if( nField==0 ){
123349 /* dbsqlfuzz 5f09e7bcc78b4954d06bf9f2400d7715f48d1fef */
123350 pParse->nMem++;
123351 sqlite3VdbeAddOp2(v, OP_Null, 0, reg+1);
123352 nField = 1;
123353 }
123354 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
123355 if( pPk ){
123356 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
123357 }else{
123358 sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
123359 }
123360 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
123361
123362 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
123363 sqlite3VdbeJumpHere(v, addr);
 
 
 
 
 
 
 
 
 
 
123364 }
123365
123366 exit_drop_column:
123367 sqlite3DbFree(db, zCol);
123368 sqlite3SrcListDelete(db, pSrc);
@@ -123864,48 +124478,10 @@
123864 (void)NotUsed;
123865 sqlite3_result_error(ctx, zText, -1);
123866 sqlite3_result_error_code(ctx, err);
123867 }
123868
123869 /*
123870 ** Buffer pCons, which is nCons bytes in size, contains the text of a
123871 ** NOT NULL or CHECK constraint that will be inserted into a CREATE TABLE
123872 ** statement. If successful, this function returns the size of the buffer in
123873 ** bytes not including any trailing whitespace or "--" style comments. Or,
123874 ** if an OOM occurs, it returns 0 and sets db->mallocFailed to true.
123875 **
123876 ** C-style comments at the end are preserved. "--" style comments are
123877 ** removed because the comment terminator might be \000, and we are about
123878 ** to insert the pCons[] text into the middle of a larger string, and that
123879 ** will have the effect of removing the comment terminator and messing up
123880 ** the syntax.
123881 */
123882 static int alterRtrimConstraint(
123883 sqlite3 *db, /* used to record OOM error */
123884 const char *pCons, /* Buffer containing constraint */
123885 int nCons /* Size of pCons in bytes */
123886 ){
123887 u8 *zTmp = (u8*)sqlite3MPrintf(db, "%.*s", nCons, pCons);
123888 int iOff = 0;
123889 int iEnd = 0;
123890
123891 if( zTmp==0 ) return 0;
123892
123893 while( 1 ){
123894 int t = 0;
123895 int nToken = sqlite3GetToken(&zTmp[iOff], &t);
123896 if( t==TK_ILLEGAL ) break;
123897 if( t!=TK_SPACE && (t!=TK_COMMENT || zTmp[iOff]!='-') ){
123898 iEnd = iOff+nToken;
123899 }
123900 iOff += nToken;
123901 }
123902
123903 sqlite3DbFree(db, zTmp);
123904 return iEnd;
123905 }
123906
123907 /*
123908 ** Prepare a statement of the form:
123909 **
123910 ** ALTER TABLE pSrc ALTER pCol SET NOT NULL
123911 */
@@ -123932,11 +124508,11 @@
123932 return;
123933 }
123934
123935 /* Find the length in bytes of the constraint definition */
123936 pCons = pFirst->z;
123937 nCons = alterRtrimConstraint(pParse->db, pCons, pParse->sLastToken.z - pCons);
123938
123939 /* Search for a constraint violation. Throw an exception if one is found. */
123940 sqlite3NestedParse(pParse,
123941 "SELECT sqlite_fail('constraint failed', %d) "
123942 "FROM %Q.%Q AS x WHERE x.%.*s IS NULL",
@@ -124064,11 +124640,11 @@
124064 SQLITE_CONSTRAINT, zDb, pTab->zName, nExpr, zExpr
124065 );
124066
124067 /* Edit the SQL for the named table. */
124068 pCons = pFirst->z;
124069 nCons = alterRtrimConstraint(pParse->db, pCons, pParse->sLastToken.z - pCons);
124070
124071 sqlite3NestedParse(pParse,
124072 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
124073 "sql = sqlite_add_constraint(sql, %.*Q, -1) "
124074 "WHERE type='table' AND tbl_name=%Q COLLATE nocase"
@@ -124076,25 +124652,83 @@
124076 );
124077
124078 /* Finally, reload the database schema. */
124079 renameReloadSchema(pParse, iDb, INITFLAG_AlterDropCons);
124080 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124081
124082 /*
124083 ** Register built-in functions used to help implement ALTER TABLE
124084 */
124085 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
124086 static FuncDef aAlterTableFuncs[] = {
 
124087 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
124088 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
124089 INTERNAL_FUNCTION(sqlite_rename_test, 7, renameTableTest),
124090 INTERNAL_FUNCTION(sqlite_drop_column, 3, dropColumnFunc),
124091 INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc),
124092 INTERNAL_FUNCTION(sqlite_drop_constraint,2, dropConstraintFunc),
124093 INTERNAL_FUNCTION(sqlite_fail, 2, failConstraintFunc),
124094 INTERNAL_FUNCTION(sqlite_add_constraint, 3, addConstraintFunc),
124095 INTERNAL_FUNCTION(sqlite_find_constraint,2, findConstraintFunc),
124096 };
124097 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
124098 }
124099 #endif /* SQLITE_ALTER_TABLE */
124100
@@ -127172,10 +127806,20 @@
127172 for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
127173 return 1;
127174 }
127175 #endif
127176
 
 
 
 
 
 
 
 
 
 
127177 /*
127178 ** This routine is called after a single SQL statement has been
127179 ** parsed and a VDBE program to execute that statement has been
127180 ** prepared. This routine puts the finishing touches on the
127181 ** VDBE program and resets the pParse structure for the next
@@ -127664,27 +128308,37 @@
127664 }
127665 }
127666
127667 /*
127668 ** Reset the schema for the database at index iDb. Also reset the
127669 ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
127670 ** Deferred resets may be run by calling with iDb<0.
 
 
127671 */
127672 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
127673 int i;
127674 assert( iDb<db->nDb );
127675
127676 if( iDb>=0 ){
127677 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
127678 DbSetProperty(db, iDb, DB_ResetWanted);
127679 DbSetProperty(db, 1, DB_ResetWanted);
127680 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
 
127681 }
127682
127683 if( db->nSchemaLock==0 ){
 
 
 
127684 for(i=0; i<db->nDb; i++){
127685 if( DbHasProperty(db, i, DB_ResetWanted) ){
 
 
 
 
127686 sqlite3SchemaClear(db->aDb[i].pSchema);
127687 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
127688 }
127689 }
127690 }
@@ -127705,10 +128359,11 @@
127705 }else{
127706 DbSetProperty(db, i, DB_ResetWanted);
127707 }
127708 }
127709 }
 
127710 db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
127711 sqlite3VtabUnlockList(db);
127712 sqlite3BtreeLeaveAll(db);
127713 if( db->nSchemaLock==0 ){
127714 sqlite3CollapseDatabaseArray(db);
@@ -128130,16 +128785,20 @@
128130 ** is reserved for internal use.
128131 **
128132 ** When parsing the sqlite_schema table, this routine also checks to
128133 ** make sure the "type", "name", and "tbl_name" columns are consistent
128134 ** with the SQL.
 
 
 
128135 */
128136 SQLITE_PRIVATE int sqlite3CheckObjectName(
128137 Parse *pParse, /* Parsing context */
128138 const char *zName, /* Name of the object to check */
128139 const char *zType, /* Type of this object */
128140 const char *zTblName /* Parent table name for triggers and indexes */
 
128141 ){
128142 sqlite3 *db = pParse->db;
128143 if( sqlite3WritableSchema(db)
128144 || db->init.imposterTable
128145 || !sqlite3Config.bExtraSchemaChecks
@@ -128155,11 +128814,12 @@
128155 sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
128156 return SQLITE_ERROR;
128157 }
128158 }else{
128159 if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
128160 || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))
 
128161 ){
128162 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
128163 zName);
128164 return SQLITE_ERROR;
128165 }
@@ -128342,14 +129002,18 @@
128342 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
128343 zName = sqlite3NameFromToken(db, pName);
128344 if( IN_RENAME_OBJECT ){
128345 sqlite3RenameTokenMap(pParse, (void*)zName, pName);
128346 }
 
 
 
128347 }
128348 pParse->sNameToken = *pName;
128349 if( zName==0 ) return;
128350 if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){
 
128351 goto begin_table_error;
128352 }
128353 if( db->init.iDb==1 ) isTemp = 1;
128354 #ifndef SQLITE_OMIT_AUTHORIZATION
128355 assert( isTemp==0 || isTemp==1 );
@@ -128379,13 +129043,10 @@
128379 ** and types will be used, so there is no need to test for namespace
128380 ** collisions.
128381 */
128382 if( !IN_SPECIAL_PARSE ){
128383 char *zDb = db->aDb[iDb].zDbSName;
128384 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
128385 goto begin_table_error;
128386 }
128387 pTable = sqlite3FindTable(db, zName, zDb);
128388 if( pTable ){
128389 if( !noErr ){
128390 sqlite3ErrorMsg(pParse, "%s %T already exists",
128391 (IsView(pTable)? "view" : "table"), pName);
@@ -128613,19 +129274,18 @@
128613
128614 /* Because keywords GENERATE ALWAYS can be converted into identifiers
128615 ** by the parser, we can sometimes end up with a typename that ends
128616 ** with "generated always". Check for this case and omit the surplus
128617 ** text. */
128618 if( sType.n>=16
128619 && sqlite3_strnicmp(sType.z+(sType.n-6),"always",6)==0
128620 ){
128621 sType.n -= 6;
128622 while( ALWAYS(sType.n>0) && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
128623 if( sType.n>=9
128624 && sqlite3_strnicmp(sType.z+(sType.n-9),"generated",9)==0
128625 ){
128626 sType.n -= 9;
128627 while( sType.n>0 && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
128628 }
128629 }
128630
128631 /* Check for standard typenames. For standard typenames we will
@@ -129692,25 +130352,38 @@
129692 }
129693 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
129694
129695 #ifndef SQLITE_OMIT_VIRTUALTABLE
129696 /*
129697 ** Return true if zName is a shadow table name in the current database
129698 ** connection.
 
 
 
 
 
129699 */
129700 SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
129701 const char *zTail; /* Pointer to the last "_" in zName */
129702 Table *pTab; /* Table that zName is a shadow of */
129703 char *zCopy; /* Transient copy of zName after last "_" */
 
 
129704 zTail = strrchr(zName, '_');
129705 if( zTail==0 ) return 0;
129706 zCopy = sqlite3DbStrNDup(db, zName, (int)(zTail-zName));
129707 pTab = zCopy ? sqlite3FindTable(db, zCopy, 0) : 0;
 
 
 
 
 
 
 
 
129708 sqlite3DbFree(db, zCopy);
129709 if( pTab==0 ) return 0;
129710 if( !IsVirtual(pTab) ) return 0;
129711 return sqlite3IsShadowTableOf(db, pTab, zName);
129712 }
129713 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
129714
129715
129716 #ifdef SQLITE_DEBUG
@@ -129775,11 +130448,14 @@
129775 return;
129776 }
129777 p = pParse->pNewTable;
129778 if( p==0 ) return;
129779
129780 if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
 
 
 
129781 p->tabFlags |= TF_Shadow;
129782 }
129783
129784 /* If the db->init.busy is 1 it means we are reading the SQL off the
129785 ** "sqlite_schema" or "sqlite_temp_schema" table on the disk.
@@ -131123,13 +131799,17 @@
131123 assert( pName && pName->z );
131124
131125 #ifndef SQLITE_OMIT_TEMPDB
131126 /* If the index name was unqualified, check if the table
131127 ** is a temp table. If so, set the database to 1. Do not do this
131128 ** if initializing a database schema.
131129 */
131130 if( !db->init.busy ){
 
 
 
 
131131 pTab = sqlite3SrcListLookup(pParse, pTblName);
131132 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
131133 iDb = 1;
131134 }
131135 }
@@ -131196,11 +131876,13 @@
131196 */
131197 if( pName ){
131198 zName = sqlite3NameFromToken(db, pName);
131199 if( zName==0 ) goto exit_create_index;
131200 assert( pName->z!=0 );
131201 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
 
 
131202 goto exit_create_index;
131203 }
131204 if( !IN_RENAME_OBJECT ){
131205 if( !db->init.busy ){
131206 if( sqlite3FindTable(db, zName, pDb->zDbSName)!=0 ){
@@ -131775,12 +132457,12 @@
131775 sqlite3NestedParse(pParse,
131776 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE " WHERE name=%Q AND type='index'",
131777 db->aDb[iDb].zDbSName, pIndex->zName
131778 );
131779 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
131780 sqlite3ChangeCookie(pParse, iDb);
131781 destroyRootPage(pParse, pIndex->tnum, iDb);
 
131782 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
131783 }
131784
131785 exit_drop_index:
131786 sqlite3SrcListDelete(db, pName);
@@ -134754,11 +135436,11 @@
134754 ** something that can be converted into a number, we have:
134755 ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
134756 ** that cannot be converted to a numeric value.
134757 */
134758 double rVal = sqlite3_value_double(argv[0]);
134759 if( rVal<0 ) rVal = -rVal;
134760 sqlite3_result_double(context, rVal);
134761 break;
134762 }
134763 }
134764 }
@@ -134897,12 +135579,19 @@
134897 assert( argc==3 || argc==2 );
134898 p0type = sqlite3_value_type(argv[0]);
134899 p1 = sqlite3_value_int64(argv[1]);
134900 if( p0type==SQLITE_BLOB ){
134901 len = sqlite3_value_bytes(argv[0]);
134902 z = sqlite3_value_blob(argv[0]);
134903 if( z==0 ) return;
 
 
 
 
 
 
 
134904 assert( len==sqlite3_value_bytes(argv[0]) );
134905 }else{
134906 z = sqlite3_value_text(argv[0]);
134907 if( z==0 ) return;
134908 len = 0;
@@ -134932,11 +135621,11 @@
134932 if( p1<0 ){
134933 p1 += len;
134934 if( p1<0 ){
134935 if( p2<0 ){
134936 p2 = 0;
134937 }else{
134938 p2 += p1;
134939 }
134940 p1 = 0;
134941 }
134942 }else if( p1>0 ){
@@ -135022,14 +135711,12 @@
135022 ** handle the rounding directly,
135023 ** otherwise use printf.
135024 */
135025 if( r<-4503599627370496.0 || r>+4503599627370496.0 ){
135026 /* The value has no fractional part so there is nothing to round */
135027 }else if( n==0 ){
135028 r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5)));
135029 }else{
135030 zBuf = sqlite3_mprintf("%!.*f",(int)n,r);
135031 if( zBuf==0 ){
135032 sqlite3_result_error_nomem(context);
135033 return;
135034 }
135035 sqlite3AtoF(zBuf, &r);
@@ -137109,11 +137796,11 @@
137109 if( argc==2 ){
137110 switch( sqlite3_value_numeric_type(argv[1]) ){
137111 case SQLITE_INTEGER:
137112 case SQLITE_FLOAT:
137113 b = log(x);
137114 if( b<=0.0 ) return;
137115 x = sqlite3_value_double(argv[1]);
137116 if( x<=0.0 ) return;
137117 break;
137118 default:
137119 return;
@@ -138544,10 +139231,12 @@
138544 for(i=0; i<nCol; i++){
138545 sqlite3VdbeAddOp2(v, OP_Copy,
138546 sqlite3TableColumnToStorage(pFKey->pFrom, aiCol[i])+1+regData,
138547 regTemp+i);
138548 }
 
 
138549
138550 /* If the parent table is the same as the child table, and we are about
138551 ** to increment the constraint-counter (i.e. this is an INSERT operation),
138552 ** then check if the row being inserted matches itself. If so, do not
138553 ** increment the constraint-counter.
@@ -138558,29 +139247,29 @@
138558 ** none of the child key values are).
138559 */
138560 if( pTab==pFKey->pFrom && nIncr==1 ){
138561 int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
138562 for(i=0; i<nCol; i++){
138563 int iChild = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i])
138564 +1+regData;
138565 int iParent = 1+regData;
138566 iParent += sqlite3TableColumnToStorage(pIdx->pTable,
138567 pIdx->aiColumn[i]);
138568 assert( pIdx->aiColumn[i]>=0 );
138569 assert( aiCol[i]!=pTab->iPKey );
138570 if( pIdx->aiColumn[i]==pTab->iPKey ){
138571 /* The parent key is a composite key that includes the IPK column */
138572 iParent = regData;
138573 }
138574 sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
 
 
138575 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
138576 }
138577 sqlite3VdbeGoto(v, iOk);
138578 }
138579
138580 sqlite3VdbeAddOp4(v, OP_Affinity, regTemp, nCol, 0,
138581 sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
138582 sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regTemp, nCol);
138583 VdbeCoverage(v);
138584 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
138585 }
138586 }
@@ -139150,10 +139839,27 @@
139150 return 1;
139151 }
139152 }
139153 return 0;
139154 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139155
139156 /*
139157 ** This function is called when inserting, deleting or updating a row of
139158 ** table pTab to generate VDBE code to perform foreign key constraint
139159 ** processing for the operation.
@@ -139184,10 +139890,11 @@
139184 sqlite3 *db = pParse->db; /* Database handle */
139185 FKey *pFKey; /* Used to iterate through FKs */
139186 int iDb; /* Index of database containing pTab */
139187 const char *zDb; /* Name of database containing pTab */
139188 int isIgnoreErrors = pParse->disableTriggers;
 
139189
139190 /* Exactly one of regOld and regNew should be non-zero. */
139191 assert( (regOld==0)!=(regNew==0) );
139192
139193 /* If foreign-keys are disabled, this function is a no-op. */
@@ -139197,110 +139904,120 @@
139197 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
139198 assert( iDb>=00 && iDb<db->nDb );
139199 zDb = db->aDb[iDb].zDbSName;
139200
139201 /* Loop through all the foreign key constraints for which pTab is the
139202 ** child table (the table that the foreign key definition is part of). */
139203 for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
139204 Table *pTo; /* Parent table of foreign key pFKey */
139205 Index *pIdx = 0; /* Index on key columns in pTo */
139206 int *aiFree = 0;
139207 int *aiCol;
139208 int iCol;
139209 int i;
139210 int bIgnore = 0;
139211
139212 if( aChange
139213 && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
139214 && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
139215 ){
139216 continue;
139217 }
139218
139219 /* Find the parent table of this foreign key. Also find a unique index
139220 ** on the parent key columns in the parent table. If either of these
139221 ** schema items cannot be located, set an error in pParse and return
139222 ** early. */
139223 if( pParse->disableTriggers ){
139224 pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
139225 }else{
139226 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
139227 }
139228 if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
139229 assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
139230 if( !isIgnoreErrors || db->mallocFailed ) return;
139231 if( pTo==0 ){
139232 /* If isIgnoreErrors is true, then a table is being dropped. In this
139233 ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
139234 ** before actually dropping it in order to check FK constraints.
139235 ** If the parent table of an FK constraint on the current table is
139236 ** missing, behave as if it is empty. i.e. decrement the relevant
139237 ** FK counter for each row of the current table with non-NULL keys.
139238 */
139239 Vdbe *v = sqlite3GetVdbe(pParse);
139240 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
139241 for(i=0; i<pFKey->nCol; i++){
139242 int iFromCol, iReg;
139243 iFromCol = pFKey->aCol[i].iFrom;
139244 iReg = sqlite3TableColumnToStorage(pFKey->pFrom,iFromCol) + regOld+1;
139245 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
139246 }
139247 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
139248 }
139249 continue;
139250 }
139251 assert( pFKey->nCol==1 || (aiFree && pIdx) );
139252
139253 if( aiFree ){
139254 aiCol = aiFree;
139255 }else{
139256 iCol = pFKey->aCol[0].iFrom;
139257 aiCol = &iCol;
139258 }
139259 for(i=0; i<pFKey->nCol; i++){
139260 if( aiCol[i]==pTab->iPKey ){
139261 aiCol[i] = -1;
139262 }
139263 assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
139264 #ifndef SQLITE_OMIT_AUTHORIZATION
139265 /* Request permission to read the parent key columns. If the
139266 ** authorization callback returns SQLITE_IGNORE, behave as if any
139267 ** values read from the parent table are NULL. */
139268 if( db->xAuth ){
139269 int rcauth;
139270 char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zCnName;
139271 rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
139272 bIgnore = (rcauth==SQLITE_IGNORE);
139273 }
139274 #endif
139275 }
139276
139277 /* Take a shared-cache advisory read-lock on the parent table. Allocate
139278 ** a cursor to use to search the unique index on the parent key columns
139279 ** in the parent table. */
139280 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
139281 pParse->nTab++;
139282
139283 if( regOld!=0 ){
139284 /* A row is being removed from the child table. Search for the parent.
139285 ** If the parent does not exist, removing the child row resolves an
139286 ** outstanding foreign key constraint violation. */
139287 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
139288 }
139289 if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
139290 /* A row is being added to the child table. If a parent row cannot
139291 ** be found, adding the child row has violated the FK constraint.
139292 **
139293 ** If this operation is being performed as part of a trigger program
139294 ** that is actually a "SET NULL" action belonging to this very
139295 ** foreign key, then omit this scan altogether. As all child key
139296 ** values are guaranteed to be NULL, it is not possible for adding
139297 ** this row to cause an FK violation. */
139298 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
139299 }
139300
139301 sqlite3DbFree(db, aiFree);
 
 
 
 
 
 
 
 
 
 
139302 }
139303
139304 /* Loop through all the foreign key constraints that refer to this table.
139305 ** (the "child" constraints) */
139306 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
@@ -139343,14 +140060,20 @@
139343 if( regOld!=0 ){
139344 int eAction = pFKey->aAction[aChange!=0];
139345 if( (db->flags & SQLITE_FkNoAction) ) eAction = OE_None;
139346
139347 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
139348 /* If this is a deferred FK constraint, or a CASCADE or SET NULL
139349 ** action applies, then any foreign key violations caused by
139350 ** removing the parent key will be rectified by the action trigger.
139351 ** So do not set the "may-abort" flag in this case.
 
 
 
 
 
 
139352 **
139353 ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
139354 ** may-abort flag will eventually be set on this statement anyway
139355 ** (when this function is called as part of processing the UPDATE
139356 ** within the action trigger).
@@ -139360,11 +140083,14 @@
139360 ** applies. The trouble starts if the CASCADE or SET NULL action
139361 ** trigger causes other triggers or action rules attached to the
139362 ** child table to fire. In these cases the fk constraint counters
139363 ** might be set incorrectly if any OP_FkCounter related scans are
139364 ** omitted. */
139365 if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
 
 
 
139366 sqlite3MayAbort(pParse);
139367 }
139368 }
139369 pItem->zName = 0;
139370 sqlite3SrcListDelete(db, pSrc);
@@ -139423,11 +140149,16 @@
139423 **
139424 ** * There are any FKs for which pTab is the child and the parent table
139425 ** and any FK processing at all is required (even of a different FK), or
139426 **
139427 ** * the UPDATE modifies one or more parent keys for which the action is
139428 ** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
 
 
 
 
 
139429 **
139430 ** Or, assuming some other foreign key processing is required, 1.
139431 */
139432 SQLITE_PRIVATE int sqlite3FkRequired(
139433 Parse *pParse, /* Parse context */
@@ -139462,10 +140193,11 @@
139462 if( (pParse->db->flags & SQLITE_FkNoAction)==0
139463 && p->aAction[1]!=OE_None
139464 ){
139465 return 2;
139466 }
 
139467 bHaveFK = 1;
139468 }
139469 }
139470 }
139471 }
@@ -140403,10 +141135,22 @@
140403 if( 0!=sqlite3ExprAffinity(pExpr) ) return 0;
140404 }
140405 return 1;
140406
140407 }
 
 
 
 
 
 
 
 
 
 
 
 
140408
140409 /*
140410 ** This function is called by the parser for the second and subsequent
140411 ** rows of a multi-row VALUES clause. Argument pLeft is the part of
140412 ** the VALUES clause already parsed, argument pRow is the vector of values
@@ -140454,18 +141198,28 @@
140454 ** has an affinity (i.e. is a CAST expression). This causes problems
140455 ** because the complex rules SQLite uses (see function
140456 ** sqlite3SubqueryColumnTypes() in select.c) to determine the effective
140457 ** affinity of such a column for all rows require access to all values in
140458 ** the column simultaneously.
 
 
 
 
 
 
 
 
140459 */
140460 SQLITE_PRIVATE Select *sqlite3MultiValues(Parse *pParse, Select *pLeft, ExprList *pRow){
140461
140462 if( pParse->bHasWith /* condition (a) above */
140463 || pParse->db->init.busy /* condition (b) above */
140464 || sqlite3ExprListIsConstant(pParse, pRow, 1)==0 /* condition (c) above */
140465 || (pLeft->pSrc->nSrc==0 &&
140466 exprListIsNoAffinity(pParse,pLeft->pEList)==0) /* condition (d) above */
 
 
140467 || IN_SPECIAL_PARSE
140468 ){
140469 /* The co-routine method cannot be used. Fall back to UNION ALL. */
140470 Select *pSelect = 0;
140471 int f = SF_Values | SF_MultiValue;
@@ -140503,11 +141257,11 @@
140503 SelectDest dest;
140504 Subquery *pSubq;
140505 pRet->pSrc->nSrc = 1;
140506 pRet->pPrior = pLeft->pPrior;
140507 pRet->op = pLeft->op;
140508 if( pRet->pPrior ) pRet->selFlags |= SF_Values;
140509 pLeft->pPrior = 0;
140510 pLeft->op = TK_SELECT;
140511 assert( pLeft->pNext==0 );
140512 assert( pRet->pNext==0 );
140513 p = &pRet->pSrc->a[0];
@@ -140729,11 +141483,15 @@
140729
140730 /* If the Select object is really just a simple VALUES() list with a
140731 ** single row (the common case) then keep that one row of values
140732 ** and discard the other (unused) parts of the pSelect object
140733 */
140734 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
 
 
 
 
140735 pList = pSelect->pEList;
140736 pSelect->pEList = 0;
140737 sqlite3SelectDelete(db, pSelect);
140738 pSelect = 0;
140739 }
@@ -142054,10 +142812,16 @@
142054 if( pUpsertClause!=0 ){
142055 if( pUpsertClause->isDoUpdate==0 ){
142056 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
142057 }else{
142058 onError = OE_Update; /* DO UPDATE */
 
 
 
 
 
 
142059 }
142060 }
142061 if( pUpsertClause!=pUpsert ){
142062 /* The first ON CONFLICT clause has a conflict target other than
142063 ** the IPK. We have to jump ahead to that first ON CONFLICT clause
@@ -142213,10 +142977,18 @@
142213 bAffinityDone = 1;
142214 }
142215 VdbeNoopComment((v, "prep index %s", pIdx->zName));
142216 iThisCur = iIdxCur+ix;
142217
 
 
 
 
 
 
 
 
142218
142219 /* Skip partial indices for which the WHERE clause is not true */
142220 if( pIdx->pPartIdxWhere ){
142221 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
142222 pParse->iSelfTab = -(regNewData+1);
@@ -142897,10 +143669,13 @@
142897 return 0; /* FROM clause must have exactly one term */
142898 }
142899 if( pSelect->pSrc->a[0].fg.isSubquery ){
142900 return 0; /* FROM clause cannot contain a subquery */
142901 }
 
 
 
142902 if( pSelect->pWhere ){
142903 return 0; /* SELECT may not have a WHERE clause */
142904 }
142905 if( pSelect->pOrderBy ){
142906 return 0; /* SELECT may not have an ORDER BY clause */
@@ -143064,19 +143839,21 @@
143064 ){
143065 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
143066 }
143067 #endif
143068 #ifndef SQLITE_OMIT_FOREIGN_KEY
143069 /* Disallow the transfer optimization if the destination table contains
143070 ** any foreign key constraints. This is more restrictive than necessary.
143071 ** But the main beneficiary of the transfer optimization is the VACUUM
143072 ** command, and the VACUUM command disables foreign key constraints. So
143073 ** the extra complication to make this rule less restrictive is probably
143074 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
143075 */
 
 
143076 assert( IsOrdinaryTable(pDest) );
143077 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->u.tab.pFKey!=0 ){
143078 return 0;
143079 }
143080 #endif
143081 if( (db->flags & SQLITE_CountRows)!=0 ){
143082 return 0; /* xfer opt does not play well with PRAGMA count_changes */
@@ -146157,17 +146934,26 @@
146157 ** Helper subroutine for PRAGMA integrity_check:
146158 **
146159 ** Generate code to output a single-column result row with a value of the
146160 ** string held in register 3. Decrement the result count in register 1
146161 ** and halt if the maximum number of result rows have been issued.
 
 
 
 
 
146162 */
146163 static int integrityCheckResultRow(Vdbe *v){
146164 int addr;
146165 sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
146166 addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
146167 VdbeCoverage(v);
146168 sqlite3VdbeAddOp0(v, OP_Halt);
 
 
 
 
146169 return addr;
146170 }
146171
146172 /*
146173 ** Should table pTab be skipped when doing an integrity_check?
@@ -147567,11 +148353,11 @@
147567 addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
147568 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
147569 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
147570 P4_DYNAMIC);
147571 sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
147572 integrityCheckResultRow(v);
147573 sqlite3VdbeJumpHere(v, addr);
147574
147575 /* Check that the indexes all have the right number of rows */
147576 cnt = pObjTab ? 1 : 0;
147577 sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
@@ -147593,11 +148379,11 @@
147593 if( pIdx->pPartIdxWhere==0 ){
147594 addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+cnt, 0, 8+iTab);
147595 VdbeCoverageNeverNull(v);
147596 sqlite3VdbeLoadString(v, 4, pIdx->zName);
147597 sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
147598 integrityCheckResultRow(v);
147599 sqlite3VdbeJumpHere(v, addr);
147600 }
147601 cnt++;
147602 }
147603 }
@@ -147639,25 +148425,20 @@
147639 ** will also prepopulate the cursor column cache that is used
147640 ** by the OP_IsType code, so it is a required step.
147641 */
147642 assert( !IsVirtual(pTab) );
147643 if( HasRowid(pTab) ){
147644 mxCol = -1;
147645 for(j=0; j<pTab->nCol; j++){
147646 if( (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)==0 ) mxCol++;
147647 }
147648 if( mxCol==pTab->iPKey ) mxCol--;
147649 }else{
147650 /* COLFLAG_VIRTUAL columns are not included in the WITHOUT ROWID
147651 ** PK index column-count, so there is no need to account for them
147652 ** in this case. */
147653 mxCol = sqlite3PrimaryKeyIndex(pTab)->nColumn-1;
147654 }
147655 if( mxCol>=0 ){
147656 sqlite3VdbeAddOp3(v, OP_Column, iDataCur, mxCol, 3);
147657 sqlite3VdbeTypeofColumn(v, 3);
147658 }
147659
147660 if( !isQuick ){
147661 if( pPk ){
147662 /* Verify WITHOUT ROWID keys are in ascending order */
147663 int a1;
@@ -147667,11 +148448,11 @@
147667 sqlite3VdbeAddOp1(v, OP_IsNull, r2); VdbeCoverage(v);
147668 zErr = sqlite3MPrintf(db,
147669 "row not in PRIMARY KEY order for %s",
147670 pTab->zName);
147671 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
147672 integrityCheckResultRow(v);
147673 sqlite3VdbeJumpHere(v, a1);
147674 sqlite3VdbeJumpHere(v, a1+1);
147675 for(j=0; j<pPk->nKeyCol; j++){
147676 sqlite3ExprCodeLoadIndexColumn(pParse, pPk, iDataCur, j, r2+j);
147677 }
@@ -147804,11 +148585,11 @@
147804 zErr = sqlite3MPrintf(db, "TEXT value in %s.%s",
147805 pTab->zName, pTab->aCol[j].zCnName);
147806 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
147807 }
147808 sqlite3VdbeResolveLabel(v, labelError);
147809 integrityCheckResultRow(v);
147810 sqlite3VdbeResolveLabel(v, labelOk);
147811 }
147812 /* Verify CHECK constraints */
147813 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
147814 ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
@@ -147826,11 +148607,11 @@
147826 sqlite3VdbeResolveLabel(v, addrCkFault);
147827 pParse->iSelfTab = 0;
147828 zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
147829 pTab->zName);
147830 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
147831 integrityCheckResultRow(v);
147832 sqlite3VdbeResolveLabel(v, addrCkOk);
147833 }
147834 sqlite3ExprListDelete(db, pCheck);
147835 }
147836 if( !isQuick ){ /* Omit the remaining tests for quick_check */
@@ -147852,21 +148633,21 @@
147852 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
147853 sqlite3MPrintf(db, "index %s stores an imprecise floating-point "
147854 "value for row ", pIdx->zName),
147855 P4_DYNAMIC);
147856 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
147857 integrityCheckResultRow(v);
147858 sqlite3VdbeAddOp2(v, OP_Goto, 0, ckUniq);
147859
147860 sqlite3VdbeJumpHere(v, jmp2);
147861 sqlite3VdbeLoadString(v, 3, "row ");
147862 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
147863 sqlite3VdbeLoadString(v, 4, " missing from index ");
147864 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
147865 jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
147866 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
147867 jmp4 = integrityCheckResultRow(v);
147868 sqlite3VdbeResolveLabel(v, ckUniq);
147869
147870 /* The OP_IdxRowid opcode is an optimized version of OP_Column
147871 ** that extracts the rowid off the end of the index record.
147872 ** But it only works correctly if index record does not have
@@ -147961,11 +148742,11 @@
147961 if( pVTab->pModule->xIntegrity==0 ) continue;
147962 sqlite3VdbeAddOp3(v, OP_VCheck, i, 3, isQuick);
147963 pTab->nTabRef++;
147964 sqlite3VdbeAppendP4(v, pTab, P4_TABLEREF);
147965 a1 = sqlite3VdbeAddOp1(v, OP_IsNull, 3); VdbeCoverage(v);
147966 integrityCheckResultRow(v);
147967 sqlite3VdbeJumpHere(v, a1);
147968 continue;
147969 }
147970 #endif
147971 }
@@ -148761,15 +149542,17 @@
148761 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
148762 int rc;
148763 int i, j;
148764 StrAccum acc;
148765 char *zSql;
 
148766
148767 UNUSED_PARAMETER(idxNum);
148768 UNUSED_PARAMETER(idxStr);
148769 pragmaVtabCursorClear(pCsr);
148770 j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
 
148771 for(i=0; i<argc; i++, j++){
148772 const char *zText = (const char*)sqlite3_value_text(argv[i]);
148773 assert( j<ArraySize(pCsr->azArg) );
148774 assert( pCsr->azArg[j]==0 );
148775 if( zText ){
@@ -148784,11 +149567,15 @@
148784 if( pCsr->azArg[1] ){
148785 sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
148786 }
148787 sqlite3_str_appendall(&acc, pTab->pName->zName);
148788 if( pCsr->azArg[0] ){
148789 sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
 
 
 
 
148790 }
148791 zSql = sqlite3StrAccumFinish(&acc);
148792 if( zSql==0 ) return SQLITE_NOMEM;
148793 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
148794 sqlite3_free(zSql);
@@ -149018,10 +149805,17 @@
149018 const char *zEnd;
149019 TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
149020
149021 assert( db->init.busy );
149022 db->init.iDb = iDb;
 
 
 
 
 
 
 
149023 if( sqlite3GetUInt32(argv[3], &db->init.newTnum)==0
149024 || (db->init.newTnum>pData->mxPage && pData->mxPage>0)
149025 ){
149026 if( sqlite3Config.bExtraSchemaChecks ){
149027 corruptSchema(pData, argv, "invalid rootpage");
@@ -149267,12 +150061,13 @@
149267 assert( db->init.busy );
149268 initData.mxPage = sqlite3BtreeLastPage(pDb->pBt);
149269 {
149270 char *zSql;
149271 zSql = sqlite3MPrintf(db,
149272 "SELECT*FROM\"%w\".%s ORDER BY rowid",
149273 db->aDb[iDb].zDbSName, zSchemaTabName);
 
149274 #ifndef SQLITE_OMIT_AUTHORIZATION
149275 {
149276 sqlite3_xauth xAuth;
149277 xAuth = db->xAuth;
149278 db->xAuth = 0;
@@ -149289,10 +150084,16 @@
149289 sqlite3AnalysisLoad(db, iDb);
149290 }
149291 #endif
149292 }
149293 assert( pDb == &(db->aDb[iDb]) );
 
 
 
 
 
 
149294 if( db->mallocFailed ){
149295 rc = SQLITE_NOMEM_BKPT;
149296 sqlite3ResetAllSchemasOfConnection(db);
149297 pDb = &db->aDb[iDb];
149298 }else
@@ -149324,11 +150125,11 @@
149324 error_out:
149325 if( rc ){
149326 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
149327 sqlite3OomFault(db);
149328 }
149329 sqlite3ResetOneSchema(db, iDb);
149330 }
149331 db->init.busy = 0;
149332 return rc;
149333 }
149334
@@ -149426,11 +150227,11 @@
149426 ** set Parse.rc to SQLITE_SCHEMA. */
149427 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
149428 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
149429 if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
149430 if( DbHasProperty(db, iDb, DB_SchemaLoaded) ) pParse->rc = SQLITE_SCHEMA;
149431 sqlite3ResetOneSchema(db, iDb);
149432 }
149433
149434 /* Close the transaction, if one was opened. */
149435 if( openedTransaction ){
149436 sqlite3BtreeCommit(pBt);
@@ -149768,11 +150569,11 @@
149768 rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
149769 assert( rc==SQLITE_OK || *ppStmt==0 );
149770 if( rc==SQLITE_OK || db->mallocFailed ) break;
149771 cnt++;
149772 }while( (rc==SQLITE_ERROR_RETRY && ALWAYS(cnt<=SQLITE_MAX_PREPARE_RETRY))
149773 || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt)==1) );
149774 sqlite3BtreeLeaveAll(db);
149775 assert( rc!=SQLITE_ERROR_RETRY );
149776 rc = sqlite3ApiExit(db, rc);
149777 assert( (rc&db->errMask)==rc );
149778 db->busyHandler.nBusy = 0;
@@ -150492,10 +151293,41 @@
150492 }
150493 unsetJoinExpr(p->pLeft, iTable, nullable);
150494 p = p->pRight;
150495 }
150496 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150497
150498 /*
150499 ** This routine processes the join information for a SELECT statement.
150500 **
150501 ** * A NATURAL join is converted into a USING join. After that, we
@@ -150522,10 +151354,11 @@
150522 SrcItem *pLeft; /* Left table being joined */
150523 SrcItem *pRight; /* Right table being joined */
150524 int bSeenTFunc = 0; /* True if have seen table-valued function */
150525
150526 pSrc = p->pSrc;
 
150527 pLeft = &pSrc->a[0];
150528 pRight = &pLeft[1];
150529 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
150530 Table *pRightTab = pRight->pSTab;
150531 u32 joinType;
@@ -151254,17 +152087,17 @@
151254 if( srcTab>=0 ){
151255 for(i=0; i<nResultCol; i++){
151256 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
151257 VdbeComment((v, "%s", p->pEList->a[i].zEName));
151258 }
151259 }else if( eDest!=SRT_Exists ){
 
 
 
151260 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
151261 ExprList *pExtra = 0;
151262 #endif
151263 /* If the destination is an EXISTS(...) expression, the actual
151264 ** values returned by the SELECT are not required.
151265 */
151266 u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
151267 ExprList *pEList;
151268 if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
151269 ecelFlags = SQLITE_ECEL_DUP;
151270 }else{
@@ -152647,16 +153480,20 @@
152647 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
152648 }else{
152649 pRet = 0;
152650 }
152651 assert( iCol>=0 );
152652 /* iCol must be less than p->pEList->nExpr. Otherwise an error would
152653 ** have been thrown during name resolution and we would not have gotten
152654 ** this far */
152655 if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
 
 
 
152656 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
152657 }
 
152658 return pRet;
152659 }
152660
152661 /*
152662 ** The select statement passed as the second parameter is a compound SELECT
@@ -152864,11 +153701,11 @@
152864
152865 /* Find the next row in the Queue and output that row */
152866 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
152867
152868 /* Transfer the next row in Queue over to Current */
152869 sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
152870 if( pOrderBy ){
152871 sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
152872 }else{
152873 sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
152874 }
@@ -152968,10 +153805,21 @@
152968 */
152969 static int hasAnchor(Select *p){
152970 while( p && (p->selFlags & SF_Recursive)!=0 ){ p = p->pPrior; }
152971 return p!=0;
152972 }
 
 
 
 
 
 
 
 
 
 
 
152973
152974 /*
152975 ** Return TRUE if p is a UNION with a LIMIT of exactly 1 and no OFFSET
152976 ** clause. This is a precondition for a couple of related optimizations.
152977 **
@@ -153080,11 +153928,11 @@
153080 #endif
153081 if( p->pOrderBy ){
153082 /* If the compound has an ORDER BY clause, then always use the merge
153083 ** algorithm. */
153084 return multiSelectByMerge(pParse, p, pDest);
153085 }else if( p->op!=TK_ALL && !unionWithLimitOne(db,p) ){
153086 /* If the compound is EXCEPT, INTERSECT, or UNION (anything other than
153087 ** UNION ALL) then also always use the merge algorithm. However, the
153088 ** multiSelectByMerge() routine requires that the compound have an
153089 ** ORDER BY clause, and it doesn't right now. So invent one first. */
153090 Expr *pOne = sqlite3ExprInt32(db, 1);
@@ -153236,30 +154084,34 @@
153236 switch( pDest->eDest ){
153237 /* Store the result as data using a unique key.
153238 */
153239 case SRT_Fifo:
153240 case SRT_DistFifo:
 
153241 case SRT_Table:
 
153242 case SRT_EphemTab: {
153243 int r1 = sqlite3GetTempReg(pParse);
153244 int r2 = sqlite3GetTempReg(pParse);
153245 int iParm = pDest->iSDParm;
153246 testcase( pDest->eDest==SRT_Table );
153247 testcase( pDest->eDest==SRT_EphemTab );
153248 testcase( pDest->eDest==SRT_Fifo );
153249 testcase( pDest->eDest==SRT_DistFifo );
153250 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
 
 
153251 #if !defined(SQLITE_ENABLE_NULL_TRIM) && defined(SQLITE_DEBUG)
153252 /* A destination of SRT_Table and a non-zero iSDParm2 parameter means
153253 ** that this is an "UPDATE ... FROM" on a virtual table or view. In this
153254 ** case set the p5 parameter of the OP_MakeRecord to OPFLAG_NOCHNG_MAGIC.
153255 ** This does not affect operation in any way - it just allows MakeRecord
153256 ** to process OPFLAG_NOCHANGE values without an assert() failing. */
153257 if( pDest->eDest==SRT_Table && pDest->iSDParm2 ){
153258 sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
153259 }
153260 #endif
 
153261 #ifndef SQLITE_OMIT_CTE
153262 if( pDest->eDest==SRT_DistFifo ){
153263 /* If the destination is DistFifo, then cursor (iParm+1) is open
153264 ** on an ephemeral index that is used to enforce uniqueness on the
153265 ** total result. At this point, we are processing the setup portion
@@ -153863,10 +154715,19 @@
153863 **
153864 ** When the subquery on the right side of the LEFT JOIN is flattened, we
153865 ** have to add OP_IfNullRow in front of the OP_Integer that implements the
153866 ** "m" value of the subquery so that a NULL will be loaded instead of 59
153867 ** when processing a non-matched row of the left.
 
 
 
 
 
 
 
 
 
153868 */
153869 typedef struct SubstContext {
153870 Parse *pParse; /* The parsing context */
153871 int iTable; /* Replace references to this table */
153872 int iNewTable; /* New table number */
@@ -153904,10 +154765,11 @@
153904 testcase( ExprHasProperty(pExpr, EP_InnerON) );
153905 pExpr->w.iJoin = pSubst->iNewTable;
153906 }
153907 if( pExpr->op==TK_COLUMN
153908 && pExpr->iTable==pSubst->iTable
 
153909 && !ExprHasProperty(pExpr, EP_FixedCol)
153910 ){
153911 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
153912 if( pExpr->iColumn<0 ){
153913 pExpr->op = TK_NULL;
@@ -153975,13 +154837,23 @@
153975 pExpr = pNew;
153976 }
153977 }
153978 }else{
153979 if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
 
 
 
 
 
 
 
153980 pExpr->iTable = pSubst->iNewTable;
153981 }
153982 if( pExpr->op==TK_AGG_FUNCTION && pExpr->op2>=pSubst->nSelDepth ){
 
 
 
153983 pExpr->op2--;
153984 }
153985 pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
153986 pExpr->pRight = substExpr(pSubst, pExpr->pRight);
153987 if( ExprUseXSelect(pExpr) ){
@@ -154037,10 +154909,38 @@
154037 }
154038 }
154039 }while( doPrior && (p = p->pPrior)!=0 );
154040 pSubst->nSelDepth--;
154041 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154042 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
154043
154044 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
154045 /*
154046 ** pSelect is a SELECT statement and pSrcItem is one item in the FROM
@@ -154213,10 +155113,34 @@
154213 }
154214 return 0;
154215 }
154216
154217 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154218 /*
154219 ** This routine attempts to flatten subqueries as a performance optimization.
154220 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
154221 **
154222 ** To understand the concept of flattening, consider the following
@@ -154541,10 +155465,11 @@
154541 if( compoundHasDifferentAffinities(pSub) ) return 0;
154542
154543 if( pSrc->nSrc>1 ){
154544 if( pParse->nSelect>500 ) return 0;
154545 if( OptimizationDisabled(db, SQLITE_FlttnUnionAll) ) return 0;
 
154546 aCsrMap = sqlite3DbMallocZero(db, ((i64)pParse->nTab+1)*sizeof(int));
154547 if( aCsrMap ) aCsrMap[0] = pParse->nTab;
154548 }
154549 }
154550
@@ -154829,11 +155754,11 @@
154829 struct WhereConst {
154830 Parse *pParse; /* Parsing context */
154831 u8 *pOomFault; /* Pointer to pParse->db->mallocFailed */
154832 int nConst; /* Number for COLUMN=CONSTANT terms */
154833 int nChng; /* Number of times a constant is propagated */
154834 int bHasAffBlob; /* At least one column in apExpr[] as affinity BLOB */
154835 u32 mExcludeOn; /* Which ON expressions to exclude from considertion.
154836 ** Either EP_OuterON or EP_InnerON|EP_OuterON */
154837 Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */
154838 };
154839
@@ -154997,12 +155922,13 @@
154997 assert( TK_GE==TK_EQ+4 );
154998 if( pConst->bHasAffBlob ){
154999 if( (pExpr->op>=TK_EQ && pExpr->op<=TK_GE)
155000 || pExpr->op==TK_IS
155001 ){
155002 propagateConstantExprRewriteOne(pConst, pExpr->pLeft, 0);
155003 if( pConst->pOomFault[0] ) return WRC_Prune;
 
155004 if( sqlite3ExprAffinity(pExpr->pLeft)!=SQLITE_AFF_TEXT ){
155005 propagateConstantExprRewriteOne(pConst, pExpr->pRight, 0);
155006 }
155007 }
155008 }
@@ -155466,14 +156392,19 @@
155466 for(pX=pSub; pX; pX=pX->pPrior) {
155467 Expr *pY = pX->pEList->a[j].pExpr;
155468 if( pY->op==TK_NULL ) continue;
155469 pY->op = TK_NULL;
155470 ExprClearProperty(pY, EP_Skip|EP_Unlikely);
155471 pX->selFlags |= SF_PushDown;
155472 nChng++;
155473 }
155474 }
 
 
 
 
 
 
155475 return nChng;
155476 }
155477
155478
155479 /*
@@ -156447,10 +157378,11 @@
156447 pX->zEName = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
156448 pX->fg.eEName = ENAME_NAME;
156449 }else{
156450 pX->zEName = sqlite3DbStrDup(db, zName);
156451 pX->fg.eEName = ENAME_NAME;
 
156452 }
156453 }
156454 }
156455 if( !tableSeen ){
156456 if( zTName ){
@@ -156816,10 +157748,13 @@
156816 assert( pAggInfo->iFirstReg>0 );
156817 assert( pParse->db->pParse==pParse );
156818 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
156819 if( nReg==0 ) return;
156820 if( pParse->nErr ) return;
 
 
 
156821 sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->iFirstReg,
156822 pAggInfo->iFirstReg+nReg-1);
156823 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
156824 if( pFunc->iDistinct>=0 ){
156825 Expr *pE = pFunc->pFExpr;
@@ -157826,11 +158761,19 @@
157826 sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric,
157827 p->pOrderBy);
157828 testcase( pParse->earlyCleanup );
157829 p->pOrderBy = 0;
157830 }
157831 p->selFlags &= ~(u32)SF_Distinct;
 
 
 
 
 
 
 
 
157832 }
157833 sqlite3SelectPrep(pParse, p, 0);
157834 if( pParse->nErr ){
157835 goto select_end;
157836 }
@@ -157949,12 +158892,17 @@
157949 unsetJoinExpr(p->pWhere, pI2->iCursor, 1);
157950 }
157951 }
157952 }
157953 for(j=pTabList->nSrc-1; j>=0; j--){
157954 pTabList->a[j].fg.jointype &= ~JT_LTORJ;
157955 if( pTabList->a[j].fg.jointype & JT_RIGHT ) break;
 
 
 
 
 
157956 }
157957 }
157958 }
157959
157960 /* No further action if this term of the FROM clause is not a subquery */
@@ -158618,11 +159566,11 @@
158618 pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
158619 pAggInfo->pGroupBy = pGroupBy;
158620 sqlite3ExprAnalyzeAggList(&sNC, pEList);
158621 sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
158622 if( pHaving ){
158623 if( pGroupBy ){
158624 assert( pWhere==p->pWhere );
158625 assert( pHaving==p->pHaving );
158626 assert( pGroupBy==p->pGroupBy );
158627 havingToWhere(pParse, p);
158628 pWhere = p->pWhere;
@@ -159529,15 +160477,19 @@
159529
159530 /* If the trigger name was unqualified, and the table is a temp table,
159531 ** then set iDb to 1 to create the trigger in the temporary database.
159532 ** If sqlite3SrcListLookup() returns 0, indicating the table does not
159533 ** exist, the error is caught by the block below.
159534 */
159535 pTab = sqlite3SrcListLookup(pParse, pTableName);
159536 if( db->init.busy==0 && pName2->n==0 && pTab
159537 && pTab->pSchema==db->aDb[1].pSchema ){
159538 iDb = 1;
 
 
 
 
159539 }
159540
159541 /* Ensure the table name matches database name and that the table exists */
159542 if( db->mallocFailed ) goto trigger_cleanup;
159543 assert( pTableName->nSrc==1 );
@@ -159564,11 +160516,12 @@
159564 zName = sqlite3NameFromToken(db, pName);
159565 if( zName==0 ){
159566 assert( db->mallocFailed );
159567 goto trigger_cleanup;
159568 }
159569 if( sqlite3CheckObjectName(pParse, zName, "trigger", pTab->zName) ){
 
159570 goto trigger_cleanup;
159571 }
159572 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
159573 if( !IN_RENAME_OBJECT ){
159574 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
@@ -159706,10 +160659,11 @@
159706 if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
159707 zName = pTrig->zName;
159708 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
159709 assert( iDb>=00 && iDb<db->nDb );
159710 pTrig->step_list = pStepList;
 
159711 for(n=0; pStepList; n++){
159712 pStepList->pTrig = pTrig;
159713 pStepList = pStepList->pNext;
159714 }
159715 if( n>pParse->db->aLimit[SQLITE_LIMIT_TRIGGER_STEPS] ){
@@ -159739,16 +160693,19 @@
159739 Vdbe *v;
159740 char *z;
159741
159742 /* If this is a new CREATE TABLE statement, and if shadow tables
159743 ** are read-only, and the trigger makes a change to a shadow table,
159744 ** then raise an error - do not allow the trigger to be created. */
 
 
159745 if( sqlite3ReadOnlyShadowTables(db) ){
159746 TriggerStep *pStep;
 
159747 for(pStep=pTrig->step_list; pStep; pStep=pStep->pNext){
159748 if( pStep->pSrc!=0
159749 && sqlite3ShadowTableName(db, pStep->pSrc->a[0].zName)
159750 ){
159751 sqlite3ErrorMsg(pParse,
159752 "trigger \"%s\" may not write to shadow table \"%s\"",
159753 pTrig->zName, pStep->pSrc->a[0].zName);
159754 goto triggerfinish_cleanup;
@@ -160656,10 +161613,11 @@
160656 memset(&sNC, 0, sizeof(sNC));
160657 sNC.pParse = &sSubParse;
160658 sSubParse.pTriggerTab = pTab;
160659 sSubParse.pToplevel = pTop;
160660 sSubParse.pTrigCoded = pTrigger;
 
160661 sSubParse.zAuthContext = pTrigger->zName;
160662 sSubParse.eTriggerOp = pTrigger->op;
160663 sSubParse.nQueryLoop = pParse->nQueryLoop;
160664 sSubParse.prepFlags = pParse->prepFlags;
160665 sSubParse.oldmask = 0;
@@ -164628,10 +165586,11 @@
164628 struct InLoop {
164629 int iCur; /* The VDBE cursor used by this IN operator */
164630 int addrInTop; /* Top of the IN loop */
164631 int iBase; /* Base register of multi-key index record */
164632 int nPrefix; /* Number of prior entries in the key */
 
164633 u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
164634 } *aInLoop; /* Information about each nested IN operator */
164635 } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
164636 Index *pCoveringIdx; /* Possible covering index for WHERE_MULTI_OR */
164637 } u;
@@ -165937,10 +166896,11 @@
165937 sqlite3WhereRealloc(pTerm->pWC->pWInfo,
165938 pLevel->u.in.aInLoop,
165939 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
165940 pIn = pLevel->u.in.aInLoop;
165941 if( pIn ){
 
165942 int iMap = 0; /* Index in aiMap[] */
165943 pIn += i;
165944 for(i=iEq; i<pLoop->nLTerm; i++){
165945 if( pLoop->aLTerm[i]->pExpr==pX ){
165946 int iOut = iTarget + i - iEq;
@@ -165948,13 +166908,14 @@
165948 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
165949 }else{
165950 int iCol = aiMap ? aiMap[iMap++] : 0;
165951 pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
165952 }
165953 sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
165954 if( i==iEq ){
165955 pIn->iCur = iTab;
 
165956 pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
165957 if( iEq>0 ){
165958 pIn->iBase = iTarget - i;
165959 pIn->nPrefix = i;
165960 }else{
@@ -166924,10 +167885,11 @@
166924 */
166925 int iReg; /* P3 Value for OP_VFilter */
166926 int addrNotFound;
166927 int nConstraint = pLoop->nLTerm;
166928
 
166929 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
166930 addrNotFound = pLevel->addrBrk;
166931 for(j=0; j<nConstraint; j++){
166932 int iTarget = iReg+j+2;
166933 pTerm = pLoop->aLTerm[j];
@@ -167297,10 +168259,11 @@
167297 ** index entries for which the column is null and for those for which
167298 ** it is not. For an ASC sort, the non-NULL entries are scanned first.
167299 ** For DESC, NULL entries are scanned first.
167300 */
167301 if( (pLoop->wsFlags & (WHERE_TOP_LIMIT|WHERE_BTM_LIMIT))==0
 
167302 && (pLoop->wsFlags & WHERE_BIGNULL_SORT)!=0
167303 ){
167304 assert( bSeekPastNull==0 && nExtraReg==0 && nBtm==0 && nTop==0 );
167305 assert( pRangeEnd==0 && pRangeStart==0 );
167306 testcase( pLoop->nSkip>0 );
@@ -168512,10 +169475,47 @@
168512 assert( op!=TK_GE || c==WO_GE );
168513 assert( op!=TK_IS || c==WO_IS );
168514 return c;
168515 }
168516
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168517
168518 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
168519 /*
168520 ** Check to see if the given expression is a LIKE or GLOB operator that
168521 ** can be optimized using inequality constraints. Return TRUE if it is
@@ -168567,11 +169567,11 @@
168567 }
168568 sqlite3VdbeReprepareOnBind(pParse->pVdbe, iCol, 0);
168569 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
168570 }else if( op==TK_STRING ){
168571 assert( !ExprHasProperty(pRight, EP_IntValue) );
168572 z = (u8*)pRight->u.zToken;
168573 }
168574 if( z ){
168575 /* Count the number of prefix bytes prior to the first wildcard,
168576 ** U+fffd character, or malformed utf-8. If the underlying database
168577 ** has a UTF16LE encoding, then only consider ASCII characters. Note that
@@ -168583,27 +169583,40 @@
168583 cnt++;
168584 if( c==wc[3] && z[cnt]>0 && z[cnt]<0x80 ){
168585 cnt++;
168586 }else if( c>=0x80 ){
168587 const u8 *z2 = z+cnt-1;
168588 if( c==0xff || sqlite3Utf8Read(&z2)==0xfffd /* bad utf-8 */
168589 || ENC(db)==SQLITE_UTF16LE
 
 
 
168590 ){
 
 
 
 
 
 
 
 
 
 
168591 cnt--;
168592 break;
168593 }else{
168594 cnt = (int)(z2-z);
168595 }
168596 }
168597 }
168598
168599 /* The optimization is possible only if (1) the pattern does not begin
168600 ** with a wildcard and if (2) the non-wildcard prefix does not end with
168601 ** an (illegal 0xff) character, or (3) the pattern does not consist of
168602 ** a single escape character. The second condition is necessary so
168603 ** that we can increment the prefix key to find an upper bound for the
168604 ** range search. The third is because the caller assumes that the pattern
168605 ** consists of at least one character after all escapes have been
168606 ** removed. */
168607 if( (cnt>1 || (cnt>0 && z[0]!=wc[3])) && ALWAYS(255!=(u8)z[cnt-1]) ){
168608 Expr *pPrefix;
168609
@@ -168625,41 +169638,41 @@
168625 zNew[iTo] = 0;
168626 assert( iTo>0 );
168627
168628 /* If the LHS is not an ordinary column with TEXT affinity, then the
168629 ** pattern prefix boundaries (both the start and end boundaries) must
168630 ** not look like a number. Otherwise the pattern might be treated as
168631 ** a number, which will invalidate the LIKE optimization.
 
 
 
168632 **
168633 ** Getting this right has been a persistent source of bugs in the
168634 ** LIKE optimization. See, for example:
168635 ** 2018-09-10 https://sqlite.org/src/info/c94369cae9b561b1
168636 ** 2019-05-02 https://sqlite.org/src/info/b043a54c3de54b28
168637 ** 2019-06-10 https://sqlite.org/src/info/fd76310a5e843e07
168638 ** 2019-06-14 https://sqlite.org/src/info/ce8717f0885af975
168639 ** 2019-09-03 https://sqlite.org/src/info/0f0428096f17252a
 
168640 */
168641 if( pLeft->op!=TK_COLUMN
168642 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
168643 || (ALWAYS( ExprUseYTab(pLeft) )
168644 && ALWAYS(pLeft->y.pTab)
168645 && IsVirtual(pLeft->y.pTab)) /* Might be numeric */
168646 ){
168647 int isNum;
168648 double rDummy;
168649 assert( zNew[iTo]==0 );
168650 isNum = sqlite3AtoF(zNew, &rDummy);
168651 if( isNum<=0 ){
168652 if( iTo==1 && zNew[0]=='-' ){
168653 isNum = +1;
168654 }else{
168655 zNew[iTo-1]++;
168656 isNum = sqlite3AtoF(zNew, &rDummy);
168657 zNew[iTo-1]--;
168658 }
168659 }
168660 if( isNum>0 ){
168661 sqlite3ExprDelete(db, pPrefix);
168662 sqlite3ValueFree(pVal);
168663 return 0;
168664 }
168665 }
@@ -168920,11 +169933,17 @@
168920 Expr *pNew; /* New virtual expression */
168921 int op; /* Operator for the combined expression */
168922 int idxNew; /* Index in pWC of the next virtual term */
168923 Expr *pA, *pB; /* Expressions associated with pOne and pTwo */
168924
168925 if( (pOne->wtFlags | pTwo->wtFlags) & TERM_VNULL ) return;
 
 
 
 
 
 
168926 if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
168927 if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
168928 if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
168929 && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
168930 pA = pOne->pExpr;
@@ -169881,11 +170900,11 @@
169881 ** used by each such virtual term is pExpr (the full vector IN(...)
169882 ** expression). The WhereTerm.u.x.iField variable identifies the index within
169883 ** the vector on the LHS that the virtual term represents.
169884 **
169885 ** This only works if the RHS is a simple SELECT (not a compound) that does
169886 ** not use window functions.
169887 */
169888 else if( pExpr->op==TK_IN
169889 && pTerm->u.x.iField==0
169890 && pExpr->pLeft->op==TK_VECTOR
169891 && ALWAYS( ExprUseXSelect(pExpr) )
@@ -169892,10 +170911,12 @@
169892 && (pExpr->x.pSelect->pPrior==0 || (pExpr->x.pSelect->selFlags & SF_Values))
169893 #ifndef SQLITE_OMIT_WINDOWFUNC
169894 && pExpr->x.pSelect->pWin==0
169895 #endif
169896 && (pExpr->x.pSelect->selFlags & SF_MinMaxAgg)==0
 
 
169897 && pWC->op==TK_AND
169898 && pExpr->x.pSelect->pEList->nExpr <= UMXV(pTerm->nChild)
169899 /* ^-- See bug 2026-06-04T10:00:49Z */
169900 ){
169901 int i;
@@ -170574,18 +171595,20 @@
170574 return 0;
170575 }
170576 }
170577 if( pSet->n<N_OR_COST ){
170578 p = &pSet->a[pSet->n++];
170579 p->nOut = nOut;
170580 }else{
 
 
170581 p = pSet->a;
170582 for(i=1; i<pSet->n; i++){
170583 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
170584 }
170585 if( p->rRun<=rRun ) return 0;
170586 }
 
170587 whereOrInsert_done:
170588 p->prereq = prereq;
170589 p->rRun = rRun;
170590 if( p->nOut>nOut ) p->nOut = nOut;
170591 return 1;
@@ -170697,10 +171720,33 @@
170697 CollSeq *pRet = sqlite3ExprCompareCollSeq(pParse, pX);
170698 return pRet ? pRet->zName : sqlite3StrBINARY;
170699 }
170700 return 0;
170701 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170702
170703 /*
170704 ** Advance to the next WhereTerm that matches according to the criteria
170705 ** established when the pScan object was initialized by whereScanInit().
170706 ** Return NULL if there are no more matching WhereTerms.
@@ -170731,10 +171777,11 @@
170731 && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_OuterON))
170732 ){
170733 if( (pTerm->eOperator & WO_EQUIV)!=0
170734 && pScan->nEquiv<ArraySize(pScan->aiCur)
170735 && (pX = whereRightSubexprIsColumn(pTerm->pExpr))!=0
 
170736 ){
170737 int j;
170738 for(j=0; j<pScan->nEquiv; j++){
170739 if( pScan->aiCur[j]==pX->iTable
170740 && pScan->aiColumn[j]==pX->iColumn ){
@@ -170761,11 +171808,23 @@
170761 CollSeq *pColl;
170762 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
170763 continue;
170764 }
170765 assert(pX->pLeft);
170766 pColl = sqlite3ExprCompareCollSeq(pParse, pX);
 
 
 
 
 
 
 
 
 
 
 
 
170767 zCollName = pColl ? pColl->zName : sqlite3StrBINARY;
170768 }
170769
170770 if( sqlite3StrICmp(zCollName, pScan->zCollName) ){
170771 continue;
@@ -171360,11 +172419,13 @@
171360 int mxBitCol; /* Maximum column in pSrc->colUsed */
171361 CollSeq *pColl; /* Collating sequence to on a column */
171362 WhereLoop *pLoop; /* The Loop object */
171363 char *zNotUsed; /* Extra space on the end of pIdx */
171364 Bitmask idxCols; /* Bitmap of columns used for indexing */
 
171365 Bitmask extraCols; /* Bitmap of additional columns */
 
171366 u8 sentWarning = 0; /* True if a warning has been issued */
171367 u8 useBloomFilter = 1; /* True to also add a Bloom filter */
171368 Expr *pPartial = 0; /* Partial Index Expression */
171369 int iContinue = 0; /* Jump here to skip excluded rows */
171370 SrcList *pTabList; /* The complete FROM clause */
@@ -171388,10 +172449,11 @@
171388 pSrc = &pTabList->a[pLevel->iFrom];
171389 pTable = pSrc->pSTab;
171390 pWCEnd = &pWC->a[pWC->nTerm];
171391 pLoop = pLevel->pWLoop;
171392 idxCols = 0;
 
171393 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
171394 Expr *pExpr = pTerm->pExpr;
171395 /* Make the automatic index a partial index if there are terms in the
171396 ** WHERE clause (or the ON clause of a LEFT join) that constrain which
171397 ** rows of the target table (pSrc) that can be used. */
@@ -171419,10 +172481,29 @@
171419 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
171420 goto end_auto_index_create;
171421 }
171422 pLoop->aLTerm[nKeyCol++] = pTerm;
171423 idxCols |= cMask;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171424 }
171425 }
171426 }
171427 assert( nKeyCol>0 || pParse->db->mallocFailed );
171428 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
@@ -171440,35 +172521,38 @@
171440 if( IsView(pTable) ){
171441 extraCols = ALLBITS & ~idxCols;
171442 }else{
171443 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
171444 }
 
171445 if( !HasRowid(pTable) ){
171446 /* For WITHOUT ROWID tables, ensure that all PRIMARY KEY columns are
171447 ** either in the idxCols mask or in the extraCols mask */
 
 
171448 for(i=0; i<pTable->nCol; i++){
171449 if( (pTable->aCol[i].colFlags & COLFLAG_PRIMKEY)==0 ) continue;
171450 if( i>=BMS-1 ){
171451 extraCols |= MASKBIT(BMS-1);
171452 break;
171453 }
171454 if( idxCols & MASKBIT(i) ) continue;
171455 extraCols |= MASKBIT(i);
171456 }
171457 }
171458 mxBitCol = MIN(BMS-1,pTable->nCol);
171459 testcase( pTable->nCol==BMS-1 );
171460 testcase( pTable->nCol==BMS-2 );
171461 for(i=0; i<mxBitCol; i++){
171462 if( extraCols & MASKBIT(i) ) nKeyCol++;
171463 }
171464 if( pSrc->colUsed & MASKBIT(BMS-1) ){
171465 nKeyCol += pTable->nCol - BMS + 1;
171466 }
171467
171468 /* Construct the Index object to describe this index */
171469 assert( nKeyCol <= pTable->nCol + MAX(0, pTable->nCol - BMS + 1) );
171470 /* ^-- This guarantees that the number of index columns will fit in the u16 */
171471 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+HasRowid(pTable),
171472 0, &zNotUsed);
171473 if( pIdx==0 ) goto end_auto_index_create;
171474 pLoop->u.btree.pIndex = pIdx;
@@ -171488,11 +172572,11 @@
171488 if( (idxCols & cMask)==0 ){
171489 Expr *pX = pTerm->pExpr;
171490 idxCols |= cMask;
171491 pIdx->aiColumn[n] = pTerm->u.x.leftColumn;
171492 pColl = sqlite3ExprCompareCollSeq(pParse, pX);
171493 assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */
171494 if( !sqlite3IsBinary(pColl) ){
171495 /* Disallow the use of a Bloom filter if any non-BINARY collating
171496 ** sequence is involved. tag-202607231411 */
171497 useBloomFilter = 0;
171498 }
@@ -171510,11 +172594,11 @@
171510 pIdx->aiColumn[n] = i;
171511 pIdx->azColl[n] = sqlite3StrBINARY;
171512 n++;
171513 }
171514 }
171515 if( pSrc->colUsed & MASKBIT(BMS-1) ){
171516 for(i=BMS-1; i<pTable->nCol; i++){
171517 pIdx->aiColumn[n] = i;
171518 pIdx->azColl[n] = sqlite3StrBINARY;
171519 n++;
171520 }
@@ -174113,13 +175197,43 @@
174113 */
174114 typedef struct CoveringIndexCheck CoveringIndexCheck;
174115 struct CoveringIndexCheck {
174116 Index *pIdx; /* The index */
174117 int iTabCur; /* Cursor number for the corresponding table */
 
174118 u8 bExpr; /* Uses an indexed expression */
174119 u8 bUnidx; /* Uses an unindexed column not within an indexed expr */
174120 };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174121
174122 /*
174123 ** Information passed in is pWalk->u.pCovIdxCk. Call it pCk.
174124 **
174125 ** If the Expr node references the table with cursor pCk->iTabCur, then
@@ -174143,10 +175257,13 @@
174143 u16 nColumn; /* Number of columns in the index */
174144 CoveringIndexCheck *pCk; /* Info about this search */
174145
174146 pCk = pWalk->u.pCovIdxCk;
174147 pIdx = pCk->pIdx;
 
 
 
174148 if( (pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN) ){
174149 /* if( pExpr->iColumn<(BMS-1) && pIdx->bHasExpr==0 ) return WRC_Continue;*/
174150 if( pExpr->iTable!=pCk->iTabCur ) return WRC_Continue;
174151 pIdx = pWalk->u.pCovIdxCk->pIdx;
174152 aiColumn = pIdx->aiColumn;
@@ -174169,10 +175286,16 @@
174169 ** pIdx is an index that covers all of the low-number columns used by
174170 ** pWInfo->pSelect (columns from 0 through 62) or an index that has
174171 ** expressions terms. Hence, we cannot determine whether or not it is
174172 ** a covering index by using the colUsed bitmasks. We have to do a search
174173 ** to see if the index is covering. This routine does that search.
 
 
 
 
 
 
174174 **
174175 ** The return value is one of these:
174176 **
174177 ** 0 The index is definitely not a covering index
174178 **
@@ -174189,21 +175312,22 @@
174189 ** returned can lead to incorrect bytecode and assertion faults.
174190 */
174191 static SQLITE_NOINLINE u32 whereIsCoveringIndex(
174192 WhereInfo *pWInfo, /* The WHERE clause context */
174193 Index *pIdx, /* Index that is being tested */
174194 int iTabCur /* Cursor for the table being indexed */
 
174195 ){
174196 int i, rc;
174197 struct CoveringIndexCheck ck;
174198 Walker w;
174199 if( pWInfo->pSelect==0 ){
174200 /* We don't have access to the full query, so we cannot check to see
174201 ** if pIdx is covering. Assume it is not. */
174202 return 0;
174203 }
174204 if( pIdx->bHasExpr==0 ){
174205 for(i=0; i<pIdx->nColumn; i++){
174206 if( pIdx->aiColumn[i]>=BMS-1 ) break;
174207 }
174208 if( i>=pIdx->nColumn ){
174209 /* pIdx does not index any columns greater than 62, but we know from
@@ -174212,10 +175336,11 @@
174212 return 0;
174213 }
174214 }
174215 ck.pIdx = pIdx;
174216 ck.iTabCur = iTabCur;
 
174217 ck.bExpr = 0;
174218 ck.bUnidx = 0;
174219 memset(&w, 0, sizeof(w));
174220 w.xExprCallback = whereIsCoveringIndexWalkCallback;
174221 w.xSelectCallback = sqlite3SelectWalkNoop;
@@ -174563,10 +175688,11 @@
174563 rc = whereLoopInsert(pBuilder, pNew);
174564 pNew->nOut = rSize;
174565 if( rc ) break;
174566 }else{
174567 Bitmask m;
 
174568 if( pProbe->isCovering ){
174569 m = 0;
174570 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
174571 }else{
174572 m = pSrc->colUsed & pProbe->colNotIdxed;
@@ -174574,14 +175700,34 @@
174574 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
174575 ){
174576 wherePartIdxExpr(
174577 pWInfo->pParse, pProbe, pProbe->pPartIdxWhere, &m, 0, 0
174578 );
 
 
 
 
 
 
 
 
 
174579 }
174580 pNew->wsFlags = WHERE_INDEXED;
174581 if( m==TOPBIT || (pProbe->bHasExpr && !pProbe->bHasVCol && m!=0) ){
174582 u32 isCov = whereIsCoveringIndex(pWInfo, pProbe, pSrc->iCursor);
 
 
 
 
 
 
 
 
 
 
 
174583 if( isCov==0 ){
174584 WHERETRACE(0x200,
174585 ("-> %s is not a covering index"
174586 " according to whereIsCoveringIndex()\n", pProbe->zName));
174587 assert( m!=0 );
@@ -174597,17 +175743,10 @@
174597 WHERETRACE(0x200,
174598 ("-> %s might be a covering expression index"
174599 " according to whereIsCoveringIndex()\n", pProbe->zName));
174600 }
174601 }
174602 }else if( m==0
174603 && (HasRowid(pTab) || pWInfo->pSelect!=0 || sqlite3FaultSim(700))
174604 ){
174605 WHERETRACE(0x200,
174606 ("-> %s is a covering index according to bitmasks\n",
174607 pProbe->zName, m==0 ? "is" : "is not"));
174608 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
174609 }
174610 }
174611
174612 /* Full scan via index */
174613 if( b
@@ -175445,21 +176584,19 @@
175445 ** long as the subquery ORDER BY does the same. But if the
175446 ** outer ORDER BY uses COLLATE, even a redundant COLLATE, the
175447 ** optimization is bypassed.
175448 **
175449 ** (2) The subquery ORDER BY terms must exactly match subquery result
175450 ** columns, including any COLLATE annotations. This routine relies
175451 ** on iOrderByCol to do matching between order by terms and result
175452 ** columns, and iOrderByCol will not be set if the result column
175453 ** and ORDER BY collations differ.
175454 **
175455 ** (3) The subquery and outer ORDER BY can be in opposite directions as
175456 ** long as the subquery is materialized. If the subquery is
175457 ** implemented as a co-routine, the sort orders must be in the same
175458 ** direction because there is no way to run a co-routine backwards.
175459 */
175460 static SQLITE_NOINLINE int wherePathMatchSubqueryOB(
 
175461 WhereLoop *pLoop, /* The nested loop term that is a subquery */
175462 int iLoop, /* Which level of the nested loop. 0==outermost */
175463 int iCur, /* Cursor used by the this loop */
175464 ExprList *pOrderBy, /* The ORDER BY clause on the whole query */
175465 Bitmask *pRevMask, /* When loops need to go in reverse order */
@@ -175475,18 +176612,20 @@
175475
175476 pSubOB = pLoop->u.btree.pOrderBy;
175477 assert( pSubOB!=0 );
175478 for(iOB=0; (MASKBIT(iOB) & *pOBSat)!=0; iOB++){}
175479 for(jSub=0; jSub<pSubOB->nExpr && iOB<pOrderBy->nExpr; jSub++, iOB++){
175480 if( pSubOB->a[jSub].u.x.iOrderByCol==0 ) break;
 
175481 pOBExpr = pOrderBy->a[iOB].pExpr;
175482 if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) break;
175483 if( pOBExpr->iTable!=iCur ) break;
175484 if( pOBExpr->iColumn!=pSubOB->a[jSub].u.x.iOrderByCol-1 ) break;
 
175485 if( (wctrlFlags & WHERE_GROUPBY)==0 ){
175486 u8 sfOB = pOrderBy->a[iOB].fg.sortFlags; /* sortFlags for iOB */
175487 u8 sfSub = pSubOB->a[jSub].fg.sortFlags; /* sortFlags for jSub */
175488 if( (sfSub & KEYINFO_ORDER_BIGNULL) != (sfOB & KEYINFO_ORDER_BIGNULL) ){
175489 break;
175490 }
175491 revIdx = sfSub & KEYINFO_ORDER_DESC;
175492 if( jSub>0 ){
@@ -175662,11 +176801,11 @@
175662
175663 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
175664 if( pLoop->wsFlags & WHERE_IPK ){
175665 if( pLoop->u.btree.pOrderBy
175666 && OptimizationEnabled(db, SQLITE_OrderBySubq)
175667 && wherePathMatchSubqueryOB(pLoop,iLoop,iCur,
175668 pOrderBy,pRevMask, &obSat, wctrlFlags)
175669 ){
175670 nColumn = 0;
175671 isOrderDistinct = 0;
175672 }else{
@@ -176158,11 +177297,11 @@
176158 for(pWLoop=pStart; pWLoop; pWLoop=pWLoop->pNextLoop){
176159 if( pWLoop->iTab<iFromIdx ) continue;
176160 if( pWLoop->iTab>iFromIdx ) break;
176161 if( pWLoop->rRun>mxRun ) mxRun = pWLoop->rRun;
176162 }
176163 if( ALWAYS(mxRun<LOGEST_MAX) ) mxRun++;
176164
176165 /* Increase the cost of table scans for dimension tables to be
176166 ** slightly more than the maximum cost of the fact table */
176167 for(pWLoop=pStart; pWLoop; pWLoop=pWLoop->pNextLoop){
176168 if( (pWLoop->maskSelf & mSeen)==0 ) continue;
@@ -178053,46 +179192,46 @@
178053 #endif
178054 if( (pLoop->wsFlags & WHERE_IN_ABLE)!=0 && pLevel->u.in.nIn>0 ){
178055 struct InLoop *pIn;
178056 int j;
178057 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
178058 assert( sqlite3VdbeGetOp(v, pIn->addrInTop+1)->opcode==OP_IsNull
178059 || pParse->db->mallocFailed );
178060 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
178061 if( pIn->eEndLoopOp!=OP_Noop ){
178062 if( pIn->nPrefix ){
178063 int bEarlyOut =
178064 (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
178065 && (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0;
178066 if( pLevel->iLeftJoin ){
178067 /* For LEFT JOIN queries, cursor pIn->iCur might have been
178068 ** disabled by OP_NullRow. This occurs for WHERE clauses such
178069 ** as "a = ? AND b IN (...)", where the index is on (a, b).
178070 ** When the OP_IfNullRow jump is taken, the pIn->iBase register
178071 ** is NULLed out as a side effect. But as that register is not
178072 ** used when the jump is taken, the side-effect is harmless. */
178073 sqlite3VdbeAddOp3(v, OP_IfNullRow, pIn->iCur,
178074 sqlite3VdbeCurrentAddr(v) + 2 + bEarlyOut, pIn->iBase);
178075 VdbeCoverage(v);
178076 }
178077 if( bEarlyOut ){
178078 sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
178079 sqlite3VdbeCurrentAddr(v)+2,
178080 pIn->iBase, pIn->nPrefix);
178081 VdbeCoverage(v);
178082 /* Retarget the OP_IsNull against the left operand of IN so
178083 ** it jumps past the OP_IfNoHope. This is because the
178084 ** OP_IsNull also bypasses the OP_Affinity opcode that is
178085 ** required by OP_IfNoHope. */
178086 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
178087 }
178088 }
178089 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
178090 VdbeCoverage(v);
178091 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
178092 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
178093 }
178094 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
178095 }
178096 }
178097 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
178098 if( pLevel->pRJ ){
@@ -178140,10 +179279,20 @@
178140 if( pIn->eEndLoopOp!=OP_Noop ){
178141 sqlite3VdbeAddOp1(v, OP_NullRow, pIn->iCur);
178142 }
178143 }
178144 }
 
 
 
 
 
 
 
 
 
 
178145 if( pLevel->op==OP_Return ){
178146 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
178147 }else{
178148 sqlite3VdbeGoto(v, pLevel->addrFirst);
178149 }
@@ -179744,10 +180893,11 @@
179744 assert( pSelect->pSrc->a[0].fg.isSubquery );
179745 nEphExpr = pSelect->pSrc->a[0].u4.pSubq->pSelect->pEList->nExpr;
179746 pMWin = pSelect->pWin;
179747 v = sqlite3GetVdbe(pParse);
179748
 
179749 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr);
179750 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
179751 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
179752 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
179753
@@ -180438,17 +181588,21 @@
180438 **
180439 ** If the sort-order for the ORDER BY term in the window is DESC, then the
180440 ** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is
180441 ** subtracted. And the comparison operator is inverted to - ">=" becomes "<=",
180442 ** ">" becomes "<", and so on. So, with DESC sort order, if the argument op
180443 ** is OP_Ge, the generated code is equivalent to:
180444 **
180445 ** if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;
180446 **
180447 ** A special type of arithmetic is used such that if csr1.peerVal is not
180448 ** a numeric type (real or integer), then the result of the addition
180449 ** or subtraction is a a copy of csr1.peerVal.
 
 
 
 
180450 */
180451 static void windowCodeRangeTest(
180452 WindowCodeArg *p,
180453 int op, /* OP_Ge, OP_Gt, or OP_Le */
180454 int csr1, /* Cursor number for cursor 1 */
@@ -180460,11 +181614,12 @@
180460 Vdbe *v = sqlite3GetVdbe(pParse);
180461 ExprList *pOrderBy = p->pMWin->pOrderBy; /* ORDER BY clause for window */
180462 int reg1 = sqlite3GetTempReg(pParse); /* Reg. for csr1.peerVal+regVal */
180463 int reg2 = sqlite3GetTempReg(pParse); /* Reg. for csr2.peerVal */
180464 int regString = ++pParse->nMem; /* Reg. for constant value '' */
180465 int arith = OP_Add; /* OP_Add or OP_Subtract */
 
180466 int addrGe; /* Jump destination */
180467 int addrDone = sqlite3VdbeMakeLabel(pParse); /* Address past OP_Ge */
180468 CollSeq *pColl;
180469
180470 /* Read the peer-value from each cursor into a register */
@@ -180477,16 +181632,18 @@
180477 switch( op ){
180478 case OP_Ge: op = OP_Le; break;
180479 case OP_Gt: op = OP_Lt; break;
180480 default: assert( op==OP_Le ); op = OP_Ge; break;
180481 }
180482 arith = OP_Subtract;
 
180483 }
180484
180485 VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl",
180486 reg1, (arith==OP_Add ? "+" : "-"), regVal,
180487 ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2
 
180488 ));
180489
180490 /* If the BIGNULL flag is set for the ORDER BY, then it is required to
180491 ** consider NULL values to be larger than all other values, instead of
180492 ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this
@@ -180530,30 +181687,31 @@
180530 sqlite3VdbeAddOp2(v, OP_IsNull, reg2,
180531 (op==OP_Gt || op==OP_Ge) ? addrDone : lbl);
180532 VdbeCoverage(v);
180533 }
180534
180535 /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).
180536 ** This block adds (or subtracts for DESC) the numeric value in regVal
180537 ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob),
180538 ** then leave reg1 as it is. In pseudo-code, this is implemented as:
 
180539 **
180540 ** if( reg1>='' ) goto addrGe;
180541 ** reg1 = reg1 +/- regVal
180542 ** addrGe:
180543 **
180544 ** Since all strings and blobs are greater-than-or-equal-to an empty string,
180545 ** the add/subtract is skipped for these, as required. If reg1 is a NULL,
180546 ** then the arithmetic is performed, but since adding or subtracting from
180547 ** NULL is always NULL anyway, this case is handled as required too. */
180548 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
180549 addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
180550 VdbeCoverage(v);
180551 if( (op==OP_Ge && arith==OP_Add) || (op==OP_Le && arith==OP_Subtract) ){
180552 sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
180553 }
180554 sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
180555 sqlite3VdbeJumpHere(v, addrGe);
180556
180557 /* Compare registers reg2 and reg1, taking the jump if required. Note that
180558 ** control skips over this test if the BIGNULL flag is set and either
180559 ** reg1 or reg2 contain a NULL value. */
@@ -185801,13 +186959,12 @@
185801 {
185802 yylhsminor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0);
185803 if( yylhsminor.yy203 ){
185804 if( IN_RENAME_OBJECT ){
185805 sqlite3RenameTokenMap(pParse, yylhsminor.yy203->a[0].zName, &yymsp[-2].minor.yy0);
185806 }else{
185807 yylhsminor.yy203->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
185808 }
 
185809 }
185810 }
185811 yymsp[-2].minor.yy203 = yylhsminor.yy203;
185812 break;
185813 case 123: /* xfullname ::= nm DOT nm AS nm */
@@ -185814,13 +186971,12 @@
185814 {
185815 yylhsminor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0);
185816 if( yylhsminor.yy203 ){
185817 if( IN_RENAME_OBJECT ){
185818 sqlite3RenameTokenMap(pParse, yylhsminor.yy203->a[0].zName, &yymsp[-2].minor.yy0);
185819 }else{
185820 yylhsminor.yy203->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
185821 }
 
185822 }
185823 }
185824 yymsp[-4].minor.yy203 = yylhsminor.yy203;
185825 break;
185826 case 124: /* joinop ::= COMMA|JOIN */
@@ -186267,23 +187423,23 @@
186267 ** Except, do not apply this optimization if expr1 contains a function
186268 ** because that function might be an aggregate (we don't know yet whether
186269 ** it is or not) and if it is an aggregate, that could change the meaning
186270 ** of the whole query.
186271 */
186272 Expr *pB = sqlite3Expr(pParse->db, TK_STRING, yymsp[-3].minor.yy144 ? "true" : "false");
186273 if( pB ) sqlite3ExprIdToTrueFalse(pB);
186274 if( !ExprHasProperty(yymsp[-4].minor.yy454, EP_HasFunc) ){
 
186275 sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy454);
186276 yymsp[-4].minor.yy454 = pB;
186277 }else{
186278 yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, yymsp[-3].minor.yy144 ? TK_OR : TK_AND, pB, yymsp[-4].minor.yy454);
186279 }
186280 }else{
186281 Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
186282 if( yymsp[-1].minor.yy14->nExpr==1
186283 && sqlite3ExprIsConstant(pParse,pRHS)
186284 && pRHS->op!=TK_COLLATE
186285 && yymsp[-4].minor.yy454->op!=TK_VECTOR
186286 ){
186287 yymsp[-1].minor.yy14->a[0].pExpr = 0;
186288 sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
186289 pRHS = sqlite3PExpr(pParse, TK_UPLUS, pRHS, 0);
@@ -186328,10 +187484,13 @@
186328 break;
186329 case 226: /* expr ::= expr in_op nm dbnm paren_exprlist */
186330 {
186331 SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
186332 Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
 
 
 
186333 if( yymsp[0].minor.yy14 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy14);
186334 yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy454, 0);
186335 sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy454, pSelect);
186336 if( yymsp[-3].minor.yy144 ) yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy454, 0);
186337 }
@@ -190096,10 +191255,13 @@
190096 { SQLITE_DBCONFIG_STMT_SCANSTATUS, SQLITE_StmtScanStatus },
190097 { SQLITE_DBCONFIG_REVERSE_SCANORDER, SQLITE_ReverseOrder },
190098 { SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE, SQLITE_AttachCreate },
190099 { SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE, SQLITE_AttachWrite },
190100 { SQLITE_DBCONFIG_ENABLE_COMMENTS, SQLITE_Comments },
 
 
 
190101 };
190102 unsigned int i;
190103 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
190104 for(i=0; i<ArraySize(aFlagOp); i++){
190105 if( aFlagOp[i].op==op ){
@@ -190366,10 +191528,13 @@
190366 return SQLITE_OK;
190367 }
190368 if( !sqlite3SafetyCheckSickOrOk(db) ){
190369 return SQLITE_MISUSE_BKPT;
190370 }
 
 
 
190371 sqlite3_mutex_enter(db->mutex);
190372 if( db->mTrace & SQLITE_TRACE_CLOSE ){
190373 db->trace.xV2(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
190374 }
190375
@@ -193607,11 +194772,11 @@
193607 case SQLITE_TESTCTRL_BYTEORDER: {
193608 rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
193609 break;
193610 }
193611
193612 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
193613 **
193614 ** Enable or disable various optimizations for testing purposes. The
193615 ** argument N is a bitmask of optimizations to be disabled. For normal
193616 ** operation N should be 0. The idea is that a test program (like the
193617 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
@@ -193618,22 +194783,22 @@
193618 ** with various optimizations disabled to verify that the same answer
193619 ** is obtained in every case.
193620 */
193621 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
193622 sqlite3 *db = va_arg(ap, sqlite3*);
193623 db->dbOptFlags = va_arg(ap, u32);
193624 break;
193625 }
193626
193627 /* sqlite3_test_control(SQLITE_TESTCTRL_GETOPT, sqlite3 *db, int *N)
193628 **
193629 ** Write the current optimization settings into *N. A zero bit means that
193630 ** the optimization is on, and a 1 bit means that the optimization is off.
193631 */
193632 case SQLITE_TESTCTRL_GETOPT: {
193633 sqlite3 *db = va_arg(ap, sqlite3*);
193634 int *pN = va_arg(ap, int*);
193635 *pN = db->dbOptFlags;
193636 break;
193637 }
193638
193639 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, onoff, xAlt);
@@ -193877,10 +195042,32 @@
193877 const char *z = va_arg(ap,const char*);
193878 double *pR = va_arg(ap,double*);
193879 rc = sqlite3AtoF(z,pR);
193880 break;
193881 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193882
193883 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
193884 /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
193885 **
193886 ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
@@ -195581,12 +196768,12 @@
195581 int nIndex; /* Size of aIndex[] */
195582 struct Fts3Index {
195583 int nPrefix; /* Prefix length (0 for main terms index) */
195584 Fts3Hash hPending; /* Pending terms table for this index */
195585 } *aIndex;
195586 int nMaxPendingData; /* Max pending data before flush to disk */
195587 int nPendingData; /* Current bytes of pending data */
195588 sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
195589 int iPrevLangid; /* Langid of recently inserted document */
195590 int bPrevDelete; /* True if last operation was a delete */
195591
195592 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
@@ -195901,10 +197088,13 @@
195901 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
195902 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
195903 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
195904 SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
195905 SQLITE_PRIVATE int sqlite3Fts3ReadInt(const char *z, int *pnOut);
 
 
 
195906
195907 /* fts3_tokenizer.c */
195908 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
195909 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
195910 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
@@ -196573,10 +197763,11 @@
196573 if( p->zContentTbl==0 ){
196574 if( !zFunc ){
196575 zFunction = "";
196576 }else{
196577 zFree = zFunction = fts3QuoteId(zFunc);
 
196578 }
196579 fts3Appendf(pRc, &zRet, "docid");
196580 for(i=0; i<p->nColumn; i++){
196581 fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
196582 }
@@ -196629,10 +197820,11 @@
196629
196630 if( !zFunc ){
196631 zFunction = "";
196632 }else{
196633 zFree = zFunction = fts3QuoteId(zFunc);
 
196634 }
196635 fts3Appendf(pRc, &zRet, "?");
196636 for(i=0; i<p->nColumn; i++){
196637 fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
196638 }
@@ -199774,10 +200966,35 @@
199774 if( pHash->nRef<=0 ){
199775 sqlite3Fts3HashClear(&pHash->hash);
199776 sqlite3_free(pHash);
199777 }
199778 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199779
199780 /*
199781 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
199782 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
199783 ** respectively. The following three forward declarations are for functions
@@ -199829,17 +201046,18 @@
199829 if( rc!=SQLITE_OK ) return rc;
199830
199831 sqlite3Fts3SimpleTokenizerModule(&pSimple);
199832 sqlite3Fts3PorterTokenizerModule(&pPorter);
199833
199834 /* Allocate and initialize the hash-table used to store tokenizers. */
 
199835 pHash = sqlite3_malloc(sizeof(Fts3HashWrapper));
199836 if( !pHash ){
199837 rc = SQLITE_NOMEM;
199838 }else{
199839 sqlite3Fts3HashInit(&pHash->hash, FTS3_HASH_STRING, 1);
199840 pHash->nRef = 0;
199841 }
199842
199843 /* Load the built-in tokenizers into the hash table */
199844 if( rc==SQLITE_OK ){
199845 if( sqlite3Fts3HashInsert(&pHash->hash, "simple", 7, (void *)pSimple)
@@ -199886,20 +201104,27 @@
199886 }
199887 if( rc==SQLITE_OK ){
199888 pHash->nRef++;
199889 rc = sqlite3Fts3InitTok(db, (void *)pHash, hashDestroy);
199890 }
199891 return rc;
199892 }
199893
 
 
 
 
 
 
 
 
 
 
 
199894
199895 /* An error has occurred. Delete the hash table and return the error code. */
199896 assert( rc!=SQLITE_OK );
199897 if( pHash ){
199898 sqlite3Fts3HashClear(&pHash->hash);
199899 sqlite3_free(pHash);
199900 }
199901 return rc;
199902 }
199903
199904 /*
199905 ** Allocate an Fts3MultiSegReader for each token in the expression headed
@@ -201955,11 +203180,12 @@
201955
201956 /*
201957 ** Schema of the terms table.
201958 */
201959 #define FTS3_AUX_SCHEMA \
201960 "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
 
201961
201962 /*
201963 ** This function does all the work for both the xConnect and xCreate methods.
201964 ** These tables have no persistent representation of their own, so xConnect
201965 ** and xCreate are identical operations.
@@ -202342,11 +203568,11 @@
202342 if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
202343 pCsr->filter.nTerm = (int)strlen(pCsr->filter.zTerm);
202344 }
202345 }
202346
202347 if( iLe>=0 && sqlite3_value_type(apVal[0])==SQLITE_TEXT ){
202348 pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
202349 if( pCsr->zStop==0 ) return SQLITE_NOMEM;
202350 pCsr->nStop = (int)strlen(pCsr->zStop);
202351 }
202352
@@ -203780,16 +205006,17 @@
203780 /*
203781 ** Register the query expression parser test function fts3_exprtest()
203782 ** with database connection db.
203783 */
203784 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash *pHash){
203785 int rc = sqlite3_create_function(
203786 db, "fts3_exprtest", -1, SQLITE_UTF8, (void*)pHash, fts3ExprTest, 0, 0
203787 );
203788 if( rc==SQLITE_OK ){
203789 rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
203790 -1, SQLITE_UTF8, (void*)pHash, fts3ExprTestRebalance, 0, 0
 
203791 );
203792 }
203793 return rc;
203794 }
203795
@@ -205326,11 +206553,10 @@
205326 sqlite3 *db,
205327 Fts3Hash *pHash,
205328 const char *zName
205329 ){
205330 int rc = SQLITE_OK;
205331 void *p = (void *)pHash;
205332 const int any = SQLITE_UTF8|SQLITE_DIRECTONLY;
205333
205334 #ifdef SQLITE_TEST
205335 char *zTest = 0;
205336 char *zTest2 = 0;
@@ -205341,18 +206567,22 @@
205341 rc = SQLITE_NOMEM;
205342 }
205343 #endif
205344
205345 if( SQLITE_OK==rc ){
205346 rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
 
 
205347 }
205348 if( SQLITE_OK==rc ){
205349 rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
 
 
205350 }
205351 #ifdef SQLITE_TEST
205352 if( SQLITE_OK==rc ){
205353 rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
205354 }
205355 if( SQLITE_OK==rc ){
205356 rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
205357 }
205358 #endif
@@ -206847,12 +208077,12 @@
206847 int rc = SQLITE_OK;
206848
206849 pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
206850 if( pList ){
206851 assert( (i64)pList->nData+(i64)nToken+(i64)sizeof(Fts3HashElem)
206852 <= (i64)p->nPendingData );
206853 p->nPendingData -= (int)(pList->nData + nToken + sizeof(Fts3HashElem));
206854 }
206855 if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
206856 if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
206857 /* Malloc failed while inserting the new entry. This can only
206858 ** happen if there was no previous entry for this token.
@@ -206861,13 +208091,13 @@
206861 sqlite3_free(pList);
206862 rc = SQLITE_NOMEM;
206863 }
206864 }
206865 if( rc==SQLITE_OK ){
206866 assert( (i64)p->nPendingData + pList->nData + nToken
206867 + sizeof(Fts3HashElem) <= 0x3fffffff );
206868 p->nPendingData += (int)(pList->nData + nToken + sizeof(Fts3HashElem));
206869 }
206870 return rc;
206871 }
206872
206873 /*
@@ -209848,13 +211078,13 @@
209848 **
209849 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
209850 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
209851 ** to reflect the new size of the pBlob->a[] buffer.
209852 */
209853 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
209854 if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
209855 int nAlloc = nMin;
209856 char *a = (char *)sqlite3_realloc64(pBlob->a, nAlloc);
209857 if( a ){
209858 pBlob->nAlloc = nAlloc;
209859 pBlob->a = a;
209860 }else{
@@ -210118,23 +211348,23 @@
210118 const char *zTerm = pCsr->zTerm;
210119 int nTerm = pCsr->nTerm;
210120 const char *aDoclist = pCsr->aDoclist;
210121 int nDoclist = pCsr->nDoclist;
210122 int rc = SQLITE_OK; /* Return code */
210123 int nSpace; /* Total space in bytes required on leaf */
210124 int nPrefix; /* Size of prefix shared with previous term */
210125 int nSuffix; /* Size of suffix (nTerm - nPrefix) */
210126 NodeWriter *pLeaf; /* Object used to write leaf nodes */
210127
210128 pLeaf = &pWriter->aNodeWriter[0];
210129 nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
210130 nSuffix = nTerm - nPrefix;
210131 if(nSuffix<=0 ) return FTS_CORRUPT_VTAB;
210132
210133 nSpace = sqlite3Fts3VarintLen(nPrefix);
210134 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
210135 nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
210136
210137 /* If the current block is not empty, and if adding this term/doclist
210138 ** to the current block would make it larger than Fts3Table.nNodeSize bytes,
210139 ** and if there is still room for another leaf page, write this block out to
210140 ** the database. */
@@ -211110,11 +212340,11 @@
211110 pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
211111
211112 if( rc==SQLITE_OK ){
211113 rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
211114 assert( bUseHint==1 || bUseHint==0 );
211115 if( iIdx==0 || (bUseHint && iIdx==1) ){
211116 int bIgnore = 0;
211117 rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
211118 if( bIgnore ){
211119 pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
211120 }
@@ -214882,11 +216112,15 @@
214882 #define JEDIT_INS 3 /* Insert if not exists */
214883 #define JEDIT_SET 4 /* Insert or overwrite */
214884 #define JEDIT_AINS 5 /* array_insert() */
214885
214886 /*
214887 ** Maximum nesting depth of JSON for this implementation.
 
 
 
 
214888 **
214889 ** This limit is needed to avoid a stack overflow in the recursive
214890 ** descent parser. A depth of 1000 is far deeper than any sane JSON
214891 ** should go. Historical note: This limit was 2000 prior to version 3.42.0
214892 */
@@ -215901,10 +217135,11 @@
215901 if( z[j]=='-' ){
215902 j++;
215903 if( sz<2 ) return i+1;
215904 }
215905 k = i+n+sz;
 
215906 while( j<k ){
215907 if( sqlite3Isdigit(z[j]) ){
215908 j++;
215909 }else{
215910 return j+1;
@@ -215961,11 +217196,11 @@
215961 }
215962 seen = 1;
215963 continue;
215964 }
215965 if( z[j]=='e' || z[j]=='E' ){
215966 if( seen==2 ) return j+1;
215967 if( j==k-1 ) return j+1;
215968 if( z[j+1]=='+' || z[j+1]=='-' ){
215969 j++;
215970 if( j==k-1 ) return j+1;
215971 }
@@ -216375,10 +217610,11 @@
216375 pParse->iErr = i+1;
216376 return -1;
216377 }
216378 }else{
216379 if( !sqlite3Isdigit(z[i+1]) ){
 
216380 /* JSON5 allows for "+Infinity" and "-Infinity" using exactly
216381 ** that case. SQLite also allows these in any case and it allows
216382 ** "+inf" and "-inf". */
216383 if( (z[i+1]=='I' || z[i+1]=='i')
216384 && sqlite3StrNICmp(&z[i+1], "inf",3)==0
@@ -216394,10 +217630,22 @@
216394 if( z[i+1]=='.' ){
216395 pParse->hasNonstd = 1;
216396 t |= 0x01;
216397 goto parse_number_2;
216398 }
 
 
 
 
 
 
 
 
 
 
 
 
216399 pParse->iErr = i;
216400 return -1;
216401 }
216402 if( z[i+1]=='0' ){
216403 if( sqlite3Isdigit(z[i+2]) ){
@@ -216573,10 +217821,11 @@
216573 #endif
216574 while( jsonIsspace(zJson[i]) ) i++;
216575 if( zJson[i] ){
216576 i += json5Whitespace(&zJson[i]);
216577 if( zJson[i] ){
 
216578 if( pCtx ) sqlite3_result_error(pCtx, "malformed JSON", -1);
216579 jsonParseReset(pParse);
216580 return 1;
216581 }
216582 pParse->hasNonstd = 1;
@@ -216845,10 +218094,98 @@
216845 #else /* if !SQLITE_USES_INLINE */
216846 /* On compilers that do not support in-lining, just call the original
216847 ** jsonbPayloadSize(). It's slower, but it gets the right answer. */
216848 # define jsonbPayloadSizeSemiInline(a,b,c) jsonbPayloadSize(a,b,c)
216849 #endif
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216850
216851 /*
216852 ** Translate the binary JSONB representation of JSON beginning at
216853 ** pParse->aBlob[i] into a JSON text string. Append the JSON
216854 ** text onto the end of pOut. Return the index in pParse->aBlob[]
@@ -216891,33 +218228,11 @@
216891 if( sz==0 ) goto malformed_jsonb;
216892 jsonAppendRaw(pOut, (const char*)&pParse->aBlob[i+n], sz);
216893 break;
216894 }
216895 case JSONB_INT5: { /* Integer literal in hexadecimal notation */
216896 u32 k = 2;
216897 sqlite3_uint64 u = 0;
216898 const char *zIn = (const char*)&pParse->aBlob[i+n];
216899 int bOverflow = 0;
216900 if( sz==0 ) goto malformed_jsonb;
216901 if( zIn[0]=='-' ){
216902 jsonAppendChar(pOut, '-');
216903 k++;
216904 }else if( zIn[0]=='+' ){
216905 k++;
216906 }
216907 for(; k<sz; k++){
216908 if( !sqlite3Isxdigit(zIn[k]) ){
216909 pOut->eErr |= JSTRING_MALFORMED;
216910 break;
216911 }else if( (u>>60)!=0 ){
216912 bOverflow = 1;
216913 }else{
216914 u = u*16 + sqlite3HexToInt(zIn[k]);
216915 }
216916 }
216917 jsonPrintf(100,pOut,bOverflow?"9.0e999":"%llu", u);
216918 break;
216919 }
216920 case JSONB_FLOAT5: { /* Float literal missing digits beside "." */
216921 u32 k = 0;
216922 const char *zIn = (const char*)&pParse->aBlob[i+n];
216923 if( sz==0 ) goto malformed_jsonb;
@@ -217170,11 +218485,10 @@
217170 jsonAppendChar(pOut, '\n');
217171 pPretty->nIndent++;
217172 if( pPretty->nIndent >= JSON_MAX_DEPTH ){
217173 jsonStringTooDeep(pOut);
217174 }
217175 pParse->iDepth = pPretty->nIndent;
217176 while( pOut->eErr==0 ){
217177 jsonPrettyIndent(pPretty);
217178 j = jsonTranslateBlobToText(pParse, j, pOut);
217179 if( j>iEnd ){
217180 pOut->eErr |= JSTRING_MALFORMED;
@@ -217672,11 +218986,11 @@
217672 jsonBlobEdit(pParse, iRoot, sz, 0, 0);
217673 }else if( pParse->eEdit==JEDIT_INS ){
217674 /* Already exists, so json_insert() is a no-op */
217675 }else if( pParse->eEdit==JEDIT_AINS ){
217676 /* json_array_insert() */
217677 if( zPath[-1]!=']' ){
217678 return JSON_LOOKUP_NOTARRAY;
217679 }else{
217680 jsonBlobEdit(pParse, iRoot, 0, pParse->aIns, pParse->nIns);
217681 }
217682 }else{
@@ -217929,56 +219243,28 @@
217929 sqlite3_result_int(pCtx, 0);
217930 break;
217931 }
217932 case JSONB_INT5:
217933 case JSONB_INT: {
217934 sqlite3_int64 iRes = 0;
217935 char *z;
217936 int bNeg = 0;
217937 char x;
217938 if( sz==0 ) goto returnfromblob_malformed;
217939 x = (char)pParse->aBlob[i+n];
217940 if( x=='-' ){
217941 if( sz<2 ) goto returnfromblob_malformed;
217942 n++;
217943 sz--;
217944 bNeg = 1;
217945 }
217946 z = sqlite3DbStrNDup(db, (const char*)&pParse->aBlob[i+n], (int)sz);
217947 if( z==0 ) goto returnfromblob_oom;
217948 rc = sqlite3DecOrHexToI64(z, &iRes);
217949 sqlite3DbFree(db, z);
217950 if( rc==0 ){
217951 if( iRes<0 ){
217952 /* A hexadecimal literal with 16 significant digits and with the
217953 ** high-order bit set is a negative integer in SQLite (and hence
217954 ** iRes comes back as negative) but should be interpreted as a
217955 ** positive value if it occurs within JSON. The value is too
217956 ** large to appear as an SQLite integer so it must be converted
217957 ** into floating point. */
217958 double r;
217959 r = (double)*(sqlite3_uint64*)&iRes;
217960 sqlite3_result_double(pCtx, bNeg ? -r : r);
217961 }else{
217962 sqlite3_result_int64(pCtx, bNeg ? -iRes : iRes);
217963 }
217964 }else if( rc==3 && bNeg ){
217965 sqlite3_result_int64(pCtx, SMALLEST_INT64);
217966 }else if( rc==1 ){
217967 goto returnfromblob_malformed;
217968 }else{
217969 if( bNeg ){ n--; sz++; }
217970 goto to_double;
217971 }
217972 break;
217973 }
217974 case JSONB_FLOAT5:
217975 case JSONB_FLOAT: {
217976 double r;
217977 char *z;
217978 if( sz==0 ) goto returnfromblob_malformed;
217979 to_double:
217980 z = sqlite3DbStrNDup(db, (const char*)&pParse->aBlob[i+n], (int)sz);
217981 if( z==0 ) goto returnfromblob_oom;
217982 rc = sqlite3AtoF(z, &r);
217983 sqlite3DbFree(db, z);
217984 if( rc<=0 ) goto returnfromblob_malformed;
@@ -218242,12 +219528,15 @@
218242 return;
218243 }
218244 if( zPath[1]==0 ){
218245 if( eEdit==JEDIT_REPL || eEdit==JEDIT_SET ){
218246 jsonBlobEdit(p, 0, p->nBlob, ax.aBlob, ax.nBlob);
 
 
 
 
218247 }
218248 rc = 0;
218249 }else{
218250 p->eEdit = eEdit;
218251 p->nIns = ax.nBlob;
218252 p->aIns = ax.aBlob;
218253 p->delta = 0;
@@ -220063,13 +221352,14 @@
220063 }
220064 break;
220065 }
220066 if( p->eType==JSONB_OBJECT ){
220067 jsonReturnFromBlob(&p->sParse, p->i, ctx, 1);
220068 }else{
220069 assert( p->eType==JSONB_ARRAY );
220070 sqlite3_result_int64(ctx, p->aParent[p->nParent-1].iKey);
 
 
220071 }
220072 break;
220073 }
220074 case JEACH_VALUE: {
220075 u32 i = jsonSkipLabel(p);
@@ -221333,11 +222623,13 @@
221333 if( pNode->iNode ){
221334 sqlite3_bind_int64(p, 1, pNode->iNode);
221335 }else{
221336 sqlite3_bind_null(p, 1);
221337 }
221338 sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
 
 
221339 sqlite3_step(p);
221340 pNode->isDirty = 0;
221341 rc = sqlite3_reset(p);
221342 sqlite3_bind_null(p, 2);
221343 if( pNode->iNode==0 && rc==SQLITE_OK ){
@@ -225214,11 +226506,11 @@
225214 sqlite3_str_append(x, "[", 1);
225215 for(i=0; i<p->nVertex; i++){
225216 sqlite3_str_appendf(x, "[%!g,%!g],", GeoX(p,i), GeoY(p,i));
225217 }
225218 sqlite3_str_appendf(x, "[%!g,%!g]]", GeoX(p,0), GeoY(p,0));
225219 sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
225220 sqlite3_free(p);
225221 }
225222 }
225223
225224 /*
@@ -225251,11 +226543,11 @@
225251 if( z && z[0] ){
225252 sqlite3_str_appendf(x, " %s", z);
225253 }
225254 }
225255 sqlite3_str_appendf(x, "></polyline>");
225256 sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
225257 sqlite3_free(p);
225258 }
225259 }
225260
225261 /*
@@ -226570,11 +227862,12 @@
226570 GeoPoly *p = 0;
226571 if( sqlite3_value_type(pShape)==SQLITE_TEXT
226572 && (p = geopolyFuncParam(0, pShape, &rc))!=0
226573 && rc==SQLITE_OK
226574 ){
226575 sqlite3_bind_blob(pUp, 2, p->hdr, 4+8*p->nVertex, SQLITE_TRANSIENT);
 
226576 }else{
226577 sqlite3_bind_value(pUp, 2, pShape);
226578 }
226579 sqlite3_free(p);
226580 nChange = 1;
@@ -226581,11 +227874,11 @@
226581 }
226582 for(jj=1; jj<nData-2; jj++){
226583 nChange++;
226584 sqlite3_bind_value(pUp, jj+2, aData[jj+2]);
226585 }
226586 if( nChange ){
226587 sqlite3_step(pUp);
226588 rc = sqlite3_reset(pUp);
226589 }
226590 }
226591
@@ -228654,10 +229947,11 @@
228654 sqlite3_stmt *pTblIter; /* Iterate through tables */
228655 sqlite3_stmt *pIdxIter; /* Index iterator */
228656 int nTblCol; /* Size of azTblCol[] array */
228657 char **azTblCol; /* Array of unquoted target column names */
228658 char **azTblType; /* Array of target column types */
 
228659 int *aiSrcOrder; /* src table col -> target table col */
228660 u8 *abTblPk; /* Array of flags, set on target PK columns */
228661 u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
228662 u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
228663 int eType; /* Table type - an RBU_PK_XXX value */
@@ -229219,14 +230513,16 @@
229219 static void rbuObjIterFreeCols(RbuObjIter *pIter){
229220 int i;
229221 for(i=0; i<pIter->nTblCol; i++){
229222 sqlite3_free(pIter->azTblCol[i]);
229223 sqlite3_free(pIter->azTblType[i]);
 
229224 }
229225 sqlite3_free(pIter->azTblCol);
229226 pIter->azTblCol = 0;
229227 pIter->azTblType = 0;
 
229228 pIter->aiSrcOrder = 0;
229229 pIter->abTblPk = 0;
229230 pIter->abNotNull = 0;
229231 pIter->nTblCol = 0;
229232 pIter->eType = 0; /* Invalid value */
@@ -229475,10 +230771,47 @@
229475 }
229476 sqlite3_free(zSql);
229477 va_end(ap);
229478 return p->rc;
229479 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229480
229481 /*
229482 ** Attempt to allocate and return a pointer to a zeroed block of nByte
229483 ** bytes.
229484 **
@@ -229507,18 +230840,19 @@
229507 ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
229508 ** there is room for at least nCol elements. If an OOM occurs, store an
229509 ** error code in the RBU handle passed as the first argument.
229510 */
229511 static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
229512 sqlite3_int64 nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
229513 char **azNew;
229514
229515 azNew = (char**)rbuMalloc(p, nByte);
229516 if( azNew ){
229517 pIter->azTblCol = azNew;
229518 pIter->azTblType = &azNew[nCol];
229519 pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
 
229520 pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
229521 pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
229522 pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
229523 }
229524 }
@@ -229548,10 +230882,35 @@
229548 }
229549 }
229550
229551 return zRet;
229552 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229553
229554 /*
229555 ** Finalize the statement passed as the second argument.
229556 **
229557 ** If the sqlite3_finalize() call indicates that an error occurs, and the
@@ -229734,10 +231093,29 @@
229734
229735 rbuFinalize(p, pList);
229736 if( bIndex==0 ) pIter->abIndexed = 0;
229737 }
229738
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229739
229740 /*
229741 ** If they are not already populated, populate the pIter->azTblCol[],
229742 ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
229743 ** the table (not index) that the iterator currently points to.
@@ -229752,10 +231130,11 @@
229752 int nCol = 0;
229753 int i; /* for() loop iterator variable */
229754 int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
229755 int iOrder = 0;
229756 int iTnum = 0;
 
229757
229758 /* Figure out the type of table this step will deal with. */
229759 assert( pIter->eType==0 );
229760 rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
229761 if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
@@ -229802,14 +231181,16 @@
229802 p->zErrmsg = sqlite3_mprintf(
229803 "table %q %s rbu_rowid column", pIter->zDataTbl,
229804 (bRbuRowid ? "may not have" : "requires")
229805 );
229806 }
 
 
229807
229808 /* Check that all non-HIDDEN columns in the destination table are also
229809 ** present in the input table. Populate the abTblPk[], azTblType[] and
229810 ** aiTblOrder[] arrays at the same time.
229811 **
229812 ** RBU does not support tables with GENERATED columns. If the target
229813 ** table has any, return an error. */
229814 if( p->rc==SQLITE_OK ){
229815 p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
@@ -229838,17 +231219,22 @@
229838 );
229839 }else{
229840 int iPk = sqlite3_column_int(pStmt, 5);
229841 int bNotNull = sqlite3_column_int(pStmt, 3);
229842 const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
 
229843
229844 if( i!=iOrder ){
229845 SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
229846 SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
229847 }
229848
229849 pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
 
 
 
 
229850 assert( iPk>=0 );
229851 pIter->abTblPk[iOrder] = (u8)iPk;
229852 pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
229853 iOrder++;
229854 }
@@ -230517,11 +231903,11 @@
230517 }
230518 zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
230519 rbuFinalize(p, pXInfo);
230520
230521 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
230522 rbuMPrintfExec(p, p->dbMain,
230523 "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
230524 zCols, zPk
230525 );
230526 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
230527 }
@@ -230567,13 +231953,15 @@
230567 if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
230568 /* If the target table column is an "INTEGER PRIMARY KEY", add
230569 ** "PRIMARY KEY" to the imposter table column declaration. */
230570 zPk = "PRIMARY KEY ";
230571 }
230572 zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s",
230573 zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
230574 (pIter->abNotNull[iCol] ? " NOT NULL" : "")
 
 
230575 );
230576 zComma = ", ";
230577 }
230578
230579 if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
@@ -230582,11 +231970,11 @@
230582 zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
230583 }
230584 }
230585
230586 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
230587 rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
230588 pIter->zTbl, zSql,
230589 (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
230590 );
230591 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
230592 }
@@ -230786,11 +232174,11 @@
230786 zBind = rbuObjIterGetBindlist(p, nBind);
230787
230788 /* Create the imposter table used to write to this index. */
230789 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
230790 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
230791 rbuMPrintfExec(p, p->dbMain,
230792 "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
230793 zTbl, zImposterCols, zImposterPK
230794 );
230795 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
230796
@@ -230913,11 +232301,11 @@
230913 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
230914 zRbuRowid = ", rbu_rowid";
230915 }
230916
230917 /* Create the rbu_tmp_xxx table and the triggers to populate it. */
230918 rbuMPrintfExec(p, p->dbRbu,
230919 "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
230920 "SELECT *%s FROM '%q' WHERE 0;"
230921 , p->zStateDb, pIter->zDataTbl
230922 , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
230923 , pIter->zDataTbl
@@ -230942,11 +232330,11 @@
230942 zWrite, zTbl, zOldlist,
230943 zWrite, zTbl, zNewlist
230944 );
230945
230946 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
230947 rbuMPrintfExec(p, p->dbMain,
230948 "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
230949 "BEGIN "
230950 " SELECT rbu_tmp_insert(0, %s);"
230951 "END;",
230952 zWrite, zTbl, zNewlist
@@ -231227,11 +232615,11 @@
231227 }
231228
231229 /* If using separate RBU and state databases, attach the state database to
231230 ** the RBU db handle now. */
231231 if( p->zState ){
231232 rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
231233 memcpy(p->zStateDb, "stat", 4);
231234 }else{
231235 memcpy(p->zStateDb, "main", 4);
231236 }
231237
@@ -231353,11 +232741,11 @@
231353 }
231354
231355 if( p->rc==SQLITE_OK ){
231356 p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
231357 }
231358 rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_schema");
231359
231360 /* Mark the database file just opened as an RBU target database. If
231361 ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
231362 ** This is an error. */
231363 if( p->rc==SQLITE_OK ){
@@ -231961,11 +233349,11 @@
231961 iCookie = sqlite3_column_int(pStmt, 0);
231962 }
231963 rbuFinalize(p, pStmt);
231964 }
231965 if( p->rc==SQLITE_OK ){
231966 rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
231967 }
231968 }
231969 }
231970
231971 /*
@@ -232039,11 +233427,11 @@
232039 sqlite3_stmt *pPragma = 0;
232040 p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
232041 sqlite3_mprintf("PRAGMA main.%s", zPragma)
232042 );
232043 if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
232044 p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
232045 zPragma, sqlite3_column_int(pPragma, 0)
232046 );
232047 }
232048 rbuFinalize(p, pPragma);
232049 }
@@ -232130,11 +233518,11 @@
232130 if( pIter->bCleanup ){
232131 /* Clean up the rbu_tmp_xxx table for the previous table. It
232132 ** cannot be dropped as there are currently active SQL statements.
232133 ** But the contents can be deleted. */
232134 if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
232135 rbuMPrintfExec(p, p->dbRbu,
232136 "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
232137 );
232138 }
232139 }else{
232140 rbuObjIterPrepareAll(p, pIter, 0);
@@ -234286,11 +235674,13 @@
234286 if( p->iPgno==1 ) nHdr += 100;
234287 p->nCell = get2byte(&aHdr[3]);
234288 p->nMxPayload = 0;
234289 szPage = sqlite3BtreeGetPageSize(pBt);
234290
234291 nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
 
 
234292 nUnused += (int)aHdr[7];
234293 iOff = get2byte(&aHdr[1]);
234294 while( iOff ){
234295 int iNext;
234296 if( iOff>=szPage ) goto statPageIsCorrupt;
@@ -235036,11 +236426,16 @@
235036 if( NEVER(pBt==0) ) return SQLITE_OK;
235037 pCsr->pPager = sqlite3BtreePager(pBt);
235038 pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
235039 pCsr->mxPgno = sqlite3BtreeLastPage(pBt);
235040 if( idxNum & 1 ){
235041 i64 iPg = sqlite3_value_int64(argv[idxNum>>1]);
 
 
 
 
 
235042 assert( argc>(idxNum>>1) );
235043 if( iPg<1 || iPg>pCsr->mxPgno ){
235044 pCsr->pgno = 1;
235045 pCsr->mxPgno = 0;
235046 }else{
@@ -235798,14 +237193,17 @@
235798 }else if( mFlags==CARRAY_BLOB ){
235799 struct iovec *p = (struct iovec*)pNew->aData;
235800 unsigned char *z = (unsigned char*)&p[nData];
235801 for(i=0; i<nData; i++){
235802 size_t n = ((struct iovec*)aData)[i].iov_len;
 
235803 p[i].iov_len = n;
235804 p[i].iov_base = z;
235805 z += n;
235806 memcpy(p[i].iov_base, ((struct iovec*)aData)[i].iov_base, n);
 
 
235807 }
235808 }else if( sz>0 ){
235809 memcpy(pNew->aData, aData, sz);
235810 }
235811 pNew->xDel = sqlite3_free;
@@ -236494,11 +237892,12 @@
236494 int n;
236495 assert( a!=0 );
236496 e = *a;
236497 if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
236498 if( e==SQLITE_TEXT || e==SQLITE_BLOB ){
236499 return sessionVarintGet(&a[1], &n) + 1 + n;
 
236500 }
236501 return 1;
236502 }
236503
236504 /*
@@ -239796,13 +241195,19 @@
239796 ** there are no fields in the old.* record that are not (a) PK fields,
239797 ** or (b) also present in the new.* record.
239798 **
239799 ** Such records are technically corrupt, but the rebaser was at one
239800 ** point generating them. Under most circumstances this is benign, but
239801 ** can cause spurious SQLITE_RANGE errors when applying the changeset. */
 
 
 
239802 if( p->bPatchset==0 && p->op==SQLITE_UPDATE){
239803 for(i=0; i<p->nCol; i++){
 
 
 
239804 if( p->abPK[i]==0 && p->apValue[i+p->nCol]==0 ){
239805 sqlite3ValueFree(p->apValue[i]);
239806 p->apValue[i] = 0;
239807 }
239808 }
@@ -241050,23 +242455,26 @@
241050 ** before reattempting the INSERT. */
241051 else if( bReplace ){
241052 assert( pIter->op==SQLITE_INSERT );
241053 rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
241054 if( rc==SQLITE_OK ){
 
241055 rc = sessionBindRow(pIter,
241056 sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
241057 sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
241058 }
241059 if( rc==SQLITE_OK ){
241060 sqlite3_step(pApply->pDelete);
241061 rc = sqlite3_reset(pApply->pDelete);
241062 }
241063 if( rc==SQLITE_OK ){
241064 rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
241065 }
241066 if( rc==SQLITE_OK ){
241067 rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
 
 
241068 }
241069 }
241070 }
241071
241072 return rc;
@@ -243213,13 +244621,10 @@
243213 *pzErr = sqlite3_mprintf("no such table: %s", zTab);
243214 }
243215 }
243216 if( rc==SQLITE_OK ){
243217 int nReq = pTab->nCol * (eOp==SQLITE_UPDATE ? 2 : 1);
243218 pGrp->cd.pTab = pTab;
243219 pGrp->cd.eOp = eOp;
243220 pGrp->cd.bIndirect = bIndirect;
243221
243222 if( pGrp->cd.nBufAlloc<nReq ){
243223 SessionBuffer *aBuf = (SessionBuffer*)sqlite3_realloc(
243224 pGrp->cd.aBuf, nReq * sizeof(SessionBuffer)
243225 );
@@ -243231,10 +244636,18 @@
243231 );
243232 pGrp->cd.aBuf = aBuf;
243233 pGrp->cd.nBufAlloc = nReq;
243234 }
243235 }
 
 
 
 
 
 
 
 
243236
243237 #ifdef SQLITE_DEBUG
243238 {
243239 /* Assert that all column values are currently undefined */
243240 int ii;
@@ -243273,12 +244686,13 @@
243273 SessionBuffer *pBuf = &pGrp->cd.aBuf[iCol];
243274 if( pGrp->cd.eOp==SQLITE_UPDATE && bNew ){
243275 pBuf += pGrp->cd.pTab->nCol;
243276 }
243277 pBuf->nBuf = 0;
243278 sessionBufferGrow(pBuf, nReq, &rc);
243279 pBuf->nBuf = nReq;
 
243280 *ppBuf = pBuf;
243281 }
243282 return rc;
243283 }
243284
@@ -248832,11 +250246,11 @@
248832 zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
248833 for(i=0; zSql && i<pConfig->nCol; i++){
248834 const char *zSep = (i==0?"":", ");
248835 zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
248836 }
248837 zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
248838 zSql, pConfig->zName, FTS5_RANK_NAME
248839 );
248840
248841 assert( zSql || rc==SQLITE_NOMEM );
248842 if( zSql ){
@@ -249135,11 +250549,13 @@
249135 pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
249136 pConfig->nDeleteMerge = FTS5_DEFAULT_DELETE_AUTOMERGE;
249137
249138 zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
249139 if( zSql ){
249140 rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
 
 
249141 sqlite3_free(zSql);
249142 }
249143
249144 assert( rc==SQLITE_OK || p==0 );
249145 if( rc==SQLITE_OK ){
@@ -249185,11 +250601,11 @@
249185 char *zMsg = 0;
249186
249187 va_start(ap, zFmt);
249188 zMsg = sqlite3_vmprintf(zFmt, ap);
249189 if( pConfig->pzErrmsg ){
249190 assert( *pConfig->pzErrmsg==0 );
249191 *pConfig->pzErrmsg = zMsg;
249192 }else{
249193 sqlite3_free(zMsg);
249194 }
249195
@@ -253657,10 +255073,13 @@
253657 /* Variables populated based on current entry. */
253658 Fts5Buffer term; /* Current term */
253659 i64 iRowid; /* Current rowid */
253660 int nPos; /* Number of bytes in current position list */
253661 u8 bDel; /* True if the delete flag is set */
 
 
 
253662 };
253663
253664 static int fts5IndexCorruptRowid(Fts5Index *pIdx, i64 iRowid){
253665 pIdx->rc = FTS5_CORRUPT;
253666 sqlite3Fts5ConfigErrmsg(pIdx->pConfig,
@@ -254050,11 +255469,12 @@
254050 char *zSql
254051 ){
254052 if( p->rc==SQLITE_OK ){
254053 if( zSql ){
254054 int rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
254055 SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB,
 
254056 ppStmt, 0);
254057 /* If this prepare() call fails with SQLITE_ERROR, then one of the
254058 ** %_idx or %_data tables has been removed or modified. Call this
254059 ** corruption. */
254060 p->rc = (rc==SQLITE_ERROR ? SQLITE_CORRUPT : rc);
@@ -254064,10 +255484,21 @@
254064 }
254065 sqlite3_free(zSql);
254066 return p->rc;
254067 }
254068
 
 
 
 
 
 
 
 
 
 
 
254069
254070 /*
254071 ** INSERT OR REPLACE a record into the %_data table.
254072 */
254073 static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
@@ -254081,13 +255512,12 @@
254081 ));
254082 if( p->rc ) return;
254083 }
254084
254085 sqlite3_bind_int64(p->pWriter, 1, iRowid);
254086 sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
254087 sqlite3_step(p->pWriter);
254088 p->rc = sqlite3_reset(p->pWriter);
254089 sqlite3_bind_null(p->pWriter, 2);
254090 }
254091
254092 /*
254093 ** Execute the following SQL:
@@ -254690,10 +256120,21 @@
254690 }
254691 fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
254692 }
254693 }
254694
 
 
 
 
 
 
 
 
 
 
 
254695
254696 /*
254697 ** Advance the iterator passed as the only argument. If the end of the
254698 ** doclist-index page is reached, return non-zero.
254699 */
@@ -254712,11 +256153,11 @@
254712 if( pData->p[iOff] ) break;
254713 }
254714
254715 if( iOff<pData->nn ){
254716 u64 iVal;
254717 pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
254718 iOff += fts5GetVarint(&pData->p[iOff], &iVal);
254719 pLvl->iRowid += iVal;
254720 pLvl->iOff = iOff;
254721 }else{
254722 pLvl->bEof = 1;
@@ -254822,11 +256263,11 @@
254822 ii++;
254823 }
254824 ii += sqlite3Fts5GetVarint(&a[ii], &delta);
254825
254826 if( ii>=iOff ) break;
254827 pLvl->iLeafPgno += nZero+1;
254828 pLvl->iRowid += delta;
254829 pLvl->iOff = ii;
254830 }
254831 }
254832
@@ -255828,11 +257269,12 @@
255828 /* This block sets stack variable iPg to the leaf page number that may
255829 ** contain term (pTerm/nTerm), if it is present in the segment. */
255830 pIdxSelect = fts5IdxSelectStmt(p);
255831 if( p->rc ) return;
255832 sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
255833 sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
 
255834 if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
255835 i64 val = sqlite3_column_int(pIdxSelect, 0);
255836 iPg = (int)(val>>1);
255837 bDlidx = (val & 0x0001);
255838 }
@@ -255920,12 +257362,12 @@
255920
255921 pSel = fts5IdxNextStmt(p);
255922 if( pSel ){
255923 assert( p->rc==SQLITE_OK );
255924 sqlite3_bind_int(pSel, 1, pSeg->iSegid);
255925 sqlite3_bind_blob(pSel, 2, pTerm, nTerm, SQLITE_STATIC);
255926
255927 if( sqlite3_step(pSel)==SQLITE_ROW ){
255928 i64 val = sqlite3_column_int64(pSel, 0);
255929 iPg = (int)(val>>1);
255930 bDlidx = (val & 0x0001);
255931 }
@@ -256204,10 +257646,14 @@
256204 if( res==0 ){
256205 assert_nc( i2>i1 );
256206 assert_nc( i2!=0 );
256207 pRes->bTermEq = 1;
256208 if( p1->iRowid==p2->iRowid ){
 
 
 
 
256209 return i2;
256210 }
256211 res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
256212 }
256213 assert( res!=0 );
@@ -256721,10 +258167,15 @@
256721 int pgno = pSeg->iLeafPgno;
256722 int pgnoSave = 0;
256723
256724 /* This function does not work with detail=none databases. */
256725 assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
 
 
 
 
 
256726
256727 if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
256728 pgnoSave = pgno+1;
256729 }
256730
@@ -257416,14 +258867,15 @@
257416
257417 if( p->rc==SQLITE_OK ){
257418 const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
257419 /* The following was already done in fts5WriteInit(): */
257420 /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
257421 sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
 
 
257422 sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
257423 sqlite3_step(p->pIdxWriter);
257424 p->rc = sqlite3_reset(p->pIdxWriter);
257425 sqlite3_bind_null(p->pIdxWriter, 2);
257426 }
257427 pWriter->iBtPage = 0;
257428 }
257429
@@ -257966,10 +259418,18 @@
257966 ){
257967 Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
257968 int nPos; /* position-list size field value */
257969 int nTerm;
257970 const u8 *pTerm;
 
 
 
 
 
 
 
 
257971
257972 pTerm = fts5MultiIterTerm(pIter, &nTerm);
257973 if( nTerm!=term.n || fts5Memcmp(pTerm, term.p, nTerm) ){
257974 if( pnRem && writer.nLeafWritten>nRem ){
257975 break;
@@ -257977,11 +259437,11 @@
257977 fts5BufferSet(&p->rc, &term, nTerm, pTerm);
257978 bTermWritten =0;
257979 }
257980
257981 /* Check for key annihilation. */
257982 if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
257983
257984 if( p->rc==SQLITE_OK && bTermWritten==0 ){
257985 /* This is a new term. Append a term to the output segment. */
257986 fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
257987 bTermWritten = 1;
@@ -257990,19 +259450,19 @@
257990 /* Append the rowid to the output */
257991 /* WRITEPOSLISTSIZE */
257992 fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
257993
257994 if( eDetail==FTS5_DETAIL_NONE ){
257995 if( pSegIter->bDel ){
257996 fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
257997 if( pSegIter->nPos>0 ){
257998 fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
257999 }
258000 }
258001 }else{
258002 /* Append the position-list data to the output */
258003 nPos = pSegIter->nPos*2 + pSegIter->bDel;
258004 fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
258005 fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
258006 }
258007 }
258008
@@ -258437,11 +259897,12 @@
258437
258438 iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
258439 assert_nc( iSOP<=pSeg->iLeafOffset );
258440
258441 if( bDetailNone ){
258442 while( iSOP<pSeg->iLeafOffset ){
 
258443 if( aPg[iSOP]==0x00 ) iSOP++;
258444 if( aPg[iSOP]==0x00 ) iSOP++;
258445 iStart = iSOP;
258446 iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
258447 }
@@ -258502,11 +259963,11 @@
258502 }
258503 }
258504
258505 if( pSeg->bDel ){
258506 iOff += sqlite3Fts5PutVarint(&aPg[iOff], iDelta);
258507 aPg[iOff++] = 0x01;
258508 }else if( bLastInDoclist==0 ){
258509 if( iNextOff!=iPgIdx ){
258510 u64 iNextDelta = 0;
258511 iNextOff += fts5GetVarint(&aPg[iNextOff], &iNextDelta);
258512 iOff += sqlite3Fts5PutVarint(&aPg[iOff], iDelta + iNextDelta);
@@ -261715,11 +263176,13 @@
261715 fts5DlidxIterEof(p, pDlidx)==0;
261716 fts5DlidxIterNext(p, pDlidx)
261717 ){
261718
261719 /* Check any rowid-less pages that occur before the current leaf. */
261720 for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
 
 
261721 iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
261722 pLeaf = fts5LeafRead(p, iKey);
261723 if( pLeaf ){
261724 if( fts5LeafFirstRowidOff(pLeaf)!=0 ) FTS5_CORRUPT_ROWID(p, iKey);
261725 fts5DataRelease(pLeaf);
@@ -263917,11 +265380,12 @@
263917 if( zRankArgs ){
263918 char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
263919 if( zSql ){
263920 sqlite3_stmt *pStmt = 0;
263921 rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
263922 SQLITE_PREPARE_PERSISTENT, &pStmt, 0);
 
263923 sqlite3_free(zSql);
263924 assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
263925 if( rc==SQLITE_OK ){
263926 if( SQLITE_ROW==sqlite3_step(pStmt) ){
263927 sqlite3_int64 nByte;
@@ -264859,10 +266323,11 @@
264859 */
264860 static int fts5RollbackMethod(sqlite3_vtab *pVtab){
264861 int rc;
264862 Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
264863 fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
 
264864 rc = sqlite3Fts5StorageRollback(pTab->pStorage);
264865 pTab->p.pConfig->pgsz = 0;
264866 return rc;
264867 }
264868
@@ -266335,11 +267800,11 @@
266335 int nArg, /* Number of args */
266336 sqlite3_value **apUnused /* Function arguments */
266337 ){
266338 assert( nArg==0 );
266339 UNUSED_PARAM2(nArg, apUnused);
266340 sqlite3_result_text(pCtx, "fts5: 2026-10-24 22:25:07 d08cabd778f7844d04f3852d93197e80c0d0f4f30a589f7fd0d28577fa3fa68b", -1, SQLITE_TRANSIENT);
266341 }
266342
266343 /*
266344 ** Implementation of fts5_locale(LOCALE, TEXT) function.
266345 **
@@ -266810,11 +268275,11 @@
266810 }
266811
266812 if( zSql==0 ){
266813 rc = SQLITE_NOMEM;
266814 }else{
266815 int f = SQLITE_PREPARE_PERSISTENT;
266816 if( eStmt>FTS5_STMT_LOOKUP2 ) f |= SQLITE_PREPARE_NO_VTAB;
266817 p->pConfig->bLock++;
266818 rc = sqlite3_prepare_v3(pC->db, zSql, -1, f, &p->aStmt[eStmt], 0);
266819 p->pConfig->bLock--;
266820 sqlite3_free(zSql);
@@ -267376,14 +268841,16 @@
267376 rc = sqlite3Fts5IndexGetOrigin(p->pIndex, &iOrigin);
267377 sqlite3_bind_int64(pReplace, 3, iOrigin);
267378 }
267379 }
267380 if( rc==SQLITE_OK ){
267381 sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
267382 sqlite3_step(pReplace);
267383 rc = sqlite3_reset(pReplace);
267384 sqlite3_bind_null(pReplace, 2);
 
 
267385 }
267386 }
267387 return rc;
267388 }
267389
@@ -267765,11 +269232,13 @@
267765 );
267766 if( zSql==0 ){
267767 rc = SQLITE_NOMEM;
267768 }else{
267769 sqlite3_stmt *pCnt = 0;
267770 rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
 
 
267771 if( rc==SQLITE_OK ){
267772 if( SQLITE_ROW==sqlite3_step(pCnt) ){
267773 *pnRow = sqlite3_column_int64(pCnt, 0);
267774 }
267775 rc = sqlite3_finalize(pCnt);
267776
--- extsrc/sqlite3.c
+++ extsrc/sqlite3.c
@@ -16,11 +16,11 @@
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
19 **
20 ** The content in this amalgamation comes from Fossil check-in
21 ** ad4ee20509dc4e2803f35093b03df55cb3e3 with changes in files:
22 **
23 **
24 */
25 #ifndef SQLITE_AMALGAMATION
26 #define SQLITE_CORE 1
@@ -467,14 +467,14 @@
467 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
468 ** [sqlite_version()] and [sqlite_source_id()].
469 */
470 #define SQLITE_VERSION "3.55.0"
471 #define SQLITE_VERSION_NUMBER 3055000
472 #define SQLITE_SOURCE_ID "2026-11-15 00:55:04 ad4ee20509dc4e2803f35093b03df55cb3e39c8083b0d4ad231e1432516c7841"
473 #define SQLITE_SCM_BRANCH "trunk"
474 #define SQLITE_SCM_TAGS ""
475 #define SQLITE_SCM_DATETIME "2026-11-15T00:55:04.503Z"
476
477 /*
478 ** CAPI3REF: Run-Time Library Version Numbers
479 ** KEYWORDS: sqlite3_version sqlite3_sourceid
480 **
@@ -795,10 +795,11 @@
795 #define SQLITE_FORMAT 24 /* Not used */
796 #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
797 #define SQLITE_NOTADB 26 /* File opened that is not a database file */
798 #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
799 #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
800 #define SQLITE_MOVED 29 /* Internal use only: Cursor moved */
801 #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
802 #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
803 /* end-of-error-codes */
804
805 /*
@@ -2983,16 +2984,23 @@
2984 ** the number of significant digits that SQLite will attempt to preserve when
2985 ** converting floating point numbers (IEEE 754 "doubles") into text. The
2986 ** default value 17, as of SQLite version 3.52.0. The value was 15 in all
2987 ** prior versions.<p>
2988 ** This option takes two arguments which are an integer and a pointer
2989 ** to an integer. The first argument is a small integer, between 4 and 23, or
2990 ** zero. The FP_DIGITS setting is changed to that small integer, or left
2991 ** unaltered if the first argument is zero or out of range. The second argument
2992 ** is a pointer to an integer. If the pointer is not NULL, then the value of
2993 ** the FP_DIGITS setting, after possibly being modified by the first
2994 ** arguments, is written into the integer to which the second argument points.
2995 **
2996 ** [[SQLITE_DBCONFIG_VDBE_TRACE]]
2997 ** <dt>SQLITE_DBCONFIG_VDBE_TRACE</dt>
2998 ** <dd>The SQLITE_DBCONFIG_VDBE_TRACE setting enables or disables tracing
2999 ** of the [bytecode engine]. This setting is only available when SQLite has
3000 ** be compiled with -DSQLITE_DEBUG. It is the equivalent of using
3001 ** [PRAGMA vdbe_trace].
3002 ** </dd>
3003 **
3004 ** </dl>
3005 **
3006 ** [[DBCONFIG arguments]] <h3>Arguments To SQLITE_DBCONFIG Options</h3>
@@ -3039,11 +3047,12 @@
3047 #define SQLITE_DBCONFIG_REVERSE_SCANORDER 1019 /* int int* */
3048 #define SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE 1020 /* int int* */
3049 #define SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE 1021 /* int int* */
3050 #define SQLITE_DBCONFIG_ENABLE_COMMENTS 1022 /* int int* */
3051 #define SQLITE_DBCONFIG_FP_DIGITS 1023 /* int int* */
3052 #define SQLITE_DBCONFIG_VDBE_TRACE 1024 /* int int* */
3053 #define SQLITE_DBCONFIG_MAX 1024 /* Largest DBCONFIG */
3054
3055 /*
3056 ** CAPI3REF: Enable Or Disable Extended Result Codes
3057 ** METHOD: sqlite3
3058 **
@@ -5320,11 +5329,11 @@
5329 ** or indicates the lifetime of the object referenced by the third parameter.
5330 ** These three options exist:
5331 ** ^ (1) A destructor to dispose of the BLOB or string after SQLite has finished
5332 ** with it may be passed. ^It is called to dispose of the BLOB or string even
5333 ** if the call to the bind API fails, except the destructor is not called if
5334 ** the third parameter is a NULL pointer or the fifth parameter is negative.
5335 ** ^ (2) The special constant, [SQLITE_STATIC], may be passed to indicate that
5336 ** the application remains responsible for disposing of the object. ^In this
5337 ** case, the object and the provided pointer to it must remain valid until
5338 ** either the prepared statement is finalized or the same SQL parameter is
5339 ** bound to something else, whichever occurs sooner.
@@ -9112,11 +9121,12 @@
9121 #define SQLITE_TESTCTRL_TRACEFLAGS 31
9122 #define SQLITE_TESTCTRL_TUNE 32
9123 #define SQLITE_TESTCTRL_LOGEST 33
9124 #define SQLITE_TESTCTRL_USELONGDOUBLE 34 /* NOT USED */
9125 #define SQLITE_TESTCTRL_ATOF 34
9126 #define SQLITE_TESTCTRL_EXPIRE_STMTS 35
9127 #define SQLITE_TESTCTRL_LAST 35 /* Largest TESTCTRL */
9128
9129 /*
9130 ** CAPI3REF: SQL Keyword Checking
9131 **
9132 ** These routines provide access to the set of SQL language keywords
@@ -18041,64 +18051,66 @@
18051 #define OP_ResetCount 132
18052 #define OP_SorterCompare 133 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
18053 #define OP_SorterData 134 /* synopsis: r[P2]=data */
18054 #define OP_RowData 135 /* synopsis: r[P2]=data */
18055 #define OP_Rowid 136 /* synopsis: r[P2]=PX rowid of P1 */
18056 #define OP_Stale 137
18057 #define OP_NullRow 138
18058 #define OP_SeekEnd 139
18059 #define OP_IdxInsert 140 /* synopsis: key=r[P2] */
18060 #define OP_SorterInsert 141 /* synopsis: key=r[P2] */
18061 #define OP_IdxDelete 142 /* synopsis: key=r[P2@P5] */
18062 #define OP_DeferredSeek 143 /* synopsis: Move P3 to P1.rowid if needed */
18063 #define OP_IdxRowid 144 /* synopsis: r[P2]=rowid */
18064 #define OP_FinishSeek 145
18065 #define OP_Destroy 146
18066 #define OP_DbLock 147
18067 #define OP_Clear 148
18068 #define OP_ResetSorter 149
18069 #define OP_CreateBtree 150 /* synopsis: r[P2]=root iDb=P1 flags=P3 */
18070 #define OP_SqlExec 151
18071 #define OP_ParseSchema 152
18072 #define OP_LoadAnalysis 153
18073 #define OP_Real 154 /* same as TK_FLOAT, synopsis: r[P2]=PDBL13 */
18074 #define OP_DropTable 155
18075 #define OP_DropIndex 156
18076 #define OP_DropTrigger 157
18077 #define OP_IntegrityCk 158
18078 #define OP_RowSetAdd 159 /* synopsis: rowset(P1)=r[P2] */
18079 #define OP_Param 160
18080 #define OP_FkCounter 161 /* synopsis: fkctr[P1]+=P2 */
18081 #define OP_MemMax 162 /* synopsis: r[P1]=max(r[P1],r[P2]) */
18082 #define OP_OffsetLimit 163 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
18083 #define OP_AggInverse 164 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */
18084 #define OP_AggStep 165 /* synopsis: accum=r[P3] step(r[P2@P5]) */
18085 #define OP_AggStep1 166 /* synopsis: accum=r[P3] step(r[P2@P5]) */
18086 #define OP_AggValue 167 /* synopsis: r[P3]=value N=P2 */
18087 #define OP_AggFinal 168 /* synopsis: accum=r[P1] N=P2 */
18088 #define OP_Expire 169
18089 #define OP_CursorLock 170
18090 #define OP_CursorUnlock 171
18091 #define OP_TableLock 172 /* synopsis: iDb=P1 root=P2 write=P3 */
18092 #define OP_VBegin 173
18093 #define OP_VCreate 174
18094 #define OP_VDestroy 175
18095 #define OP_VOpen 176
18096 #define OP_VCheck 177
18097 #define OP_VInitIn 178 /* synopsis: r[P2]=ValueList(P1,P3) */
18098 #define OP_VColumn 179 /* synopsis: r[P3]=vcolumn(P2) */
18099 #define OP_VRename 180
18100 #define OP_Pagecount 181
18101 #define OP_MaxPgcnt 182
18102 #define OP_ClrSubtype 183 /* synopsis: r[P1].subtype = 0 */
18103 #define OP_GetSubtype 184 /* synopsis: r[P2] = r[P1].subtype */
18104 #define OP_SetSubtype 185 /* synopsis: r[P2].subtype = r[P1] */
18105 #define OP_FilterAdd 186 /* synopsis: filter(P1) += key(P3@P4) */
18106 #define OP_Trace 187
18107 #define OP_CursorHint 188
18108 #define OP_ReleaseReg 189 /* synopsis: release r[P1@P2] mask P3 */
18109 #define OP_Noop 190
18110 #define OP_Explain 191
18111 #define OP_Abortable 192
18112
18113 /* Properties such as "out2" or "jump" that are specified in
18114 ** comments following the "case" for each opcode in the vdbe.c
18115 ** are encoded into bitvectors as follows:
18116 */
@@ -18126,17 +18138,18 @@
18138 /* 96 */ 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x26,\
18139 /* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,\
18140 /* 112 */ 0x26, 0x40, 0x00, 0x12, 0x40, 0x40, 0x10, 0x40,\
18141 /* 120 */ 0x00, 0x00, 0x00, 0x40, 0x00, 0x40, 0x40, 0x10,\
18142 /* 128 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00,\
18143 /* 136 */ 0x50, 0x00, 0x00, 0x40, 0x04, 0x04, 0x00, 0x40,\
18144 /* 144 */ 0x50, 0x40, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00,\
18145 /* 152 */ 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x06,\
18146 /* 160 */ 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00,\
18147 /* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
18148 /* 176 */ 0x40, 0x10, 0x50, 0x40, 0x00, 0x10, 0x10, 0x02,\
18149 /* 184 */ 0x12, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
18150 /* 192 */ 0x00,}
18151
18152 /* The resolve3P2Values() routine is able to run faster if it knows
18153 ** the value of the largest JUMP opcode. The smaller the maximum
18154 ** JUMP opcode the better, so the mkopcodeh.tcl script that
18155 ** generated this include file strives to group all JUMP opcodes
@@ -18930,14 +18943,15 @@
18943 u8 mTrace; /* zero or more SQLITE_TRACE flags */
18944 u8 noSharedCache; /* True if no shared-cache backends */
18945 u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
18946 u8 eOpenState; /* Current condition of the connection */
18947 u8 nFpDigit; /* Significant digits to keep on double->text */
18948 u8 bPendingSchemaReset; /* 1 or more schema resets pending */
18949 int nextPagesize; /* Pagesize after VACUUM if >0 */
18950 i64 nChange; /* Value returned by sqlite3_changes() */
18951 i64 nTotalChange; /* Value returned by sqlite3_total_changes() */
18952 u64 dbOptFlags; /* Flags to enable/disable optimizations */
18953 int aLimit[SQLITE_N_LIMIT]; /* Limits */
18954 int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
18955 struct sqlite3InitInfo { /* Information used during initialization */
18956 Pgno newTnum; /* Rootpage of table being initialized */
18957 u8 iDb; /* Which db file is being initialized */
@@ -19161,11 +19175,11 @@
19175 #define SQLITE_PropagateConst 16 /* The constant propagation opt */
19176 #define SQLITE_MinMaxOpt 17 /* The min/max optimization */
19177 #define SQLITE_SeekScan 18 /* The OP_SeekScan optimization */
19178 #define SQLITE_OmitOrderBy 19 /* Omit pointless ORDER BY */
19179 #define SQLITE_BloomFilter 20 /* Use a Bloom filters */
19180 #define SQLITE_DevTest 21 /* Temporary development testing use */
19181 #define SQLITE_BalancedMerge 22 /* Balance multi-way merges */
19182 #define SQLITE_ReleaseReg 23 /* Use OP_ReleaseReg for testing */
19183 #define SQLITE_FlttnUnionAll 24 /* Disable the UNION ALL flattener */
19184 #define SQLITE_IndexedExpr 25 /* Pull exprs from index when able */
19185 #define SQLITE_Coroutines 26 /* Co-routines for subqueries */
@@ -19173,16 +19187,17 @@
19187 #define SQLITE_OnePass 28 /* Single-pass DELETE and UPDATE */
19188 #define SQLITE_OrderBySubq 29 /* ORDER BY in subquery helps outer */
19189 #define SQLITE_StarQuery 30 /* Heurists for star queries */
19190 #define SQLITE_ExistsToJoin 31 /* The EXISTS-to-JOIN optimization */
19191 #define SQLITE_UnionLimit 32 /* Optimizations for UNION + LIMIT */
19192 #define SQLITE_HavingToWhere 33 /* HAVING-to-WHERE optimization */
19193
19194 /*
19195 ** Macros for testing whether or not optimizations are enabled or disabled.
19196 */
19197 #define OptimizationDisabled(D,M) (((D)->dbOptFlags&(1ull<<((M)-1)))!=0)
19198 #define OptimizationEnabled(D,M) (((D)->dbOptFlags&(1ull<<((M)-1)))==0)
19199
19200 /*
19201 ** Return true if it OK to factor constant expressions into the initialization
19202 ** code. The argument is a Parse object for the code generator.
19203 */
@@ -20486,10 +20501,11 @@
20501 unsigned reusable :1; /* Constant expression is reusable */
20502 unsigned bSorterRef :1; /* Defer evaluation until after sorting */
20503 unsigned bNulls :1; /* True if explicit "NULLS FIRST/LAST" */
20504 unsigned bUsed :1; /* This column used in a SF_NestedFrom subquery */
20505 unsigned bUsingTerm:1; /* Term from the USING clause of a NestedFrom */
20506 unsigned bStarName:1; /* RENAME only: zEName from expanding a "*" */
20507 unsigned bNoExpand: 1; /* Term is an auxiliary in NestedFrom and should
20508 ** not be expanded by "*" in parent queries */
20509 } fg;
20510 union {
20511 struct { /* Used by any ExprList other than Parse.pConsExpr */
@@ -21053,20 +21069,26 @@
21069 #if SQLITE_MAX_ATTACHED>30
21070 typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
21071 # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
21072 # define DbMaskZero(M) memset((M),0,sizeof(M))
21073 # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
21074 # define DbMaskUnion(M,X) sqlite3DbMaskUnion(M,X)
21075 # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
21076 # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
21077 #else
21078 typedef unsigned int yDbMask;
21079 # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
21080 # define DbMaskZero(M) ((M)=0)
21081 # define DbMaskSet(M,I) ((M)|=(((yDbMask)1)<<(I)))
21082 # define DbMaskUnion(M,X) ((M)|=(X))
21083 # define DbMaskAllZero(M) ((M)==0)
21084 # define DbMaskNonZero(M) ((M)!=0)
21085 #endif
21086
21087 /* Should be in vdbe.h, but we needed yDbMask definition first */
21088 SQLITE_PRIVATE void sqlite3VdbeSchemaInUse(sqlite3*,Vdbe*,yDbMask*);
21089
21090
21091 /*
21092 ** For each index X that has as one of its arguments either an expression
21093 ** or the name of a virtual generated column, and if X is in scope such that
21094 ** the value of the expression can simply be read from the index, then
@@ -21194,11 +21216,10 @@
21216 ** determined by offsetof(Parse,aTempReg).
21217 **************************************************************************/
21218
21219 int aTempReg[8]; /* Holding area for temporary registers */
21220 Parse *pOuterParse; /* Outer Parse object when nested */
 
21221 u32 oldmask; /* Mask of old.* columns referenced */
21222 u32 newmask; /* Mask of new.* columns referenced */
21223 union {
21224 struct { /* These fields available when isCreate is true */
21225 int addrCrTab; /* Address of OP_CreateBtree on CREATE TABLE */
@@ -21223,11 +21244,12 @@
21244 ** each recursion. The boundary between these two regions is determined
21245 ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
21246 ** first field in the recursive region.
21247 ************************************************************************/
21248
21249 Token sLastToken; /* The last token parsed */
21250 Token sNameToken; /* Token with unqualified schema object name */
21251 ynVar nVar; /* Number of '?' variables seen in the SQL so far */
21252 u64 aVnbmc[SQLITE_VNBMC]; /* Varible Number Bitmap Cache */
21253 u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
21254 u8 explain; /* True if the EXPLAIN flag is found on the query */
21255 u8 eParseMode; /* PARSE_MODE_XXX constant */
@@ -21347,17 +21369,25 @@
21369 ** linked list is stored as the "pTrigger" member of the associated
21370 ** struct Table.
21371 **
21372 ** The "step_list" member points to the first element of a linked list
21373 ** containing the SQL statements specified as the trigger program.
21374 **
21375 ** Trigger.nSelect is a copy of the Parse.nSelect value from when the
21376 ** trigger and its steps were parsed. There are no Select.selId values
21377 ** equal to or greater than this anywhere in the trigger program.
21378 ** Initializing the Parse.nSelect field to this value before coding
21379 ** the trigger program based on these structures ensures that no duplicate
21380 ** selId values are assigned.
21381 */
21382 struct Trigger {
21383 char *zName; /* The name of the trigger */
21384 char *table; /* The table or view to which the trigger applies */
21385 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
21386 u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
21387 u8 bReturning; /* This trigger implements a RETURNING clause */
21388 int nSelect; /* Upper bound on Select.selId in this trigger */
21389 Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
21390 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
21391 the <column-list> is stored here */
21392 Schema *pSchema; /* Schema containing the trigger */
21393 Schema *pTabSchema; /* Schema containing the table */
@@ -22276,11 +22306,11 @@
22306 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
22307 #ifndef SQLITE_OMIT_VIRTUALTABLE
22308 SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
22309 #endif
22310 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
22311 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int,Vdbe*);
22312 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
22313 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
22314 SQLITE_PRIVATE void sqlite3ColumnSetExpr(Parse*,Table*,Column*,Expr*);
22315 SQLITE_PRIVATE Expr *sqlite3ColumnExpr(Table*,Column*);
22316 SQLITE_PRIVATE Expr *sqlite3ColumnExprAuth(Table*,Column*,Parse*);
@@ -22353,10 +22383,11 @@
22383 # define sqlite3ViewGetColumnNames(A,B) 0
22384 #endif
22385
22386 #if SQLITE_MAX_ATTACHED>30
22387 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
22388 SQLITE_PRIVATE void sqlite3DbMaskUnion(yDbMask,yDbMask);
22389 #endif
22390 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
22391 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
22392 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
22393 SQLITE_PRIVATE void sqlite3DeleteTableGeneric(sqlite3*, void*);
@@ -22718,11 +22749,11 @@
22749 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
22750 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
22751 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr*);
22752 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
22753 SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*);
22754 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse*,const char*,const char*,const char*,const char*);
22755 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, i64);
22756 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
22757 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
22758 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
22759 SQLITE_PRIVATE int sqlite3AbsInt32(int);
@@ -22787,10 +22818,11 @@
22818 );
22819 SQLITE_PRIVATE void sqlite3AlterSetNotNull(Parse*, SrcList*, Token*, Token*);
22820 SQLITE_PRIVATE i64 sqlite3GetToken(const unsigned char *, int *);
22821 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
22822 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int);
22823 SQLITE_PRIVATE void sqlite3ExpireStmtsUsingSchema(sqlite3*, int, Vdbe*);
22824 SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int, int);
22825 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr*);
22826 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
22827 SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, SrcItem*);
22828 SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
@@ -22952,16 +22984,16 @@
22984 );
22985 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
22986 #endif
22987 SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db);
22988 #ifndef SQLITE_OMIT_VIRTUALTABLE
22989 SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName, const char *zDb);
22990 SQLITE_PRIVATE int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*);
22991 SQLITE_PRIVATE void sqlite3MarkAllShadowTablesOf(sqlite3*, Table*);
22992 SQLITE_PRIVATE void sqlite3VtabEponymousTableClearAll(sqlite3*);
22993 #else
22994 # define sqlite3ShadowTableName(A,B,C) 0
22995 # define sqlite3IsShadowTableOf(A,B,C) 0
22996 # define sqlite3MarkAllShadowTablesOf(A,B)
22997 # define sqlite3VtabEponymousTableClearAll(X)
22998 #endif
22999 SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
@@ -25999,11 +26031,11 @@
26031 ** The HH, MM, and SS must each be exactly 2 digits. The
26032 ** fractional seconds FFFF can be one or more digits.
26033 **
26034 ** Return 1 if there is a parsing error and 0 on success.
26035 */
26036 static int parseHhMmSs(const char *zDate, DateTime *p, int bAllowTZ){
26037 int h, m, s;
26038 double ms = 0.0;
26039 if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
26040 return 1;
26041 }
@@ -26035,10 +26067,11 @@
26067 p->rawS = 0;
26068 p->validHMS = 1;
26069 p->h = h;
26070 p->m = m;
26071 p->s = s + ms;
26072 if( !bAllowTZ && zDate[0] ) return 1;
26073 if( parseTimezone(zDate, p) ) return 1;
26074 return 0;
26075 }
26076
26077 /*
@@ -26154,11 +26187,11 @@
26187 return 1;
26188 }
26189 if( neg ) Y = -Y;
26190 zDate += 10;
26191 while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
26192 if( parseHhMmSs(zDate, p, 1)==0 ){
26193 if( p->h==24 ){
26194 int mxD = daysOfMonth(Y,M);
26195 p->h = 0;
26196 D++;
26197 if( D>mxD ){
@@ -26245,11 +26278,11 @@
26278 DateTime *p
26279 ){
26280 double r;
26281 if( parseYyyyMmDd(zDate,p)==0 ){
26282 return 0;
26283 }else if( parseHhMmSs(zDate, p, 1)==0 ){
26284 return 0;
26285 }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
26286 return setDateTimeToCurrent(context, p);
26287 }else if( sqlite3AtoF(zDate, &r)>0 ){
26288 setRawDateNumber(p, r);
@@ -26624,10 +26657,11 @@
26657 clearYMD_HMS_TZ(p);
26658 rc = 0;
26659 }else if( sqlite3_stricmp(z,"year")==0 ){
26660 p->M = 12;
26661 p->D = 31;
26662 p->nFloor = 0;
26663 rc = 0;
26664 }else if( sqlite3_stricmp(z,"day")==0 ){
26665 rc = 0;
26666 }
26667 break;
@@ -26640,10 +26674,11 @@
26674 ** previous month.
26675 */
26676 if( sqlite3_stricmp(z, "floor")==0 ){
26677 computeJD(p);
26678 p->iJD -= p->nFloor*86400000;
26679 p->nFloor = 0;
26680 clearYMD_HMS_TZ(p);
26681 rc = 0;
26682 }
26683 break;
26684 }
@@ -26703,11 +26738,13 @@
26738 if( p->isUtc==0 ){
26739 i64 iOrigJD; /* Original localtime */
26740 i64 iGuess; /* Guess at the corresponding utc time */
26741 int cnt = 0; /* Safety to prevent infinite loop */
26742 i64 iErr; /* Guess is off by this much */
26743 int useSubsec; /* Saved subseconds flag */
26744
26745 useSubsec = p->useSubsec;
26746 computeJD(p);
26747 iGuess = iOrigJD = p->iJD;
26748 iErr = 0;
26749 do{
26750 DateTime new;
@@ -26723,10 +26760,11 @@
26760 memset(p, 0, sizeof(*p));
26761 p->iJD = iGuess;
26762 p->validJD = 1;
26763 p->isUtc = 1;
26764 p->isLocal = 0;
26765 p->useSubsec = useSubsec;
26766 }
26767 rc = SQLITE_OK;
26768 }
26769 #endif
26770 break;
@@ -26757,10 +26795,11 @@
26795 if( Z>n ) Z -= 7;
26796 p->iJD += (n - Z)*86400000;
26797 if( strchr(z+8,'-')!=0 ) p->iJD -= 7*86400000;
26798 }
26799 clearYMD_HMS_TZ(p);
26800 p->nFloor = 0;
26801 rc = 0;
26802 }
26803 break;
26804 }
26805 case 's': {
@@ -26796,14 +26835,16 @@
26835 p->rawS = 0;
26836 p->tz = 0;
26837 p->validJD = 0;
26838 if( sqlite3_stricmp(z,"month")==0 ){
26839 p->D = 1;
26840 p->nFloor = 0;
26841 rc = 0;
26842 }else if( sqlite3_stricmp(z,"year")==0 ){
26843 p->M = 1;
26844 p->D = 1;
26845 p->nFloor = 0;
26846 rc = 0;
26847 }else if( sqlite3_stricmp(z,"day")==0 ){
26848 rc = 0;
26849 }
26850 break;
@@ -26896,21 +26937,30 @@
26937 ** omitted.
26938 */
26939
26940 DateTime tx;
26941 sqlite3_int64 day;
26942 int is24hr; /* 1 for a shift of exactly 24:00 */
26943 int bTimeOnly = z2==z; /* This is not the HH:MM tail of a
26944 ** +/-YYYY-MM-DD HH:MM shift, whose own
26945 ** nFloor must survive (e0fe679e7c) */
26946 if( !sqlite3Isdigit(*z2) ) z2++;
26947 memset(&tx, 0, sizeof(tx));
26948 if( parseHhMmSs(z2, &tx, 0) ){
26949 break; /* HH:MM:SS.FFF failed to parse */
26950 }
26951 is24hr = tx.h==24;
26952 computeJD(&tx);
26953 tx.iJD -= 43200000;
26954 day = tx.iJD/86400000;
26955 tx.iJD -= day*86400000;
26956 if( is24hr ) tx.iJD += (sqlite3_int64)86400000;
26957 if( z0=='-' ) tx.iJD = -tx.iJD;
26958 computeJD(p);
26959 clearYMD_HMS_TZ(p);
26960 p->iJD += tx.iJD;
26961 if( bTimeOnly ) p->nFloor = 0;
26962 rc = 0;
26963 break;
26964 }
26965
26966 /* If control reaches this point, it means the transformation is
@@ -27007,13 +27057,14 @@
27057 n = sqlite3_value_bytes(argv[i]);
27058 if( z==0 || parseModifier(context, (char*)z, n, p, i) ) return 1;
27059 }
27060 computeJD(p);
27061 if( p->isError || !validJulianDay(p->iJD) ) return 1;
27062 if( p->validYMD && p->D>28 ){
27063 /* Make sure a YYYY-MM-DD is normalized.
27064 ** Example: 2023-02-31 -> 2023-03-03
27065 */
27066 assert( p->validJD );
27067 p->validYMD = 0;
27068 }
27069 return 0;
27070 }
@@ -33722,11 +33773,11 @@
33773 if( (zz[i]&0xc0)==0x80 ) len--;
33774 }
33775 }
33776 if( width>len ){
33777 sqlite3_int64 sp = width-len;
33778 assert( sp>0 && sp<=0x7fffffff );
33779 sqlite3StrAppendchar64(pAccum, (int)sp, ' ');
33780 if( !flag_leftjustify
33781 && n>0
33782 && sqlite3_str_errcode(pAccum)==0
33783 ){
@@ -37664,11 +37715,11 @@
37715 ** Return an IEEE754 floating point value that approximates d*pow(10,p).
37716 **
37717 ** The (current) algorithm is adapted from the work of Ross Cox at
37718 ** https://github.com/rsc/fpfmt
37719 */
37720 static double sqlite3Fp10Convert2(u64 d, i64 p){
37721 int b, lp, e, adj, s;
37722 u32 pwr10l, mid1;
37723 u64 pwr10h, x, hi, lo, sticky, u, m;
37724 double r;
37725 if( p<POWERSOF10_FIRST ) return 0.0;
@@ -37723,15 +37774,17 @@
37774 **
37775 ** bit 0 => Set if any prefix of the input is valid. Clear if
37776 ** there is no prefix of the input that can be seen as
37777 ** a valid floating point number.
37778 ** bit 1 => Set if the input contains a decimal point or eNNN
37779 ** clause or other text that disqualifies it as an
37780 ** integer value. Zero if the input is an integer.
37781 ** bit 2 => The input is exactly 0.0, not an underflow from
37782 ** some value near zero.
37783 ** bit 3 => Set if there are more than about 19 significant
37784 ** digits in the input.
37785 ** bit 4 => The input is a special value like "Inf" or "NaN"
37786 **
37787 ** If the input contains a syntax error but begins with text that might
37788 ** be a valid number of some kind, then the result is negative. The
37789 ** result is only zero if no prefix of the input could be interpreted as
37790 ** a number.
@@ -37760,11 +37813,11 @@
37813 SQLITE_PRIVATE int sqlite3AtoF(const char *zIn, double *pResult){
37814 #ifndef SQLITE_OMIT_FLOATING_POINT
37815 const unsigned char *z = (const unsigned char*)zIn;
37816 int neg = 0; /* True for a negative value */
37817 u64 s = 0; /* mantissa */
37818 i64 d = 0; /* Value is s * pow(10,d) */
37819 int mState = 0; /* 1: digit seen 2: fp 4: hard-zero */
37820 unsigned v; /* Value of a single digit */
37821
37822 start_of_text:
37823 if( (v = (unsigned)z[0] - '0')<10 ){
@@ -37812,12 +37865,17 @@
37865 *pResult = 0.0;
37866 return 0;
37867 }
37868 mState |= 2;
37869 }else if( mState==0 ){
37870 if( sqlite3StrICmp((const char*)z,"Inf")==0 ){
37871 *pResult = neg ? -INFINITY : INFINITY;
37872 return 0x13;
37873 }else{
37874 *pResult = 0.0;
37875 return 0;
37876 }
37877 }
37878
37879 /* if exponent is present */
37880 if( *z=='e' || *z=='E' ){
37881 int esign;
@@ -37833,18 +37891,18 @@
37891 z++;
37892 }
37893 }
37894 /* copy digits to exponent */
37895 if( (v = (unsigned)z[0] - '0')<10 ){
37896 u64 exp = v;
37897 z++;
37898 mState |= 2;
37899 while( (v = (unsigned)z[0] - '0')<10 ){
37900 exp = exp*10 + v + (exp & (0xffULL<<32));
37901 z++;
37902 }
37903 d += esign*(exp & ((1ULL<<48)-1));
37904 }else{
37905 z--; /* Leave z[0] at 'e' or '+' or '-',
37906 ** so that the return is 0 or -1 */
37907 }
37908 }
@@ -39387,11 +39445,10 @@
39445 }
39446 insertElement(pH, pH->ht ? &pH->ht[new_elem->h % pH->htsize] : 0, new_elem);
39447 return 0;
39448 }
39449
 
39450 /************** End of hash.c ************************************************/
39451 /************** Begin file opcodes.c *****************************************/
39452 /* Automatically generated. Do not edit */
39453 /* See the tool/mkopcodec.tcl script for details. */
39454 #if !defined(SQLITE_OMIT_EXPLAIN) \
@@ -39539,64 +39596,66 @@
39596 /* 132 */ "ResetCount" OpHelp(""),
39597 /* 133 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
39598 /* 134 */ "SorterData" OpHelp("r[P2]=data"),
39599 /* 135 */ "RowData" OpHelp("r[P2]=data"),
39600 /* 136 */ "Rowid" OpHelp("r[P2]=PX rowid of P1"),
39601 /* 137 */ "Stale" OpHelp(""),
39602 /* 138 */ "NullRow" OpHelp(""),
39603 /* 139 */ "SeekEnd" OpHelp(""),
39604 /* 140 */ "IdxInsert" OpHelp("key=r[P2]"),
39605 /* 141 */ "SorterInsert" OpHelp("key=r[P2]"),
39606 /* 142 */ "IdxDelete" OpHelp("key=r[P2@P5]"),
39607 /* 143 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),
39608 /* 144 */ "IdxRowid" OpHelp("r[P2]=rowid"),
39609 /* 145 */ "FinishSeek" OpHelp(""),
39610 /* 146 */ "Destroy" OpHelp(""),
39611 /* 147 */ "DbLock" OpHelp(""),
39612 /* 148 */ "Clear" OpHelp(""),
39613 /* 149 */ "ResetSorter" OpHelp(""),
39614 /* 150 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),
39615 /* 151 */ "SqlExec" OpHelp(""),
39616 /* 152 */ "ParseSchema" OpHelp(""),
39617 /* 153 */ "LoadAnalysis" OpHelp(""),
39618 /* 154 */ "Real" OpHelp("r[P2]=PDBL13"),
39619 /* 155 */ "DropTable" OpHelp(""),
39620 /* 156 */ "DropIndex" OpHelp(""),
39621 /* 157 */ "DropTrigger" OpHelp(""),
39622 /* 158 */ "IntegrityCk" OpHelp(""),
39623 /* 159 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
39624 /* 160 */ "Param" OpHelp(""),
39625 /* 161 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
39626 /* 162 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
39627 /* 163 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
39628 /* 164 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"),
39629 /* 165 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
39630 /* 166 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"),
39631 /* 167 */ "AggValue" OpHelp("r[P3]=value N=P2"),
39632 /* 168 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
39633 /* 169 */ "Expire" OpHelp(""),
39634 /* 170 */ "CursorLock" OpHelp(""),
39635 /* 171 */ "CursorUnlock" OpHelp(""),
39636 /* 172 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
39637 /* 173 */ "VBegin" OpHelp(""),
39638 /* 174 */ "VCreate" OpHelp(""),
39639 /* 175 */ "VDestroy" OpHelp(""),
39640 /* 176 */ "VOpen" OpHelp(""),
39641 /* 177 */ "VCheck" OpHelp(""),
39642 /* 178 */ "VInitIn" OpHelp("r[P2]=ValueList(P1,P3)"),
39643 /* 179 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
39644 /* 180 */ "VRename" OpHelp(""),
39645 /* 181 */ "Pagecount" OpHelp(""),
39646 /* 182 */ "MaxPgcnt" OpHelp(""),
39647 /* 183 */ "ClrSubtype" OpHelp("r[P1].subtype = 0"),
39648 /* 184 */ "GetSubtype" OpHelp("r[P2] = r[P1].subtype"),
39649 /* 185 */ "SetSubtype" OpHelp("r[P2].subtype = r[P1]"),
39650 /* 186 */ "FilterAdd" OpHelp("filter(P1) += key(P3@P4)"),
39651 /* 187 */ "Trace" OpHelp(""),
39652 /* 188 */ "CursorHint" OpHelp(""),
39653 /* 189 */ "ReleaseReg" OpHelp("release r[P1@P2] mask P3"),
39654 /* 190 */ "Noop" OpHelp(""),
39655 /* 191 */ "Explain" OpHelp(""),
39656 /* 192 */ "Abortable" OpHelp(""),
39657 };
39658 return azName[i];
39659 }
39660 #endif
39661
@@ -41832,11 +41891,11 @@
41891 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
41892 struct vxworksFileId *pNew; /* search key and new file ID */
41893 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
41894 int n; /* Length of zAbsoluteName string */
41895
41896 if( zAbsoluteName==0 || zAbsoluteName[0]=='/' );
41897 n = (int)strlen(zAbsoluteName);
41898 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
41899 if( pNew==0 ) return 0;
41900 pNew->zCanonicalName = (char*)&pNew[1];
41901 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
@@ -45261,23 +45320,23 @@
45320 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
45321 sqlite3_mutex *pShmMutex; /* Mutex to access this object */
45322 char *zFilename; /* Name of the mmapped file */
45323 int hShm; /* Open file descriptor */
45324 int szRegion; /* Size of shared-memory regions */
45325 int nRegion; /* Size of array apRegion */
45326 int nRef; /* Number of unixShm objects pointing to this */
45327 u8 isReadonly; /* True if read-only */
45328 u8 isUnlocked; /* True if no DMS lock held */
45329 #ifdef SQLITE_DEBUG
45330 u8 nextShmId; /* Next available unixShm.id value */
45331 #endif
45332 char **apRegion; /* Array of mapped shared-memory regions */
 
45333 unixShm *pFirst; /* All unixShm objects pointing to this */
45334 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
45335 sqlite3_mutex *aMutex[SQLITE_SHM_NLOCK];
45336 #endif
45337 int aLock[SQLITE_SHM_NLOCK]; /* # shared locks on slot, -1==excl lock */
 
 
 
45338 };
45339
45340 /*
45341 ** Structure used internally by this VFS to record the state of an
45342 ** open shared memory connection.
@@ -46809,14 +46868,18 @@
46868 if( strcmp(pVfs->zName,"unix-excl")==0 ){
46869 pNew->ctrlFlags |= UNIXFILE_EXCL;
46870 }
46871
46872 #if OS_VXWORKS
46873 if( zFilename ){
46874 pNew->pId = vxworksFindFileId(zFilename);
46875 if( pNew->pId==0 ){
46876 ctrlFlags |= UNIXFILE_NOLOCK;
46877 rc = SQLITE_NOMEM_BKPT;
46878 }
46879 }else{
46880 pNew->pId = 0;
46881 }
46882 #endif
46883
46884 if( ctrlFlags & UNIXFILE_NOLOCK ){
46885 pLockingStyle = &nolockIoMethods;
@@ -46917,16 +46980,19 @@
46980 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
46981 char *zSemName = pNew->pInode->aSemName;
46982 int n;
46983 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
46984 pNew->pId->zCanonicalName);
46985 for(n=1; zSemName[n]; n++){
46986 if( zSemName[n]=='/' && !sqlite3FaultSim(801) ) zSemName[n] = '_';
46987 }
46988 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
46989 if( pNew->pInode->pSem == SEM_FAILED ){
46990 rc = SQLITE_NOMEM_BKPT;
46991 pNew->pInode->aSemName[0] = '\0';
46992 releaseInodeInfo(pNew);
46993 pNew->pInode = 0;
46994 }
46995 }
46996 unixLeaveMutex();
46997 }
46998 #endif
@@ -61074,15 +61140,22 @@
61140 **
61141 ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
61142 ** file has been created already (via a spill on pagerStress()) and
61143 ** when the number of dirty pages in memory exceeds 25% of the total
61144 ** cache size.
61145 **
61146 ** * Never sync a TEMP database if the current transaction has not
61147 ** modified the database (eState<PAGER_WRITER_CACHEMOD). In this case
61148 ** sqlite3PagerCommitPhaseOne() returns early without flushing any
61149 ** dirty pages left over from earlier transactions, so they must not
61150 ** be marked as clean by pager_end_transaction().
61151 */
61152 static int pagerFlushOnCommit(Pager *pPager, int bCommit){
61153 if( pPager->tempFile==0 ) return 1;
61154 if( !bCommit ) return 0;
61155 if( !isOpen(pPager->fd) ) return 0;
61156 if( pPager->eState<PAGER_WRITER_CACHEMOD ) return 0;
61157 return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
61158 }
61159
61160 /*
61161 ** This routine ends a transaction. A transaction is usually ended by
@@ -65750,10 +65823,15 @@
65823 if( rc!=SQLITE_OK ){
65824 sqlite3OsClose(pPager->jfd);
65825 goto commit_phase_one_exit;
65826 }
65827 bBatch = 0;
65828
65829 /* The journal file was just created on disk. Sync it now before
65830 ** any pages are written to the database file. */
65831 rc = syncJournal(pPager, 0);
65832 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
65833 }else{
65834 sqlite3OsClose(pPager->jfd);
65835 }
65836 }
65837 #endif /* SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
@@ -78225,32 +78303,38 @@
78303
78304 /*
78305 ** This variant of sqlite3BtreePayload() works even if the cursor has not
78306 ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
78307 ** interface.
78308 **
78309 ** If the cursor has to be restored to its saved position, then SQLITE_MOVED
78310 ** is returned and no data is read. The content of the row might have changed
78311 ** while the cursor position was saved, so the caller needs to recompute the
78312 ** size and offset of the data it is reading before it tries again. If the
78313 ** row no longer exists, SQLITE_ABORT is returned.
78314 */
78315 #ifndef SQLITE_OMIT_INCRBLOB
78316 static SQLITE_NOINLINE int accessPayloadChecked(BtCursor *pCur){
 
 
 
 
 
78317 int rc;
78318 if ( pCur->eState==CURSOR_INVALID ){
78319 return SQLITE_ABORT;
78320 }
78321 assert( cursorOwnsBtShared(pCur) );
78322 rc = btreeRestoreCursorPosition(pCur);
78323 if( rc ) return rc;
78324 if( pCur->eState!=CURSOR_VALID ){
78325 /* The row is gone, and the cursor was restored onto a neighbor. */
78326 return SQLITE_ABORT;
78327 }
78328 return SQLITE_MOVED;
78329 }
78330 SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
78331 if( pCur->eState==CURSOR_VALID ){
78332 assert( cursorOwnsBtShared(pCur) );
78333 return accessPayload(pCur, offset, amt, pBuf, 0);
78334 }else{
78335 return accessPayloadChecked(pCur);
78336 }
78337 }
78338 #endif /* SQLITE_OMIT_INCRBLOB */
78339
78340 /*
@@ -79871,14 +79955,12 @@
79955 }
79956 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
79957 pBt = pPage->pBt;
79958 assert( pBt->usableSize > 4 );
79959 ovflPageSize = pBt->usableSize - 4;
79960 nOvfl = (pInfo->nPayload - pInfo->nLocal + (u64)ovflPageSize-1)/ovflPageSize;
79961 assert( nOvfl>0 );
 
 
79962 while( nOvfl-- ){
79963 Pgno iNext = 0;
79964 MemPage *pOvfl = 0;
79965 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
79966 /* 0 is not a legal page number and page 1 cannot be an
@@ -82331,10 +82413,11 @@
82413 if( pCur->eState>=CURSOR_REQUIRESEEK ){
82414 testcase( pCur->eState==CURSOR_REQUIRESEEK );
82415 testcase( pCur->eState==CURSOR_FAULT );
82416 rc = moveToRoot(pCur);
82417 if( rc && rc!=SQLITE_EMPTY ) return rc;
82418 loc = 0; /* Indicate the the cursor is not in a known position */
82419 }
82420
82421 assert( cursorOwnsBtShared(pCur) );
82422 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
82423 && p->pBt->inTransaction==TRANS_WRITE
@@ -82354,15 +82437,17 @@
82437 ** cursors open on the row being replaced */
82438 if( p->hasIncrblobCur ){
82439 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
82440 }
82441
82442 /* If BTREE_SAVEPOSITION is set and seekResult is non-zero and
82443 ** if we didn't have to reposition the cursor initially, then
82444 ** the cursor must already be pointing to a row with the same
82445 ** key as the new entry being inserted. Verify that this is so.
82446 */
82447 #ifdef SQLITE_DEBUG
82448 if( (flags & BTREE_SAVEPOSITION)!=0 && loc!=0 ){
82449 assert( pCur->curFlags & BTCF_ValidNKey );
82450 assert( pX->nKey==pCur->info.nKey );
82451 assert( loc==0 );
82452 }
82453 #endif
@@ -86019,11 +86104,15 @@
86104 }
86105 }
86106 assert( j<=n/2 );
86107 zCopy[j] = 0;
86108 rc = sqlite3AtoF(zCopy, pValue);
86109 if( i<n && rc>0 ){
86110 /* Only a prefix was converted. Adjust rc to match would
86111 ** sqlite3AtoF() would have done. */
86112 rc |= -16;
86113 }
86114 sqlite3DbFree(pMem->db, zCopy);
86115 }
86116 return rc;
86117 }
86118 }
@@ -87162,11 +87251,11 @@
87251
87252 if( op==TK_CAST ){
87253 u8 aff;
87254 assert( !ExprHasProperty(pExpr, EP_IntValue) );
87255 aff = sqlite3AffinityType(pExpr->u.zToken,0);
87256 rc = valueFromExpr(db, pExpr->pLeft, enc, SQLITE_AFF_BLOB, ppVal, pCtx);
87257 testcase( rc!=SQLITE_OK );
87258 if( *ppVal ){
87259 #ifdef SQLITE_ENABLE_STAT4
87260 rc = ExpandBlob(*ppVal);
87261 #else
@@ -88420,10 +88509,13 @@
88509 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
88510 || opcode==OP_VDestroy
88511 || opcode==OP_VCreate
88512 || opcode==OP_ParseSchema
88513 || opcode==OP_Function || opcode==OP_PureFunc
88514 || opcode==OP_AggStep || opcode==OP_AggInverse
88515 || opcode==OP_AggFinal || opcode==OP_AggValue
88516 || opcode==OP_VFilter || opcode==OP_VColumn
88517 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
88518 && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
88519 || (opcode==OP_MustBeInt && pOp->p2==0)
88520 ){
88521 hasAbort = 1;
@@ -89992,10 +90084,12 @@
90084 if( eMode==2 ){
90085 Op *pOp = aOp + i;
90086 if( pOp->opcode==OP_OpenRead ) break;
90087 if( pOp->opcode==OP_OpenWrite && (pOp->p5 & OPFLAG_P2ISREG)==0 ) break;
90088 if( pOp->opcode==OP_ReopenIdx ) break;
90089 if( pOp->opcode==OP_Clear ) break;
90090 if( pOp->opcode==OP_Destroy ) break;
90091 }else
90092 #endif
90093 {
90094 assert( eMode==1 );
90095 if( aOp[i].opcode==OP_Explain ) break;
@@ -90846,10 +90940,26 @@
90940 assert( nRead==db->nVdbeRead );
90941 }
90942 #else
90943 #define checkActiveVdbeCnt(x)
90944 #endif
90945
90946 /*
90947 ** Return a bitmask of all schemas referenced by active VDBEs, other
90948 ** than pExcept.
90949 */
90950 SQLITE_PRIVATE void sqlite3VdbeSchemaInUse(sqlite3 *db, Vdbe *pExcept, yDbMask *pM){
90951 Vdbe *p;
90952 yDbMask m;
90953 DbMaskZero(m);
90954 for(p=db->pVdbe; p; p=p->pVNext){
90955 if( p==pExcept ) continue;
90956 if( p->eVdbeState!=VDBE_RUN_STATE ) continue;
90957 DbMaskUnion(m,p->btreeMask);
90958 }
90959 memcpy(pM, &m, sizeof(m));
90960 }
90961
90962 /*
90963 ** If the Vdbe passed as the first argument opened a statement-transaction,
90964 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
90965 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
@@ -91152,10 +91262,17 @@
91262 ** to invoke any required unlock-notify callbacks.
91263 */
91264 if( db->autoCommit ){
91265 sqlite3ConnectionUnlocked(db);
91266 }
91267
91268 /* Do any pending schema resets that were deferred because multiple
91269 ** VDBEs where active at the same time.
91270 */
91271 if( db->bPendingSchemaReset && db->nVdbeActive==0 ){
91272 sqlite3ResetOneSchema(db, -1, 0);
91273 }
91274
91275 assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
91276 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
91277 }
91278
@@ -92919,10 +93036,27 @@
93036 Vdbe *p;
93037 for(p = db->pVdbe; p; p=p->pVNext){
93038 p->expired = iCode+1;
93039 }
93040 }
93041
93042 /*
93043 ** Expire (urgently, with iCode 0) every prepared statement that is using
93044 ** a particular schema (iDb).
93045 */
93046 SQLITE_PRIVATE void sqlite3ExpireStmtsUsingSchema(
93047 sqlite3 *db, /* The database connection statements belong to */
93048 int iDb, /* Index of the schema they are using */
93049 Vdbe *pExcept /* Except, don't expire this one */
93050 ){
93051 Vdbe *p;
93052 for(p = db->pVdbe; p; p=p->pVNext){
93053 if( p==pExcept ) continue;
93054 if( !DbMaskTest(p->btreeMask, iDb) ) continue;
93055 p->expired = 1;
93056 }
93057 }
93058
93059 /*
93060 ** Return the database associated with the Vdbe.
93061 */
93062 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
@@ -93512,10 +93646,13 @@
93646 rc = SQLITE_OK;
93647 }else{
93648 Vdbe *v = (Vdbe*)pStmt;
93649 sqlite3 *db = v->db;
93650 if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
93651 #if defined(SQLITE_DISPOSAL_NOTIFIER)
93652 SQLITE_DISPOSAL_NOTIFIER(2,pStmt);
93653 #endif
93654 sqlite3_mutex_enter(db->mutex);
93655 checkProfileCallback(db, v);
93656 assert( v->eVdbeState>=VDBE_READY_STATE );
93657 rc = sqlite3VdbeReset(v);
93658 sqlite3VdbeDelete(v);
@@ -99426,11 +99563,11 @@
99563 case OP_IfNullRow: { /* jump */
99564 VdbeCursor *pC;
99565 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99566 pC = p->apCsr[pOp->p1];
99567 if( pC && pC->nullRow ){
99568 if( pOp->p3>0 ) sqlite3VdbeMemSetNull(aMem + pOp->p3);
99569 goto jump_to_p2;
99570 }
99571 break;
99572 }
99573
@@ -99890,10 +100027,11 @@
100027 Column *aCol;
100028 int i;
100029 int nCol;
100030
100031 assert( pOp->p4type==P4_TABLE );
100032 if( p->expired==1 ) goto abort_due_to_expired;
100033 pTab = pOp->p4.pTab;
100034 assert( pTab->tabFlags & TF_Strict );
100035 assert( pOp->p3>=0 && pOp->p3<pTab->nCol+2 );
100036 aCol = pTab->aCol;
100037 pIn1 = &aMem[pOp->p1];
@@ -99942,15 +100080,15 @@
100080 testcase( pIn1->u.i==140737488355327LL );
100081 testcase( pIn1->u.i==-140737488355328LL );
100082 testcase( pIn1->u.i==-140737488355329LL );
100083 if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL){
100084 pIn1->flags |= MEM_IntReal;
100085 pIn1->flags &= ~(MEM_Int|MEM_Str);
100086 }else{
100087 pIn1->u.r = (double)pIn1->u.i;
100088 pIn1->flags |= MEM_Real;
100089 pIn1->flags &= ~(MEM_Int|MEM_Str);
100090 }
100091 }else if( (pIn1->flags & (MEM_Real|MEM_IntReal))==0 ){
100092 goto vdbe_type_error;
100093 }
100094 break;
@@ -100089,11 +100227,11 @@
100227 pRec = pData0;
100228 do{
100229 applyAffinity(pRec, zAffinity[0], encoding);
100230 if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){
100231 pRec->flags |= MEM_IntReal;
100232 pRec->flags &= ~(MEM_Int|MEM_Str);
100233 }
100234 REGISTER_TRACE((int)(pRec-aMem), pRec);
100235 zAffinity++;
100236 pRec++;
100237 assert( zAffinity[0]==0 || pRec<=pLast );
@@ -100217,17 +100355,17 @@
100355 assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) );
100356 assert( pRec->n>=0 );
100357 len = (u32)pRec->n;
100358 serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);
100359 if( pRec->flags & MEM_Zero ){
 
100360 if( nData ){
100361 if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
100362 len += pRec->u.nZero;
100363 }else{
100364 nZero += pRec->u.nZero;
100365 }
100366 serial_type += 2*(u32)pRec->u.nZero;
100367 }
100368 nData += len;
100369 nHdr += sqlite3VarintLen(serial_type);
100370 pRec->uTemp = serial_type;
100371 }
@@ -100789,11 +100927,11 @@
100927 ** v-table would have to be ready for the sqlite3_vtab structure itself
100928 ** to be invalidated whenever sqlite3_step() is called from within
100929 ** a v-table method.
100930 */
100931 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
100932 sqlite3ResetOneSchema(db, pOp->p1, p);
100933 }
100934 p->expired = 1;
100935 rc = SQLITE_SCHEMA;
100936
100937 /* Set changeCntOn to 0 to prevent the value returned by sqlite3_changes()
@@ -100936,11 +101074,14 @@
101074 /* Opcode: OpenWrite P1 P2 P3 P4 P5
101075 ** Synopsis: root=P2 iDb=P3
101076 **
101077 ** Open a read/write cursor named P1 on the table or index whose root
101078 ** page is P2 (or whose root page is held in register P2 if the
101079 ** OPFLAG_P2ISREG bit is set in P5 - see below). The database file is
101080 ** determined by P3. P3==0 means the main database, P3==1 means the
101081 ** database used for temporary tables, and P3>1 means used the
101082 ** corresponding attached database.
101083 **
101084 ** The P4 value may be either an integer (P4_INT32) or a pointer to
101085 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
101086 ** object, then table being opened must be an [index b-tree] where the
101087 ** KeyInfo object defines the content and collating
@@ -102122,11 +102263,11 @@
102263 ** integer value of pIn3. Jump to P2 if pIn3 cannot be converted
102264 ** into an integer without loss of information. Take care to avoid
102265 ** changing the datatype of pIn3, however, as it is used by other
102266 ** parts of the prepared statement. */
102267 Mem x = pIn3[0];
102268 if( (x.flags & (MEM_Str|MEM_Int|MEM_Real|MEM_IntReal))==MEM_Str ){
102269 applyNumericAffinity(&x, 1);
102270 }
102271 if( x.flags & MEM_Int ){
102272 iKey = x.u.i;
102273 }else
@@ -102399,10 +102540,11 @@
102540 REGISTER_TRACE(pOp->p3, pKey);
102541 x.nKey = pKey->u.i;
102542
102543 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
102544 assert( pC->iDb>=0 );
102545 if( p->expired==1 ) goto abort_due_to_expired;
102546 zDb = db->aDb[pC->iDb].zDbSName;
102547 pTab = pOp->p4.pTab;
102548 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
102549 }else{
102550 pTab = 0;
@@ -102541,10 +102683,11 @@
102683 assert( pC->deferredMoveto==0 );
102684 sqlite3VdbeIncrWriteCounter(p, pC);
102685
102686 #ifdef SQLITE_DEBUG
102687 if( pOp->p4type==P4_TABLE
102688 && !p->expired
102689 && HasRowid(pOp->p4.pTab)
102690 && pOp->p5==0
102691 && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
102692 ){
102693 /* If p5 is zero, the seek operation that positioned the cursor prior to
@@ -102559,10 +102702,11 @@
102702 ** the name of the db to pass as to it. Also set local pTab to a copy
102703 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
102704 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
102705 ** VdbeCursor.movetoTarget to the current rowid. */
102706 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
102707 if( p->expired==1 ) goto abort_due_to_expired;
102708 assert( pC->iDb>=0 );
102709 assert( pOp->p4.pTab!=0 );
102710 zDb = db->aDb[pC->iDb].zDbSName;
102711 pTab = pOp->p4.pTab;
102712 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
@@ -102815,10 +102959,26 @@
102959 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
102960 }
102961 pOut->u.i = v;
102962 break;
102963 }
102964
102965 /* Opcode: Stale P1 * * * *
102966 **
102967 ** Mark the row cache for cursor P1 as stale. This opcode is used
102968 ** on pseudo-cursors right before the content of the register that
102969 ** holds their record is modified.
102970 */
102971 case OP_Stale: {
102972 VdbeCursor *pC;
102973
102974 pC = p->apCsr[pOp->p1];
102975 assert( pC!=0 );
102976 assert( pC->eCurType==CURTYPE_PSEUDO );
102977 pC->cacheStatus = CACHE_STALE;
102978 break;
102979 }
102980
102981 /* Opcode: NullRow P1 P2 * * *
102982 **
102983 ** Move the cursor P1 to a null row if P2 is 0. Any OP_Column operations
102984 ** that occur while the cursor is on the null row will always
@@ -102830,10 +102990,11 @@
102990 ** If P2 is not 0, then the nullRow flag on the pseudo-cursor is
102991 ** turned off.
102992 */
102993 case OP_NullRow: {
102994 VdbeCursor *pC;
102995 Mem *pMem;
102996
102997 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
102998 pC = p->apCsr[pOp->p1];
102999 if( pC==0 ){
103000 /* If the cursor is not already open, create a special kind of
@@ -102848,10 +103009,18 @@
103009 pC->nullRow = (pOp->p2==0);
103010 pC->cacheStatus = CACHE_STALE;
103011 if( pC->eCurType==CURTYPE_BTREE ){
103012 assert( pC->uc.pCursor!=0 );
103013 sqlite3BtreeClearCursor(pC->uc.pCursor);
103014 }else if( pC->eCurType==CURTYPE_PSEUDO && pC->seekResult>0 ){
103015 static char nullRecord[] = { 0x02, 0x00 };
103016 pMem = &aMem[pC->seekResult];
103017 assert( !VdbeMemDynamic(pMem) );
103018 pC->nullRow = 1;
103019 pMem->z = nullRecord;
103020 pMem->n = 2;
103021 pMem->flags = MEM_Blob|MEM_Ephem;
103022 }
103023 #ifdef SQLITE_DEBUG
103024 if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
103025 #endif
103026 break;
@@ -103288,10 +103457,11 @@
103457 r.default_rc = 0;
103458 r.aMem = &aMem[pOp->p2];
103459 rc = sqlite3BtreeIndexMoveto(pCrsr, &r, &res);
103460 if( rc ) goto abort_due_to_error;
103461 if( res!=0 ){
103462 if( p->expired==1 ) goto abort_due_to_expired;
103463 rc = sqlite3VdbeFindIndexKey(pCrsr, pOp->p4.pIdx, &r, &res, 0);
103464 if( rc!=SQLITE_OK ) goto abort_due_to_error;
103465 if( res!=0 ){
103466 if( !sqlite3WritableSchema(db) ){
103467 rc = sqlite3ReportError(
@@ -103601,10 +103771,25 @@
103771 }
103772 #endif
103773 }
103774 break;
103775 }
103776
103777 /*
103778 ** Opcode: DbLock
103779 **
103780 ** Raise an SQLITE_LOCKED error if there are any other reader statements
103781 ** currently active.
103782 */
103783 case OP_DbLock: {
103784 if( db->nVdbeRead>1 ){
103785 rc = SQLITE_LOCKED;
103786 p->errorAction = OE_Abort;
103787 goto abort_due_to_error;
103788 }
103789 break;
103790 };
103791
103792 /* Opcode: Clear P1 P2 P3
103793 **
103794 ** Delete all contents of the database table or index whose root page
103795 ** in the database file is given by P1. But, unlike Destroy, do not
@@ -103784,13 +103969,17 @@
103969 assert( iDb>=0 && iDb<db->nDb );
103970 assert( DbHasProperty(db, iDb, DB_SchemaLoaded)
103971 || db->mallocFailed
103972 || (CORRUPT_DB && (db->flags & SQLITE_NoSchemaError)!=0) );
103973
103974 /* ParseSchema is never invoked on a read-only database */
103975 assert( db->aDb[iDb].pBt==0 || sqlite3BtreeIsReadonly(db->aDb[iDb].pBt)==0 );
103976
103977 #ifndef SQLITE_OMIT_ALTERTABLE
103978 if( pOp->p4.z==0 ){
103979 assert( pOp->p5!=0 );
103980 sqlite3ExpireStmtsUsingSchema(db, iDb, p);
103981 sqlite3SchemaClear(db->aDb[iDb].pSchema);
103982 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
103983 rc = sqlite3InitOne(db, iDb, &p->zErrMsg, pOp->p5);
103984 db->mDbFlags |= DBFLAG_SchemaChange;
103985 p->expired = 0;
@@ -103827,10 +104016,11 @@
104016 db->init.busy = 0;
104017 }
104018 }
104019 if( rc ){
104020 sqlite3ResetAllSchemasOfConnection(db);
104021 sqlite3ExpirePreparedStatements(db, 0);
104022 if( rc==SQLITE_NOMEM ){
104023 goto no_mem;
104024 }
104025 goto abort_due_to_error;
104026 }
@@ -103985,10 +104175,11 @@
104175 assert( pOp[-1].opcode==OP_Found );
104176 assert( pOp[-1].p1==pOp->p1 );
104177 assert( pOp[-1].p3==pOp->p3 );
104178 pC = p->apCsr[pOp->p1];
104179 assert( pOp->p4type==P4_INDEX );
104180 if( p->expired==1 ) goto abort_due_to_expired;
104181 assert( pC->eCurType==CURTYPE_BTREE );
104182 assert( pC->uc.pCursor!=0 );
104183 assert( pC->isTable==0 );
104184
104185 memset(&r, 0, sizeof(r));
@@ -105984,11 +106175,11 @@
106175 if( rc==SQLITE_CORRUPT && db->autoCommit==0 ){
106176 db->flags |= SQLITE_CorruptRdOnly;
106177 }
106178 rc = SQLITE_ERROR;
106179 if( resetSchemaOnFault>0 ){
106180 sqlite3ResetOneSchema(db, resetSchemaOnFault-1, p);
106181 }
106182
106183 /* This is the only way out of this procedure. We have to
106184 ** release the mutexes on btrees that were acquired at the
106185 ** top. */
@@ -106045,10 +106236,14 @@
106236 */
106237 abort_due_to_interrupt:
106238 assert( AtomicLoad(&db->u1.isInterrupted) );
106239 rc = SQLITE_INTERRUPT;
106240 goto abort_due_to_error;
106241
106242 abort_due_to_expired:
106243 rc = SQLITE_SCHEMA;
106244 goto abort_due_to_error;
106245 }
106246
106247
106248 /************** End of vdbe.c ************************************************/
106249 /************** Begin file vdbeblob.c ****************************************/
@@ -106078,10 +106273,11 @@
106273 typedef struct Incrblob Incrblob;
106274 struct Incrblob {
106275 int nByte; /* Size of open blob, in bytes */
106276 int iOffset; /* Byte offset of blob in cursor data */
106277 u16 iCol; /* Table column this handle is open on */
106278 u8 bRetry; /* Doing a blobReadWrite() retry */
106279 BtCursor *pCsr; /* Cursor pointing at blob row */
106280 sqlite3_stmt *pStmt; /* Statement holding cursor open */
106281 sqlite3 *db; /* The associated database */
106282 char *zDb; /* Database name */
106283 Table *pTab; /* Table object */
@@ -106426,10 +106622,71 @@
106622 }else{
106623 rc = SQLITE_OK;
106624 }
106625 return rc;
106626 }
106627
106628 /* Forward reference */
106629 static int blobReadWrite(
106630 sqlite3_blob *pBlob,
106631 void *z,
106632 int n,
106633 int iOffset,
106634 int (*xCall)(BtCursor*, u32, u32, void*)
106635 );
106636
106637 /*
106638 ** The b-tree cursor for blob handle p was restored to its saved position by
106639 ** sqlite3BtreePayloadChecked(), which then returned SQLITE_MOVED. The
106640 ** position is saved, for example, by a ROLLBACK, and that might have changed
106641 ** the content of the row. So the iOffset and nByte values computed when the
106642 ** handle was opened or last moved cannot be trusted. A ROLLBACK can change
106643 ** the size of a column that precedes the blob, which moves the blob within
106644 ** the row.
106645 **
106646 ** Recompute iOffset and nByte in the same way that sqlite3_blob_reopen()
106647 ** does. Then retry the blobReadWrite().
106648 */
106649 static SQLITE_NOINLINE int blobReadWriteRetry(
106650 Incrblob *p,
106651 void *z,
106652 int n,
106653 int iOffset,
106654 int (*xCall)(BtCursor*, u32, u32, void*)
106655 ){
106656 int rc;
106657 sqlite3_int64 iRow;
106658 char *zErr = 0;
106659 sqlite3 *db = p->db;
106660
106661 sqlite3BtreeEnterCursor(p->pCsr);
106662 iRow = sqlite3BtreeIntegerKey(p->pCsr);
106663 sqlite3BtreeLeaveCursor(p->pCsr);
106664 ((Vdbe*)p->pStmt)->rc = SQLITE_OK;
106665 if( NEVER(p->bRetry) || sqlite3FaultSim(210) ){
106666 /* It should not be possible for blobReadWrite() and blobReadWriteRetry()
106667 ** to get into a loop, but we check anyway, for safety. */
106668 rc = SQLITE_ABORT;
106669 sqlite3VdbeFinalize((Vdbe*)p->pStmt);
106670 p->pStmt = 0;
106671 }else{
106672 rc = blobSeekToRow(p, iRow, &zErr);
106673 }
106674 assert( rc==SQLITE_OK || p->pStmt==0 );
106675 if( rc==SQLITE_OK ){
106676 sqlite3DbFree(db, zErr);
106677 p->bRetry = 1;
106678 rc = blobReadWrite((sqlite3_blob*)p,z,n,iOffset,xCall);
106679 p->bRetry = 0;
106680 }else{
106681 sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : (char*)0), zErr);
106682 sqlite3DbFree(db, zErr);
106683 rc = sqlite3ApiExit(db, rc);
106684 }
106685 sqlite3_mutex_leave(db->mutex);
106686 return rc;
106687 }
106688
106689 /*
106690 ** Perform a read or write operation on a blob
106691 */
106692 static int blobReadWrite(
@@ -106504,15 +106761,25 @@
106761 #else
106762 rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
106763 #endif
106764
106765 sqlite3BtreeLeaveCursor(p->pCsr);
106766 if( rc==SQLITE_OK ){
106767 v->rc = SQLITE_OK;
 
106768 }else{
106769 if( rc==SQLITE_MOVED ){
106770 /* The cursor was restored and no data was read. Refresh the
106771 ** handle and try the read again. */
106772 return blobReadWriteRetry(p,z,n,iOffset,xCall);
106773 }
106774 if( rc==SQLITE_ABORT ){
106775 assert( p->pStmt );
106776 sqlite3VdbeFinalize(v);
106777 p->pStmt = 0;
106778 }else{
106779 v->rc = rc;
106780 }
106781 }
106782 }
106783 sqlite3Error(db, rc);
106784 rc = sqlite3ApiExit(db, rc);
106785 sqlite3_mutex_leave(db->mutex);
@@ -109749,12 +110016,28 @@
110016 i = 8;
110017 }else{
110018 if( i<=2 && pCur->zType==0 ){
110019 Schema *pSchema;
110020 HashElem *k;
110021 int iDb;
110022 Pgno iRoot;
110023 switch( pOp->opcode ){
110024 case OP_Clear: {
110025 iRoot = (Pgno)pOp->p1;
110026 iDb = pOp->p2;
110027 break;
110028 }
110029 case OP_Destroy: {
110030 iRoot = (Pgno)pOp->p1;
110031 iDb = pOp->p3;
110032 break;
110033 }
110034 default: {
110035 iRoot = (Pgno)pOp->p2;
110036 iDb = pOp->p3;
110037 }
110038 }
110039 sqlite3 *db = pVTab->db;
110040 pSchema = db->aDb[iDb].pSchema;
110041 pCur->zSchema = db->aDb[iDb].zDbSName;
110042 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
110043 Table *pTab = (Table*)sqliteHashData(k);
@@ -109847,11 +110130,14 @@
110130 break;
110131 case 22: /* tables_used.name */
110132 sqlite3_result_text(ctx, pCur->zName, -1, SQLITE_STATIC);
110133 break;
110134 case 23: /* tables_used.wr */
110135 sqlite3_result_int(ctx,
110136 pOp->opcode==OP_OpenWrite ||
110137 pOp->opcode==OP_Clear ||
110138 pOp->opcode==OP_Destroy);
110139 break;
110140 }
110141 return SQLITE_OK;
110142 }
110143
@@ -110690,10 +110976,23 @@
110976 */
110977 SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
110978 UNUSED_PARAMETER2(NotUsed, NotUsed2);
110979 return WRC_Continue;
110980 }
110981
110982 /*
110983 ** This is a SELECT-node callback for the expression walker that
110984 ** always "fails". By "fail" in this case, we mean set
110985 ** pWalker->eCode to zero and abort.
110986 **
110987 ** This callback is used by multiple expression walkers.
110988 */
110989 SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
110990 UNUSED_PARAMETER(NotUsed);
110991 pWalker->eCode = 0;
110992 return WRC_Abort;
110993 }
110994
110995 /************** End of walker.c **********************************************/
110996 /************** Begin file resolve.c *****************************************/
110997 /*
110998 ** 2008 August 18
@@ -111157,12 +111456,19 @@
111456 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
111457 }
111458 }
111459 cnt++;
111460 pMatch = pItem;
111461 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY.
111462 ** Except when parsing for ALTER TABLE. In that case leave
111463 ** Expr.iColumn set to iCol so that it can be distinguished from
111464 ** literal "rowid" references. */
111465 if( j==pTab->iPKey && !IN_RENAME_OBJECT ){
111466 pExpr->iColumn = -1;
111467 }else{
111468 pExpr->iColumn = (i16)j;
111469 }
111470 if( pItem->fg.isNestedFrom ){
111471 sqlite3SrcItemColumnUsed(pItem, j);
111472 }
111473 }
111474 if( 0==cnt && VisibleRowid(pTab) ){
@@ -111257,11 +111563,11 @@
111563 int iCol;
111564 pSchema = pTab->pSchema;
111565 cntTab++;
111566 iCol = sqlite3ColumnIndex(pTab, zCol);
111567 if( iCol>=0 ){
111568 if( pTab->iPKey==iCol && !IN_RENAME_OBJECT ) iCol = -1;
111569 }else{
111570 if( sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
111571 iCol = -1;
111572 }else{
111573 iCol = pTab->nCol;
@@ -111672,10 +111978,14 @@
111978 break;
111979 }
111980 if( pExpr->op==TK_UPLUS ){
111981 pExpr = pExpr->pLeft;
111982 assert( pExpr!=0 );
111983 }else if( pExpr->op==TK_CASE ){
111984 assert( ExprUseXList(pExpr) );
111985 resolveSetExprSubtypeArg(pExpr->x.pList);
111986 break;
111987 }else{
111988 break;
111989 }
111990 }
111991 }
@@ -112300,10 +112610,33 @@
112610 }
112611
112612 /* If no match, return 0. */
112613 return 0;
112614 }
112615
112616 /*
112617 ** ORDER BY term pE, a simple identifier, has been matched by resolveAsName()
112618 ** against the iCol-th (1-based) entry of result-set pEList. If this is an
112619 ** ALTER TABLE rename, and the name of that entry was generated by expanding
112620 ** "*" or "tbl.*", then modify pE to refer to the table column directly.
112621 */
112622 static void resolveRenameStarTerm(
112623 Parse *pParse, /* Parsing context */
112624 ExprList *pEList, /* Result-set that pE was matched against */
112625 int iCol, /* 1-based index of the matching pEList entry */
112626 Expr *pE /* ORDER BY term to convert */
112627 ){
112628 if( IN_RENAME_OBJECT && pEList->a[iCol-1].fg.bStarName ){
112629 Expr *pX = pEList->a[iCol-1].pExpr;
112630 if( ALWAYS(pX->op==TK_COLUMN) && ALWAYS(pE->op==TK_ID) ){
112631 pE->op = TK_COLUMN;
112632 pE->iTable = pX->iTable;
112633 pE->iColumn = pX->iColumn;
112634 pE->y.pTab = pX->y.pTab;
112635 }
112636 }
112637 }
112638
112639 /*
112640 ** Generate an ORDER BY or GROUP BY term out-of-range error.
112641 */
112642 static void resolveOutOfRangeError(
@@ -112375,11 +112708,13 @@
112708 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE);
112709 return 1;
112710 }
112711 }else{
112712 iCol = resolveAsName(pParse, pEList, pE);
112713 if( iCol>0 ){
112714 resolveRenameStarTerm(pParse, pEList, iCol, pE);
112715 }else{
112716 /* Now test if expression pE matches one of the values returned
112717 ** by pSelect. In the usual case this is done by duplicating the
112718 ** expression, resolving any symbols in it, and then comparing
112719 ** it against each expression returned by the SELECT statement.
112720 ** Once the comparisons are finished, the duplicate expression
@@ -112543,10 +112878,11 @@
112878 Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);
112879 if( NEVER(pE2==0) ) continue;
112880 if( zType[0]!='G' ){
112881 iCol = resolveAsName(pParse, pSelect->pEList, pE2);
112882 if( iCol>0 ){
112883 resolveRenameStarTerm(pParse, pSelect->pEList, iCol, pE2);
112884 /* If an AS-name match is found, mark this ORDER BY column as being
112885 ** a copy of the iCol-th result-set column. The subsequent call to
112886 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
112887 ** copy of the iCol-th result-set expression. */
112888 pItem->u.x.iOrderByCol = (u16)iCol;
@@ -113141,15 +113477,20 @@
113477 assert( pExpr->iTable==pExpr->pLeft->x.pSelect->pEList->nExpr );
113478 return sqlite3ExprAffinity(
113479 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
113480 );
113481 }
113482 if( op==TK_VECTOR ){
 
 
113483 assert( ExprUseXList(pExpr) );
113484 return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
113485 }
113486 if( op==TK_FUNCTION && pExpr->affExpr==SQLITE_AFF_DEFER ){
113487 /* The USING column of a FULL JOIN: coalesce(L.x, R.x). Use the
113488 ** affinity of L.x, except that REAL becomes NUMERIC, since the
113489 ** value may come from R.x and so need not be REAL. */
113490 char aff = sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
113491 return aff==SQLITE_AFF_REAL ? SQLITE_AFF_NUMERIC : aff;
113492 }
113493 if( ExprHasProperty(pExpr, EP_Skip|EP_IfNullRow) ){
113494 assert( pExpr->op==TK_COLLATE
113495 || pExpr->op==TK_IF_NULL_ROW
113496 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) );
@@ -114665,12 +115006,12 @@
115006 **
115007 ** The return value includes space to duplicate all Expr nodes in the
115008 ** tree formed by Expr.pLeft and Expr.pRight, but not any other
115009 ** substructure such as Expr.x.pList, Expr.x.pSelect, and Expr.y.pWin.
115010 */
115011 static u64 dupedExprSize(const Expr *p){
115012 u64 nByte;
115013 assert( p!=0 );
115014 nByte = dupedExprNodeSize(p, EXPRDUP_REDUCE);
115015 if( p->pLeft ) nByte += dupedExprSize(p->pLeft);
115016 if( p->pRight ) nByte += dupedExprSize(p->pRight);
115017 assert( nByte==ROUND8(nByte) );
@@ -114723,11 +115064,11 @@
115064 #endif
115065 staticFlag = EP_Static;
115066 assert( sEdupBuf.zAlloc!=0 );
115067 assert( dupFlags==EXPRDUP_REDUCE );
115068 }else{
115069 u64 nAlloc;
115070 if( dupFlags ){
115071 nAlloc = dupedExprSize(p);
115072 }else if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
115073 nToken = sqlite3Strlen30NN(p->u.zToken)+1;
115074 nAlloc = ROUND8(EXPR_FULLSIZE + nToken);
@@ -115392,23 +115733,10 @@
115733 m |= pExpr->flags;
115734 }
115735 return m;
115736 }
115737
 
 
 
 
 
 
 
 
 
 
 
 
 
115738 /*
115739 ** Check the input string to see if it is "true" or "false" (in any case).
115740 **
115741 ** If the string is.... Return
115742 ** "true" EP_IsTrue
@@ -115702,10 +116030,22 @@
116030 case TK_IS:
116031 case TK_ISNOT:
116032 if( pWalker->eCode==6 ){
116033 pWalker->eCode = 0;
116034 return WRC_Abort;
116035 }
116036 if( pWalker->eCode==4 || pWalker->eCode==5 ){
116037 /* This is a DEFAULT expression. As it will never be name resolved,
116038 ** attempt the the TK_IS -> TK_TRUTH transform here. */
116039 Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);
116040 if( ALWAYS(pRight) ){
116041 if( pRight->op==TK_ID ) sqlite3ExprIdToTrueFalse(pRight);
116042 if( pRight->op==TK_TRUEFALSE ){
116043 pExpr->op2 = pExpr->op;
116044 pExpr->op = TK_TRUTH;
116045 }
116046 }
116047 }
116048 return WRC_Continue;
116049 case TK_VARIABLE:
116050 if( pWalker->eCode==5 ){
116051 /* Silently convert bound parameters that appear inside of CREATE
@@ -115907,35 +116247,157 @@
116247 }
116248 /* Rules (1), (2a), and (2b) handled by the following: */
116249 return sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor, bAllowSubq);
116250 }
116251
116252
116253 /*
116254 ** Return true if pExpr is a copy of a term of pGroupBy that sorts using
116255 ** the BINARY collating sequence.
116256 */
116257 static int exprIsBinaryGroupByTerm(
116258 Parse *pParse,
116259 Expr *pExpr,
116260 ExprList *pGroupBy
116261 ){
116262 int i;
116263 for(i=0; i<pGroupBy->nExpr; i++){
116264 Expr *p = pGroupBy->a[i].pExpr;
116265 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
116266 CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, p);
116267 if( sqlite3IsBinary(pColl) ) return 1;
116268 }
116269 }
116270 return 0;
116271 }
116272
116273 /*
116274 ** Bits returned by exprScanOperand().
116275 */
116276 #define GBOP_GROUPBY 0x01 /* The operand is a GROUP BY term */
116277 #define GBOP_INEXACT 0x02 /* That GROUP BY term might be a number */
116278 #define GBOP_NOAFF 0x04 /* That GROUP BY term has no affinity */
116279 #define GBOP_TEXT 0x08 /* The operand has TEXT affinity */
116280
116281 /*
116282 ** Inspect operand pOp of an operator and return a mask of GBOP_* bits that
116283 ** describe it. GBOP_GROUPBY is set if pOp is a GROUP BY term. Then
116284 ** GBOP_INEXACT is also set if that term might be a number, and GBOP_NOAFF
116285 ** if it has no affinity. GBOP_TEXT is set if pOp has TEXT affinity.
116286 */
116287 static int exprScanOperand(Walker *pWalker, Expr *pOp){
116288 int m = 0;
116289 if( pOp ){
116290 char aff = sqlite3ExprAffinity(pOp);
116291 if( exprIsBinaryGroupByTerm(pWalker->pParse, pOp, pWalker->u.pGroupBy) ){
116292 m |= GBOP_GROUPBY;
116293 if( aff<=SQLITE_AFF_NONE ) m |= GBOP_NOAFF;
116294 if( aff!=SQLITE_AFF_TEXT && pOp->op!=TK_CONCAT ) m |= GBOP_INEXACT;
116295 }
116296 if( aff==SQLITE_AFF_TEXT ) m |= GBOP_TEXT;
116297 }
116298 return m;
116299 }
116300
116301 /*
116302 ** pExpr is not itself a GROUP BY term. Return true if it has an operand
116303 ** that is a GROUP BY term, and the value of pExpr might depend on which
116304 ** member of a group that operand was taken from.
116305 **
116306 ** The rows of a group are equal in the GROUP BY sense but are not always
116307 ** identical. With the BINARY collating sequence, two values in the same
116308 ** group can still differ in type: 1 and 1.0 (also -0.0 and 0.0) are in the
116309 ** same group. So typeof(x), length(x), x||'', x/2, x+1 and so forth can
116310 ** have a different value for different rows of one group. A GROUP BY
116311 ** term that might be a number may therefore only be an operand of a
116312 ** comparison, because comparisons treat values that are equal as
116313 ** interchangeable, or of a logical operator. A GROUP BY term that is
116314 ** always TEXT or BLOB (the result of the || operator, or a column or CAST
116315 ** with TEXT affinity) can be an operand of anything, since equal text
116316 ** values are identical.
116317 **
116318 ** The exception for comparisons is a comparison of a GROUP BY term that
116319 ** has no affinity (an expression, not a column) against a TEXT operand.
116320 ** TEXT affinity is applied to the term and converts 1 to '1' but 1.0 to
116321 ** '1.0'.
116322 */
116323 static int exprGroupByOperandUnsafe(Walker *pWalker, Expr *pExpr){
116324 int bCmp = 0; /* True for a comparison operator */
116325 int bOther = 0; /* True for any operator or function that is not a
116326 ** comparison or a logical operator */
116327 int m = 0; /* Union of the GBOP_* bits for all operands */
116328 int i;
116329
116330 switch( pExpr->op ){
116331 case TK_EQ: case TK_NE: case TK_LT: case TK_LE:
116332 case TK_GT: case TK_GE: case TK_IS: case TK_ISNOT:
116333 case TK_IN: case TK_BETWEEN: {
116334 testcase( pExpr->op==TK_EQ ); testcase( pExpr->op==TK_NE );
116335 testcase( pExpr->op==TK_LT ); testcase( pExpr->op==TK_LE );
116336 testcase( pExpr->op==TK_GT ); testcase( pExpr->op==TK_GE );
116337 testcase( pExpr->op==TK_IS ); testcase( pExpr->op==TK_ISNOT );
116338 testcase( pExpr->op==TK_IN ); testcase( pExpr->op==TK_BETWEEN );
116339 bCmp = 1;
116340 break;
116341 }
116342 case TK_ISNULL: case TK_NOTNULL: case TK_AND: case TK_OR: case TK_NOT: {
116343 testcase( pExpr->op==TK_ISNULL ); testcase( pExpr->op==TK_NOTNULL );
116344 testcase( pExpr->op==TK_AND ); testcase( pExpr->op==TK_OR );
116345 testcase( pExpr->op==TK_NOT );
116346 break;
116347 }
116348 default: {
116349 bOther = 1;
116350 break;
116351 }
116352 }
116353 m |= exprScanOperand(pWalker, pExpr->pLeft);
116354 m |= exprScanOperand(pWalker, pExpr->pRight);
116355 assert( ExprUseXList(pExpr) ); /* Sub-selects were handled by the caller */
116356 if( pExpr->x.pList ){
116357 for(i=0; i<pExpr->x.pList->nExpr; i++){
116358 m |= exprScanOperand(pWalker, pExpr->x.pList->a[i].pExpr);
116359 }
116360 }
116361 if( (m & GBOP_GROUPBY)==0 ) return 0;
116362
116363 /* Any other operator or function is unsafe if it has an operand that
116364 ** is a GROUP BY term that might be a number. */
116365 if( bOther ) return (m & GBOP_INEXACT)!=0;
116366
116367 /* A comparison is unsafe if a GROUP BY operand without affinity is
116368 ** compared against an operand with TEXT affinity. */
116369 testcase( (m & (GBOP_NOAFF|GBOP_TEXT))==0 );
116370 testcase( (m & (GBOP_NOAFF|GBOP_TEXT))==GBOP_NOAFF );
116371 testcase( (m & (GBOP_NOAFF|GBOP_TEXT))==GBOP_TEXT );
116372 return bCmp && (m & (GBOP_NOAFF|GBOP_TEXT))==(GBOP_NOAFF|GBOP_TEXT);
116373 }
116374
116375 /*
116376 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
116377 */
116378 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
116379 ExprList *pGroupBy = pWalker->u.pGroupBy;
 
116380
116381 /* Check if pExpr is identical to any GROUP BY term. If so, consider
116382 ** it constant. */
116383 if( exprIsBinaryGroupByTerm(pWalker->pParse, pExpr, pGroupBy) ){
116384 return WRC_Prune;
 
 
 
 
 
 
116385 }
116386
116387 /* Check if pExpr is a sub-select. If so, consider it variable. */
116388 if( ExprUseXSelect(pExpr) ){
116389 pWalker->eCode = 0;
116390 return WRC_Abort;
116391 }
116392
116393 /* An operator applied to a GROUP BY term is constant only if its value
116394 ** is the same for every member of a group. */
116395 if( exprGroupByOperandUnsafe(pWalker, pExpr) ){
116396 pWalker->eCode = 0;
116397 return WRC_Abort;
116398 }
116399
116400 return exprNodeIsConstant(pWalker, pExpr);
116401 }
116402
116403 /*
@@ -115944,20 +116406,29 @@
116406 ** in pGroupBy that sort with the BINARY collation sequence.
116407 **
116408 ** This routine is used to determine if a term of the HAVING clause can
116409 ** be promoted into the WHERE clause. In order for such a promotion to work,
116410 ** the value of the HAVING clause term must be the same for all members of
116411 ** a "group". There are two requirements for this.
116412 **
116413 ** (1) Members of a group are equal in the sense of the GROUP BY collating
116414 ** sequence, but need not be identical. The requirement that the
116415 ** GROUP BY term be BINARY assumes that no other collating sequence
116416 ** will have a finer-grained grouping than binary. In other words
116417 ** (A=B COLLATE binary) implies A=B in every other collating sequence.
116418 ** The requirement that the GROUP BY be BINARY is stricter than
116419 ** necessary. It would also work to promote HAVING clauses that use the
116420 ** same alternative collating sequence as the GROUP BY term, but that
116421 ** is much harder to check, alternative collating sequences are
116422 ** uncommon, and this is only an optimization, so we take the easy way
116423 ** out and simply require the GROUP BY to use the BINARY collating
116424 ** sequence.
116425 **
116426 ** (2) Even with BINARY, equal values can be distinguishable, as in the
116427 ** case of 1 and 1.0. A GROUP BY term may therefore only be used as
116428 ** an operand of a comparison or logical operator. See
116429 ** exprGroupByOperandUnsafe() for details.
116430 */
116431 SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
116432 Walker w;
116433 w.eCode = 1;
116434 w.xExprCallback = exprNodeIsConstantOrGroupBy;
@@ -116617,10 +117088,15 @@
117088 #ifndef SQLITE_OMIT_SUBQUERY
117089 /*
117090 ** Argument pExpr is an (?, ?...) IN(...) expression. This
117091 ** function allocates and returns a nul-terminated string containing
117092 ** the affinities to be used for each column of the comparison.
117093 **
117094 ** NUMERIC affinity is used in place of REAL. Within a comparison the
117095 ** two are the same, except that REAL affinity (as applied by OP_Affinity
117096 ** and OP_MakeRecord) converts integers into floating point, and that
117097 ** might change the value of a large integer.
117098 **
117099 ** It is the responsibility of the caller to ensure that the returned
117100 ** string is eventually freed using sqlite3DbFree().
117101 */
117102 static char *exprINAffinity(Parse *pParse, const Expr *pExpr){
@@ -116639,10 +117115,11 @@
117115 if( pSelect ){
117116 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
117117 }else{
117118 zRet[i] = a;
117119 }
117120 if( zRet[i]==SQLITE_AFF_REAL ) zRet[i] = SQLITE_AFF_NUMERIC;
117121 }
117122 zRet[nVal] = '\0';
117123 }
117124 return zRet;
117125 }
@@ -117115,11 +117592,11 @@
117592 }
117593 sqlite3ExprDeferredDelete(pParse, pLeft);
117594 pSel->pLimit->pLeft = pLimit;
117595 }
117596 }else{
117597 /* If there is no limit add a limit of 1. (tag-202611101908) */
117598 pLimit = sqlite3ExprInt32(pParse->db, 1);
117599 pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
117600 }
117601 pSel->iLimit = 0;
117602 if( sqlite3Select(pParse, pSel, &dest) ){
@@ -117435,13 +117912,14 @@
117912 **
117913 ** For a scalar LHS, it is sufficient to check just the first row
117914 ** of the RHS.
117915 */
117916 if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
117917 if( eType==IN_INDEX_INDEX_DESC && nVector==1 ){
117918 addrTop = sqlite3VdbeAddOp2(v, OP_Last, iTab, destIfFalse);
117919 }else{
117920 testcase( eType==IN_INDEX_INDEX_DESC );
117921 testcase( eType==IN_INDEX_EPH );
117922 testcase( eType==IN_INDEX_ROWID );
117923 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
117924 }
117925 VdbeCoverage(v);
@@ -117953,10 +118431,34 @@
118431 w.xExprCallback = exprNodeCanReturnSubtype;
118432 sqlite3WalkExpr(&w, pExpr);
118433 return w.eCode;
118434 }
118435
118436 /*
118437 ** Return 0 iff the expression in IndexedExpr object p is identical to
118438 ** expression pExpr, and the affinity is such that an entry read from
118439 ** the index may be substituted for pExpr in any context. Otherwise
118440 ** return non-zero.
118441 */
118442 static int indexedExprCompare(
118443 IndexedExpr *p, /* Indexed expression */
118444 Expr *pExpr, /* Expression to compare to p */
118445 int iDataCur /* iTab argument for ExprCompare() */
118446 ){
118447 u8 exprAff;
118448 if( sqlite3ExprCompare(0, pExpr, p->pExpr, iDataCur)!=0 ) return 1;
118449 assert( p->aff>=SQLITE_AFF_BLOB && p->aff<=SQLITE_AFF_NUMERIC );
118450 exprAff = sqlite3ExprAffinity(pExpr);
118451 if( (exprAff<=SQLITE_AFF_BLOB && p->aff!=SQLITE_AFF_BLOB)
118452 || (exprAff==SQLITE_AFF_TEXT && p->aff!=SQLITE_AFF_TEXT)
118453 || (exprAff>=SQLITE_AFF_NUMERIC && p->aff!=SQLITE_AFF_NUMERIC)
118454 ){
118455 /* Affinity mismatch on a generated column */
118456 return 1;
118457 }
118458 return 0;
118459 }
118460
118461 /*
118462 ** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr.
118463 ** If it is, then resolve the expression by reading from the index and
118464 ** return the register into which the value has been read. If pExpr is
@@ -117967,29 +118469,19 @@
118469 Expr *pExpr, /* The expression to potentially bypass */
118470 int target /* Where to store the result of the expression */
118471 ){
118472 IndexedExpr *p;
118473 Vdbe *v;
118474
118475 for(p=pParse->pIdxEpr; p; p=p->pIENext){
 
118476 int iDataCur = p->iDataCur;
118477 if( iDataCur<0 ) continue;
118478 if( pParse->iSelfTab ){
118479 if( p->iDataCur!=pParse->iSelfTab-1 ) continue;
118480 iDataCur = -1;
118481 }
118482 if( indexedExprCompare(p, pExpr, iDataCur)!=0 ) continue;
 
 
 
 
 
 
 
 
 
 
118483
118484 /* Functions that might set a subtype should not be replaced by the
118485 ** value taken from an expression index if they are themselves an
118486 ** argument to another scalar function or aggregate.
118487 ** https://sqlite.org/forum/forumpost/68d284c86b082c3e */
@@ -117996,23 +118488,24 @@
118488 if( ExprHasProperty(pExpr, EP_SubtArg)
118489 && sqlite3ExprCanReturnSubtype(pParse, pExpr)
118490 ){
118491 continue;
118492 }
118493
118494 /* Do not read the value from an index if the expression is a constant.
118495 ** This prevents an attempt to use an index value outside of the loop that
118496 ** uses the index. (Bugs 2026-10-11T19:26:40Z and 2026-11-03T02:12:43Z). */
118497 if( sqlite3ExprIsConstant(pParse, pExpr) ){
118498 return -1;
118499 }
118500
118501 v = pParse->pVdbe;
118502 assert( v!=0 );
118503 if( p->bMaybeNullRow ){
118504 /* The value of pExpr should be computed from the original expression,
118505 ** not from the index, if the index might be on a NULL row due to an
118506 ** outer join. */
 
 
 
 
 
 
118507 int addr = sqlite3VdbeCurrentAddr(v);
118508 sqlite3VdbeAddOp3(v, OP_IfNullRow, p->iIdxCur, addr+3, target);
118509 VdbeCoverage(v);
118510 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
118511 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
@@ -118047,13 +118540,17 @@
118540 for(p=pParse->pIdxPartExpr; p; p=p->pIENext){
118541 if( pExpr->iColumn==p->iIdxCol && pExpr->iTable==p->iDataCur ){
118542 Vdbe *v = pParse->pVdbe;
118543 int addr = 0;
118544 int ret;
118545 u8 okConstFactor = pParse->okConstFactor;
118546
118547 if( p->bMaybeNullRow ){
118548 /* OP_IfNullRow can overwrite the result register with NULL, so the
118549 ** value must be recomputed each time, not factored out. */
118550 addr = sqlite3VdbeAddOp1(v, OP_IfNullRow, p->iIdxCur);
118551 pParse->okConstFactor = 0;
118552 }
118553 ret = sqlite3ExprCodeTarget(pParse, p->pExpr, iTarget);
118554 sqlite3VdbeAddOp4(pParse->pVdbe, OP_Affinity, ret, 1, 0,
118555 (const char*)&p->aff, 1);
118556 if( sqlite3ExprCanReturnSubtype(pParse, p->pExpr) ){
@@ -118060,10 +118557,11 @@
118557 /* If the expression value may have a sub-type, clear it. Values
118558 ** read from columns do not have subtypes. */
118559 sqlite3VdbeAddOp1(pParse->pVdbe, OP_ClrSubtype, ret);
118560 }
118561 if( addr ){
118562 pParse->okConstFactor = okConstFactor;
118563 sqlite3VdbeJumpHere(v, addr);
118564 sqlite3VdbeChangeP3(v, addr, ret);
118565 }
118566 return ret;
118567 }
@@ -118187,11 +118685,11 @@
118685 case TK_AGG_COLUMN: {
118686 AggInfo *pAggInfo = pExpr->pAggInfo;
118687 struct AggInfo_col *pCol;
118688 assert( pAggInfo!=0 );
118689 assert( pExpr->iAgg>=0 );
118690 if( NEVER(pExpr->iAgg>=pAggInfo->nColumn) ){
118691 /* Happens when the left table of a RIGHT JOIN is null and
118692 ** is using an expression index */
118693 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
118694 #ifdef SQLITE_VDBE_COVERAGE
118695 /* Verify that the OP_Null above is exercised by tests
@@ -118963,11 +119461,11 @@
119461 assert( pExpr->affExpr==OE_Rollback
119462 || pExpr->affExpr==OE_Abort
119463 || pExpr->affExpr==OE_Fail
119464 || pExpr->affExpr==OE_Ignore
119465 );
119466 if( !pParse->pTriggerTab ){
119467 sqlite3ErrorMsg(pParse,
119468 "RAISE() may only be used within a trigger-program");
119469 return 0;
119470 }
119471 if( pExpr->affExpr==OE_Abort ){
@@ -118977,12 +119475,11 @@
119475 if( pExpr->affExpr==OE_Ignore ){
119476 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, OE_Ignore);
119477 VdbeCoverage(v);
119478 }else{
119479 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
119480 sqlite3VdbeAddOp3(v, OP_Halt, SQLITE_CONSTRAINT_TRIGGER,
 
119481 pExpr->affExpr, r1);
119482 }
119483 break;
119484 }
119485 #endif
@@ -119736,14 +120233,22 @@
120233 if( pR ){
120234 iVar = pVar->iColumn;
120235 sqlite3VdbeReprepareOnBind(pParse->pVdbe, iVar, 0);
120236 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
120237 if( pL ){
120238 int eType;
120239 if( sqlite3_value_type(pL)==SQLITE_TEXT ){
120240 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
120241 }
120242 /* The bound value and the literal must be interchangeable, not
120243 ** just compare equal. For example, integer 1 and real 1.0 are equal
120244 ** according to MemCompare(), but are different if TEXT affinity
120245 ** is applied to them. */
120246 eType = sqlite3_value_type(pL);
120247 if( eType==sqlite3_value_type(pR) && sqlite3MemCompare(pL, pR, 0)==0 ){
120248 res = 0;
120249 }
120250 }
120251 sqlite3ValueFree(pR);
120252 sqlite3ValueFree(pL);
120253 }
120254 return res;
@@ -120629,14 +121134,24 @@
121134 IndexedExpr *pIEpr;
121135 Expr tmp;
121136 assert( pParse->iSelfTab==0 );
121137 if( (pNC->ncFlags & NC_InAggFunc)==0 ) break;
121138 if( pParse->pIdxEpr==0 ) break;
121139 if( pWalker->walkerDepth>0 ){
121140 break; /* See bug report 2026-11-07T18:33:11Z */
121141 }
121142 for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
121143 int iDataCur = pIEpr->iDataCur;
121144 if( iDataCur<0 ) continue;
121145 /* If the index might be on the NULL row of an outer join, then the
121146 ** expression must not be replaced by a plain read of the index
121147 ** column, as the value of the expression on the NULL row is not
121148 ** necessarily NULL. In many cases (when the GROUP BY is not
121149 ** using temp b-tree to sort), sqlite3IndexedExprLookup() will make
121150 ** the same substitution later on anyway. */
121151 if( pIEpr->bMaybeNullRow ) continue;
121152 if( indexedExprCompare(pIEpr, pExpr, iDataCur)==0 ) break;
121153 }
121154 if( pIEpr==0 ) break;
121155 if( NEVER(!ExprUseYTab(pExpr)) ) break;
121156 for(i=0; i<pSrcList->nSrc; i++){
121157 if( pSrcList->a[i].iCursor==pIEpr->iDataCur ){
@@ -120644,10 +121159,15 @@
121159 break;
121160 }
121161 }
121162 if( i>=pSrcList->nSrc ) break;
121163 if( NEVER(pExpr->pAggInfo!=0) ) break; /* Resolved by outer context */
121164 if( ExprHasProperty(pExpr, EP_SubtArg)
121165 && sqlite3ExprCanReturnSubtype(pParse, pExpr)
121166 ){
121167 break;
121168 }
121169 if( pParse->nErr ){ return WRC_Abort; }
121170
121171 /* If we reach this point, it means that expression pExpr can be
121172 ** translated into a reference to an index column as described by
121173 ** pIEpr.
@@ -121112,11 +121632,11 @@
121632 ** that the table is being renamed to.
121633 */
121634 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
121635 goto exit_rename_table;
121636 }
121637 if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName,zDb) ){
121638 goto exit_rename_table;
121639 }
121640
121641 #ifndef SQLITE_OMIT_VIEW
121642 if( IsView(pTab) ){
@@ -121157,35 +121677,35 @@
121677 /* figure out how many UTF-8 characters are in zName */
121678 zTabName = pTab->zName;
121679 nTabName = sqlite3Utf8CharLen(zTabName, -1);
121680
121681 /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
121682 ** the schema to use the new table name, and update the tbl_name and
121683 ** name columns as required. */
121684 sqlite3NestedParse(pParse,
121685 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
121686 "sql = CASE WHEN type='index' AND "
121687 "name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' THEN sql "
121688 "ELSE sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) END, "
121689 "tbl_name = CASE "
121690 "WHEN tbl_name=%Q COLLATE nocase AND (type!='trigger' OR %d=0 OR "
121691 " sqlite_rename_test(%Q, sql, type, name, 1, 'after rename', 0)) "
121692 "THEN %Q ELSE tbl_name END, "
121693 "name = CASE "
121694 "WHEN type='table' AND tbl_name=%Q COLLATE nocase THEN %Q "
121695 "WHEN type='index' AND name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
121696 "THEN 'sqlite_autoindex_' || %Q || substr(name,%d+18) "
121697 "ELSE name END "
121698 "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase) "
121699 "AND (name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
121700 "OR (type='index' AND name LIKE 'sqliteX_autoindex%%' ESCAPE 'X'))"
121701 , zDb,
121702 zDb, zTabName, zName, (iDb==1),
121703 zTabName, (iDb==1), zDb, zName,
121704 zTabName, zName,
121705 zName, nTabName,
121706 zTabName
 
121707 );
121708
121709 #ifndef SQLITE_OMIT_AUTOINCREMENT
121710 /* If the sqlite_sequence table exists in this database, then update
121711 ** it with the new table name.
@@ -121242,11 +121762,11 @@
121762 const char *zDb, /* Schema holding the table */
121763 const char *zTab, /* Table to check for empty */
121764 const char *zErr /* Error message text */
121765 ){
121766 sqlite3NestedParse(pParse,
121767 "SELECT sqlite_fail(%Q, 1) FROM \"%w\".\"%w\"",
121768 zErr, zDb, zTab
121769 );
121770 }
121771
121772 /*
@@ -121270,10 +121790,55 @@
121790 }
121791 return SQLITE_OK;
121792 }
121793
121794
121795
121796 /*
121797 ** Buffer pFrag, which is nFrag bytes in size, contains a fragment of
121798 ** SQL that will be inserted into a CREATE TABLE statement. If successful, this
121799 ** function returns the size of the buffer in bytes not including any trailing
121800 ** whitespace, semicolons, "--" style comments or unterminated C-style
121801 ** comments. Or, if an OOM occurs, it returns 0 and sets db->mallocFailed to
121802 ** true.
121803 **
121804 ** Terminated C-style comments at the end are preserved. "--" style
121805 ** comments and unterminated C-style comments are removed because otherwise
121806 ** inserting pFrag[] into the middle of a larger SQL statement without a
121807 ** comment terminator will mess up its syntax.
121808 */
121809 static int alterRtrimFragment(
121810 sqlite3 *db, /* used to record OOM error */
121811 const char *pFrag, /* Buffer containing SQL fragment */
121812 int nFrag /* Size of pFrag in bytes */
121813 ){
121814 u8 *zTmp = (u8*)sqlite3MPrintf(db, "%.*s", nFrag, pFrag);
121815 int iOff = 0;
121816 int iEnd = 0;
121817
121818 if( zTmp==0 ) return 0;
121819
121820 while( 1 ){
121821 int t = 0;
121822 int nToken = sqlite3GetToken(&zTmp[iOff], &t);
121823 if( t==TK_ILLEGAL ) break;
121824 if( t==TK_COMMENT ){
121825 /* Ignore all but properly terminated C-style comments */
121826 if( zTmp[iOff]=='/' && nToken>=4
121827 && zTmp[iOff+nToken-2]=='*' && zTmp[iOff+nToken-1]=='/'
121828 ){
121829 iEnd = iOff+nToken;
121830 }
121831 }else if( t!=TK_SPACE && t!=TK_SEMI ){
121832 iEnd = iOff+nToken;
121833 }
121834 iOff += nToken;
121835 }
121836
121837 sqlite3DbFree(db, zTmp);
121838 return iEnd;
121839 }
121840
121841 /*
121842 ** This function is called after an "ALTER TABLE ... ADD" statement
121843 ** has been parsed. Argument pColDef contains the text of the new
121844 ** column definition.
@@ -121286,10 +121851,11 @@
121851 Table *pTab; /* Table being altered */
121852 int iDb; /* Database number */
121853 const char *zDb; /* Database name */
121854 const char *zTab; /* Table name */
121855 char *zCol; /* Null-terminated column definition */
121856 int nCol; /* Size of zCol in bytes */
121857 Column *pCol; /* The new column */
121858 Expr *pDflt; /* Default value for the new column */
121859 sqlite3 *db; /* The database connection; */
121860 Vdbe *v; /* The prepared statement under construction */
121861 int r1; /* Temporary registers */
@@ -121331,32 +121897,16 @@
121897 "Cannot add a UNIQUE column");
121898 return;
121899 }
121900 if( isRowidAlias(pParse, pTab, pCol->zCnName, "add") ) return;
121901 if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
 
 
 
 
121902 assert( pDflt==0 || pDflt->op==TK_SPAN );
121903
121904 /* Ensure the default expression, if any, is something that
121905 ** sqlite3ValueFromExpr() can handle (i.e. not CURRENT_TIME etc.).
121906 ** If the default expression evaluates to NULL, then set pDflt to
121907 ** 0. This simplifies the checks below. */
 
 
 
 
 
 
 
 
 
 
 
 
121908 if( pDflt ){
121909 sqlite3_value *pVal = 0;
121910 int rc;
121911 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
121912 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
@@ -121365,25 +121915,35 @@
121915 return;
121916 }
121917 if( !pVal ){
121918 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
121919 "Cannot add a column with non-constant default");
121920 }else if( sqlite3_value_type(pVal)==SQLITE_NULL ){
121921 pDflt = 0;
121922 }
121923 sqlite3ValueFree(pVal);
121924 }
121925
121926 assert( IsOrdinaryTable(pNew) );
121927 if( (db->flags&SQLITE_ForeignKeys) && pNew->u.tab.pFKey && pDflt ){
121928 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
121929 "Cannot add a REFERENCES column with non-NULL default value");
121930 }
121931 if( pCol->notNull && !pDflt ){
121932 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
121933 "Cannot add a NOT NULL column with default value NULL");
121934 }
121935
121936 }else if( pCol->colFlags & COLFLAG_STORED ){
121937 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column");
121938 }
121939
121940
121941 /* Modify the CREATE TABLE statement. */
121942 nCol = alterRtrimFragment(db, (char*)pColDef->z, pColDef->n);
121943 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, nCol);
121944 if( zCol ){
 
 
 
 
121945 /* substr() operations on characters, but addColOffset is in bytes. So we
121946 ** have to use printf() to translate between these units: */
121947 assert( IsOrdinaryTable(pTab) );
121948 assert( IsOrdinaryTable(pNew) );
121949 sqlite3NestedParse(pParse,
@@ -121397,10 +121957,13 @@
121957 sqlite3DbFree(db, zCol);
121958 }
121959
121960 v = sqlite3GetVdbe(pParse);
121961 if( v ){
121962 int isStrict = pTab->tabFlags & TF_Strict;
121963 int isGen = (pCol->colFlags & COLFLAG_GENERATED)!=0;
121964
121965 /* Make sure the schema version is at least 3. But do not upgrade
121966 ** from less than 3 to 4, as that will corrupt any preexisting DESC
121967 ** index.
121968 */
121969 r1 = sqlite3GetTempReg(pParse);
@@ -121413,28 +121976,46 @@
121976 sqlite3ReleaseTempReg(pParse, r1);
121977
121978 /* Reload the table definition */
121979 renameReloadSchema(pParse, iDb, INITFLAG_AlterAdd);
121980
121981 /* Verify that constraints are still satisfied. This requires a scan
121982 ** of the entire table if:
121983 **
121984 ** 1) the new column has a CHECK constraint, or
121985 ** 2) the new column is a NOT NULL generated column, or
121986 ** 3) the table is STRICT and the new column is a generated column
121987 ** with a type other than ANY.
121988 */
121989 if( pNew->pCheck!=0
121990 || (pCol->notNull && isGen)
121991 || (isStrict && isGen && pCol->eCType!=COLTYPE_ANY)
121992 ){
121993 pParse->colNamesSet = 1;
121994 sqlite3NestedParse(pParse,
121995 "SELECT CASE WHEN quick_check GLOB 'CHECK*'"
121996 " THEN sqlite_fail('CHECK constraint failed', 1)"
121997 " WHEN quick_check GLOB 'non-* value in*'"
121998 " THEN sqlite_fail('type mismatch on DEFAULT', 1)"
121999 " ELSE sqlite_fail('NOT NULL constraint failed', 1)"
122000 " END"
122001 " FROM pragma_quick_check(%Q,%Q)"
122002 " WHERE quick_check GLOB 'CHECK*'"
122003 " OR quick_check GLOB 'NULL*'"
122004 " OR quick_check GLOB 'non-* value in*'",
122005 zTab, zDb
122006 );
122007 }else if( pDflt && isStrict && pCol->eCType>COLTYPE_ANY ){
122008 static const char *azTypeof[] = {
122009 "any", "blob", "integer", "integer", "real", "text"
122010 };
122011 assert( pCol->eCType<=ArraySize(azTypeof) );
122012 pParse->colNamesSet = 1;
122013 sqlite3NestedParse(pParse,
122014 "SELECT sqlite_fail('type mismatch on DEFAULT', 1)"
122015 " WHERE sqlite_check_type(%Q, %Q, %Q, %Q)",
122016 zDb, zTab, pCol->zCnName, azTypeof[pCol->eCType-1]
122017 );
122018 }
122019 }
122020 }
122021
@@ -122348,10 +122929,11 @@
122929 SrcList *pSrc = sqlite3SrcListDup(db, pStep->pSrc, 0);
122930 if( pSrc ){
122931 Select *pSel = sqlite3SelectNew(
122932 pParse, pStep->pExprList, pSrc, 0, 0, 0, 0, 0, 0
122933 );
122934 Upsert *pUpsert = 0;
122935 if( pSel==0 ){
122936 pStep->pExprList = 0;
122937 pSrc = 0;
122938 rc = SQLITE_NOMEM;
122939 }else{
@@ -122371,34 +122953,39 @@
122953 assert( pSrc==pSel->pSrc );
122954 if( pStep->pExprList ) pSel->pEList = 0;
122955 pSel->pSrc = 0;
122956 sqlite3SelectDelete(db, pSel);
122957 }
122958
122959 sNC.pSrcList = pSrc;
122960 if( ALWAYS(pStep->pSrc) ){
122961 int i;
122962 for(i=0; i<pStep->pSrc->nSrc && rc==SQLITE_OK; i++){
122963 SrcItem *p = &pStep->pSrc->a[i];
122964 if( p->fg.isSubquery ){
122965 assert( p->u4.pSubq!=0 );
122966 sqlite3SelectPrep(pParse, p->u4.pSubq->pSelect, 0);
122967 }
122968 if( p->fg.isUsing==0 ){
122969 rc = sqlite3ResolveExprNames(&sNC, p->u3.pOn);
122970 }
122971 }
122972 }
122973 if( db->mallocFailed ){
 
122974 rc = SQLITE_NOMEM;
122975 }
 
122976 if( rc==SQLITE_OK && pStep->pWhere ){
122977 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
122978 }
122979 if( rc==SQLITE_OK ){
122980 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
122981 }
122982 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
122983 for(pUpsert=pStep->pUpsert;
122984 pUpsert && rc==SQLITE_OK;
122985 pUpsert=pUpsert->pNextUpsert
122986 ){
122987 pUpsert->pUpsertSrc = pSrc;
122988 sNC.uNC.pUpsert = pUpsert;
122989 sNC.ncFlags = NC_UUpsert;
122990 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
122991 if( rc==SQLITE_OK ){
@@ -122433,27 +123020,31 @@
123020 /* Find tokens to edit in WHEN clause */
123021 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
123022
123023 /* Find tokens to edit in trigger steps */
123024 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
123025 Upsert *pUpsert = 0;
123026 sqlite3WalkSelect(pWalker, pStep->pSelect);
123027 sqlite3WalkExpr(pWalker, pStep->pWhere);
123028 sqlite3WalkExprList(pWalker, pStep->pExprList);
123029 for(pUpsert=pStep->pUpsert; pUpsert; pUpsert=pUpsert->pNextUpsert){
 
123030 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
123031 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
123032 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
123033 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
123034 }
123035 if( pStep->pSrc ){
123036 int i;
123037 SrcList *pSrc = pStep->pSrc;
123038 for(i=0; i<pSrc->nSrc; i++){
123039 SrcItem *p = &pSrc->a[i];
123040 if( p->fg.isSubquery ){
123041 assert( p->u4.pSubq!=0 );
123042 sqlite3WalkSelect(pWalker, p->u4.pSubq->pSelect);
123043 }
123044 if( p->fg.isUsing==0 ){
123045 sqlite3WalkExpr(pWalker, p->u3.pOn);
123046 }
123047 }
123048 }
123049 }
123050 }
@@ -122539,11 +123130,11 @@
123130 sqlite3BtreeLeaveAll(db);
123131 return;
123132 }
123133 zOld = pTab->aCol[iCol].zCnName;
123134 memset(&sCtx, 0, sizeof(sCtx));
123135 sCtx.iCol = iCol;
123136
123137 #ifndef SQLITE_OMIT_AUTHORIZATION
123138 db->xAuth = 0;
123139 #endif
123140 rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
@@ -122577,11 +123168,11 @@
123168 if( iCol<sParse.pNewTable->nCol ){
123169 renameTokenFind(
123170 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zCnName
123171 );
123172 }
123173 if( iCol==sParse.pNewTable->iPKey ){
123174 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
123175 }
123176 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
123177 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
123178 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
@@ -122623,13 +123214,13 @@
123214
123215 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
123216 if( pStep->pSrc ){
123217 Table *pTarget = sqlite3LocateTableItem(&sParse, 0, &pStep->pSrc->a[0]);
123218 if( pTarget==pTab ){
123219 Upsert *pUpsert = 0;
123220 for(pUpsert=pStep->pUpsert; pUpsert; pUpsert=pUpsert->pNextUpsert){
123221 renameColumnElistNames(&sParse,&sCtx,pUpsert->pUpsertSet,zOld);
123222 }
123223 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
123224 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
123225 }
123226 }
@@ -122705,10 +123296,30 @@
123296 renameWalkWith(pWalker, pSelect);
123297
123298 return WRC_Continue;
123299 }
123300
123301
123302 #ifndef SQLITE_OMIT_TRIGGER
123303 /*
123304 ** Return the table that SrcItem pItem, which is part of the pSrc list of
123305 ** an INSERT, UPDATE or DELETE trigger step (the target table, or a table
123306 ** from the FROM clause of an UPDATE ... FROM), refers to. Or NULL if it
123307 ** does not refer to any existing table.
123308 */
123309 static Table *renameTriggerSrcTab(sqlite3 *db, SrcItem *pItem){
123310 const char *zDb;
123311 assert( pItem->fg.isSubquery==0 );
123312 if( pItem->fg.fixedSchema ){
123313 int iDb = sqlite3SchemaToIndex(db, pItem->u4.pSchema);
123314 zDb = db->aDb[iDb].zDbSName;
123315 }else{
123316 zDb = pItem->u4.zDatabase;
123317 }
123318 return sqlite3FindTable(db, pItem->zName, zDb);
123319 }
123320 #endif
123321
123322 /*
123323 ** This C function implements an SQL user function that is used by SQL code
123324 ** generated by the ALTER TABLE ... RENAME command to modify the definition
123325 ** of any foreign key constraints that use the table being renamed as the
@@ -122824,12 +123435,12 @@
123435 #ifndef SQLITE_OMIT_TRIGGER
123436 else{
123437 Trigger *pTrigger = sParse.pNewTrigger;
123438 TriggerStep *pStep;
123439 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
123440 && sCtx.pTab->pSchema==pTrigger->pTabSchema
123441 ){
123442 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
123443 }
123444
123445 if( isLegacy==0 ){
123446 rc = renameResolveTrigger(&sParse);
@@ -122837,13 +123448,13 @@
123448 renameWalkTrigger(&sWalker, pTrigger);
123449 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
123450 if( pStep->pSrc ){
123451 int i;
123452 for(i=0; i<pStep->pSrc->nSrc; i++){
123453 SrcItem *p = &pStep->pSrc->a[i];
123454 if( p->zName && renameTriggerSrcTab(db, p)==sCtx.pTab ){
123455 renameTokenFind(&sParse, &sCtx, p->zName);
123456 }
123457 }
123458 }
123459 }
123460 }
@@ -123294,75 +123905,78 @@
123905 /* Drop and reload the database schema. */
123906 renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
123907 renameTestSchema(pParse, zDb, iDb==1, "after drop column", 1);
123908
123909 /* Edit rows of table on disk */
123910 if( pParse->nErr==0 ){
 
 
 
 
 
 
 
123911 Vdbe *v = sqlite3GetVdbe(pParse);
123912 sqlite3VdbeAddOp0(v, OP_DbLock);
123913 if( (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
123914 int i;
123915 int addr;
123916 int reg;
123917 int regRec;
123918 Index *pPk = 0;
123919 int nField = 0; /* Number of non-virtual columns after drop */
123920 int iCur;
123921 iCur = pParse->nTab++;
123922 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
123923 addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
123924 reg = ++pParse->nMem;
123925 if( HasRowid(pTab) ){
123926 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
123927 pParse->nMem += pTab->nCol;
123928 }else{
123929 pPk = sqlite3PrimaryKeyIndex(pTab);
123930 pParse->nMem += pPk->nColumn;
123931 for(i=0; i<pPk->nKeyCol; i++){
123932 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, reg+i+1);
123933 }
123934 nField = pPk->nKeyCol;
123935 }
123936 regRec = ++pParse->nMem;
123937 for(i=0; i<pTab->nCol; i++){
123938 if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
123939 int regOut;
123940 if( pPk ){
123941 int iPos = sqlite3TableColumnToIndex(pPk, i);
123942 int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
123943 if( iPos<pPk->nKeyCol ) continue;
123944 regOut = reg+1+iPos-(iPos>iColPos);
123945 }else{
123946 regOut = reg+1+nField;
123947 }
123948 if( i==pTab->iPKey ){
123949 sqlite3VdbeAddOp2(v, OP_Null, 0, regOut);
123950 }else{
123951 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
123952 assert( pParse->nErr
123953 || sqlite3VdbeGetOp(v,sqlite3VdbeCurrentAddr(v)-1)->opcode
123954 != OP_RealAffinity
123955 || pTab->aCol[i].affinity==SQLITE_AFF_REAL );
123956 sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
123957 }
123958 nField++;
123959 }
123960 }
123961 if( nField==0 ){
123962 /* dbsqlfuzz 5f09e7bcc78b4954d06bf9f2400d7715f48d1fef */
123963 pParse->nMem++;
123964 sqlite3VdbeAddOp2(v, OP_Null, 0, reg+1);
123965 nField = 1;
123966 }
123967 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
123968 if( pPk ){
123969 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1,pPk->nKeyCol);
123970 }else{
123971 sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
123972 }
123973 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
123974
123975 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
123976 sqlite3VdbeJumpHere(v, addr);
123977 }
123978 }
123979
123980 exit_drop_column:
123981 sqlite3DbFree(db, zCol);
123982 sqlite3SrcListDelete(db, pSrc);
@@ -123864,48 +124478,10 @@
124478 (void)NotUsed;
124479 sqlite3_result_error(ctx, zText, -1);
124480 sqlite3_result_error_code(ctx, err);
124481 }
124482
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124483 /*
124484 ** Prepare a statement of the form:
124485 **
124486 ** ALTER TABLE pSrc ALTER pCol SET NOT NULL
124487 */
@@ -123932,11 +124508,11 @@
124508 return;
124509 }
124510
124511 /* Find the length in bytes of the constraint definition */
124512 pCons = pFirst->z;
124513 nCons = alterRtrimFragment(pParse->db, pCons, pParse->sLastToken.z - pCons);
124514
124515 /* Search for a constraint violation. Throw an exception if one is found. */
124516 sqlite3NestedParse(pParse,
124517 "SELECT sqlite_fail('constraint failed', %d) "
124518 "FROM %Q.%Q AS x WHERE x.%.*s IS NULL",
@@ -124064,11 +124640,11 @@
124640 SQLITE_CONSTRAINT, zDb, pTab->zName, nExpr, zExpr
124641 );
124642
124643 /* Edit the SQL for the named table. */
124644 pCons = pFirst->z;
124645 nCons = alterRtrimFragment(pParse->db, pCons, pParse->sLastToken.z - pCons);
124646
124647 sqlite3NestedParse(pParse,
124648 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
124649 "sql = sqlite_add_constraint(sql, %.*Q, -1) "
124650 "WHERE type='table' AND tbl_name=%Q COLLATE nocase"
@@ -124076,25 +124652,83 @@
124652 );
124653
124654 /* Finally, reload the database schema. */
124655 renameReloadSchema(pParse, iDb, INITFLAG_AlterDropCons);
124656 }
124657
124658 /*
124659 ** The implementation of internal SQL function:
124660 **
124661 ** sqlite_check_type(DB, TAB, COL, TYPE)
124662 **
124663 ** Read the value of column COL from the first row of table DB.TAB. Return
124664 ** 1 if the table contains at least one row and typeof() of the value read
124665 ** is not TYPE. Otherwise, return NULL.
124666 */
124667 static void checkTypeFunc(
124668 sqlite3_context *ctx,
124669 int NotUsed,
124670 sqlite3_value **argv
124671 ){
124672 sqlite3 *db = sqlite3_context_db_handle(ctx);
124673 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
124674 const char *zTab = (const char*)sqlite3_value_text(argv[1]);
124675 const char *zCol = (const char*)sqlite3_value_text(argv[2]);
124676 const char *zType = (const char*)sqlite3_value_text(argv[3]);
124677 sqlite3_stmt *pStmt = 0;
124678 char *zSql;
124679 int rc;
124680
124681 #ifndef SQLITE_OMIT_AUTHORIZATION
124682 sqlite3_xauth xAuth = db->xAuth;
124683 db->xAuth = 0;
124684 #endif
124685
124686 (void)NotUsed;
124687 if( zDb==0 || zTab==0 || zCol==0 || zType==0 ) return;
124688 zSql = sqlite3MPrintf(db,
124689 "SELECT typeof(\"%w\") FROM \"%w\".\"%w\" LIMIT 1", zCol, zDb, zTab
124690 );
124691 if( zSql==0 ){
124692 sqlite3_result_error_nomem(ctx);
124693 return;
124694 }
124695 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
124696 sqlite3DbFree(db, zSql);
124697 if( rc==SQLITE_OK ){
124698 if( sqlite3_step(pStmt)==SQLITE_ROW ){
124699 const char *zVal = (const char*)sqlite3_column_text(pStmt, 0);
124700 if( sqlite3_stricmp(zVal, zType)!=0 ){
124701 sqlite3_result_int(ctx, 1);
124702 }
124703 }
124704 rc = sqlite3_finalize(pStmt);
124705 }
124706 if( rc!=SQLITE_OK ){
124707 sqlite3_result_error(ctx, sqlite3_errmsg(db), -1);
124708 sqlite3_result_error_code(ctx, rc);
124709 }
124710 #ifndef SQLITE_OMIT_AUTHORIZATION
124711 db->xAuth = xAuth;
124712 #endif
124713 }
124714
124715 /*
124716 ** Register built-in functions used to help implement ALTER TABLE
124717 */
124718 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
124719 static FuncDef aAlterTableFuncs[] = {
124720 INTERNAL_FUNCTION(sqlite_check_type, 4, checkTypeFunc),
124721 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
124722 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
124723 INTERNAL_FUNCTION(sqlite_rename_test, 7, renameTableTest),
124724 INTERNAL_FUNCTION(sqlite_drop_column, 3, dropColumnFunc),
124725 INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc),
124726 INTERNAL_FUNCTION(sqlite_drop_constraint,2, dropConstraintFunc),
124727 INTERNAL_FUNCTION(sqlite_fail, 2, failConstraintFunc),
124728 INTERNAL_FUNCTION(sqlite_add_constraint, 3, addConstraintFunc),
124729 INTERNAL_FUNCTION(sqlite_find_constraint,2, findConstraintFunc)
124730 };
124731 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
124732 }
124733 #endif /* SQLITE_ALTER_TABLE */
124734
@@ -127172,10 +127806,20 @@
127806 for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
127807 return 1;
127808 }
127809 #endif
127810
127811 /*
127812 ** Do the union all two yDbMask objects into the first.
127813 */
127814 #if SQLITE_MAX_ATTACHED>30
127815 SQLITE_PRIVATE void sqlite3DbMaskUnion(yDbMask m, yDbMask x){
127816 int i;
127817 for(i=0; i<sizeof(yDbMask); i++){ m[i] |= x[i]; }
127818 }
127819 #endif
127820
127821 /*
127822 ** This routine is called after a single SQL statement has been
127823 ** parsed and a VDBE program to execute that statement has been
127824 ** prepared. This routine puts the finishing touches on the
127825 ** VDBE program and resets the pParse structure for the next
@@ -127664,27 +128308,37 @@
128308 }
128309 }
128310
128311 /*
128312 ** Reset the schema for the database at index iDb. Also reset the
128313 ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero
128314 ** or if an active VDBE other than pSafe is using iDb
128315 **
128316 ** Deferred schema resets may be retried by calling with iDb<0.
128317 */
128318 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb, Vdbe *pSafe){
128319 int i;
128320 assert( iDb<db->nDb );
128321
128322 if( iDb>=0 ){
128323 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
128324 DbSetProperty(db, iDb, DB_ResetWanted);
128325 DbSetProperty(db, 1, DB_ResetWanted);
128326 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
128327 db->bPendingSchemaReset = 1;
128328 }
128329
128330 if( db->nSchemaLock==0 ){
128331 yDbMask m;
128332 sqlite3VdbeSchemaInUse(db, pSafe, &m);
128333 db->bPendingSchemaReset = 0;
128334 for(i=0; i<db->nDb; i++){
128335 if( !DbHasProperty(db, i, DB_ResetWanted) ){
128336 /* no-op */
128337 }else if( DbMaskTest(m,i) ){
128338 db->bPendingSchemaReset = 1;
128339 }else{
128340 sqlite3SchemaClear(db->aDb[i].pSchema);
128341 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
128342 }
128343 }
128344 }
@@ -127705,10 +128359,11 @@
128359 }else{
128360 DbSetProperty(db, i, DB_ResetWanted);
128361 }
128362 }
128363 }
128364 sqlite3ExpirePreparedStatements(db, 0);
128365 db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
128366 sqlite3VtabUnlockList(db);
128367 sqlite3BtreeLeaveAll(db);
128368 if( db->nSchemaLock==0 ){
128369 sqlite3CollapseDatabaseArray(db);
@@ -128130,16 +128785,20 @@
128785 ** is reserved for internal use.
128786 **
128787 ** When parsing the sqlite_schema table, this routine also checks to
128788 ** make sure the "type", "name", and "tbl_name" columns are consistent
128789 ** with the SQL.
128790 **
128791 ** If shadow tables are read-only, names that are shadow table names
128792 ** of a virtual table in schema zDb are also reserved.
128793 */
128794 SQLITE_PRIVATE int sqlite3CheckObjectName(
128795 Parse *pParse, /* Parsing context */
128796 const char *zName, /* Name of the object to check */
128797 const char *zType, /* Type of this object */
128798 const char *zTblName, /* Parent table name for triggers and indexes */
128799 const char *zDb /* Schema in which the object will be created */
128800 ){
128801 sqlite3 *db = pParse->db;
128802 if( sqlite3WritableSchema(db)
128803 || db->init.imposterTable
128804 || !sqlite3Config.bExtraSchemaChecks
@@ -128155,11 +128814,12 @@
128814 sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
128815 return SQLITE_ERROR;
128816 }
128817 }else{
128818 if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
128819 || (sqlite3ReadOnlyShadowTables(db)
128820 && sqlite3ShadowTableName(db, zName, zDb))
128821 ){
128822 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
128823 zName);
128824 return SQLITE_ERROR;
128825 }
@@ -128342,14 +129002,18 @@
129002 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
129003 zName = sqlite3NameFromToken(db, pName);
129004 if( IN_RENAME_OBJECT ){
129005 sqlite3RenameTokenMap(pParse, (void*)zName, pName);
129006 }
129007 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
129008 goto begin_table_error;
129009 }
129010 }
129011 pParse->sNameToken = *pName;
129012 if( zName==0 ) return;
129013 if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName,
129014 db->aDb[iDb].zDbSName) ){
129015 goto begin_table_error;
129016 }
129017 if( db->init.iDb==1 ) isTemp = 1;
129018 #ifndef SQLITE_OMIT_AUTHORIZATION
129019 assert( isTemp==0 || isTemp==1 );
@@ -128379,13 +129043,10 @@
129043 ** and types will be used, so there is no need to test for namespace
129044 ** collisions.
129045 */
129046 if( !IN_SPECIAL_PARSE ){
129047 char *zDb = db->aDb[iDb].zDbSName;
 
 
 
129048 pTable = sqlite3FindTable(db, zName, zDb);
129049 if( pTable ){
129050 if( !noErr ){
129051 sqlite3ErrorMsg(pParse, "%s %T already exists",
129052 (IsView(pTable)? "view" : "table"), pName);
@@ -128613,19 +129274,18 @@
129274
129275 /* Because keywords GENERATE ALWAYS can be converted into identifiers
129276 ** by the parser, we can sometimes end up with a typename that ends
129277 ** with "generated always". Check for this case and omit the surplus
129278 ** text. */
129279 if( sType.n>=16 && sqlite3_strnicmp(sType.z+(sType.n-6),"always",6)==0 ){
129280 u32 nType = sType.n - 6;
129281 while( ALWAYS(nType>0) && sqlite3Isspace(sType.z[nType-1]) ) nType--;
129282 if( nType>=9 && nType<(sType.n - 6)
129283 && sqlite3_strnicmp(sType.z+(nType-9),"generated",9)==0
129284 && (nType==9 || sqlite3Isspace(sType.z[nType-10]))
129285 ){
129286 sType.n = nType - 9;
 
129287 while( sType.n>0 && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
129288 }
129289 }
129290
129291 /* Check for standard typenames. For standard typenames we will
@@ -129692,25 +130352,38 @@
130352 }
130353 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
130354
130355 #ifndef SQLITE_OMIT_VIRTUALTABLE
130356 /*
130357 ** Return true if zName is the name of a shadow table of a virtual table
130358 ** in schema zDb. If zDb is NULL, return true if zName is a shadow table
130359 ** name of a virtual table in any schema of the database connection.
130360 **
130361 ** Each schema is checked separately. An ordinary table in one schema
130362 ** (for example, a TEMP table) must not hide a same-named virtual table
130363 ** in another schema.
130364 */
130365 SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName, const char *zDb){
130366 const char *zTail; /* Pointer to the last "_" in zName */
130367 Table *pTab; /* Table that zName is a shadow of */
130368 char *zCopy; /* Transient copy of zName after last "_" */
130369 int i; /* Loop counter over schemas */
130370 int bRet = 0; /* Return value */
130371 zTail = strrchr(zName, '_');
130372 if( zTail==0 ) return 0;
130373 zCopy = sqlite3DbStrNDup(db, zName, (int)(zTail-zName));
130374 if( zCopy==0 ) return 0;
130375 for(i=0; i<db->nDb && bRet==0; i++){
130376 const char *zSchema = db->aDb[i].zDbSName;
130377 if( zDb && sqlite3DbIsNamed(db, i, zDb)==0 ) continue;
130378 pTab = sqlite3FindTable(db, zCopy, zSchema);
130379 if( pTab && IsVirtual(pTab) ){
130380 bRet = sqlite3IsShadowTableOf(db, pTab, zName);
130381 }
130382 }
130383 sqlite3DbFree(db, zCopy);
130384 return bRet;
 
 
130385 }
130386 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
130387
130388
130389 #ifdef SQLITE_DEBUG
@@ -129775,11 +130448,14 @@
130448 return;
130449 }
130450 p = pParse->pNewTable;
130451 if( p==0 ) return;
130452
130453 if( pSelect==0
130454 && sqlite3ShadowTableName(db, p->zName,
130455 db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].zDbSName)
130456 ){
130457 p->tabFlags |= TF_Shadow;
130458 }
130459
130460 /* If the db->init.busy is 1 it means we are reading the SQL off the
130461 ** "sqlite_schema" or "sqlite_temp_schema" table on the disk.
@@ -131123,13 +131799,17 @@
131799 assert( pName && pName->z );
131800
131801 #ifndef SQLITE_OMIT_TEMPDB
131802 /* If the index name was unqualified, check if the table
131803 ** is a temp table. If so, set the database to 1. Do not do this
131804 ** if initializing a database schema, if ALTER TABLE is reparsing an
131805 ** existing index, or if VACUUM is recreating the indexes of a
131806 ** database. */
131807 if( !db->init.busy
131808 && !IN_RENAME_OBJECT
131809 && (db->mDbFlags & DBFLAG_Vacuum)==0
131810 ){
131811 pTab = sqlite3SrcListLookup(pParse, pTblName);
131812 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
131813 iDb = 1;
131814 }
131815 }
@@ -131196,11 +131876,13 @@
131876 */
131877 if( pName ){
131878 zName = sqlite3NameFromToken(db, pName);
131879 if( zName==0 ) goto exit_create_index;
131880 assert( pName->z!=0 );
131881 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName, "index",
131882 pTab->zName, db->aDb[iDb].zDbSName)
131883 ){
131884 goto exit_create_index;
131885 }
131886 if( !IN_RENAME_OBJECT ){
131887 if( !db->init.busy ){
131888 if( sqlite3FindTable(db, zName, pDb->zDbSName)!=0 ){
@@ -131775,12 +132457,12 @@
132457 sqlite3NestedParse(pParse,
132458 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE " WHERE name=%Q AND type='index'",
132459 db->aDb[iDb].zDbSName, pIndex->zName
132460 );
132461 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
 
132462 destroyRootPage(pParse, pIndex->tnum, iDb);
132463 sqlite3ChangeCookie(pParse, iDb);
132464 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
132465 }
132466
132467 exit_drop_index:
132468 sqlite3SrcListDelete(db, pName);
@@ -134754,11 +135436,11 @@
135436 ** something that can be converted into a number, we have:
135437 ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
135438 ** that cannot be converted to a numeric value.
135439 */
135440 double rVal = sqlite3_value_double(argv[0]);
135441 if( signbit(rVal) ) rVal = -rVal;
135442 sqlite3_result_double(context, rVal);
135443 break;
135444 }
135445 }
135446 }
@@ -134897,12 +135579,19 @@
135579 assert( argc==3 || argc==2 );
135580 p0type = sqlite3_value_type(argv[0]);
135581 p1 = sqlite3_value_int64(argv[1]);
135582 if( p0type==SQLITE_BLOB ){
135583 len = sqlite3_value_bytes(argv[0]);
135584 if( len==0){
135585 /* sqlite3_value_blob() returns a NULL pointer for a zero-length blob.
135586 ** But the call to sqlite3_result_blob() below interprets a NULL pointer
135587 ** as an SQL NULL. So set z to point to some non-NULL location here. */
135588 z = (const unsigned char*)"";
135589 }else{
135590 z = sqlite3_value_blob(argv[0]);
135591 if( z==0 ) return;
135592 }
135593 assert( len==sqlite3_value_bytes(argv[0]) );
135594 }else{
135595 z = sqlite3_value_text(argv[0]);
135596 if( z==0 ) return;
135597 len = 0;
@@ -134932,11 +135621,11 @@
135621 if( p1<0 ){
135622 p1 += len;
135623 if( p1<0 ){
135624 if( p2<0 ){
135625 p2 = 0;
135626 }else if( argc==3 ){
135627 p2 += p1;
135628 }
135629 p1 = 0;
135630 }
135631 }else if( p1>0 ){
@@ -135022,14 +135711,12 @@
135711 ** handle the rounding directly,
135712 ** otherwise use printf.
135713 */
135714 if( r<-4503599627370496.0 || r>+4503599627370496.0 ){
135715 /* The value has no fractional part so there is nothing to round */
 
 
135716 }else{
135717 zBuf = sqlite3_mprintf("%#!.*f",(int)n,r);
135718 if( zBuf==0 ){
135719 sqlite3_result_error_nomem(context);
135720 return;
135721 }
135722 sqlite3AtoF(zBuf, &r);
@@ -137109,11 +137796,11 @@
137796 if( argc==2 ){
137797 switch( sqlite3_value_numeric_type(argv[1]) ){
137798 case SQLITE_INTEGER:
137799 case SQLITE_FLOAT:
137800 b = log(x);
137801 if( b==0.0 ) return;
137802 x = sqlite3_value_double(argv[1]);
137803 if( x<=0.0 ) return;
137804 break;
137805 default:
137806 return;
@@ -138544,10 +139231,12 @@
139231 for(i=0; i<nCol; i++){
139232 sqlite3VdbeAddOp2(v, OP_Copy,
139233 sqlite3TableColumnToStorage(pFKey->pFrom, aiCol[i])+1+regData,
139234 regTemp+i);
139235 }
139236 sqlite3VdbeAddOp4(v, OP_Affinity, regTemp, nCol, 0,
139237 sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
139238
139239 /* If the parent table is the same as the child table, and we are about
139240 ** to increment the constraint-counter (i.e. this is an INSERT operation),
139241 ** then check if the row being inserted matches itself. If so, do not
139242 ** increment the constraint-counter.
@@ -138558,29 +139247,29 @@
139247 ** none of the child key values are).
139248 */
139249 if( pTab==pFKey->pFrom && nIncr==1 ){
139250 int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
139251 for(i=0; i<nCol; i++){
139252 CollSeq *pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
139253 int iChild = regTemp+i;
139254 int iParent = 1+regData;
139255 iParent += sqlite3TableColumnToStorage(pIdx->pTable,
139256 pIdx->aiColumn[i]);
139257 assert( pIdx->aiColumn[i]>=0 );
139258 assert( aiCol[i]!=pTab->iPKey );
139259 if( pIdx->aiColumn[i]==pTab->iPKey ){
139260 /* The parent key is a composite key that includes the IPK column */
139261 iParent = regData;
139262 }
139263 sqlite3VdbeAddOp4(v, OP_Ne, iChild, iJump, iParent,
139264 (char*)pColl, P4_COLLSEQ);
139265 VdbeCoverage(v);
139266 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
139267 }
139268 sqlite3VdbeGoto(v, iOk);
139269 }
139270
 
 
139271 sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regTemp, nCol);
139272 VdbeCoverage(v);
139273 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
139274 }
139275 }
@@ -139150,10 +139839,27 @@
139839 return 1;
139840 }
139841 }
139842 return 0;
139843 }
139844
139845 /*
139846 ** Return true if the child table of FK constraint pFKey has one or
139847 ** more BEFORE triggers that could interfere with the action (either
139848 ** a CASCADE or SET NULL) caused by either a DELETE (if bUpdate==0)
139849 ** or UPDATE (if bUpdate==1) of the parent table. Or false otherwise.
139850 */
139851 static int fkBeforeTriggersExist(
139852 Parse *pParse, /* Parse context */
139853 FKey *pFKey, /* Foreign key constraint */
139854 int bUpdate /* True for ON UPDATE, false ON DELETE */
139855 ){
139856 int mask = 0;
139857 int op = (!bUpdate && pFKey->aAction[0]==OE_Cascade) ? TK_DELETE : TK_UPDATE;
139858 sqlite3TriggersExist(pParse, pFKey->pFrom, op, 0, &mask);
139859 return (mask & TRIGGER_BEFORE)!=0;
139860 }
139861
139862 /*
139863 ** This function is called when inserting, deleting or updating a row of
139864 ** table pTab to generate VDBE code to perform foreign key constraint
139865 ** processing for the operation.
@@ -139184,10 +139890,11 @@
139890 sqlite3 *db = pParse->db; /* Database handle */
139891 FKey *pFKey; /* Used to iterate through FKs */
139892 int iDb; /* Index of database containing pTab */
139893 const char *zDb; /* Name of database containing pTab */
139894 int isIgnoreErrors = pParse->disableTriggers;
139895 int iPass; /* 0: immediate FKs, 1: deferred FKs */
139896
139897 /* Exactly one of regOld and regNew should be non-zero. */
139898 assert( (regOld==0)!=(regNew==0) );
139899
139900 /* If foreign-keys are disabled, this function is a no-op. */
@@ -139197,110 +139904,120 @@
139904 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
139905 assert( iDb>=00 && iDb<db->nDb );
139906 zDb = db->aDb[iDb].zDbSName;
139907
139908 /* Loop through all the foreign key constraints for which pTab is the
139909 ** child table (the table that the foreign key definition is part of).
139910 **
139911 ** Immediate constraints are processed first, then deferred constraints
139912 ** in a second pass. This is because immediate FK processing may halt
139913 ** the VM, and in cases where there is no statement journal this needs
139914 ** to happen before any deferred FKs are processed. */
139915 for(iPass=0; iPass<2; iPass++){
139916 for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
139917 Table *pTo; /* Parent table of foreign key pFKey */
139918 Index *pIdx = 0; /* Index on key columns in pTo */
139919 int *aiFree = 0;
139920 int *aiCol;
139921 int iCol;
139922 int i;
139923 int bIgnore = 0;
139924
139925 assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
139926 if( pFKey->isDeferred!=iPass ) continue;
139927
139928 if( aChange
139929 && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
139930 && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
139931 ){
139932 continue;
139933 }
139934
139935 /* Find the parent table of this foreign key. Also find a unique index
139936 ** on the parent key columns in the parent table. If either of these
139937 ** schema items cannot be located, set an error in pParse and return
139938 ** early. */
139939 if( pParse->disableTriggers ){
139940 pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
139941 }else{
139942 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
139943 }
139944 if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
139945 assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
139946 if( !isIgnoreErrors || db->mallocFailed ) return;
139947 if( pTo==0 ){
139948 /* If isIgnoreErrors is true, then a table is being dropped. In this
139949 ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
139950 ** before actually dropping it in order to check FK constraints.
139951 ** If the parent table of an FK constraint on the current table is
139952 ** missing, behave as if it is empty. i.e. decrement the relevant
139953 ** FK counter for each row of the current table with non-NULL keys.
139954 */
139955 Vdbe *v = sqlite3GetVdbe(pParse);
139956 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
139957 for(i=0; i<pFKey->nCol; i++){
139958 int iFromCol, iReg;
139959 iFromCol = pFKey->aCol[i].iFrom;
139960 iReg = sqlite3TableColumnToStorage(pFKey->pFrom,iFromCol)+regOld+1;
139961 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
139962 }
139963 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
139964 }
139965 continue;
139966 }
139967 assert( pFKey->nCol==1 || (aiFree && pIdx) );
139968
139969 if( aiFree ){
139970 aiCol = aiFree;
139971 }else{
139972 iCol = pFKey->aCol[0].iFrom;
139973 aiCol = &iCol;
139974 }
139975 for(i=0; i<pFKey->nCol; i++){
139976 if( aiCol[i]==pTab->iPKey ){
139977 aiCol[i] = -1;
139978 }
139979 assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
139980 #ifndef SQLITE_OMIT_AUTHORIZATION
139981 /* Request permission to read the parent key columns. If the
139982 ** authorization callback returns SQLITE_IGNORE, behave as if any
139983 ** values read from the parent table are NULL. */
139984 if( db->xAuth ){
139985 int rcauth;
139986 char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zCnName;
139987 rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
139988 bIgnore = (rcauth==SQLITE_IGNORE);
139989 }
139990 #endif
139991 }
139992
139993 /* Take a shared-cache advisory read-lock on the parent table. Allocate
139994 ** a cursor to use to search the unique index on the parent key columns
139995 ** in the parent table. */
139996 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
139997 pParse->nTab++;
139998
139999 if( regOld!=0 ){
140000 /* A row is being removed from the child table. Search for the parent.
140001 ** If the parent does not exist, removing the child row resolves an
140002 ** outstanding foreign key constraint violation. */
140003 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld,-1,bIgnore);
140004 }
140005 if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
140006 /* A row is being added to the child table. If a parent row cannot
140007 ** be found, adding the child row has violated the FK constraint.
140008 **
140009 ** If this operation is being performed as part of a trigger program
140010 ** that is actually a "SET NULL" action belonging to this very
140011 ** foreign key, then omit this scan altogether. As all child key
140012 ** values are guaranteed to be NULL, it is not possible for adding
140013 ** this row to cause an FK violation. */
140014 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew,+1,bIgnore);
140015 }
140016
140017 sqlite3DbFree(db, aiFree);
140018 }
140019 }
140020
140021 /* Loop through all the foreign key constraints that refer to this table.
140022 ** (the "child" constraints) */
140023 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
@@ -139343,14 +140060,20 @@
140060 if( regOld!=0 ){
140061 int eAction = pFKey->aAction[aChange!=0];
140062 if( (db->flags & SQLITE_FkNoAction) ) eAction = OE_None;
140063
140064 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
140065 /* If this is an immediate FK constraint, then foreign key violations
140066 ** caused by removing the parent key may cause an abort.
140067 **
140068 ** Except - if a CASCADE or SET NULL action applies, then any such
140069 ** foreign key violations will be rectified by the action trigger. So
140070 ** do not set the "may-abort" flag in this case.
140071 **
140072 ** Except - if there are BEFORE triggers on the child table, then
140073 ** one of them may use RAISE(IGNORE) to prevent the SET NULL or
140074 ** CASCADE action from taking place. Do set the "may-abort" flag then.
140075 **
140076 ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
140077 ** may-abort flag will eventually be set on this statement anyway
140078 ** (when this function is called as part of processing the UPDATE
140079 ** within the action trigger).
@@ -139360,11 +140083,14 @@
140083 ** applies. The trouble starts if the CASCADE or SET NULL action
140084 ** trigger causes other triggers or action rules attached to the
140085 ** child table to fire. In these cases the fk constraint counters
140086 ** might be set incorrectly if any OP_FkCounter related scans are
140087 ** omitted. */
140088 if( !pFKey->isDeferred && (
140089 (eAction!=OE_Cascade && eAction!=OE_SetNull)
140090 || fkBeforeTriggersExist(pParse, pFKey, aChange!=0)
140091 )){
140092 sqlite3MayAbort(pParse);
140093 }
140094 }
140095 pItem->zName = 0;
140096 sqlite3SrcListDelete(db, pSrc);
@@ -139423,11 +140149,16 @@
140149 **
140150 ** * There are any FKs for which pTab is the child and the parent table
140151 ** and any FK processing at all is required (even of a different FK), or
140152 **
140153 ** * the UPDATE modifies one or more parent keys for which the action is
140154 ** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL), or
140155 **
140156 ** * the UPDATE modifies one or more parent keys of an FK for which pTab
140157 ** is also the child table. The old version of the row must be removed
140158 ** from the table before the FK checks run, as otherwise the scan for
140159 ** rows that refer to the new parent key may find it.
140160 **
140161 ** Or, assuming some other foreign key processing is required, 1.
140162 */
140163 SQLITE_PRIVATE int sqlite3FkRequired(
140164 Parse *pParse, /* Parse context */
@@ -139462,10 +140193,11 @@
140193 if( (pParse->db->flags & SQLITE_FkNoAction)==0
140194 && p->aAction[1]!=OE_None
140195 ){
140196 return 2;
140197 }
140198 if( p->pFrom==pTab ) eRet = 2;
140199 bHaveFK = 1;
140200 }
140201 }
140202 }
140203 }
@@ -140403,10 +141135,22 @@
141135 if( 0!=sqlite3ExprAffinity(pExpr) ) return 0;
141136 }
141137 return 1;
141138
141139 }
141140
141141 /*
141142 ** Return true if any expression in the expression-list passed as the
141143 ** only argument contains a COLLATE operator.
141144 */
141145 static int exprListHasCollate(ExprList *pRow){
141146 int ii;
141147 for(ii=0; ii<pRow->nExpr; ii++){
141148 if( ExprHasProperty(pRow->a[ii].pExpr, EP_Collate) ) return 1;
141149 }
141150 return 0;
141151 }
141152
141153 /*
141154 ** This function is called by the parser for the second and subsequent
141155 ** rows of a multi-row VALUES clause. Argument pLeft is the part of
141156 ** the VALUES clause already parsed, argument pRow is the vector of values
@@ -140454,18 +141198,28 @@
141198 ** has an affinity (i.e. is a CAST expression). This causes problems
141199 ** because the complex rules SQLite uses (see function
141200 ** sqlite3SubqueryColumnTypes() in select.c) to determine the effective
141201 ** affinity of such a column for all rows require access to all values in
141202 ** the column simultaneously.
141203 **
141204 ** e) The new row, or the row that would become the first row of the
141205 ** co-routine, contains a COLLATE operator. This ensures that the
141206 ** columns of a co-routine never have a collation sequence (see
141207 ** multiSelectCollSeq() in select.c). Each explicit COLLATE in a VALUES
141208 ** clause is instead part of an ordinary SELECT in a UNION ALL
141209 ** compound, where it is available when the collation sequence for a
141210 ** compound SELECT column is determined.
141211 */
141212 SQLITE_PRIVATE Select *sqlite3MultiValues(Parse *pParse, Select *pLeft, ExprList *pRow){
141213
141214 if( pParse->bHasWith /* condition (a) above */
141215 || pParse->db->init.busy /* condition (b) above */
141216 || sqlite3ExprListIsConstant(pParse, pRow, 1)==0 /* condition (c) above */
141217 || (pLeft->pSrc->nSrc==0 &&
141218 exprListIsNoAffinity(pParse,pLeft->pEList)==0) /* condition (d) above */
141219 || exprListHasCollate(pRow) /* condition (e) above */
141220 || (pLeft->pSrc->nSrc==0 && exprListHasCollate(pLeft->pEList))
141221 || IN_SPECIAL_PARSE
141222 ){
141223 /* The co-routine method cannot be used. Fall back to UNION ALL. */
141224 Select *pSelect = 0;
141225 int f = SF_Values | SF_MultiValue;
@@ -140503,11 +141257,11 @@
141257 SelectDest dest;
141258 Subquery *pSubq;
141259 pRet->pSrc->nSrc = 1;
141260 pRet->pPrior = pLeft->pPrior;
141261 pRet->op = pLeft->op;
141262 pRet->selFlags |= SF_Values;
141263 pLeft->pPrior = 0;
141264 pLeft->op = TK_SELECT;
141265 assert( pLeft->pNext==0 );
141266 assert( pRet->pNext==0 );
141267 p = &pRet->pSrc->a[0];
@@ -140729,11 +141483,15 @@
141483
141484 /* If the Select object is really just a simple VALUES() list with a
141485 ** single row (the common case) then keep that one row of values
141486 ** and discard the other (unused) parts of the pSelect object
141487 */
141488 if( pSelect
141489 && (pSelect->selFlags & SF_Values)!=0
141490 && pSelect->pPrior==0
141491 && pSelect->pSrc->nSrc==0
141492 ){
141493 pList = pSelect->pEList;
141494 pSelect->pEList = 0;
141495 sqlite3SelectDelete(db, pSelect);
141496 pSelect = 0;
141497 }
@@ -142054,10 +142812,16 @@
142812 if( pUpsertClause!=0 ){
142813 if( pUpsertClause->isDoUpdate==0 ){
142814 onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
142815 }else{
142816 onError = OE_Update; /* DO UPDATE */
142817 /* The excluded.* values used by the DO UPDATE must have
142818 ** column affinity applied before the rowid conflict check. */
142819 if( bAffinityDone==0 ){
142820 sqlite3TableAffinity(v, pTab, regNewData+1);
142821 bAffinityDone = 1;
142822 }
142823 }
142824 }
142825 if( pUpsertClause!=pUpsert ){
142826 /* The first ON CONFLICT clause has a conflict target other than
142827 ** the IPK. We have to jump ahead to that first ON CONFLICT clause
@@ -142213,10 +142977,18 @@
142977 bAffinityDone = 1;
142978 }
142979 VdbeNoopComment((v, "prep index %s", pIdx->zName));
142980 iThisCur = iIdxCur+ix;
142981
142982 /* If an OE_Replace resolution earlier in the constraint checks may
142983 ** have already deleted a conflicting row, and evaluating the partial
142984 ** index WHERE clause or an indexed expression for this index might
142985 ** raise an error, then a statement journal may be required to undo
142986 ** the deletion. */
142987 if( seenReplace && (pIdx->pPartIdxWhere || pIdx->aColExpr) ){
142988 sqlite3MultiWrite(pParse);
142989 }
142990
142991 /* Skip partial indices for which the WHERE clause is not true */
142992 if( pIdx->pPartIdxWhere ){
142993 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
142994 pParse->iSelfTab = -(regNewData+1);
@@ -142897,10 +143669,13 @@
143669 return 0; /* FROM clause must have exactly one term */
143670 }
143671 if( pSelect->pSrc->a[0].fg.isSubquery ){
143672 return 0; /* FROM clause cannot contain a subquery */
143673 }
143674 if( pSelect->pSrc->a[0].fg.isIndexedBy ){
143675 return 0; /* FROM clause cannot have an INDEXED BY clause */
143676 }
143677 if( pSelect->pWhere ){
143678 return 0; /* SELECT may not have a WHERE clause */
143679 }
143680 if( pSelect->pOrderBy ){
143681 return 0; /* SELECT may not have an ORDER BY clause */
@@ -143064,19 +143839,21 @@
143839 ){
143840 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
143841 }
143842 #endif
143843 #ifndef SQLITE_OMIT_FOREIGN_KEY
143844 /* Disallow the transfer optimization if foreign key processing is
143845 ** enabled and the destination table is either the child or the parent
143846 ** of any foreign key constraint. This is more restrictive than
143847 ** necessary. But the main beneficiary of the transfer optimization is
143848 ** the VACUUM command, and the VACUUM command disables foreign key
143849 ** constraints. So the extra complication to make this rule less
143850 ** restrictive is probably not worth the effort. Ticket
143851 ** [6284df89debdfa61db8073e062908af0c9b6118e] and bugs forum post
143852 ** [2026-11-04T20:24:15Z]. */
143853 assert( IsOrdinaryTable(pDest) );
143854 if( sqlite3FkRequired(pParse, pDest, 0, 0) ){
143855 return 0;
143856 }
143857 #endif
143858 if( (db->flags & SQLITE_CountRows)!=0 ){
143859 return 0; /* xfer opt does not play well with PRAGMA count_changes */
@@ -146157,17 +146934,26 @@
146934 ** Helper subroutine for PRAGMA integrity_check:
146935 **
146936 ** Generate code to output a single-column result row with a value of the
146937 ** string held in register 3. Decrement the result count in register 1
146938 ** and halt if the maximum number of result rows have been issued.
146939 **
146940 ** If iCol is not negative, then after the result row has been output,
146941 ** also load column iCol of cursor iCur into register 3. This is to ensure
146942 ** the cursor's column cache is valid after it is invalidated by the
146943 ** OP_ResultRow.
146944 */
146945 static int integrityCheckResultRow(Vdbe *v, int iCur, int iCol){
146946 int addr;
146947 sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
146948 addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
146949 VdbeCoverage(v);
146950 sqlite3VdbeAddOp0(v, OP_Halt);
146951 if( iCol>=0 ){
146952 sqlite3VdbeAddOp3(v, OP_Column, iCur, iCol, 3);
146953 sqlite3VdbeTypeofColumn(v, 3);
146954 }
146955 return addr;
146956 }
146957
146958 /*
146959 ** Should table pTab be skipped when doing an integrity_check?
@@ -147567,11 +148353,11 @@
148353 addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
148354 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
148355 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
148356 P4_DYNAMIC);
148357 sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
148358 integrityCheckResultRow(v, 0, -1);
148359 sqlite3VdbeJumpHere(v, addr);
148360
148361 /* Check that the indexes all have the right number of rows */
148362 cnt = pObjTab ? 1 : 0;
148363 sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
@@ -147593,11 +148379,11 @@
148379 if( pIdx->pPartIdxWhere==0 ){
148380 addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+cnt, 0, 8+iTab);
148381 VdbeCoverageNeverNull(v);
148382 sqlite3VdbeLoadString(v, 4, pIdx->zName);
148383 sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
148384 integrityCheckResultRow(v, 0, -1);
148385 sqlite3VdbeJumpHere(v, addr);
148386 }
148387 cnt++;
148388 }
148389 }
@@ -147639,25 +148425,20 @@
148425 ** will also prepopulate the cursor column cache that is used
148426 ** by the OP_IsType code, so it is a required step.
148427 */
148428 assert( !IsVirtual(pTab) );
148429 if( HasRowid(pTab) ){
148430 mxCol = pTab->nNVCol-1;
 
 
 
 
148431 }else{
148432 /* COLFLAG_VIRTUAL columns are not included in the WITHOUT ROWID
148433 ** PK index column-count, so there is no need to account for them
148434 ** in this case. */
148435 mxCol = sqlite3PrimaryKeyIndex(pTab)->nColumn-1;
148436 }
148437 assert( mxCol>=0 );
148438 sqlite3VdbeAddOp3(v, OP_Column, iDataCur, mxCol, 3);
148439 sqlite3VdbeTypeofColumn(v, 3);
 
148440
148441 if( !isQuick ){
148442 if( pPk ){
148443 /* Verify WITHOUT ROWID keys are in ascending order */
148444 int a1;
@@ -147667,11 +148448,11 @@
148448 sqlite3VdbeAddOp1(v, OP_IsNull, r2); VdbeCoverage(v);
148449 zErr = sqlite3MPrintf(db,
148450 "row not in PRIMARY KEY order for %s",
148451 pTab->zName);
148452 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
148453 integrityCheckResultRow(v, iDataCur, mxCol);
148454 sqlite3VdbeJumpHere(v, a1);
148455 sqlite3VdbeJumpHere(v, a1+1);
148456 for(j=0; j<pPk->nKeyCol; j++){
148457 sqlite3ExprCodeLoadIndexColumn(pParse, pPk, iDataCur, j, r2+j);
148458 }
@@ -147804,11 +148585,11 @@
148585 zErr = sqlite3MPrintf(db, "TEXT value in %s.%s",
148586 pTab->zName, pTab->aCol[j].zCnName);
148587 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
148588 }
148589 sqlite3VdbeResolveLabel(v, labelError);
148590 integrityCheckResultRow(v, iDataCur, mxCol);
148591 sqlite3VdbeResolveLabel(v, labelOk);
148592 }
148593 /* Verify CHECK constraints */
148594 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
148595 ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
@@ -147826,11 +148607,11 @@
148607 sqlite3VdbeResolveLabel(v, addrCkFault);
148608 pParse->iSelfTab = 0;
148609 zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
148610 pTab->zName);
148611 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
148612 integrityCheckResultRow(v, 0, -1);
148613 sqlite3VdbeResolveLabel(v, addrCkOk);
148614 }
148615 sqlite3ExprListDelete(db, pCheck);
148616 }
148617 if( !isQuick ){ /* Omit the remaining tests for quick_check */
@@ -147852,21 +148633,21 @@
148633 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
148634 sqlite3MPrintf(db, "index %s stores an imprecise floating-point "
148635 "value for row ", pIdx->zName),
148636 P4_DYNAMIC);
148637 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
148638 integrityCheckResultRow(v, 0, -1);
148639 sqlite3VdbeAddOp2(v, OP_Goto, 0, ckUniq);
148640
148641 sqlite3VdbeJumpHere(v, jmp2);
148642 sqlite3VdbeLoadString(v, 3, "row ");
148643 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
148644 sqlite3VdbeLoadString(v, 4, " missing from index ");
148645 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
148646 jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
148647 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
148648 jmp4 = integrityCheckResultRow(v, 0, -1);
148649 sqlite3VdbeResolveLabel(v, ckUniq);
148650
148651 /* The OP_IdxRowid opcode is an optimized version of OP_Column
148652 ** that extracts the rowid off the end of the index record.
148653 ** But it only works correctly if index record does not have
@@ -147961,11 +148742,11 @@
148742 if( pVTab->pModule->xIntegrity==0 ) continue;
148743 sqlite3VdbeAddOp3(v, OP_VCheck, i, 3, isQuick);
148744 pTab->nTabRef++;
148745 sqlite3VdbeAppendP4(v, pTab, P4_TABLEREF);
148746 a1 = sqlite3VdbeAddOp1(v, OP_IsNull, 3); VdbeCoverage(v);
148747 integrityCheckResultRow(v, 0, -1);
148748 sqlite3VdbeJumpHere(v, a1);
148749 continue;
148750 }
148751 #endif
148752 }
@@ -148761,15 +149542,17 @@
149542 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
149543 int rc;
149544 int i, j;
149545 StrAccum acc;
149546 char *zSql;
149547 int type0 = SQLITE_NULL;
149548
149549 UNUSED_PARAMETER(idxNum);
149550 UNUSED_PARAMETER(idxStr);
149551 pragmaVtabCursorClear(pCsr);
149552 j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
149553 if( argc>0 ) type0 = sqlite3_value_type(argv[0]);
149554 for(i=0; i<argc; i++, j++){
149555 const char *zText = (const char*)sqlite3_value_text(argv[i]);
149556 assert( j<ArraySize(pCsr->azArg) );
149557 assert( pCsr->azArg[j]==0 );
149558 if( zText ){
@@ -148784,11 +149567,15 @@
149567 if( pCsr->azArg[1] ){
149568 sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
149569 }
149570 sqlite3_str_appendall(&acc, pTab->pName->zName);
149571 if( pCsr->azArg[0] ){
149572 if( type0<=SQLITE_FLOAT ){
149573 sqlite3_str_appendf(&acc, "=%s", pCsr->azArg[0]);
149574 }else{
149575 sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
149576 }
149577 }
149578 zSql = sqlite3StrAccumFinish(&acc);
149579 if( zSql==0 ) return SQLITE_NOMEM;
149580 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
149581 sqlite3_free(zSql);
@@ -149018,10 +149805,17 @@
149805 const char *zEnd;
149806 TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
149807
149808 assert( db->init.busy );
149809 db->init.iDb = iDb;
149810
149811 /* We never try to parse a trigger on a read-only database */
149812 assert( db->aDb[iDb].pBt==0
149813 || sqlite3BtreeIsReadonly(db->aDb[iDb].pBt)==0
149814 || sqlite3_stricmp(argv[0],"trigger")!=0
149815 || CORRUPT_DB );
149816
149817 if( sqlite3GetUInt32(argv[3], &db->init.newTnum)==0
149818 || (db->init.newTnum>pData->mxPage && pData->mxPage>0)
149819 ){
149820 if( sqlite3Config.bExtraSchemaChecks ){
149821 corruptSchema(pData, argv, "invalid rootpage");
@@ -149267,12 +150061,13 @@
150061 assert( db->init.busy );
150062 initData.mxPage = sqlite3BtreeLastPage(pDb->pBt);
150063 {
150064 char *zSql;
150065 zSql = sqlite3MPrintf(db,
150066 "SELECT*FROM\"%w\".%s %sORDER BY rowid",
150067 db->aDb[iDb].zDbSName, zSchemaTabName,
150068 sqlite3BtreeIsReadonly(db->aDb[iDb].pBt)?"WHERE type<>'trigger'":"");
150069 #ifndef SQLITE_OMIT_AUTHORIZATION
150070 {
150071 sqlite3_xauth xAuth;
150072 xAuth = db->xAuth;
150073 db->xAuth = 0;
@@ -149289,10 +150084,16 @@
150084 sqlite3AnalysisLoad(db, iDb);
150085 }
150086 #endif
150087 }
150088 assert( pDb == &(db->aDb[iDb]) );
150089
150090 /* Confirm that TRIGGERs are not parsed on a read-only database */
150091 assert( sqlite3BtreeIsReadonly(pDb->pBt)==0
150092 || sqliteHashCount(&pDb->pSchema->trigHash)==0
150093 || CORRUPT_DB );
150094
150095 if( db->mallocFailed ){
150096 rc = SQLITE_NOMEM_BKPT;
150097 sqlite3ResetAllSchemasOfConnection(db);
150098 pDb = &db->aDb[iDb];
150099 }else
@@ -149324,11 +150125,11 @@
150125 error_out:
150126 if( rc ){
150127 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
150128 sqlite3OomFault(db);
150129 }
150130 sqlite3ResetOneSchema(db, iDb, 0);
150131 }
150132 db->init.busy = 0;
150133 return rc;
150134 }
150135
@@ -149426,11 +150227,11 @@
150227 ** set Parse.rc to SQLITE_SCHEMA. */
150228 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
150229 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
150230 if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
150231 if( DbHasProperty(db, iDb, DB_SchemaLoaded) ) pParse->rc = SQLITE_SCHEMA;
150232 sqlite3ResetOneSchema(db, iDb, 0);
150233 }
150234
150235 /* Close the transaction, if one was opened. */
150236 if( openedTransaction ){
150237 sqlite3BtreeCommit(pBt);
@@ -149768,11 +150569,11 @@
150569 rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
150570 assert( rc==SQLITE_OK || *ppStmt==0 );
150571 if( rc==SQLITE_OK || db->mallocFailed ) break;
150572 cnt++;
150573 }while( (rc==SQLITE_ERROR_RETRY && ALWAYS(cnt<=SQLITE_MAX_PREPARE_RETRY))
150574 || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1,0), cnt)==1) );
150575 sqlite3BtreeLeaveAll(db);
150576 assert( rc!=SQLITE_ERROR_RETRY );
150577 rc = sqlite3ApiExit(db, rc);
150578 assert( (rc&db->errMask)==rc );
150579 db->busyHandler.nBusy = 0;
@@ -150492,10 +151293,41 @@
151293 }
151294 unsetJoinExpr(p->pLeft, iTable, nullable);
151295 p = p->pRight;
151296 }
151297 }
151298
151299 /*
151300 ** Tree walker expression callback for clearOuterOnExpr().
151301 **
151302 ** If the Expr node is marked as coming from an outer join for
151303 ** table pWalker->u.iCur, then clear its join markers completely.
151304 */
151305 static int clearOuterOnExprCb(Walker *pWalker, Expr *p){
151306 if( ExprHasProperty(p, EP_OuterON) && p->w.iJoin==pWalker->u.iCur ){
151307 ExprClearProperty(p, EP_OuterON|EP_InnerON);
151308 }
151309 return WRC_Continue;
151310 }
151311
151312 /*
151313 ** Remove the EP_OuterON mark, without substituting EP_InnerON, from every
151314 ** term of the expression tree p that is marked EP_OuterON with w.iJoin==iTable.
151315 ** The resulting terms are ordinary WHERE-clause terms.
151316 **
151317 ** This is used when table iTable was marked as an outer-join table only
151318 ** because it was the left operand of a RIGHT JOIN (JT_LTORJ) and that
151319 ** status has been removed by OUTER JOIN strength reduction.
151320 */
151321 static void clearOuterOnExpr(Expr *p, int iTable){
151322 Walker w;
151323 memset(&w, 0, sizeof(w));
151324 w.u.iCur = iTable;
151325 w.xExprCallback = clearOuterOnExprCb;
151326 w.xSelectCallback = 0;
151327 sqlite3WalkExpr(&w,p);
151328 }
151329
151330 /*
151331 ** This routine processes the join information for a SELECT statement.
151332 **
151333 ** * A NATURAL join is converted into a USING join. After that, we
@@ -150522,10 +151354,11 @@
151354 SrcItem *pLeft; /* Left table being joined */
151355 SrcItem *pRight; /* Right table being joined */
151356 int bSeenTFunc = 0; /* True if have seen table-valued function */
151357
151358 pSrc = p->pSrc;
151359 if( pSrc->nSrc<=1 ) return 0;
151360 pLeft = &pSrc->a[0];
151361 pRight = &pLeft[1];
151362 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
151363 Table *pRightTab = pRight->pSTab;
151364 u32 joinType;
@@ -151254,17 +152087,17 @@
152087 if( srcTab>=0 ){
152088 for(i=0; i<nResultCol; i++){
152089 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
152090 VdbeComment((v, "%s", p->pEList->a[i].zEName));
152091 }
152092 }else if( eDest!=SRT_Exists || hasDistinct ){
152093 /* If the destination is an EXISTS(...) expression, the actual
152094 ** values returned by the SELECT are only required if the query is
152095 ** DISTINCT. */
152096 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
152097 ExprList *pExtra = 0;
152098 #endif
 
 
 
152099 u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
152100 ExprList *pEList;
152101 if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
152102 ecelFlags = SQLITE_ECEL_DUP;
152103 }else{
@@ -152647,16 +153480,20 @@
153480 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
153481 }else{
153482 pRet = 0;
153483 }
153484 assert( iCol>=0 );
153485 /* iCol must be less than p->pEList->nExpr. Otherwise an error would
153486 ** have been thrown during name resolution and we would not have gotten
153487 ** this far. If p is really a multi-row VALUES statement, it is guaranteed
153488 ** not to have any collation sequences. So leave pRet set to 0 in this case */
153489 if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr)
153490 && ((p->selFlags & SF_Values)==0 || p->pSrc->nSrc==0) /* multi-row VALUES */
153491 ){
153492 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
153493 }
153494
153495 return pRet;
153496 }
153497
153498 /*
153499 ** The select statement passed as the second parameter is a compound SELECT
@@ -152864,11 +153701,11 @@
153701
153702 /* Find the next row in the Queue and output that row */
153703 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
153704
153705 /* Transfer the next row in Queue over to Current */
153706 sqlite3VdbeAddOp1(v, OP_Stale, iCurrent); /* To reset column cache */
153707 if( pOrderBy ){
153708 sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
153709 }else{
153710 sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
153711 }
@@ -152968,10 +153805,21 @@
153805 */
153806 static int hasAnchor(Select *p){
153807 while( p && (p->selFlags & SF_Recursive)!=0 ){ p = p->pPrior; }
153808 return p!=0;
153809 }
153810
153811 /*
153812 ** Return TRUE if every compound operator in the compound SELECT that
153813 ** ends with p is UNION ALL.
153814 */
153815 static int selectIsUnionAll(Select *p){
153816 for(; p->pPrior; p=p->pPrior){
153817 if( p->op!=TK_ALL ) return 0;
153818 }
153819 return 1;
153820 }
153821
153822 /*
153823 ** Return TRUE if p is a UNION with a LIMIT of exactly 1 and no OFFSET
153824 ** clause. This is a precondition for a couple of related optimizations.
153825 **
@@ -153080,11 +153928,11 @@
153928 #endif
153929 if( p->pOrderBy ){
153930 /* If the compound has an ORDER BY clause, then always use the merge
153931 ** algorithm. */
153932 return multiSelectByMerge(pParse, p, pDest);
153933 }else if( !selectIsUnionAll(p) && !unionWithLimitOne(db,p) ){
153934 /* If the compound is EXCEPT, INTERSECT, or UNION (anything other than
153935 ** UNION ALL) then also always use the merge algorithm. However, the
153936 ** multiSelectByMerge() routine requires that the compound have an
153937 ** ORDER BY clause, and it doesn't right now. So invent one first. */
153938 Expr *pOne = sqlite3ExprInt32(db, 1);
@@ -153236,30 +154084,34 @@
154084 switch( pDest->eDest ){
154085 /* Store the result as data using a unique key.
154086 */
154087 case SRT_Fifo:
154088 case SRT_DistFifo:
154089 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
154090 case SRT_Table:
154091 #endif
154092 case SRT_EphemTab: {
154093 int r1 = sqlite3GetTempReg(pParse);
154094 int r2 = sqlite3GetTempReg(pParse);
154095 int iParm = pDest->iSDParm;
 
154096 testcase( pDest->eDest==SRT_EphemTab );
154097 testcase( pDest->eDest==SRT_Fifo );
154098 testcase( pDest->eDest==SRT_DistFifo );
154099 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
154100 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
154101 testcase( pDest->eDest==SRT_Table );
154102 #if !defined(SQLITE_ENABLE_NULL_TRIM) && defined(SQLITE_DEBUG)
154103 /* A destination of SRT_Table and a non-zero iSDParm2 parameter means
154104 ** that this is an "UPDATE ... FROM" on a virtual table or view. In this
154105 ** case set the p5 parameter of the OP_MakeRecord to OPFLAG_NOCHNG_MAGIC.
154106 ** This does not affect operation in any way - it just allows MakeRecord
154107 ** to process OPFLAG_NOCHANGE values without an assert() failing. */
154108 if( pDest->eDest==SRT_Table && pDest->iSDParm2 ){
154109 sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
154110 }
154111 #endif /* !ENABLE_NULL_TRIM && DEBUG */
154112 #endif /* UPDATE_DELETE_LIMIT */
154113 #ifndef SQLITE_OMIT_CTE
154114 if( pDest->eDest==SRT_DistFifo ){
154115 /* If the destination is DistFifo, then cursor (iParm+1) is open
154116 ** on an ephemeral index that is used to enforce uniqueness on the
154117 ** total result. At this point, we are processing the setup portion
@@ -153863,10 +154715,19 @@
154715 **
154716 ** When the subquery on the right side of the LEFT JOIN is flattened, we
154717 ** have to add OP_IfNullRow in front of the OP_Integer that implements the
154718 ** "m" value of the subquery so that a NULL will be loaded instead of 59
154719 ** when processing a non-matched row of the left.
154720 **
154721 ** ## Unwrap mode:
154722 **
154723 ** If pEList is NULL, then the SubstContext is being used by
154724 ** unwrapIfNullRow() to remove TK_IF_NULL_ROW wrappers instead of to
154725 ** substitute column references. In that mode, only the TK_IF_NULL_ROW
154726 ** nodes with iTable==iTable are touched, each one being replaced by its
154727 ** operand. Column references are left alone and iNewTable must equal
154728 ** iTable.
154729 */
154730 typedef struct SubstContext {
154731 Parse *pParse; /* The parsing context */
154732 int iTable; /* Replace references to this table */
154733 int iNewTable; /* New table number */
@@ -153904,10 +154765,11 @@
154765 testcase( ExprHasProperty(pExpr, EP_InnerON) );
154766 pExpr->w.iJoin = pSubst->iNewTable;
154767 }
154768 if( pExpr->op==TK_COLUMN
154769 && pExpr->iTable==pSubst->iTable
154770 && pSubst->pEList!=0
154771 && !ExprHasProperty(pExpr, EP_FixedCol)
154772 ){
154773 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
154774 if( pExpr->iColumn<0 ){
154775 pExpr->op = TK_NULL;
@@ -153975,13 +154837,23 @@
154837 pExpr = pNew;
154838 }
154839 }
154840 }else{
154841 if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
154842 if( pSubst->pEList==0 ){
154843 /* Unwrap mode. See unwrapIfNullRow(). */
154844 Expr *pInner = pExpr->pLeft;
154845 pExpr->pLeft = 0;
154846 sqlite3ExprDelete(pSubst->pParse->db, pExpr);
154847 return substExpr(pSubst, pInner);
154848 }
154849 pExpr->iTable = pSubst->iNewTable;
154850 }
154851 if( pExpr->op==TK_AGG_FUNCTION
154852 && pSubst->pEList!=0
154853 && pExpr->op2>=pSubst->nSelDepth
154854 ){
154855 pExpr->op2--;
154856 }
154857 pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
154858 pExpr->pRight = substExpr(pSubst, pExpr->pRight);
154859 if( ExprUseXSelect(pExpr) ){
@@ -154037,10 +154909,38 @@
154909 }
154910 }
154911 }while( doPrior && (p = p->pPrior)!=0 );
154912 pSubst->nSelDepth--;
154913 }
154914
154915 /*
154916 ** The flattener wraps each substituted expression in a TK_IF_NULL_ROW
154917 ** operator when the subquery being flattened is on the NULL-able side of
154918 ** an outer join. The wrapper is keyed to the cursor iCur of the
154919 ** (single-table) subquery.
154920 **
154921 ** If OUTER JOIN strength reduction later determines that the table with
154922 ** cursor iCur can no longer be a NULL row, then those wrappers are
154923 ** unnecessary. Worse, they are harmful if the FROM-clause term for iCur
154924 ** is itself a subquery that is flattened later. The flattener would
154925 ** then renumber the wrappers to refer to the first table of that
154926 ** subquery, and that table might legitimately be a NULL row (for example,
154927 ** if it is the left operand of a FULL JOIN inside the subquery). The
154928 ** substituted expressions would then be incorrectly forced to NULL.
154929 **
154930 ** So when strength reduction removes the NULL-able status from the
154931 ** table at iCur, remove all of the TK_IF_NULL_ROW wrappers for iCur from
154932 ** the entire SELECT statement p.
154933 */
154934 static void unwrapIfNullRow(Parse *pParse, Select *p, int iCur){
154935 SubstContext x;
154936 memset(&x, 0, sizeof(x));
154937 x.pParse = pParse;
154938 x.iTable = iCur;
154939 x.iNewTable = iCur;
154940 substSelect(&x, p, 0);
154941 }
154942 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
154943
154944 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
154945 /*
154946 ** pSelect is a SELECT statement and pSrcItem is one item in the FROM
@@ -154213,10 +155113,34 @@
155113 }
155114 return 0;
155115 }
155116
155117 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
155118 /*
155119 ** Return true if the FROM clause pSrc, other than item iExcept, contains
155120 ** a subquery implemented using a co-routine. Such co-routines may have
155121 ** been coded while the SQL text was being parsed, before query planning.
155122 */
155123 static int srcListHasCoroutine(const SrcList *pSrc, int iExcept){
155124 int i;
155125 for(i=0; i<pSrc->nSrc; i++){
155126 const SrcItem *pItem = &pSrc->a[i];
155127 if( i==iExcept ) continue;
155128 if( pItem->fg.viaCoroutine ) return 1;
155129 if( pItem->fg.isSubquery ){
155130 Select *pSelect;
155131 for(pSelect=pItem->u4.pSubq->pSelect;
155132 pSelect;
155133 pSelect=pSelect->pPrior
155134 ){
155135 if( srcListHasCoroutine(pSelect->pSrc, -1) ) return 1;
155136 }
155137 }
155138 }
155139 return 0;
155140 }
155141
155142 /*
155143 ** This routine attempts to flatten subqueries as a performance optimization.
155144 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
155145 **
155146 ** To understand the concept of flattening, consider the following
@@ -154541,10 +155465,11 @@
155465 if( compoundHasDifferentAffinities(pSub) ) return 0;
155466
155467 if( pSrc->nSrc>1 ){
155468 if( pParse->nSelect>500 ) return 0;
155469 if( OptimizationDisabled(db, SQLITE_FlttnUnionAll) ) return 0;
155470 if( p->pOrderBy && srcListHasCoroutine(pSrc, iFrom) ) return 0;
155471 aCsrMap = sqlite3DbMallocZero(db, ((i64)pParse->nTab+1)*sizeof(int));
155472 if( aCsrMap ) aCsrMap[0] = pParse->nTab;
155473 }
155474 }
155475
@@ -154829,11 +155754,11 @@
155754 struct WhereConst {
155755 Parse *pParse; /* Parsing context */
155756 u8 *pOomFault; /* Pointer to pParse->db->mallocFailed */
155757 int nConst; /* Number for COLUMN=CONSTANT terms */
155758 int nChng; /* Number of times a constant is propagated */
155759 int bHasAffBlob; /* A column in apExpr[] has affinity NONE or BLOB */
155760 u32 mExcludeOn; /* Which ON expressions to exclude from considertion.
155761 ** Either EP_OuterON or EP_InnerON|EP_OuterON */
155762 Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */
155763 };
155764
@@ -154997,12 +155922,13 @@
155922 assert( TK_GE==TK_EQ+4 );
155923 if( pConst->bHasAffBlob ){
155924 if( (pExpr->op>=TK_EQ && pExpr->op<=TK_GE)
155925 || pExpr->op==TK_IS
155926 ){
155927 if( sqlite3ExprAffinity(pExpr->pRight)!=SQLITE_AFF_TEXT ){
155928 propagateConstantExprRewriteOne(pConst, pExpr->pLeft, 0);
155929 }
155930 if( sqlite3ExprAffinity(pExpr->pLeft)!=SQLITE_AFF_TEXT ){
155931 propagateConstantExprRewriteOne(pConst, pExpr->pRight, 0);
155932 }
155933 }
155934 }
@@ -155466,14 +156392,19 @@
156392 for(pX=pSub; pX; pX=pX->pPrior) {
156393 Expr *pY = pX->pEList->a[j].pExpr;
156394 if( pY->op==TK_NULL ) continue;
156395 pY->op = TK_NULL;
156396 ExprClearProperty(pY, EP_Skip|EP_Unlikely);
 
156397 nChng++;
156398 }
156399 }
156400 if( nChng ){
156401 /* If there were any changes, mark the SELECT as modified. This is
156402 ** to let isSelfJoinView() know not to allow another reference to this
156403 ** view to use the existing materialization. */
156404 pSub->selFlags |= SF_PushDown;
156405 }
156406 return nChng;
156407 }
156408
156409
156410 /*
@@ -156447,10 +157378,11 @@
157378 pX->zEName = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
157379 pX->fg.eEName = ENAME_NAME;
157380 }else{
157381 pX->zEName = sqlite3DbStrDup(db, zName);
157382 pX->fg.eEName = ENAME_NAME;
157383 if( IN_RENAME_OBJECT ) pX->fg.bStarName = 1;
157384 }
157385 }
157386 }
157387 if( !tableSeen ){
157388 if( zTName ){
@@ -156816,10 +157748,13 @@
157748 assert( pAggInfo->iFirstReg>0 );
157749 assert( pParse->db->pParse==pParse );
157750 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
157751 if( nReg==0 ) return;
157752 if( pParse->nErr ) return;
157753 if( pAggInfo->nFunc ){
157754 sqlite3MayAbort(pParse);
157755 }
157756 sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->iFirstReg,
157757 pAggInfo->iFirstReg+nReg-1);
157758 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
157759 if( pFunc->iDistinct>=0 ){
157760 Expr *pE = pFunc->pFExpr;
@@ -157826,11 +158761,19 @@
158761 sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric,
158762 p->pOrderBy);
158763 testcase( pParse->earlyCleanup );
158764 p->pOrderBy = 0;
158765 }
158766 /* Do not ignore DISTINCT for an EXISTS subquery with an OFFSET clause.
158767 ** In this case the OFFSET must be applied after duplicates are discarded,
158768 ** so the DISTINCT is required. */
158769 if( pDest->eDest!=SRT_Exists
158770 || (ALWAYS(p->pLimit!=0) && p->pLimit->pRight==0)
158771 /* ^^^^^^-- because tag-202611101908 and SRT_Exists set nowhere else */
158772 ){
158773 p->selFlags &= ~(u32)SF_Distinct;
158774 }
158775 }
158776 sqlite3SelectPrep(pParse, p, 0);
158777 if( pParse->nErr ){
158778 goto select_end;
158779 }
@@ -157949,12 +158892,17 @@
158892 unsetJoinExpr(p->pWhere, pI2->iCursor, 1);
158893 }
158894 }
158895 }
158896 for(j=pTabList->nSrc-1; j>=0; j--){
158897 SrcItem *pI2 = &pTabList->a[j];
158898 pI2->fg.jointype &= ~JT_LTORJ;
158899 if( (pI2->fg.jointype & (JT_LEFT|JT_RIGHT))==0 ){
158900 clearOuterOnExpr(p->pWhere, pI2->iCursor);
158901 unwrapIfNullRow(pParse, p, pI2->iCursor);
158902 }
158903 if( pI2->fg.jointype & JT_RIGHT ) break;
158904 }
158905 }
158906 }
158907
158908 /* No further action if this term of the FROM clause is not a subquery */
@@ -158618,11 +159566,11 @@
159566 pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
159567 pAggInfo->pGroupBy = pGroupBy;
159568 sqlite3ExprAnalyzeAggList(&sNC, pEList);
159569 sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
159570 if( pHaving ){
159571 if( pGroupBy && OptimizationEnabled(db, SQLITE_HavingToWhere) ){
159572 assert( pWhere==p->pWhere );
159573 assert( pHaving==p->pHaving );
159574 assert( pGroupBy==p->pGroupBy );
159575 havingToWhere(pParse, p);
159576 pWhere = p->pWhere;
@@ -159529,15 +160477,19 @@
160477
160478 /* If the trigger name was unqualified, and the table is a temp table,
160479 ** then set iDb to 1 to create the trigger in the temporary database.
160480 ** If sqlite3SrcListLookup() returns 0, indicating the table does not
160481 ** exist, the error is caught by the block below.
160482 **
160483 ** Do not do this if ALTER TABLE is reparsing an existing trigger. In
160484 ** that case iDb is already set correctly. */
160485 if( !IN_RENAME_OBJECT ){
160486 pTab = sqlite3SrcListLookup(pParse, pTableName);
160487 if( db->init.busy==0 && pName2->n==0 && pTab
160488 && pTab->pSchema==db->aDb[1].pSchema ){
160489 iDb = 1;
160490 }
160491 }
160492
160493 /* Ensure the table name matches database name and that the table exists */
160494 if( db->mallocFailed ) goto trigger_cleanup;
160495 assert( pTableName->nSrc==1 );
@@ -159564,11 +160516,12 @@
160516 zName = sqlite3NameFromToken(db, pName);
160517 if( zName==0 ){
160518 assert( db->mallocFailed );
160519 goto trigger_cleanup;
160520 }
160521 if( sqlite3CheckObjectName(pParse, zName, "trigger", pTab->zName,
160522 db->aDb[iDb].zDbSName) ){
160523 goto trigger_cleanup;
160524 }
160525 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
160526 if( !IN_RENAME_OBJECT ){
160527 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
@@ -159706,10 +160659,11 @@
160659 if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
160660 zName = pTrig->zName;
160661 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
160662 assert( iDb>=00 && iDb<db->nDb );
160663 pTrig->step_list = pStepList;
160664 pTrig->nSelect = pParse->nSelect;
160665 for(n=0; pStepList; n++){
160666 pStepList->pTrig = pTrig;
160667 pStepList = pStepList->pNext;
160668 }
160669 if( n>pParse->db->aLimit[SQLITE_LIMIT_TRIGGER_STEPS] ){
@@ -159739,16 +160693,19 @@
160693 Vdbe *v;
160694 char *z;
160695
160696 /* If this is a new CREATE TABLE statement, and if shadow tables
160697 ** are read-only, and the trigger makes a change to a shadow table,
160698 ** then raise an error - do not allow the trigger to be created.
160699 ** The targets of a TEMP trigger may be in any schema, so check all
160700 ** of them in that case. */
160701 if( sqlite3ReadOnlyShadowTables(db) ){
160702 TriggerStep *pStep;
160703 const char *zDb = iDb==1 ? 0 : db->aDb[iDb].zDbSName;
160704 for(pStep=pTrig->step_list; pStep; pStep=pStep->pNext){
160705 if( pStep->pSrc!=0
160706 && sqlite3ShadowTableName(db, pStep->pSrc->a[0].zName, zDb)
160707 ){
160708 sqlite3ErrorMsg(pParse,
160709 "trigger \"%s\" may not write to shadow table \"%s\"",
160710 pTrig->zName, pStep->pSrc->a[0].zName);
160711 goto triggerfinish_cleanup;
@@ -160656,10 +161613,11 @@
161613 memset(&sNC, 0, sizeof(sNC));
161614 sNC.pParse = &sSubParse;
161615 sSubParse.pTriggerTab = pTab;
161616 sSubParse.pToplevel = pTop;
161617 sSubParse.pTrigCoded = pTrigger;
161618 sSubParse.nSelect = pTrigger->nSelect;
161619 sSubParse.zAuthContext = pTrigger->zName;
161620 sSubParse.eTriggerOp = pTrigger->op;
161621 sSubParse.nQueryLoop = pParse->nQueryLoop;
161622 sSubParse.prepFlags = pParse->prepFlags;
161623 sSubParse.oldmask = 0;
@@ -164628,10 +165586,11 @@
165586 struct InLoop {
165587 int iCur; /* The VDBE cursor used by this IN operator */
165588 int addrInTop; /* Top of the IN loop */
165589 int iBase; /* Base register of multi-key index record */
165590 int nPrefix; /* Number of prior entries in the key */
165591 int lblNull; /* Jump here if RHS value is NULL */
165592 u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
165593 } *aInLoop; /* Information about each nested IN operator */
165594 } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
165595 Index *pCoveringIdx; /* Possible covering index for WHERE_MULTI_OR */
165596 } u;
@@ -165937,10 +166896,11 @@
166896 sqlite3WhereRealloc(pTerm->pWC->pWInfo,
166897 pLevel->u.in.aInLoop,
166898 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
166899 pIn = pLevel->u.in.aInLoop;
166900 if( pIn ){
166901 int lblNull = sqlite3VdbeMakeLabel(pParse);
166902 int iMap = 0; /* Index in aiMap[] */
166903 pIn += i;
166904 for(i=iEq; i<pLoop->nLTerm; i++){
166905 if( pLoop->aLTerm[i]->pExpr==pX ){
166906 int iOut = iTarget + i - iEq;
@@ -165948,13 +166908,14 @@
166908 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
166909 }else{
166910 int iCol = aiMap ? aiMap[iMap++] : 0;
166911 pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
166912 }
166913 sqlite3VdbeAddOp2(v, OP_IsNull, iOut, lblNull); VdbeCoverage(v);
166914 if( i==iEq ){
166915 pIn->iCur = iTab;
166916 pIn->lblNull = lblNull;
166917 pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
166918 if( iEq>0 ){
166919 pIn->iBase = iTarget - i;
166920 pIn->nPrefix = i;
166921 }else{
@@ -166924,10 +167885,11 @@
167885 */
167886 int iReg; /* P3 Value for OP_VFilter */
167887 int addrNotFound;
167888 int nConstraint = pLoop->nLTerm;
167889
167890 sqlite3MayAbort(pParse);
167891 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
167892 addrNotFound = pLevel->addrBrk;
167893 for(j=0; j<nConstraint; j++){
167894 int iTarget = iReg+j+2;
167895 pTerm = pLoop->aLTerm[j];
@@ -167297,10 +168259,11 @@
168259 ** index entries for which the column is null and for those for which
168260 ** it is not. For an ASC sort, the non-NULL entries are scanned first.
168261 ** For DESC, NULL entries are scanned first.
168262 */
168263 if( (pLoop->wsFlags & (WHERE_TOP_LIMIT|WHERE_BTM_LIMIT))==0
168264 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
168265 && (pLoop->wsFlags & WHERE_BIGNULL_SORT)!=0
168266 ){
168267 assert( bSeekPastNull==0 && nExtraReg==0 && nBtm==0 && nTop==0 );
168268 assert( pRangeEnd==0 && pRangeStart==0 );
168269 testcase( pLoop->nSkip>0 );
@@ -168512,10 +169475,47 @@
169475 assert( op!=TK_GE || c==WO_GE );
169476 assert( op!=TK_IS || c==WO_IS );
169477 return c;
169478 }
169479
169480 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
169481 /*
169482 ** The input is an N-byte GLOB or LIKE pattern prefix
169483 ** with the following guarantees:
169484 **
169485 ** (1) It contains no wildcards.
169486 ** (2) z[N]==0
169487 ** (3) N>0
169488 ** (4) bHasSpace is true if and only if the original complete LIKE/GLOB
169489 ** pattern contained wildcards and/or escapes. (It is usually true,
169490 ** therefore). bHasSpace also means that there is at least one byte
169491 ** of overrun space at z[N+1] that this routine may use.
169492 **
169493 ** This routine checks to see if the input will be a prefix to
169494 ** any number (integer or floating-point) that SQLite might generate
169495 ** from a MEM_Int or MEM_Real, including "Inf" and "-Inf".
169496 **
169497 ** Return true if the input is a possible numeric prefix and
169498 ** false if the input cannot possibly be a numeric prefix.
169499 */
169500 static SQLITE_NOINLINE int isNumericPrefix(char *z, int N, int bHasSpace){
169501 int x;
169502 double rDummy;
169503 assert( N>0 );
169504 if( sqlite3AtoF(z, &rDummy)>0 ) return 1; /* Boundary is itself a number */
169505 if( bHasSpace ){
169506 z[N] = '0';
169507 z[N+1] = 0;
169508 x = sqlite3AtoF(z, &rDummy); /* Prefix like "1.0e" or "-" */
169509 z[N] = 0;
169510 if( x>0 ) return 1;
169511 }
169512 if( z[0]=='-' ){ z++; N--; }
169513 if( N>0 && N<=3 && sqlite3StrNICmp(z,"inf",N)==0 ) return 1;
169514 return 0;
169515 }
169516 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
169517
169518 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
169519 /*
169520 ** Check to see if the given expression is a LIKE or GLOB operator that
169521 ** can be optimized using inequality constraints. Return TRUE if it is
@@ -168567,11 +169567,11 @@
169567 }
169568 sqlite3VdbeReprepareOnBind(pParse->pVdbe, iCol, 0);
169569 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
169570 }else if( op==TK_STRING ){
169571 assert( !ExprHasProperty(pRight, EP_IntValue) );
169572 z = (u8*)pRight->u.zToken;
169573 }
169574 if( z ){
169575 /* Count the number of prefix bytes prior to the first wildcard,
169576 ** U+fffd character, or malformed utf-8. If the underlying database
169577 ** has a UTF16LE encoding, then only consider ASCII characters. Note that
@@ -168583,27 +169583,40 @@
169583 cnt++;
169584 if( c==wc[3] && z[cnt]>0 && z[cnt]<0x80 ){
169585 cnt++;
169586 }else if( c>=0x80 ){
169587 const u8 *z2 = z+cnt-1;
169588 u32 u;
169589 if( c==0xff /* (1) */
169590 || (u = sqlite3Utf8Read(&z2))>=0xfffd /* (2) */
169591 || u==0x7ff /* (3) */
169592 || ENC(db)==SQLITE_UTF16LE /* (4) */
169593 ){
169594 /* Do not accept this character as part of the prefix because
169595 ** (1) 0xff is not part of any valid UTF-8 character and the
169596 ** 0xff causes difficult when incrementing to the upper bound
169597 ** (2) 0xfffd is not a valid UTF-8 character and values greater
169598 ** start getting into the surrogate pairs in UTF16BE.
169599 ** (3) When incrementing this code point to the upper bound,
169600 ** that would require adding an extra byte to the UTF-8
169601 ** (4) UTF16LE does not compare in sorted order. Only
169602 ** UTF16BE and UTF8 have that property.
169603 */
169604 cnt--;
169605 break;
169606 }else{
169607 cnt = (int)(z2-z);
169608 }
169609 }
169610 }
169611
169612 /* The optimization is possible only if either (1a) the pattern does not
169613 ** begin with a wildcard and if (1b) the non-wildcard prefix does not end
169614 ** with an (illegal) 0xff character, or (2) the pattern does not consist of
169615 ** a single escape character. The (1b) condition is necessary so
169616 ** that we can increment the prefix key to find an upper bound for the
169617 ** range search. The (2) is because the caller assumes that the pattern
169618 ** consists of at least one character after all escapes have been
169619 ** removed. */
169620 if( (cnt>1 || (cnt>0 && z[0]!=wc[3])) && ALWAYS(255!=(u8)z[cnt-1]) ){
169621 Expr *pPrefix;
169622
@@ -168625,41 +169638,41 @@
169638 zNew[iTo] = 0;
169639 assert( iTo>0 );
169640
169641 /* If the LHS is not an ordinary column with TEXT affinity, then the
169642 ** pattern prefix boundaries (both the start and end boundaries) must
169643 ** not look like a number or the prefix of a number. Otherwise the
169644 ** pattern might might match against a number, which means this
169645 ** optimization will not work. If either the start or end boundary
169646 ** strings has any possibility of matching against a text rendering
169647 ** of a MEM_Int or MEM_Real, then we must return 0.
169648 **
169649 ** Getting this right has been a persistent source of bugs in the
169650 ** LIKE optimization. See, for example:
169651 ** 2018-09-10 https://sqlite.org/src/info/c94369cae9b561b1
169652 ** 2019-05-02 https://sqlite.org/src/info/b043a54c3de54b28
169653 ** 2019-06-10 https://sqlite.org/src/info/fd76310a5e843e07
169654 ** 2019-06-14 https://sqlite.org/src/info/ce8717f0885af975
169655 ** 2019-09-03 https://sqlite.org/src/info/0f0428096f17252a
169656 ** 2026-10-28 https://sqlite.org/bugs/info/e85ab73aa1483325
169657 */
169658 if( pLeft->op!=TK_COLUMN
169659 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
169660 || (ALWAYS( ExprUseYTab(pLeft) )
169661 && ALWAYS(pLeft->y.pTab)
169662 && IsVirtual(pLeft->y.pTab)) /* Might be numeric */
169663 ){
169664 int bHasSpace = iTo < (int)strlen((const char*)z);
169665 int x;
169666 assert( zNew[iTo]==0 );
169667 x = isNumericPrefix(zNew, iTo, bHasSpace); /* start boundary */
169668 if( x==0 ){
169669 zNew[iTo-1]++;
169670 x = isNumericPrefix(zNew, iTo, bHasSpace); /* end boundary */
169671 zNew[iTo-1]--;
169672 }
169673 if( x!=0 ){
 
 
 
 
169674 sqlite3ExprDelete(db, pPrefix);
169675 sqlite3ValueFree(pVal);
169676 return 0;
169677 }
169678 }
@@ -168920,11 +169933,17 @@
169933 Expr *pNew; /* New virtual expression */
169934 int op; /* Operator for the combined expression */
169935 int idxNew; /* Index in pWC of the next virtual term */
169936 Expr *pA, *pB; /* Expressions associated with pOne and pTwo */
169937
169938 if( (pOne->wtFlags | pTwo->wtFlags) & (TERM_VNULL|TERM_LIKEOPT) ){
169939 testcase( pOne->wtFlags & TERM_VNULL );
169940 testcase( pOne->wtFlags & TERM_LIKEOPT );
169941 testcase( pTwo->wtFlags & TERM_VNULL );
169942 testcase( pTwo->wtFlags & TERM_LIKEOPT );
169943 return;
169944 }
169945 if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
169946 if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
169947 if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
169948 && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
169949 pA = pOne->pExpr;
@@ -169881,11 +170900,11 @@
170900 ** used by each such virtual term is pExpr (the full vector IN(...)
170901 ** expression). The WhereTerm.u.x.iField variable identifies the index within
170902 ** the vector on the LHS that the virtual term represents.
170903 **
170904 ** This only works if the RHS is a simple SELECT (not a compound) that does
170905 ** not use window functions or a LIMIT clause.
170906 */
170907 else if( pExpr->op==TK_IN
170908 && pTerm->u.x.iField==0
170909 && pExpr->pLeft->op==TK_VECTOR
170910 && ALWAYS( ExprUseXSelect(pExpr) )
@@ -169892,10 +170911,12 @@
170911 && (pExpr->x.pSelect->pPrior==0 || (pExpr->x.pSelect->selFlags & SF_Values))
170912 #ifndef SQLITE_OMIT_WINDOWFUNC
170913 && pExpr->x.pSelect->pWin==0
170914 #endif
170915 && (pExpr->x.pSelect->selFlags & SF_MinMaxAgg)==0
170916 && pExpr->x.pSelect->pLimit==0
170917 /* ^-- See bug 2026-11-04T00:59:22Z */
170918 && pWC->op==TK_AND
170919 && pExpr->x.pSelect->pEList->nExpr <= UMXV(pTerm->nChild)
170920 /* ^-- See bug 2026-06-04T10:00:49Z */
170921 ){
170922 int i;
@@ -170574,18 +171595,20 @@
171595 return 0;
171596 }
171597 }
171598 if( pSet->n<N_OR_COST ){
171599 p = &pSet->a[pSet->n++];
 
171600 }else{
171601 /* The set is full. Replace the most expensive entry, but only if the
171602 ** new entry is less expensive than it. */
171603 p = pSet->a;
171604 for(i=1; i<pSet->n; i++){
171605 if( p->rRun<pSet->a[i].rRun ) p = pSet->a + i;
171606 }
171607 if( p->rRun<=rRun ) return 0;
171608 }
171609 p->nOut = nOut;
171610 whereOrInsert_done:
171611 p->prereq = prereq;
171612 p->rRun = rRun;
171613 if( p->nOut>nOut ) p->nOut = nOut;
171614 return 1;
@@ -170697,10 +171720,33 @@
171720 CollSeq *pRet = sqlite3ExprCompareCollSeq(pParse, pX);
171721 return pRet ? pRet->zName : sqlite3StrBINARY;
171722 }
171723 return 0;
171724 }
171725
171726 /*
171727 ** pTerm is a WO_EQUIV term "X=Y" that whereScanNext() might use to add
171728 ** Y to the equivalence class of X. Return true if any of the following
171729 ** are true:
171730 **
171731 ** * Parameter zCollName is NULL,
171732 ** * The collation sequence of pTerm is BINARY, or
171733 ** * The collation sequence of pTerm is zCollName.
171734 **
171735 ** Otherwise return false.
171736 */
171737 static int whereScanEquivCollOk(
171738 Parse *pParse,
171739 WhereTerm *pTerm,
171740 const char *zCollName
171741 ){
171742 CollSeq *pColl;
171743 if( zCollName==0 ) return 1;
171744 pColl = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr);
171745 if( sqlite3IsBinary(pColl) ) return 1;
171746 return sqlite3StrICmp(pColl->zName, zCollName)==0;
171747 }
171748
171749 /*
171750 ** Advance to the next WhereTerm that matches according to the criteria
171751 ** established when the pScan object was initialized by whereScanInit().
171752 ** Return NULL if there are no more matching WhereTerms.
@@ -170731,10 +171777,11 @@
171777 && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_OuterON))
171778 ){
171779 if( (pTerm->eOperator & WO_EQUIV)!=0
171780 && pScan->nEquiv<ArraySize(pScan->aiCur)
171781 && (pX = whereRightSubexprIsColumn(pTerm->pExpr))!=0
171782 && whereScanEquivCollOk(pWC->pWInfo->pParse, pTerm, pScan->zCollName)
171783 ){
171784 int j;
171785 for(j=0; j<pScan->nEquiv; j++){
171786 if( pScan->aiCur[j]==pX->iTable
171787 && pScan->aiColumn[j]==pX->iColumn ){
@@ -170761,11 +171808,23 @@
171808 CollSeq *pColl;
171809 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
171810 continue;
171811 }
171812 assert(pX->pLeft);
171813 if( pX->pLeft->op==TK_VECTOR ){
171814 /* A vector inequality such as (a,b)>(?,?). This term
171815 ** constrains only the first field, so the collation is
171816 ** that of the first pair of fields only. */
171817 Expr *pL = sqlite3VectorFieldSubexpr(pX->pLeft, 0);
171818 Expr *pR = sqlite3VectorFieldSubexpr(pX->pRight, 0);
171819 assert( pTerm->u.x.iField==0 );
171820 assert( pX->op>=TK_GT && pX->op<=TK_GE );
171821 if( ExprHasProperty(pX, EP_Commuted) ) SWAP(Expr*, pL, pR);
171822 pColl = sqlite3BinaryCompareCollSeq(pParse, pL, pR);
171823 }else{
171824 pColl = sqlite3ExprCompareCollSeq(pParse, pX);
171825 }
171826 zCollName = pColl ? pColl->zName : sqlite3StrBINARY;
171827 }
171828
171829 if( sqlite3StrICmp(zCollName, pScan->zCollName) ){
171830 continue;
@@ -171360,11 +172419,13 @@
172419 int mxBitCol; /* Maximum column in pSrc->colUsed */
172420 CollSeq *pColl; /* Collating sequence to on a column */
172421 WhereLoop *pLoop; /* The Loop object */
172422 char *zNotUsed; /* Extra space on the end of pIdx */
172423 Bitmask idxCols; /* Bitmap of columns used for indexing */
172424 Bitmask pkCols; /* PK cols whose key collation keeps them unique */
172425 Bitmask extraCols; /* Bitmap of additional columns */
172426 int bHighCols; /* True to add all columns >= BMS-1 */
172427 u8 sentWarning = 0; /* True if a warning has been issued */
172428 u8 useBloomFilter = 1; /* True to also add a Bloom filter */
172429 Expr *pPartial = 0; /* Partial Index Expression */
172430 int iContinue = 0; /* Jump here to skip excluded rows */
172431 SrcList *pTabList; /* The complete FROM clause */
@@ -171388,10 +172449,11 @@
172449 pSrc = &pTabList->a[pLevel->iFrom];
172450 pTable = pSrc->pSTab;
172451 pWCEnd = &pWC->a[pWC->nTerm];
172452 pLoop = pLevel->pWLoop;
172453 idxCols = 0;
172454 pkCols = 0;
172455 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
172456 Expr *pExpr = pTerm->pExpr;
172457 /* Make the automatic index a partial index if there are terms in the
172458 ** WHERE clause (or the ON clause of a LEFT join) that constrain which
172459 ** rows of the target table (pSrc) that can be used. */
@@ -171419,10 +172481,29 @@
172481 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
172482 goto end_auto_index_create;
172483 }
172484 pLoop->aLTerm[nKeyCol++] = pTerm;
172485 idxCols |= cMask;
172486
172487 /* For a WITHOUT ROWID table, all PRIMARY KEY columns must be
172488 ** present in the automatic index, sorted with either BINARY or
172489 ** the same collation used by the PK index itself, to guarantee each
172490 ** entry is unique. If the current field matches that criteria,
172491 ** set the corresponding bit in pkCols. */
172492 if( !HasRowid(pTable) && iCol<BMS-1
172493 && (pTable->aCol[iCol].colFlags & COLFLAG_PRIMKEY)
172494 ){
172495 Index *pPk = sqlite3PrimaryKeyIndex(pTable);
172496 CollSeq *pX = sqlite3ExprCompareCollSeq(pParse, pExpr);
172497 int iPk = sqlite3TableColumnToIndex(pPk, iCol);
172498 assert( iPk>=0 && iPk<pPk->nKeyCol );
172499 if( sqlite3IsBinary(pX)
172500 || sqlite3StrICmp(pPk->azColl[iPk], pX->zName)==0
172501 ){
172502 pkCols |= cMask;
172503 }
172504 }
172505 }
172506 }
172507 }
172508 assert( nKeyCol>0 || pParse->db->mallocFailed );
172509 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
@@ -171440,35 +172521,38 @@
172521 if( IsView(pTable) ){
172522 extraCols = ALLBITS & ~idxCols;
172523 }else{
172524 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
172525 }
172526 bHighCols = (pSrc->colUsed & MASKBIT(BMS-1))!=0;
172527 if( !HasRowid(pTable) ){
172528 /* For WITHOUT ROWID tables, ensure that all PRIMARY KEY columns are
172529 ** either in the pkCols mask or in the extraCols mask. A column that
172530 ** is already an index key but is not in pkCols is added a second
172531 ** time, using the BINARY collating sequence. */
172532 for(i=0; i<pTable->nCol; i++){
172533 if( (pTable->aCol[i].colFlags & COLFLAG_PRIMKEY)==0 ) continue;
172534 if( i>=BMS-1 ){
172535 bHighCols = 1;
172536 break;
172537 }
172538 if( pkCols & MASKBIT(i) ) continue;
172539 extraCols |= MASKBIT(i);
172540 }
172541 }
172542 mxBitCol = MIN(BMS-1,pTable->nCol);
172543 testcase( pTable->nCol==BMS-1 );
172544 testcase( pTable->nCol==BMS-2 );
172545 for(i=0; i<mxBitCol; i++){
172546 if( extraCols & MASKBIT(i) ) nKeyCol++;
172547 }
172548 if( bHighCols ){
172549 nKeyCol += pTable->nCol - BMS + 1;
172550 }
172551
172552 /* Construct the Index object to describe this index */
172553 assert( nKeyCol <= pTable->nCol + MIN(pTable->nCol, BMS) );
172554 /* ^-- This guarantees that the number of index columns will fit in the u16 */
172555 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+HasRowid(pTable),
172556 0, &zNotUsed);
172557 if( pIdx==0 ) goto end_auto_index_create;
172558 pLoop->u.btree.pIndex = pIdx;
@@ -171488,11 +172572,11 @@
172572 if( (idxCols & cMask)==0 ){
172573 Expr *pX = pTerm->pExpr;
172574 idxCols |= cMask;
172575 pIdx->aiColumn[n] = pTerm->u.x.leftColumn;
172576 pColl = sqlite3ExprCompareCollSeq(pParse, pX);
172577 testcase( pColl==0 && pParse->nErr==0 ); /* TH3 collate01.810 */
172578 if( !sqlite3IsBinary(pColl) ){
172579 /* Disallow the use of a Bloom filter if any non-BINARY collating
172580 ** sequence is involved. tag-202607231411 */
172581 useBloomFilter = 0;
172582 }
@@ -171510,11 +172594,11 @@
172594 pIdx->aiColumn[n] = i;
172595 pIdx->azColl[n] = sqlite3StrBINARY;
172596 n++;
172597 }
172598 }
172599 if( bHighCols ){
172600 for(i=BMS-1; i<pTable->nCol; i++){
172601 pIdx->aiColumn[n] = i;
172602 pIdx->azColl[n] = sqlite3StrBINARY;
172603 n++;
172604 }
@@ -174113,13 +175197,43 @@
175197 */
175198 typedef struct CoveringIndexCheck CoveringIndexCheck;
175199 struct CoveringIndexCheck {
175200 Index *pIdx; /* The index */
175201 int iTabCur; /* Cursor number for the corresponding table */
175202 WhereClause *pWC; /* Ignore terms of this WHERE implied by pIdx, or NULL */
175203 u8 bExpr; /* Uses an indexed expression */
175204 u8 bUnidx; /* Uses an unindexed column not within an indexed expr */
175205 };
175206
175207 /*
175208 ** Return true if pExpr is a term of the WHERE clause pCk->pWC (not merely
175209 ** a copy of such a term) and is identical to one of the AND-connected
175210 ** terms of the WHERE clause of partial index pCk->pIdx. Such a term is
175211 ** never evaluated when pCk->pIdx drives the loop, because the
175212 ** whereApplyPartialIndexConstraints() routine marks it as already coded.
175213 ** Hence any columns used by the term do not need to be in the index.
175214 */
175215 static int whereTermImpliedByPartialIndex(
175216 CoveringIndexCheck *pCk,
175217 const Expr *pExpr
175218 ){
175219 WhereClause *pWC = pCk->pWC;
175220 Expr *pPart;
175221 int i;
175222 for(i=0; i<pWC->nTerm; i++){
175223 if( pWC->a[i].pExpr==pExpr ) break;
175224 }
175225 if( i>=pWC->nTerm ) return 0;
175226 pPart = pCk->pIdx->pPartIdxWhere;
175227 while( pPart->op==TK_AND ){
175228 if( sqlite3ExprCompare(0, pExpr, pPart->pRight, pCk->iTabCur)==0 ){
175229 return 1;
175230 }
175231 pPart = pPart->pLeft;
175232 }
175233 return sqlite3ExprCompare(0, pExpr, pPart, pCk->iTabCur)==0;
175234 }
175235
175236 /*
175237 ** Information passed in is pWalk->u.pCovIdxCk. Call it pCk.
175238 **
175239 ** If the Expr node references the table with cursor pCk->iTabCur, then
@@ -174143,10 +175257,13 @@
175257 u16 nColumn; /* Number of columns in the index */
175258 CoveringIndexCheck *pCk; /* Info about this search */
175259
175260 pCk = pWalk->u.pCovIdxCk;
175261 pIdx = pCk->pIdx;
175262 if( pCk->pWC && whereTermImpliedByPartialIndex(pCk, pExpr) ){
175263 return WRC_Prune;
175264 }
175265 if( (pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN) ){
175266 /* if( pExpr->iColumn<(BMS-1) && pIdx->bHasExpr==0 ) return WRC_Continue;*/
175267 if( pExpr->iTable!=pCk->iTabCur ) return WRC_Continue;
175268 pIdx = pWalk->u.pCovIdxCk->pIdx;
175269 aiColumn = pIdx->aiColumn;
@@ -174169,10 +175286,16 @@
175286 ** pIdx is an index that covers all of the low-number columns used by
175287 ** pWInfo->pSelect (columns from 0 through 62) or an index that has
175288 ** expressions terms. Hence, we cannot determine whether or not it is
175289 ** a covering index by using the colUsed bitmasks. We have to do a search
175290 ** to see if the index is covering. This routine does that search.
175291 **
175292 ** If pWC is not NULL, then pIdx is a partial index and terms of the
175293 ** WHERE clause pWC that are implied by the WHERE clause of pIdx are
175294 ** ignored, as they will never be evaluated when pIdx drives the loop.
175295 ** In this case pIdx might not cover all low-numbered columns used by
175296 ** pWInfo->pSelect.
175297 **
175298 ** The return value is one of these:
175299 **
175300 ** 0 The index is definitely not a covering index
175301 **
@@ -174189,21 +175312,22 @@
175312 ** returned can lead to incorrect bytecode and assertion faults.
175313 */
175314 static SQLITE_NOINLINE u32 whereIsCoveringIndex(
175315 WhereInfo *pWInfo, /* The WHERE clause context */
175316 Index *pIdx, /* Index that is being tested */
175317 int iTabCur, /* Cursor for the table being indexed */
175318 WhereClause *pWC /* Ignore terms implied by pIdx, or NULL */
175319 ){
175320 int i, rc;
175321 struct CoveringIndexCheck ck;
175322 Walker w;
175323 if( pWInfo->pSelect==0 ){
175324 /* We don't have access to the full query, so we cannot check to see
175325 ** if pIdx is covering. Assume it is not. */
175326 return 0;
175327 }
175328 if( pIdx->bHasExpr==0 && pWC==0 ){
175329 for(i=0; i<pIdx->nColumn; i++){
175330 if( pIdx->aiColumn[i]>=BMS-1 ) break;
175331 }
175332 if( i>=pIdx->nColumn ){
175333 /* pIdx does not index any columns greater than 62, but we know from
@@ -174212,10 +175336,11 @@
175336 return 0;
175337 }
175338 }
175339 ck.pIdx = pIdx;
175340 ck.iTabCur = iTabCur;
175341 ck.pWC = pWC;
175342 ck.bExpr = 0;
175343 ck.bUnidx = 0;
175344 memset(&w, 0, sizeof(w));
175345 w.xExprCallback = whereIsCoveringIndexWalkCallback;
175346 w.xSelectCallback = sqlite3SelectWalkNoop;
@@ -174563,10 +175688,11 @@
175688 rc = whereLoopInsert(pBuilder, pNew);
175689 pNew->nOut = rSize;
175690 if( rc ) break;
175691 }else{
175692 Bitmask m;
175693 WhereClause *pPartWC = 0; /* WHERE terms that pProbe might imply */
175694 if( pProbe->isCovering ){
175695 m = 0;
175696 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
175697 }else{
175698 m = pSrc->colUsed & pProbe->colNotIdxed;
@@ -174574,14 +175700,34 @@
175700 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
175701 ){
175702 wherePartIdxExpr(
175703 pWInfo->pParse, pProbe, pProbe->pPartIdxWhere, &m, 0, 0
175704 );
175705 /* WHERE clause terms implied by the partial index WHERE clause
175706 ** are not evaluated, so the columns they use need not be in the
175707 ** index. But this does not apply to outer joins. See the
175708 ** call to whereApplyPartialIndexConstraints() in wherecode.c. */
175709 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==0
175710 && pWC==&pWInfo->sWC
175711 ){
175712 pPartWC = pWC;
175713 }
175714 }
175715 pNew->wsFlags = WHERE_INDEXED;
175716 if( m==0 ){
175717 if( HasRowid(pTab) || pWInfo->pSelect!=0 || sqlite3FaultSim(700) ){
175718 WHERETRACE(0x200,
175719 ("-> %s is a covering index according to bitmasks\n",
175720 pProbe->zName, m==0 ? "is" : "is not"));
175721 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
175722 }
175723 }else if( m==TOPBIT
175724 || (pProbe->bHasExpr && !pProbe->bHasVCol)
175725 || pPartWC
175726 ){
175727 u32 isCov = whereIsCoveringIndex(pWInfo, pProbe, pSrc->iCursor,
175728 pPartWC);
175729 if( isCov==0 ){
175730 WHERETRACE(0x200,
175731 ("-> %s is not a covering index"
175732 " according to whereIsCoveringIndex()\n", pProbe->zName));
175733 assert( m!=0 );
@@ -174597,17 +175743,10 @@
175743 WHERETRACE(0x200,
175744 ("-> %s might be a covering expression index"
175745 " according to whereIsCoveringIndex()\n", pProbe->zName));
175746 }
175747 }
 
 
 
 
 
 
 
175748 }
175749 }
175750
175751 /* Full scan via index */
175752 if( b
@@ -175445,21 +176584,19 @@
176584 ** long as the subquery ORDER BY does the same. But if the
176585 ** outer ORDER BY uses COLLATE, even a redundant COLLATE, the
176586 ** optimization is bypassed.
176587 **
176588 ** (2) The subquery ORDER BY terms must exactly match subquery result
176589 ** columns, and the collations used must match as well.
 
 
 
176590 **
176591 ** (3) The subquery and outer ORDER BY can be in opposite directions as
176592 ** long as the subquery is materialized. If the subquery is
176593 ** implemented as a co-routine, the sort orders must be in the same
176594 ** direction because there is no way to run a co-routine backwards.
176595 */
176596 static SQLITE_NOINLINE int wherePathMatchSubqueryOB(
176597 Parse *pParse, /* The parsing context */
176598 WhereLoop *pLoop, /* The nested loop term that is a subquery */
176599 int iLoop, /* Which level of the nested loop. 0==outermost */
176600 int iCur, /* Cursor used by the this loop */
176601 ExprList *pOrderBy, /* The ORDER BY clause on the whole query */
176602 Bitmask *pRevMask, /* When loops need to go in reverse order */
@@ -175475,18 +176612,20 @@
176612
176613 pSubOB = pLoop->u.btree.pOrderBy;
176614 assert( pSubOB!=0 );
176615 for(iOB=0; (MASKBIT(iOB) & *pOBSat)!=0; iOB++){}
176616 for(jSub=0; jSub<pSubOB->nExpr && iOB<pOrderBy->nExpr; jSub++, iOB++){
176617 struct ExprList_item *pItem = &pSubOB->a[jSub];
176618 if( pItem->u.x.iOrderByCol==0 ) break;
176619 pOBExpr = pOrderBy->a[iOB].pExpr;
176620 if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) break;
176621 if( pOBExpr->iTable!=iCur ) break;
176622 if( pOBExpr->iColumn!=pItem->u.x.iOrderByCol-1 ) break;
176623 if( 0==sqlite3ExprCollSeqMatch(pParse, pOBExpr, pItem->pExpr) ) break;
176624 if( (wctrlFlags & WHERE_GROUPBY)==0 ){
176625 u8 sfOB = pOrderBy->a[iOB].fg.sortFlags; /* sortFlags for iOB */
176626 u8 sfSub = pItem->fg.sortFlags; /* sortFlags for jSub */
176627 if( (sfSub & KEYINFO_ORDER_BIGNULL) != (sfOB & KEYINFO_ORDER_BIGNULL) ){
176628 break;
176629 }
176630 revIdx = sfSub & KEYINFO_ORDER_DESC;
176631 if( jSub>0 ){
@@ -175662,11 +176801,11 @@
176801
176802 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
176803 if( pLoop->wsFlags & WHERE_IPK ){
176804 if( pLoop->u.btree.pOrderBy
176805 && OptimizationEnabled(db, SQLITE_OrderBySubq)
176806 && wherePathMatchSubqueryOB(pWInfo->pParse, pLoop,iLoop,iCur,
176807 pOrderBy,pRevMask, &obSat, wctrlFlags)
176808 ){
176809 nColumn = 0;
176810 isOrderDistinct = 0;
176811 }else{
@@ -176158,11 +177297,11 @@
177297 for(pWLoop=pStart; pWLoop; pWLoop=pWLoop->pNextLoop){
177298 if( pWLoop->iTab<iFromIdx ) continue;
177299 if( pWLoop->iTab>iFromIdx ) break;
177300 if( pWLoop->rRun>mxRun ) mxRun = pWLoop->rRun;
177301 }
177302 if( mxRun<LOGEST_MAX ) mxRun++;
177303
177304 /* Increase the cost of table scans for dimension tables to be
177305 ** slightly more than the maximum cost of the fact table */
177306 for(pWLoop=pStart; pWLoop; pWLoop=pWLoop->pNextLoop){
177307 if( (pWLoop->maskSelf & mSeen)==0 ) continue;
@@ -178053,46 +179192,46 @@
179192 #endif
179193 if( (pLoop->wsFlags & WHERE_IN_ABLE)!=0 && pLevel->u.in.nIn>0 ){
179194 struct InLoop *pIn;
179195 int j;
179196 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
179197 /* The second and subsequent components of a row-value IN operator
179198 ** have eEndLoopOp==OP_Noop. Nothing to do for them. */
179199 if( pIn->eEndLoopOp==OP_Noop ) continue;
179200
179201 if( pIn->nPrefix ){
179202 int bEarlyOut = (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
179203 && (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0;
179204 if( pLevel->iLeftJoin ){
179205 /* For LEFT JOIN queries, cursor pIn->iCur might have been
179206 ** disabled by OP_NullRow. This occurs for WHERE clauses such
179207 ** as "a = ? AND b IN (...)", where the index is on (a, b).
179208 ** When the OP_IfNullRow jump is taken, the pIn->iBase register
179209 ** is NULLed out as a side effect. But as that register is not
179210 ** used when the jump is taken, the side-effect is harmless. */
179211 sqlite3VdbeAddOp3(v, OP_IfNullRow, pIn->iCur,
179212 sqlite3VdbeCurrentAddr(v) + 2 + bEarlyOut, pIn->iBase);
179213 VdbeCoverage(v);
179214 }
179215 if( bEarlyOut ){
179216 sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
179217 sqlite3VdbeCurrentAddr(v)+2,
179218 pIn->iBase, pIn->nPrefix);
179219 VdbeCoverage(v);
179220 }
179221 }
179222
179223 /* The OP_IsNull opcodes that test the components of the RHS of the
179224 ** IN operator jump directly here to the end-of-loop opcode. They
179225 ** must jump past the OP_IfNoHope above, because they may also jump
179226 ** past the OP_Affinity codes that prepare the key used by IfNoHope. */
179227 sqlite3VdbeResolveLabel(v, pIn->lblNull);
179228
179229 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
179230 VdbeCoverage(v);
179231 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
179232 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
179233 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
179234 }
179235 }
179236 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
179237 if( pLevel->pRJ ){
@@ -178140,10 +179279,20 @@
179279 if( pIn->eEndLoopOp!=OP_Noop ){
179280 sqlite3VdbeAddOp1(v, OP_NullRow, pIn->iCur);
179281 }
179282 }
179283 }
179284 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
179285 if( pLevel->addrLikeRep ){
179286 /* The LIKE loop counter is initialized after the == and IN terms
179287 ** are coded, so a NULL == term or an empty IN list can reach this
179288 ** point without ever setting it. Set it to 0 so that the
179289 ** OP_DecrJumpZero at the bottom of the loop falls through after
179290 ** the NULL row instead of reading an undefined register. */
179291 sqlite3VdbeAddOp2(v, OP_Integer, 0, (int)(pLevel->iLikeRepCntr>>1));
179292 }
179293 #endif
179294 if( pLevel->op==OP_Return ){
179295 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
179296 }else{
179297 sqlite3VdbeGoto(v, pLevel->addrFirst);
179298 }
@@ -179744,10 +180893,11 @@
180893 assert( pSelect->pSrc->a[0].fg.isSubquery );
180894 nEphExpr = pSelect->pSrc->a[0].u4.pSubq->pSelect->pEList->nExpr;
180895 pMWin = pSelect->pWin;
180896 v = sqlite3GetVdbe(pParse);
180897
180898 sqlite3MayAbort(pParse);
180899 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr);
180900 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
180901 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
180902 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
180903
@@ -180438,17 +181588,21 @@
181588 **
181589 ** If the sort-order for the ORDER BY term in the window is DESC, then the
181590 ** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is
181591 ** subtracted. And the comparison operator is inverted to - ">=" becomes "<=",
181592 ** ">" becomes "<", and so on. So, with DESC sort order, if the argument op
181593 ** is OP_Ge, the test is logically:
181594 **
181595 ** if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;
181596 **
181597 ** But in the DESC case, to avoid integer overflow in some cases, in practice:
181598 **
181599 ** if( csr1.peerVal <= csr2.peerVal + regVal ) goto lbl;
181600 **
181601 ** A special type of arithmetic is used such that if the peer-value that
181602 ** regVal is added to is not a numeric type (real or integer), then the
181603 ** result of the addition is a copy of that peer-value.
181604 */
181605 static void windowCodeRangeTest(
181606 WindowCodeArg *p,
181607 int op, /* OP_Ge, OP_Gt, or OP_Le */
181608 int csr1, /* Cursor number for cursor 1 */
@@ -180460,11 +181614,12 @@
181614 Vdbe *v = sqlite3GetVdbe(pParse);
181615 ExprList *pOrderBy = p->pMWin->pOrderBy; /* ORDER BY clause for window */
181616 int reg1 = sqlite3GetTempReg(pParse); /* Reg. for csr1.peerVal+regVal */
181617 int reg2 = sqlite3GetTempReg(pParse); /* Reg. for csr2.peerVal */
181618 int regString = ++pParse->nMem; /* Reg. for constant value '' */
181619 int regArith = reg1; /* Register to add regVal to */
181620 int bDesc = 0; /* True for DESC ORDER BY */
181621 int addrGe; /* Jump destination */
181622 int addrDone = sqlite3VdbeMakeLabel(pParse); /* Address past OP_Ge */
181623 CollSeq *pColl;
181624
181625 /* Read the peer-value from each cursor into a register */
@@ -180477,16 +181632,18 @@
181632 switch( op ){
181633 case OP_Ge: op = OP_Le; break;
181634 case OP_Gt: op = OP_Lt; break;
181635 default: assert( op==OP_Le ); op = OP_Ge; break;
181636 }
181637 bDesc = 1;
181638 regArith = reg2;
181639 }
181640
181641 VdbeModuleComment((v, "CodeRangeTest: if( R%d%s%s %s R%d%s%s ) goto lbl",
181642 reg1, (bDesc ? "" : " + R"), (bDesc ? "" : "regVal"),
181643 ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2,
181644 (bDesc ? " + R" : ""), (bDesc ? "regVal" : "")
181645 ));
181646
181647 /* If the BIGNULL flag is set for the ORDER BY, then it is required to
181648 ** consider NULL values to be larger than all other values, instead of
181649 ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this
@@ -180530,30 +181687,31 @@
181687 sqlite3VdbeAddOp2(v, OP_IsNull, reg2,
181688 (op==OP_Gt || op==OP_Ge) ? addrDone : lbl);
181689 VdbeCoverage(v);
181690 }
181691
181692 /* Register regArith currently contains a peer-value - csr1.peerVal for
181693 ** ASC, or csr2.peerVal for DESC. This block adds the numeric value in
181694 ** regVal to it. Or, if regArith is not numeric (it is a NULL, a text value
181695 ** or a blob), then leave it as it is. In pseudo-code, this is implemented
181696 ** as:
181697 **
181698 ** if( regArith>='' ) goto addrGe;
181699 ** regArith = regArith + regVal
181700 ** addrGe:
181701 **
181702 ** Since all strings and blobs are greater-than-or-equal-to an empty string,
181703 ** the addition is skipped for these, as required. If regArith is a NULL,
181704 ** then the arithmetic is performed, but since adding to NULL is always
181705 ** NULL anyway, this case is handled as required too. */
181706 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
181707 addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, regArith);
181708 VdbeCoverage(v);
181709 if( (op==OP_Ge && !bDesc) || (op==OP_Le && bDesc) ){
181710 sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
181711 }
181712 sqlite3VdbeAddOp3(v, OP_Add, regVal, regArith, regArith);
181713 sqlite3VdbeJumpHere(v, addrGe);
181714
181715 /* Compare registers reg2 and reg1, taking the jump if required. Note that
181716 ** control skips over this test if the BIGNULL flag is set and either
181717 ** reg1 or reg2 contain a NULL value. */
@@ -185801,13 +186959,12 @@
186959 {
186960 yylhsminor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0);
186961 if( yylhsminor.yy203 ){
186962 if( IN_RENAME_OBJECT ){
186963 sqlite3RenameTokenMap(pParse, yylhsminor.yy203->a[0].zName, &yymsp[-2].minor.yy0);
 
 
186964 }
186965 yylhsminor.yy203->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
186966 }
186967 }
186968 yymsp[-2].minor.yy203 = yylhsminor.yy203;
186969 break;
186970 case 123: /* xfullname ::= nm DOT nm AS nm */
@@ -185814,13 +186971,12 @@
186971 {
186972 yylhsminor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0);
186973 if( yylhsminor.yy203 ){
186974 if( IN_RENAME_OBJECT ){
186975 sqlite3RenameTokenMap(pParse, yylhsminor.yy203->a[0].zName, &yymsp[-2].minor.yy0);
 
 
186976 }
186977 yylhsminor.yy203->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
186978 }
186979 }
186980 yymsp[-4].minor.yy203 = yylhsminor.yy203;
186981 break;
186982 case 124: /* joinop ::= COMMA|JOIN */
@@ -186267,23 +187423,23 @@
187423 ** Except, do not apply this optimization if expr1 contains a function
187424 ** because that function might be an aggregate (we don't know yet whether
187425 ** it is or not) and if it is an aggregate, that could change the meaning
187426 ** of the whole query.
187427 */
187428 Expr *pB = sqlite3ExprInt32(pParse->db, yymsp[-3].minor.yy144!=0);
 
187429 if( !ExprHasProperty(yymsp[-4].minor.yy454, EP_HasFunc) ){
187430 if( pB ) pB->op2 = 1;
187431 sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy454);
187432 yymsp[-4].minor.yy454 = pB;
187433 }else{
187434 yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, yymsp[-3].minor.yy144 ? TK_OR : TK_AND, pB, yymsp[-4].minor.yy454);
187435 }
187436 }else{
187437 Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
187438 if( yymsp[-1].minor.yy14->nExpr==1
187439 && sqlite3ExprIsConstant(pParse,pRHS)
187440 && ExprHasProperty(pRHS, EP_Collate)==0
187441 && yymsp[-4].minor.yy454->op!=TK_VECTOR
187442 ){
187443 yymsp[-1].minor.yy14->a[0].pExpr = 0;
187444 sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
187445 pRHS = sqlite3PExpr(pParse, TK_UPLUS, pRHS, 0);
@@ -186328,10 +187484,13 @@
187484 break;
187485 case 226: /* expr ::= expr in_op nm dbnm paren_exprlist */
187486 {
187487 SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
187488 Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
187489 if( pSelect && IN_RENAME_OBJECT ){
187490 sqlite3RenameTokenMap(pParse, pSrc->a[0].zName, yymsp[-1].minor.yy0.z ? &yymsp[-1].minor.yy0 : &yymsp[-2].minor.yy0);
187491 }
187492 if( yymsp[0].minor.yy14 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy14);
187493 yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy454, 0);
187494 sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy454, pSelect);
187495 if( yymsp[-3].minor.yy144 ) yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy454, 0);
187496 }
@@ -190096,10 +191255,13 @@
191255 { SQLITE_DBCONFIG_STMT_SCANSTATUS, SQLITE_StmtScanStatus },
191256 { SQLITE_DBCONFIG_REVERSE_SCANORDER, SQLITE_ReverseOrder },
191257 { SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE, SQLITE_AttachCreate },
191258 { SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE, SQLITE_AttachWrite },
191259 { SQLITE_DBCONFIG_ENABLE_COMMENTS, SQLITE_Comments },
191260 #ifdef SQLITE_DEBUG
191261 { SQLITE_DBCONFIG_VDBE_TRACE, SQLITE_VdbeTrace },
191262 #endif
191263 };
191264 unsigned int i;
191265 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
191266 for(i=0; i<ArraySize(aFlagOp); i++){
191267 if( aFlagOp[i].op==op ){
@@ -190366,10 +191528,13 @@
191528 return SQLITE_OK;
191529 }
191530 if( !sqlite3SafetyCheckSickOrOk(db) ){
191531 return SQLITE_MISUSE_BKPT;
191532 }
191533 #if defined(SQLITE_DISPOSAL_NOTIFIER)
191534 SQLITE_DISPOSAL_NOTIFIER(1,db);
191535 #endif
191536 sqlite3_mutex_enter(db->mutex);
191537 if( db->mTrace & SQLITE_TRACE_CLOSE ){
191538 db->trace.xV2(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
191539 }
191540
@@ -193607,11 +194772,11 @@
194772 case SQLITE_TESTCTRL_BYTEORDER: {
194773 rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
194774 break;
194775 }
194776
194777 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, u64 N)
194778 **
194779 ** Enable or disable various optimizations for testing purposes. The
194780 ** argument N is a bitmask of optimizations to be disabled. For normal
194781 ** operation N should be 0. The idea is that a test program (like the
194782 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
@@ -193618,22 +194783,22 @@
194783 ** with various optimizations disabled to verify that the same answer
194784 ** is obtained in every case.
194785 */
194786 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
194787 sqlite3 *db = va_arg(ap, sqlite3*);
194788 db->dbOptFlags = va_arg(ap, u64);
194789 break;
194790 }
194791
194792 /* sqlite3_test_control(SQLITE_TESTCTRL_GETOPT, sqlite3 *db, u64 *N)
194793 **
194794 ** Write the current optimization settings into *N. A zero bit means that
194795 ** the optimization is on, and a 1 bit means that the optimization is off.
194796 */
194797 case SQLITE_TESTCTRL_GETOPT: {
194798 sqlite3 *db = va_arg(ap, sqlite3*);
194799 u64 *pN = va_arg(ap, u64*);
194800 *pN = db->dbOptFlags;
194801 break;
194802 }
194803
194804 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, onoff, xAlt);
@@ -193877,10 +195042,32 @@
195042 const char *z = va_arg(ap,const char*);
195043 double *pR = va_arg(ap,double*);
195044 rc = sqlite3AtoF(z,pR);
195045 break;
195046 }
195047
195048 /* sqlite3_test_control(SQLITE_TESTCTRL_ATOF, sqlite3 *db, int iDb)
195049 **
195050 ** Test access to the sqlite3ExpireStmtsUsingSchema() routine. All
195051 ** prepared statements associated with database connection db and that
195052 ** use schema iDb (0==main, 1==temp, etc.) are marked as expired.
195053 ** Or if iDb is exactly -1, then expire all prepared statements.
195054 **
195055 ** If iDb is out of range, this test-control is a harmless no-op.
195056 */
195057 case SQLITE_TESTCTRL_EXPIRE_STMTS: {
195058 sqlite3 *db = va_arg(ap,sqlite3*);
195059 int iDb = va_arg(ap,int);
195060 assert( db!=0 );
195061 if( iDb>=0 && iDb<db->nDb ){
195062 sqlite3ExpireStmtsUsingSchema(db, iDb, 0);
195063 }else if( iDb==(-1) ){
195064 sqlite3ExpirePreparedStatements(db, 0);
195065 }
195066 rc = SQLITE_OK;
195067 break;
195068 }
195069
195070 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
195071 /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
195072 **
195073 ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
@@ -195581,12 +196768,12 @@
196768 int nIndex; /* Size of aIndex[] */
196769 struct Fts3Index {
196770 int nPrefix; /* Prefix length (0 for main terms index) */
196771 Fts3Hash hPending; /* Pending terms table for this index */
196772 } *aIndex;
196773 sqlite_int64 nMaxPendingData; /* Max pending data before flush to disk */
196774 sqlite_int64 nPendingData; /* Current bytes of pending data */
196775 sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
196776 int iPrevLangid; /* Langid of recently inserted document */
196777 int bPrevDelete; /* True if last operation was a delete */
196778
196779 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
@@ -195901,10 +197088,13 @@
197088 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
197089 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
197090 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
197091 SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
197092 SQLITE_PRIVATE int sqlite3Fts3ReadInt(const char *z, int *pnOut);
197093 SQLITE_PRIVATE int sqlite3Fts3CreateHashFunction(sqlite3*, const char*, int, int, Fts3Hash*,
197094 void (*)(sqlite3_context*,int,sqlite3_value**)
197095 );
197096
197097 /* fts3_tokenizer.c */
197098 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
197099 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
197100 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
@@ -196573,10 +197763,11 @@
197763 if( p->zContentTbl==0 ){
197764 if( !zFunc ){
197765 zFunction = "";
197766 }else{
197767 zFree = zFunction = fts3QuoteId(zFunc);
197768 if( zFunction==0 ) *pRc = SQLITE_NOMEM;
197769 }
197770 fts3Appendf(pRc, &zRet, "docid");
197771 for(i=0; i<p->nColumn; i++){
197772 fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
197773 }
@@ -196629,10 +197820,11 @@
197820
197821 if( !zFunc ){
197822 zFunction = "";
197823 }else{
197824 zFree = zFunction = fts3QuoteId(zFunc);
197825 if( zFunction==0 ) *pRc = SQLITE_NOMEM;
197826 }
197827 fts3Appendf(pRc, &zRet, "?");
197828 for(i=0; i<p->nColumn; i++){
197829 fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
197830 }
@@ -199774,10 +200966,35 @@
200966 if( pHash->nRef<=0 ){
200967 sqlite3Fts3HashClear(&pHash->hash);
200968 sqlite3_free(pHash);
200969 }
200970 }
200971
200972 /*
200973 ** Register an SQL function that uses the tokenizer hash table pHash as its
200974 ** user-data pointer. The new function holds a reference to the hash table,
200975 ** which is released by hashDestroy() when the function is deleted or if
200976 ** this call fails.
200977 **
200978 ** The Fts3Hash object passed as the fifth argument must be the "hash" member
200979 ** of an Fts3HashWrapper object. Since it is the first member of that
200980 ** structure, the pointer may be cast to (Fts3HashWrapper*).
200981 */
200982 SQLITE_PRIVATE int sqlite3Fts3CreateHashFunction(
200983 sqlite3 *db, /* Database connection */
200984 const char *zName, /* Name of SQL function */
200985 int nArg, /* Number of arguments */
200986 int eTextRep, /* Text encoding and function flags */
200987 Fts3Hash *pHash, /* Tokenizer hash table */
200988 void (*xFunc)(sqlite3_context*,int,sqlite3_value**) /* Implementation */
200989 ){
200990 Fts3HashWrapper *pWrapper = (Fts3HashWrapper*)pHash;
200991 pWrapper->nRef++;
200992 return sqlite3_create_function_v2(
200993 db, zName, nArg, eTextRep, (void*)pWrapper, xFunc, 0, 0, hashDestroy
200994 );
200995 }
200996
200997 /*
200998 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
200999 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
201000 ** respectively. The following three forward declarations are for functions
@@ -199829,17 +201046,18 @@
201046 if( rc!=SQLITE_OK ) return rc;
201047
201048 sqlite3Fts3SimpleTokenizerModule(&pSimple);
201049 sqlite3Fts3PorterTokenizerModule(&pPorter);
201050
201051 /* Allocate and initialize the hash-table used to store tokenizers. The
201052 ** reference held by this function is released before it returns. */
201053 pHash = sqlite3_malloc(sizeof(Fts3HashWrapper));
201054 if( !pHash ){
201055 rc = SQLITE_NOMEM;
201056 }else{
201057 sqlite3Fts3HashInit(&pHash->hash, FTS3_HASH_STRING, 1);
201058 pHash->nRef = 1;
201059 }
201060
201061 /* Load the built-in tokenizers into the hash table */
201062 if( rc==SQLITE_OK ){
201063 if( sqlite3Fts3HashInsert(&pHash->hash, "simple", 7, (void *)pSimple)
@@ -199886,20 +201104,27 @@
201104 }
201105 if( rc==SQLITE_OK ){
201106 pHash->nRef++;
201107 rc = sqlite3Fts3InitTok(db, (void *)pHash, hashDestroy);
201108 }
 
201109 }
201110
201111 /* If an error has occurred, remove any modules and functions registered
201112 ** above. If this is a loadable extension, the shared library may be unloaded
201113 ** as soon as this function returns, so they must not be left in place. */
201114 if( rc!=SQLITE_OK ){
201115 sqlite3_create_module(db, "fts3", 0, 0);
201116 sqlite3_create_module(db, "fts4", 0, 0);
201117 sqlite3_create_module(db, "fts3tokenize", 0, 0);
201118 sqlite3_create_module(db, "fts4aux", 0, 0);
201119 sqlite3_create_function(db, "fts3_tokenizer", 1, SQLITE_UTF8, 0, 0, 0, 0);
201120 sqlite3_create_function(db, "fts3_tokenizer", 2, SQLITE_UTF8, 0, 0, 0, 0);
201121 }
201122
201123 /* Release the reference held by this function. If nothing else still holds
201124 ** a reference, this deletes the hash table. */
201125 if( pHash ) hashDestroy(pHash);
 
 
 
201126 return rc;
201127 }
201128
201129 /*
201130 ** Allocate an Fts3MultiSegReader for each token in the expression headed
@@ -201955,11 +203180,12 @@
203180
203181 /*
203182 ** Schema of the terms table.
203183 */
203184 #define FTS3_AUX_SCHEMA \
203185 "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN, " \
203186 "PRIMARY KEY(term, col, languageid)) WITHOUT ROWID"
203187
203188 /*
203189 ** This function does all the work for both the xConnect and xCreate methods.
203190 ** These tables have no persistent representation of their own, so xConnect
203191 ** and xCreate are identical operations.
@@ -202342,11 +203568,11 @@
203568 if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
203569 pCsr->filter.nTerm = (int)strlen(pCsr->filter.zTerm);
203570 }
203571 }
203572
203573 if( iLe>=0 && sqlite3_value_type(apVal[iLe])==SQLITE_TEXT ){
203574 pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
203575 if( pCsr->zStop==0 ) return SQLITE_NOMEM;
203576 pCsr->nStop = (int)strlen(pCsr->zStop);
203577 }
203578
@@ -203780,16 +205006,17 @@
205006 /*
205007 ** Register the query expression parser test function fts3_exprtest()
205008 ** with database connection db.
205009 */
205010 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash *pHash){
205011 int rc = sqlite3Fts3CreateHashFunction(
205012 db, "fts3_exprtest", -1, SQLITE_UTF8, pHash, fts3ExprTest
205013 );
205014 if( rc==SQLITE_OK ){
205015 rc = sqlite3Fts3CreateHashFunction(
205016 db, "fts3_exprtest_rebalance", -1, SQLITE_UTF8, pHash,
205017 fts3ExprTestRebalance
205018 );
205019 }
205020 return rc;
205021 }
205022
@@ -205326,11 +206553,10 @@
206553 sqlite3 *db,
206554 Fts3Hash *pHash,
206555 const char *zName
206556 ){
206557 int rc = SQLITE_OK;
 
206558 const int any = SQLITE_UTF8|SQLITE_DIRECTONLY;
206559
206560 #ifdef SQLITE_TEST
206561 char *zTest = 0;
206562 char *zTest2 = 0;
@@ -205341,18 +206567,22 @@
206567 rc = SQLITE_NOMEM;
206568 }
206569 #endif
206570
206571 if( SQLITE_OK==rc ){
206572 rc = sqlite3Fts3CreateHashFunction(
206573 db, zName, 1, any, pHash, fts3TokenizerFunc
206574 );
206575 }
206576 if( SQLITE_OK==rc ){
206577 rc = sqlite3Fts3CreateHashFunction(
206578 db, zName, 2, any, pHash, fts3TokenizerFunc
206579 );
206580 }
206581 #ifdef SQLITE_TEST
206582 if( SQLITE_OK==rc ){
206583 rc = sqlite3Fts3CreateHashFunction(db, zTest, -1, any, pHash, testFunc);
206584 }
206585 if( SQLITE_OK==rc ){
206586 rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
206587 }
206588 #endif
@@ -206847,12 +208077,12 @@
208077 int rc = SQLITE_OK;
208078
208079 pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
208080 if( pList ){
208081 assert( (i64)pList->nData+(i64)nToken+(i64)sizeof(Fts3HashElem)
208082 <= p->nPendingData );
208083 p->nPendingData -= pList->nData + nToken + sizeof(Fts3HashElem);
208084 }
208085 if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
208086 if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
208087 /* Malloc failed while inserting the new entry. This can only
208088 ** happen if there was no previous entry for this token.
@@ -206861,13 +208091,13 @@
208091 sqlite3_free(pList);
208092 rc = SQLITE_NOMEM;
208093 }
208094 }
208095 if( rc==SQLITE_OK ){
208096 assert( p->nPendingData + pList->nData + nToken
208097 + sizeof(Fts3HashElem) <= 0x3fffffff );
208098 p->nPendingData += pList->nData + nToken + sizeof(Fts3HashElem);
208099 }
208100 return rc;
208101 }
208102
208103 /*
@@ -209848,13 +211078,13 @@
211078 **
211079 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
211080 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
211081 ** to reflect the new size of the pBlob->a[] buffer.
211082 */
211083 static void blobGrowBuffer(Blob *pBlob, i64 nMin, int *pRc){
211084 if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
211085 i64 nAlloc = nMin;
211086 char *a = (char *)sqlite3_realloc64(pBlob->a, nAlloc);
211087 if( a ){
211088 pBlob->nAlloc = nAlloc;
211089 pBlob->a = a;
211090 }else{
@@ -210118,23 +211348,23 @@
211348 const char *zTerm = pCsr->zTerm;
211349 int nTerm = pCsr->nTerm;
211350 const char *aDoclist = pCsr->aDoclist;
211351 int nDoclist = pCsr->nDoclist;
211352 int rc = SQLITE_OK; /* Return code */
211353 i64 nSpace; /* Total space in bytes required on leaf */
211354 int nPrefix; /* Size of prefix shared with previous term */
211355 int nSuffix; /* Size of suffix (nTerm - nPrefix) */
211356 NodeWriter *pLeaf; /* Object used to write leaf nodes */
211357
211358 pLeaf = &pWriter->aNodeWriter[0];
211359 nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
211360 nSuffix = nTerm - nPrefix;
211361 if(nSuffix<=0 ) return FTS_CORRUPT_VTAB;
211362
211363 nSpace = (i64)sqlite3Fts3VarintLen(nPrefix);
211364 nSpace += (i64)sqlite3Fts3VarintLen(nSuffix) + nSuffix;
211365 nSpace += (i64)sqlite3Fts3VarintLen(nDoclist) + nDoclist;
211366
211367 /* If the current block is not empty, and if adding this term/doclist
211368 ** to the current block would make it larger than Fts3Table.nNodeSize bytes,
211369 ** and if there is still room for another leaf page, write this block out to
211370 ** the database. */
@@ -211110,11 +212340,11 @@
212340 pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
212341
212342 if( rc==SQLITE_OK ){
212343 rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
212344 assert( bUseHint==1 || bUseHint==0 );
212345 if( rc==SQLITE_OK && (iIdx==0 || (bUseHint && iIdx==1)) ){
212346 int bIgnore = 0;
212347 rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
212348 if( bIgnore ){
212349 pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
212350 }
@@ -214882,11 +216112,15 @@
216112 #define JEDIT_INS 3 /* Insert if not exists */
216113 #define JEDIT_SET 4 /* Insert or overwrite */
216114 #define JEDIT_AINS 5 /* array_insert() */
216115
216116 /*
216117 ** The approximate maximum nesting depth of JSON for this implementation.
216118 **
216119 ** Applications should say well clear of this maximum. Depending on
216120 ** implementation quirks, the limit might not reached one or two before
216121 ** or one or two after the published limit.
216122 **
216123 ** This limit is needed to avoid a stack overflow in the recursive
216124 ** descent parser. A depth of 1000 is far deeper than any sane JSON
216125 ** should go. Historical note: This limit was 2000 prior to version 3.42.0
216126 */
@@ -215901,10 +217135,11 @@
217135 if( z[j]=='-' ){
217136 j++;
217137 if( sz<2 ) return i+1;
217138 }
217139 k = i+n+sz;
217140 if( z[j]=='0' && j<k-1 ) return j+1;
217141 while( j<k ){
217142 if( sqlite3Isdigit(z[j]) ){
217143 j++;
217144 }else{
217145 return j+1;
@@ -215961,11 +217196,11 @@
217196 }
217197 seen = 1;
217198 continue;
217199 }
217200 if( z[j]=='e' || z[j]=='E' ){
217201 if( seen==2 || j==i+n ) return j+1;
217202 if( j==k-1 ) return j+1;
217203 if( z[j+1]=='+' || z[j+1]=='-' ){
217204 j++;
217205 if( j==k-1 ) return j+1;
217206 }
@@ -216375,10 +217610,11 @@
217610 pParse->iErr = i+1;
217611 return -1;
217612 }
217613 }else{
217614 if( !sqlite3Isdigit(z[i+1]) ){
217615 assert( z[i]=='-' || z[i]=='+' );
217616 /* JSON5 allows for "+Infinity" and "-Infinity" using exactly
217617 ** that case. SQLite also allows these in any case and it allows
217618 ** "+inf" and "-inf". */
217619 if( (z[i+1]=='I' || z[i+1]=='i')
217620 && sqlite3StrNICmp(&z[i+1], "inf",3)==0
@@ -216394,10 +217630,22 @@
217630 if( z[i+1]=='.' ){
217631 pParse->hasNonstd = 1;
217632 t |= 0x01;
217633 goto parse_number_2;
217634 }
217635 #if 0
217636 /* Full JSON5 compliance requires support for +NaN and -NaN, even
217637 ** though the extra prefix is not used for anything. Enable this
217638 ** block of code to get SQLite to do the same thing. It never
217639 ** has in an official release, and the only accomplishment of
217640 ** enabling it would be to take up a few bytes more code space. */
217641 if( sqlite3StrNICmp(&z[i+1],"NaN",3)==0 ){
217642 pParse->hasNonstd = 1;
217643 jsonBlobAppendOneByte(pParse, JSONB_NULL);
217644 return i+4;
217645 }
217646 #endif
217647 pParse->iErr = i;
217648 return -1;
217649 }
217650 if( z[i+1]=='0' ){
217651 if( sqlite3Isdigit(z[i+2]) ){
@@ -216573,10 +217821,11 @@
217821 #endif
217822 while( jsonIsspace(zJson[i]) ) i++;
217823 if( zJson[i] ){
217824 i += json5Whitespace(&zJson[i]);
217825 if( zJson[i] ){
217826 pParse->iErr = i;
217827 if( pCtx ) sqlite3_result_error(pCtx, "malformed JSON", -1);
217828 jsonParseReset(pParse);
217829 return 1;
217830 }
217831 pParse->hasNonstd = 1;
@@ -216845,10 +218094,98 @@
218094 #else /* if !SQLITE_USES_INLINE */
218095 /* On compilers that do not support in-lining, just call the original
218096 ** jsonbPayloadSize(). It's slower, but it gets the right answer. */
218097 # define jsonbPayloadSizeSemiInline(a,b,c) jsonbPayloadSize(a,b,c)
218098 #endif
218099
218100 /*
218101 ** Convert a JSONB integer literal into either an integer (if it is small
218102 ** enough) or into a double. Include the sign. Return:
218103 **
218104 ** 0 Value is an integer, results written into *pI.
218105 ** 1 Value is a double, results written into *pR.
218106 ** 2 Syntax error
218107 */
218108 static int jsonConvertInteger(const char *zIn, u32 sz, i64 *pI, double *pR){
218109 u32 k = 0;
218110 int bNeg = 0;
218111 sqlite3_uint64 u = 0;
218112 double rOverflow = 1.0;
218113 if( sz==0 ) return 2;
218114 if( zIn[0]=='-' ){
218115 bNeg = 1;
218116 k = 1;
218117 }else if( zIn[0]=='+' ){
218118 k = 1;
218119 }
218120 if( k+2<sz && zIn[k]=='0' && (zIn[k+1]=='x' || zIn[k+1]=='X') ){
218121 k += 2;
218122 do{
218123 if( !sqlite3Isxdigit(zIn[k]) ){
218124 return 2;
218125 }else if( (u>>60)!=0 ){
218126 rOverflow *= 16.0;
218127 }else{
218128 u = u*16 + sqlite3HexToInt(zIn[k]);
218129 }
218130 k++;
218131 }while( k<sz );
218132 }else if( k>=sz ){
218133 return 2;
218134 }else{
218135 do{
218136 if( zIn[k]<'0' || zIn[k]>'9' ){
218137 return 2;
218138 }else if( (u>>60)!=0 ){
218139 rOverflow *= 10.0;
218140 }else{
218141 u = u*10 + zIn[k] - '0';
218142 }
218143 k++;
218144 }while( k<sz );
218145 }
218146 if( rOverflow>1.0
218147 || (u>0x7fffffffffffffffULL && (!bNeg || u>0x8000000000000000ULL))
218148 ){
218149 *pR = rOverflow * (double)u;
218150 if( bNeg ) *pR = -*pR;
218151 return 1;
218152 }else{
218153 memcpy(pI, &u, sizeof(u));
218154 if( bNeg && u!=0x8000000000000000ULL ) *pI = -*pI;
218155 return 0;
218156 }
218157 }
218158
218159 /*
218160 ** Tail recursive code to implement the JSON_INT5 case of of
218161 ** jsonTranslateBlobInt5ToText(). This is split out because
218162 ** the resulting reduction in the stack frame size helps the
218163 ** caller to run faster.
218164 */
218165 static SQLITE_NOINLINE u32 jsonTranslateBlobInt5ToText(
218166 JsonParse *pParse, /* the complete parse of the JSON */
218167 u32 i, /* Start rendering at this index */
218168 JsonString *pOut, /* Write JSON here */
218169 u32 sz, /* Payload size */
218170 u32 n /* Header size */
218171 ){
218172 int k;
218173 const char *zIn = (const char*)&pParse->aBlob[i+n];
218174 i64 ival;
218175 double rval;
218176 k = jsonConvertInteger(zIn, sz, &ival, &rval);
218177 if( k==0 ){
218178 jsonPrintf(100, pOut, "%lld", ival);
218179 }else if( k==1 ){
218180 jsonPrintf(100, pOut, "%!0.17g", rval);
218181 }else{
218182 pOut->eErr |= JSTRING_MALFORMED;
218183 }
218184 return i+n+sz;
218185 }
218186
218187
218188 /*
218189 ** Translate the binary JSONB representation of JSON beginning at
218190 ** pParse->aBlob[i] into a JSON text string. Append the JSON
218191 ** text onto the end of pOut. Return the index in pParse->aBlob[]
@@ -216891,33 +218228,11 @@
218228 if( sz==0 ) goto malformed_jsonb;
218229 jsonAppendRaw(pOut, (const char*)&pParse->aBlob[i+n], sz);
218230 break;
218231 }
218232 case JSONB_INT5: { /* Integer literal in hexadecimal notation */
218233 return jsonTranslateBlobInt5ToText(pParse, i, pOut, sz, n);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218234 }
218235 case JSONB_FLOAT5: { /* Float literal missing digits beside "." */
218236 u32 k = 0;
218237 const char *zIn = (const char*)&pParse->aBlob[i+n];
218238 if( sz==0 ) goto malformed_jsonb;
@@ -217170,11 +218485,10 @@
218485 jsonAppendChar(pOut, '\n');
218486 pPretty->nIndent++;
218487 if( pPretty->nIndent >= JSON_MAX_DEPTH ){
218488 jsonStringTooDeep(pOut);
218489 }
 
218490 while( pOut->eErr==0 ){
218491 jsonPrettyIndent(pPretty);
218492 j = jsonTranslateBlobToText(pParse, j, pOut);
218493 if( j>iEnd ){
218494 pOut->eErr |= JSTRING_MALFORMED;
@@ -217672,11 +218986,11 @@
218986 jsonBlobEdit(pParse, iRoot, sz, 0, 0);
218987 }else if( pParse->eEdit==JEDIT_INS ){
218988 /* Already exists, so json_insert() is a no-op */
218989 }else if( pParse->eEdit==JEDIT_AINS ){
218990 /* json_array_insert() */
218991 if( zPath[-1]!=']' || iLabel ){
218992 return JSON_LOOKUP_NOTARRAY;
218993 }else{
218994 jsonBlobEdit(pParse, iRoot, 0, pParse->aIns, pParse->nIns);
218995 }
218996 }else{
@@ -217929,56 +219243,28 @@
219243 sqlite3_result_int(pCtx, 0);
219244 break;
219245 }
219246 case JSONB_INT5:
219247 case JSONB_INT: {
219248 sqlite3_int64 ival;
219249 double rval;
219250 int k;
219251 k = jsonConvertInteger((const char*)&pParse->aBlob[i+n], sz,&ival,&rval);
219252 if( k==0 ){
219253 sqlite3_result_int64(pCtx, ival);
219254 }else if( k==1 ){
219255 sqlite3_result_double(pCtx, rval);
219256 }else{
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219257 goto returnfromblob_malformed;
 
 
 
219258 }
219259 break;
219260 }
219261 case JSONB_FLOAT5:
219262 case JSONB_FLOAT: {
219263 double r;
219264 char *z;
219265 if( sz==0 ) goto returnfromblob_malformed;
 
219266 z = sqlite3DbStrNDup(db, (const char*)&pParse->aBlob[i+n], (int)sz);
219267 if( z==0 ) goto returnfromblob_oom;
219268 rc = sqlite3AtoF(z, &r);
219269 sqlite3DbFree(db, z);
219270 if( rc<=0 ) goto returnfromblob_malformed;
@@ -218242,12 +219528,15 @@
219528 return;
219529 }
219530 if( zPath[1]==0 ){
219531 if( eEdit==JEDIT_REPL || eEdit==JEDIT_SET ){
219532 jsonBlobEdit(p, 0, p->nBlob, ax.aBlob, ax.nBlob);
219533 }else if( eEdit==JEDIT_AINS ){
219534 rc = JSON_LOOKUP_NOTARRAY;
219535 }else{
219536 rc = 0;
219537 }
 
219538 }else{
219539 p->eEdit = eEdit;
219540 p->nIns = ax.nBlob;
219541 p->aIns = ax.aBlob;
219542 p->delta = 0;
@@ -220063,13 +221352,14 @@
221352 }
221353 break;
221354 }
221355 if( p->eType==JSONB_OBJECT ){
221356 jsonReturnFromBlob(&p->sParse, p->i, ctx, 1);
221357 }else if( p->eType==JSONB_ARRAY ){
 
221358 sqlite3_result_int64(ctx, p->aParent[p->nParent-1].iKey);
221359 }else{
221360 sqlite3_result_error(ctx, "malformed JSON", -1);
221361 }
221362 break;
221363 }
221364 case JEACH_VALUE: {
221365 u32 i = jsonSkipLabel(p);
@@ -221333,11 +222623,13 @@
222623 if( pNode->iNode ){
222624 sqlite3_bind_int64(p, 1, pNode->iNode);
222625 }else{
222626 sqlite3_bind_null(p, 1);
222627 }
222628 rc = sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize,
222629 SQLITE_STATIC);
222630 if( rc!=SQLITE_OK ) return rc;
222631 sqlite3_step(p);
222632 pNode->isDirty = 0;
222633 rc = sqlite3_reset(p);
222634 sqlite3_bind_null(p, 2);
222635 if( pNode->iNode==0 && rc==SQLITE_OK ){
@@ -225214,11 +226506,11 @@
226506 sqlite3_str_append(x, "[", 1);
226507 for(i=0; i<p->nVertex; i++){
226508 sqlite3_str_appendf(x, "[%!g,%!g],", GeoX(p,i), GeoY(p,i));
226509 }
226510 sqlite3_str_appendf(x, "[%!g,%!g]]", GeoX(p,0), GeoY(p,0));
226511 sqlite3_result_str(context, x, SQLITE_FINISH);
226512 sqlite3_free(p);
226513 }
226514 }
226515
226516 /*
@@ -225251,11 +226543,11 @@
226543 if( z && z[0] ){
226544 sqlite3_str_appendf(x, " %s", z);
226545 }
226546 }
226547 sqlite3_str_appendf(x, "></polyline>");
226548 sqlite3_result_str(context, x, SQLITE_FINISH);
226549 sqlite3_free(p);
226550 }
226551 }
226552
226553 /*
@@ -226570,11 +227862,12 @@
227862 GeoPoly *p = 0;
227863 if( sqlite3_value_type(pShape)==SQLITE_TEXT
227864 && (p = geopolyFuncParam(0, pShape, &rc))!=0
227865 && rc==SQLITE_OK
227866 ){
227867 rc = sqlite3_bind_blob(pUp, 2, p->hdr, 4+8*p->nVertex,
227868 SQLITE_TRANSIENT);
227869 }else{
227870 sqlite3_bind_value(pUp, 2, pShape);
227871 }
227872 sqlite3_free(p);
227873 nChange = 1;
@@ -226581,11 +227874,11 @@
227874 }
227875 for(jj=1; jj<nData-2; jj++){
227876 nChange++;
227877 sqlite3_bind_value(pUp, jj+2, aData[jj+2]);
227878 }
227879 if( rc==SQLITE_OK && nChange ){
227880 sqlite3_step(pUp);
227881 rc = sqlite3_reset(pUp);
227882 }
227883 }
227884
@@ -228654,10 +229947,11 @@
229947 sqlite3_stmt *pTblIter; /* Iterate through tables */
229948 sqlite3_stmt *pIdxIter; /* Index iterator */
229949 int nTblCol; /* Size of azTblCol[] array */
229950 char **azTblCol; /* Array of unquoted target column names */
229951 char **azTblType; /* Array of target column types */
229952 char **azTblDflt; /* Array of target column DEFAULT exprs */
229953 int *aiSrcOrder; /* src table col -> target table col */
229954 u8 *abTblPk; /* Array of flags, set on target PK columns */
229955 u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
229956 u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
229957 int eType; /* Table type - an RBU_PK_XXX value */
@@ -229219,14 +230513,16 @@
230513 static void rbuObjIterFreeCols(RbuObjIter *pIter){
230514 int i;
230515 for(i=0; i<pIter->nTblCol; i++){
230516 sqlite3_free(pIter->azTblCol[i]);
230517 sqlite3_free(pIter->azTblType[i]);
230518 sqlite3_free(pIter->azTblDflt[i]);
230519 }
230520 sqlite3_free(pIter->azTblCol);
230521 pIter->azTblCol = 0;
230522 pIter->azTblType = 0;
230523 pIter->azTblDflt = 0;
230524 pIter->aiSrcOrder = 0;
230525 pIter->abTblPk = 0;
230526 pIter->abNotNull = 0;
230527 pIter->nTblCol = 0;
230528 pIter->eType = 0; /* Invalid value */
@@ -229475,10 +230771,47 @@
230771 }
230772 sqlite3_free(zSql);
230773 va_end(ap);
230774 return p->rc;
230775 }
230776
230777 /*
230778 ** Like rbuMPrintfExec() except that it is guaranteed to only run a
230779 ** single statement. If the generated SQL text includes two or more
230780 ** statements, all but the first is ignored.
230781 **
230782 ** If an error occurs, an error code and error message is stored in the
230783 ** RBU handle. If an error has already occurred when this function is
230784 ** called, it is a no-op.
230785 */
230786 static int rbuMPrintfOneStmt(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
230787 va_list ap;
230788 char *zSql;
230789 va_start(ap, zFmt);
230790 zSql = sqlite3_vmprintf(zFmt, ap);
230791 if( p->rc==SQLITE_OK ){
230792 if( zSql==0 ){
230793 p->rc = SQLITE_NOMEM;
230794 }else{
230795 sqlite3_stmt *pStmt;
230796 p->rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
230797 if( pStmt ){
230798 if( p->rc==SQLITE_OK ){
230799 while( sqlite3_step(pStmt)==SQLITE_ROW ){}
230800 }
230801 p->rc = sqlite3_finalize(pStmt);
230802 }
230803 if( p->rc!=SQLITE_OK ){
230804 sqlite3_free(p->zErrmsg);
230805 p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
230806 }
230807 }
230808 }
230809 sqlite3_free(zSql);
230810 va_end(ap);
230811 return p->rc;
230812 }
230813
230814 /*
230815 ** Attempt to allocate and return a pointer to a zeroed block of nByte
230816 ** bytes.
230817 **
@@ -229507,18 +230840,19 @@
230840 ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
230841 ** there is room for at least nCol elements. If an OOM occurs, store an
230842 ** error code in the RBU handle passed as the first argument.
230843 */
230844 static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
230845 sqlite3_int64 nByte = (3*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
230846 char **azNew;
230847
230848 azNew = (char**)rbuMalloc(p, nByte);
230849 if( azNew ){
230850 pIter->azTblCol = azNew;
230851 pIter->azTblType = &azNew[nCol];
230852 pIter->azTblDflt = &azNew[nCol*2];
230853 pIter->aiSrcOrder = (int*)&pIter->azTblDflt[nCol];
230854 pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
230855 pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
230856 pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
230857 }
230858 }
@@ -229548,10 +230882,35 @@
230882 }
230883 }
230884
230885 return zRet;
230886 }
230887
230888 /*
230889 ** Return a copy of the declared column type zType that is safe to paste
230890 ** into a CREATE TABLE statement.
230891 **
230892 ** zType comes from the schema of a database that RBU does not control.
230893 ** A type name may legally be a quoted string, so after the quotes are
230894 ** removed (as PRAGMA table_xinfo does) it can contain any text at all,
230895 ** including ")", ";" and CHECK or other column constraints. So it is
230896 ** returned as a single double-quoted token, which the parser turns back
230897 ** into the identical type name. An empty type is returned as an empty
230898 ** string. The result must be freed using sqlite3_free().
230899 */
230900 static char *rbuQuoteType(const char *zType, int *pRc){
230901 char *zRet = 0;
230902 if( *pRc==SQLITE_OK ){
230903 if( zType==0 || zType[0]==0 ){
230904 zRet = rbuStrndup("", pRc);
230905 }else{
230906 zRet = sqlite3_mprintf("\"%w\"", zType);
230907 if( zRet==0 ) *pRc = SQLITE_NOMEM;
230908 }
230909 }
230910 return zRet;
230911 }
230912
230913 /*
230914 ** Finalize the statement passed as the second argument.
230915 **
230916 ** If the sqlite3_finalize() call indicates that an error occurs, and the
@@ -229734,10 +231093,29 @@
231093
231094 rbuFinalize(p, pList);
231095 if( bIndex==0 ) pIter->abIndexed = 0;
231096 }
231097
231098 /*
231099 ** Return true if table zTbl in the main database of the target is a
231100 ** STRICT table, or false otherwise. If an error occurs, an error code
231101 ** and message are left in the RBU handle and zero is returned.
231102 */
231103 static int rbuTableIsStrict(sqlite3rbu *p, const char *zTbl){
231104 int bStrict = 0;
231105 sqlite3_stmt *pStmt = 0;
231106 if( p->rc==SQLITE_OK ){
231107 p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
231108 sqlite3_mprintf("PRAGMA main.table_list(%Q)", zTbl)
231109 );
231110 if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
231111 bStrict = sqlite3_column_int(pStmt, 5);
231112 }
231113 rbuFinalize(p, pStmt);
231114 }
231115 return bStrict;
231116 }
231117
231118 /*
231119 ** If they are not already populated, populate the pIter->azTblCol[],
231120 ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
231121 ** the table (not index) that the iterator currently points to.
@@ -229752,10 +231130,11 @@
231130 int nCol = 0;
231131 int i; /* for() loop iterator variable */
231132 int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
231133 int iOrder = 0;
231134 int iTnum = 0;
231135 int bStrict = 0; /* True if target is a STRICT table */
231136
231137 /* Figure out the type of table this step will deal with. */
231138 assert( pIter->eType==0 );
231139 rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
231140 if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
@@ -229802,14 +231181,16 @@
231181 p->zErrmsg = sqlite3_mprintf(
231182 "table %q %s rbu_rowid column", pIter->zDataTbl,
231183 (bRbuRowid ? "may not have" : "requires")
231184 );
231185 }
231186
231187 bStrict = rbuTableIsStrict(p, pIter->zTbl);
231188
231189 /* Check that all non-HIDDEN columns in the destination table are also
231190 ** present in the input table. Populate the abTblPk[], azTblType[],
231191 ** azTblDflt[] and aiTblOrder[] arrays at the same time.
231192 **
231193 ** RBU does not support tables with GENERATED columns. If the target
231194 ** table has any, return an error. */
231195 if( p->rc==SQLITE_OK ){
231196 p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
@@ -229838,17 +231219,22 @@
231219 );
231220 }else{
231221 int iPk = sqlite3_column_int(pStmt, 5);
231222 int bNotNull = sqlite3_column_int(pStmt, 3);
231223 const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
231224 const char *zDflt = (const char*)sqlite3_column_text(pStmt, 4);
231225
231226 if( i!=iOrder ){
231227 SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
231228 SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
231229 }
231230
231231 /* In a STRICT table, ANY means no affinity. In the non-STRICT
231232 ** imposter it would mean NUMERIC, so declare it without a type. */
231233 if( bStrict && sqlite3_stricmp(zType, "ANY")==0 ) zType = "";
231234 pIter->azTblType[iOrder] = rbuQuoteType(zType, &p->rc);
231235 pIter->azTblDflt[iOrder] = rbuStrndup(zDflt, &p->rc);
231236 assert( iPk>=0 );
231237 pIter->abTblPk[iOrder] = (u8)iPk;
231238 pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
231239 iOrder++;
231240 }
@@ -230517,11 +231903,11 @@
231903 }
231904 zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
231905 rbuFinalize(p, pXInfo);
231906
231907 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
231908 rbuMPrintfOneStmt(p, p->dbMain,
231909 "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
231910 zCols, zPk
231911 );
231912 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
231913 }
@@ -230567,13 +231953,15 @@
231953 if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
231954 /* If the target table column is an "INTEGER PRIMARY KEY", add
231955 ** "PRIMARY KEY" to the imposter table column declaration. */
231956 zPk = "PRIMARY KEY ";
231957 }
231958 zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s%s%s",
231959 zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
231960 (pIter->abNotNull[iCol] ? " NOT NULL" : ""),
231961 (pIter->azTblDflt[iCol] ? " DEFAULT " : ""),
231962 (pIter->azTblDflt[iCol] ? pIter->azTblDflt[iCol] : "")
231963 );
231964 zComma = ", ";
231965 }
231966
231967 if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
@@ -230582,11 +231970,11 @@
231970 zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
231971 }
231972 }
231973
231974 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
231975 rbuMPrintfOneStmt(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
231976 pIter->zTbl, zSql,
231977 (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
231978 );
231979 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
231980 }
@@ -230786,11 +232174,11 @@
232174 zBind = rbuObjIterGetBindlist(p, nBind);
232175
232176 /* Create the imposter table used to write to this index. */
232177 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
232178 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
232179 rbuMPrintfOneStmt(p, p->dbMain,
232180 "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
232181 zTbl, zImposterCols, zImposterPK
232182 );
232183 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
232184
@@ -230913,11 +232301,11 @@
232301 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
232302 zRbuRowid = ", rbu_rowid";
232303 }
232304
232305 /* Create the rbu_tmp_xxx table and the triggers to populate it. */
232306 rbuMPrintfOneStmt(p, p->dbRbu,
232307 "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
232308 "SELECT *%s FROM '%q' WHERE 0;"
232309 , p->zStateDb, pIter->zDataTbl
232310 , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
232311 , pIter->zDataTbl
@@ -230942,11 +232330,11 @@
232330 zWrite, zTbl, zOldlist,
232331 zWrite, zTbl, zNewlist
232332 );
232333
232334 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
232335 rbuMPrintfOneStmt(p, p->dbMain,
232336 "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
232337 "BEGIN "
232338 " SELECT rbu_tmp_insert(0, %s);"
232339 "END;",
232340 zWrite, zTbl, zNewlist
@@ -231227,11 +232615,11 @@
232615 }
232616
232617 /* If using separate RBU and state databases, attach the state database to
232618 ** the RBU db handle now. */
232619 if( p->zState ){
232620 rbuMPrintfOneStmt(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
232621 memcpy(p->zStateDb, "stat", 4);
232622 }else{
232623 memcpy(p->zStateDb, "main", 4);
232624 }
232625
@@ -231353,11 +232741,11 @@
232741 }
232742
232743 if( p->rc==SQLITE_OK ){
232744 p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
232745 }
232746 rbuMPrintfOneStmt(p, p->dbMain, "SELECT * FROM sqlite_schema");
232747
232748 /* Mark the database file just opened as an RBU target database. If
232749 ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
232750 ** This is an error. */
232751 if( p->rc==SQLITE_OK ){
@@ -231961,11 +233349,11 @@
233349 iCookie = sqlite3_column_int(pStmt, 0);
233350 }
233351 rbuFinalize(p, pStmt);
233352 }
233353 if( p->rc==SQLITE_OK ){
233354 rbuMPrintfOneStmt(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
233355 }
233356 }
233357 }
233358
233359 /*
@@ -232039,11 +233427,11 @@
233427 sqlite3_stmt *pPragma = 0;
233428 p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
233429 sqlite3_mprintf("PRAGMA main.%s", zPragma)
233430 );
233431 if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
233432 p->rc = rbuMPrintfOneStmt(p, p->dbMain, "PRAGMA main.%s = %d",
233433 zPragma, sqlite3_column_int(pPragma, 0)
233434 );
233435 }
233436 rbuFinalize(p, pPragma);
233437 }
@@ -232130,11 +233518,11 @@
233518 if( pIter->bCleanup ){
233519 /* Clean up the rbu_tmp_xxx table for the previous table. It
233520 ** cannot be dropped as there are currently active SQL statements.
233521 ** But the contents can be deleted. */
233522 if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
233523 rbuMPrintfOneStmt(p, p->dbRbu,
233524 "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
233525 );
233526 }
233527 }else{
233528 rbuObjIterPrepareAll(p, pIter, 0);
@@ -234286,11 +235674,13 @@
235674 if( p->iPgno==1 ) nHdr += 100;
235675 p->nCell = get2byte(&aHdr[3]);
235676 p->nMxPayload = 0;
235677 szPage = sqlite3BtreeGetPageSize(pBt);
235678
235679 nUnused = get2byte(&aHdr[5]);
235680 if( nUnused==0 ) nUnused = 65536;
235681 nUnused -= nHdr + 2*p->nCell;
235682 nUnused += (int)aHdr[7];
235683 iOff = get2byte(&aHdr[1]);
235684 while( iOff ){
235685 int iNext;
235686 if( iOff>=szPage ) goto statPageIsCorrupt;
@@ -235036,11 +236426,16 @@
236426 if( NEVER(pBt==0) ) return SQLITE_OK;
236427 pCsr->pPager = sqlite3BtreePager(pBt);
236428 pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
236429 pCsr->mxPgno = sqlite3BtreeLastPage(pBt);
236430 if( idxNum & 1 ){
236431 i64 iPg;
236432 if( sqlite3_value_numeric_type(argv[idxNum>>1])==SQLITE_INTEGER ){
236433 iPg = sqlite3_value_int64(argv[idxNum>>1]);
236434 }else{
236435 iPg = 0;
236436 }
236437 assert( argc>(idxNum>>1) );
236438 if( iPg<1 || iPg>pCsr->mxPgno ){
236439 pCsr->pgno = 1;
236440 pCsr->mxPgno = 0;
236441 }else{
@@ -235798,14 +237193,17 @@
237193 }else if( mFlags==CARRAY_BLOB ){
237194 struct iovec *p = (struct iovec*)pNew->aData;
237195 unsigned char *z = (unsigned char*)&p[nData];
237196 for(i=0; i<nData; i++){
237197 size_t n = ((struct iovec*)aData)[i].iov_len;
237198 void *a = ((struct iovec*)aData)[i].iov_base;
237199 p[i].iov_len = n;
237200 p[i].iov_base = a ? z : 0;
237201 if( n ){
237202 z += n;
237203 memcpy(p[i].iov_base, a, n);
237204 }
237205 }
237206 }else if( sz>0 ){
237207 memcpy(pNew->aData, aData, sz);
237208 }
237209 pNew->xDel = sqlite3_free;
@@ -236494,11 +237892,12 @@
237892 int n;
237893 assert( a!=0 );
237894 e = *a;
237895 if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
237896 if( e==SQLITE_TEXT || e==SQLITE_BLOB ){
237897 const int v = sessionVarintGet(&a[1], &n);
237898 return v + 1 + n;
237899 }
237900 return 1;
237901 }
237902
237903 /*
@@ -239796,13 +241195,19 @@
241195 ** there are no fields in the old.* record that are not (a) PK fields,
241196 ** or (b) also present in the new.* record.
241197 **
241198 ** Such records are technically corrupt, but the rebaser was at one
241199 ** point generating them. Under most circumstances this is benign, but
241200 ** can cause spurious SQLITE_RANGE errors when applying the changeset.
241201 **
241202 ** Also check that all PK fields are present in the old.* record. If
241203 ** they are not, the changeset is corrupt. */
241204 if( p->bPatchset==0 && p->op==SQLITE_UPDATE){
241205 for(i=0; i<p->nCol; i++){
241206 if( p->abPK[i] && p->apValue[i]==0 ){
241207 return (p->rc = SQLITE_CORRUPT_BKPT);
241208 }
241209 if( p->abPK[i]==0 && p->apValue[i+p->nCol]==0 ){
241210 sqlite3ValueFree(p->apValue[i]);
241211 p->apValue[i] = 0;
241212 }
241213 }
@@ -241050,23 +242455,26 @@
242455 ** before reattempting the INSERT. */
242456 else if( bReplace ){
242457 assert( pIter->op==SQLITE_INSERT );
242458 rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
242459 if( rc==SQLITE_OK ){
242460 int rc2;
242461 rc = sessionBindRow(pIter,
242462 sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
242463 sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
242464 if( rc==SQLITE_OK ){
242465 sqlite3_step(pApply->pDelete);
242466 rc = sqlite3_reset(pApply->pDelete);
242467 }
242468 if( rc==SQLITE_OK ){
242469 rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
242470 }
242471 if( rc!=SQLITE_OK ){
242472 sqlite3_exec(db, "ROLLBACK TO replace_op", 0, 0, 0);
242473 }
242474 rc2 = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
242475 if( rc==SQLITE_OK ) rc = rc2;
242476 }
242477 }
242478 }
242479
242480 return rc;
@@ -243213,13 +244621,10 @@
244621 *pzErr = sqlite3_mprintf("no such table: %s", zTab);
244622 }
244623 }
244624 if( rc==SQLITE_OK ){
244625 int nReq = pTab->nCol * (eOp==SQLITE_UPDATE ? 2 : 1);
 
 
 
244626
244627 if( pGrp->cd.nBufAlloc<nReq ){
244628 SessionBuffer *aBuf = (SessionBuffer*)sqlite3_realloc(
244629 pGrp->cd.aBuf, nReq * sizeof(SessionBuffer)
244630 );
@@ -243231,10 +244636,18 @@
244636 );
244637 pGrp->cd.aBuf = aBuf;
244638 pGrp->cd.nBufAlloc = nReq;
244639 }
244640 }
244641
244642 /* Only mark a change as under construction once the column buffers
244643 ** have been allocated. */
244644 if( rc==SQLITE_OK ){
244645 pGrp->cd.pTab = pTab;
244646 pGrp->cd.eOp = eOp;
244647 pGrp->cd.bIndirect = bIndirect;
244648 }
244649
244650 #ifdef SQLITE_DEBUG
244651 {
244652 /* Assert that all column values are currently undefined */
244653 int ii;
@@ -243273,12 +244686,13 @@
244686 SessionBuffer *pBuf = &pGrp->cd.aBuf[iCol];
244687 if( pGrp->cd.eOp==SQLITE_UPDATE && bNew ){
244688 pBuf += pGrp->cd.pTab->nCol;
244689 }
244690 pBuf->nBuf = 0;
244691 if( sessionBufferGrow(pBuf, nReq, &rc)==0 ){
244692 pBuf->nBuf = (int)nReq;
244693 }
244694 *ppBuf = pBuf;
244695 }
244696 return rc;
244697 }
244698
@@ -248832,11 +250246,11 @@
250246 zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
250247 for(i=0; zSql && i<pConfig->nCol; i++){
250248 const char *zSep = (i==0?"":", ");
250249 zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
250250 }
250251 zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q BLOB HIDDEN, %s HIDDEN)",
250252 zSql, pConfig->zName, FTS5_RANK_NAME
250253 );
250254
250255 assert( zSql || rc==SQLITE_NOMEM );
250256 if( zSql ){
@@ -249135,11 +250549,13 @@
250549 pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
250550 pConfig->nDeleteMerge = FTS5_DEFAULT_DELETE_AUTOMERGE;
250551
250552 zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
250553 if( zSql ){
250554 rc = sqlite3_prepare_v3(
250555 pConfig->db, zSql, -1, SQLITE_PREPARE_FROM_DDL, &p, 0
250556 );
250557 sqlite3_free(zSql);
250558 }
250559
250560 assert( rc==SQLITE_OK || p==0 );
250561 if( rc==SQLITE_OK ){
@@ -249185,11 +250601,11 @@
250601 char *zMsg = 0;
250602
250603 va_start(ap, zFmt);
250604 zMsg = sqlite3_vmprintf(zFmt, ap);
250605 if( pConfig->pzErrmsg ){
250606 sqlite3_free(*pConfig->pzErrmsg);
250607 *pConfig->pzErrmsg = zMsg;
250608 }else{
250609 sqlite3_free(zMsg);
250610 }
250611
@@ -253657,10 +255073,13 @@
255073 /* Variables populated based on current entry. */
255074 Fts5Buffer term; /* Current term */
255075 i64 iRowid; /* Current rowid */
255076 int nPos; /* Number of bytes in current position list */
255077 u8 bDel; /* True if the delete flag is set */
255078
255079 /* True if the current entry shadows an entry that has the delete flag set */
255080 u8 bDelDup;
255081 };
255082
255083 static int fts5IndexCorruptRowid(Fts5Index *pIdx, i64 iRowid){
255084 pIdx->rc = FTS5_CORRUPT;
255085 sqlite3Fts5ConfigErrmsg(pIdx->pConfig,
@@ -254050,11 +255469,12 @@
255469 char *zSql
255470 ){
255471 if( p->rc==SQLITE_OK ){
255472 if( zSql ){
255473 int rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
255474 SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB
255475 |SQLITE_PREPARE_FROM_DDL,
255476 ppStmt, 0);
255477 /* If this prepare() call fails with SQLITE_ERROR, then one of the
255478 ** %_idx or %_data tables has been removed or modified. Call this
255479 ** corruption. */
255480 p->rc = (rc==SQLITE_ERROR ? SQLITE_CORRUPT : rc);
@@ -254064,10 +255484,21 @@
255484 }
255485 sqlite3_free(zSql);
255486 return p->rc;
255487 }
255488
255489 /*
255490 ** If *pRc is other than SQLITE_OK when this function is called, it is a
255491 ** no-op. Otherwise, call sqlite3_step() and then sqlite3_reset() on the
255492 ** supplied statement pointer. Set (*pRc) to the result of sqlite3_reset().
255493 */
255494 static void fts5StepAndReset(int *pRc, sqlite3_stmt *pStmt){
255495 if( *pRc==SQLITE_OK ){
255496 sqlite3_step(pStmt);
255497 *pRc = sqlite3_reset(pStmt);
255498 }
255499 }
255500
255501 /*
255502 ** INSERT OR REPLACE a record into the %_data table.
255503 */
255504 static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
@@ -254081,13 +255512,12 @@
255512 ));
255513 if( p->rc ) return;
255514 }
255515
255516 sqlite3_bind_int64(p->pWriter, 1, iRowid);
255517 p->rc = sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
255518 fts5StepAndReset(&p->rc, p->pWriter);
 
255519 sqlite3_bind_null(p->pWriter, 2);
255520 }
255521
255522 /*
255523 ** Execute the following SQL:
@@ -254690,10 +256120,21 @@
256120 }
256121 fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
256122 }
256123 }
256124
256125 /*
256126 ** Return the page number iPgno+nDelta. If this is larger than FTS5_MAX_PGNO,
256127 ** which can only happen if the doclist-index record is corrupt, return
256128 ** FTS5_MAX_PGNO+1 instead. No leaf page with that number may exist, so
256129 ** this causes the corruption to be detected when the caller attempts to
256130 ** use the page number.
256131 */
256132 static int fts5AddPgno(int iPgno, int nDelta){
256133 i64 iRet = (i64)iPgno + nDelta;
256134 return (int)(iRet>FTS5_MAX_PGNO ? FTS5_MAX_PGNO+1 : iRet);
256135 }
256136
256137 /*
256138 ** Advance the iterator passed as the only argument. If the end of the
256139 ** doclist-index page is reached, return non-zero.
256140 */
@@ -254712,11 +256153,11 @@
256153 if( pData->p[iOff] ) break;
256154 }
256155
256156 if( iOff<pData->nn ){
256157 u64 iVal;
256158 pLvl->iLeafPgno = fts5AddPgno(pLvl->iLeafPgno, iOff-pLvl->iOff+1);
256159 iOff += fts5GetVarint(&pData->p[iOff], &iVal);
256160 pLvl->iRowid += iVal;
256161 pLvl->iOff = iOff;
256162 }else{
256163 pLvl->bEof = 1;
@@ -254822,11 +256263,11 @@
256263 ii++;
256264 }
256265 ii += sqlite3Fts5GetVarint(&a[ii], &delta);
256266
256267 if( ii>=iOff ) break;
256268 pLvl->iLeafPgno = fts5AddPgno(pLvl->iLeafPgno, nZero+1);
256269 pLvl->iRowid += delta;
256270 pLvl->iOff = ii;
256271 }
256272 }
256273
@@ -255828,11 +257269,12 @@
257269 /* This block sets stack variable iPg to the leaf page number that may
257270 ** contain term (pTerm/nTerm), if it is present in the segment. */
257271 pIdxSelect = fts5IdxSelectStmt(p);
257272 if( p->rc ) return;
257273 sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
257274 p->rc = sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
257275 if( p->rc ) return;
257276 if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
257277 i64 val = sqlite3_column_int(pIdxSelect, 0);
257278 iPg = (int)(val>>1);
257279 bDlidx = (val & 0x0001);
257280 }
@@ -255920,12 +257362,12 @@
257362
257363 pSel = fts5IdxNextStmt(p);
257364 if( pSel ){
257365 assert( p->rc==SQLITE_OK );
257366 sqlite3_bind_int(pSel, 1, pSeg->iSegid);
257367 p->rc = sqlite3_bind_blob(pSel, 2, pTerm, nTerm, SQLITE_STATIC);
257368 if( p->rc ) return;
257369 if( sqlite3_step(pSel)==SQLITE_ROW ){
257370 i64 val = sqlite3_column_int64(pSel, 0);
257371 iPg = (int)(val>>1);
257372 bDlidx = (val & 0x0001);
257373 }
@@ -256204,10 +257646,14 @@
257646 if( res==0 ){
257647 assert_nc( i2>i1 );
257648 assert_nc( i2!=0 );
257649 pRes->bTermEq = 1;
257650 if( p1->iRowid==p2->iRowid ){
257651 /* p2 is about to be advanced past this entry. If it, or an entry
257652 ** it shadowed, has the delete flag set, record this on p1. */
257653 p1->bDelDup |= (p2->bDel | p2->bDelDup);
257654 p2->bDelDup = 0;
257655 return i2;
257656 }
257657 res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
257658 }
257659 assert( res!=0 );
@@ -256721,10 +258167,15 @@
258167 int pgno = pSeg->iLeafPgno;
258168 int pgnoSave = 0;
258169
258170 /* This function does not work with detail=none databases. */
258171 assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
258172
258173 if( nChunk<0 ){
258174 FTS5_CORRUPT_IDX(p);
258175 return;
258176 }
258177
258178 if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
258179 pgnoSave = pgno+1;
258180 }
258181
@@ -257416,14 +258867,15 @@
258867
258868 if( p->rc==SQLITE_OK ){
258869 const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
258870 /* The following was already done in fts5WriteInit(): */
258871 /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
258872 p->rc = sqlite3_bind_blob(
258873 p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC
258874 );
258875 sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
258876 fts5StepAndReset(&p->rc, p->pIdxWriter);
 
258877 sqlite3_bind_null(p->pIdxWriter, 2);
258878 }
258879 pWriter->iBtPage = 0;
258880 }
258881
@@ -257966,10 +259418,18 @@
259418 ){
259419 Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
259420 int nPos; /* position-list size field value */
259421 int nTerm;
259422 const u8 *pTerm;
259423 int bDel; /* True to set delete flag on output */
259424
259425 /* If this entry has the delete flag set, or shadows an entry with the
259426 ** delete flag set, set the delete flag on the output. Unless the output
259427 ** will be the oldest segment in the table - in that case the delete flag
259428 ** may be discarded. */
259429 bDel = bOldest ? 0 : (pSegIter->bDel || pSegIter->bDelDup);
259430 pSegIter->bDelDup = 0;
259431
259432 pTerm = fts5MultiIterTerm(pIter, &nTerm);
259433 if( nTerm!=term.n || fts5Memcmp(pTerm, term.p, nTerm) ){
259434 if( pnRem && writer.nLeafWritten>nRem ){
259435 break;
@@ -257977,11 +259437,11 @@
259437 fts5BufferSet(&p->rc, &term, nTerm, pTerm);
259438 bTermWritten =0;
259439 }
259440
259441 /* Check for key annihilation. */
259442 if( pSegIter->nPos==0 && (bOldest || bDel==0) ) continue;
259443
259444 if( p->rc==SQLITE_OK && bTermWritten==0 ){
259445 /* This is a new term. Append a term to the output segment. */
259446 fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
259447 bTermWritten = 1;
@@ -257990,19 +259450,19 @@
259450 /* Append the rowid to the output */
259451 /* WRITEPOSLISTSIZE */
259452 fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
259453
259454 if( eDetail==FTS5_DETAIL_NONE ){
259455 if( bDel ){
259456 fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
259457 if( pSegIter->nPos>0 ){
259458 fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
259459 }
259460 }
259461 }else{
259462 /* Append the position-list data to the output */
259463 nPos = pSegIter->nPos*2 + bDel;
259464 fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
259465 fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
259466 }
259467 }
259468
@@ -258437,11 +259897,12 @@
259897
259898 iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
259899 assert_nc( iSOP<=pSeg->iLeafOffset );
259900
259901 if( bDetailNone ){
259902 int iEnd = pSeg->iLeafOffset - (pSeg->bDel ? 1 + pSeg->nPos : 0);
259903 while( iSOP<iEnd ){
259904 if( aPg[iSOP]==0x00 ) iSOP++;
259905 if( aPg[iSOP]==0x00 ) iSOP++;
259906 iStart = iSOP;
259907 iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
259908 }
@@ -258502,11 +259963,11 @@
259963 }
259964 }
259965
259966 if( pSeg->bDel ){
259967 iOff += sqlite3Fts5PutVarint(&aPg[iOff], iDelta);
259968 aPg[iOff++] = bDetailNone ? 0x00 : 0x01;
259969 }else if( bLastInDoclist==0 ){
259970 if( iNextOff!=iPgIdx ){
259971 u64 iNextDelta = 0;
259972 iNextOff += fts5GetVarint(&aPg[iNextOff], &iNextDelta);
259973 iOff += sqlite3Fts5PutVarint(&aPg[iOff], iDelta + iNextDelta);
@@ -261715,11 +263176,13 @@
263176 fts5DlidxIterEof(p, pDlidx)==0;
263177 fts5DlidxIterNext(p, pDlidx)
263178 ){
263179
263180 /* Check any rowid-less pages that occur before the current leaf. */
263181 for(iPg=iPrevLeaf+1; p->rc==SQLITE_OK && iPg<fts5DlidxIterPgno(pDlidx);
263182 iPg++
263183 ){
263184 iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
263185 pLeaf = fts5LeafRead(p, iKey);
263186 if( pLeaf ){
263187 if( fts5LeafFirstRowidOff(pLeaf)!=0 ) FTS5_CORRUPT_ROWID(p, iKey);
263188 fts5DataRelease(pLeaf);
@@ -263917,11 +265380,12 @@
265380 if( zRankArgs ){
265381 char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
265382 if( zSql ){
265383 sqlite3_stmt *pStmt = 0;
265384 rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
265385 SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_FROM_DDL, &pStmt, 0
265386 );
265387 sqlite3_free(zSql);
265388 assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
265389 if( rc==SQLITE_OK ){
265390 if( SQLITE_ROW==sqlite3_step(pStmt) ){
265391 sqlite3_int64 nByte;
@@ -264859,10 +266323,11 @@
266323 */
266324 static int fts5RollbackMethod(sqlite3_vtab *pVtab){
266325 int rc;
266326 Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
266327 fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
266328 fts5TripCursors(pTab);
266329 rc = sqlite3Fts5StorageRollback(pTab->pStorage);
266330 pTab->p.pConfig->pgsz = 0;
266331 return rc;
266332 }
266333
@@ -266335,11 +267800,11 @@
267800 int nArg, /* Number of args */
267801 sqlite3_value **apUnused /* Function arguments */
267802 ){
267803 assert( nArg==0 );
267804 UNUSED_PARAM2(nArg, apUnused);
267805 sqlite3_result_text(pCtx, "fts5: 2026-11-15 00:55:04 ad4ee20509dc4e2803f35093b03df55cb3e39c8083b0d4ad231e1432516c7841", -1, SQLITE_TRANSIENT);
267806 }
267807
267808 /*
267809 ** Implementation of fts5_locale(LOCALE, TEXT) function.
267810 **
@@ -266810,11 +268275,11 @@
268275 }
268276
268277 if( zSql==0 ){
268278 rc = SQLITE_NOMEM;
268279 }else{
268280 int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_FROM_DDL;
268281 if( eStmt>FTS5_STMT_LOOKUP2 ) f |= SQLITE_PREPARE_NO_VTAB;
268282 p->pConfig->bLock++;
268283 rc = sqlite3_prepare_v3(pC->db, zSql, -1, f, &p->aStmt[eStmt], 0);
268284 p->pConfig->bLock--;
268285 sqlite3_free(zSql);
@@ -267376,14 +268841,16 @@
268841 rc = sqlite3Fts5IndexGetOrigin(p->pIndex, &iOrigin);
268842 sqlite3_bind_int64(pReplace, 3, iOrigin);
268843 }
268844 }
268845 if( rc==SQLITE_OK ){
268846 rc = sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
268847 if( rc==SQLITE_OK ){
268848 sqlite3_step(pReplace);
268849 rc = sqlite3_reset(pReplace);
268850 sqlite3_bind_null(pReplace, 2);
268851 }
268852 }
268853 }
268854 return rc;
268855 }
268856
@@ -267765,11 +269232,13 @@
269232 );
269233 if( zSql==0 ){
269234 rc = SQLITE_NOMEM;
269235 }else{
269236 sqlite3_stmt *pCnt = 0;
269237 rc = sqlite3_prepare_v3(
269238 pConfig->db, zSql, -1, SQLITE_PREPARE_FROM_DDL, &pCnt, 0
269239 );
269240 if( rc==SQLITE_OK ){
269241 if( SQLITE_ROW==sqlite3_step(pCnt) ){
269242 *pnRow = sqlite3_column_int64(pCnt, 0);
269243 }
269244 rc = sqlite3_finalize(pCnt);
269245
+16 -6
--- extsrc/sqlite3.h
+++ extsrc/sqlite3.h
@@ -146,14 +146,14 @@
146146
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
147147
** [sqlite_version()] and [sqlite_source_id()].
148148
*/
149149
#define SQLITE_VERSION "3.55.0"
150150
#define SQLITE_VERSION_NUMBER 3055000
151
-#define SQLITE_SOURCE_ID "2026-10-24 22:25:07 d08cabd778f7844d04f3852d93197e80c0d0f4f30a589f7fd0d28577fa3fa68b"
151
+#define SQLITE_SOURCE_ID "2026-11-15 00:55:04 ad4ee20509dc4e2803f35093b03df55cb3e39c8083b0d4ad231e1432516c7841"
152152
#define SQLITE_SCM_BRANCH "trunk"
153153
#define SQLITE_SCM_TAGS ""
154
-#define SQLITE_SCM_DATETIME "2026-10-24T22:25:07.764Z"
154
+#define SQLITE_SCM_DATETIME "2026-11-15T00:55:04.503Z"
155155
156156
/*
157157
** CAPI3REF: Run-Time Library Version Numbers
158158
** KEYWORDS: sqlite3_version sqlite3_sourceid
159159
**
@@ -474,10 +474,11 @@
474474
#define SQLITE_FORMAT 24 /* Not used */
475475
#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
476476
#define SQLITE_NOTADB 26 /* File opened that is not a database file */
477477
#define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
478478
#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
479
+#define SQLITE_MOVED 29 /* Internal use only: Cursor moved */
479480
#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
480481
#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
481482
/* end-of-error-codes */
482483
483484
/*
@@ -2662,16 +2663,23 @@
26622663
** the number of significant digits that SQLite will attempt to preserve when
26632664
** converting floating point numbers (IEEE 754 "doubles") into text. The
26642665
** default value 17, as of SQLite version 3.52.0. The value was 15 in all
26652666
** prior versions.<p>
26662667
** This option takes two arguments which are an integer and a pointer
2667
-** to an integer. The first argument is a small integer, between 3 and 23, or
2668
+** to an integer. The first argument is a small integer, between 4 and 23, or
26682669
** zero. The FP_DIGITS setting is changed to that small integer, or left
26692670
** unaltered if the first argument is zero or out of range. The second argument
26702671
** is a pointer to an integer. If the pointer is not NULL, then the value of
26712672
** the FP_DIGITS setting, after possibly being modified by the first
26722673
** arguments, is written into the integer to which the second argument points.
2674
+**
2675
+** [[SQLITE_DBCONFIG_VDBE_TRACE]]
2676
+** <dt>SQLITE_DBCONFIG_VDBE_TRACE</dt>
2677
+** <dd>The SQLITE_DBCONFIG_VDBE_TRACE setting enables or disables tracing
2678
+** of the [bytecode engine]. This setting is only available when SQLite has
2679
+** be compiled with -DSQLITE_DEBUG. It is the equivalent of using
2680
+** [PRAGMA vdbe_trace].
26732681
** </dd>
26742682
**
26752683
** </dl>
26762684
**
26772685
** [[DBCONFIG arguments]] <h3>Arguments To SQLITE_DBCONFIG Options</h3>
@@ -2718,11 +2726,12 @@
27182726
#define SQLITE_DBCONFIG_REVERSE_SCANORDER 1019 /* int int* */
27192727
#define SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE 1020 /* int int* */
27202728
#define SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE 1021 /* int int* */
27212729
#define SQLITE_DBCONFIG_ENABLE_COMMENTS 1022 /* int int* */
27222730
#define SQLITE_DBCONFIG_FP_DIGITS 1023 /* int int* */
2723
-#define SQLITE_DBCONFIG_MAX 1023 /* Largest DBCONFIG */
2731
+#define SQLITE_DBCONFIG_VDBE_TRACE 1024 /* int int* */
2732
+#define SQLITE_DBCONFIG_MAX 1024 /* Largest DBCONFIG */
27242733
27252734
/*
27262735
** CAPI3REF: Enable Or Disable Extended Result Codes
27272736
** METHOD: sqlite3
27282737
**
@@ -4999,11 +5008,11 @@
49995008
** or indicates the lifetime of the object referenced by the third parameter.
50005009
** These three options exist:
50015010
** ^ (1) A destructor to dispose of the BLOB or string after SQLite has finished
50025011
** with it may be passed. ^It is called to dispose of the BLOB or string even
50035012
** if the call to the bind API fails, except the destructor is not called if
5004
-** the third parameter is a NULL pointer or the fourth parameter is negative.
5013
+** the third parameter is a NULL pointer or the fifth parameter is negative.
50055014
** ^ (2) The special constant, [SQLITE_STATIC], may be passed to indicate that
50065015
** the application remains responsible for disposing of the object. ^In this
50075016
** case, the object and the provided pointer to it must remain valid until
50085017
** either the prepared statement is finalized or the same SQL parameter is
50095018
** bound to something else, whichever occurs sooner.
@@ -8791,11 +8800,12 @@
87918800
#define SQLITE_TESTCTRL_TRACEFLAGS 31
87928801
#define SQLITE_TESTCTRL_TUNE 32
87938802
#define SQLITE_TESTCTRL_LOGEST 33
87948803
#define SQLITE_TESTCTRL_USELONGDOUBLE 34 /* NOT USED */
87958804
#define SQLITE_TESTCTRL_ATOF 34
8796
-#define SQLITE_TESTCTRL_LAST 34 /* Largest TESTCTRL */
8805
+#define SQLITE_TESTCTRL_EXPIRE_STMTS 35
8806
+#define SQLITE_TESTCTRL_LAST 35 /* Largest TESTCTRL */
87978807
87988808
/*
87998809
** CAPI3REF: SQL Keyword Checking
88008810
**
88018811
** These routines provide access to the set of SQL language keywords
88028812
--- extsrc/sqlite3.h
+++ extsrc/sqlite3.h
@@ -146,14 +146,14 @@
146 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
147 ** [sqlite_version()] and [sqlite_source_id()].
148 */
149 #define SQLITE_VERSION "3.55.0"
150 #define SQLITE_VERSION_NUMBER 3055000
151 #define SQLITE_SOURCE_ID "2026-10-24 22:25:07 d08cabd778f7844d04f3852d93197e80c0d0f4f30a589f7fd0d28577fa3fa68b"
152 #define SQLITE_SCM_BRANCH "trunk"
153 #define SQLITE_SCM_TAGS ""
154 #define SQLITE_SCM_DATETIME "2026-10-24T22:25:07.764Z"
155
156 /*
157 ** CAPI3REF: Run-Time Library Version Numbers
158 ** KEYWORDS: sqlite3_version sqlite3_sourceid
159 **
@@ -474,10 +474,11 @@
474 #define SQLITE_FORMAT 24 /* Not used */
475 #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
476 #define SQLITE_NOTADB 26 /* File opened that is not a database file */
477 #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
478 #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
 
479 #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
480 #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
481 /* end-of-error-codes */
482
483 /*
@@ -2662,16 +2663,23 @@
2662 ** the number of significant digits that SQLite will attempt to preserve when
2663 ** converting floating point numbers (IEEE 754 "doubles") into text. The
2664 ** default value 17, as of SQLite version 3.52.0. The value was 15 in all
2665 ** prior versions.<p>
2666 ** This option takes two arguments which are an integer and a pointer
2667 ** to an integer. The first argument is a small integer, between 3 and 23, or
2668 ** zero. The FP_DIGITS setting is changed to that small integer, or left
2669 ** unaltered if the first argument is zero or out of range. The second argument
2670 ** is a pointer to an integer. If the pointer is not NULL, then the value of
2671 ** the FP_DIGITS setting, after possibly being modified by the first
2672 ** arguments, is written into the integer to which the second argument points.
 
 
 
 
 
 
 
2673 ** </dd>
2674 **
2675 ** </dl>
2676 **
2677 ** [[DBCONFIG arguments]] <h3>Arguments To SQLITE_DBCONFIG Options</h3>
@@ -2718,11 +2726,12 @@
2718 #define SQLITE_DBCONFIG_REVERSE_SCANORDER 1019 /* int int* */
2719 #define SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE 1020 /* int int* */
2720 #define SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE 1021 /* int int* */
2721 #define SQLITE_DBCONFIG_ENABLE_COMMENTS 1022 /* int int* */
2722 #define SQLITE_DBCONFIG_FP_DIGITS 1023 /* int int* */
2723 #define SQLITE_DBCONFIG_MAX 1023 /* Largest DBCONFIG */
 
2724
2725 /*
2726 ** CAPI3REF: Enable Or Disable Extended Result Codes
2727 ** METHOD: sqlite3
2728 **
@@ -4999,11 +5008,11 @@
4999 ** or indicates the lifetime of the object referenced by the third parameter.
5000 ** These three options exist:
5001 ** ^ (1) A destructor to dispose of the BLOB or string after SQLite has finished
5002 ** with it may be passed. ^It is called to dispose of the BLOB or string even
5003 ** if the call to the bind API fails, except the destructor is not called if
5004 ** the third parameter is a NULL pointer or the fourth parameter is negative.
5005 ** ^ (2) The special constant, [SQLITE_STATIC], may be passed to indicate that
5006 ** the application remains responsible for disposing of the object. ^In this
5007 ** case, the object and the provided pointer to it must remain valid until
5008 ** either the prepared statement is finalized or the same SQL parameter is
5009 ** bound to something else, whichever occurs sooner.
@@ -8791,11 +8800,12 @@
8791 #define SQLITE_TESTCTRL_TRACEFLAGS 31
8792 #define SQLITE_TESTCTRL_TUNE 32
8793 #define SQLITE_TESTCTRL_LOGEST 33
8794 #define SQLITE_TESTCTRL_USELONGDOUBLE 34 /* NOT USED */
8795 #define SQLITE_TESTCTRL_ATOF 34
8796 #define SQLITE_TESTCTRL_LAST 34 /* Largest TESTCTRL */
 
8797
8798 /*
8799 ** CAPI3REF: SQL Keyword Checking
8800 **
8801 ** These routines provide access to the set of SQL language keywords
8802
--- extsrc/sqlite3.h
+++ extsrc/sqlite3.h
@@ -146,14 +146,14 @@
146 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
147 ** [sqlite_version()] and [sqlite_source_id()].
148 */
149 #define SQLITE_VERSION "3.55.0"
150 #define SQLITE_VERSION_NUMBER 3055000
151 #define SQLITE_SOURCE_ID "2026-11-15 00:55:04 ad4ee20509dc4e2803f35093b03df55cb3e39c8083b0d4ad231e1432516c7841"
152 #define SQLITE_SCM_BRANCH "trunk"
153 #define SQLITE_SCM_TAGS ""
154 #define SQLITE_SCM_DATETIME "2026-11-15T00:55:04.503Z"
155
156 /*
157 ** CAPI3REF: Run-Time Library Version Numbers
158 ** KEYWORDS: sqlite3_version sqlite3_sourceid
159 **
@@ -474,10 +474,11 @@
474 #define SQLITE_FORMAT 24 /* Not used */
475 #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
476 #define SQLITE_NOTADB 26 /* File opened that is not a database file */
477 #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
478 #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
479 #define SQLITE_MOVED 29 /* Internal use only: Cursor moved */
480 #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
481 #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
482 /* end-of-error-codes */
483
484 /*
@@ -2662,16 +2663,23 @@
2663 ** the number of significant digits that SQLite will attempt to preserve when
2664 ** converting floating point numbers (IEEE 754 "doubles") into text. The
2665 ** default value 17, as of SQLite version 3.52.0. The value was 15 in all
2666 ** prior versions.<p>
2667 ** This option takes two arguments which are an integer and a pointer
2668 ** to an integer. The first argument is a small integer, between 4 and 23, or
2669 ** zero. The FP_DIGITS setting is changed to that small integer, or left
2670 ** unaltered if the first argument is zero or out of range. The second argument
2671 ** is a pointer to an integer. If the pointer is not NULL, then the value of
2672 ** the FP_DIGITS setting, after possibly being modified by the first
2673 ** arguments, is written into the integer to which the second argument points.
2674 **
2675 ** [[SQLITE_DBCONFIG_VDBE_TRACE]]
2676 ** <dt>SQLITE_DBCONFIG_VDBE_TRACE</dt>
2677 ** <dd>The SQLITE_DBCONFIG_VDBE_TRACE setting enables or disables tracing
2678 ** of the [bytecode engine]. This setting is only available when SQLite has
2679 ** be compiled with -DSQLITE_DEBUG. It is the equivalent of using
2680 ** [PRAGMA vdbe_trace].
2681 ** </dd>
2682 **
2683 ** </dl>
2684 **
2685 ** [[DBCONFIG arguments]] <h3>Arguments To SQLITE_DBCONFIG Options</h3>
@@ -2718,11 +2726,12 @@
2726 #define SQLITE_DBCONFIG_REVERSE_SCANORDER 1019 /* int int* */
2727 #define SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE 1020 /* int int* */
2728 #define SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE 1021 /* int int* */
2729 #define SQLITE_DBCONFIG_ENABLE_COMMENTS 1022 /* int int* */
2730 #define SQLITE_DBCONFIG_FP_DIGITS 1023 /* int int* */
2731 #define SQLITE_DBCONFIG_VDBE_TRACE 1024 /* int int* */
2732 #define SQLITE_DBCONFIG_MAX 1024 /* Largest DBCONFIG */
2733
2734 /*
2735 ** CAPI3REF: Enable Or Disable Extended Result Codes
2736 ** METHOD: sqlite3
2737 **
@@ -4999,11 +5008,11 @@
5008 ** or indicates the lifetime of the object referenced by the third parameter.
5009 ** These three options exist:
5010 ** ^ (1) A destructor to dispose of the BLOB or string after SQLite has finished
5011 ** with it may be passed. ^It is called to dispose of the BLOB or string even
5012 ** if the call to the bind API fails, except the destructor is not called if
5013 ** the third parameter is a NULL pointer or the fifth parameter is negative.
5014 ** ^ (2) The special constant, [SQLITE_STATIC], may be passed to indicate that
5015 ** the application remains responsible for disposing of the object. ^In this
5016 ** case, the object and the provided pointer to it must remain valid until
5017 ** either the prepared statement is finalized or the same SQL parameter is
5018 ** bound to something else, whichever occurs sooner.
@@ -8791,11 +8800,12 @@
8800 #define SQLITE_TESTCTRL_TRACEFLAGS 31
8801 #define SQLITE_TESTCTRL_TUNE 32
8802 #define SQLITE_TESTCTRL_LOGEST 33
8803 #define SQLITE_TESTCTRL_USELONGDOUBLE 34 /* NOT USED */
8804 #define SQLITE_TESTCTRL_ATOF 34
8805 #define SQLITE_TESTCTRL_EXPIRE_STMTS 35
8806 #define SQLITE_TESTCTRL_LAST 35 /* Largest TESTCTRL */
8807
8808 /*
8809 ** CAPI3REF: SQL Keyword Checking
8810 **
8811 ** These routines provide access to the set of SQL language keywords
8812

Keyboard Shortcuts

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